text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Pygame Error Not Showing Scaled Image
So i am trying to draw a simple image of a torch in Pygame. But the problem is this sprite and all of my other sprites are around 10x10. So i was using scale to draw it experimentally like this:
import pygame, sys
class sprites:
class torch(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.image = pygame.transform.scale(self.image, ((100, 100)))
window = pygame.display.set_mode((300, 300))
width, height = window.get_size()
pygame.mouse.set_visible(True)
window.fill([0, 0, 0])
sprites.torch("torch.png", (50, 50))
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
sys.exit()
I am new to pygame so I am not sure what im doing wrong. Another solution to this problem would be if I could set the resolution to like 100x100 but the size to like 500x500
thanks in advance guys!
https://www.dropbox.com/s/38cy7a15jynes7c/torch.png
Ok, so according to the comments I didnt draw the sprite, then how do i? like i said, im completely new, sorry.
A:
From the comments, it sounds like your problem isn't that the scaling up is failing, but that the code isn't actually displaying your sprite (scaled-up or otherwise) anywhere.
If so, that's because you never tell pygame to do so. Just creating a sprite doesn't actually draw it.
You really should work through the tutorials and look over a few sample programs rather than try to figure out what is and isn't necessary and when and in what order just from the reference docs.
The basic idea is that you put your Sprite objects into Group objects, and then somewhere inside your event loop or framerate loop, you call the draw method on each Group, passing it your window. This is explained in the overview for pygame.sprite.
In your program, since you never actually update anything, but just render a single static display and then flip it and wait forever for a keypress, you should be able to just draw once:
thetorch = sprites.torch("torch.png", (50, 50))
everything = pygame.sprite.Group()
everything.add(thetorch)
everything.draw(window)
pygame.display.flip()
In many types of game, it can make sense to have static objects like this add themselves to a Group in their constructor or vice-versa, and in some games even to make a special group for static objects that draw themselves on construction. Although that's not very common. Again, look through the examples. If you go to the draw docs and click "Search examples", it'll give you 50 sample programs that use that method, and you can get an idea of how they're organized. But first, go through the really basic examples in the tutorials.
| {
"pile_set_name": "StackExchange"
} |
Q:
Perl regex wrongfully evaluating expressions
I have the following perl code with a string that I'm needing to check against several cases in order to decide what to do with it. None of them work. Code looks like this:
my $param = "02 1999";
my @months = qw(january february march april may june july august september october november december);
my $white = /^\s*$/; #check if all whitespace
my $singleyear = /^\d{2,4}$/; #check if 2-4 digits
my $nummonth = /^\d{1,2}\s\d{1,4}$/; #check if 1-2 digits then 1-4
if ($param =~ $white) {
my($day, $month, $year)=(localtime)[3,4,5];
my $monthname = $months[$month];
print "$monthname $year\n";
}
if ($param =~ $singleyear) {
print "$param\n";
}
if ($param =~ $nummonth) {
my $monthnumber = $param =~ /^\d{1,2}/; #grabs the number at the front of the string
my $monthstring = $months[$monthnumber];
my $yearnumber = $param =~ /(\d{1,4})$/; #grab second number, it does this wrong
print "$monthstring $yearnumber\n";
}
Given the above, the output should simply be:
february 1999
Instead, the output is:
3 118
02 1999
february 1 #this only grabbed the first digit for some reason.
So ALL of the cases evaluated as true for some reason, and the capture on the year didn't even work. What am I doing wrong? Testing all of my regex at regex101 worked fine, but not in the script.
A:
I see two issues that are central to your question.
First, you apparently want to save precompiled regexes in the variables $white, $singleyear, and $nummonth, but you are not using the right operator for that - you should use qr// to compile and save the regex. Code like my $white = /^\s*$/; will run the regex against $_ and store the result in $white.
Second, my $monthnumber = $param =~ /^\d{1,2}/; has two issues: the =~ operator used with m// in scalar context simply returns a true/false value (that's the 1 you're seeing in the output february 1), but if you want to get the capture groups from the regex, you need to use it in list context, in this case by saying my ($monthnumber) = ... (the same issue applies to $yearnumber). Second, that regex doesn't contain any capture groups!
I don't get exactly the output you claim (although it's close) - please have a look at Minimal, Complete, and Verifiable example, especially since your post initially contained quite a few syntax errors. If I apply the fixes I described above, I get the output
march 1999
which is what I would expect - I hope you can figure out how to fix the off-by-one error.
Update: I should add that you also don't need to try and parse date/times yourself. My favorite module for date/time handling is DateTime (together with DateTime::Format::Strptime), but in this case the core Time::Piece is enough:
use Time::Piece;
my $param = "02 1999";
my $dt = Time::Piece->strptime($param, "%m %Y");
print $dt->fullmonth, " ", $dt->year, "\n"; # prints "February 1999"
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to get intent filters from a package
I want to list all the intent filters that are present in an package.
I am trying to do it using PackageManager class.
I have set the flag PackageManager.GET_INTENT_FILTERS while fetching the PackageInfo object.
But I dont know how to use it.
I was able to get all the info related to activites and receivers using the respective flags, but dunno how to proceed for intent-filters.
Any ideas how to solve this issue?
A:
Looks like intent filters are not exposed in the API and the flag effectively does nothing: http://code.google.com/p/android/issues/detail?id=3217
| {
"pile_set_name": "StackExchange"
} |
Q:
How to config gitignore?
I want to ignore some of my files (/config/environments/production.rb , /webrat.log , /config/database.yml ). My gitignore:
/.bundle
/db/*.sqlite3
/doc/
*.rbc
*.sassc
.sass-cache
capybara-*.html
.rspec
/vendor/bundle
/log/*
/tmp/*
/public/system/*
/coverage/
/spec/tmp/*
**.orig
rerun.txt
pickle-email-*.html
/config/environments/production.rb
/config/*.yml
/*.log
But this doesn't work. What's wrong?
A:
What you did is correct. Probably you have already added these files, before making .gitignore.
So Try this
git rm -r --cached . (Note the period at the end.)
git add .
Then check whether the files that you put in ignore is still added to the index. Or you could modify them and check whether they are being tracked.
A:
If those files were already added to the index, you need to remove them first.
git rm --cache /config/environments/production.rb
git rm --cache /webrat.log
git rm --cache /config/database.yml
Then the .gitignore can work on those files.
| {
"pile_set_name": "StackExchange"
} |
Q:
how do i execute a statement in batch /powershell just once?
I want to know how to execute a set of statements or a command in a Windows Batch file or PowerShell script to be executed just once. Even if I run the script multiple times, that particular set of code or program should just run once.
If possible give an example for both Batch files and PowerShell.
A:
In both cases you need to make changes that (a) persist beyond running the batch file or PowerShell script and (b) are visible when you start it the next time. What those changes are would depend on how cluttered you want to leave the system.
One option would be an environment variable. You can set those from batch files with setx or from PowerShell with [Environment]::SetEnvironmentVariable. You should also set them normally to have them in the current session, just to make sure that it can't be called from that session again, too.
if defined AlreadyRun (
echo This script ran already
goto :eof
)
...
setx AlreadyRun 1
set AlreadyRun 1
or
if (Test-Path Env:\AlreadyRun) {
Write-Host This script ran already
exit
}
...
[Environment]::SetEnvironmentVariable('AlreadyRun', '1', [EnvironmentVariableTarget]::User)
'1' > Env:\AlreadyRun
This approach has its drawbacks, though. For example, it won't prevent you from running the same script twice in different processes that both existed at the time the script ran first. This is because environment variables are populated on process start-up and thus even the system-wide change only applies to new processes, not to those already running.
Another option would be a file you check for existence. This has the benefit of working even under the scenario outlined above that fails with environment variables. On the other hand, a file might be accidentally deleted easier than an environment variable.
However, since I believe your batch file or PowerShell script should do something, i.e. have a side-effect, you should probably use exactly that as your criterion for abort. That is, if the side-effect is visible somehow. E.g. if you are changing some system setting or creating a bunch of output files, etc. you can just check if the change has already been made or whether the files are already there.
A probably very safe option is to delete or rename the batch file / PowerShell script at the end of its first run. Or at least change the extension to something that won't be executed easily.
| {
"pile_set_name": "StackExchange"
} |
Q:
Deploying WCF Service on Azure : Web Role or Worker Role?
I am evaluating the various options to deploy a web service in Azure. Presently, the web service would be consumed only by a front end UI which will be deployed as a separate web role within the same cloud service that would be hosting the web service. However, the web service would be exposed in its own right at a later stage. Apparently, web services can be hosted from within either Web Role or from a worker role. Could you please throw some light on pros and cons of either approach? Which of these approaches would you recommend for my scnario?
A:
A web role assumes that the application will be hosted in IIS. If your service does not require any of the benefits provided by IIS or its HTTP stack, then hosting it in a worker role may do you perfectly fine and also provide you a lower resource utilization for that service (since there's no "overhead" for the IIS server).
| {
"pile_set_name": "StackExchange"
} |
Q:
Integer Hash to a String Value
I want to compute Hash of a String, but the Hash value should be a number (long or integer).
In other words I want to compute integer hash of a string.
Collusion resistance in not the concern.
Is there an way to convert MessageDigest of SHA-256 to a number.
I am using Java to accomplish this.
A:
A Sha Hash has 256 Bits e.g.
"364b7e70a9966ef7686ab814958cd0017b7f19147a257d40603d4a1307662b42"
this will exceed the range of long and integer.
You could use new BigInteger( hash, 16 ); for a decimal representation.
public static void main(String[] args) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update("string".getBytes() );
byte[] hash = digest.digest();
BigInteger bi = new BigInteger( hash );
System.out.println( "hex:" + bi.toString(16) + "\r\ndec:" + bi.toString() );
}
| {
"pile_set_name": "StackExchange"
} |
Q:
IPhone, MPMoviePlayerController how to disable zooming when double tap on the screen?
How can I dissable the strange double tap behaviour when playing movie using MPMoviePlayerController.
The double tap makes zoom/unzoom of the movie and makes some of my gestures in the overlay view to stop working on the double tap area.
A:
I had the same problem. Just add:
self.moviePlayerViewController.view.userInteractionEnabled = NO;
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if an instance variable has one or more objects?
This is an example code, just to illustrate the problem.
When I click one of the buttons I will load some instance variable into the view and render it. I don't know if the variable will have one or more objects inside. I therefore have to check if the variable has one or more objects inside, when it is loaded into the view (else the .each method will fail if there is only one object inside). Or is there a way to store just one object inside the variable as an array?
aa.html.erb
<div class="fill"></div>
<%= button_to 'ALL', { :controller => 'animals', :action => 'vaa', :id => "0" } , remote: true %>
<%= button_to 'ELEPHANT', { :controller => 'animals', :action => 'vaa', :id => "1" } , remote: true %>
<%= button_to 'ZEBRA', { :controller => 'animals', :action => 'vaa', :id => "2" } , remote: true %>
<div class="fill3"></div>
<%= render 'animals/vaa' %>
_vaa.html.erb
<div class="fill4">
<% @animals.each do |animal| %>
<table>
<tr>
<td><%= animal.name %></td>
<td><%= animal.race %></td>
<td><%= link_to 'Show', animal %></td>
<td><%= link_to 'Edit', edit_animal_path(animal) %></td>
<td><%= link_to 'Destroy', animal, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
</table>
<% end %>
</div>
<div class="fill5">
</div>
animals_controller.rb
def vaa
if params[:id] == "0"
@animals = Animal.all
elsif params[:id] == "1"
@animals = Animal.first
elsif params[:id] == "2"
@animals.second
end
respond_to do |format|
format.js
end
end
A:
You can return @animals as array if @animals you're retrieving is not an array like follows:
def vaa
if params[:id] == "0"
@animals = Animal.all
elsif params[:id] == "1"
@animals = Animal.first
elsif params[:id] == "2"
@animals.second
end
# The following line makes sure @animals is Array if @animals is not an array.
@animals = [@animals] unless @animals.kind_of?(Array)
respond_to do |format|
format.js
end
end
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert the following into a standard time format in j query (2015-08-21T12:35:01.5588081Z)?
Actually I having a time and date format as following 2015-08-21T12:35:01.5588081Z now what I need is how to convert this format 2015-08-21T12:35:01.5588081Z to this one12:35 08/21/15 in jquery. Thanks in advance.
A:
Try utilizing new Date() with argument "2015-08-21T12:35:01.5588081Z" to convert to Date object , .getUTCHours() , .getMinutes() , .getDate() , .getDay() , .getFullYear() , String.prototype.slice()
var date = "2015-08-21T12:35:01.5588081Z";
var d = new Date(date);
var res = String(d.getUTCHours() + ":" + d.getUTCMinutes() + " ")
.concat(d.getMonth() + 1 + "/")
.concat(d.getDate() + "/")
.concat(d.getFullYear().toString().slice(-2));
document.write(res);
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I put the results of TrigFactor function into a more convenient form?
a1 D11 Cos[n x] + a0 a1 D11 Cos[n x] + 1/2 a1 a3 D11 Cos[n x] + 1/2 a2 a4 D11 Cos[n x]
I have a large trigonometric expression. Can I factor out different coefficients to Cos[n x] and Sin[n x] so that it will be easy to copy the expression corresponding to each trigonometric term? I just want the coefficient to each trigonometric function to be printed out separately.
A:
Second update (2015-05-11):
Amandeep, you recently left a comment with the following expression:
xpr = a1*D11*Cos[n*x] + a0*a1*D11*Cos[n*x] + 1/2*a1*a3*D11*Cos[n*x] + 1/2*a2*a4*D11*Cos[n*x] + a2*a3*a4*Sin[n*x]
I believe that you may have left out a multiplication sign on the argument of the last Sin function. Once we add that back in, the approach using Collect still seems to work:
Collect[xpr, {Cos[n x], Sin[n x]}]
(* Out:
(a1 D11 + a0 a1 D11 + (a1 a3 D11)/2 + (a2 a4 D11)/2) Cos[n x] + a2 a3 a4 Sin[n x]
*)
An alternative approach is to use the Coefficient function:
Coefficient[xpr, Cos[n x]]
Coefficient[xpr, Sin[n x]]
(*Out:
a1 D11 + a0 a1 D11 + (a1 a3 D11)/2 + (a2 a4 D11)/2
a2 a3 a4
*)
Hopefully those coefficients should be easy enough to copy and paste, or to otherwise work with programmatically.
First update
Upon re-reading your question, I realized that the D11 Cos[n x] factor is common to all terms in your original expression. It would be just as easy to collect that term:
a1 D11 Cos[n x] + a0 a1 D11 Cos[n x] + 1/2 a1 a3 D11 Cos[n x] + 1/2 a2 a4 D11 Cos[n x];
Collect[%, D11 Cos[n x]]
(* Output: (a1 + a0 a1 + (a1 a3)/2 + (a2 a4)/2) D11 Cos[n x] *)
In my understanding, you want to factor the expression to obtain the coefficients of the $\cos(n\ x)$ and $\sin(n\ x)$. However, your example does not contain any Sin[] expressions.
Let me consider a modification of your expression instead, in which I have changed some of the original Cos[n x] into Sin[n x]:
a1 D11 Cos[n x] + a0 a1 D11 Sin[n x] + 1/2 a1 a3 D11 Cos[n x] + 1/2 a2 a4 D11 Sin[n x]
You can then use Collect to obtain your coefficients:
Collect[%, {Cos[n x], Sin[n x]}]
(* Output: (a1 D11 + (a1 a3 D11)/2) Cos[n x] + (a0 a1 D11 + (a2 a4 D11)/2) Sin[n x] *)
Now they should be easier to copy out.
Alternatively, you could also programmatically extract the two coefficient from the result above, as parts of the output expression:
{%[[1, 1]], %[[2, 1]]}
(* Output: {a1 D11 + (a1 a3 D11)/2, a0 a1 D11 + (a2 a4 D11)/2} *)
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I be using www. when setting up virtual hosts on apache?
Does it matter whether or not I include the www. sub-domain when creating new virtual hosts on apache?
So is this?
/etc/apache2/sites-available/www.example.com
better than this?
/etc/apache2/sites-available/example.com
I would assume I'd need to a2ensite either www.example.com or example.com. Depending on whichever method used?
This might be a a fairly basic question But, I have no one else to ask. And, want to do it right.
A:
You don't need to create two separate vhosts for this - just use the ServerAlias directive:
<Virtualhost *:80>
ServerName example.com
ServerAlias www.example.com
...
</VirtualHost>
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the difference between DDR3 PC3-1300, PC3-1600, PC3-12800, etc
My mainboard has only 2 slots for RAM. Currently, Speccy says that I have:
2 x Kingston 4GB DD3 PC3-10700
Can I replace these RAMs with 2 x 8GB DD3 PC3-12800
My mainboard is a Gigabyte GA-H61M-DS2 Rev 2.0 and on it's specs it says:
1. 2 x 1.5V DDR3 DIMM sockets supporting up to 16 GB of system memory
* Due to Windows 32-bit operating system limitation, when more than 4 GB of physical memory is installed, the actual memory size displayed will be less than 4 GB.
2. Dual channel memory architecture
3. Support for DDR3 2200(OC)/1333/1066/800 MHz memory modules
4. Support for non-ECC memory modules
A:
PC3-12800 (12800 MB/sec) is the same thing as DDR3 1600MHz (1600 MHz data transfer rate) and it runs at 800 MHz DDR clock. Similarly for others, just divide/multiply by 8.
Any memory that has the correct voltage and capacity and is same or faster than what is supported by the board should work in the board. The memory will run at 1333 MHz (PC3-10700), unless you enable overclocking (XMP or other) on the board because the CPU likely doesn't support 1600 MHz within its specification.
So in your case, there should be no issue replacing your RAMs with the new pair. I say should as there can always be incompatibilies beyond what is covered by specification.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the real world experience of riding a light bike understated by physics-based calculators?
Take the case where you have two identical riders, Joe Slo and Billy Whizz. They both weigh 75kg and have identical aerobic threshold power output.
Joe has a 11kg steel audax bike, but Billy likes shiny gear so bought the latest Emonda weighing 5kg.
Physics based calculators (e.g. http://www.analyticcycling.com/ForcesLessWeight_Page.html or http://bikecalculator.com) put Billy about 50m head of Joe after 1km cycling up a 1km hill averaging 5% gradient.
That doesn't sound like much, and not worth spending $5k on.
However, during a hilly sportive the pair will ride 160km including 20km at gradients over 5%, and these are spaced evenly throughout the ride.
Let's assume Billy makes an effort and rides the hills at his aerobic threshold, which is 300watts, and they therefore ride at 20.2kph (http://bikecalculator.com). Joe has to ride at 316watts to keep up (so ~5% above his threshold). That doesn't sound like as much fun.
What would the likely effect on recovery be for the last part of the ride? Does chasing those few additional watts on each climb have a non-additive impact on performance in the final 20km, for example?
I guess my question is, even though Billy would wait for Joe at the top of each hill, does the additional effort required to keep up make this a sufferfest for Joe?
A:
The physics model of cycling power and speed has been validated in the real world. Two examples are this and this. The model embedded in Analyticcyling.com's online calculator is based on these two papers.
Whether the amount of difference calculated by the validated models is worth it to Joe and Billy is a question that can't be answered by the physics.
A:
This largely depends on rider goals and finances. Your example clearly highlights the advantage of a light bike (although aero is probably equally important). If Joe and Billy are racing, and they are exactly the same, we can assume Billy is going to win. If Joe can afford it, and wants to stay competitive with Billy, it will likely be worth it for him. If Joe and Billy are non-competitive and just riding for fun, Billy likely isn't going to ride at a high level to make it a sufferfest for Joe (unless Joe is into that sort of thing).
You may also be missing the fact that Billy is recovering (a bit) while waiting. Whether or not this is a "sufferfest" for Joe is sort of irrelevant. Joe may enjoy training pain. Regardless, because of equipment, Joe has a lower level of upper performance than Billy.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Fatal error: Cannot access empty property
I'm new to php and I have executed below code.
<?php
class my_class{
var $my_value = array();
function my_class ($value){
$this->my_value[] = $value;
}
function set_value ($value){
// Error occurred from here as Undefined variable: my_value
$this->$my_value = $value;
}
}
$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c');
$a->my_class('d');
foreach ($a->my_value as &$value) {
echo $value;
}
?>
I got below errors. What could be the error?
Notice: Undefined variable: my_value in C:\xampp\htdocs\MyTestPages\f.php on line 15
Fatal error: Cannot access empty property in C:\xampp\htdocs\MyTestPages\f.php on line 15
A:
You access the property in the wrong way. With the $this->$my_value = .. syntax, you set the property with the name of the value in $my_value. What you want is $this->my_value = ..
$var = "my_value";
$this->$var = "test";
is the same as
$this->my_value = "test";
To fix a few things from your example, the code below is a better aproach
class my_class {
public $my_value = array();
function __construct ($value) {
$this->my_value[] = $value;
}
function set_value ($value) {
if (!is_array($value)) {
throw new Exception("Illegal argument");
}
$this->my_value = $value;
}
function add_value($value) {
$this->my_value = $value;
}
}
$a = new my_class ('a');
$a->my_value[] = 'b';
$a->add_value('c');
$a->set_value(array('d'));
This ensures, that my_value won't change it's type to string or something else when you call set_value. But you can still set the value of my_value direct, because it's public. The final step is, to make my_value private and only access my_value over getter/setter methods
A:
First, don't declare variables using var, but
public $my_value;
Then you can access it using
$this->my_value;
and not
$this->$my_value;
A:
To access a variable in a class, you must use $this->myVar instead of $this->$myvar.
And, you should use access identifier to declare a variable instead of var.
Please read the doc here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete raw pointer after creating a shared_ptr from it
If I do the following,
int* p = new int(10);
std::shared_ptr<int>(p);
delete p;
What happens here? Is the shared_ptr invalid after deletion of the raw pointer? Is there any way to ensure memory access safety in such a scenario?
A:
The code in your question contains 2 conflicting definitions of p. I'm assuming you meant to post something like
int* p = new int(10);
std::shared_ptr<int> p1(p);
delete p;
When the shared_ptr goes out of scope and its reference count falls to zero it will attempt to delete p;, leading to double deletion and undefined behavior.
You've passed ownership of the dynamically allocated int to the shared_ptr, so let it do its job, and don't go about deleting the int yourself.
If you want clients of your API from doing something similar to the code above, one possibility is to change the API function's parameter type from a shared_ptr to a parameter pack of constructor arguments. For instance
template<typename T, typename... Args>
void api_func(Args&&... args)
{
auto p = std::make_shared<T>(std::forward<Args>(args)...);
// Use the shared_ptr p as before
}
Then, instead of passing a shared_ptr<int>, client code would call the above function as api_func<int>(10);.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cakephp 2 errors on reporting level 0
I would like to show a custom error page when the reporting level is set to 0 and it is a 500 error not a 404. It seems I can't access the error message at all, outside of the default view.
I would like to set a custom layout outside of the normal error layouts. I know if I switch the reporting to level 1 or 2 then it works fine. I want this for production where it is set at 0 and not a 400 error. Is this possible?
$error->getMessage()
A:
Q: I would like to show a custom error page when the reporting level is set to 0 and it is a 500 error
A: You can edit the default error views error400.ctp and also error500.ctp in /app/View/Errors/
Q: I would like to set a custom layout outside of the normal error layouts.
A: If you want to use another (custom) layout you can copy the file CakeErrorController.php from /lib/Cake/Controller/ to /app/Controller/ and add the following line in the function:
function __construct($request = null, $response = null) {
$this->layout = 'your-layout-name'; // add this line in the function
// ...
}
and add the custom layout template file as usual in /app/View/Layouts/, e.g. your-layout-name.ctp
If you want to show data from your app in the error page/layout (eg generate the main menu from the database) you can add more custom code in your error controller as well, e.g.:
// Error controller in /app/Controller/CakeErrorController.php
class CakeErrorController extends AppController {
public $uses = array('MenuCategory'); // load relevant table/model
public function __construct($request = null, $response = null) {
$this->set('mainmenu', $this->MenuCategory->getMenu()); // or find() or whatever
// ...
}
}
Q: How can I keep different error messages in production mode (debug level = 0)?
A According to the documentation "ErrorHandler by default, displays errors when debug > 0, and logs errors when debug = 0." The reason is e.g. that you should not show your public visitors (in production mode) an error message like "Missing Component", because this error is irrelevant and not useful for the visitor (so a 404/500 is responded). These kind of errors are only relevant for development and should be fixed before you go live in production mode.
If you want to change this behaviour you have to set up your own error handling as it is exlained in the book. Please also have a look at the explanation directly in the CakePHP code. You can also create your own exeptions if necessary.
If you have problems in using/creating your own error handler, please start a new question on Stackoverflow with more details: What files have you created (e.g. your error handler and/or exceptions), how is your code looking like, what have you tried to solve the problem... and please give a clear example of what you want to achieve (e.g. in the comments below to the first version of my answer you are talking about special 500 errors - What is triggering these errors and what do you want to response instead of a 500 or what exactly do you want to change...)?
An alternative solution in some situations could also be something like this:
// In your controller
public function moderator_view($id = null) {
// Your error check, in this example the user role
if ( $this->Auth->user('role') != 'moderator' ) {
// Custom error message
$this->Flash->custom('You are not a moderator.');
// Redirect to your your special error page
// In this example got to previous page
return $this->redirect(
$this->referer(
// or go to a default page if no referrer is given
array('controller' => 'articles', 'action' => 'index', 'moderator' => false)
)
);
}
// else show moderator content...
}
Please also have a look at the many other questions to custom error pages in CakePHP ;-)
| {
"pile_set_name": "StackExchange"
} |
Q:
Sphere only turns red when it intersects the first sphere of an array
I use the below code to color my reference sphere red whenever it intersects with another sphere:
for(i=0;i<numTriangles;i++) {
if(DoSpheresIntersect(&ref,&triArray[i]))
c=RED;
else
c=GREY;
OpenGLDrawSphere(ref, c);
OpenGLDrawSphere(triArray[i], c);
}
However, my reference sphere only turns red if it intersects the first member of triArray[i], meaning triArray[0]. In all other cases it stays grey, regardless of whether or not it intersects the remaining members of triArray[i]. What's wrong with my logic?
A:
Since you draw your reference sphere inside the loop, you draw it multiple times, once for each other sphere you test against. Since you most likely have a depth buffer, only the first time you draw the reference sphere will result in visible rendering. So if it's red the first time through the loop (i.e. it intersects the first sphere), it will show as red. Otherwise, it will be grey.
You can change your logic to something like this:
Color refColor = GREY;
for (i = 0; i < numTriangles; i++) {
if (DoSpheresIntersect(&ref, &triArray[i])) {
c = RED;
refColor = RED;
} else {
c = GREY;
}
OpenGLDrawSphere(triArray[i], c);
}
OpenGLDrawSphere(ref, refColor);
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Play and Cordova 4.1.1
Google Play is rejecting my application because of the Cordova version I use :
Apache Cordova
The vulnerabilities were fixed in Apache Cordova v.4.1.1 or higher.
You can find information about how to upgrade in this Google Help Center article.
I updated to Cordova 4.1.1 and I still get this error when uploading a new build.
$ cordova -v
6.4.0
$ cordova platform ls
Installed platforms:
android 4.1.1
Anyone knows how to fix this issue?
A:
The problem was pretty simple : Google Play refused a build I sent in production with Cordova 3.5.0. Since this moment, for every Alpha build I sent, Google Play was complaining about my production build that was using Cordova 3.5.0. The only way to resolve this issue was to send a build in Alpha, and move it to Production, without being able to test it in Alpha mode through the Google Play. It's sad that we can't test any build in the Google Play Store in Alpha or Beta when there's a build with security issue in Production.
Hope this will help some people having this weird issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Analogies between Hodge conjecture and Tate conjecture
I hear sometimes that there is many analogies between the Hodge conjecture and the Tate conjecture.
If we take a look at the statements of this two conjectures, we have the followings :
The Tate conjecture :
Let $k$ be a field and let $X$ be a smooth geometrically irreducible projective variety over $k$ of dimension $d$.
We denote by $\overline{X} = X \times_k \overline{k}$ the base change of $X$ to the algebraic closure $\overline{k}$.
The Galois group $G = Gal ( \overline{k} / k )$ then acts on $\overline{X}$ via the second factor.
Let $Z^r ( \overline{X} )$ be the free abelian group generated by the irreducible closed subvarieties of $\overline{X}$ of codimension $r$ ( $1 \leq r \leq d$ ). An element of $ Z^r ( \overline{X} ) $ is called an algebraic cycle of codimension $ r $ on $\overline{X}$.
Let $\ell $ be a prime different from $p = \mathrm{car} (k) \geq 0$.
There is a cycle map ( of $G$ - modules ) :
$$ c^r \ : \ Z^r ( \overline{X} ) \otimes \mathbb{Q}_{ \ell } \to H^{2r} ( \overline{X} , \mathbb{Q}_{ \ell } ( r ) )^G $$
which associates to every algebraic cycle an $ \ell $ - adic etale cohomology class.
Suppose $k$ is finitely generated over its prime field.
Then, the Tate conjecture says that the map $c^r$ is surjective.
The Hodge conjecture :
For each integer $ p \in \mathbb{N} $, let $ H^{p,p} (X) $ denotes the subspace of $ H^{2p} ( X ,\mathbb{C} ) $ of type $ (p,p) $.
The group of rational $ (p,p) $- cycles : $ H^{p,p} (X , \mathbb{Q} ) = H^{2p} ( X , \mathbb{Q} ) \cap H^{p,p} (X) $ is called the group of rational Hodge classes of type $ (p,p) $.
An $ r $ -cycle of an algebraic variety $ X $ is a formal finite linear combination $ \displaystyle \sum_{ i \in [1,h] } m_i Z_i $ of closed irreducible subvarieties $ Z $ of dimension $ r $ with integer coefficients $ m_i $.
The group of $ r $ -cycles is denoted by $ \mathcal{Z}_r (X) $.
On a compact complex algebraic manifold, the class of closed irreducible subvarieties of codimension $ p $ extends into a linear morphism :
$$ \mathrm{cl}_{ \mathbb{Q} } \ : \ \mathcal{Z}_{p} (X) \otimes \mathbb{Q} \to H^{p,p} (X, \mathbb{Q} ) $$
defined by : $ \mathrm{cl}_{ \mathbb{Q} } \big( \sum_{ i \in [1,h] } m_i Z_i \big) = \sum_{ i \in [1,h] } m_i \eta_{Z_{i}} \ , \ \forall m_i \in \mathbb{Q} $.
The elements of the image of $ \mathrm{cl}_{ \mathbb{Q} } $ are called rational algebraic Hodge classes of type $ (p,p) $.
The Hodge conjecture says :
On a non-singular complex projective variety, any rational Hodge class of type $ (p,p) $ is algebraic, i.e : in the image of $ \mathrm{cl}_{ \mathbb{Q} } $.
Questions :
If we look at the statements of the two conjectures above, and look for similarities between them, which group $G$ is it such that: $H^{2k} (X, \mathbb{Q})^G = H^{2p } (X, \mathbb {Q}) \cap H ^ {p, p} (X)$ to bring the statement of Hodge's conjecture closer to the statement of Tate's conjecture?
Thanks in advance for your help.
A:
You can find similarities between both conjectures by observing that the $\ell$-adic cohomologies appearing in Tate conjecture are objects of the category of $\mathbb{Q}_{\ell}[G]$-modules (may be continuous), where $G$ is the Galois group here, and $$H^{2r} ( \overline{X} , \mathbb{Q}_{ \ell } ( r ) )^G\cong \operatorname{Hom}_{\mathbb{Q}_{\ell}[G]}(\mathbb{Q}_{\ell}, H^{2r} ( \overline{X} , \mathbb{Q}_{ \ell } ( r )) ).$$
Now, for the Hodge Conjecture, you need to find an appropriate category to play the role of $\mathbb{Q}_{\ell}[G]$-modules, and this is the Hodge Mixed Structures (I abbreviate MHS). This is a Tannakian category, and it has an object called $\mathbb{Q}[0]$, which plays the analogous role of $\mathbb{Q}_{\ell}$ in the $\ell$-adic setting. We have that the cohomology $H^{2r} ( X , \mathbb{Q} ) $ together with the Hodge Filtration when tensoring by $\mathbb{C}$ and with the "trivial" weight filtration of weight $2r$ (since $X$ is smooth and projective) is a Hodge Mixed Structure (so $H^{2r} ( X , \mathbb{Q} )(r) $ has weight $0$) , and that
$$ H^{p,p} (X , \mathbb{Q} ) = H^{2p} ( X , \mathbb{Q} ) \cap H^{p,p} (X) \cong \operatorname{Hom}_{MHS}(\mathbb{Q}[0], H^{2r} ( X , \mathbb{Q}) ( r ) ).$$
What it is more interesting, we also get an interpretation of the (Griffiths) intermediate Jacobian (in fact the group of points and tensor with $\mathbb{Q}$) as $$\operatorname{Ext}^1_{MHS}(\mathbb{Q}[0], H^{2r-1} ( X , \mathbb{Q}) ( r ) ).$$
and a unified construction of the cycle map and the Abel-Jacobi map in both settings (where the $\ell$-adic intermediate Jacobian is essentially $H^1(G,H^{2r-1} ( \overline{X} , \mathbb{Q}_{ \ell } ( r ))$ ).
| {
"pile_set_name": "StackExchange"
} |
Q:
C++, curious compiler error when implementing a function `int next(std::string param)`
I've been badly bitten by the following code, on which I wasted many hours of precious time.
#include<string>
int next(std::string param){
return 0;
}
void foo(){
next(std::string{ "abc" });
}
This produces the following compiler error (on Visual Studio 2013):
1>------ Build started: Project: sandbox, Configuration: Debug Win32 ------
1> test.cpp
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(371): error C2039: 'iterator_category' : is not a member of 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>'
1> c:\users\ray\dropbox\programming\c++\sandbox\test.cpp(8) : see reference to class template instantiation 'std::iterator_traits<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>' being compiled
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(371): error C2146: syntax error : missing ';' before identifier 'iterator_category'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(371): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(371): error C2602: 'std::iterator_traits<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>::iterator_category' is not a member of a base class of 'std::iterator_traits<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>'
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(371) : see declaration of 'std::iterator_traits<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>::iterator_category'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(371): error C2868: 'std::iterator_traits<std::basic_string<char,std::char_traits<char>,std::allocator<char>>>::iterator_category' : illegal syntax for using-declaration; expected qualified-name
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I found out later that if I change my function name from next() to something else, all is fine. To me, this indicates that there is a name conflict, specifically of the name next. I find this strange because I didn't use anything like using namespace std. As far as I know, next is not a built-in C++ keyword (is it?). I looked up next here, but it's std::next and as I said I didn't using namespace std. So how did this conflict happen? How do I prevent similar things in the future? What other names might cause a conflict like this?
A:
There are several things going on here, interacting in subtle ways.
Firstly, an unqualified call to next with an argument of type std::string means that as well as your own next function, the standard function template std::next is found by Argument-dependent lookup (ADL).
After name lookup has found your ::next and the standard library's std::next it performs overload resolution to see which one is a better match for the arguments you called it with.
The definition of std::next looks like:
template <class ForwardIterator>
ForwardIterator next(ForwardIterator x,
typename std::iterator_traits<ForwardIterator>::difference_type n = 1);
This means that when the compiler performs overload resolution it substitutes the type std::string into std::iterator_traits<std::string>.
Prior to C++14 iterator_traits is not SFINAE-friendly which means that it is invalid to instantiate it with a type that is not an iterator. std::string is not an iterator, so it's invalid. The SFINAE rule does not apply here, because the error is not in the immediate context, and so using iterator_traits<T>::difference_type for any non-iterator T will produce a hard error, not a substitution failure.
Your code should work correctly in C++14, or using a different standard library implementation that already provides a SFINAE-friendly iterator_traits, such as GCC's library. I believe Microsoft will also provide a SFINAE-friendly iterator_traits for the next major release of Visual Studio.
To make your code work now you can qualify the call to next so ADL is not performed:
::next(std::string{ "abc" });
This says to call the next in the global namespace, rather than any other next that might be found by unqualified name lookup.
A:
(Updated per Jonathan's comments)
There are two views here, the C++11 and the C++14 view. Back in 2013, C++11's std::next was not properly defined. It is supposed to apply to iterators, but due to what looks like an oversight it will cause hard failures when you pass it a non-iterator. I believe the intention was that SFINAE should have prevented this; std::iterator_traits<X> should cause substitution failures.
In C++14, this problem is solved. The definition of std::next hasn't changed, but it's second argument (std::iterator_traits<>) is now properly empty for non-iterators. This eliminates std::next from the overload set for non-iterators.
The relevant declaration (taken from VS2013) is
template<class _FwdIt> inline
_FwdIt next(_FwdIt _First,
typename iterator_traits<_FwdIt>::difference_type _Off = 1)
This function should be added to the overload set if it can be instantiated for the given arguments.
The function is found via Argument Dependent Lookup and Microsoft's header structure. They put std::next in <xutility> which is shared between <string> and <iterator>
Note: _FwdIt and _Off are part of the implementation namespace. Don't use leading underscores yourself.
A:
Actually std::next() is a function defined in <iterator> which returns the next iterator passed to std::next(). Your code is running on my computer with gcc-4.9.2. More : http://en.cppreference.com/w/cpp/iterator/next
The code I used:
#include<string>
#include <iostream>
int next(std::string param){
std::cout<<param<<std::endl;
return 0;
}
void foo(){
next(std::string{ "abc" });
}
int main()
{
foo();
return 0;
}
Also on ideone : http://ideone.com/QVxbO4
| {
"pile_set_name": "StackExchange"
} |
Q:
Question in Probability Theory
Lets say that I have 3 sets $A,B,C\subseteq E$ and I know $|E|,|A|,|B|,|C|,|\overline{A}|,|A\cap B|,|B\cap C|,|C\cap A|,|\overline{A}\cap B|,|\overline{A}\cap C|$ and $|A\cap B\cap C|$.
First of all is solvable?
If yes Is there any way that I can find $|\overline{A}\cap B\cap C|$?
A:
Hint: Use the known values of $|A\cap B \cap C|$ and $|B \cap C|$.
A:
You know how many elements are in $B \cap C$, so that are both in $B$ and $C$.
Also you know how many are in $A \cap B \cap C$, so which are in all three.
The difference are all elements that are in $B$ and in $C$ but not in $A$, so exactly in $\overline{A} \cap B \cap C$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Graphical layout doesnt show toggle button
I'm new with android programming and i have a problem. I use Eclipse and i create a Toggle Button but in Graphical layout that doesn't show anything and it shows me this "Exception raised during rendering: -1". What can i do? I post below my code that i have used.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="25dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/etCommands"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Type a Command"
android:password="true" />
<LinearLayout
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_weight="20"
android:id="@+id/bResults"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Try Command" />
<ToggleButton
android:layout_weight="80"
android:paddingBottom="10dp"
android:checked="true"
android:id="@+id/tbPassword"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="ToggleButton" />
</LinearLayout>
<TextView
android:id="@+id/tvResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="invalid" />
A:
The recommended way to use "layout_weight" is to set the dimension to "0dp" and set the desired weight, so android will resize it:
<ToggleButton
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="80"
android:text="ToggleButton" />
I don't think this is the reason it crashes, so you better post the entire xml
----UPDATE----------------------------------------------
I don't get any rendering error, but as your button width is set to "fill_parent" (you should use "match_parent" instead as "fill_parent" is deprecated), and there are two items in a horizontal linear layout, the second one is not visible.
Also, use "0dp" when using weights for the intended dynamic dimension.
Here is your layout fixed. I also swapped weights so your buttons look better (I think it was a bug)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="25dp" >
<EditText
android:id="@+id/etCommands"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type a Command"
android:password="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<Button
android:id="@+id/bResults"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="80"
android:text="Try Command" />
<ToggleButton
android:id="@+id/tbPassword"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="20"
android:checked="true"
android:paddingBottom="10dp"
android:text="ToggleButton" />
</LinearLayout>
<TextView
android:id="@+id/tvResults"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="invalid" />
| {
"pile_set_name": "StackExchange"
} |
Q:
Wordpress bloginfo('template_directory') not working in jquery
I have a custom jquery file in a wordpress site and I am trying to use the bloginfo('template_directory') assigned to a variable to use in the ajax url paths rather than having to type out the full url each time (especially as this is in development on a test site at the moment so need to ensure everything works when moving to the live site on the actual domain), however all that happens is that the php is added to the url, not the directory path.
What I have at the moment:
$(document).ready(function(){
var templateDir = "<?php bloginfo('template_directory') ?>";
// Login
$('.login-form').on('submit', function(e){
e.preventDefault();
dataString = $(this).serialize() + '&ajax=1';
$.ajax ({
type: "POST",
url: templateDir + "/inc/do-login.php",
data: dataString,
cache: false,
success: function(data)
{.
.
.
}
});
});
And what I get in the console error is (site url replaced with ...):
POST http://www......./...../%3C?php%20get_bloginfo('template_directory')%20?%3E/inc/do-login.php 404 (Not Found)
Can anyone shed any light on this please.
A:
You need to create a Javascript snippet that saves the template dir in a variable, and you can use later using that variable
<script type="text/javascript">
var templateDir = "<?php bloginfo('template_directory') ?>";
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
xpath : Get data attribute / value
I want to extract from a website some product data with Xpath.
Unfortunatly , I don't get it. I am really blocked.
The URL is the following :
https://www.fertighaus.de/haeuser/suche/
my xpath in Chrome is at the moment : $x('//*[@id="SearchResultsPage"]/div[2]/div/div[2]/div[4]/div[2]/div1/div1/text()')
this xpath give an array with an element, I need a proper xpath giving me the value of data of this element( price of the house) I circled it in yellow in the picture. I guess it is a small change in this xpath....
If someone could help me, it would be great. I am new with scraping and scrapy and it it bite difficult
Thank you very much in advance
A:
My solution was to inspect the all the networking from the JS (request mad by the js ). I discovered an API that I could use very easily :).
In my case Splash or Selenium did not help .
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing pointer to function that accepts reference in c++
I guess this is a n00b question because I couldn't find anything about it on web...
Here is Point class:
class Point {
public:
Point();
Point(double x, double y);
double getX() const;
double getY() const;
void setX(double);
void setY(double);
friend std::ostream& operator<<(std::ostream& os, const Point& obj);
private:
double x;
double y;
};
And here is an implementation of operator<< function:
inline std::ostream& operator<<(std::ostream& os, const Point& obj) {
os << "(" << obj.getX() << "," << obj.getY() << ")";
return os;
}
Now, in main function I have Point *p;... How can I print it using std::cout?
A:
You need to dereference your pointer but as pointers can be null, you should check first.
if( p != nullptr )
std::cout << *p << std::endl;
or even just
if( p )
std::cout << *p << std::endl;
And now, go and read this in our community wiki, hopefully it will provide you the answers.
What are the differences between a pointer variable and a reference variable in C++?
A:
So, I finally found out where was the problem.
Although all tutorials, books and even c++ reference agree that inline directive can be ignored by the compiler, it turns out that when I remove inline keyword from implementation of an overloaded function everything works.
| {
"pile_set_name": "StackExchange"
} |
Q:
_tkinter.TclError: wrong # args : What's the matter?
Still writing a game. This error's a little different, though. I get a trace back like this...
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py",
line 1399, in __call__
return self.func(*args)
File "/Users/bluedragon1223/Desktop/Djambi0-2.py", line 68, in _newSpaceChosen
pieceID = event.widget.find_withtag(currentCommand)
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinte/__init__.py",
line2199, in find_withtag
return self.find('withtag', tagOrId)
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py",
line 2173, in find
self.tk.call((self._w, 'find') + args)) or ()
_tkinter.TclError: wrong # args: should be ".23215664 find withtag tagOrId"
I mean, I thought the code innocuous enough.
I have global variables currentCommand = None and (CurX, CurY) = (0,0) and (ToX, ToY) = (0,0) to start with, if that has something to do with it, but the main problem is my events.
There are two:
def _newSpaceChosen(event):
print(event.widget.find_withtag('rN')) #Used to check if I had used find_withtag correctly
pieceID = event.widget.find_withtag(currentCommand) #This is the problem source
[CurX, CurY] = event.widget.coords(pieceID[1])
print(CurX, CurY)
[MetaToX, MetaToY] = _point2square(event.x, event.y)
print(event.x, event.y)
print(MetaToX, MetaToY)
[ToX, ToY] = _square2point(MetaToX, MetaToY)
print(ToX, ToY)
event.widget.move(pieceID, ToX - CurX, ToY - CurY)
def _onPieceClick(event):
stuffTags = event.widget.gettags(event.widget.find_closest(event.x, event.y))
try:
event.widget.delete(event.widget.find_withtag('bbox'))
except:
pass
bboxULX = (event.x // 90 + 1) * 90
bboxULY = (event.y // 90 + 1) * 90
bboxLRX = (event.x // 90 + 1) * 90 - 90
bboxLRY = (event.y // 90 + 1) * 90 - 90
event.widget.create_rectangle(bboxULX,bboxULY,bboxLRX,bboxLRY, width=3,
outline='yellow',tag='bbox')
currentCommand = stuffTags[0]
print(currentCommand)`
The idea was to store the game piece tag in currentCommand, and then use that value to control that specific piece until the piece was moved with bindings like this:
canvas.bind('<1>', _newSpaceChosen)
in the def __init__(self, mainWin): of a class Board(Canvas):
Each piece has it's own tag_bind(#piece-var, '<1>', _onPieceClick)
My hypothesis is that currentCommand is not receiving a value soon enough.
What do you guys think causes this trace?
A:
Your hypothesis is almost certainly correct. You can easily test this hypothesis by printing out the value before calling find_withtag.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Frameworks - Layout Dynamic Menu
I am developing a website in PHP and I would like to use a mvc framework to do this as I want to gain experience with PHP frameworks.
I have looked at Zend, CakePHP, and CodeIgniter and I have not been able to find an intuitive way to accomplish this.
What I need to do is create a layout that will be for example:
<html>
<head>
<!--scripts go here-->
</head>
<body>
<div id='banner'></div>
<div id='menu'><?php $this->layout()->menu ?></div>
<div id='container'><?php $this->layout()->content ?></div>
<div id='ads'><?php $this->layout()->ads ?>
<div id='footer'>blah</div>
</body>
</html>
I am looking for a framework that could do this simply without a lot of hacks as this should be simple to accomplish from my perspective.
This would pull the menu, content, and ads from separate controllers and views and would of course be dynamic content. I do not want to put the menu code into every view...
Maybe this is simple and I am just going about it the wrong way?
Any help is appreciated.
Thank you,
-Ben
A:
Symfony can do what you are looking for using a mix of concepts.
Layout - This is the main structure used to decorate a page.
Template - This is the main view attached to a URL by the controller.
Fragments - Lightweight and uses data you pass to it.
Component - Used if you need access to the model, the code is split between presentation and logic.
Slot - used to replace a defined section of the layout.
In your case the layout would have the main content included using the template logic which is the core of the view layer and the other items would be either fragments or components depending on how much of the model they would need to access.
The Symfony documentation has a full explanation of this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Communicating between two C# exe
I have created a C# WPF project. I have two exe's running, both are created by me. One exe has a Window and another doesn't.
Now I want to communicate from the exe to the other .
I want to send a small message from exe (no window) to the other.
I really confused about this IPC in Windows C#, can anyone suggest me which one will be good for this problem
A:
You should not be rude in your comments.
Now try this:
On the client: create a client side proxy with the following few lines
// Create the proxy:
EndpointAddress ep = new EndpointAddress("net.pipe://localhost/SomeAddress/PipeEndpoint/");
IMyinterface instance = ChannelFactory<IMyinterface>.CreateChannel(new NetNamedPipeBinding(), ep);
// now use it:
instance.SendMessage();
On the server side, run the server and register the object to do the work:
ServiceHost host = new ServiceHost(new MyClass(), new Uri("net.pipe://localhost/SomeAddress"));
host.AddServiceEndpoint(typeof(IMyinterface), new NetNamedPipeBinding(), "PipeEndpoint");
host.Open();
The MyClass code on the server side too:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class MyClass : IMyinterface
{
public void SendMessage()
{
// do something here
}
}
And the interface should be in separate project referensed by both, client and server projects:
[ServiceContract]
interface IMyinterface
{
[OperationContract]
void SendMessage();
}
Remark: when I say "Client", I mean the one who sends the message. Server is the one who receives the message. I think in your architecture is the opposite, so I wanted to be clear with my terminology.
I hope it helps
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I execute a stored procedure without parameters in JDBC?
I'm trying to execute a stored procedure without input variables like :
String sql2 = "{call vivek}" ;
System.out.println(sql2);
System.out.println("Executing procedure without parameters");
stmt = conn.createStatement();
stmt.executeQuery(sql2);
But its throwing an error saying :
syntax error at or near "{"
Position: 1
I'm trying to google it but not able to find anything. How do I do it ? By the way it didn't work with callablestatement also
A:
Not tested:
CallableStatement cs = null;
cs = conn.prepareCall("{call vivek}");
cs.executeQuery();
http://docs.oracle.com/javase/tutorial/jdbc/basics/storedprocedures.html
| {
"pile_set_name": "StackExchange"
} |
Q:
unit u and primes in $\mathbb{Z}[i]$ with criterias
There is a unit u and primes $\pi_{j}=a_{j}+b_{j}i$ in $\mathbb{Z}[i]$ with $a_{j}>0, b_{j}>0$ and $7+i = u\pi_{1}\dots\pi_{k}$
$\mathbb{Z}[i]$ has four units: $i,-i,1,-1$. The product of the primes is also in $\mathbb{Z}[i]$, so : $7+i=u\pi… \pi_{k} = i(a+bi) = -b+ai$. This can't be the case since then it would follow that : $a=1, b=-7$ but since $b_{j}> 0$ i therefore can't be that unit.
For -i : we get -i(a+bi)= -ai+b . With this it follows that $a=-1, b= 7 $, therefore since $a_{j}>0$ this also can not be true.
For 1: 1(a+bi)= a+bi , a=7, b=1. This could be true, so now it is to show that 7+i is prime in $\mathbb{Z}[i]$. We can see directly that 7+i is irreducible over $\mathbb{Z}[i]$ and that means it must also be prime since $\mathbb{Z}[i]$ is a UFD. Therefore 1 is that unit.
I believe this can't be right, because I didn't use the indices at all. Does anybody see the right way? Please do tell.
A:
Your claim that $u=i$ is impossible does not follow.
You know that each $b_i$ is positive; but that does not tell you that the final product $a+bi$ must have $b$ positive.
For example, you can have $(a_1+b_1i)(a_2+b_2i)$ with $b_1,b_2\gt 0$, but with product $(a_1a_2-b_1b_2) + (a_1b_2+b_1a_2)i$ having imaginary part negative. Just take $a_1=0$, $b_1=2$, $a_2=-2$, $b_2=1$. Then you have $(0+2i)(-2+i)$, and the product is $-2-4i$, with negative real and negative imaginary parts. The other conclusions are likewise incorrect.
Finally, your claim that $7+i$ is irreducible is also incorrect. Note that $N(7+i) = 50 = 2\times 5^2$; if it is reducible, you could look for an element with norm $5$ and one with norm $10$, which quickly leads to $7+i = (2+i)(3-i)$. Since neither factor is a unit (their norms are indeed $5$ and $10$), then this shows $7+i$ is indeed reducible. (You can also look for elements with norms $2$ and $25$).
| {
"pile_set_name": "StackExchange"
} |
Q:
send cookies to another web page with javascript
How can I send cookie on a page, to another page with JS?
For example I have two pages:
1 - www.domain1.com/admin.php
2 - www.domain2.com/getCookies.php
How can I send cookies from admin.php to getCookies.php and get them in this form :
getCookies.php?name=x&val=y
x is cookie name and y is the value of x.
A:
I have done this in the past using JSONP. It will work in all browsers.
Simply read in the cookie values, craft a JSON string and send it across.
See http://www.ibm.com/developerworks/library/wa-aj-jsonp1/ for some examples.
| {
"pile_set_name": "StackExchange"
} |
Q:
My first attemp to create a wordlist,
I'm trying to create a wordlist that contains all the combination of letters(uppercase and lowercase) and some symbols. Basically most of the ASCII table.
I was just curios about how much memory the text file will occupy . I think i will use some other functions to delete unnecessary words. But for now i pray that my 1 TB hard disk won't blow up.
I don't know if this method is the right metod, using nested for loops with subscripted array, maybe i should use linked list for better performance. In the meantime i can create functions that delete lines with more characters than some tot.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PATH "wordlist.txt"
#define SIZE 68
void Write(char * word[], FILE * f, int N)
{
for(int i = 0; i <= N; i++)
{
fprintf(f,"%s", word[i]);
}
fprintf(f,"\n");
}
void thirteen_Digits(char * word[],char * letters[] , FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
for(int m = 0; m< SIZE; m++)
{
word[4] = letters[m];
for(int n = 0; n < SIZE; n++)
{
word[5] = letters[n];
for(int o = 0; o < SIZE; o++)
{
word[6] = letters[o];
for(int p = 0; p < SIZE; p++)
{
word[7] = letters[p];
for(int q = 0; q < SIZE; q++)
{
word[8] = letters[q];
for(int r = 0; r < SIZE; r++)
{
word[9] = letters[r];
for(int s = 0; s < SIZE;s++)
{
word[10] = letters[s];
for(int t = 0; t < SIZE; t++)
{
word[11] = letters[t];
for(int u = 0; u < SIZE; u++)
{
word[12] = letters[u];
Write(word, f, 12);
}
}
}
}
}
}
}
}
}
}
}
}
}
fclose(f);
}
void twelve_Digits(char * word[],char * letters[] , FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
for(int m = 0; m< SIZE; m++)
{
word[4] = letters[m];
for(int n = 0; n < SIZE; n++)
{
word[5] = letters[n];
for(int o = 0; o < SIZE; o++)
{
word[6] = letters[o];
for(int p = 0; p < SIZE; p++)
{
word[7] = letters[p];
for(int q = 0; q < SIZE; q++)
{
word[8] = letters[q];
for(int r = 0; r < SIZE; r++)
{
word[9] = letters[r];
for(int s = 0; s < SIZE;s++)
{
word[10] = letters[s];
for(int t = 0; t < SIZE; t++)
{
word[11] = letters[t];
Write(word, f,11);
}
}
}
}
}
}
}
}
}
}
}
}
}
void eleven_Digits(char * word[],char * letters[] , FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
for(int m = 0; m< SIZE; m++)
{
word[4] = letters[m];
for(int n = 0; n < SIZE; n++)
{
word[5] = letters[n];
for(int o = 0; o < SIZE; o++)
{
word[6] = letters[o];
for(int p = 0; p < SIZE; p++)
{
word[7] = letters[p];
for(int q = 0; q < SIZE; q++)
{
word[8] = letters[q];
for(int r = 0; r < SIZE; r++)
{
word[9] = letters[r];
for(int s = 0; s < SIZE;s++)
{
word[10] = letters[s];
Write(word, f,10);
}
}
}
}
}
}
}
}
}
}
}
}
void ten_Digits(char * word[],char * letters[] , FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
for(int m = 0; m< SIZE; m++)
{
word[4] = letters[m];
for(int n = 0; n < SIZE; n++)
{
word[5] = letters[n];
for(int o = 0; o < SIZE; o++)
{
word[6] = letters[o];
for(int p = 0; p < SIZE; p++)
{
word[7] = letters[p];
for(int q = 0; q < SIZE; q++)
{
word[8] = letters[q];
for(int r = 0; r < SIZE; r++)
{
word[9] = letters[r];
Write(word, f,9);
}
}
}
}
}
}
}
}
}
}
}
void nine_Digits(char * word[], char * letters[] ,FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
for(int m = 0; m< SIZE; m++)
{
word[4] = letters[m];
for(int n = 0; n < SIZE; n++)
{
word[5] = letters[n];
for(int o = 0; o < SIZE; o++)
{
word[6] = letters[o];
for(int p = 0; p < SIZE; p++)
{
word[7] = letters[p];
for(int q = 0; q < SIZE; q++)
{
word[8] = letters[q];
Write(word, f, 8);
}
}
}
}
}
}
}
}
}
}
void eight_Digits(char * word[],char * letters[] , FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
for(int m = 0; m< SIZE; m++)
{
word[4] = letters[m];
for(int n = 0; n < SIZE; n++)
{
word[5] = letters[n];
for(int o = 0; o < SIZE; o++)
{
word[6] = letters[o];
for(int p = 0; p < SIZE; p++)
{
word[7] = letters[p];
Write(word, f, 7);
}
}
}
}
}
}
}
}
}
void seven_Digits(char * word[], char * letters[] ,FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
for(int m = 0; m< SIZE; m++)
{
word[4] = letters[m];
for(int n = 0; n < SIZE; n++)
{
word[5] = letters[n];
for(int o = 0; o < SIZE; o++)
{
word[6] = letters[o];
Write(word, f, 6);
}
}
}
}
}
}
}
}
void six_Digits(char * word[],char * letters[] , FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
for(int m = 0; m< SIZE; m++)
{
word[4] = letters[m];
for(int n = 0; n < SIZE; n++)
{
word[5] = letters[n];
Write(word, f, 5);
}
}
}
}
}
}
}
void five_Digits(char * word[],char * letters[] , FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
for(int m = 0; m< SIZE; m++)
{
word[4] = letters[m];
Write(word, f, 4);
}
}
}
}
}
}
void four_Digits(char * word[], char * letters[] ,FILE * f)
{
for(int i = 0; i < SIZE; i++)
{
word[0] = letters[i];
for(int j = 0; j < SIZE ;j++)
{
word[1] = letters[j];
for(int k = 0; k < SIZE; k++)
{
word[2] = letters[k];
for(int l = 0; l < SIZE;l++)
{
word[3] = letters[l];
Write(word, f, 3);
}
}
}
}
}
int main()
{
FILE *f;
if(!(f=fopen(PATH, "a")))
{
perror("Errore");
exit(-1);
}
char * letters[SIZE] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
".","_","1","2","3","4","5","6","7","8","9","0","!","@","$","§"};
char * word13[] = {"A","A","A","A","A","A","A","A","A","A","A","A","A"};
char * word12[] = {"A","A","A","A","A","A","A","A","A","A","A","A"};
char * word11[] = {"A","A","A","A","A","A","A","A","A","A","A"};
char * word10[] = {"A","A","A","A","A","A","A","A","A","A"};
char * word9[] = {"A","A","A","A","A","A","A","A","A"};
char * word8[] = {"A","A","A","A","A","A","A","A"};
char * word7[] = {"A","A","A","A","A","A","A"};
char * word6[] = {"A","A","A","A","A","A"};
char * word5[] = {"A","A","A","A","A"};
char * word4[] = {"A","A","A","A"};
four_Digits(word4,letters, f);
five_Digits(word5,letters, f);
six_Digits(word6,letters, f);
seven_Digits(word7,letters, f);
eight_Digits(word8,letters, f);
nine_Digits(word9,letters, f);
ten_Digits(word10, letters,f);
eleven_Digits(word11,letters, f);
twelve_Digits(word12, letters,f);
thirteen_Digits(word13,letters, f);
exit(EXIT_SUCCESS);
}
I will appreciate any help for making the alghorithm faster.
A:
This program won't finish in your lifetime -- and it'll fill up your hard disk long before that.
There are 6813 = 6 × 1023 possible combinations of thirteen characters chosen from a 68-character set. At 14 bytes each (13 characters + one newline), storing them all in a file would take approximately 9.3 × 1024 bytes, or 9.3 trillion terabytes. This is several orders of magnitude larger than the amount of data storage in existence on the planet.
You need to reconsider what you're trying to do here. This clearly won't work.
From a perspective of implementation, though, there's an easier way of approaching this than using nested loops:
void permute(int length, int maximum_digit)
{
int *digits = calloc(length, sizeof(int));
do {
print_digits(digits, length);
} while (increment(digits, length, maximum_digit));
free(digits);
}
This function creates an array of a variable number of digits (set by length), and "increments" that array at each step until it has reached a maximum value (maximum_digit).
We can implement that incrementation by stepping through the array; for each digit, we increment it and stop if it's under its maximum value, or zero it and continue otherwise:
int increment(int *digits, int length, int maximum_digit)
{
for (int i = 0; i < length; i++) {
if (digits[i] + 1 == maximum_digit) {
digits[i] = 0;
} else {
digits[i]++;
return 1;
}
}
return 0;
}
An implementation of print_digits() is left to the reader.
| {
"pile_set_name": "StackExchange"
} |
Q:
LaTeX Combined hyper reference and footnote lacks verbatim argument behaviour
Possible Duplicate:
Getting those %#!^& signs in the footnote!
Here's my first version of a clever command for URL-footnotes. It combines pdftex's hyperlink behaviour with a \footnote displaying the URL.
\usepackage[pdftex]{hyperref}
\newcommand{\hrefn}[2]{\href{#1}{#2}\footnote{See {\tt #1}}} %HyperRef and Footnote in one
However it doesn't treat the input as verbatim as \href does. How do I prevent my command \hrefn from treating characters such as # and ~ as special control characters? I already \usepackage{underscore} so _ are not a problem.
/Nordlöw
A:
The url package has a command \urldef which allows you to define robust verbatim URLs that can be used in footnotes.
Also, since you’re using LaTeX, you shouldn’t be using \tt – use \ttfamily or \texttt instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Keep correct size of embed video in TinyMce
I want to add embed media in TinyMce with media plugin. When I add an embed video for example with specific size value, when I save the post, the width is not correct. The following HTML is created:
<iframe src="//www.youtube.com/embed/XlpTLDulFe8" width="100" height="100" allowfullscreen="allowfullscreen"></iframe>
But infortunatly, i've the folowing CSS (mdl CSS) that overload my width-size:
iframe {
display: block;
width: 100%;
border: none;
}
I want to use instead a max-width:100%; for keep iFrame width if it isn't superior to 100%
How can I disable the width property for iFrame created by TinyMce ? I've tried to get the HtmlElement for remove property and set another but without success.
A:
I found a solution to my problem, this isn't the clever one but this still works well. I apply the css property to the parent <p> of the <iframe> (all iframe are put in <p> tag)
I use the following function
public correctWidthIframe(html: string) {
let regex = /<p[^>]*>(<iframe*[^>]+(width=*[^height]*height="[0-9]*")[^>]*><\/iframe><\/p>)/g;
return html.replace(regex, (match, p1, p2) => {
let dimension = p2.match(/[0-9]+/g);
let style: string = '<p style="max-width:'+dimension.shift()+'px;">'; // only width is wrong
return style + p1;
});
}
I use this function when i want to create and modify message that contain embedVideo.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the right way of building a deep Q-network?
I'm new to RL and to deep q-learning and I have a simple question about the architecture of the neural network to use in an environment with a continous state space a discrete action space.
I tought that the action $a_t$ should have been included as an input of the neural network, togheter with the state. It also made sense to me as when you have to compute the argmax or the max w.r.t. $a_t$ it was like a "standard" function. Then I've seen some examples of networks that had as inputs only $s_t$ and that had as many outputs as the number of possible actions. I quite understand the logic behind this (replicate the q-values pairs of action-state) but is it really the correct way? If so, how do you compute the $argmax$ or the $max$? Do I have to associate to each output an action?
A:
Do I have to associate to each output an action?
You are absolutely correct! In DQN, each output node of the neural network will be associated with one of your possible actions (assuming a finite discrete action space). After passing an input through the network, the value of each output node is the estimated q-value of the corresponding action. One benefit of this architecture is that you only need to pass the input through the neural network once to compute the q-value of each action, which is constant in the number of actions. If you were to include an action as an input to the neural network along with an observation, then you would need to pass an input for each action, which scales linearly in the number of actions. This is mentioned in paragraph 2 of Section 4.1 in the original DQN paper (https://arxiv.org/abs/1312.5602)
Is it really the correct way? If so, how do you compute the argmax or the max?
It's one possible way that is used in many popular algorithms such as DQN. To find the argmax, you simply take the action corresponding to the output node with highest q-value after passing an input through the network.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Check if list item does (not) contain any of other list items
I have this problem where I want to remove a list element if it contains 'illegal' characters. The legal characters are specified in multiple lists. They are formed like this, where alpha stands for the alphabet (a-z + A-Z), digit stands for digits (0-9) and punct stands for punctuation (sort of).
alpha = list(string.ascii_letters)
digit = list(string.digits)
punct = list(string.punctuation)
This way I can specify something as an illegal character if it doesn't appear in one of these lists.
After that I have a list containing elements:
Input = ["Amuu2", "Q1BFt", "dUM€n", "o°8o1G", "mgF)`", "ZR°p", "Y9^^M", "W0PD7"]
I want to filter out the elements containing illegal characters. So this is the result I want to get (doesn't need to be ordered):
var = ["Amuu2", "Q1BFt", "mgF)`", "Y9^^M", "W0PD7"]
EDIT:
I have tried (and all variants of it):
for InItem in Input:
if any(AlItem in InItem for AlItem in alpha+digit+punct):
FilInput.append(InItem)
where a new list is created with only the filtered elements, but the problem here is that the elements get added when the contain at least one legal character. For example: "ZR°p" got added, because it contains a Z, R and a p.
I also tried:
for InItem in Input:
if not any(AlItem in InItem for AlItem in alpha+digit+punct):
but after that, I couldn't figure out how to remove the element.
Oh, and a little tip, to make it extra difficult, it would be nice if it were a little bit fast because it needs to be done millions of times. But it needs to be working first.
A:
Define a set of legal characters. Then apply a list comprehension.
>>> allowed = set(string.ascii_letters + string.digits + string.punctuation)
>>> inp = ["Amuu2", "Q1BFt", "dUM€n", "o°8o1G", "mgF)`", "ZR°p", "Y9^^M", "W0PD7"]
>>> [x for x in inp if all(c in allowed for c in x)]
['Amuu2', 'Q1BFt', 'mgF)`', 'Y9^^M', 'W0PD7']
A:
Your code
As you mentioned, you append words as soon as any character is a correct one. You need to check that they are all correct:
filtered_words = []
for word in words:
if all(char in alpha+digit+punct for char in word):
filtered_words.append(word)
print(filtered_words)
# ['Amuu2', 'Q1BFt', 'mgF)`', 'Y9^^M', 'W0PD7']
You could also check that there's not a single character which isn't correct:
filtered_words = []
for word in words:
if not any(char not in alpha+digit+punct for char in word):
filtered_words.append(word)
print(filtered_words)
It's much less readable though.
For efficiency, you shouldn't concatenate lists during each iteration with alpha+digit+punct. You should do it once and for all, before any loop. It's also a good idea to create a set out of those lists, because char in set is much faster than char in list when there are many allowed characters.
Finally, you could use a list comprehension to avoid the for loop. If you do all this, you end up with @timgeb's solution :)
Alternative with regex
You can create a regex pattern from your lists and see which words match:
# encoding: utf-8
import string
import re
alpha = list(string.ascii_letters)
digit = list(string.digits)
punct = list(string.punctuation)
words = ["Amuu2", "Q1BFt", "dUM€n", "o°8o1G", "mgF)`", "ZR°p", "Y9^^M", "W0PD7"]
allowed_pattern = re.compile(
'^[' +
''.join(
re.escape(char) for char in (
alpha +
digit +
punct)) +
']+$')
# ^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\=\>\?\@\[\\\]\^_\`\{\|\}\~]+$
print([word for word in words if allowed_pattern.match(word)])
# ['Amuu2', 'Q1BFt', 'mgF)`', 'Y9^^M', 'W0PD7']
You could also write:
print(list(filter(allowed_pattern.match, words)))
# ['Amuu2', 'Q1BFt', 'mgF)`', 'Y9^^M', 'W0PD7']
re.compile will probably require more time than simply initializing a set but the filtering might be faster then.
| {
"pile_set_name": "StackExchange"
} |
Q:
Окончание в существительном
Ожидайте поступленИЯ средств / Ожидайте поступленИЕ средств
Как правильно?
A:
Здесь первый, с родительным падежом лучше. Вообще глагол "ждать" с производными сейчас все активнее использует родительный падеж дополнения. Когда речь идет о неконкретном, не фиксированном по времени и месту событии, родительный - норма.
Другими словами, можно равноправно ожидать поезд, холодА, платеж и ожидать поезда, холодов, платежа - с несколько раздичным смыслом.
Но при этом желательно только ожидать прибытия поезда, наступления холодов, поступления платежа и т. д. Иное выглядит косноязычно.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regarding a method "cannot be resolved to a type" error
I am trying to create null nodes at the bottom of a RBTree and want to instantiate EMPTY as an empty node.
this the line that has the error:
final private Node<E> EMPTY = new Empty();
And the empty class:
private class Empty extends Node<E> {
public Empty() {
red = false;
}
public Node<E> add(E data) {
count++;
return new Node<E>(data);
}
public Node<E> getNode(E data) {
return null;
}
}
I know it has something to do with the constructor but I can't zero in on it.
I have tried searching but most everything I come across on this site is related to android programming and/or some other language I'm not familiar with. I've tried the following:
(Node) casting the new Empty(); then realized it was obviously not that.
and working with the class seeing if public would work.
Aside from programming changes i've also tried the solutions offered here:
http://philip.yurchuk.com/software/eclipse-cannot-be-resolved-to-a-type-error/
But to no success.
Sorry if this question is out of place, and thank you for your time!
complete code:
package data_structures;
public class RedBlackTree<E extends Comparable<E>> {
private Node<E> root;
private int count = 0;
final private Node<E> EMPTY = new Empty<E>();
public RedBlackTree() {
root = EMPTY;
}
public void add(E data) {
root = root.add(data);
count++;
root.red = false;
}
public boolean find(E data) {
return root.getNode(data) != null;
}
private class Node<E> {
public E data;
public boolean red;
public Node<E> leftChild;
public Node<E> rightChild;
/** Used by Empty */
protected Node() {
assert EMPTY == null;
}
/** Nodes always begin red */
public Node(E k) {
data = k;
red = true;
leftChild = (Node<E>) EMPTY;
rightChild = (Node<E>) EMPTY;
}
private boolean isRed() {
return red;
}
public int height(){
return 0; //returns the counts binary left most bit position to determine the height.
}
public Node<E> add(E newData) {
if(((Comparable<E>) newData).compareTo(data) == -1) {
count++;
leftChild = leftChild.add(newData);
return leftChild;
}
if(((Comparable<E>) newData).compareTo(data) == +1){
count++;
rightChild = rightChild.add(newData);
return rightChild;
}
if(((Comparable<E>) newData).compareTo(data) == 0){
return this;
}
if (leftChild.isRed() && leftChild.leftChild.isRed()) {
return balance(leftChild.leftChild, leftChild, this,
leftChild.leftChild.rightChild, leftChild.rightChild);
} else if (leftChild.isRed() && leftChild.rightChild.isRed()) {
return balance(leftChild, leftChild.rightChild, this,
leftChild.rightChild.leftChild, leftChild.rightChild.rightChild);
} else if (rightChild.isRed() && rightChild.leftChild.isRed()) {
return balance(this, rightChild.leftChild, rightChild,
rightChild.leftChild.leftChild, rightChild.leftChild.rightChild);
} else if (rightChild.isRed() && rightChild.rightChild.isRed()) {
return balance(this, rightChild, rightChild.rightChild,
rightChild.leftChild, rightChild.rightChild.leftChild);
}
return this;
}
/** Returns the node for this key, or null. */
public Node<E> getNode(E newData) {
if(((Comparable<E>) newData).compareTo(data) == -1){
return leftChild.getNode(newData);
}
if(((Comparable<E>) newData).compareTo(data) == +1){
return rightChild.getNode(newData);
}
else{
return this;
}
}
private class Empty<E> extends Node<E> {
public Empty() {
red = false;
}
public Node<E> add(E data) {
count++;
return new Node<E>(data);
}
public Node<E> getNode(E data) {
return null;
}
}
private Node<E> balance(Node<E> a, Node<E> b, Node<E> c, Node<E> d, Node<E> e) {
a.rightChild = d;
b.leftChild = a;
b.rightChild = c;
c.leftChild = e;
a.red = false;
b.red = true;
c.red = false;
return b;
}
}
}
A:
You can't write
Node<E> EMPTY = new Empty<E>();
because E is a generic type. You can only create an object with actual class, such as:
Node<String> EMPTY = new Empty<String>()
If you know what you are doing, you can do an ugly trick that should work with a warning
Node<E> EMPTY = new Empty();
Also, move the Empty class outside of Node.
| {
"pile_set_name": "StackExchange"
} |
Q:
Whats the correct replacement for posix_memalign in Windows?
I currently trying to build word2vec in Windows. But there are problems with posix_memalign() function. Everyone is suggesting to use _aligned_malloc(), but the number of parameters are different. So what's the best equivalent for posix_memalign() in Windows?
A:
_aligned_malloc() should be decent replacement for posix_memalign() the arguments differ because posix_memalign() returns an error rather than set errno on failure, other they are the same:
void* ptr = NULL;
int error = posix_memalign(&ptr, 16, 1024);
if (error != 0) {
// OMG: it failed!, error is either EINVAL or ENOMEM, errno is indeterminate
}
Becomes:
void* ptr = _aligned_malloc(1024, 16);
if (!ptr) {
// OMG: it failed! error is stored in errno.
}
A:
Thanks everyone. Based on code I fond in some repository and your advices I build EXE sucessfully. Here the code I used:
#ifdef _WIN32
static int check_align(size_t align)
{
for (size_t i = sizeof(void *); i != 0; i *= 2)
if (align == i)
return 0;
return EINVAL;
}
int posix_memalign(void **ptr, size_t align, size_t size)
{
if (check_align(align))
return EINVAL;
int saved_errno = errno;
void *p = _aligned_malloc(size, align);
if (p == NULL)
{
errno = saved_errno;
return ENOMEM;
}
*ptr = p;
return 0;
}
#endif
UPDATE:
Looks like @alk suggest the best sollution for this problem:
#define posix_memalign(p, a, s) (((*(p)) = _aligned_malloc((s), (a))), *(p) ?0 :errno)
| {
"pile_set_name": "StackExchange"
} |
Q:
beamer definition-list overlay: uncover definition later than entry
For educational purposes, I would like to uncover the definitions of my description items only after all the items themselves have been uncovered, like so:
\documentclass{beamer}
\begin{document}
\begin{frame}
\begin{overprint}
\begin{description}
\item<1->[Spam]
\onslide<3->{Eggs}
\item<2->[Cheese]
\onslide<4->{Tofu}
\end{description}
\end{overprint}
\end{frame}
\end{document}
However, this has the effect that both Spam and Eggs appear only on slide 3. I would like that in slide 1, I have Spam (but without any content), and in slide 3, I have Spam and Eggs. How can I achieve this?
An alternative would be to use a tabular environment, but I'm interested to see if it can be achieved with a description.
A:
Something like this works:
\documentclass{beamer}
\newcommand\desctext[1]{%
\only<+(1)>{\mbox{}}%
\onslide<+(1)->{#1}}
\begin{document}
\begin{frame}
\begin{overprint}
\begin{description}
\addtocounter{beamerpauses}{-1}
\item[Spam1]\desctext{Eggs1}
\item[Spam2]\desctext{Eggs2}
\item[Spam3]\desctext{Eggs3}
\item[Spam4]\desctext{Eggs4}
\addtocounter{beamerpauses}{1}
\end{description}
\end{overprint}
\end{frame}
\end{document}
For the ordering required (all labels first, then all descriptions), something like this can be done:
\documentclass{beamer}
\newcommand\desctext[2][]{%
\only<+(1)->{\mbox{}}%
\onslide<#1->{#2}}
\begin{document}
\begin{frame}
\begin{overprint}
\begin{description}
\addtocounter{beamerpauses}{-1}
\item[Spam1]\desctext[5]{Eggs1}% add one to the number of items
\item[Spam2]\desctext[6]{Eggs2}
\item[Spam3]\desctext[7]{Eggs3}
\item[Spam4]\desctext[8]{Eggs4}
\addtocounter{beamerpauses}{1}
\end{description}
\end{overprint}
\end{frame}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Where do exactly bitcoins exist?
If Someone has bitcoin in a Wallet, then suppose that the company of the wallet get closed or finished work or destroyed, how could one restore his bitcoin?
Where exactly do the bitcoins exist? Are they "exist" in the blockchain and can be resored from there?
A:
Bitcoins are stored in the blockchain in the form of unspent transaction outputs, i.e. the product of confirmed transactions. These unspent transaction outputs can be spent if you control the private key corresponding to the address they were signed over to. If a private key is lost irretrievably, the coins will never become spendable again. There is no key recovery service. You're responsible of creating sufficient backups and keeping your private keys safe.
If a company shuts down their service, they should pay out any remaining balances to their users. If they have full custody and go out of business without returning balances, you're probably (depending on the exact circumstances) out ouf luck.
A:
your question may not be specific enough... general rule: as long as you have the private key (!), you can get your bitcoins. Why?
Wallets store private keys, and from these private keys, you derive the pubkeys. And a little more magic code (well, not really) gives you your bitcoin address. Effectivly that's what is stored in a wallet. There are no Bitcoins in your wallet!
Bitcoins exist in the blockchain (keyword is UTXO), and they can be transferred from one address to another. So effectivly the bitcoins are in the blockchain.
So when the company goes down, and they did not provide you the privkeys, you're lost (this is true for "web wallets"). On wallets, that are located on your local machine, you usually have a seed or can somehow extract the priv key. This means, you will still have access to the bitcoins, even if the company doesn't exist any more.
The concept of keys, addresses and wallets are well describerd here: http://chimera.labs.oreilly.com/books/1234000001802/ch04.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Pylint: can inherited public methods be exclude from statistics?
Pylint keeps reporting error (R: 73,0:MyLogging: Too many public methods (22/20)) for the following code:
class MyLogging(logging.Logger):
def foo(self):
pass
def bar(self):
pass
At first I thought it's a bug in Pylint since MyLogging class had exactly 22 lines of code, but than I realized, that it's including all public methods from the base class logging.Logger as well, which adds 20 to the stats.
Do you know if it's possible to exclude base classes public methods from Pylint statistics?
PS. I'm aware I can change max-public-methods to higher number, or add one time exception with # pylint: disable=R0904
A:
There are ways but none of them are good.
This is not configurable: you can check the code in pylint design_analysis.MisdesignChecker, within def leave_class:
for method in node.methods():
if not method.name.startswith('_'):
nb_public_methods += 1
The above code simply iterates over all methods not starting with "_" and counts them as public methods.
Consequently, I see two ways to do what you want to do:
1) fork pylint and modify this method:
for method in node.methods():
if not method.name.startswith('_') and method.parent == node:
nb_public_methods += 1
method.parent - the class node where this function is defined; also in your leave_class function you have a parameter node - which is the class node.
Comparing them you can understand if it is the current class or not.
2) disable this rule in the pylint config and create you own plugin:
MAX_NUMBER_PUBLIC_METHODS = 3
class PublicMethodsChecker(BaseChecker):
__implements__ = (IASTNGChecker,)
name = 'custom-public-methods-checker'
msgs = {
"C1002": ('Too many public methods (%s/%s)',
'Used when class has too many public methods, try to reduce \
this to get a more simple (and so easier to use) class.'),
}
def leave_class(self, node):
"""check number of public methods"""
nb_public_methods = 0
print type(node)
for method in node.methods():
if not method.name.startswith('_') and method.parent == node:
nb_public_methods += 1
if nb_public_methods > MAX_NUMBER_PUBLIC_METHODS:
self.add_message('C1002',
node=node,
args=(nb_public_methods, MAX_NUMBER_PUBLIC_METHODS))
basically this implementation is the slightly modified excerpt of design_analysis.MisdesignChecker from the pylint source code.
For more information about plugins: http://www.logilab.org/blogentry/78354, and in the pylint source code.
| {
"pile_set_name": "StackExchange"
} |
Q:
php DateTime object comparison
I have simple DateTime lesson. I'm comparing the 2 DateTime objects and they dont work right. I've tried swapping things around and it still fails. It fails when I enter the current date manually, even if the date is the same. I have to enter a date manually though. Thanks for any help. Heres the function:
function dtcompare(){
//I make the date the same as the current
//date and it doesnt echo that its equal.
$date1 = new DateTime('5/9/2015'); //a date entered
$date2 = new DateTime(); //the current date
$mdy = 'n/j/Y'; //the format
if($date1 == $date2){
echo "d1 == d2"; //This should be echoing
}
elseif($date1 > $date2){
echo "d1 > d2";
}
elseif($date1 < $date2){
echo " d1 < d2 "; //but this always echos
}
}
I changed everything to make format comparisons, but now the lowest date echos even when I put in a future date. Heres what happens:
function dtcompare(){
$date1 = new DateTime('5/18/2015'); //a future date
$date2 = new DateTime(); //the current date
$mdy = 'n/j/Y'; //the format
if($date1->format($mdy) == $date2->format($mdy)){
echo "d1 == d2";
}
elseif($date1->format($mdy) > $date2->format($mdy)){
//This will echo if the date is in the next month 6/1/2015
echo "d1 > d2";
}
elseif($date1->format($mdy) < $date2->format($mdy)){
//This echos even though it's not 5/18/2015 yet!
echo $date1->format($mdy)."d1 < d2".$date2->format($mdy);
}
}
I've been playing with this, and I got it to work by using some of both. I think this is not the way its supposed to work and might cause problems with some other date now that im unaware of. Heres what I did:
function dtcompare(){
$date1 = new DateTime('5/12/2015'); //a future date
$date2 = new DateTime(); //the current date
$mdy = 'n/j/Y'; //the format
//Using the datetime->format for == comparisons and the other
//way for datetimes greater or less than. This works, but I think this is NOT
//how this should work though. It feels like a rig for something that
//should work one way (DateTime->format() comparison) or another (DateTime comparison w.o format)
if($date1->format($mdy) == $date2->format($mdy)){
echo 'date1 and date2 have the same date and time';
}
elseif($date1 > $date2){
echo 'date1 > date2 meaning its a later date and time';
}
elseif($date1 < $date2){
echo 'date1 < date2 meaning its an earlier date and time';
}
}
A:
Well you defined your format in which you want to compare your two DateTime's, but you didn't used it.
Just use format() with your format variable when you compare the two DateTimes's otherwise also secons and minutes, just everything gets compared.
if($date1->format($mdy) == $date2->format($mdy)){
//^^^^^^^^^^^^^^ See here, to just compare month, day and year
echo "d1 == d2"; //This should be echoing
}
elseif($date1->format($mdy) > $date2->format($mdy)){
echo "d1 > d2";
}
elseif($date1->format($mdy) < $date2->format($mdy)){
echo " d1 < d2 "; //but this always echos
}
EDIT:
This should work for you, you have to first format your date and then take the timestamp, like this:
$mdy = 'n/j/Y'; //the format
$date1 = strtotime((new DateTime('5/18/2015'))->format($mdy));
$date2 = strtotime((new DateTime())->format($mdy));
if($date1 == $date2){
echo "d1 == d2";
} elseif($date1 > $date2) {
echo "d1 > d2";
} elseif($date1 < $date2){
echo $date1."d1 < d2".$date2;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Polymorphic Comments with Ancestry Problems
I am trying to roll together two Railscasts: http://railscasts.com/episodes/262-trees-with-ancestry and http://railscasts.com/episodes/154-polymorphic-association on my app.
My Models:
class Location < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
My Controllers:
class LocationsController < ApplicationController
def show
@location = Location.find(params[:id])
@comments = @location.comments.arrange(:order => :created_at)
respond_to do |format|
format.html # show.html.erb
format.json { render json: @location }
end
end
end
class CommentsController < InheritedResources::Base
def index
@commentable = find_commentable
@comments = @commentable.comments.where(:company_id => session[:company_id])
end
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
@comment.user_id = session[:user_id]
@comment.company_id = session[:company_id]
if @comment.save
flash[:notice] = "Successfully created comment."
redirect_to :id => nil
else
render :action => 'new'
end
end
private
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
In my locations show view I have this code:
<%= render @comments %>
<%= render "comments/form" %>
Which outputs properly. I have a _comment.html.erb file that renders each comment etc. and a _form.html.erb file that creates the form for a new comment.
The problem I have is that when I try <%= nested_comments @comments %> I get undefined method 'arrange'.
I did some Googling and the common solution to this was to add subtree before the arrange but that throws and undefined error also. I am guessing the polymorphic association is the problem here but I am at a loss as to how to fix it.
A:
Dumb mistake... forgot to add the ancestry gem and required migration which I thought I had already done. The last place I checked was my model where I eventually discovered my error.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dom Modification to clear Radio Button Info with Reset Button
So I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText".
<script type="text/javascript">
function textToDisplay (radioValue) {
console.log("textToDisplay + " + radioValue);
var displayText = "";
if (radioValue == "S") {
displayText = "Shortboards are under 7 ft in length.";
}
else if (radioValue == "L") {
displayText = "Longboards are usually between 8 and 10 ft.";
}
if (radioValue == "A") {
displayText = "Alternative boards defy easy aesthetic description.";
}
if (radioValue == "M") {
displayText = "Mid-Length surfboards are between 7 and 8 ft.";
}
return (displayText)
}
//DOM modification
function modifyDom(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
console.log(node);
var insertnode = document.getElementById("radioButtons");
var infonode = document.getElementById("info")
if (infonode === null) {
console.log("infonode does not yet exist");
var node = document.createElement("DIV");
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
console.log(node);
insertnode.appendChild(node);
}
else {
console.log("infonode already exists");
infonode.innerHTML = displayText;
}
}
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
var cbSelected = 0;
for (i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
cbSelected += 1;
}
}
if (cbSelected < 2) {
return (errorString);
} else {
return "";
}
}
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.extras, "At least TWO fin setup needs
to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
When I reset my page using the button,
<input type="reset" name="reset" value="Reset">
the buttons themselves are cleared but the information that appeared from selecting the button is still visible. How can I reset the page so the displayText information is not visible? Thanks!
A:
You can use an event listener for the reset event generated by clicking the reset button to execute cleanup code.
Here's a cut down example of the technique:
"use strict";
let myForm = document.getElementById("myForm");
let infoNode = document.getElementById("infonode");
let infoText = {
"S": "small board's are good",
"L": "large board's are good too"
};
myForm.addEventListener("change", function (event) {
if(event.target.name == "size") {
infoNode.innerHTML = infoText[ event.target.value];
}
}, false);
myForm.addEventListener("reset", function (event) {
infoNode.innerHTML = "";
}, false);
<form id="myForm">
<label> <input name="size" type="radio" value = "S"> Short</label><br>
<label> <input name="size" type="radio" value = "L"> Long</label><br>
<input type="reset" value="reset">
</form>
<div id="infonode"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Restrict modification of public view
Here's a situation:
I have users that use a list. They're allowed (and encouraged) to create personal views. With this, I wanted to see if there was a way to keep these users from being able to modify existing public views? There are a couple of users that make things difficult for the rest of the team, because they're constantly changing the default public view.
A:
Probably Users have set Edit Permissions, so change it to Contribute or create your own Permission level:
Go to Site Settings > Site Permissions > Permission Levels (in ribbon) > Click on Edit, in the end click on "Copy this permissions" - remove Manage Lists, save as new Permissions Level, use this permission Level for users
Don't edit original permission levels, always create new one.
| {
"pile_set_name": "StackExchange"
} |
Q:
ggplot grouping when using functions inside aesthetics
I'm quite new to R and ggplot and am having a tough time grasping how I am supposed to solve this problem in ggplot.
Essentially I want to draw 2 lines on a plot. One for method "a" and one for method "b". That is usually straightforward, but now I have a situation where I want to use functions in the aesthetic.
I want to do rank and length, but for each grouping separately. In this ggplot code, the rank and length are computed over all values. I have tried a lot of different configurations, but can't seem to get this! I include the code here to get the desired plot with regular plots.
d <- rbind(
data.frame(value=1:100, method=c("a")),
data.frame(value=50:60, method=c("b"))
)
ggplot(d, aes(x=value, y=rank(value)/length(value), colour=method)) + geom_point()
a <- d$value[d$method=="a"]
b <- d$value[d$method=="b"]
plot(
rank(a)/length(a),
col="red",
xlab="value",
ylab="F(value)",
pch=19
)
points(
rank(b)/length(b),
col="blue"
)
Is this possible with ggplot or do I need to do my calculations beforehand and then make a special plotting dataframe?
I am finding ggplot powerful, whenever I know how to do something, but frustrating as soon as I don't! Especially when I don't know if it can't do something, or if I just don't know how!
Thanks
A:
Thanks to the commenters. Here is their solution in the context of my test case for reference.
Ranking the grouped values outside of ggplot.
d <- rbind(
data.frame(value=1:100, method=c("a")),
data.frame(value=50:60, method=c("b"))
)
d <- mutate(group_by(d, method), rank=rank(value)/length(value))
ggplot(d, aes(x=value, y=rank, colour=method)) + geom_point()
| {
"pile_set_name": "StackExchange"
} |
Q:
Help-Sent Monero From Changelly and did not received funds
I am a total Tech NOOB. I set up the Monero GUI wallet yesterday and moved BTC to Changelly to convert to XMR. Changelly shows the transaction record but something went wrong did not get the funds in wallet. I think it was syncing still. I however have read notes have no real clue how to resolve. If anyone can help in simple step by step I would highly appreciate you!!!! I tried to put the block hash in blockchain tracking sites and said not found. I would appreciate any and all help. Thanks
A:
Check that Changly actually sent the funds. Get the TXID from them and try to find it here: https://xmrchain.net/ If they didn't send, you need to work it out with them.
If funds were sent, you can verify they were sent to the correct address even if your wallet is not yet up to date: https://monero.stackexchange.com/a/4598/57
If you verified it was sent correctly, try this: Outputs on xmrchain.net show that I have a balance but command line says no balance
| {
"pile_set_name": "StackExchange"
} |
Q:
Ayuda con tipo de dato en MySQL
Este es el script de la base de datos, todo se inserta correctamente excepto la parte del precio, al verlo en un archivo php (en el que todos los datos están en una tabla) se presentan como :
31.84
38.74
y
32.51
es decir se omite el último número que es 0 en los tres casos, necesito poder ver las cifras como las inserté, pero no sé si es por el tipo de dato, o por un error al insertarlas.
CREATE DATABASE IF NOT EXISTS `catalogo_audi` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `catalogo_audi`;
CREATE TABLE IF NOT EXISTS`audi`(
`idAudi` int,
`modelo` varchar(30) ,
`imagen` varchar(30) ,
`descripcion` TEXT,
`precio` float
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `audi` (`idAudi`, `modelo`,`imagen`, `descripcion`, `precio`) VALUES
(1, 'Audi A4','P01.jpg','Tipo de motor: Diésel, 4 cilindros en línea, 16 válvulas, TDI con turbo TGV e intercooler, DOHC
Sistema de inyección common-rail, 1.800 bares con inyectores piezoeléctricos, inyección directa con inyectores de 8 orificios, turboalimentación VTG con refrigeración del aire de sobrealimentación; canales de admisión de turbulencia y tangenciales, canal de turbulencia regulado; Bosch EDC; regulación del caudal y del inicio de inyección, control de presión de sobrealimentación y de recircirculación de gases de escape a baja temperatura.
Velocidad máxima: 215 km/h
Aceleración: 9,5 s',31.840),
(2, 'AUDI A6','P02.jpg','Tipo de motor: 4 cilindros en línea, inyección directa TFSI - 16 válvulas
Sistema de gestión del motor totalmente electrónico. Bosch MED 9.1; inyección directa, regulación lambda adaptable, encendido con distribución estática de alta tensión, regulación de picado selectiva y adaptable.
Velocidad máxima: 228 km/h
Aceleración: 8,2 s',38.740),
(3, 'Audi A8','P03.jpg','Tipo de motor: 8 cilindros en V, 32 válvulas
Sistema de gestión del motor totalmente electrónico, Bosch MED 17.1.1; inyección directa FSI con 120 bar de presión del sistema.
Velocidad máxima: 250 km/h
Aceleración: 6,9 s',0),
(4, 'aUDI TT','P04.jpg','Tipo de motor: 4 cilindros en línea, inyección directa TFSI - 16 válvulas
Gestión electrónica con control electrónico del acelerador, inyección directa; regulación lambda adaptable; encendido con distribución estática de alta tensión, regulación de picado selectiva y adaptable por cilindro; medición de la masa de aire.
Velocidad máxima: 226 km/h
Aceleración: 7,2 s',32.510);
A:
Para guardar precios MySQL recomienda el tipo de datos DECIMAL.
Es lo que se puede deducir leyendo la documentación:
Los tipos DECIMAL y NUMERIC almacenan valores de datos numéricos
exactos. Estos tipos se utilizan cuando es importante preservar la
precisión exacta, por ejemplo, con datos monetarios.
MySQL almacena valores DECIMAL en formato binario. Vea la Sección
12.21, "Matemáticas de Precisión".
En una declaración de columna DECIMAL, la precisión y la escala
pueden (y generalmente deben) especificarse; por ejemplo:
salario DECIMAL (5,2)
En este ejemplo, 5 es la precisión y 2 es la escala. La precisión
representa el número de dígitos significativos que se almacenan para
los valores, y la escala representa el número de dígitos que se pueden
almacenar después del punto decimal.
El SQL estándar requiere que DECIMAL (5,2) pueda almacenar cualquier
valor con cinco dígitos y dos decimales, por lo que los valores que se
pueden almacenar en el rango de la columna de salario de -999.99 a
999.99.
En SQL estándar, la sintaxis DECIMAL (M) es equivalente a DECIMAL
(M, 0). De forma similar, la sintaxis DECIMAL es equivalente a
DECIMAL (M, 0), donde la implementación permite decidir el valor de
M. MySQL admite ambas formas variantes de sintaxis DECIMAL. El
valor predeterminado de M es 10.
Si la escala es 0, los valores DECIMAL no contienen punto decimal
o parte fraccionaria.
El número máximo de dígitos para DECIMAL es 65, pero el rango real
para una columna DECIMAL determinada puede estar restringido por la
precisión o escala de una columna determinada. Cuando a dicha columna
se le asigna un valor con más dígitos después del punto decimal que
los permitidos por la escala especificada, el valor se convierte a esa
escala. (El comportamiento preciso es específico del sistema
operativo, pero generalmente el efecto es el truncamiento al número
permitido de dígitos).
Documentación de MySQL
Conclusión
Si es posible, cambia el tipo de datos de float a decimal, aplicando una política de seguridad y verificación de datos si la tabla en cuestión ya está en producción.
¿Por qué no usar float?
Porque los valores float son vulnerables a errores de redondeo y dependen además de muchos otros factores, por lo que la exactitud está en juego.
La documentación dice lo siguiente:
Debido a que los valores de coma flotante son aproximados y no se
almacenan como valores exactos, los intentos de tratarlos como exactos
en las comparaciones pueden generar problemas. También están sujetos a
dependencias de plataforma o implementación. Para obtener más
información, consulte la Sección B.5.4.8, "Problemas con los valores
de coma flotante".
float en la documentación de MySQL
| {
"pile_set_name": "StackExchange"
} |
Q:
ABI Split failed in NativeScript 2.3.0
I’ve asked for help in the general group but most people didnt get it work as well.
Im having a huge problem ridiculous apk size of my simple app. I used @markosko nativescript filter to reduce the app to 14MB from 17.2MB, even nativescript-snapshot couldn't help still 17MB for release version.
I tried using the ABI split sample in the nativescipt documentation but what I noticed is that it’s trying to split but the glade is using same name for all the apks so I came up with this in my app.glade
def tnsBuildMultipleApks=true;
android {
defaultConfig {
generatedDensities = []
applicationId = "com.maliyo.oneclick"
versionCode Integer.parseInt("" + "1" + "0")
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
if (Boolean.valueOf(tnsBuildMultipleApks)) {
splits {
abi {
enable true
reset()
include 'armeabi', 'armeabi-v7a', 'x86', 'mips'
universalApk true
}
}
}
}
def getDate() {
def date = new Date()
def formattedDate = date.format('yyyyMMdd')
return formattedDate
}
// map for the version code that gives each ABI a value
ext.versionCodes = [
'F0F1F2X86Debug':1, 'F0F1F2ArmeabiDebug':2, 'F0F1F2Armeabi-v7aDebug':3, 'F0F1F2MipsDebug':4,
'F0F1F2X86Release':1, 'F0F1F2ArmeabiRelease':2, 'F0F1F2Armeabi-v7aRelease':3, 'F0F1F2MipsRelease':4
]
// For each APK output variant, override versionCode with a combination of
// ABI APK value * 100 + defaultConfig.versionCode
android.applicationVariants.all { variant ->
// assign different version code for each output
variant.outputs.each { output ->
if (output.outputFile != null && output.outputFile.name.endsWith('.apk')) {
println("******************************************************")
println(output);
println(output.getVariantOutputData().getFullName())
if (Boolean.valueOf(tnsBuildMultipleApks)) {
def file = output.outputFile
// version at the end of each built apk
//output.outputFile = new File(file.parent, file.name.replace(".apk", "-" + android.defaultConfig.versionName + "-" + getDate() + ".apk"))
output.outputFile = new File(file.parent, file.name.replace(".apk", "-" + output.getVariantOutputData().getFullName() + "-" + getDate() + ".apk"))
output.versionCodeOverride =
//(assd++) * 100
project.ext.versionCodes.get(output.getVariantOutputData().getFullName(), 0) * 100
+ android.defaultConfig.versionCode
}
}
}
}
/**/
Fine, it splits but I think because I hacked the filename at output the adb couldn't find one to push the apk to the device or emulator due to the naming pattern, maybe, just saying apk not found.
I tried to manually send the appropriate apk to the device via USB, it app installed successfully but it crashes after splashscreen saying metadata/treeNodeStream.dat could not be loaded
UPDATE
@plamen-petkov thanks so much for your contribution, I agree with you that it work fine, when you build one after another changing the abi filter. But with this in my app.gradle, I managed to build multiple apks successfully and tested and OK.
but is like the the tns is only pushing appname-debug.apk or appname-release.apk to the adb. I can toggle this splitting off with tnsBuildMultipleApks and maybe when Im still testing I can turn it off and use tns run android and when I want to make final build and it turn it one again as it works fine with tns build android --release ....
// Add your native dependencies here:
// Uncomment to add recyclerview-v7 dependency
//dependencies {
// compile 'com.android.support:recyclerview-v7:+'
//}
import groovy.json.JsonSlurper //used to parse package.json
def tnsBuildMultipleApks=true;
String content = new File("$projectDir/../../app/package.json").getText("UTF-8")
def jsonSlurper = new JsonSlurper()
def appPackageJson = jsonSlurper.parseText(content)
android {
defaultConfig {
generatedDensities = []
applicationId = appPackageJson.nativescript.id
versionCode = appPackageJson.version_code ?: 1
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
if (Boolean.valueOf(tnsBuildMultipleApks)) {
splits {
abi {
enable true
reset()
include 'x86', 'armeabi-v7a', 'arm64-v8a'
universalApk true
}
}
}
}
// map for the version code that gives each ABI a value
ext.versionCodes = [
'x86':1, 'armeabi-v7a':2, 'arm64-v8a':3
]
// For each APK output variant, override versionCode with a combination of
// ABI APK value * 100 + android.defaultConfig.versionCode
// getAbiFilter() not working for me so I extracted it from getFullname()
if (Boolean.valueOf(tnsBuildMultipleApks)) {
android.applicationVariants.all { variant ->
println(appPackageJson)
println(android.defaultConfig.versionCode)
println(android.defaultConfig.applicationId)
def name
def flavorNamesConcat = ""
variant.productFlavors.each() { flavor ->
flavorNamesConcat += flavor.name
}
flavorNamesConcat = flavorNamesConcat.toLowerCase()
println(flavorNamesConcat)
variant.outputs.each { output ->
if (output.outputFile != null && output.outputFile.name.endsWith('.apk')) {
//You may look for this path in your console to see what the values are
println("******************************************************")
println(output); println(output.getVariantOutputData().getFullName())
def abiName = output.getVariantOutputData().getFullName().toLowerCase().replace(flavorNamesConcat, "").replace(project.ext.selectedBuildType, "")
println(abiName)
def file = output.outputFile
output.versionCodeOverride =
project.ext.versionCodes.get(abiName, 0) * 100
+ android.defaultConfig.versionCode
def apkDirectory = output.packageApplication.outputFile.parentFile
def apkNamePrefix = output.outputFile.name.replace(".apk", "-" + abiName)
if (output.zipAlign) {
name = apkNamePrefix + ".apk"
output.outputFile = new File(apkDirectory, name);
}
name = apkNamePrefix + "-unaligned.apk"
output.packageApplication.outputFile = new File(apkDirectory, name);
}
}
}
}
A:
ABI splits can be useful if you use them one at a time. Here's an example:
android {
...
splits {
abi {
enable true
reset()
include 'armeabi-v7a'
}
}
...
}
The resulting .apk file will only contain the libraries necessary for armeabi-v7a devices, because it's the only architecture mentioned in the ABI splits configuration above. The ABIs available are 'arm64-v8a', 'armeabi-v7a', 'x86' as pointed out in the documentation, so you can't use 'armeabi' or 'mips' architectures.
Furthermore you don't need this line: 'universalApk true', because what it does is ignoring the splits and making one .apk file containing all the provided architectures and you want the opposite.
You can also follow the progress of this issue as it will decrease the .apk size even more.
Hope this helps!
A:
This work so well for me now, both generating apks and tns run android runs fine now, thanks.
// Add your native dependencies here:
// Uncomment to add recyclerview-v7 dependency
//dependencies {
// compile 'com.android.support:recyclerview-v7:+'
//}
import groovy.json.JsonSlurper //used to parse package.json
def tnsBuildMultipleApks=true;
String content = new File("$projectDir/../../app/package.json").getText("UTF-8")
def jsonSlurper = new JsonSlurper()
def appPackageJson = jsonSlurper.parseText(content)
android {
defaultConfig {
generatedDensities = []
applicationId = appPackageJson.nativescript.id
versionCode = appPackageJson.version_code ?: 1
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
if (Boolean.valueOf(tnsBuildMultipleApks)) {
splits {
abi {
enable true
reset()
include 'x86', 'armeabi-v7a', 'arm64-v8a'
universalApk true
}
}
}
}
// map for the version code that gives each ABI a value
ext.versionCodes = [
'x86':1, 'armeabi-v7a':2, 'arm64-v8a':3
]
// For each APK output variant, override versionCode with a combination of
// ABI APK value * 100 + android.defaultConfig.versionCode
// getAbiFilter() not working for me so I extracted it from getFullname()
if (Boolean.valueOf(tnsBuildMultipleApks)) {
android.applicationVariants.all { variant ->
println(appPackageJson)
println(android.defaultConfig.versionCode)
println(android.defaultConfig.applicationId)
def name
def flavorNamesConcat = ""
variant.productFlavors.each() { flavor ->
flavorNamesConcat += flavor.name
}
flavorNamesConcat = flavorNamesConcat.toLowerCase()
println(flavorNamesConcat)
variant.outputs.each { output ->
if (output.outputFile != null && output.outputFile.name.endsWith('.apk')) {
//You may look for this path in your console to see what the values are
println("******************************************************")
println(output); println(output.getVariantOutputData().getFullName())
def abiName = output.getVariantOutputData().getFullName().toLowerCase().replace(flavorNamesConcat, "").replace(project.ext.selectedBuildType, "")
println(abiName)
def file = output.outputFile
def versionCode = project.ext.versionCodes.get(abiName, 0);
output.versionCodeOverride =
project.ext.versionCodes.get(abiName, 0) * 100
+ android.defaultConfig.versionCode
def apkDirectory = output.packageApplication.outputFile.parentFile
println(output.outputFile.name)
def apkNamePrefix = ""
if(versionCode){
apkNamePrefix = output.outputFile.name.replace(".apk", "-" + abiName)
}
else {
apkNamePrefix = output.outputFile.name.replace(".apk", "")
}
if (output.zipAlign) {
name = apkNamePrefix + ".apk"
output.outputFile = new File(apkDirectory, name);
}
name = apkNamePrefix + "-unaligned.apk"
output.packageApplication.outputFile = new File(apkDirectory, name);
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you undo a setkey ordering in data.table?
Lets say I have a data table DT and I change the ordering with set key
setkey(DT,mykey)
Then, maybe I join some things from another table.
DT=DT2[DT]
Is there any way to recover my original row ordering? I know, I can do it by explicitly including an index before I use setkey.
N=Nrow(DT)
DT[,orig_index:=1:N]
setkey(DT,mykey)
DT=DT2[DT]
setkey(DT,orig_index)
DT[,orig_index:=NULL]
Is there a simpler way? If I was doing this with order instead of set key, this would be a little simpler.
o=order(DT$mykey)
uo=order(o)
setkey(DT,mykey)
DT=DT2[DT]
DT=DT[uo,]
It would be kind cool I guess if setkey could be reversed with something like this
setkey(DT,mykey,save.unset=T)
DT=DT2[DT]
unsetkey(DT)
Here save.unset=T would tell data.table to save the last reordering so it can be reversed.
Better yet, maybe
setkey(DT, reorder=F)
DT=DT2[DT]
This option would tell data.table to use the key ordering for joins or whatever without actually changing the order of DT. Not sure if that is possible or natural to implement.
A:
Agreed. This is what we're calling a secondary key and the plan is to add set2key to do exactly that. It is possible to do manual secondary keys now. But that's very similar to what you have in the question. It has come up quite a lot.
FR#1007 Build in secondary keys
and some examples :
https://stackoverflow.com/a/13660454/403310
https://stackoverflow.com/a/13969805/403310
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS LESSphp variable with CSS code block
I would like to add multiple style declaration using lessphp. I have provide the $context array with the lessphp setVariables method.
$context['font'] = 'color: #ffffff; font-family: verdana;';
Then I would like to use it in the less file with the variable name, like this:
.selector{
@font;
}
This doesn't work, what should be the appropriate way of handle this?
A:
There are at least two issues with what you are trying to do based on both LESSphp and LESS syntax:
The array from php needs to be pairs of variable names and values, not property names and values.
LESS does not allow dynamic setting of property names.
So I believe a solution for you is something like this:
PHP
$context = array(
"fontColor" => "#ffffff",
"fontFamily" => "verdana"
);
$less->setVariables($context);
LESS
The above code should generate in the compiled LESS file the equivalent of this:
@fontColor: #ffffff;
@fontFamily: verdana;
Which then you use like this:
.selector {
color: @fontColor;
font-family: @fontFamily;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving $\lim_{x\to-\infty}x^{-k} = 0$
Please prove $\lim_{x\to-\infty}x^{-k} = 0$ for k a natural number using the definition of this limit. I am having problems discovering the proof.
A:
For all $k > 0$ there exists a $p\in\mathbb{N}$ such that $\frac{1}{p} < k$. Then
$$0 < \frac{1}{x^k} = \left(\frac{1}{x}\right)^k < \left(\frac{1}{x}\right)^{1/p}$$
Since $\frac{1}{x}\to 0$ and $f(u) = u^{1/p}$ is continuous at $0$, we have
$$\lim_{x\to -\infty}\left(\frac{1}{x}\right)^{1/p} = \lim_{x\to -\infty}\left(\frac{1}{x}\right)^{1/p} = \lim_{u\to 0}u^{1/p} = 0^{1/p} = 0$$
Therefore
$$\lim_{x\to -\infty}\frac{1}{x^k} = 0 \ \ k > 0$$
| {
"pile_set_name": "StackExchange"
} |
Q:
What Commitizen type should I use for a change that is an improvemant for an existing feature?
Here are the Commitizen types:
What Commitizen type should I use for a change that is an improvement for an existing feature?
CZ resources :
http://commitizen.github.io/cz-cli/
https://github.com/commitizen/cz-cli
A:
This has been discussed on Github. To quote one of the contributors:
In my interpretation, feat could include updates to an existing feature (new features for that feature). We could consider changing its description, if that would help.
From the available options feat makes the most sense to me too.
| {
"pile_set_name": "StackExchange"
} |
Q:
best freeware for doing batch conversion of jpg to png
Which is the best freeware for converting jpg files in different folder to png in a batch process on a windows xp?
A:
while irfanview is officially a viewer, it does a pretty good job at he sort of batch conversions you're talking about
| {
"pile_set_name": "StackExchange"
} |
Q:
PowerPoint Interop order of add picture matters?
I have to automate the creation of a powerpoint presentation.
The master slide which is causing trouble has 2 pictureboxes and some textfields.
I'm adding pictures by getting the shape (the prepared picturebox) with an id and adding the picture at position shape.Left and shape.Right.
Now it gets wierd...
When I do it like this, the pictures are positioned correctly.
var shape = slide.Shapes[ContentFields.Print.WithImage.Bild];
slide.Shapes.AddPicture(artikel.BildPath, MsoTriState.msoFalse, MsoTriState.msoCTrue, shape.Left, shape.Top, shape.Width, shape.Height);
shape = slide.Shapes[ContentFields.Print.WithImage.Kanal];
slide.Shapes.AddPicture(artikel.KanalIconPath, MsoTriState.msoFalse, MsoTriState.msoCTrue, shape.Left, shape.Top, shape.Width, shape.Height);
But when I add the Kanal first, the pictures are mixed up (Kanal is at the position of Bild and Bild at the position of Kanal).
var shape = slide.Shapes[ContentFields.Print.WithImage.Kanal];
slide.Shapes.AddPicture(artikel.KanalIconPath, MsoTriState.msoFalse, MsoTriState.msoCTrue, shape.Left, shape.Top, shape.Width, shape.Height);
shape = slide.Shapes[ContentFields.Print.WithImage.Bild];
slide.Shapes.AddPicture(artikel.BildPath, MsoTriState.msoFalse, MsoTriState.msoCTrue, shape.Left, shape.Top, shape.Width, shape.Height);
Why is this?
I'm getting the correct shape with the Id, how come they get mixed up? :-S
Thanks in advance
A:
In at least some versions of PPT, if you add a picture to a slide that contains an empty Picture or Content placeholder, the picture is added TO the placeholder rather than being placed as a new shape.
With two placeholders on the slide, the first added picture will land in the first placeholder, the second in the second placeholder, so the order in which you add pictures will matter.
Try the same code on a slide with no placeholders; substitute rectangles instead if you need the shapes to determine picture placement.
Or if you need to preserve the placeholders, temporarily add "dummy" text to any empty content placeholders before adding the pictures, then remove the dummy text afterwards.
| {
"pile_set_name": "StackExchange"
} |
Q:
project.compileClasspathElements defaults between Maven 2 and 3
I inherited a Maven project/module that failed when I switched from Maven 2 to Maven 3. It hinges on the execution of an external program that depends on the contents of project/module/target/classpath.txt. This file is generated by a custom plugin that uses ${project.compileClasspathElements}.
In Maven 2 this contained:
project/module/target/classes
[all my dependencies in my local repository]
But in Maven 3, the classpath.txt file only contains:
project/module/target/classes
In other words, the file is missing all the actual dependencies, save for the build directory. Was there a change between Maven 2 and Maven 3 regarding project.compileClasspathElements? How can I get all the dependencies back so that it will work like Maven 2?
[This question was edited to reflect the source of classpath.txt, which I only just discovered.]
A:
Just encountered this issue when migrating a maven 2 plugin that executes during the package phase. Fixed by adding
@requiresDependencyResolution compile+runtime
to the Mojo, e.g.
/**
* blah blah blah
*
* @goal validate-security
* @phase package
* @requiresDependencyResolution compile+runtime
*/
public class SecurityValidationMojo extends AbstractMojo { ... }
From http://maven.apache.org/developers/mojo-api-specification.html
If this annotation is present but no scope is specified, the scope defaults to runtime. If the annotation is not present at all, the mojo must not make any assumptions about the artifacts associated with a Maven project.
| {
"pile_set_name": "StackExchange"
} |
Q:
image buffer for video processing
I want to develope an application with Qt and opencv , in order to process all the frames comming from a camera.
I have 2 Qthread, one for capturing image and the other for processing.
the processing thread is a little slow , so in order to process all the frames , I need to have a frame buffer.
I really have no idea how to simply impelement a frame buffer.
any help would be apprecieted.
A:
You'll want to create your threads to run asynchronously. When you capture the image, add it to a std::queue using the capture thread, and then let your processing thread pull from queue. Try to use pointers as much as you can for the images to cut down on memory use and processing time. Make sure you're thread safe and use std::Mutex when appropriate.
Since you are using QT, you could use QQueue for the queue and QMutex for the mutex.
| {
"pile_set_name": "StackExchange"
} |
Q:
Given $S_{1}=2$ and $S_{n+1}= \frac{S_{n}}{2} + \frac{1}{S_{n}}$. Assume $ S_{n} > 1$, show that $S_{n+1} > 1$
I need help using induction on a recursive sequence.
Given $S_{1}=2$ and $S_{n+1}= \frac{S_{n}}{2} + \frac{1}{S_{n}}$
I am working on the recursive convergence to $\sqrt{2}$, therefore I want to show that it is bounded below by an arbitrary lower bound, in which I chose 1. thus by induction I want to show that $S_{n+1} > 1$,
$$ S_{n} > 1$$ $$\frac{1}{S_{n}} < 1$$ $$S_n +\frac{1}{S_{n}} > ?+1$$
I get stuck here. Im not to sure how to get to my end point of $S_{n+1}$.
A:
$S_n>1$
$S_n-1>0$
$(S_n-1)^2>0$
$S_n^2-2S_n+1>0$
$S_n^2+1>2S_n$
$\frac{S_n}{2}+\frac{1}{2S_n}>1$
$S_n<2S_n$
$\frac{1}{S_n}>\frac{1}{2S_n}$
$\frac{S_n}{2}+\frac{1}{S_n}>\frac{S_n}{2}+\frac{1}{2S_n}>1$
| {
"pile_set_name": "StackExchange"
} |
Q:
Como usar um Spinner em um AlertDialog?
Estou em duvida como colocar um spinner em um AlertDialog, já tenho os códigos prontos, só falta inserir o spinner.
Array:
<string-array name="categoria_array">
<item>Aeroporto</item>
<item>Bar</item>
<item>Casa Noturna</item>
<item>Cinema</item>
<item>Colégio</item>
<item>Loja</item>
<item>Museu</item>
<item>Parque</item>
<item>Restaurante</item>
<item>Rodoviárias</item>
<item>Shoppings</item>
<item>Supermercado</item>
<item>Teatro</item>
<item>Universidade</item>
<item>Outro</item>
</string-array>
Layout:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/titulo"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@color/colorPrimary"
android:gravity="center"
android:text="NOVA LOCALIZAÇÃO"
android:textColor="@color/colorWhite"
android:textSize="20sp"
android:textStyle="bold"
/>
<EditText
android:id="@+id/edt_nome"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="@id/titulo"
android:layout_margin="15dp"
android:background="@drawable/border_transp_black_redond"
android:hint=" Nome do Local"
android:padding="5dp"
android:textColorHint="@color/colorPrimaryText"
android:textSize="20sp"
android:textStyle="italic" />
<EditText
android:id="@+id/edt_endereco"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="@id/edt_nome"
android:layout_margin="15dp"
android:background="@drawable/border_transp_black_redond"
android:hint=" Endereço"
android:padding="5dp"
android:textColorHint="@color/colorPrimaryText"
android:textSize="20sp"
android:textStyle="italic" />
<EditText
android:id="@+id/edt_website"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="@id/edt_endereco"
android:layout_margin="15dp"
android:hint=" WebSite"
android:padding="5dp"
android:inputType="textWebEditText"
android:textStyle="italic"
android:textColorHint="@color/colorPrimaryText"
android:textSize="20sp"
android:background="@drawable/border_transp_black_redond"/>
<EditText
android:id="@+id/edt_telefone"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="@id/edt_website"
android:layout_margin="15dp"
android:hint=" Telefone"
android:padding="5dp"
android:inputType="number"
android:textStyle="italic"
android:textColorHint="@color/colorPrimaryText"
android:textSize="20sp"
android:background="@drawable/border_transp_black_redond"/>
<Spinner
android:id="@+id/spinner_catogorias"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/edt_telefone"/>
</RelativeLayout>
Metodo AlertDialog:
private void chamarDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
builder.setView(inflater.inflate(R.layout.layout_newcheckin, null));
//Dialog dialog = builder.show();
//dialog.dismiss(); fecha o dialog
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cliked OK!", Toast.LENGTH_SHORT);
return;
}
});
builder.show();
}
A:
Necessita de criar um ArrayAdapter que faça a ligação do string-array com o Spinner.
A classe ArrayAdapter tem o método estático createFromResource() que cria um adapter a partir de um string-array.
Atribua o adapter criado ao Spinner usando o método setAdapter().
Altere o método chamarDialog() desta forma:
private void chamarDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
//Cria a view a ser utilizada no dialog
ViewGroup view = (ViewGroup) inflater.inflate(R.layout.layout_newcheckin, null);
//Obtém uma referencia ao Spinner
Spinner spinner = (Spinner) view.findViewById(R.id.spinner_catogorias);
//Cria o Adapter
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.categoria_array,
android.R.layout.simple_spinner_dropdown_item);//ou android.R.layout.simple_spinner_item
//Atribui o adapter ao spinner
spinner.setAdapter(adapter);
builder.setView(view);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cliked OK!", Toast.LENGTH_SHORT);
return;
}
});
builder.show();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to locally quantify the 'sharpness' of an image?
I am trying to quantify how much sharpness (or acutance) is in a picture which has some bokeh (out of focus background).
I am using the Python scikit image for that. Here is my naive approach:
import matplotlib.pyplot as plt
from skimage import data
from skimage.color import rgb2gray
from skimage.morphology import disk
from skimage.filters.rank import gradient
cat = data.chelsea() # cat is a 300-by-451 pixel RGB image
cat_gray = rgb2gray(cat)
selection_element = disk(5) # matrix of n pixels with a disk shape
cat_sharpness = gradient(cat_gray, selection_element)
plt.imshow(cat_sharpness, cmap="viridis")
plt.axis('off')
plt.colorbar()
plt.show()
So here is the picture (notice the background not in focus)
And here is the gradient, which actually measures the difference in contrast:
This difference in contrast problem is more obvious if one uses the Lena image:
Here, the background is caught as well due to the difference in contrast (there is a black frame on the top right)
Any ideas about how to give an scalar value where only the focused areas are highlighted?
A:
The recent works I am aware of make use of tools that go beyond mere gradients. Here are a few references that could be starting points:
S3: A Spectral and Spatial Measure of Local Perceived Sharpness in Natural Images, 2012, with examples of sharpness maps and Matlab code (that could be converted to Python)
This paper presents an algorithm designed to measure the local perceived sharpness in an image. Our method utilizes both spectral and spatial properties
of the image: For each block, we measure the slope of the magnitude
spectrum and the total spatial variation. These measures are then
adjusted to account for visual perception, and then, the adjusted
measures are combined via a weighted geometric mean. The resulting
measure, i.e., S3 (spectral and spatial sharpness), yields a perceived
sharpness map in which greater values denote perceptually sharper
regions
Image sharpness assessment based on local phase coherence, 2013, with examples and (BROKEN yet) code (local copy of the code provided by the authors)
Sharpness is an important determinant in visual assessment of image
quality. The human visual system is able to effortlessly detect blur
and evaluate sharpness of visual images, but the underlying mechanism
is not fully understood. Existing blur/sharpness evaluation algorithms
are mostly based on edge width, local gradient, or energy reduction of
global/local high frequency content. Here we understand the subject
from a different perspective, where sharpness is identified as strong
local phase coherence (LPC) near distinctive image features evaluated
in the complex wavelet transform domain. Previous LPC computation is
restricted to be applied to complex coefficients spread in three
consecutive dyadic scales in the scale-space. Here we propose a
flexible framework that allows for LPC computation in arbitrary
fractional scales.
The given examples and comparisons across different could provide you with some hints toward your goal.
| {
"pile_set_name": "StackExchange"
} |
Q:
MS Access 2016 Dcount dynamic function
I have a textbox on a form on MS Access 2016 which count no.of present employees for current date based on Dcount formula. I want that formula to be dynamic. How to do that?
Textbox function :
=DCount("[2]","Attendance","[2]='P' And [Manager] = '" & [Label10].[Caption] & "' And [Month] = [Combo1] ")
[2] is date of a month. for example if today's date is 05th Oct'18, it would count present for [5] and so on.
Also I want another Dcount function to count present cases for the whole month
Please help me with that.
Thanks in advance !!
A:
Include Date() and correct the syntax:
=DCount("*","Attendance","[2]='P' And [Manager] = '" & [Label10].[Caption] & "' And [Month] = Month(Date())")
However:
[2] is date of a month.
makes no sense when you filter on: [2]='P'
| {
"pile_set_name": "StackExchange"
} |
Q:
IE 8, 9, 10 - YouTube iFrame Error
YouTube iFrame Players created using the iFrame API are now broken in IE 8, 9, 10 - though none of the code has changed on my side. It also seems that the issue exists with other embeds.
This YouTube demo, for example, doesn't work in IE:
https://developers.google.com/youtube/youtube_player_demo
The video plays for a few seconds and then switches to HD and then errors out.
Any solutions would be appreciated.
A:
I had the same problem today. When you listen for the onStateChange event, the event.target YouTube player dispatched to this event used to have an numeric .id for each embed on the page, and that ID seems to have disappeared.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I create an image button in BlackBerry 10 Cascades?
I need to create custom UI elements like buttons and lists with image backgrounds in Cascades Qml, However there doesn't seem to be a way to set the background of controls such as Button.
I can't find any examples of this anywhere.
It seems like this could be possible by using a container and creating a custom control, but I don't see a way of getting that container to have an onClick event.
A:
Custom control is actually very easy in BB10. Here's an example of what you are trying to do:
Container {
property alias text: label.text
property alias image: imagev.imageSource
ImageView {
id: imagev
imageSource: "asset:///images/Button1.png"
}
Label {
id: label
text: "demo"
}
gestureHandlers: [
TapHandler {
onTapped: {
//do tapped code
}
},
LongPressHandler {
onLongPressed: {
//do long press code
}
}
]
}
Save it as "CustomButton.qml" and then in your main QML file you can access it like so:
Page {
CustomButton {
text: "my text"
image: "images/myimage.png"
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Mini GBIC on 2 different brand switches?
I have a 48 port TrendNet Gigabit switch, and a 48 port dlink gigabit switch. Both with Mini GBIC slots. If I purchase a Mini GBIC that is said to be compatible w/ both switches, could I actually "trunk", or connect rather, both switches with it? Or does that not work because they would be 2 different OS's?
A:
It would work, the OS on each switch has nothing to do with the ability of each to talk with each other over the link layer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Doing a SELECT and UPDATE simultaneously IF a condition is met in MySQL
I'm trying to build a checkout system. I have 3 tables, one which holds the products and one which holds the user's cart and one which holds the completed orders.
products
product_id | product_name | stock | unit_price
1 | item1 | 10 | 40
2 | item2 | 5 | 30
3 | item3 | 4 | 29
cart
user_id | product_id | quantity
1 | 1 | 4
1 | 2 | 6
completed orders
user_id | product_id | quantity
1 | 3 | 2
What I'm trying to do is do a SELECT in the PRODUCTS and check if the Stock is greater than the quantity from the user's cart. If this is true, then it decreases the Stock count directly in the MYSQL query.
Now the issue I'm having is, I don't know if this is possible. I can do it in PHP but it will take quite a few iterations, which I want to avoid in case it's not too optimized.
I searched around and I found a partial solution here: MySQL - SELECT then UPDATE
However, I don't know how to include the IF in it.
A:
This can be done in MySQL8 in one query, using a CTE to compute whether all the stock in a cart can be satisfied and then updating products only if it can:
WITH cart_balance_ok AS (
SELECT c.user_id,
MIN(p.stock >= c.quantity) AS cart_ok
FROM cart c
JOIN products p ON p.product_id = c.product_id
GROUP BY c.user_id
)
UPDATE products p
JOIN cart c ON c.product_id = p.product_id
JOIN cart_balance_ok cb ON cb.user_id = c.user_id AND cb.cart_ok = 1
SET p.stock = p.stock - c.quantity
Demo showing no changes because not enough stock here. Demo showing changes to products where there is enough stock here.
You should then be able to use mysqli_affected_rows to determine if the update took place.
| {
"pile_set_name": "StackExchange"
} |
Q:
googlebot and layered navigation
I am having trouble with googlebot crawling through our layered navigation. I get numerous logs like:
GET /shop/dresses?clothing_size=250&color=247&dir=desc&limit=15&mode=list&order=position
GET /shop/dresses?clothing_size=268&color=248&dir=asc&order=name
GET /shop/sale?clothing_size=252&dir=asc&limit=5&mode=grid&order=name&price=50-100
Here is a copy of my robots.txt
User-agent: Googlebot-Image
Disallow: /
Allow: /shop/media/catalog/product/
Allow: /shop/media/wysiwyg/
# Crawlers Setup
User-agent: *
# Directories
Disallow: /shop/404/
Disallow: /shop/app/
Disallow: /shop/cgi-bin/
Disallow: /shop/downloader/
Disallow: /shop/errors/
Disallow: /shop/includes/
#Disallow: /shop/js/
#Disallow: /shop/lib/
Disallow: /shop/magento/
#Disallow: /shop/media/
Disallow: /shop/pkginfo/
Disallow: /shop/report/
Disallow: /shop/scripts/
Disallow: /shop/shell/
Disallow: /shop/skin/
Disallow: /shop/stats/
Disallow: /shop/var/
Disallow: /offline/
# Paths (clean URLs)
Disallow: /shop/index.php/
Disallow: /shop/catalog/product_compare/
Disallow: /shop/catalog/category/view/
Disallow: /shop/catalog/product/view/
Disallow: /shop/catalogsearch/
#Disallow: /shop/checkout/
Disallow: /shop/control/
Disallow: /shop/contacts/
Disallow: /shop/customer/
Disallow: /shop/customize/
Disallow: /shop/newsletter/
Disallow: /shop/poll/
Disallow: /shop/review/
Disallow: /shop/sendfriend/
Disallow: /shop/tag/
Disallow: /shop/wishlist/
Disallow: /shop/catalog/product/gallery/
# Files
Disallow: /cron.php
Disallow: /cron.sh
Disallow: /error_log
Disallow: /install.php
Disallow: /LICENSE.html
Disallow: /LICENSE.txt
Disallow: /LICENSE_AFL.txt
Disallow: /STATUS.txt
Disallow: /.DS_Store
Disallow: /api.php
Disallow: /get.php
Disallow: /mage
# Paths (no clean URLs)
#Disallow: /*.js$
#Disallow: /*.css$
Disallow: /*.php$
Disallow: /*?p=*&
Disallow: /*?SID=
How can I rewrite my robots.txt to block these urls?
A:
robots.txt dont work as expected anymore.
use something simple like in server config:
APACHE:
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (Googlebot|bingbot|Yahoo) [NC]
RewriteCond %{QUERY_STRING} ^clothing_size=([0-9]*) [NC]
RewriteRule .* - [G]
NGINX:
if ($http_user_agent ~* "Baiduspider|Googlebot|bingbot|Yahoo|YandexBot") { set $layered A; }
if ($args ~ ^(clothing_size|color|price)=.+) { set "${layered}B"; }
if ($layered = AB) { return 410; }
this will tell bots this page was gone, remove from index also.
you can extend regex to catch more args and bots.
A:
See solution from here as copy below to fix your issue and prevent bots crawling through your layered navigation
Denying layered navigation for crawlers and fix SEO issues caused by
the huge number of layered navigation URLs can be done by using PRG
Pattern.
This works like a charm, i. e. not changing the UX regarding Layered
Navigation and 100% reliable in terms of preventing crawlers from
wasting crawl budget on useless duplicate content URLs.
Simply said, it's about replacing the GET request to a layered
navigation/filter URL with a POST request (which search engine
crawlers do not follow) before redirecting the user to the original
layered navigation/filter URL.
For further details and reading, please see
Detailed explanation incl. sample request flow
Why robots.txt, rel=nofollow etc. are no satisfying solutions here
PRG Pattern Magento 2 Extension
PRG Pattern Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get sum of linq count results
I have a database with peoples names and ages amongst other things. I have a query which groups by names and gets amount of each name matching the criteria. The ListHelper type is only a class containing the two properties.
IEnumerable<ListHelper> HelperEnumerable = null
HelperEnumerable = _repository.Persons
.Where(b => b.Age < 18)
.GroupBy(
n => n.FirstName
, a => a.FirstName
, (key, count) => new ListHelper { Name = key, Amount = count.Count() }
);
When I ToList() the HelperEnumerable the result is like:
Name: "Michael", Amount: 100,
Name: "Eva", Amount: 122,
Name: "Lisa", Amount: 71,
etc
How can i get a similar result but with count of all persons matching the criteria with a result like this:
Name: "All", Amount: 17280
I would like to have the key value pair so all the rest of the code could stay the same, only this query would return the count of all matchig rows instead of grouped by any particular columm.
I've tried this which returns only the int count:
HelperEnumerable = _repository.Persons
.Where(b => b.Age < 18).Count();
And I can't add a
.Select(a => (key,count) new ListHelper{ key = "All", count = a })
after a Count() to try to project the result to have two fields.
A:
What does:
IEnumerable<ListHelper> HelperEnumerable = null
HelperEnumerable = _repository.Persons
.Where(b => b.Age < 18)
.GroupBy(
n => "All"
, (key, count) => new ListHelper { Name = key, Amount = count.Count() }
);
Not do that you need it to do?
or why not just:
new ListHelper{ key = "All", count = _repository.Persons.Where(b => b.Age < 18).Count() };
??
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot read property 'map' of undefined when update list
I get category-list from server. And also I have button Edit near each category. This open modal with input and submit button. When I click button my category edit and my list must be updated.
But instead update list I have error in Table.js:
Cannot read property 'map' of undefined
it happen because:
that data.data is undefined in ChangeCategory.js after this line:
const data = await response.json();
But how to fix it?
In component home my data come normally.
Maybe it related with method PUT in ChangeCategory.js?
/..... - Code which I delete in question just to have less code in the question.
Also I comment line which iplement update list
Home.js:
const Home = () => {
const [value, setValue] = useState({
listCategory: [],
numberId: "",
isOpened: false
});
useEffect(() => {
async function fetchData(/......) {
const response = await fetch(`/.....`, {/.......});
const data = await response.json();
setValue(prev => ({ ...prev, listCategory: data.data, /...... }));
} fetchData( /..... );
}, [ /..... ]);
const changeId = (argNumberId) => {
setValue({
...value,
numberId: argNumberId,
isOpened: true
});};
const updateList = data => { // METHOD WHICH UPDATE LIST
setValue({
...value,
listCategory: data
})
}
return (
<div>
<Table dataAttribute={value.listCategory} changeId={changeId} valueId={value.numberId} />
{value.isOpened && <ChangeCategory value={value.numberId} updateList={updateList}/>}
</div>);};
ChangeCategory.js:
const ChangeCategory = (props) => {
const { /....... } = useFormik({
initialValues: {
title: '',
},
onSubmit: async (formValues) => {
const response = await fetch(`${apiUrl}/${props.value}`, {
method: PUT, /.......} )
const data = await response.json();
props.updateList(data.data); // CALL FUNCTION updateList
}});
return (
<div>
<form onSubmit={handleSubmit}>
<InputCategory
/........
}}/>
<button type="submit">Edit</button>
</form>
</div>);};
Table.js:
export default (props) => (
<table>
<thead>
<tr>
<th>ID</th>
<th>TITLE</th>
</tr>
</thead>
<tbody>
{props.dataAttribute.map(item => (
<tr key={item.id}>
<td>{item.id} </td>
<td>{item.title} </td>
<td><button onClick={() => props.changeId(item.id)}>Edit</button></td>
</tr>
))}
</tbody>
</table>
);
response from server:
{"data":[{"id":1,"title":"animals"}, {"id":2,"title":"space"}, {"id":3,"title":"sport"}]}
A:
Your .map function runs even before you recieve your data, it can't do so on an undefined or null objects.
You can either:
Have a default prop value that your .map function will run on some default object.
Conditionally check for said prop object value. {props.dataAttribute ? props.dataAttribute.map(...) : null}
I would recomend doing both.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to use a DropDownButton within an IconButton in Flutter?
Update:
@override
Widget build(BuildContext context) {
return new Container(
height: MediaQuery.of(context).size.height,
child: SingleChildScrollView(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
new Container(
height: 220.0,
width: MediaQuery.of(context).size.width,
child: new GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: Column(
children: <Widget>[
SizedBox(height: 40.0),
Row(
children: <Widget>[
Expanded(
child: Stack(
children: [
Center(
child: Text(
'Profile',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Lato',
color: Colors.white,
fontSize: 50.0,
fontWeight: FontWeight.w700,
),
),
),
Positioned(
right: 8,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(padding: EdgeInsets.only(top: 400)),
PopupMenuButton<String>(
icon: Icon(
Icons.settings,
color: Colors.white,
size: 30.0,
),
onSelected: choiceAction,
itemBuilder: (BuildContext context) {
return Constants.choices.map((String choice) {
return PopupMenuItem<String>(
value: choice,
child: Text(choice),
);
}).toList();
},
),
],
),
),
],
),
),
],
),
I am trying to implement a DropDownButton inside the OnPressed command of an IconButton, so that when the icon is pressed, a drop down menu is shown.
Update: I've updated my code with the suggestion made, however the icon does not appear.
I'm not sure if this is a problem with my widget tree.
A:
You can try using showDialog
child: Row(
children: <Widget>[
IconButton(
icon: Icon(
Icons.settings,
color: Colors.black,
size: 30.0,
),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Country List'),
content: new ListView(
children: <Widget>[
new Column(
children: <Widget>[
new DropdownButton<String>(
items: <String>['A', 'B', 'C', 'D', 'E', 'F', 'G'].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (_) {},
),
],
),
],
),
);
});
})
],
)
Updated Answer
Please check this code:
class DropdownMenu extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(padding: EdgeInsets.only(top: 400)),
PopupMenuButton<String>(
icon: Icon(Icons.settings),
onSelected: choiceAction,
itemBuilder: (BuildContext context) {
return Constants.choices.map((String choice) {
return PopupMenuItem<String>(
value: choice,
child: Text(choice),
);
}).toList();
},
),
],
));
}
}
class Constants {
static const String FirstItem = 'First Item';
static const String SecondItem = 'Second Item';
static const String ThirdItem = 'Third Item';
static const List<String> choices = <String>[
FirstItem,
SecondItem,
ThirdItem,
];
}
void choiceAction(String choice) {
if (choice == Constants.FirstItem) {
print('I First Item');
} else if (choice == Constants.SecondItem) {
print('I Second Item');
} else if (choice == Constants.ThirdItem) {
print('I Third Item');
}
}
Note: This is not dropdown menu but i think this is what you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Group_by create aggregated counts conditional on value
I have a data table that looks like this:
serialno state type type2
1 100 FL A C
2 100 CA A D
3 101 CA B D
4 102 GA A C
5 103 WA A C
6 103 PA B C
7 104 CA B D
8 104 CA B C
9 105 NY A D
10 105 NJ B C
I need to create a new data table that is aggregated by serialno but calculates the count of each type of existing variables. So the end result would look like this.
FL CA GA A B C D
100 1 1 2 1 1
101 1 1 1 1
102 1 1
103 1 1 1 1 2
104 2 2 1 1
105 1 1 1 1 1 1
I'm sure there is a solution using some combination of group_by and summarize, but I haven't been able to figure this out. Is the easiest solution just to create first spread out the state, type, and type2 columns and then use summarize to create counts?
A:
Using:
library(reshape2)
recast(dat, serialno ~ value, id.var = 'serialno', fun.aggregate = length)
gives:
serialno A B C CA D FL GA NJ NY PA WA
1 100 2 0 1 1 1 1 0 0 0 0 0
2 101 0 1 0 1 1 0 0 0 0 0 0
3 102 1 0 1 0 0 0 1 0 0 0 0
4 103 1 1 2 0 0 0 0 0 0 1 1
5 104 0 2 1 2 1 0 0 0 0 0 0
6 105 1 1 1 0 1 0 0 1 1 0 0
Or:
library(dplyr)
library(tidyr)
dat %>%
gather(key, val, state:type2) %>%
group_by(serialno, val) %>%
tally() %>%
spread(val, n, fill = 0)
Or:
library(data.table)
dcast(melt(setDT(dat), id = 1), serialno ~ value, fun.aggregate = length)
Or (per @Frank's suggestion):
res <- table(melt(dat, id="serialno")[, c("serialno","value")])
print(res, zero.print="")
Of which the last one results in:
value
serialno A B C CA D FL GA NJ NY PA WA
100 2 1 1 1 1
101 1 1 1
102 1 1 1
103 1 1 2 1 1
104 2 1 2 1
105 1 1 1 1 1 1
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert 16 bit integer to 8 bit without loosing the data values of the 16 bit integer when the range of 16 bit integer is 0-255
int samples = 8;
for (unsigned int i = 0; i < (pow(double(2),samples)-1); i++)
{
unsigned int number = i << 1;
}
I am doing the coding in C++ using Opencv library.
I want to do bitshift through this and this should be in the range of 0-255 but it is crossing the 255 range and going till 508.
IN Matlab the bitshift operator keeps the range between 0-255. The pattern in matlab is 0,2,4...254,1,3,5...255. But in C++ its going 0,2,4,254,256,258...508.
I want the same answer as the matlab. Please suggest me some idea to do that.
A:
In C++, i << 1 is equivalent to i * 2, if i is an unsigned integer.
This is nothing to do with "converting 16bit integer to 8bit". One way to do that is to mask off all the bits except the lower 8: (number & 0xFF) or equivalently (number % 256).
If you multiply by 2 and then do this conversion, you will get 0 after 254. But that is still not what you want. Your target output has 1 added to the second half.
So, to get that you could use:
for (int i = 0; i < 256; i++)
number = (i * 2) % 256 + (i >= 128);
A:
The sequence 0, 2, 4, 6, ..., 252, 254, 1, 3, 5, ..., 253, 255 (which appears to be what you're after based on the sequence you show) can be generated with:
for (int i = 0; i != 257; i = (i == 254) ? 1 : i + 2)
doSomethingWith (i);
There's probably many other ways to generate that sequence as well, including what's probably a more readable dual-loop version, provided you can keep the body of the loops small:
for (int i = 0; i < 256; i += 2) doSomethingWith (i); // 0, 2, 4, 6, ..., 254
for (int i = 1; i < 256; i += 2) doSomethingWith (i); // 1, 3, 5, 7, ..., 255
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular 7 - Service Worker PWA + SSR not working on server
I am struggling to make my Server Side Rendering and Service Worker cooperate on server Side.
Information regarding localhost -> Working
This is working as expected. The service worker works and updates my app on every update. Moreover; a curl localhost:8082 send me back my info.
I start my app with the following command : npm run ssr
"ssr": "npm run build:ssr && npm run serve:ssr",
"build:ssr": "npm run build:client-and-server-bundles",
"serve:ssr": "node dist/server.js",
"build:client-and-server-bundles": "ng build --prod && npm run webpack:server",
"webpack:server": "webpack --config webpack.server.config.js --progress --colors"
Information regarding production: -> Not Working
Website is over HTTPS : https://airdropers.io
Website process is running on a close port and has HAPROXY redirecting traffic from 443 to the port of the webserver
Issue visible on Webserver logs : Could not subscribe to notifications
Error: Service workers are disabled or not supported by this browser
Extra info :
Node js on localhost and production are the same: v9.0.0
I build on production with the following process :
git pull
npm run build:ssr
pm2 start dist/server.js
UPDATE 23/02/2019
I have now a deeper understanding.
My issue is that I start my SSR/PWA server with a node command such as "node dist/server.js".
From my understanding "node dist/server.js" is not working for Service Worker (PWA)
I quote (https://angular.io/guide/service-worker-getting-started)
Because ng serve does not work with service workers, you must use a
separate HTTP server to test your project locally. You can use any
HTTP server. The example below uses the http-server package from npm.
To reduce the possibility of conflicts and avoid serving stale
content, test on a dedicated port and disable caching.
I can not launch is with http-server dist/browser because I will loose the SSR Capability.
How can I start my PWA / SSR Server ?
What command shall I use?
What build shall I do?
UPDATE 24/02/2019
As mentioned by @Gökhan Kurt the service worker is not working properly with my SSR server.
I need SSR for SEO and I need a service worker for Browser Push Notification.
What solution do I have to handle Browser User Push Notification? A third party lib such as One Signals?
Any ideas suggestions are well welcomed to help me make that work.
Thank you for support,
Alex
A:
It is actually not related to your server at all. The problem is, service worker is tried to be registered on the server side, which is not supported. What you can do is make it so that service worker will register on client side.
I haven't tried but this just may work for you. You need to put a separate script in the end of body in index.html to run on browser:
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/ngsw-worker.js');
}
</script>
Be aware that this will only give you the basic caching functionality of service worker and will probably not work for SwPush or SwUpdate. You can check how service worker module works internally here.
Another thing you should know is, service workers are actually not suitable for SSR apps. The generated ngsw.json file will not include all the pages you have. You will have to either modify this file manually or serve it not as a static file but create it dynamically.
And Caching all the pages is not a thing you want to do (unless page contents are static). Because a cached page will always show the same thing since you are not doing an XHR request on client side. For example if your home page is cached for a client, that client will always see the same page regardless of the intended dynamic content.
At this point you should consider why you want SSR and Web APP at the same time. If you need SSR for SEO, you don't need a SW. Just do SSR when the user agent is of a crawler, and serve dynamic angular when the client is a normal user.
How to switch request based on User Agent
This is my thought and I don't know if anyone is doing this. But theoretically, it should work.
Firstly, you will have to build your app to two different directories (DIST_FOLDER/ssr and DIST_FOLDER/csr in my example) with server-side and client-side rendering configurations. You may exclude SW from SSR. You can use SW in CSR as usual.
I found this package that can detect crawler/bot user agents. For express and Angular, you would use it like:
app.get('*', (req, res) => {
var CrawlerDetector = new Crawler(req)
// check the current visitor's useragent
if (CrawlerDetector.isCrawler())
{
// render the index html at server side
res.render(path.join(DIST_FOLDER, 'ssr', 'index.html'), { req });
}
else {
// serve static index.html file built without SSR and let the client render it
res.sendFile(path.join(DIST_FOLDER, 'csr', 'index.html'));
}
});
After implementing this, you can debug your application to see if it works correctly by changing your user agent to one that is written here (i.e. use Postman).
| {
"pile_set_name": "StackExchange"
} |
Q:
555N vs. 555P? One works, the other does not!
I've implemented a water level indicator using a 555 timer. It works fine when I use 555N, but the output is always high when I replace it with 555P. I don't understand.
I have tried four 555Ps to rule out the possibility of a faulty IC, but it still doesn't work. Meanwhile 555N works (I've checked with two ICs).
I googled it and found that there is virtually no difference between them. So, why is this happening?
Link to falstad circuit
Circuit diagram:
This 555N works:
This 555P doesn't work:
A:
In general, when a circuit works with a device from one maker and not from another it is telling you is that your design is incorrectly using some feature of the device on the verge of the design characteristics.
In this case how you are driving the reset pin.
That is a bad thing. You say it works with a 555N, but I am willing to bet if you tested enough 555N samples, only a proportion of them will work. So be glad you tried the other part.
Fix your design so the reset pin gets what it really needs, i.e. a digital level not an analog voltage that hovers somewhere between the logic thresholds as defined in the worst case 555N/555P data-sheet.
You likely need to add a simple comparator circuit, with hysteresis, to do that.
A:
Your design is flakey.
You are using the conductance of water to trip the reset line and this is not a great idea given that the reset pin current (the leakage current from the reset pin) is in the realm of 0.1 mA to 1.5 mA depending on the voltage state of that pin. Read the DS.
So, if it is producing 0.1 mA (ignoring the water sensor effect), this passes through a 10 k resistor to ground and produces a voltage of 1 volt. If the current is twice as high it will produce 2 volts etc..
Given that \$V_{RESET}\$ (i.e. the voltage at which a reset occurs) is typically 0.7 volts, you are in trouble with this design and you need to lower the 10k resistor.
The water sensor can only add voltage to the reset pin so this doesn't help.
Maybe one device inherently produces a lower reset pin leakage current and this happens to work on the NE555N device you have tested. As far as I can tell, you have a bad design and it may work with one chip but it certainly can't be expected to work with different supplier's chips.
Try a redesign and don't think that it must be a good design if it works on chip A.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dijkstra's algorithm with priority queue
In my implementation of Dijkstra's algorithm I have 1 array with all nodes and 1 priority queue with all nodes. Whenever a node is dequeued I update all adjacent nodes with new distance and where it came from, so I can backtrack the path.
The node in the priority queue is updated with new distance and the node in the array is updated where it came from and with new distance. When a node is dequeued the final distance in the array is updated:
PathInfo current = pq.remove();
path[current.pos].distance = current.distance;
Is it acceptable to update both the array with info about previous node and the priority queue with distance?
This happens whenever a better distance is found:
PathInfo key(i, newDistance);
path[i].distance = newDistance;
path[i].previous = current.pos;
pq.decreaseKey(key);
It seems a bit redundant to update my array and priority queue with basically the same info.
I'm currently using a regular array as a data structure in the PQ. Updating the priority is done in linear time and dequeueing is also done in linear time.
What data structure should I use in the priority queue and how should I change a nodes priority?
I'm using C++
A:
You have two kinds of distances here: your priority queue has "tentative distances" which are subject to update, while your array has "final distances", which are not (because Dijkstra's algorithm doesn't need to update nodes that have been removed from the priority queue).
It appears that you are unnecessarily updating the distances in your array. Perhaps it would also be a good idea to change the field name in your array node to document this: from arrayNode.distance to arrayNode.finalDistance.
In other words: it appears you are using your array nodes to output the results from your Dijkstra's algorithm -- so you should only set the distance in each array node once, when it is removed from the priority queue.
If your priority-queue implementation doesn't provide the ability to query the current distance associated with a given key, please check the behavior of its decreaseKey() operation. If the decreaseKey() operation rejects updates for which the new priority does not actually decrease, then you shouldn't need to perform that check yourself -- you can just call it for each neighbor of the current node.
However, if the decreaseKey() function does not handle that case correctly, and there is no auxiliary query function that would let you perform that check manually, and there is no opportunity to fix either deficiency, then you'll need to maintain redundant information for that purpose....
| {
"pile_set_name": "StackExchange"
} |
Q:
VHDL (Xilinx toolchain) I'm being scuppered by "array trimming"
I've got a two-file VHDL project that I'm having beginner's difficulties with.
It takes the system clock and use a 30-bit clock divider (of which I'm only using a small number of non-consecutive bits) to drive a primitive serial port module (outgoing TX only) module to spit out 8 bit characters periodically.
It seems that during the synthesis process, many of the essential signals are being removed by the optimizer, which I didn't expect.
The top level file "Glue.vhd"...
library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;
use ieee.std_logic_unsigned.all;
entity Glue is
port(
clk : in std_logic;
tx : out std_logic;
LED : out std_logic_vector(1 downto 0)
);
end entity Glue;
architecture behavioural of Glue is
signal divider : unsigned(29 downto 0);
begin
LED(1) <= '0';
ser_tx : entity SerialTX
port map (
baud_clk => divider(12),
byte_to_transmit => std_ulogic_vector(divider(29 downto 22)),
poke => divider(20),
busy => LED(0),
serial_out => tx
);
clocker : process(clk)
begin
IF(rising_edge(clk)) then
divider <= divider + 1;
END IF;
end process clocker;
end architecture behavioural;
SerialTX.vhd
library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;
entity SerialTX is
port (
baud_clk : in std_logic;
byte_to_transmit : in std_ulogic_vector(7 downto 0); --the byte that we want to transmit
poke : in std_logic; --a rising edge causes the byte to be sent out
busy : out std_logic; --wait for this to go low before transmiting more data
serial_out : out std_logic --the RS232 serial signal
);
end SerialTX;
architecture behavioural of SerialTX is
signal bit_buf : unsigned(9 downto 0); --(STOP bit) & (8 data bits) & (START bit)
signal internal_busy : std_logic;
shared variable bit_counter : integer range 0 to 10;
begin
busy <= internal_busy;
busy_handler : process(poke) is
begin
if(rising_edge(poke)) then
internal_busy <= '1';
end if;
if(bit_counter = 0) then
internal_busy <= '0';
end if;
end process busy_handler;
do_transmit : process(baud_clk) is
begin
if(rising_edge(baud_clk)) then
if((internal_busy = '1') and (bit_counter = 0)) then
bit_counter := 10;
bit_buf <= unsigned('1' & byte_to_transmit & '0');
end if;
serial_out <= bit_buf(0);
bit_buf <= bit_buf srl 1;
bit_counter := bit_counter - 1;
end if;
end process do_transmit;
end behavioural;
The warnings (no errors mind you) from the synthesis process are as follows...
WARNING:Xst:647 - Input <byte_to_transmit> is never used. This port will be preserved and left unconnected if it belongs to a top-level block or it belongs to a sub-block and the hierarchy of this sub-block is preserved.
WARNING:Xst:1710 - FF/Latch <bit_buf_9> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_8> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_7> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_6> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_5> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_4> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_3> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_2> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_1> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_0> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <serial_out> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:2404 - FFs/Latches <bit_buf<9:0>> (without init value) have a constant value of 0 in block <SerialTX>.
WARNING:Xst:1710 - FF/Latch <serial_out> (without init value) has a constant value of 0 in block <SerialTX>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:2677 - Node <divider_21> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_22> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_23> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_24> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_25> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_26> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_27> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_28> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_29> of sequential type is unconnected in block <Glue>.
WARNING:Route:455 - CLK Net:divider<20> may have excessive skew because 0 CLK pins and 1 NON_CLK pins failed to route using a CLK template.
WARNING:Route:455 - CLK Net:divider<12> may have excessive skew because 0 CLK pins and 1 NON_CLK pins failed to route using a CLK template.
I've traced through the connections in the source code and I cannot find the mistakes that I'm making. I get the feeling that I'm missing some edge/corner cases that I've not covered in the assignments.
The items marked "(without init value)" I have tried to rectify by giving them default values to no avail. The ones marked as "unconnected in block " are bewildering.
What must I do to satisfy the synthesizer?
A:
While user1155120 is right in the sense that you should either specify the library or do component binding, your tools very obviously found the right entity, because that's where your logic is being optimized.
First things first, don't use
use IEEE.numeric_std.all;
use ieee.std_logic_unsigned.all;
together. You should use numeric_std except when working with legacy code.
The real problem is two-fold:
You don't initialize your counter variable and it doesn't count right.
Your input data never makes it into the parallel-load shift register and is therefore trimmed.
At what value would you like your counter to start? IIRC, uninitialized integer types will assume the lowest valid value in their range. However, it's better to make the start explicit in any case. However, in reality there are no integers in FPGAs - just cold, hard flip flops. A range of 0 to 10 uses at least 4 bits and hence 4 flip flops. However, going from 0 to "-1" will underflow and wrap around to 15 instead of the 10 you might expect.
internal_busy is intended to be a flip flop but not initialized either. I say intended, because it's actually asynchronously reset by bit_counter. This asynchronous reset in itself is problematic and almost certainly not what you intended:
busy_handler : process(poke) is -- <-- wrong sensitivity list
begin
if(rising_edge(poke)) then
internal_busy <= '1';
end if;
if(bit_counter = 0) then -- <-- not clocked
internal_busy <= '0';
end if;
end process busy_handler;
You mixed clocked and combinational code. Your simulation will be off, because while the anding of internal_busy will be parallel in hardware, your simulation tool will only show updates on changes of poke.
-- can never happen, because bit_counter = 0 means internal_busy is forced to '0'
if((internal_busy = '1') and (bit_counter = 0)) then
bit_counter := 10;
bit_buf <= unsigned('1' & byte_to_transmit & '0');
end if;
Without this logic, bit_buf will indeed be 9'h000 (a value the Xilinx tools assume -- you didn't give any!). This is what the following lines try to tell you:
WARNING:Xst:1710 - FF/Latch <bit_buf_9> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_8> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_7> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_6> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_5> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_4> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_3> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_2> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_1> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1895 - Due to other FF/Latch trimming, FF/Latch <bit_buf_0> (without init value) has a constant value of 0 in block <ser_tx>. This FF/Latch will be trimmed during the optimization process.
WARNING:Xst:1710 - FF/Latch <serial_out> (without init value) has a constant value of 0 in block <SerialTX>. This FF/Latch will be trimmed during the optimization process.
bit_buf_9 is constantly zero and will be replaced with a hard zero (logic or fabric). Therefore its flip flop is redundant and can be trimmed.
bit_buf_{8..0} were determined to be equivalent to some other flip flop (here: bit_buf_9). However, that flip flop got trimmed, so therefore, these flip flops will be trimmed too.
bit_buf_9 feeds serial_out, so it, too, gets trimmed.
The rest of the error messages:
WARNING:Xst:647 - Input <byte_to_transmit> is never used. This port will be preserved and left unconnected if it belongs to a top-level block or it belongs to a sub-block and the hierarchy of this sub-block is preserved.
WARNING:Xst:2677 - Node <divider_21> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_22> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_23> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_24> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_25> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_26> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_27> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_28> of sequential type is unconnected in block <Glue>.
WARNING:Xst:2677 - Node <divider_29> of sequential type is unconnected in block <Glue>.
byte_to_transmit is unused and not part of a top-level block, it will not be preserved.
divider(29 downto 22) is connected to byte_to_transmit. Since that port will be removed, all flip flip flops following the last used flip flop, divider(20) can be optimized away.
Clock warnings:
WARNING:Route:455 - CLK Net:divider<20> may have excessive skew because 0 CLK pins and 1 NON_CLK pins failed to route using a CLK template.
WARNING:Route:455 - CLK Net:divider<12> may have excessive skew because 0 CLK pins and 1 NON_CLK pins failed to route using a CLK template.
divider(20) and divider(12) are used as clocks.
divider(20) and divider(12) are generated from logic: LUTs and flip flops inside one or more slices. Depending on the FPGA, there are a few that can be fed back to clock routing resources.
In your case, the tools didn't find a way to route these signals on clock routing resources and had to use resources normally reserved for logic signals, hence skew might be excessive.
These clocking errors can be avoided by 1. using a common clock clk for both modules and 2. using poke and baud_clk as clock enables instead:
clk_en_p: process (clk) is
begin
if (rising_edge(clk)) then
if (clk_en = '1') then
my_signal <= assignment;
end if;
end if;
end process clk_en_p;
All in all, you should write a testbench and simulate your design prior to synthesis as Brian Drummond suggested.
It often helps to write parts of a testbench before writing the implementation, because it will force you to think about the interface of your component and how you expect it to react prior to actually writing it.
A:
You can simulate your design, it's on the edge of complexity where it would be easier than guessing why it doesn't work when synthesized and loaded in an FPGA. It can also be made simpler.
It's possible to get rid of bit_counter because you have a 10 bit bit_buf shift register.
The way this would work, is that you set a default pattern that is recognized as 'empty', and that pattern is constructed as a result of shifting bit_buf out.
The pattern doesn't occur other than as an artifact of shifting out with a 'left' shift in of '0'. The shift register shifts '0's in and stops when the stop bit is in the right most position ("0000000001"). The '1' in the right had position maintains the transmit idle mark.
The idea of the idle pattern comes from your use of srl which left fills with '0's, noticed while debugging your original design. The amount of incremental changes while 'learning' why you designed this the way you did became prohibitive. It lead to looking at first principles and describing an implementation based on yours from that.
To simulate your design to begin with there are changes to Glue including an initial value for divide so the increment works, and moving the divider tap-offs for poke and byte_to_transmit, to reduce the simulation time to the neighborhood of 40 ms for the following.
The instantiation of SerialTx uses a selected name, simulators don't include a use work.all; context item implicitly, as is sometimes provided in synthesis tools.
A mark up of your design with an added testbench, without bit_counter:
library ieee;
use ieee.std_logic_1164.all;
-- use ieee.numeric_std.all;
entity SerialTX is
port (
baud_clk: in std_logic;
byte_to_transmit: in std_logic_vector(7 downto 0); -- before -2008
poke: in std_logic;
busy: out std_logic;
serial_out: out std_logic
);
end entity SerialTX;
architecture foo of SerialTX is
-- signal bit_buf: unsigned(9 downto 0);
constant BB_IDLE: std_logic_vector (9 downto 0) := "0000000001";
signal bit_buf: std_logic_vector (9 downto 0) := BB_IDLE;
-- signal internal_busy: std_logic;
signal poke_reg: std_logic_vector (0 to 2) := "000";
signal start_tx: std_logic;
-- shared variable bit_counter: integer range 0 to 10;
begin
-- busy <= internal_busy;
poke_filt:
process (baud_clk) -- translate poke to baud_clk domain
begin
if rising_edge (baud_clk) then
poke_reg <= poke & poke_reg (0 to 1);
end if;
end process;
-- front edge of poke in baud_clk_domain:
start_tx <= poke_reg(0) and poke_reg(1) and not poke_reg(2);
-- busy_handler:
-- process (poke) is
-- begin
-- if rising_edge (poke) then
-- internal_busy <= '1';
-- end if;
-- if bit_counter = 0 then
-- internal_busy <= '0';
-- end if;
-- end process busy_handler;
busy_handler:
process (baud_clk)
begin
if rising_edge (baud_clk) then
if start_tx = '1' and bit_buf = BB_IDLE then
busy <= '1';
elsif bit_buf = BB_IDLE then
busy <= '0';
end if;
end if;
end process;
do_transmit:
process (baud_clk)
begin
if rising_edge(baud_clk) then
if start_tx = '1' and bit_buf = BB_IDLE then
bit_buf <= '1' & byte_to_transmit & '0';
elsif bit_buf /= BB_IDLE then
-- bit_buf <= bit_buf srl 1;
-- srl UNDEFINED in package std_logic_1164
bit_buf <= '0' & bit_buf(9 downto 1); -- shift right one
end if; -- zero fill
end if;
end process;
-- do_transmit:
-- process (baud_clk)
-- begin
-- if rising_edge(baud_clk) then
-- if internal_busy = '1' and bit_counter = 0 then
-- bit_counter := 10;
-- bit_buf <= unsigned ('1' & byte_to_transmit & '0');
-- end if;
-- serial_out <= bit_buf(0);
-- bit_buf <= bit_buf srl 1;
-- bit_counter := bit_counter - 1;
-- end if;
-- end process do_transmit;
serial_out <= bit_buf(0); -- ADDED, no 11th flip flop
end architecture;
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
-- use ieee.std_logic_unsigned.all;
entity Glue is
port (
clk: in std_logic;
tx: out std_logic;
LED: out std_logic_vector(1 downto 0)
);
end entity Glue;
architecture behavioural of Glue is
signal divider: unsigned(29 downto 0) := (others => '0'); -- init val
begin
LED(1) <= '0';
ser_tx:
entity work.SerialTX -- ADDED work prefix to make selected name
port map (
baud_clk => divider(12),
-- byte_to_transmit => std_ulogic_vector(divider(29 downto 22)),
byte_to_transmit => std_logic_vector(divider(25 downto 18)),
poke => divider(17), -- WAS divider(20), for simulation
busy => LED(0),
serial_out => tx
);
clocker:
process (clk)
begin
if rising_edge(clk) then
divider <= divider + 1;
end if;
end process clocker;
end architecture behavioural;
library ieee;
use ieee.std_logic_1164.all;
entity glue_tb is
end entity;
architecture fum of glue_tb is
signal clk: std_logic := '0';
signal tx: std_logic;
signal led: std_logic_vector(1 downto 0);
begin
DUT:
entity work.glue
port map (
clk => clk,
tx => tx,
led => led
);
CLOCK:
process
begin
wait for 10 ns;
clk <= not clk;
if now > 40 ms then
wait;
end if;
end process;
end architecture;
Running for 40 ms gives:
A close up of byte_to_transmit value 05:
You could note srl is not provided in package std_logic_1164, and has been replaced as has the use of std_ulogic_vector, std_logic_vector became it's subtype in -2008.
poke is filtered into the baud_clk domain and generates an single clock period event the sets internal_busy to '1', which is subsequently set to '0' when the idle pattern is again detected in bit_buf.
Note busy is '1' for 10 clocks (start bit, 8 data bits, and stop bit) and the 11th flip flop for serial_out has been dropped.
This was simulated using ghdl, binaries can be downloaded here. The waveform displays are from gtkwave. Both are licensed under the GPL.
VHDL has a specific set of language constructs for inferring sequential logic - memories, registers and latches, part of a subset of the language useful in synthesis. A superset or subset of eligible VHDL is typically supported by a synthesis vendor who might also include restrictions based on their target platform silicon. Eligibility and supported constructs are found in synthesis vendor documentation. The VHDL language itself is defined in IEEE Std 1076-2008, although universal support is only found for the -1993 or -2002 revision.
One of the things you'll find is that shared variables have become protected types with access through methods, insuring exclusive access to shared resources and incidentally becoming ineligible for synthesis.
Am I right in thinking that your 3-bit poke_reg system means that the poke high pulse duration must be longer than 3 baud_clk edges in order to be correctly detected? Is it possible to make the poke signal edge-triggered? – Wossname 13 hours ago
scary_jeff 's method will work for poke (send) events shorter than or equal to three baud_clk intervals.
You don't use busy (internal_busy) in SerialTx and it only covers the interval of baud_clk periods (bauds) during actual transmission.
It's possible to create a busy signal that is safe (the xor of two flip flops) and works for the entire interval between the rising edge of poke (send) and the end of internal_busy:
architecture fum of SerialTX is
constant BB_IDLE: std_logic_vector (9 downto 0) := "0000000001";
signal bit_buf: std_logic_vector (9 downto 0) := BB_IDLE;
signal poke_event: std_logic := '0'; -- Added
signal internal_busy: std_logic := '0'; -- Re-Added
signal poke_reg: std_logic_vector (0 to 1) := "00";
signal start_tx: std_logic;
signal end_event: std_logic := '0'; -- Added
begin
busy <= poke_event xor end_event; -- ADDED, was FF output
pokeevent:
process (poke)
begin
if rising_edge(poke) then
poke_event <= not poke_event;
end if;
end process;
poke_edge:
process (baud_clk) -- translate poke to baud_clk domain
begin
if rising_edge (baud_clk) then
poke_reg <= poke_event & poke_reg (0);
end if;
end process;
-- front edge of poke in baud_clk_domain:
start_tx <= poke_reg(0) xor poke_reg(1); -- CHANGED, when not equal
endevent:
process (baud_clk)
begin
if rising_edge (baud_clk) then
if internal_busy = '1' and bit_buf = BB_IDLE then
end_event <= not end_event;
end if;
end if;
end process;
busy_handler: -- CHANGED
process (baud_clk)
begin
if rising_edge (baud_clk) then
if start_tx = '1' and bit_buf = BB_IDLE then
internal_busy <= '1';
elsif bit_buf = BB_IDLE then
internal_busy <= '0';
end if;
end if;
end process;
do_transmit:
process (baud_clk)
begin
if rising_edge(baud_clk) then
if start_tx = '1' and bit_buf = BB_IDLE then
bit_buf <= '1' & byte_to_transmit & '0';
elsif bit_buf /= BB_IDLE then
bit_buf <= '0' & bit_buf(9 downto 1);
end if;
end if;
end process;
serial_out <= bit_buf(0);
end architecture;
This gives:
Note that the internal_busy signal is used to determine when the back edge of busy occurs (distinguishing between the idle pattern in bit_buf when transmitting or not).
The poke signal has been shortened by modifying Glue to prove the width of poke (send) can be arbitrary:
architecture behavioural of Glue is
signal divider: unsigned(29 downto 0) := (others => '0'); -- init val
signal poke: std_logic := '0'; -- ADDED
begin
LED(1) <= '0';
poke <= divider(17), '0' after 10 us; -- ADDED
ser_tx:
entity work.SerialTX -- ADDED work prefix to make selected name
port map (
baud_clk => divider(12),
-- byte_to_transmit => std_ulogic_vector(divider(29 downto 22)),
byte_to_transmit => std_logic_vector(divider(25 downto 18)),-- sim
poke => poke, -- WAS divider(20), for simulation
busy => LED(0),
serial_out => tx
);
(No, that complex waveform representing a singleshot on the new signal poke is not synthesis eligible.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does the NativeScript CLI command 'tns devices' just hang?
e.g.
tns devices android
Gives me:
C:\Users\Matthew>tns devices android
Connected devices & emulators
Searching for devices...
[hangs here till I Ctrl+C]
Cannot find connected devices. Reconnect any connected devices, verify that your system recognizes them, and run this command again.
Terminate batch job (Y/N)?
My device is visible in windows, a HTC One M9, and the drivers for it are installed. The device is in 'dev' mode and the USB debugging is switching on, and shows up as a warning notication.
SideKick shows no connected devices either. Although I suspect it's using the same back end that the tns command uses.
'tns doctor' says everything is good. I can build apps locally.
A:
I had a number of active adb.exe processes. And it seems they were in a bad state somehow. Closing any one of them didn't result in progress but if I closed the whole process tree with Process Explorer then:
adb devices
Would actually list without hanging.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change config file by puppet - depend hostname
I want to push some config file to my all servers by puppet. File is almost the same for all servers, but there is one change - hostname.
I've created module in puppet with manifest and temp-conf-file. I include to all node. All is fine.
My question is: how can i push that file to all server with change one/two lines in that file. But i don't want to set config file in modules for all. I want to use one file and during the push change in side two lines.
Thank you for help.
Best,
Rafal
A:
I would use a template. Set your file resource to use content instead of source:
content => template("mymodule/temp-conf-file.erb"),
Then have the template substitute the hostname. The template would be located in the templates subdirectory of your module:
# This file is managed by puppet
... random config stuff ...
hostname = <%= hostname %>
You can also use fqdn or something else.
Official documentation: https://puppet.com/docs/puppet/latest/lang_template.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Codeigniter $this->lang->line(errors) without paragraph tags for tank auth error messages
I'm wondering if someone can help me with this. I am currently trying to integrate tank auth into my codeigniter site. I am slowly getting there but have run into a minor stumbling block in that when I have moved the error messages from being displayed as part of an html view to a javascript alert they are still printing out the paragraph tags around the error message.
The error messages which are passed to my login form as an array/ or multidimensional array I think are produced in the controller by the following lines of code:
$data['errors'] = array();
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
Here is my code for displaying the error messages:
if ((isset($errors[$login['name']]))||(isset($errors[$password['name']]))||(form_error($login['name']))||(form_error($password['name']))){
echo'<script type="text/javascript">alert("';
}
echo form_error($login['name']);
echo isset($errors[$login['name']])?$errors[$login['name']]:'';
echo form_error($password['name']);
echo isset($errors[$password['name']])?$errors[$password['name']]:'';
if ((isset($errors[$login['name']]))||(isset($errors[$password['name']]))||(form_error($login['name']))||(form_error($password['name']))){
echo'")</script>';
}
Now my primary question here is how to remove the paragreaph tags ande I have found a clue here in the codeigniter documentation:
http://codeigniter.com/user_guide/libraries/file_uploading.html
They key part here is that It says you can set the delimeters for the errors on the upload script by doing this:
$this->upload->display_errors('<p>', '</p>');
But I have no idea how and where to apply this to tank auth.
I also have a second question which I would be grateful to anyone who can answer, I am slightly confused by the code for displaying the error messages. For example:
echo form_error($password['name'])
can someone explain this to me, it has no $ at the beginning so is not a variable so whats it all about, and the thing I am really trying to get to is how to simplify my logic in checking for the error messages, since it is incredibly long winded at the moment and there are a lot of error messages to handle.
I appreciate there is a lot to deal with here but any help/explainations will be gratefully recieved.
A:
To remove the tags wrapping the error message, you'll have to call the set_error_delimiters() method of the Form Validation object with 2 empty strings as the parameters.
$this->form_validation->set_error_delimiters('', '');
More on this: https://codeigniter.com/user_guide/libraries/form_validation.html#changing-the-error-delimiters
As for your second question, I'm not sure what you're asking actually. It's only a function call where the returned value of the call will be outputted to the user.
| {
"pile_set_name": "StackExchange"
} |
Q:
ramification of prime in Normal closure
Let $K$ be an algebraic number field and let $p$ be a prime in $\mathbb{Q}$ such that $p$ ramifies in $L$, the Galois closure of $K$. How can I show that $p$ ramifies in $K$ itself?
A:
Important fact: If $K, K'$ are extensions of $\mathbb Q$, and $p$ is a prime which is unramified in both $K$ and $K'$, then $p$ is unramified in the compositum $K\cdot K'$.
One can prove this, for example, by considering the inertia group $I$ of the Galois closure $L$ of $K\cdot K'$: if $K, K'\subset L^I$, then $K\cdot K'\subset L^I$.
We can use this in the following way: let $K = \mathbb Q(\alpha)$, and let $\alpha_2,\ldots,\alpha_n$ be the Galois conjugates of $\alpha$. Then for each $i$, $$\mathbb Q(\alpha)\cong\mathbb Q(\alpha_i),$$so in particular, $p$ is unramified in $\mathbb Q(\alpha)$ if and only if it is unramified in $\mathbb Q(\alpha_i)$ for each $i$.
But the Galois closure
$$L=\mathbb Q(\alpha)\cdot\mathbb Q(\alpha_2)\cdot\ldots\cdot\mathbb Q(\alpha_n),$$
so if $p$ ramifies in $L$, it cannot be unramified in $K$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to solve run time error '9' subscript out of range?
I have three columns in my Excel worksheet - Reference, Value and Date. The code goes through all given values and works perfectly but at the end I have run time error at pReference = data_table2(i + 1, 1).
Set Sheet_data = ThisWorkbook.Worksheets("Setup")
last_Row = Sheet_data.Range("A1").CurrentRegion.Rows.Count
Set data_table = Sheet_data.Range("A2:C" & last_Row)
data_table2 = data_table.Value2
' New Code for Excel Export
For i = 1 To (last_Row - 1)
If isDeveloper() = True Then
pReference = data_table2(i + 1, 1)
pValue = data_table2(i + 1, 2)
pdate = data_table2(i + 1, 3)
End If
A:
Take a look at the values of last_Row.
If you have a region of values for eg. A1:C22, the last_row will be 23, but you assigning to data_table Range("A2:C" & last_row) so you are starting from the second row.
it will be always subscript out of range error on the end, coz on the last itteration assign i = 23, and the array len is 22, so you are out of range
change your for loop to for each loop, or do this this way
For i = 1 to UBound(data_table2)
If isDeveloper() = True Then
pReference = data_table2(i, 1)
pValue = data_table2(i, 2)
pdate = data_table2(i, 3)
End If
| {
"pile_set_name": "StackExchange"
} |
Q:
What factors affect the maximum air pressure that should be put in a vehicle's tires?
For just about every car, there's at least two different "maximum tire pressure" ratings.
The vehicle manufacturer's rating. This is usually found on a sticker attached to the driver's door.
The tire manufacturer's rating. This is usually found on the side-wall of each tire.
Given this, I've actually got two questions here. I'm fairly certain I know the answer to the first, but would rather the answerers here respond to confirm. The second is really the meat of things, though.
Which rating should be followed when filling one's tires? Should you use the vehicle's rating, the tire's rating, the lesser/greater of the two, or somewhere in between?
What variables can affect the maximum pressure rating that should be used for the tires? Could some major vehicle modifications, such as drivetrain or suspension changes, make the true "best" fill level deviate from one or both of the manufacturers' ratings?
EDIT: For specificity's sake, I added the safety tag. I'd like this issue more addressed from a safety/vehicle health standpoint, than a racing/performance perspective.
A:
Bit of background: you can run your tires at various pressures, either under or over the recommendations. Over inflating the tires leads to overwear down the middle of the tire but a nice rigid tire - which is great for track days, smooth roads etc. Under inflating wears the outside edges more, and weakens the sidewalls meaning the tire can move about more - which is good on bumpy roads as they soak up bumps.
The tire manufacturer rating is usually a recommended 'do not exceed' from the manufacturer in order to avoid tire wear.
The vehicle rating is based on the weight of the car and the handling characteristics (including the suspension travel) so is more around handling/comfort.
As an example, my vehicle recommendation is 32psi on the rears and 34 at the front, but I use 36 at the rear and 38 at the front as I prefer the handling characteristics - it points more on corners and is slightly more prone to oversteer. I still keep it under the tire manufacturer recommendation, which on these ones is 44psi unless I'm on a track racing - then I crank em all up to 44/46. Those pressures on the road make it very skittish and uncomfortable.
(caveat - it is a performance car, and I err more on the side of precise control and less on comfort)
Update based on @Iszi's safety request:
If you are within the tire rating you keep the tire safe and reduce the risk of damage. As you raise the pressure, you make the tire harder and increase the pressure on the sidewalls which could be more likely to blow out in the event of hitting the tire off a kerb or pothole. Also, a higher pressure tire will place more load on the shocks/dampers/mounting brackets as it won't absorb so much of the impact from road bumps, so you can expect a shorter life for your shocks.
Realistically, unless you are pushing the performance, I wouldn't expect this to make a dramatic difference to safety or wear and tear. Keep pressures somewhere below the two maxima.
| {
"pile_set_name": "StackExchange"
} |
Q:
Watir Error: unable to locate element
I am writing a web scraper with Watir and I can't seem to figure out this error I'm getting. I have an array of text for links on a certain page, but when I loop through it and click on the link and then go back, it breaks.
Here is the HTML code
<div>
<a href="wherever">Text here</a>
</div>
<div>
<a href="wherever">Text here 2</a>
</div>
<div>
<a href="wherever">Text here 3</a>
</div>
And here is my Watir code
browser = Watir::Browser.new
browser.goto 'some_valid_site.com'
array = ['Text here', 'Text here 2', 'Text here 3']
array.each do |text|
browser.link(:text, text).click
browser.back
end
It executes the first link correctly, but when it comes to the second link, I get the following error message:
ruby-2.2.2@gemset/gems/watir-webdriver-0.8.0/lib/watir-webdriver/elements/element.rb:533:
in `assert_element_found': unable to locate element,
using {:element=>#<Selenium::WebDriver::Element:0x1bef61e9aef3c36a
id="{ad42ba23-8037-a745-8fd7-21955ab49406}">}
(Watir::Exception::UnknownObjectException)
I am pretty new to this so any advice would be much appreciated. Thanks!
A:
Watir has a wait_until_present method:
browser = Watir::Browser.new
browser.goto 'some_valid_site.com'
array = ['Text here', 'Text here 2', 'Text here 3']
array.each do |text|
browser.link(:text, text).wait_until_present
browser.link(:text, text).click
browser.back
end
default wait time is 30 seconds which should be way more than enough. If the page isn't reloading on back you might need to use the explicit URL.
| {
"pile_set_name": "StackExchange"
} |
Q:
Space appears between a table element and the overflow scrollbar
So I've been trying to make a table that contains information that has the main title/header cells to stick to the top when scrolling but in the middle of making it, I made a containing div element around the whole table to allow a set height and overflow properties. But when the preview loaded it showed a gap between the table itself and the scrollbar. So I tried to do some research and found that I could keep all the properties in the table css section by putting it into display:block , but even after I did that the same space that was show before was still apparent except it shoved the content to the side. I do not want any help regarding the sticky header, since I want to do that myself but any help with the scroll bar would be super helpful!
Also, not related to the question, I want to know if there is any way to change the scrollbar into something else besides the default browser scrollbar.
Codepen: http://codepen.io/PorototypeX/pen/iKJAq
CSS
div.table_edit {
height: 300px;
overflow-y: scroll;
overflow-x: hidden;
display: inline-block;
}
table {
text-align: center;
width: 1210px;
background: #BABABA;
padding: 0;
border-collapse: collapse;
}
th {
margin: 0;
width: calc(1210px / 6);
border: none;
padding: 15px;
}
#header_row {
background: #636363;
}
th.titleone {
background: #292929;
}
td {
padding: 15px;
width: calc(1210px / 6);
}
td.namebar {
background: #404040;
font-weight: bold;
}
tr.alternating_color {
background: #9C9C9C;
}
tr:hover {
background: #808080;
}
tr.a:ternating_color:hover {
background: #808080;
}
A:
I'd suggest making .table_edit an inline-block element; which will cause the dimensions of the element to be determined by its containing elements (which is ideally what you want). You would also need to add text-align:center to the parent element, in this case I added it to the body element.
UPDATED EXAMPLE
div.table_edit {
height: 300px;
overflow-x: hidden;
overflow-y: auto;
display: inline-block;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Dragging a widget down a long list so that scrolling is necessary with gwt-dnd
I'm investigating using gwt-dnd to implement drag-and-drop reordering of a list of widgets. The list might be longer than its visible area, and so I'd like the user to be able to do that drag-the-widget-near-the-bottom-and-the-list-auto-scrolls behavior that's pretty much standard.
Does gwt-dnd have this support built in anywhere? If not, any ideas on implementing it?
A:
As it turns out, gwt-dnd has support for this automatically. It requires that the dropArea be inside an AbsolutePanel dragBoundary, and that the dragBoundary is within a scroll panel.
| {
"pile_set_name": "StackExchange"
} |
Q:
Supposed automatically threaded scipy and numpy functions aren't making use of multiple cores
I am running Mac OS X 10.6.8 and am using the Enthought Python Distribution. I want for numpy functions to take advantage of both my cores. I am having a problem similar to that of this post: multithreaded blas in python/numpy but after following through the steps of that poster, I still have the same problem. Here is my numpy.show_config():
lapack_opt_info:
libraries = ['mkl_lapack95_lp64', 'mkl_intel_lp64', 'mkl_intel_thread', 'mkl_core', 'mkl_mc', 'mkl_mc3', 'pthread']
library_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/lib']
define_macros = [('SCIPY_MKL_H', None)]
include_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/include']
blas_opt_info:
libraries = ['mkl_intel_lp64', 'mkl_intel_thread', 'mkl_core', 'mkl_mc', 'mkl_mc3', 'pthread']
library_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/lib']
define_macros = [('SCIPY_MKL_H', None)]
include_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/include']
lapack_mkl_info:
libraries = ['mkl_lapack95_lp64', 'mkl_intel_lp64', 'mkl_intel_thread', 'mkl_core', 'mkl_mc', 'mkl_mc3', 'pthread']
library_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/lib']
define_macros = [('SCIPY_MKL_H', None)]
include_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/include']
blas_mkl_info:
libraries = ['mkl_intel_lp64', 'mkl_intel_thread', 'mkl_core', 'mkl_mc', 'mkl_mc3', 'pthread']
library_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/lib']
define_macros = [('SCIPY_MKL_H', None)]
include_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/include']
mkl_info:
libraries = ['mkl_intel_lp64', 'mkl_intel_thread', 'mkl_core', 'mkl_mc', 'mkl_mc3', 'pthread']
library_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/lib']
define_macros = [('SCIPY_MKL_H', None)]
include_dirs = ['/Library/Frameworks/EPD64.framework/Versions/1.4.2/include']
As in the original post's comments, I deleted the line that set the variable MKL_NUM_THREADS=1. But even then the numpy and scipy functions that should take advantage of multi-threading are only using one of my cores at a time. Is there something else I should change?
Edit: To clarify, I am trying to get one single calculation such as numpy.dot() to use multi-threading on its own as per the MKL implementation, I am not trying to take advantage of the fact that numpy calculations release control of the GIL, hence making multi-threading with other functions easier.
Here is a small script that should make use of multi-threading but does not on my machine:
import numpy as np
a = np.random.randn(1000, 10000)
b = np.random.randn(10000, 1000)
np.dot(a, b) #this line should be multi-threaded
A:
This article seems to imply that numpy intelligently makes certain operations parallel, depending on predicted speedup of the operation:
"If your numpy/scipy is compiled using one of these, then dot() will be computed in parallel (if this is faster) without you doing anything. "
Perhaps your small(-ish) test case won't show significant speedup according to numpy's heuristic for determining when to parallelize a particular dot() call? Maybe try a ridiculously large operation and see if both cores are utilized?
As a side note, does your processor/machine configuration actually support BLAS?
| {
"pile_set_name": "StackExchange"
} |
Q:
The code first development using the EF many-to-many how to bind data to repeater?
BlogPost and Category-many relationship, if the dataset directly bind repeater, now how to use code first developed to bind repeater?
public class BlogPost
{
public int BolgID
{
get;
set;
}
public int ID
{
get;
set;
}
public string Title
{
get;
set;
}
public virtual ICollection<Category> Category
{
get;
set;
}
}
public class Category
{
public int ID
{
get;
set;
}
public string Title
{
get;
set;
}
public virtual ICollection<BlogPost> BlogPost
{
get;
set;
}
}
using(MyDemoContext context = new MyDemoContext())
{
DbSet<BlogPost> post = context.Set<BlogPost>();
var v = post.Include(p=>p.Category).Where(p=>p.ID==5).ToList();
Repeater1.DataSource = v;
Repeater1.DataBind();
}
BlogID
BlogTitle
CategoryTitle//Category's title
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ID")%></td>
<td><%# Eval("Title")%></td>
<td><%# Eval("")%></td>//here how to bind Category.Ttitle?
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
How to get this result:
BlogID BlogTitle CategoryTitle
5 test C#
5 test asp.net
5 test VB
A:
Catgory and BlogPost has many to many relation, so on blog post will have multiple categories. I am not sure which category title you want to show here - typically, I would probably show a comma separated list (or perhaps a bulleted list), this can be achieve by nesting a repeater. For example,
<ItemTemplate>
<tr>
<td><%# Eval("ID")%></td>
<td><%# Eval("Title")%></td>
<td>
<asp:Repeater runat="server" ID="C" DataSource='<%# Eval("Category") %>'>
<ItemTemplate><%# Eval("Title") #></ItemTemplate>
<SeparatorTemplate>, </SeparatorTemplate>
</asp:Repeater>
</td>
</tr>
</ItemTemplate>
Diclaimer: untested code
Noe above template will generate comma seperated list but you can adjust layout as per your need.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Add an event in Google Calendar from Activity?
I tried using content providers, but the event was not added to the calendar.
final ContentResolver cr = ctx.getContentResolver();
ContentValues cv = new ContentValues();
cv.put("calendar_id", l_calId);
cv.put("title", title);
cv.put("description", description);
cv.put("dtstart", millis1 );
cv.put("hasAlarm", 1);
cv.put("dtend", millis2);
cv.put("eventLocation", "Hall: "+location);
cv.put("transparency", 1);
cv.put("hasAlarm", 1);
Uri newEvent ;
if (Integer.parseInt(Build.VERSION.SDK) == 8 )
newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);
else
newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);
A:
Assuming you want to add an event to your users' calendar, the (unsupported) way of doing it on Android 2.x is described here.
As of Android 4.0, the practice changed while breaking support for the unsupported way as documented here. This was replaced by an official API working on ICS and onwards which is documented here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Connect Samsung e250 and computer over USB
I have developed two applications: first works on Samsung e250, second works on computer. I need to implement their communication through the USB port. How I can do it? Where I can I find a good manual about this?
A:
Preamble: I'm not sure that Samsung E250 is Symbian based, but because this topic is marked with symbian tag, here's my answer.
You should use serial port for communications over USB. When your Symbian-based phone is attached to a PC via USB cable in PC Suite mode, virtual COM port is allocated on both sides of connection. In order to use it, refer to http://wiki.forum.nokia.com/index.php/TSS000601_-_Serial_communication_over_USB_on_S60_3rd_Edition_devices
| {
"pile_set_name": "StackExchange"
} |
Q:
complexity of iterative squaring in relation to factorization
I've run into a question dealing with the number of
modular multiplications of O(n) bit numbers in the following situation:
Given two n bit primes p,q define m=pq. Choose some 'a' so that $2<a<m\hspace{-0.04 in}-\hspace{-0.04 in}2$
and look at a^(2^t) for some integer t. This is done using iterated squaring.
The question asks about the number of modular multiplications needed for the
case of not knowing the factorization of m and the case of knowing the factorization.
The question hints at using t and n to quantify things.
Me question is, what does the factorization of m have to do with this?
The trick in integrated squaring is using the 'on bits' of a b (call them bi for i: 0 -> n) to calculate a^b by multiplying all (a^(2^i))^bi. I don't quite understand where this question is headed.
Could anyone shed a little light on things?
A:
Let $m = pq$. Computing $A := a^{2^t} \pmod m$ requires $t$ $2n$-bit modular multiplications.
Now if you know the factorization of $m$ (i.e., $p$ and $q$) then you can evaluate $A = a^{2^t} \pmod m$ from $A_p := a^{2^t} \pmod p$ and $A_q := a^{2^t} \pmod q$ using Chinese remaindering:
$$
A = A_p + p\bigl[i_p (A_q-A_p) \bmod q\bigr]\quad\text{where $i_p = p^{-1} \bmod q$}
$$
The computation of $A_p$ (resp. of $A_q$) requires $t$ $n$-bit modular multiplications. Assuming that $i_p$ is pre-computed, the computation of $A$ thus requires $(2t+1)$ $n$-bit modular multiplications.
| {
"pile_set_name": "StackExchange"
} |
Q:
ggplot2 - Multi-group histogram with in-group proportions rather than frequency
I have three cohorts of students identified by an ExperimentCohort factor. For each student, I have a LetterGrade, also a factor. I'd like to plot a histogram-like bar graph of LetterGrade for each ExperimentCohort. Using
ggplot(df, alpha = 0.2,
aes(x = LetterGrade, group = ExperimentCohort, fill = ExperimentCohort))
+ geom_bar(position = "dodge")
gets me very close, but the three ExperimentCohorts don't have the same number of students. To compare these on a more even field, I'd like the y-axis to be the in-cohort proportion of each letter-grade. So far, short of calculating this proportion and putting it in a separate dataframe before plotting, I have not been able to find a way to do this.
Every solution to a similar question on SO and elsewhere involves aes(y = ..count../sum(..count..)), but sum(..count..) is executed across the whole dataframe rather than within each cohort. Anyone got a suggestion? Here's code to create an example dataframe:
df <- data.frame(ID = 1:60,
LetterGrade = sample(c("A", "B", "C", "D", "E", "F"), 60, replace = T),
ExperimentCohort = sample(c("One", "Two", "Three"), 60, replace = T))
Thanks.
A:
Wrong solution
You can use stat_bin() and y=..density.. to get percentages in each group.
ggplot(df, alpha = 0.2,
aes(x = LetterGrade, group = ExperimentCohort, fill = ExperimentCohort))+
stat_bin(aes(y=..density..), position='dodge')
UPDATE - correct solution
As pointed out by @rpierce y=..density.. will calculate density values for each group not the percentages (they are not the same).
To get the correct solution with percentages one way is to calculate them before plotting. For this used function ddply() from library plyr. In each ExperimentCohort calculated proportions using functions prop.table() and table() and saved them as prop. With names() and table() got back LetterGrade.
df.new<-ddply(df,.(ExperimentCohort),summarise,
prop=prop.table(table(LetterGrade)),
LetterGrade=names(table(LetterGrade)))
head(df.new)
ExperimentCohort prop LetterGrade
1 One 0.21739130 A
2 One 0.08695652 B
3 One 0.13043478 C
4 One 0.13043478 D
5 One 0.30434783 E
6 One 0.13043478 F
Now use this new data frame for plotting. As proportions are already calculated - provided them as y values and added stat="identity" inside the geom_bar.
ggplot(df.new,aes(LetterGrade,prop,fill=ExperimentCohort))+
geom_bar(stat="identity",position='dodge')
A:
You can also do this by creating a weight column that sums to 1 for each group:
ggplot(df %>%
group_by(ExperimentCohort) %>%
mutate(weight = 1 / n()),
aes(x = LetterGrade, fill = ExperimentCohort)) +
geom_histogram(aes(weight = weight), stat = 'count', position = 'dodge')
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass data from an element to an action in ReactJS?
So I have the following code, which leverages Bootstrap's button styling and functionality:
import React from 'react';
import DashboardActions from '../../action/dashboard.js';
export class StatFilter extends React.Component
{
constructor(props) {
super(props);
this.state = {
selection: this.props.initialSelection
};
}
render() {
return (
<div className="btn-group">
<button ref="viewButton" type="button" className="btn btn-danger dropdown-toggle" data-toggle="dropdown"
onChange={DashboardActions.seeValue.bind(null, React.findDOMNode(this.refs.viewButton).value)}>
<span>{this.props.initialSelection}</span>
<span className="caret"></span>
<span className="sr-only">Toggle Dropdown</span>
</button>
<ul className="dropdown-menu">
<li><a>Revenue</a></li>
<li><a>Trends</a></li>
<li><a>Statistics</a></li>
</ul>
</div>
);
}
}
Inside the render function, my StatFilter attaches an action to an event. What I want to happen with that bind is that the value of the viewButton button is passed to the action. In other words, when the value of the button changes, StatFilter will dispatch an action letting my app know that its value has changed.
How I'm trying to do this is by using bind() to pass the value of the viewButton to the action. This, however, gives me the warning:
t is accessing getDOMNode or findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.
And the error:
Uncaught TypeError: Cannot read property 'value' of null
Although I'm certain I'm doing this wrong, is the warning telling me something too? Should I be handling all of this logic in the render function? If not, then where should I put it? Also, how come the above code does not work?
A:
Calling findDOMNode within the render method return is the problem. You can not call a function directly in the event handler, but rather must pass the event handler a callback. This won't invoke a function call when the component renders, but rather when an event occurs.
export class StatFilter extends React.Component
{
constructor(props) {
super(props);
this.state = {
selection: this.props.initialSelection
};
}
handleChange(){
DashboardActions.seeValue(React.findDOMNode(this.refs.viewButton).value);
}
render() {
return (
<div className="btn-group">
<button ref="viewButton" type="button" className="btn btn-danger dropdown-toggle" data-toggle="dropdown"
onChange={this.handleChange}>
<span>{this.props.initialSelection}</span>
<span className="caret"></span>
<span className="sr-only">Toggle Dropdown</span>
</button>
<ul className="dropdown-menu">
<li><a>Revenue</a></li>
<li><a>Trends</a></li>
<li><a>Statistics</a></li>
</ul>
</div>
);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Dynamic Button Event Handler Mechanism
I am creating buttons dynamically for a user-based app. Now I have to tell the new form what text to apply to the buttons via parameters to the form, the form then creates the buttons. Now I have an issue - the events for these buttons: What is the best mechanism to get the button click events through. I cannot access the form from the originating form, and I can only pass simple data types (and arrays).
My first thought is to use a code to reffer to the appropriate method in a static class - basically, pass an array of ints through with the names of the buttons and their onclick handler calls one method - handle(int code) -> where code is used in a giant switch statement to call the appropriate method.
But I doubt this is the best mechanism. I would prefer to create a listener of some sort that simply listens for button clicks, and should the click be unhandled, determine which button was clicked and manage it from there.
I have looked at the observer pattern and I am not entirely convinced this is the best one to follow. The problem is not that there is no solution, the problem is that I want the BEST solution.
This is in C# for monodroid - but the impact of this information should be minimal.
Thanks
A:
Currently I have two options:
Use reflection - pass a method name to the button and that button can then invoke a method based on the string value passed. Then simply create a static class where all button methods are kept.
Use a switch statement - since I can have delegates that take parameters (one of them being a SENDER object) I can easily send the sender object to a method containing a switch statement which performs an action based on that object.
In my research I have determined that the former (reflection) is preferred, espcially since the number of buttons is rather large.
REFS:
http://embeddedgurus.com/stack-overflow/2010/04/efficient-c-tip-12-be-wary-of-switch-statements/
Large Switch statements: Bad OOP?
Method Factory - case vs. reflection
| {
"pile_set_name": "StackExchange"
} |
Q:
LibGDX - make actors fill the parent horizontally
I can't figure out how to make a jrpg-like menu with LibGDX.
I have all the elements I need, a hero picture, a verticalGroup with hero stats and a third verticalGroup which currently only holds a test button.
The problem is that the elemens are really small, I would like for them to spread out across the whole width evenly divided.
game screenshot
package com.mygdx.game.UI;
import com.badlogic.gdx.scenes.scene2d.ui.Window;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Align;
import com.mygdx.game.Entities.Entity;
import com.mygdx.game.Map.Map;
import Utility.Utility;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.ui.HorizontalGroup;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup;
public class BottomMenu extends Window {
private static final String TAG = BottomMenu.class.getSimpleName();
private static String title = "";
private String unknownHeroImageLocation = "sprites/gui/portraits/unknown.png";
private Image heroImage;
//identifier labels
private Label hpLabel;
private Label mpLabel;
private Label xpLabel;
private Label levelLabel;
private Label iniLabel;
//value labels
private Label hp;
private Label mp;
private Label xp;
private Label levelVal;
private Label iniVal;
private Label heroNameLabel;
private Entity linkedEntity;
private static final float BOTTOMMENUHEIGHTTILES = 6;
private static final float BOTTOMMENUWIDGETS = 3;
//Attributes
private int heroLevel;
private int heroHP;
private int heroMP;
private int heroXP;
private int heroINI;
private HorizontalGroup bottomMenuTable;
public BottomMenu(Entity[] entities){
super(title, Utility.STATUSUI_SKIN);
linkUnitsToMenu(entities);
initElementsForUI();
configureElements();
addElementsToWindow();
}
private void linkUnitsToMenu(Entity[] entities) {
for(Entity entity : entities) {
entity.setbottomMenu(this);
}
}
private void initElementsForUI() {
this.debug();
//hero name
heroNameLabel = new Label("", Utility.STATUSUI_SKIN, "inventory-item-count");
heroNameLabel.setColor(Color.CYAN);
heroNameLabel.setScale(20.0f);
changeHeroImage(unknownHeroImageLocation);
//groups
bottomMenuTable = new HorizontalGroup();
//bottomMenuTable.align(Align.center);
bottomMenuTable.setFillParent(true);
this.setTransform(true);
this.setPosition(0, 0);
//labels
hpLabel = new Label(" hp:", Utility.STATUSUI_SKIN);
hp = new Label("", Utility.STATUSUI_SKIN);
mpLabel = new Label(" mp:", Utility.STATUSUI_SKIN);
mp = new Label("", Utility.STATUSUI_SKIN);
xpLabel = new Label(" xp:", Utility.STATUSUI_SKIN);
xp = new Label("", Utility.STATUSUI_SKIN);
levelLabel = new Label(" lv:", Utility.STATUSUI_SKIN);
levelVal = new Label("", Utility.STATUSUI_SKIN);
iniLabel = new Label(" ini:", Utility.STATUSUI_SKIN);
iniVal = new Label("", Utility.STATUSUI_SKIN);
}
private void changeHeroImage(String heroImageLink) {
Utility.loadTextureAsset(heroImageLink);
TextureRegion tr = new TextureRegion(Utility.getTextureAsset(heroImageLink));
TextureRegionDrawable trd = new TextureRegionDrawable(tr);
if(heroImage != null) {
trd.setMinHeight(this.getHeight());
trd.setMinWidth(this.getWidth() / BOTTOMMENUWIDGETS);
heroImage.setDrawable(trd);
}else {
trd.setMinHeight(this.getHeight());
trd.setMinWidth(this.getWidth() / BOTTOMMENUWIDGETS);
heroImage = new Image(trd);
}
}
private void configureElements() {
defaults().expand().fill();
}
private void addElementsToWindow() {
this.add(bottomMenuTable);
bottomMenuTable.addActor(heroImage);
heroImage.debug();
Table statsGroup = new Table();
statsGroup.setHeight(this.getHeight());
statsGroup.setWidth(this.getWidth() / BOTTOMMENUWIDGETS);
statsGroup.add(heroNameLabel);
statsGroup.row();
statsGroup.add(hpLabel);
statsGroup.add(hp);
statsGroup.row();
statsGroup.add(mpLabel);
statsGroup.add(mp);
statsGroup.row();
bottomMenuTable.addActor(statsGroup);
statsGroup.debug();
VerticalGroup smallMenu = new VerticalGroup();
smallMenu.setHeight(this.getHeight());
smallMenu.setWidth(this.getWidth() / BOTTOMMENUWIDGETS);
smallMenu.addActor(new TextButton("test", Utility.STATUSUI_SKIN));
bottomMenuTable.addActor(smallMenu);
smallMenu.debug();
}
public void setHero(Entity entity) {
if(entity != null) {
if(entity.getName() != heroNameLabel.getText().toString()) {
this.linkedEntity = entity;
initiateHeroStats();
populateElementsForUI(entity);
}
}else {
resetStats();
}
}
private void initiateHeroStats() {
heroLevel = this.linkedEntity.getLevel();
heroHP = this.linkedEntity.getHp();
heroMP = this.linkedEntity.getMp();
heroXP = this.linkedEntity.getXp();
heroINI = this.linkedEntity.getIni();
}
private void populateElementsForUI(Entity entity) {
heroNameLabel.setText(entity.getName());
changeHeroImage(entity.getPortraitPath());
updateLabels();
}
private void resetStats() {
heroNameLabel.setText("");
hp.setText("");
mp.setText("");
xp.setText("");
levelVal.setText("");
iniVal.setText("");
changeHeroImage(unknownHeroImageLocation);
}
public void update() {
Gdx.app.debug(TAG, "updating bottom menu UI");
updateStats();
updateLabels();
updateSize();
}
private void updateLabels() {
hp.setText(String.valueOf(heroHP));
mp.setText(String.valueOf(heroMP));
xp.setText(String.valueOf(heroXP));
levelVal.setText(String.valueOf(heroLevel));
iniVal.setText(String.valueOf(heroINI));
}
private void updateStats() {
if(linkedEntity != null) {
heroLevel = linkedEntity.getLevel();
heroHP = linkedEntity.getHp();
heroMP = linkedEntity.getMp();
heroXP = linkedEntity.getXp();
if(linkedEntity.getEntityactor().getIsHovering()) {
this.setVisible(true);
}
}
}
private void updateSize() {
int scaledWidth = Gdx.graphics.getWidth();
int scaledHeight = (int) (BOTTOMMENUHEIGHTTILES * Map.TILE_HEIGHT_PIXEL);
this.setSize(scaledWidth,scaledHeight);
bottomMenuTable.setSize(scaledWidth,scaledHeight);
}
}
A:
Change all your Vertical/HorizontalGroups to Tables.
Check out the fillX/expandX methods on the Table's Cells.
| {
"pile_set_name": "StackExchange"
} |
Q:
SSH Connect to Domain that points to different IP
A bit of background info, first:
I have a domain that is configured to run a mail server, iRedadmin, postfix, etc. I can receive and send email and everything works great. The problem lies in the fact that after I decided to sign up for an online portfolio hosting service, they wanted me to change my domain's A @ entry in the DNS to point to their server IP, so that I could use my own "custom domain" instead of their generic subdomains, so that instead of going to sub.domain.com/portfolio, I could go to my-domain.com/portfolio to visit my site, which is in fact hosted on their servers.
After changing my A @ entry to point to their IP, everything worked fine, I could send email but not receive any. The problem lied in the fact that when someone tried sending email to, say, [email protected], all the mail was really directed to their IP rather than my one, so in theory, they should have received all my mail.
I have solved the problem by creating a subdomain that points to my domain, e.g. webmail.domain.com and creating an MX entry that points to webmail.domain.com. Email works fine, however, now I have problems with ssh connection. I can connect to my domain by using its IP address, but if I use the domain, it actually connects to the portfolio hosting service's IP. Sad face.
My question: is it possible to create a DNS entry that applies only to certain ports? So I could ssh/FTP through port 22/21,etc... and use my local IP instead of theirs?
Thanks for helping, this is really important!
A:
DNS entries has nothing to do with ports. They are simply a registry for domain names to IP address translation.
When you ssh into a server say domain.com then first DNS lookup for domain.com is done. The IP returned is then used by you ssh client to connect to the server. SSH client knows that your server's SSH works on port 22 so it tries to connects to that IP address on port 22.
In your case if your domain.com points to your portfolio hosting service's IP then that is what will be resolved by your ssh client.
Maybe you can add another subdomain which points to your server and then use it to login. Or use you subdomain for email, if email is on the same server.
An another way would be to add an entry to /etc/hosts (for linux) with your domain. DNS resolution first looks up hosts file first and then DNS so if you have an entry there then your ssh client will resolve it as you server.
You can check out ways to add hosts entries for Linux and other OS here
| {
"pile_set_name": "StackExchange"
} |
Q:
Active Model Serializer - Serialize Model with multiple key and value
Most of the questions on SO seems to be too outdated to solve this problem.
I want to serialize a model.
Here's what my serializer looks like -
class AssignmentSerializer < ActiveModel::Serializer
belongs_to :lesson, class_name: "Lesson"
attributes :id, :student_id, :tutor, :name, :start_date, :end_date, :description, :lesson
end
This works perfectly well for situations where you want to serialize a single object in this form.
def index
if current_user&.student?
@assignments = Assignment.where(student_id: current_user.id)
@assignments_due = Assignment.find_due(current_user)
@submitted_assignments = Assignment.find_submitted(current_user)
elsif current_user&.tutor?
@assignments = Assignment.where(tutor_id: current_user.id)
end
respond_to do |format|
format.json { render json: @assignments }
end
end
But doesn't work when I want to serialize multiple objects like so:
def index
if current_user&.student?
@assignments = Assignment.where(student_id: current_user.id)
@assignments_due = Assignment.find_due(current_user)
@submitted_assignments = Assignment.find_submitted(current_user)
elsif current_user&.tutor?
@assignments = Assignment.where(tutor_id: current_user.id)
end
respond_to do |format|
format.json { render json: {
assignments: @assignments,
assignments_due: @assignments_due,
submitted_assignments: @submitted_assignments
}, each_serializer: AssignmentSerializer
}
end
end
I have tried multiple methods by following different methods I saw in this documentation but none seems to work.
Any idea what I could be doing wrong?
Update tried as suggested in answer and comment, but this approach did not work. Tried with and without the each_serializer key
respond_to do |format|
format.json { render json: {
assignments: @assignments.as_json,
assignments_due: @assignments_due.as_json,
submitted_assignments: @submitted_assignments.as_json
}, each_serializer: AssignmentSerializer
}
end
A:
Apparently, the answer was right there all along, it was just a bit confusing.
In the same link I shared I found the answer. This link
So this is how I did it, using ActiveModelSerializers::SerializableResource.new
def index
if current_user&.student?
@assignments = Assignment.where(student_id: current_user.id)
@assignments_due = Assignment.find_due(current_user)
@submitted_assignments = Assignment.find_submitted(current_user)
elsif current_user&.tutor?
@assignments = Assignment.where(tutor_id: current_user.id)
end
respond_to do |format|
format.json { render json: {
assignments: ActiveModelSerializers::SerializableResource.new(@assignments),
assignments_due: ActiveModelSerializers::SerializableResource.new(@assignments_due),
submitted_assignments: ActiveModelSerializers::SerializableResource.new(@submitted_assignments)
}
}
end
end
That gave me the exact structure that I wanted.
| {
"pile_set_name": "StackExchange"
} |
Q:
General Relativity: is Tangent Space Always Flat?
In General Relativity we see spacetime as a manifold; in this context vectors can't be defined on the manifold but need to be defined on the tangent space of the manifold. So each point of the manifold has its own tangent space and different vectors in different tangent spaces cannot be easily compared. At last each tangent space has its own metric tensor $g_{\mu \nu}=\partial _\mu \cdot \partial _\nu$, where $\partial _\mu,\partial _\nu$ are the base of the tangent space.
Problem is: my geometrical intuition makes me think about the tangent space as a flat space; if you have any 2D or 3D object in everyday experience the tangent space at one point is always a flat one. But it's not only intuition: spacetime locally looks like $\mathbb{M}^4$, so locally it looks flat or to say it better: locally can be approximated with a flat spacetime; but seems to me that the tangent space at one point is simply the space that better approximate the area around that point; this also push me to say that the tangent space should be always flat.
So is the tangent space of a manifold always flat? Or equivalently is the tangent space always $\mathbb{M}^4$?
Based on the upper reasoning seems to me that the answer should be yes, but this seems to create a problem: in GR we use the Christoffel connection so the curvature can be calculated using only the metric tensor $g_{\mu\nu}$, but if the tangent space is always flat then the metric tensor is always "a flat one", in the sense that it generates always flat curvature. This is obviously absurd. How can we get out of this apparent contradiction?
Edit: Based on the answer of Javier tangent space is indeed always flat. Does it mean that I can take any tangent space (with metric tensor $g_{\mu\nu}$), apply a change of coordinates and get the metric tensor of $\mathbb{M}^4$ ($\eta _{\mu\nu}$)? This is important because this is what flatness means; am I right?
And also: we state that the metric is calculated by looking at the rate of change of the metric $g_{\mu\nu}=\partial _\mu \cdot \partial _\nu$, but the metric is always flat! So the rate of change is always zero because every tangent space is flat! How can we deal with this?
A:
Short answer: yes each tangent space is flat.
In principle the tangent space is a vector space, not a Riemannian manifold, and so the concept of curvature technically doesn't apply if that's all you have. To define curvature you need to define parallel transport; for that, you need to think of the tangent space as a manifold, and that implies looking at the tangent spaces of the tangent space! And if you do that, the vector space structure gives you a canonical way to define parallel transport, and this parallel transport ends up being flat.
Finally, the solution to your paradox is simple: the curvature depends on derivatives of the metric, that is, on how it changes from tangent space to tangent space. The metric at a point is irrelevant because all vector spaces with an inner product are isometric; what matters is how it varies in space.
Edit in response to your edit: You're playing too fast and loose with the words. Differential geometry is complicated, and we need to be precise in how we speak.
You can always make any tangent space into Minkowski space by choosing an appropriate basis, not because it is flat, but because it is a vector space. The difference is subtle but important. A vector space has a single metric tensor: it takes pairs of vectors and returns a number. A manifold has a metric tensor field: a metric tensor at each point, which takes pairs of tangent vectors. The fact that the tangent space is flat is a red herring.
One definition of flatness (of a manifold) is that you can use a single coordinate system in which the metric tensor is everywhere Minkowski. This statement is different from the statement about the tangent space; here you're choosing a different basis at each point, which are related by coming from a single coordinate system. In a single tangent space, you only have one basis. And you can always have $g_{\mu\nu} = \eta_{\mu\nu}$ at a single point (and hence at a single tangent space), but making it so at every point with the same coordinate system may or may not be possible, and that's what flatness means.
A:
TL;DR: your problem is not keeping track of the points where you evaluate things.
A metric tensor $g$ on a manifold $M$ is a smooth choice of scalar products $g_x$ on each vector space $T_xM$.
But every vector space $V$ is a manifold on its own right, and for $x \in V$, we have that $T_xV \cong V$. If $V$ equipped with a scalar product, which I'll call $h$, then $h$ may be regarded as a metric tensor on the manifold $V$, by assigning to each tangent space $T_xV$ the scalar product $h$ itself. Since this is a "constant" metric tensor, in the sense that in each tangent space you put the same scalar product (namely, $h$), the manifold $(V,h)$ is flat. The reason is very simple: the curvature depends on derivatives of the metric, and all of them are zero in this case. When one says that the vector space $(V,h)$ is flat, one actually means that the manifold $(V,h)$ is flat, in the sense explained above.
That being said, there are three manifolds with metric tensors into play here. Your spacetime $(M,g)$, Minkowski space $(\Bbb M^4, \eta)$, and for a given $x \in M$, the tangent space $(T_xM,g_x)$. The spacetime $(M,g)$ is not necessarily flat, but $(T_xM, g_x)$ and $(\Bbb M^4,\eta)$ are because of the previous paragraph.
The issue is that given coordinates for $(x^\mu)$ for $M$, sure, we may compute $g_{\mu\nu} = g(\partial_\nu, \partial_\nu)$ on the coordinate system domain. These functions are not in general constant. But when you fix a tangent space $T_xM$, every tangent vector $v \in T_xM$ is a combination $v = v^\mu\partial_\mu|_x$ of the coordinate vectors evaluated at the point $x$. And this gives rise to coordinates on $T_xM$, whose coordinate vectors are $\partial_\mu|_x$. In other words, I am saying that while $x \mapsto \partial_\mu|_x$ is a vector field on the coordinate neighborhood in $M$, the coordinate fields $$ T_xM \ni v \mapsto (\partial_\mu|_x)|_v \doteq \partial_\mu|_x \in T_xM \cong T_vT_xM $$are defined globally on $T_xM$, and they're constant. And the metric coefficients of the metric tensor $g_x$ (evaluated at $x$) on $T_xM$ are constant, and equal to $g_{\mu\nu}(x)$ (evaluated at $x$!!!).
And $(T_xM,g_x)$ is isometric to Minkowski space $(\Bbb M^4,\eta)$ because one can always choose normal coordinates for $M$ centered at $x$ for which $g_{\mu\nu}(x) = \eta_{\mu\nu}$. And this happens only at the point $x$. One can do this even if $(M,g)$ is not flat. On the other hand, $(M,g)$ being flat is equivalent to having $g_{\mu\nu} = \eta_{\mu\nu}$ along entire open neighborhoods, as opposed to only at a single point. Then one defines $T_xM \to \Bbb M^4$ by taking $\partial_\mu|_x$ to the canonical vectors $e_\mu$ in $\Bbb M^4$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reference global class names from within a css module
Picture a more traditional web application that is slowly introducing a React component in one page that is complex enough to need it.
We're developing this new UI with Webpack, and we're using css modules for all the new css that the new UI needs. But we still need to reuse some css that's global and provided in the app via a traditional css stylesheet linked in the html.
Therefore we need in our css modules to occasionally write rules that refer to a css class in the global namespace, not a class that's locally scoped to it and therefore converted to a more gem-like long css class name when the app is run:
.container {
// rules for container
}
.container.pull-right {
// rules for when the container element also has the pull-right class
}
In the above example, container is meant to be a css class that the css module will contextualize to the particular component using this module.
But pull-right is a class that exist in a css file available in the page, but not processed by css modules or Webpack. Therefore we need a way (a syntax probably) to tell css modules "hey, leave pull-right as is in your output. Do not mess with it or try to BEM the s**t out of it".
I imagine something like this should exist, but I haven't been able to find it so far by googling around.
A:
To refer to a globally declared class name inside :local scoped css modules you should use :global switch:
.container {
// rules for container
}
.container:global(.pull-right) {
// rules for when the container element also has the pull-right class
}
More detailed explanation in css-modules documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Centripetal effect or curved space time
I think I understand both the centrepedal effect and Einsteins curved space time. However I am confused about which best describes the motion of a planet ( or other orbiting body ). Simply put, does the earth experience any centrepedal effect or does it just follow the geodesic line and therefore not experience any centrepedal forces. Can someone please explain or let me know that science has yet to answer this question.
A:
You can explain the motion of the Earth around the Sun either by a centipetal gravitational force or by spacetime curvature. It isn't the case that one description is wrong and one is right, but rather that they are both mathematical models that describe the motion in different ways.
To illustrate this suppose we replace the Sun by a positive charge and the Earth by a negative charge. A negative charge will orbit a positive charge in the same way that a planet orbits the Sun. Indeed this principle was the basis of the Bohr model for the hydrogen atom. In a model like this we would be quite happy to consider the orbital motion to be due to a centripetal force (the electromagnetic force), though as it happens you can describe the EM force using the concepts of curvature.
The attraction of general relativity is that it explains exactly what the gravitational force is and how it arises. For example Newton's law of gravitation tells us that the centripetal force will be:
$$ F_\text{Newton} = \frac{GMm}{r^2} $$
This is a nice simple equation, and indeed we would expect an inverse square force like this to apply so it's a reasonable approach to studying orbital motion. However when we use general relativity to look more deeply we find that the force is actually:
$$ F_\text{GR} = \frac{GMm}{r^2\sqrt{1-\frac{2GM}{c^2r}}} $$
We could continue to work with a centripetal force $F_\text{GR}$ but the equation has become a bit messy and in any case it only applies in the specific case of spherical symmetry. If we decide to abandon the idea of a force and use spacetime curvature instead we find describing the motion becomes conceptually simpler (though the details of the maths can be hard!).
The point is that if you're a physicist then what you're trying to do is predict how objects will move in a gravitational field. In some circumstances it's easier to use a centripetal force and in other circumstances it's easier to use a curvature approach. Whatever approach you choose, as long as it ends up giving the correct answers it isn't wrong.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.