text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Is there a standard way to ensure that a piece of code is executed at global scope?
I have some code I want to execute at global scope. So, I can use a global variable in a compilation unit like this:
int execute_global_code();
namespace {
int dummy = execute_global_code();
}
The thing is that if this compilation unit ends up in a static library (or a shared one with -fvisibility=hidden), the linker may decide to eliminate dummy, as it isn't used, and with it my global code execution.
So, I know that I can use concrete solutions based on the specific context: specific compiler (pragma include), compilation unit location (attribute visibility default), surrounding code (say, make an dummy use of dummy in my code).
The question is, is there a standard way to ensure execute_global_code will be executed that can fit in a single macro which will work regardless of the compilation unit placement (executable or lib)? ie: only standard c++ and no user code outside of that macro (like a dummy use of dummy in main())
A:
The issue is that the linker will use all object files for linking a binary given to it directly, but for static libraries it will only pull those object files which define a symbol that is currently undefined.
That means that if all the object files in a static library contain only such self-registering code (or other code that is not referenced from the binary being linked) - nothing from the entire static library shall be used!
This is true for all modern compilers. There is no platform-independent solution.
A non-intrusive to the source code way to circumvent this using CMake can be found here - read more about it here - it will work if no precompiled headers are used. Example usage:
doctest_force_link_static_lib_in_target(exe_name lib_name)
There are some compiler-specific ways to do this as grek40 has already pointed out in a comment.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Testable code with ORM factory
I'm trying to improve the following code for testability.
public function can_apply_extension()
{
$search_dates = [
Carbon::createFromTimestamp(strtotime($this->billing_verified_to))->subMonth(1),
$this->billing_verified_to
];
$record = ORM::factory('a model')
->where('created_at', 'BETWEEN', $search_dates)
->find();
if( !$record->loaded() )
{
return true;
}
return false;
}
Here's how I think I can improve it:
public function can_apply_extension($search_from = null, $search_to = null)
{
$search_from = is_null($search_from) ? Carbon::createFromTimestamp(strtotime($this->billing_verified_to))->subMonth(1) : $search_from;
$search_to = is_null($search_to) ? $this->billing_verified_to : $search_to
$search_dates = [$search_from, $search_to];
$record = ORM::factory('a model')
->where('created_at', 'BETWEEN', $search_dates)
->find();
if( !$record->loaded() )
{
return true;
}
return false;
}
I still have to mock ORM part. I think the only option is that I pass an object as a parameter or make a method that injects the ORM object.
Are there any other better ways? I'm aware of IoC container, but I can't use it in our current environment.
Update: Beside passing ORM as a parameter so that I can just swap it out, I found another workaround.
Since ORM::factory() actually returns an object, I was able to add a method and modify the factory method.
public function testing($bool)
{
$this->_testing = $bool;
}
public function instead($when_this_passed, ORM $use_this_instead)
{
$this->_instead_map[$when_this_passed] = $use_this_instead;
}
public function factory($name)
{
if($this->_testing && array_key_exists($name, $this->_instead_map))
{
return $this->_instead_map[$name];
}
else
{
parent::factory($name);
}
}
A:
(I've not coded in PHP recently, my examples are Java or Java-like pseudocode.)
In his Working Effectively with Legacy Code book Michael C. Feathers describes a lot of techniques which help making any code testable. Another good resource is the following article: Killing the Helper class, part two
The usual way to breaking static dependencies is the following: Create a non-static interface which has a similar method than the original static class:
public interface OrmFactory {
OrmSomething create($name);
}
Then create an implementation which calls the static method/class:
public class OrmFactoryImpl implements OrmFactory {
public OrmSomething create($name) {
return ORM::factory($name);
}
}
Finally, use the interface in the can_apply_extension function:
public class MyClass {
private OrmFactory ormFactory;
public MyClass(OrmFactory ormFactory) {
this.ormFactory = ormFactory;
}
public void can_apply_extension() {
...
$record = ormFactory.create('a model')
->where('created_at', 'BETWEEN', $search_dates)
->find();
...
}
}
In tests you can pass a mocked OrmFactory to the class while in production code you can use the original one through the OrmFactoryImpl wrapper/delegate. (I guess PHP also has some mocking framework implementations which makes testing easier but you can implement a TestOrmFactory which emulates some behaviour of the original one without the need of any database.)
The second snippet in the question has test logic in production smell. I would avoid that and use the much cleaner dependency breaking above. The linked page contains some disadvantages of the smell. One of them is the following:
Code that was not designed to work in production
and which has not been verified to work properly
in the production environment could accidently be
run in production and cause serious problems.
And another one is:
Software that is added to the SUT For Tests Only
makes the SUT more complex. It can confuse potential
clients of the software's interface by introducing
additional methods that are not intended to be
used by any code other than the tests. This
code may have been tested only in very specific
circumstances and might not work in the typical
usage patterns used by real clients.
(SUT means System Under Test, in this case the class with can_apply_extension().)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is $2x-y = 0$ a plane or line in 3d?
I am going through Strang's linear algebra video 1 (https://www.youtube.com/watch?time_continue=1131&v=ZK3O402wf1c), and he seemed to suggest that the equation:
$2x - y = 0$
is a plane in 3 dimensions. However, isn't $z$ zero in this equation? Therefore, this would describe a line in 3d not a plane. I think his logic was that the omitted term is $0z$, so $z$ can be anything.
That makes sense, but I also don't understand how the same equation can be a line in 2d but a plane in 3d.
A:
There are a few ways to see this.
$1.$ $2x-y=0$ defines a line in the $(x,y)-$plane which is then shifted in $z$ because if $(x_0,y_0)$ satisfies $2x-y$, then we are free to choose $z_0$ so that $(x_0,y_0,z_0)$ satisfies the equation. So, we get a line in the $(x,y)-$plane shifted in the $z$ direction forming a plane.
$2.$ This is the kernel of the linear map $T:\mathbb{R}^3\to \mathbb{R}$ given by $T(x,y,z)=2x-y$. Now, $\dim\operatorname{range}(T)=1$, so that by the rank nullity theorem, $\dim\ker(T)=2$. This tells us that
$$ \dim\ker(T)=\dim\{(x,y,z)\in \mathbb{R}^3: 2x-y=0\}=2.$$
So, the dimension of the solution set to that equation is $2-$dimensional, i.e. a plane.
$3.$ Alternatively, we can view the set of solutions of the equation $2x-y=0$ as the set of elements $(x,y,z)$ in $\mathbb{R}^3$ such that
$$ (2,-1,0)\cdot(x,y,z)=0.$$
That is, the solutions to the equation are the set of vectors in $\mathbb{R}^3$ orthogonal to $(2,-1,0)$. Such vectors form a plane.
A:
$z$ is not always zero because $z$ can take any value. The equation that you have defines the plane by two directions. One of them is given by the line in the $xy$ plane, the other is along the $z$ axis.
A:
The confusion appears to arise from Strang conflating equations and sets. I.e. "$2x-y=0$" isn't really a plane or a line; it's just an equation. Instead it's the set $\{(x,y,z) \in \mathbb{R}^3 | 2x-y=0\}$ that is a plane. (If you're unfamiliar with this set notation, read it as, "The set of triples $(x,y,z)$ such that $2x-y=0$.")
Note that this set is different to both $\{(x,y,z) \in \mathbb{R}^3 | 2x-y=0, z=0\}$ (the line in 3-D space given by the same equation from before and also the extra condition that $z=0$) and the set $\{(x,y) \in \mathbb{R}^2 | 2x-y=0\}$ (the line given by the same equation in 2-D space).
Once you're more experienced, you'll be able to work out the sets other mathematicians are talking about from context without them having to spell out the whole thing (e.g. Strang talking about $2x-y=0$ in 3 dimensions is clearly referring to $\{(x,y,z) \in \mathbb{R}^3 | 2x-y=0\}$ rather than any other set). But until then, the extra formalism of the set notation can help you understand the difference between each of the things you had confused.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Creating user-friendly installer for Node.js application
How can I create a user-friendly installation for my Node.js application? The installer must connect to the MySQL database and exec commands. Can user do it without the Node.js installed? Or have you got any tips how can I provide it? And how about SaaS? I thought about it, but I'm afraid of server and the hard drives. node_modules can be very big. Thanks.
A:
The most standard way to deploy an app in nodejs ecosystem is thru npm which requires nodejs on the target system.
You must prepare your package.json stating all your dependencies and your installation scripts (preinstall and postinstall). Then, you distribute your code artifacts along with the package.json. At the target system, you or your users would just copy all your artifacts and run npm install and eventually npm test.
This is the standard procedure that anyone fluent in nodejs, as many sysadmins are nowadays, is able to easily understand and follow.
However if your application is to be used by end users without systems admin experience, or that who migh not have node/npm installed, this is somewhat complicated for them. In that case, you need to provide a simplified installation that includes packaging nodejs with the app.
For ideas; if your app is a kinda desktop app for end users) take a look at electron and electron-packager. Or if your app can better be characterized as a local server app, a container like docker can be worth studying.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can sqrtsd in inline assembler be faster than sqrt()?
I am creating a testing utility that requires high usage of sqrt() function. After digging in possible optimisations, I have decided to try inline assembler in C++. The code is:
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
volatile double normalSqrt(double a){
double b = 0;
for(int i = 0; i < ITERATIONS; i++){
b = sqrt(a);
}
return b;
}
volatile double asmSqrt(double a){
double b = 0;
for(int i = 0; i < ITERATIONS; i++){
asm volatile(
"movq %1, %%xmm0 \n"
"sqrtsd %%xmm0, %%xmm1 \n"
"movq %%xmm1, %0 \n"
: "=r"(b)
: "g"(a)
: "xmm0", "xmm1", "memory"
);
}
return b;
}
int main(int argc, char *argv[]){
double a = atoi(argv[1]);
double c;
std::clock_t start;
double duration;
start = std::clock();
c = asmSqrt(a);
duration = std::clock() - start;
cout << "asm sqrt: " << c << endl;
cout << duration << " clocks" <<endl;
cout << "Start: " << start << " end: " << start + duration << endl;
start = std::clock();
c = normalSqrt(a);
duration = std::clock() - start;
cout << endl << "builtin sqrt: " << c << endl;
cout << duration << " clocks" << endl;
cout << "Start: " << start << " end: " << start + duration << endl;
return 0;
}
I am compiling this code using this script that sets number of iterations, starts profiling, and opens profiling output in VIM:
#!/bin/bash
DEFAULT_ITERATIONS=1000000
if [ $# -eq 1 ]; then
echo "Setting ITERATIONS to $1"
DEFAULT_ITERATIONS=$1
else
echo "Using default value: $DEFAULT_ITERATIONS"
fi
rm -rf asd
g++ -msse4 -std=c++11 -O0 -ggdb -pg -DITERATIONS=$DEFAULT_ITERATIONS test.cpp -o asd
./asd 16
gprof asd gmon.out > output.txt
vim -O output.txt
true
The output is:
Using default value: 1000000
asm sqrt: 4
3802 clocks
Start: 1532 end: 5334
builtin sqrt: 4
5501 clocks
Start: 5402 end: 10903
The question is why the sqrtsd instruction takes only 3802 clocks, to count square root of 16, and sqrt() takes 5501 clocks?
Does it have something to do with HW implementation of certain instructions? Thank you.
CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 2
Core(s) per socket: 2
Socket(s): 1
NUMA node(s): 1
Vendor ID: AuthenticAMD
CPU family: 21
Model: 48
Model name: AMD A8-7600 Radeon R7, 10 Compute Cores 4C+6G
Stepping: 1
CPU MHz: 3100.000
CPU max MHz: 3100,0000
CPU min MHz: 1400,0000
BogoMIPS: 6188.43
Virtualization: AMD-V
L1d cache: 16K
L1i cache: 96K
L2 cache: 2048K
NUMA node0 CPU(s): 0-3
A:
Floating point arithmetic has to take into consideration rounding. Most C/C++ compilers adopt IEEE 754, so they have an "ideal" algorithm to perform operations such as square root. They are then free to optimize, but they must return the same result down to the last decimal, in all cases. So their freedom to optimize is not complete, in fact it is severely constrained.
Your algorithm probably is off by a digit or two part of the time. Which could be completely negligible for some users, but could also cause nasty bugs for some others, so it's not allowed by default.
If you care more for speed than standard compliance, try poking around with the options of your compiler. For instance in GCC the first I'd try is -funsafe-math-optimizations, which should enable optimizations disregarding strict standard compliance. Once you tweak it enough, you should come closer to and possibly pass your handmade implementation's speed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
LayoutAnchorable Title font
For the XAML below I'm using AvalonDock 2.0.2. I'm wanting to set the font of the Title property of the LayoutAnchorable
<xcad:DockingManager Name="TabItemDockingManager"
AllowMixedOrientation="True"
BorderBrush="Black"
BorderThickness="0" Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
AnchorablesSource="{Binding Anchorables, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" viewModels:AvalonDockLayoutSerializer.LoadLayoutCommand="{Binding ADLayout.LoadLayoutCommand}" viewModels:AvalonDockLayoutSerializer.SaveLayoutCommand="{Binding ADLayout.SaveLayoutCommand}">
<xcad:DockingManager.LayoutUpdateStrategy>
<pane:LayoutInitializer/>
</xcad:DockingManager.LayoutUpdateStrategy>
<xcad:DockingManager.LayoutItemTemplateSelector>
<pane:PanesTemplateSelector>
<pane:PanesTemplateSelector.MyViewTemplate>
<DataTemplate>
...
</DataTemplate>
</pane:PanesTemplateSelector.MyViewTemplate>
</pane:PanesTemplateSelector>
</xcad:DockingManager.LayoutItemTemplateSelector>
<xcad:DockingManager.LayoutItemContainerStyleSelector>
<pane:PanesStyleSelector>
<pane:PanesStyleSelector.ToolStyle>
<Style TargetType="{x:Type xcad:LayoutAnchorableItem}">
<Setter Property="Title" Value="{Binding Model.Title}"/>
<Setter Property="IconSource" Value="{Binding Model.IconSource}"/>
<Setter Property="Visibility" Value="{Binding Model.IsVisible, Mode=TwoWay, Converter={StaticResource BoolToVisibilityConverter}, ConverterParameter={x:Static Visibility.Hidden}}"/>
<Setter Property="ContentId" Value="{Binding Model.ContentId}"/>
<Setter Property="IsSelected" Value="{Binding Model.IsSelected, Mode=TwoWay}"/>
<Setter Property="IsActive" Value="{Binding Model.IsActive, Mode=TwoWay}"/>
</Style>
</pane:PanesStyleSelector.ToolStyle>
</pane:PanesStyleSelector>
</xcad:DockingManager.LayoutItemContainerStyleSelector>
<xcad:LayoutRoot x:Name="_LayoutRoot">
<xcad:LayoutPanel Orientation="Vertical">
<xcad:LayoutAnchorablePane Name="AnchorablesPane" DockHeight="150">
</xcad:LayoutAnchorablePane>
</xcad:LayoutPanel>
</xcad:LayoutRoot>
</xcad:DockingManager>
I can set the Title text (which is done via reading/loading the layout), however I don't see a Font/FontFamily property I can set
Does anyone know how this can be done ?
A:
Thanks to Attila (apols that I cannot mark his answer as I don't have enough points)
AvalonDock 2.2 - Full width TitleTemplate (fill parent container)
AvalonDock is a fantastic library - that said implementing it with MVVM is a challenge but the below seems to work well
<xcad:DockingManager.Resources>
<DataTemplate x:Key="DockingWindowTitleDataTemplate" DataType="{x:Type xcad:LayoutContent}">
<Label>
<TextBlock Text="{Binding Path=Title}" Margin="5,0,0,0" VerticalAlignment="Center" FontSize="14" />
</Label>
</DataTemplate>
</xcad:DockingManager.Resources>
<xcad:DockingManager.AnchorableTitleTemplate>
<StaticResource ResourceKey="DockingWindowTitleDataTemplate" />
</xcad:DockingManager.AnchorableTitleTemplate>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are there penalties for Enum Singletons?
Are there (performance) penalties* associated with the Enum Singleton Pattern in any way, as it seems to be used less than the classical singleton pattern or the inner holder class idiom?
* Penalties, such as the cost of serializability in cases when it is not needed and such, or is the usage low because few of the developers read Effective Java 2nd edition?
A:
All Java singleton patterns (both this and the standard with private constructor and static accessor) have this bad property that if you to test them (or test anything that even remotely depends on them) can use this and only this object.
For example if you want to test PrintingService class that depends on PrintingSingleton you will not be able to replace this printing singleton with a mock because it is bound statically.
i.e. imagine testing this function
boolean printDocument(Document d) {
if (PrintingSingleton.INSTANCE.isPrinterEnabled()) {
PrintingSingleton.INSTANCE.print(d);
}
throw new RuntimeExeption("Printing not enabled");
}
with a test
@Test(expectedExceptions = {RuntimeException.class})
public void testPrinting() {
PrintingService service = ...
service.print(new Document()); // How will you simulate
// throwing an exception?
}
Personally, I would just avoid using singletons that way but rather introduce dependency injection, via Guice, Spring or Pico Container. That way you ensure existence of only one object, while not limiting yourself to not being able to mock the object out for example for tests.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do you display an arrayList in a ListView?
At the moment I have 14 elements added to an array list but I want them to be displayed in a listview activity so far I have:
public class ListView extends ListActivity{
static final String baseURL ="http://www.dublincity.ie/dublintraffic/cpdata.xml?1354720067473";
TextView tvcp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
StringBuilder URL = new StringBuilder(baseURL);
String fullURL = URL.toString();
try{
URL website = new URL(fullURL);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandelingXML gettingData = new HandelingXML();
xr.setContentHandler(gettingData);
xr.parse(new InputSource(website.openStream()));
ArrayList<CarparkNode>carparks = gettingData.getCarparks();
this.setListAdapter(
new ArrayAdapter<CarparkNode>(ListView.this,R.layout.listview, android.R.id.list, carparks)
);
}catch(Exception e){
tvcp.setText("error");
}
}
}
However, every time I run this it will crash and I have no idea why as i have done this before using a simple array. If someone could point out what i'm doing wrong and give a solution that would be great thanks!
A:
First don't give class name ListView Which is predefined class in Android
second Don't perform Network Operation on UI Thread.
Edit:
Reason:
Android version 3.x or more devices won't allow network operation to perform in the UI Thread, when you try to do that it will throw an exception saying you are performing network operation on the UI Thread, i.e NetworkOnMainThreadException. So What you need to do is to Create a separate thread to execute network operation or AsyncTask.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Hide / Show div doesn't work
I'm trying to create a simple component with React (I'm a new user), and I have some troubles to show and hide div. I'm using a state to handle a click and change state, which works fine. Problem is when I'm using the back button from the browser, and come back on the main page, I've no clue how to handle state change as there is no interaction with the user.
I tried to use the location context to change state if the URL pathname === "/", but it looks like anti react pattern because I have to force the component to rerender and check the pathname inside the initial state function. Any ideas how to handle this case?
// DIV on the main page
const Div = React.createClass({
/*contextTypes: {
location: React.PropTypes.object
},*/
getInitialState: function() {
console.log("get initial state");
return { hideDiv: false };
},
handleClick(){
this.setState({ hideDiv: true });
},
render() {
console.log(this.state.hideDiv);
let componentDOM;
if(this.state.hideDiv === true){ componentDOM = <div></div>;}
else{
componentDOM = <div id='showHide'>
<form>
<div>
<select>
<option> ... </option>
</select>
</div>
//Link to a second page
<button type='submit' onClick={this.handleClick}> <Link to {'/destination'}>Submit</Link></button>
</form>
</div>;
}
return (componentDOM);
}
});
A:
I would advise against storing the information about whether or not the component with the form is visible in its own state. From your description, it seems to me like this information belongs higher in the hierarchy - the Div component itself is not capable of deciding whether or not it should be visible, as that depends on some context (URL / application phase) unknown to it.
I'd recommend something like this:
var App = React.createClass({
//Data for the form, you might want to keep them in a store
getInitialState(){ return {data: {}}; }
render(){
//Pass data from your routing library to the props of App
if(this.props.routingParams.url === 'form')
return <Div data={this.state.data} onDataChanged={...} />
else
return <Destination data={this.state.data} />
}
});
Plus remove the state and the hiding logic from Div completely.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Difference effect filter in before and after amplifier
Is there any difference between low pass filter that put before amplifier and after amplifier? Which one is good for PC audio amplifier?
A:
When you amplify something, you are increasing the power. If you look at the cost of components, it will cost you less to filter a "pre-amped" signal.
Also, why would you want to amplify the "dirty" parts of a signal?
Clean it up, then amplify.
A:
The answer is yes in ideal circuit theory and the approximation to it that we call "The Real World".
Consider an ideal RC low-pass filter. The open-circuit output voltage, due to an input voltage \$V_s\$ is
$$V_{o} = V_s \frac{1}{1 + j \omega RC}$$
However, if one connects a load impedance \$Z_L\$ to the output of this filter, the loaded output voltage is
$$V_{ol} = V_s \frac{Z_L}{R + Z_L}\frac{1}{1 + j\omega \left( R||Z_L\right)C}$$
Thus, the DC gain and frequency response of our low-pass filter depends on the load \$Z_L\$
However, if there is a good amplifier (high input impedance, low output impedance) between the low-pass filter and the load, the DC gain and frequency response will effectively be independent of \$Z_L\$.
There are other reasons you might want the filter before the amplifier rather than after. For example:
With the low-pass filter before the amplifier, the amplifier is not
required to needlessly amplify frequencies well above the corner
frequency.
If the low-pass filter is after the amplifier, the power delivered to
the load must pass through the filter.
and which one is good for PC audio amplifier?
Without more details of your application, it isn't clear what the 'good' is.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Delay on ssh authentication
I've just installed 12.04.2 server amd64 in VMWare Player and noticed that there is a 3-5 seconds delay after I put the password and before the shell appears. The same happens when I try to connect using some SFTP software.
In the logs it looks like:
Jun 26 22:40:01 ubuntu-1204-2-server-amd64 sshd[1525]: Accepted publickey for zerkms from 192.168.19.1 port 56018 ssh2
Jun 26 22:40:01 ubuntu-1204-2-server-amd64 sshd[1525]: pam_unix(sshd:session): session opened for user zerkms by (uid=0)
Jun 26 22:40:04 ubuntu-1204-2-server-amd64 sshd[1662]: subsystem request for sftp by user zerkms
Jun 26 22:40:04 ubuntu-1204-2-server-amd64 sshd[1525]: pam_unix(sshd:session): session closed for user zerkms
I've already added UseDNS no to /etc/ssh/sshd_config (and I didn't forget to restart ssh after that. I even reboot the whole server ;-)
Anything else I missed? Any ideas?
A:
start another sshd in debug mode (no need to stop the regular daemon) on a high port number for instance 2222 and connect to that server, you will see at what point the server is stopping. You can play with the debug level by adding more d's.
#/usr/sbin/sshd -dd -p 2222
edit :
Maybe sshd is not the problem but the login process.
Try to bypass all the profile scripting by directly starting a remote shell, see if it connects faster.
# ssh -t user@servername /bin/bash
(option -t will gets you a tty so you bash will show a prompt and will have command line editing)
Session script should to be the cause as your logs shows the session is opened after
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Generate Wsdl/Client Stubs For Web Service
I have been doing some reading up on web services programming with Java, Eclipse, etc. and I found one particular example where the person created the web service and client by doing the following:
define the web service java class (interface + impl)
deploy the web service using Endpoint.publish
grab the wsdl from the url of the web service (eg, localhost://greeting?wsdl)
use wsimport to generate stubs
create a client class using generated stubs
Is there another way to generate the wsdl without having to publish the web service and download it? Perhaps a maven plugin to auto-generate wsdl and client stubs?
Update: Rather than creating a new question I am just going to piggyback on this one.
I have created my web service by defining an interface:
@WebService
public interface HelloWorldWs {
@WebMethod
public String sayHello(String name);
}
and an impl class:
@WebService(endpointInterface = "com.me.helloworldws.HelloWorldWs")
public class HelloWorldWsImpl implements HelloWorldWs {
@Override
@WebMethod
public String sayHello(String name) {
return "Hello World Ws, " + name;
}
}
When I run wsgen I get the following error:
The @javax.jws.WebMethod annotation cannot be used in with @javax.jws.WebService.endpointInterface element.
Eclipse seems to be okay with it.
Any idea why?
Note, I originally did not have the annotation but when I tried to call my webservice I got the following error:
com.me.helloworldws.HelloWorldWsImpl is not an interface
A:
The JSR 224 says in 3.1 section:
An SEI is a Java interface that meets all of the following criteria:
Any of its methods MAY carry a javax.jws.WebMethod annotation (see 7.11.2).
javax.jws.WebMethod if used, MUST NOT have the exclude element set to true.
If the implementation class include the javax.jws.WebMethod, then you cant put @WebMethod(exclude=true) and that in not possible, according to specification.
Depends of custom version of Eclipse, shows a warning for this. e.g. Rational Application Developer for Websphere shows:
JSR-181, 3.1: WebMethod cannot be used with the endpointInterface
property of WebService
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Skype profile picture is too blurry
Everytime I add a new skype image (even in the expected resolution - 480x480 pixels) Skype resizes it and the picture becames blurred.
Is there a way to fix it using Windows 7?
I read somewhere else that it is possible on Windows 8 but I don't have this OS right now.
UPDATE:
I upvoted Dave's answer but I would like to know if there are any other way of doing that without an external app.
A:
This appears to be a common issue with no direct fix, only a work around.
Download Skype Portable 5.0 (or Google it if link dies.)
Quite Normal Skype.
Open Skype Portable.
Change picture.
Close Skype Portable.
Open Normal Skype with nice picture.
Update
Or, change the picture on the phone/tablet instead of the computer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JavaScript function that returns AJAX call data
I would like to create a JavaScript function which returns the value of a jQuery AJAX call. I would like something like this.
function checkUserIdExists(userid){
return $.ajax({
url: 'theurl',
type: 'GET',
cache: false,
data: {
userid: userid
},
success: function(data){
return data;
}
});
}
I know I can do this by setting async to false but I would rather not.
A:
You can't return data returned by an AJAX call unless you want to call it synchronously (and you don't – trust me). But what you can return is a promise of a data returned by an AJAX call and you can do it actually in a very elegant way.
(UPDATE:
Please note that currently jQuery Promises are not compatible with the Promises/A+ specification - more info in this answer.)
Basically you can return the return value of your $.ajax(...) call:
function checkUserIdExists(userid){
return $.ajax({
url: 'theurl',
type: 'GET',
cache: false,
data: {
userid: userid
}
});
}
and someone who calls your function can use it like this:
checkUserIdExists(userid).success(function (data) {
// do something with data
});
See this post of mine for a better explanation and demos if you are interested.
A:
you can pass in a callback function:
function checkUserIdExists(userid, callback) {
$.ajax({
...
success: callback
});
}
checkUserIdExists(4, function(data) {
});
A:
With jQuery 1.5, you can use the brand-new $.Deferred feature, which is meant for exactly this.
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
Source
|
{
"pile_set_name": "StackExchange"
}
|
Q:
4D-vector calculations
For a 4D vector, how can I calculate any component as a function of the three other components and a magnitude and vice versa?
I want x = f(y, z, i, m) where m is the magnitude of the vector.
Will the function be different if I want to calculate y, z or i?
Is there a universal method for n-dimensional vectors?
A:
You cannot. You can't even do this in 1D. Suppose I have a one-vector $(x)$ and I tell you its length, $|x|$. You can't tell whether $x$ is positive or negative. But if you're willing to ignore the sign issue, you can do this:
For $u = (a, b, c, d)$, if you're given $a, b, c$ and $\| u\|$ (the magnitude of $u$), you can compute
$$
d^2 = \| u \|^2 - (a^2 + b^2 + c^2)
$$
from which you can get $\pm d$. Similar formulas hold for finding $a$, given $b, c, d$ and $\| u \|$, and so on.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Admob issue when using GridLayoutManager with RecyclerView
I have a recyclerview with GridLayoutManager and have its spancount as 3. I have two viewtypes - one for the recyclerview items and one for ads(admob). Following is the result when my spancount is 3
You can see that the ad is not visible, now when i change the spancount to 1 it becomes visible like below
i think this is because the admob ads don't support these dimensions, is there a work around for this?
the ad is not showing up even if i try to hardcode the adsize
My question is that is there a way to fit the adview into my recyclerview with GridLayoutManager and spancount as 3
A:
Yes, this is possible. All you have to do is to call setSpanSizeLookup on your layout manager like below
mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position % MainActivity.ITEMS_PER_AD == 0) {//your condition for showing ad
return 3;//replace 3 with the number of items in each row
}
return 1;
}
});
And then set the layout manager to your recyclerview.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
1-loop quiver and the classification of quivers
Gabriel's theorem states that finite type quivers are exactly the ones whose underlying graphs are ADE type Dynkin diagrams. Furthermore, the quivers whose underlying diagrams are ADE type affine Dynkin diagrams are tame quivers. What about the 1-loop quiver? It isn't Dynkin or affine Dynkin, but I don't think it's wild type either since the indecomposables are parametrized by the dimension vector and one continuous parameter (as in a Jordan block). But people say that a quiver is either finite, tame, or wild type. So where should the 1-loop quiver belong?
A:
As you already noticed the $1$-loop quiver should be considered tame as for each dimension you only need one continous parameter to describe its finite dimensional representations. Similarly this is true for the $\tilde{A}_n$-quiver with cyclic orientation.
When one says that a quiver is tame one usually restricts to the case of acyclic quivers. In this case, as you mentioned there is the generalisation of Gabriel's theorem by Donovan-Freislich and Nazarova saying that these are exactly given by the affine Dynkin diagrams. Here, it is implicitly assumed that you don't take the cyclic orientation in type $\tilde{A}_n$.
One problem with the cyclic orientation is that there is in general no tame-wild dichotomy theorem for infinite-dimensional algebras. I'm not sure whether the case of quivers with oriented cycles has already been considered.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to run Spark 1.0 SparkPi on HDP 2.0
I stuck in issue with runing spark PI example on HDP 2.0
I downloaded spark 1.0 pre-build from http://spark.apache.org/downloads.html (for HDP2)
The run example from spark web-site:
./bin/spark-submit --class org.apache.spark.examples.SparkPi --master yarn-cluster --num-executors 3 --driver-memory 2g --executor-memory 2g --executor-cores 1 ./lib/spark-examples-1.0.0-hadoop2.2.0.jar 2
I got error:
Application application_1404470405736_0044 failed 3 times due to AM
Container for appattempt_1404470405736_0044_000003 exited with
exitCode: 1 due to: Exception from container-launch:
org.apache.hadoop.util.Shell$ExitCodeException: at
org.apache.hadoop.util.Shell.runCommand(Shell.java:464) at
org.apache.hadoop.util.Shell.run(Shell.java:379) at
org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:589)
at
org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:195)
at
org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:283)
at
org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:79)
at java.util.concurrent.FutureTask.run(FutureTask.java:262) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744) .Failing this attempt..
Failing the application.
Unknown/unsupported param List(--executor-memory, 2048,
--executor-cores, 1, --num-executors, 3) Usage: org.apache.spark.deploy.yarn.ApplicationMaster [options] Options:
--jar JAR_PATH Path to your application's JAR file (required) --class CLASS_NAME Name of your application's main class (required) ...bla-bla-bla
any ideas? how can I make it works?
A:
I had the same problem.
The reason was that version of spark-assembly.jar, in the hdfs
differs from your current spark version.
For example params list of org.apache.spark.deploy.yarn.Client in hdfs version:
$ hadoop jar ./spark-assembly.jar org.apache.spark.deploy.yarn.Client --help
Usage: org.apache.spark.deploy.yarn.Client [options]
Options:
--jar JAR_PATH Path to your application's JAR file (required in yarn-cluster mode)
--class CLASS_NAME Name of your application's main class (required)
--args ARGS Arguments to be passed to your application's main class.
Mutliple invocations are possible, each will be passed in order.
--num-workers NUM Number of workers to start (Default: 2)
--worker-cores NUM Number of cores for the workers (Default: 1). This is unsused right now.
--master-class CLASS_NAME Class Name for Master (Default: spark.deploy.yarn.ApplicationMaster)
--master-memory MEM Memory for Master (e.g. 1000M, 2G) (Default: 512 Mb)
--worker-memory MEM Memory per Worker (e.g. 1000M, 2G) (Default: 1G)
--name NAME The name of your application (Default: Spark)
--queue QUEUE The hadoop queue to use for allocation requests (Default: 'default')
--addJars jars Comma separated list of local jars that want SparkContext.addJar to work with.
--files files Comma separated list of files to be distributed with the job.
--archives archives Comma separated list of archives to be distributed with the job.
And the same help for latest installed spark-assembly jar file:
$ hadoop jar ./spark-assembly-1.0.0-cdh5.1.0-hadoop2.3.0-cdh5.1.0.jar org.apache.spark.deploy.yarn.Client
Usage: org.apache.spark.deploy.yarn.Client [options]
Options:
--jar JAR_PATH Path to your application's JAR file (required in yarn-cluster mode)
--class CLASS_NAME Name of your application's main class (required)
--arg ARGS Argument to be passed to your application's main class.
Multiple invocations are possible, each will be passed in order.
--num-executors NUM Number of executors to start (Default: 2)
--executor-cores NUM Number of cores for the executors (Default: 1).
--driver-memory MEM Memory for driver (e.g. 1000M, 2G) (Default: 512 Mb)
--executor-memory MEM Memory per executor (e.g. 1000M, 2G) (Default: 1G)
--name NAME The name of your application (Default: Spark)
--queue QUEUE The hadoop queue to use for allocation requests (Default: 'default')
--addJars jars Comma separated list of local jars that want SparkContext.addJar to work with.
--files files Comma separated list of files to be distributed with the job.
--archives archives Comma separated list of archives to be distributed with the job.
so, I updated my spark-assembly.jar into hdfs and spark started working well
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linked list, if element in param in __init__() is iterable, construct new linked llist from it
I have this implementation of linked list,
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class Linked_list:
def __init__(self, llist=None):
self.head = None
self.tail = None
if llist is not None:
for i in llist:
self.append(i)
def add_head(self, data):
self.head = Node(data, self.head)
if self.tail is None:
self.tail = self.head
def append(self, data):
if self.head is None:
self.add_head(data)
else:
self.tail.next = Node(data)
self.tail = self.tail.next
I want to change the __init__() so if the llist parameter contains an iterable element (list, range(), string, tuple, etc.) it will construct a new Linked_list from it. I'm believe recursion is the way to go, but I'm really confused how to implement it inside the __init__(). For example
a = Linked_list([1, 2, Linked_list(range(5)), Linked_list(range(3))])
b = Linked_list([1, 2, list(range(5)), list(range(3))])
c = Linked_list([1, 2, (0, 1, 2, 3, 4), (0, 1, 2)])
a,b,c should return same Linked_list
A:
You could use isinstance() to check the types of the values in llist and act accordingly. The recursion basically comes for free, via the constructor.
from collections import Iterable # Using Python 2.7
class Linked_list:
def __init__(self, llist=None):
... # Same as your code.
if llist is not None:
for i in llist:
if isinstance(i, basestring):
ll = Linked_list()
for c in i:
ll.append(c)
self.append(ll)
elif isinstance(i, Iterable):
self.append(Linked_list(i))
else:
self.append(i)
...
def __repr__(self):
xs = []
nd = self.head
while nd is not None:
xs.append(nd.data)
nd = nd.next
return repr(xs)
a = Linked_list([1, 2, Linked_list(range(5)), Linked_list(range(3))])
b = Linked_list([1, 2, list(range(5)), list(range(3))])
c = Linked_list([1, 2, (0, 1, 2, 3, 4), (0, 1, 2)])
d = Linked_list([1, 2, (0, 1, range(4), 3, 4), (0, 1, [4,5,'abc'])])
print a
print b
print c
print d
Output:
[1, 2, [0, 1, 2, 3, 4], [0, 1, 2]]
[1, 2, [0, 1, 2, 3, 4], [0, 1, 2]]
[1, 2, [0, 1, 2, 3, 4], [0, 1, 2]]
[1, 2, [0, 1, [0, 1, 2, 3], 3, 4], [0, 1, [4, 5, ['a', 'b', 'c']]]]
A:
To test if something is iterable, you can use the abstract base class in the collection.abc module:
isinstance(llist, collection.abc.Iterable)
Note that Python defines a behavior/protocol for iterable objects, it might not be the aim of your exercise but it could be interesting for you to try to conform to it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I run Ruby code on a button click?
I have a Rails partial, and a Ruby script I want to run when I click a button in the partial.
How do I do this?
This is the script I want to run - I have it in <%= %> tags right now.
<%= require 'nokogiri'
doc = Nokogiri::HTML(table_string)
doc.xpath('//table//tr').each do |row|
row.xpath('td').each do |cell|
print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
end
print "\n"
end
%>
I want to have a button that runs that snippet when I click it.
A:
Create a controller
Create an action that will contain the code you want to run
Set up your routes
Ex:
resources :my_resources do
collection do
get :your_action
end
end
And your link should be something like: link_to "text", your_action_my_resources_path.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Passing list/array between JSP pages
I'm trying to pass a List between two JSP pages that I have. This is a list of objects that is of a class that I wrote.
How do I pass this list between JSP pages? request.setAttribute seems to work for strings, but not anything else. And, if this cannot be easily done with a list, I can convert the list to an array and pass it that way, no problem.
A:
The first thing is that a very bad design will lead to such questions as passing lists between different JSP pages. The "nip the evil at the bud" will be to create a separate java class which contains the list and initializes it, then you can access the list at as many jsp pages as you want.
But incase you really want to do, you can put the list in the session.
request.getSession().setAttribute("list",myListObject);
Then on the other page you can get
List<MyType>myListObject=(List<MyType>) request.getSession().getAttribute("list");
And you should clear the list from the session after you do not require it,
request.getSession().removeAttribute("list");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Initiate a bluetooth tether programmatically
The Android bluetooth class is fairly easy to use with regards to enabling, discovering, listing paired devices, and connecting to bluetooth devices.
My plan was to initiate a connection to another bluetooth device that provides tethering via bluetooth.
After a bit of investigation, this doesn't look feasible - it looks like I'd have to implement the profile myself, and have root access to do the networking, and do everything in an app.
There also doesn't seem to be an intent I can trigger via Settings to initiate a bluetooth connection, the best I can do is turn it on.
Am I missing something - if the system doesn't expose a method for initiating a system level bluetooth connection, am I out of luck?
A:
A private profile is already present in the API: BluetoothPan
Bluetooth PAN (Personal Area Network) is the correct name to identify tethering over Bluetooth.
This private class allows you to connect to and disconnect from a device exposing the PAN Bluetooth Profile, via the public boolean connect(BluetoothDevice device) and public boolean disconnect(BluetoothDevice device) methods.
Here is a sample snippet connecting to a specific device:
String sClassName = "android.bluetooth.BluetoothPan";
class BTPanServiceListener implements BluetoothProfile.ServiceListener {
private final Context context;
public BTPanServiceListener(final Context context) {
this.context = context;
}
@Override
public void onServiceConnected(final int profile,
final BluetoothProfile proxy) {
Log.e("MyApp", "BTPan proxy connected");
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("AA:BB:CC:DD:EE:FF"); //e.g. this line gets the hardware address for the bluetooth device with MAC AA:BB:CC:DD:EE:FF. You can use any BluetoothDevice
try {
Method connectMethod = proxy.getClass().getDeclaredMethod("connect", BluetoothDevice.class);
if(!((Boolean) connectMethod.invoke(proxy, device))){
Log.e("MyApp", "Unable to start connection");
}
} catch (Exception e) {
Log.e("MyApp", "Unable to reflect android.bluetooth.BluetoothPan", e);
}
}
@Override
public void onServiceDisconnected(final int profile) {
}
}
try {
Class<?> classBluetoothPan = Class.forName(sClassName);
Constructor<?> ctor = classBluetoothPan.getDeclaredConstructor(Context.class, BluetoothProfile.ServiceListener.class);
ctor.setAccessible(true);
Object instance = ctor.newInstance(getApplicationContext(), new BTPanServiceListener(getApplicationContext()));
} catch (Exception e) {
Log.e("MyApp", "Unable to reflect android.bluetooth.BluetoothPan", e);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why does'nt my js code reflect the right runtime value?
When I run this code (under a <script> code)
window.msg = { a: 0}
var b = window.msg;
function g()
{
console.log(b)
}
msg = { a: 1};
g()
in the console - I get {a: 0} .
why is that ? I thought that msg = { a: 1}; will update the reference...
A:
If you change your code to:
window.msg = { a: 0}
var b = window.msg;
function g()
{
console.log(b)
}
msg.a = 1; // this line is changed
g()
You will get {a:1}.
You're reassigning msg so b just points to the old value of msg.
b does not reference window.msg but the {a:0} object.
A:
You're are creating the object { a: 0 }, and assigning a reference to that object to msg and b. Later, you're creating a new object { a: 1 }, and assigning a reference to that object to msg, but b is still referencing the original object:
window.msg = { a: 0} // msg --> { a: 0 }, b --> undefined
var b = window.msg; // msg --> { a: 0 }, b --> { a: 0 }
msg = { a: 1}; // msg --> { a: 1 }, b --> { a: 0 }
g() // prints b --> { a: 0 }
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the origin of the term "woo"?
On the Skeptics StackExchange you quite often read users referring to certain things and practices as "woo".
What is the origin of this word? How did it come to be synonymous with skeptics?
A:
"Woo" (or "WooWoo") seems to refer to the types of "magical thinking" that skeptics love to, well, be skeptical about.
From Respectful Insolence, this thought on its origins:
Finally, regarding the etymology, I tried to look into that a bit. I do know that The origin of "woo woo" is lost in the mists of time (well, at least decades) of time. I've seen suggestions that it comes from the "woooooo" noise that a Theramin used to make in old horror or science fiction movies. I've also seen suggestions that it somehow derives from the music in the theme to The Twilight Zone. Whatever the etymology, the term can, as far as I can tell, only be traced back to around 1986, at least in print, although I'd be shocked if the term wasn't in use long before that. However, I can't remember having heard the term until more recently, within the last few years. Maybe I was just sheltered.
Personally, +1 on the Theremin idea.
A:
from http://www.skepdic.com/woowoo.html:
woo-woo
Woo-woo (or just plain woo) refers to ideas considered irrational or based on extremely flimsy evidence or that appeal to mysterious occult forces or powers.
Here's a dictionary definition of woo-woo:
adj. concerned with emotions, mysticism, or spiritualism; other than rational or scientific; mysterious; new agey. Also n., a person who has mystical or new age beliefs.
When used by skeptics, woo-woo is a derogatory and dismissive term used to refer to beliefs one considers nonsense or to a person who holds such beliefs.
Sometimes woo-woo is used by skeptics as a synonym for pseudoscience, true-believer, or quackery. But mostly the term is used for its emotive content and is an emotive synonym for such terms as nonsense, irrational, nutter, nut, or crazy.
See also discussion on The Lippard Blog re: a 1984 citation:
THE NEW AGE SOUND: SOOTHING MUSIC BY SINCERE ARTISTS
Philadelphia Inquirer, The (PA) - Sunday, October 21, 1984
So who is this New Age audience? Mostly upscale folks in their 30s and early 40s, the ones weaned on Baba Ram Dass and Woodstock and hallucinogenics, macrobiotic diets and transcendental meditation.
.....
George Winston, who practices yoga and who currently has three albums on the jazz charts (his five Windham Hill recordings have reportedly sold more than 800,000 copies; his LP December has just been certified gold), has jokingly called this crowd the "woo-woos." In a 1983 interview in New Age Journal, Winston, asked if he knew who comprised his audience, answered that there were some classical fans, some jazz, some pop and "all the woo-woos."
"You know," he added, "there's real New Age stuff that has substance, and then there's the woo-woo . A friend of mine once said, 'George, you really love these woo-woos, don't you?' and I said 'Yes, I do love them,' and I do. I mean, I'm half woo-woo myself."
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Twitter Bootstrap nav nav-tabs don't change on click
I like how the nav-tabs looks so I want to use it. This is how the web application looks right now:
Unfortunately, if I click on other tab (for example "Buscar alojamiento"), the active tab doesn't change. This is my code:
<ul class="nav nav-tabs">
<li>
<g:link controller="usuario" action="show">
<g:message code="nav.usuario.show" default="Datos del usuario" />
</g:link>
</li>
<li class="active">
<a href="${createLink(uri: '/')}">
<g:message code="nav.home" default="Página de inicio" />
</a>
</li>
<li>
<g:link controller="alojamiento" action="show">
<g:message code="nav.alojamiento.show" default="Buscar alojamiento" />
</g:link>
</li>
</ul>
I also try removing class="active". No tab is active ever doing that.
A:
Check the "Tabbable Nav" example in the Twitter Bootstrap Components. You must have the correct html to this work. Example:
<ul class="nav nav-tabs">
<li class="active">
<a href="#home" data-toggle="tab">Home</a>
</li>
<li><a href="#other" data-toggle="tab">Other</a></li>
<li><a href="#">...</a></li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane active">
<p>Home</p>
</div>
<div id="other" class="tab-pane">
<p>Other</p>
</div>
</div>
See the class applied and the href of the links.
UPDATE
As we have discussed in the comments, we also can change it with Javascript:
<script type="text/javascript">
...
document.getElementById("home").setAttribute("class","active")
Or JQuery:
$('#home').attr('class','active')
A:
You would need Tabbable Nav to toggle between the contents of each tab.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Help building electric generator?
I am in the process of building an electric generator for the first time, and I have found out most of what I need to do, except the following things.
Can I have 2 rows of magnets linked together side by side spinning around the stator?
a. If possible does this change the recommended size of the inner diameter of my coil? (I read it's suppose to be about the width of my magnet)
This is the type of generator i'm building. >https://www.youtube.com/watch?v=yuKKrVlilVk
Right at the beginning the video shows a rotor with 1 row of magnets going around it. I am wondering if I can add another row of magnets side by side going around the wheel.
So the wheel would look like this.
+-+-+-+-+-+-+-+-+-
-+-+-+-+-+-+-+-+-+
I am wondering if a positive and negative going across the wire at the same time would like cancel each other out or something.
A:
You can add more magnets, but they have to be aligned with the first row, meaning if the first row is +-+-, after adding the second row it should look like
+-+-
+-+-
This increases the strength of the magnetic field, which means more electricity is generated.
Alternatively, you could use stronger magnets, which will accomplish the same thing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Best practice for running maintenance updates in Firestore?
Sometimes I need to run maintenance queries, like backfilling data of a new field I just created. How do I do this easily?
Firebase Functions seems targeted towards triggering on certain keywords or on certain schedules.
Basically, whatever I would do in MongoDB's terminal at will, I'd like to do in Firestore easily (even if I have to deploy code).
A:
There is no set of "best practices" per se, but you can easily write programs to access Firebase and Google Cloud resources from your desktop. Just do some web searches for the server SDKs that provide access (there are many for different languages), and initialize them with a service account that has access to write data in the project.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to save `None` value in a dict to redis in Python?
I am using redis==3.3.8 in my python application to talk with redis. And I use redis.mset to save a python dict on redis. However, I got this error if there is a None value in my dict:
redis.exceptions.DataError: Invalid input of type: 'NoneType'. Convert to a byte, string or number first..
I wonder how I can save None value into redis without converting?
A:
You need to decide what is an appropriate null value in your case.
An empty string, '', may work for you.
data = {
'key1': 'value1',
'key2': None,
}
# convert None to ''
converted_data = {}
for k, v in data.items():
converted_data[k] = v if v is not None else ''
REDIS.mset(converted_data)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cakephp routing with optional params
I have a method in my users controller similar to:
function members($type = null, $category = null) { ... }
Both params are optional and can be used together or on their own.
So with the following route.
Router::connect('/members/*', array('controller' => 'users', 'action' => 'members'));
http://example.com/users/members successfully becomes http://example.com/members.
Unfortunately the following don't work
http://example.com/members/type:cat
http://example.com/members/category:dog
http://example.com/members/type:cat/category:dog
how could I set up my routes so that they all work properly?
A:
Named parameters aren't automagicaly mapped to the action. You can either get them by calling
$this->passedArgs['type'] or $this->passedArgs['category']
or by using the 3rd parameter in the Router::connect:
Router::connect(
'/members/*',
array('controller' => 'users', 'action' => 'members'),
array(
'pass' => array('type', 'category')
)
);
http://book.cakephp.org/view/46/Routes-Configuration
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Building a toolchain with cmake to cross-compile for android
gcc (GCC) 4.8.1
android-ndk-r9
Hello,
My host machine is Fedora 19 and I want to create a tool-chain for compiling programs to run on android, later I want to extend this for iOS.
I get the following error:
Check for working C compiler: /opt/ndk/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc -- broken
I am not sure why I am getting this error, as everything has been installed. I have also installed binutils-arm-linux-gnu. However, this is my first time do this type of thing, so many I have got something mixed up.
I am trying to create a toolchain file using cmake to croos-compile to run libraries on an android device.
I have installed the android-ndk-r9 in the following location with the path to the compiler:
/opt/ndk/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin
arm-linux-androideabi-addr2line
arm-linux-androideabi-ar
arm-linux-androideabi-as
arm-linux-androideabi-c++
arm-linux-androideabi-c++filt
arm-linux-androideabi-cpp
arm-linux-androideabi-elfedit
arm-linux-androideabi-g++
arm-linux-androideabi-gcc
arm-linux-androideabi-gcc-4.8
arm-linux-androideabi-gcc-ar
arm-linux-androideabi-gcc-nm
arm-linux-androideabi-gcc-ranlib
arm-linux-androideabi-gcov
arm-linux-androideabi-gdb
arm-linux-androideabi-gprof
arm-linux-androideabi-ld
arm-linux-androideabi-ld.bfd
arm-linux-androideabi-ld.gold
arm-linux-androideabi-ld.mcld
arm-linux-androideabi-nm
arm-linux-androideabi-objcopy
arm-linux-androideabi-objdump
arm-linux-androideabi-ranlib
arm-linux-androideabi-readelf
arm-linux-androideabi-run
arm-linux-androideabi-size
arm-linux-androideabi-strings
arm-linux-androideabi-strip
My cross-compile file is:
include(CMakeForceCompiler)
set(toolchain_path /opt/ndk/toolchains)
# Target system
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
set(CMAKE_SYSTEM_VERSION 1)
# Compiler to build for the target
set(CMAKE_C_COMPILER /opt/ndk/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc)
set(CMAKE_FIND_ROOT_PATH /opt/ndk/toolchains)
I run this from my build/debug directory with my toolchain being in the root directory.
[ant@localhost debug]$ cmake -DCMAKE_TOOLCHAIN_FILE=arm-eabi-gcc.cmake ../..
Output
-- The C compiler identification is GNU 4.8.0
-- Check for working C compiler: /opt/ndk/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc
-- Check for working C compiler: /opt/ndk/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc -- broken
CMake Error at /usr/share/cmake/Modules/CMakeTestCCompiler.cmake:61 (message):
The C compiler
"/opt/ndk/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc"
is not able to compile a simple test program.
It fails with the following output:
Change Dir: /home/steve/mobile_progs/linux_pjsip/build/debug/CMakeFiles/CMakeTmp
Run Build Command:/usr/bin/gmake "cmTryCompileExec379796592/fast"
/usr/bin/gmake -f CMakeFiles/cmTryCompileExec379796592.dir/build.make
CMakeFiles/cmTryCompileExec379796592.dir/build
gmake[1]: Entering directory
`/home/steve/mobile_progs/linux_pjsip/build/debug/CMakeFiles/CMakeTmp'
/usr/bin/cmake -E cmake_progress_report
/home/steve/mobile_progs/linux_pjsip/build/debug/CMakeFiles/CMakeTmp/CMakeFiles
1
Building C object
CMakeFiles/cmTryCompileExec379796592.dir/testCCompiler.c.o
/opt/ndk/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc
-o CMakeFiles/cmTryCompileExec379796592.dir/testCCompiler.c.o -c
/home/steve/mobile_progs/linux_pjsip/build/debug/CMakeFiles/CMakeTmp/testCCompiler.c
Linking C executable cmTryCompileExec379796592
/usr/bin/cmake -E cmake_link_script
CMakeFiles/cmTryCompileExec379796592.dir/link.txt --verbose=1
/opt/ndk/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/arm-linux-androideabi-gcc
CMakeFiles/cmTryCompileExec379796592.dir/testCCompiler.c.o -o
cmTryCompileExec379796592 -rdynamic
/opt/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.8/../../../../arm-linux-androideabi/bin/ld:
error: cannot open crtbegin_dynamic.o: No such file or directory
/opt/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.8/../../../../arm-linux-androideabi/bin/ld:
error: cannot open crtend_android.o: No such file or directory
/opt/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.8/../../../../arm-linux-androideabi/bin/ld:
error: cannot find -lc
/opt/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.8/../../../../arm-linux-androideabi/bin/ld:
error: cannot find -ldl
collect2: error: ld returned 1 exit status
gmake[1]: *** [cmTryCompileExec379796592] Error 1
gmake[1]: Leaving directory
`/home/steve/mobile_progs/linux_pjsip/build/debug/CMakeFiles/CMakeTmp'
gmake: *** [cmTryCompileExec379796592/fast] Error 2
CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
CMakeLists.txt:4 (project)
Many thanks in advance,
A:
I managed to solve the problem by first going to this website:
http://developer.android.com/tools/sdk/ndk/index.html
There is an example of using the standalone toolchain that comes with NDK.
make-standalone-toolchain.sh --toolchain=arm-linux-androideabi-4.8
Extracted the into my /opt directory.
And using this sample toolchain cmake file
# Target system
set(CMAKE_SYSTEM_NAME Android)
set(CMAKE_SYSTEM_VERSION 1)
# Compiler to build for the target
set(CMAKE_C_COMPILER /opt/arm-linux-androideabi-4.8/bin/arm-linux-androideabi-gcc)
set(CMAKE_CXX_COMPILER /opt/arm-linux-androideabi-4.8/bin/arm-linux-androideabi-g++)
Everything just worked after that. However, I couldn't get my previous problem working. Maybe I have set some environmental variables incorrectly to the wrong paths.
Hope this helps someone else.
A:
Why you don't try this android-cmake. I still use this script and it works fairly well. If that approach does not fit your needs, you could use it as an inspiration anyway :-) .
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ember data Error while loading route: TypeError: undefined is not a function
I'm trying to use ember data to get json data from my rails backend. Here's the app.js
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:3000',
buildURL: function(record, suffix) {
console.log(this._super(record, suffix) +'.json');
return this._super(record, suffix) + '.json';
}
});
App.Router.map(function() {
this.resource('posts', { path: '/' }, function() {
this.resource('post', { path: ':post_id' });
});
});
App.PostRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('post', params.post_id);
}
});
App.PostsRoute = Ember.Route.extend({
model: function() {
return this.store.find('post');
}
});
App.Post = Ember.Object.extend({
title: DS.attr('string'),
body: DS.attr('string'),
created_at: DS.attr('date'),
updated_at: DS.attr('date')
});
and here's the data being returned by /posts.json
{
"posts":[
{
"id": 1,
"title": "Some Title",
"body": "Some text",
"created_at": "2014-05-04T22:25:35.578Z",
"updated_at": "2014-05-04T22:25:35.578Z"
},
{
"id": 2,
"title": "Some Title",
"body": "Some text",
"created_at": "2014-05-04T22:25:35.578Z",
"updated_at": "2014-05-04T22:25:35.578Z"
}
]
}
The this.store.find('post') seems to not be working, but I'm not sure why. After looking through docs and a few tutorials I don't see the problem with the code. here's the error I'm getting.
Error while loading route: TypeError: undefined is not a function
at Ember.Object.extend.applyTransforms (http://localhost:3000/assets/ember-data.min.js:9:15567)
at Ember.Object.extend.normalize (http://localhost:3000/assets/ember-data.min.js:9:15707)
at superFunction [as _super] (http://localhost:3000/assets/ember-1.5.1.js:7724:16)
at d.extend.normalize (http://localhost:3000/assets/ember-data.min.js:9:18220)
at superWrapper [as normalize] (http://localhost:3000/assets/ember-1.5.1.js:1293:16)
at null.<anonymous> (http://localhost:3000/assets/ember-data.min.js:9:19505)
at Array.map (native)
at d.extend.extractArray (http://localhost:3000/assets/ember-data.min.js:9:19474)
at superWrapper (http://localhost:3000/assets/ember-1.5.1.js:1293:16)
at Ember.Object.extend.extractFindAll (http://localhost:3000/assets/ember-data.min.js:9:16821)
A:
You're model is extending the wrong object, I don't see any other obvious errors.
Incorrect
App.Post = Ember.Object.extend({
title: DS.attr('string'),
body: DS.attr('string'),
created_at: DS.attr('date'),
updated_at: DS.attr('date')
});
Correct
App.Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
created_at: DS.attr('date'),
updated_at: DS.attr('date')
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
unable to to locate package apt-fast
This is what I tried:
$ sudo add-apt-repository ppa:apt-fast/stable
$ sudo apt-get update
..........something something.........
.................................................................
.................................................................
W: Failed to fetch http://ppa.launchpad.net/apt-fast/stable/ubuntu/dists/trusty/main/binary-amd64/Packages 404 Not Found
W: Failed to fetch http://ppa.launchpad.net/apt-fast/stable/ubuntu/dists/trusty/main/binary-i386/Packages 404 Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.
I then tried
$ sudo apt-get install apt-fast
but it says:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package apt-fast
A:
add it as you did before and then :
open system settings-> software updates-> other software
look for the ppa that was added. Click it and then select edit. Change the distribution from trusty to saucy. Exit and open a terminal.
sudo apt-get update
and then
sudo apt-get install apt-fast
A:
The PPA manager hasn't uploaded any packages for Trusty yet (as evidenced by the two "Failed to fetch" errors). Therefore, apt can't find apt-fast because the package isn't available yet.
You might want to contact the PPA maintainer and ask him to upload a version for Trusty.
I've made a version for Trusty, which you can use from my PPA.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I split a method across two cs files?
I have .cs that is over 33K lines long. Whenever this file is open Visual Studio slows down tremendously and occasionally momentarily freezes. All this class is is a dictionary initialization.
Is there some way to split my Initialize() method across multiple .cs?
A:
If your class simply acts as storage for a bunch of different dictionary items, you may want to consider storing those items in a file instead. You could store that file in the assembly as a .txt or .xml file. That way, you could edit the file and have your program load the data at runtime.
Simply create a new file in your solution and set it to "Embedded Resource", then load the data into your class instead.
For more information on embedded resources, see https://support.microsoft.com/en-us/kb/319292.
A:
It sounds like you need to break your method into smaller chunks. Our team tends to keep methods around one screen in length, which is about 50-60 lines max. You can call other methods that will in turn call other methods, but it sounds like you have way too much happening in a sinlge method.
You can split a class across multiple files by using the partial keyword:
// file Test1.cs
public partial class Test{} //...
// file Test2.cs
public partial class Test{} //...
As long as they are in the same namespace, an instance of the class would have all the methods declared in both files.
https://msdn.microsoft.com/en-us/library/wa80x488.aspx
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to add different base templates for different languages of same page in django cms
How can i add different base templates for different languages of same page in django cms?
I am trying to set a page and show it in different languages. And for all the languages, i need to use a different base template.
I am completely new django cms. Please help.
A:
You need to create different page trees per language.
Every page has only one template. Use {% trans %} and {% blocktrans %} for translating string in it. Or {% if request.LANGUAGE == "en" %}.
If the templates really differ that much: don't add other languages to pages... but create different page trees with only one language.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VBA code to re-name a text file, execute a macro, then repeat (for all files in the folder)
I am very new to VBA, so please be patient. I need to to re-name .txt files in a folder to a file name that never changes (it is linked as a table in Access). Run a macro that scrapes data into another table, then repeat the process for all the files in the folder (loop). The code below renames the 1st file and runs the macro, but that is as far as I get. It does not loop correctly. Any help is greatly appreciated!
Function process()
Dim tmp As String
tmp = Dir("C:\Users\Calhoun\Documents\REPORTING\Correspondence\*.txt")
Do While tmp > ""
If Len(Dir("C:\Users\Calhoun\Documents\REPORTING\Correspondence\STATIC_FILE_NAME.txt")) <> 0 Then
Kill "C:\Users\Calhoun\Documents\REPORTING\Correspondence\STATIC_FILE_NAME.txt"
End If
Name "C:\Users\Calhoun\Documents\REPORTING\Correspondence\" & tmp As "C:\Users\Calhoun\Documents\REPORTING\Correspondence\STATIC_FILE_NAME.txt"
DoCmd.RunMacro "RunQueries"
tmp = Dir
Loop
End Function
A:
Your Adhok solution is
Function process()
'
Dim tmp As String
tmp = Dir("C:\Users\Calhoun\Documents\REPORTING\Correspondence\*.txt")
Do While tmp > ""
on error resume next
Kill "C:\Users\Calhoun\Documents\REPORTING\Correspondence\STATIC_FILE_NAME.txt"
On Error Goto 0
Name "C:\Users\Calhoun\Documents\REPORTING\Correspondence\" & tmp As "C:\Users\Calhoun\Documents\REPORTING\Correspondence\STATIC_FILE_NAME.txt"
DoCmd.RunMacro "RunQueries"
tmp = Dir
Loop
End Function
Using Dir inside the loop breaks the Dir outside the loop as Mathieu Guindon mentiond in comment
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Perl/CGI form checking
This is my first attempt at CGI (I know some Perl) but i'm falling on my face.
I want to enter a form and check it - but the check section isn't seeing the submitted values at all.
I am running this directly as http://example/cgi-bin/formcheck.cgi - there is no HTML calling this.
I suspect it's running, dropping out the bottom and then running from scratch whenever a button is pressed. I'm not sure though. Here's my code:
#!/usr/bin/perl -w
use strict; # let's tighten things up
use CGI ':standard';
use CGI::Carp qw(fatalsToBrowser);
print header;
print start_html("form check");
print "<h1>form check</h1>\n";
print_questions();
print_checks();
print "<hr>\n";
print end_html;
sub print_questions {
if ( !defined(param('action')) || param('action') eq 'New' ) {
my $p = int(rand(10)); # fix error under strict
my $q = int(rand(10)); # fix error under strict
my $i = 0; # fix error under strict
my @question = ''; # fix error under strict
my @answer = ''; # fix error under strict
$question[$i] = "$p X $q =";
$answer[$i] = $p * $q;
print start_form;
print "$question[$i]";
print textfield(-name=>'response',-default=>'',-size=>3);
print "<p>";
print submit('action','New');
print submit('action','Check');
print end_form;
print "<p>";
param(-name=>'question',-value=>@question);
param(-name=>'answer',-value=>@answer);
print "<hr>\n";
}
}
sub print_checks {
if ( param('action') eq 'Check' ) {
my $errors = 0; # fix error under strict
my $i = 0; # fix error under strict
my @question = param('question'); # fix error under strict
my @answer = param('answer'); # fix error under strict
my @response = param('response'); # fix error under strict
if ( $answer[$i] != $response[$i] ) {
$errors++;
print "<font color=#FF0000>";
} else {
print "<font color=#00FF00>";
}
print "$question[$i] = $answer[$i]";
print "</font>";
print "<p>";
print start_form;
print submit('action','New');
print end_form;
print "<p>";
print "<hr>\n";
if ($errors == 0) {
print "CORRECT!<br>";
} else {
print "NOPE!<br>";
}
}
}
Any help greatly appreciated
A:
Ok, read your code again:
You set an question and answer parameter, but they do not have
any representation in the form. You need a hidden()-field to
preserve them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does it hurt the next day after doing significant exercise?
I think this is a fairly common observation that if one does some significant amount of exercise, he/she may feel alright for the rest of the day, but it generally hurts bad the next day. Why is this the case?
I would expect that if the muscles have undergone significant strain (say I started pushups/plank today), then it should cause pain while doing the strenuous activity, or during rest of the day, but it happens often that we don't feel the pain while doing the activity or even on that day, but surely and sorely feel it the next day.
Another example - say after a long time, you played a long game of basketball/baseball/cricket. You generally don't feel any pain during the game/that day, but there is a good chance it will hurt bad the next day.
I am trying to understand both - why does the pain not happen on that day, and why it does, the next day (or the day after that).
A:
Unlike the conventional wisdom, the pain you feel the next day (after a strenuous exercise) has nothing to do with lactic acid.
Actually, lactic acid is rapidly removed from the muscle cell and converted to other substances in the liver (see Cori cycle). If you start to feel your muscles "burning" during exercise (due to lactic acid), you just need to rest for some seconds, and the "burning" sensation disappears.
According to Scientific American:
Contrary to popular opinion, lactate or, as it is often called, lactic acid buildup is not responsible for the muscle soreness felt in the days following strenuous exercise. Rather, the production of lactate and other metabolites during extreme exertion results in the burning sensation often felt in active muscles. Researchers who have examined lactate levels right after exercise found little correlation with the level of muscle soreness felt a few days later. (emphasis mine)
So if it's not lactic acid, what is the cause of the pain?
What you're feeling in the next day is called Delayed Onset Muscle Soreness
(DOMS).
DOMS is basically an inflammatory process (with accumulation of histamine and prostaglandins), due to microtrauma or micro ruptures in the muscle fibers. The soreness can last from some hours to a couple of days or more, depending on the severity of the trauma (see below).
According to the "damage hypothesis" (also known as "micro tear model"), microruptures are necessary for hypertrophy (if you are working out seeking hypertrophy), and that explains why lifting very little weight doesn't promote hypertrophy.
However, this same microtrauma promotes an inflammatory reaction (Tiidus, 2008). This inflammation can take some time to develop (that's why you normally feel the soreness the next day) and, like a regular inflammation, has as signs pain, edema and heat.
This figure from McArdle (2010) shows the proposed sequence for DOMS:
Figure: proposed sequence for delayed-onset muscle soreness. Source:
McArdle (2010).
As anyone who works out at the gym knows, deciding how much weight to add to the barbell can be complicated: too little weight promotes no microtrauma, and you won't have any hypertrophy. Too much weight leads to too much microtraumata, and you'll have trouble to get out of the bed the next day.
EDIT: This comment asks if there is evidence of the "micro tear model" or "damage model" (also EIMD, or Exercise-induced muscle damage). First, that's precisely why I was careful when I used the term hypothesis. Second, despite the matter not being settled, there is indeed evidence supporting EIMD. This meta-analysis (Schoenfeld, 2012) says:
There is a sound theoretical rationale supporting a potential role for EIMD in the hypertrophic response. Although it appears that muscle growth can occur in the relative absence of muscle damage, potential mechanisms exist whereby EIMD may enhance the accretion of muscle proteins including the release of inflammatory agents, activation of satellite cells, and upregulation of IGF-1 system, or at least set in motion the signaling pathways that lead to hypertrophy.
The same paper, however, discuss the problems of EIMD and a few alternative hypotheses (some of them not mutually exclusive, though).
Sources:
Tiidus, P. (2008). Skeletal muscle damage and repair. Champaign: Human Kinetics.
McArdle, W., Katch, F. and Katch, V. (2010). Exercise physiology. Baltimore: Wolters Kluwer Health/Lippincott Williams & Wilkins.
Roth, S. (2017). Why Does Lactic Acid Build Up in Muscles? And Why Does It Cause Soreness?. [online] Scientific American. Available at: https://www.scientificamerican.com/article/why-does-lactic-acid-buil/ [Accessed 22 Jun. 2017].
Schoenfeld, B. (2012). Does Exercise-Induced Muscle Damage Play a Role in Skeletal Muscle Hypertrophy?. Journal of Strength and Conditioning Research, 26(5), pp.1441-1453.
A:
It should be noted that in some people (somewhere between 1% and 3% of the population, depending on who's counting) there is another mechanism for delayed muscle pain. Myoadenylate Deaminase Deficiency (MADD) is a genetic condition whose primary symptom is pain and cramping with an onset about 36 hours after moderately intense exercise. The pain often persists (due to muscle damage), resulting in a "pulled muscle" sensation which lasts for weeks or months.
The condition is caused by a genetic defect which causes the AMP<=>ATP recycling mechanism in the muscles to "leak" AMP into the bloodstream, weakening the muscles' ability to continue exercise.
Significant relief of symptoms is often achieved by taking D-ribose orally.
And another somewhat rarer genetic disorder which can result in muscle pain is McArdle's Disease.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Html Attributes on EditorFor() or Check dataType in EditorTemplate
I have a class with a property Password annotated as DataType.Password like this:
[DataType(DataType.Password)]
[Required]
public string Password { get; set; }
When I use EditorFor to show this field on the view, I need to apply a CSS class on it.
I do it the following way:
@Html.EditorFor(model => model.Password, "loginTextBox", new { @class = "form-control ", placeholder = "" })
For some reason there's no build-in way of using Html attributes for EditorFor() (like I could read here for example: Html attributes for EditorFor() in ASP.NET MVC), so I needed to create a simple EditorTemplate to allow it like this:
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = ViewData["class"], id = ViewData["id"], placeholder = ViewData["placeholder"]})
The problem is that, this editor is shared between other properties which are not DataType.Password. In the case the property is annotated as DataType.Password I want to use
@Html.Password(...)
otherwise
@Html.TextBox(...)
The only way I can think to achieve this is by checking the DataType, but I don't how to do that.
Any idea on how to check the DataType or even a better approach?
A:
Now ASP.Net MVC 5.1 supports htmlAttributes for EditorFor. Just pass this as an anonymous object.
ASP.Net MVC 5.1 Release Notes
@Html.EditorFor(model => model.Password, "loginTextBox",
new { htmlAttributes = new { @class = "form-control ", placeholder = ""})
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Object properties dynamic delete
I am curious about an improved way to dynamically delete properties from a javascript object based on wildcards. Firstly, suppose I have the following object:
object =
{
checkbox_description_1 : 'Chatoyant',
checkbox_description_2 : 'Desultory',
random_property : 'Firefly is a great program',
checkbox_mood_1 : 'Efflorescent',
checkbox_description_3 : 'Ephemeral'
}
Task
Now, the end result is to have removed all properties under the guise of
'checkbox_description' and leave the rest of the object intact as shown:
object =
{
random_property : 'Firefly is a great program',
checkbox_mood_1 : 'Efflorescent',
}
My solution
At present my solution involves jquery and the following code:
var strKeyToDelete = 'checkbox_description'
/* Start looping through the object */
$.each(object, function(strKey, strValue) {
/* Check if the key starts with the wildcard key to delete */
if(this.match("^"+strKey) == strKeyToDelete) {
/* Kill... */
delete object[strKey];
};
});
Issue
Something about this seems very inelegant to me and if the object were to be of reasonable size very process intensive. Is there a better way of performing this operation?
A:
This is the bare minimum required:
function deleteFromObject(keyPart, obj){
for (var k in obj){ // Loop through the object
if(~k.indexOf(keyPart)){ // If the current key contains the string we're looking for
delete obj[k]; // Delete obj[key];
}
}
}
var myObject = {
checkbox_description_1 : 'Chatoyant',
checkbox_description_2 : 'Desultory',
random_property : 'Firefly is a great program',
checkbox_mood_1 : 'Efflorescent',
checkbox_description_3 : 'Ephemeral'
};
deleteFromObject('checkbox_description', myObject);
console.log(myObject);
// myObject is now: {random_property: "Firefly is a great program", checkbox_mood_1: "Efflorescent"};
So that's pretty close to the jQuery function you have.
(Though a little faster, considering it doesn't use jQuery, and indexOf instead of match)
So, what's with the ~ before indexOf?
indexOf returns a integer value: -1 if the string is not found, and a index, starting from 0, if it is found. (So always a positive integer if found)
~ is a bitwise NOT, that inverts this output. As it happens to be, the inverted output of indexOf is just what we need to indicate "found" or "not found".
~-1 becomes 0, a false-ish value.
~x, where x is 0 or postitive, becomes -(x+1), a true-ish value.
This way, ~string.indexOf('needle') acts like string.contains('needle'), a function that we don't have in JavaScript.
Additionally, you could add a double boolean not (!!) in front of the ~, to convert the true-ish or false-ish output to a real true / false, but that's not necessary in JavaScript.
Functionally, ~string.indexOf('needle') and !!~string.indexOf('needle') are equal.
In case you specifically need the key to begin with the needle, replace the:
~k.indexOf(keyPart)
With:
k.indexOf(keyPart) === 0
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Make HAProxy forward requests to a hostname instead of IP address.
I have 3 virtual hosts on a single IP address.Host_a, Host_b and Host_c all mapping to 192.168.1.10.
My HAProxy configuration is as follows:
frontend http
.
.
.
acl host_one path_end -i /ABC/application
acl host_two path_end -i /XYZ/application
acl host_three path_end -i /PQR/application
use_backend be_host1 if host_one
use_backend be_host2 if host_two
use_backend be_host3 if host_three
backend be_host1
server channel Host_a
backend be_host2
server channel Host_b
backend be_host3
server channel Host_c
Now for example, HAproxy forwards request to 192.168.1.10/ABC/application in case it matches an incoming URL ending with /ABC/application. Is there a way I could forward it to http://Host_a/ABC/application instead ? It is important for me that they use the hostname instead of its corresponding IP address.
A:
The hostname is a part of the HTTP request, and that means you can use the HAProxy option reqirep to set it to whatever you want.
reqirep ^Host: Host:\ Host_a
You can use this type of option in all three of your backends.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C Pointer Equivalence in Java
I wanted to know what the Java translation of this block of C code would be.
Person * father = malloc(sizeof(Person));
Marriage * marriage = malloc(sizeof(Marriage));
(* marriage).male = father;
I'm guessing I use reference. So instead of making a variable father point to Person I just make a father object for the class Person like this:
Person father = new Person();
I might be wrong on this.
How would the line (* marriage).male = father; work?
I'm quite new to C and I am just trying to get a better understanding of how it works.
A:
That would be a mere marriage.male = father; in Java.
(*marriage).male is equivalent to marriage->male in C. marriage is a pointer to a memory location, similar to a reference to an object created with new in Java.
Also, note that while in a certain sense those can be associated with Java constructs, they are certainly no "equivalents." Java has a garbage collector, for one. C doesn't. Java is interpreted. C isn't. There's a lot of subtle differences, so I would never say that anything in C is anywhere equivalent to any Java.
Instead of learning C by equating it with Java, read a book explicitly about C. There are articles like "C for Java programmers" that might be a better entrance for you. However, don't really equate Java with C at all, that just leads to bad stuff.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to answer someone else's phone?
I am in a Japanese office setup sitting next to my boss. He often gets phone calls but most of the time he is not in his seat. How do I answer his phone say that "This is Mr. XX's seat and this is YY (my name) talking and Mr.XX is not in his place" in Japanese?
A:
I've found answering the phone at work follows a fairly fixed pattern.
I would answer the phone with something along the lines of:
株式会社ZのYYと申{もう}します。
This is company Z, MR Y speaking.
or just with the company name.
株式会社Zでございます。
This is company Z.
After they introduce themselves and said their "お世話になっております". You generally reply with something similar :
お世話{せわ}になっております。
If they ask for someone who is away from their seat (but probably return soon) you can say something like:
申{もう}し訳{わけ}ないですがXXさんは席{せき}を外{はず}しておりますが...
I'm very sorry but he has left his seat...
At that point they will either ask when he will be back, or say they will call back later.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where does this session come from?
I have a header.html which start with session_start();.
Then the following code, $_SESSION['cart'][$sw_id] is not set, but suddenly came out.
Q1. Can you start session in this way?
Q2. How come you can increment quantity of purchase with $_SESSION['cart'][$sw_id]++?
It seems to me incrementing id number.
<?php # Script 5.7 - cart.php
/*
* This is the shopping cart page.
* This page has two modes:
* - add a product to the cart
* - update the cart
* The page shows the cart as a form for updating quantities.
*/
// Require the configuration file before any PHP code:
require_once ('./includes/config.inc.php');
// Include the header file:
$page_title = 'Shopping Cart';
include_once ('./includes/header.html');
echo '<h1>View Your Shopping Cart</h1>';
// This page will either add to or update the
// shopping cart, based upon the value of $_REQUEST['do'];
if (isset($_REQUEST['do']) && ($_REQUEST['do'] == 'add') ) { // Add new item.
if (isset($_GET['sw_id'])) { // Check for a product ID.
// Typecast to an integer:
$sw_id = (int) $_GET['sw_id'];
// If it's a positive integer,
// get the item information:
if ($sw_id > 0) {
// Define and execute the query:
$q = "SELECT name, color, size FROM general_widgets LEFT JOIN specific_widgets USING (gw_id) LEFT JOIN colors USING (color_id) LEFT JOIN sizes USING (size_id) WHERE sw_id=$sw_id";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1) {
// Get the information:
list ($name, $color, $size) = mysqli_fetch_array($r, MYSQLI_NUM);
// If the cart already contains
// one of these widgets, increment the quantity:
if (isset($_SESSION['cart'][$sw_id])) {
$_SESSION['cart'][$sw_id]++;
// Display a message:
echo "<p>Another copy of '$name' in color $color, size $size has been added to your shopping cart.</p>\n";
} else { // New to the cart.
// Add to the cart.
$_SESSION['cart'][$sw_id] = 1;
// Display a message:
echo "<p>The widget '$name' in color $color, size $size has been added to your shopping cart.</p>\n";
}
} // End of mysqli_num_rows() IF.
} // End of ($sw_id > 0) IF.
} // End of isset($_GET['sw_id']) IF.
} elseif (isset($_REQUEST['do']) && ($_REQUEST['do'] == 'update')) {
// Change any quantities...
// $k is the product ID.
// $v is the new quantity.
foreach ($_POST['qty'] as $k => $v) {
// Must be integers!
$pid = (int) $k;
$qty = (int) $v;
if ($qty == 0) { // Delete item.
unset ($_SESSION['cart'][$pid]);
} elseif ($qty > 0) { // Change quantity.
$_SESSION['cart'][$pid] = $qty;
}
} // End of FOREACH.
// Print a message.
echo '<p>Your shopping cart has been updated.</p>';
} // End of $_REQUEST IF-ELSE.
// Show the shopping cart if it's not empty:
if (isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
// Retrieve all of the information for the products in the cart:
$q = "SELECT sw_id, name, color, size, default_price, price FROM general_widgets LEFT JOIN specific_widgets USING (gw_id) LEFT JOIN colors USING (color_id) LEFT JOIN sizes USING (size_id) WHERE sw_id IN (";
// Add each product ID.
foreach ($_SESSION['cart'] as $sw_id => $v) {
$q .= (int) $sw_id . ',';
}
$q = substr ($q, 0, -1) . ') ORDER BY name, size, color';
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) > 0) {
// Create a table and a form:
echo '<table border="0" width="90%" cellspacing="2" cellpadding="2" align="center">
<tr>
<td align="left" width="20%"><b>Widget</b></td>
<td align="left" width="15%"><b>Size</b></td>
<td align="left" width="15%"><b>Color</b></td>
<td align="right" width="15%"><b>Price</b></td>
<td align="center" width="10%"><b>Qty</b></td>
<td align="right" width="15%"><b>Total Price</b></td>
</tr>
<form action="cart.php" method="post">
<input type="hidden" name="do" value="update" />
';
// Print each item:
$total = 0; // Total cost of the order.
while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {
// Determine the price:
$price = (empty($row['price'])) ? $row['default_price'] : $row['price'];
// Calculate the total and sub-totals:
$subtotal = $_SESSION['cart'][$row['sw_id']] * $price;
$total += $subtotal;
$subtotal = number_format($subtotal, 2);
// Print the row:
echo <<<EOT
<tr>
<td align="left">{$row['name']}</td>
<td align="left">{$row['size']}</td>
<td align="left">{$row['color']}</td>
<td align="right">\$$price</td>
<td align="center"><input type="text" size="3" name="qty[{$row['sw_id']}]" value="{$_SESSION['cart'][$row['sw_id']]}" /></td>
<td align="right">\$$subtotal</td>
</tr>\n
EOT;
} // End of the WHILE loop.
// Print the footer, close the table, and the form:
echo ' <tr>
<td colspan="5" align="right"><b>Total:</b></td>
<td align="right">$' . number_format ($total, 2) . '</td>
</tr>
<tr>
<td colspan="6" align="center">Set an item\'s quantity to 0 to remove it from your cart.</td>
</tr>
</table><div align="center"><button type="submit" name="submit" value="update">Update Cart</button>
<a href="checkout.php"><button type="button" name="checkout" value="Checkout">Checkout</button></a></div>
</form>';
} // End of mysqli_num_rows() IF.
} else {
echo '<p>Your cart is currently empty.</p>';
}
// Include the footer file to complete the template:
include_once ('./includes/footer.html');
?>
A:
A1. Your session starts when you call session_start(). Although a certain variable may not be set in $_SESSION, the session is still initiated.
A2. If you look closely at the code, you'll see that it checks whether $_SESSION['cart'][$sw_id] is set yet. If it is, it uses the ++ operator. If not, it initializes it with a value of 1.
As an aside, you can initialize a variable with ++ in PHP. If the variable or array key is not initialized, PHP assumes it has a starting value of 0.
A:
A1.
Yes you can start a session this way. PHP instantiates session keys the same way it instantiates any other variable.
A2.
When you do $_SESSION['cart'][$sw_id]++, you're saying add 1 to the value, not to the key. In other words if $array[0]==5 and you do $array[0]++, you get 6, not $array[1].
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VSFTPD error 530 on fresh install
I need to setup an FTP server and SFTP server on EC2 supporting both password and cert logins. I just used the stock RHEL and Amazon AMI's and I can't login to either.
$ sudo yum install vsftpd
$ sudo adduser someuser
$ sudo passwd someuser
#edit /etc/ssh/sshd_config
PasswordAuthentication yes
#Comment out this line on /etc/pam.d/vsftpd for good measure, read about it elsewhere
#auth required pam_listfile.so item=user sense=deny file=/etc/vsftpd/ftpusers onerr=succeed
$ sudo systemctl start vsftpd
My vsftpd conf is as follows
#edit /etc/vsftpd/vsftpd.conf to disable anon login
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
dirmessage_enable=YES
xferlog_enable=YES
connect_from_port_20=YES
xferlog_std_format=YES
listen=NO
listen_ipv6=YES
pam_service_name=vsftpd
userlist_enable=YES
tcp_wrappers=YES
I do all this, then attempt connecting from another host. SFTP hangs with the error below and I have to Ctrl+C to get sftp to exit.
$ sftp -v -P 21 someuser@ec2host
...
debug1: ssh_exchange_identification: 530 Please login with USER and PASS.
I expect to be prompted for a password and see the users directory! Note: sftp works against port 22 with the regular sshd install. Any idea what I'm doing wrong?
A:
There seems to be a lot of confusion on the internet between the SSH file transfer client sftp, and FTP with SSL ftps (cf http->https).
vsftpd does not support sftp connections. For ftps connections you would need an SSL key+certificate, and the appropriate configuration eg
rsa_cert_file=/etc/vsftpd/vsftpd.pem
ssl_enable=YES
and then you would need to use an FTP client that supports ftps (eg lftp)
The ProFTPd server has an SFTP module that can be enabled, but it cannot share the same port with regular FTP since it is a completely incompatible protocol. You would need to either run it on a non-standard port, or move openssh server to a nonstandard port to have proftpd listen on port 22.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Visual Studio passing variables as reference?
I have been working on this program for a good hour or two now and every time I attempt to debug it visual studio is deciding to change the values in currentGuess.guessLine and I have no idea why. They're not being passed by reference any where and the only time they should change is under the comment 'Get guess from user'. Could someone please help as it's driving me crazy? I have provided the code below: (I have removed any completely irrelevant methods to make it shorter.
I am using visual studio professional and I have re-written this code 3 times now and I still cannot figure out why it is happening. Any help would be greatly appreciated.
struct History
{
public Guess[] previousGuesses;
public int noOfPreviousGuesses;
}
struct Guess
{
public int[] guessLine;
public Hint givenHint;
}
struct Hint
{
public int blackPegs;
public int whitePegs;
}
static void Main(string[] args)
{
Mastermind(3, 3);
}
static void Mastermind(int N, int M)
{
bool gameFinished;
int playAgain;
History gameHistory;
Guess currentGuess;
int[] secretCode;
do
{
//Game start
gameFinished = false;
//Reset history
gameHistory.previousGuesses = new Guess[0];
gameHistory.noOfPreviousGuesses = 0;
//Generate secretCode
secretCode = GenerateSecretCode(N, M);
do
{
//Get guess from user
currentGuess.guessLine = GetGuessLine(N, M);
//Evaluate guess
gameFinished = EvaluateGuess(currentGuess.guessLine, secretCode, N);
if (gameFinished == false)
{
//Generate hint
currentGuess.givenHint = GenerateHint(currentGuess.guessLine, secretCode, N);
//Add guess to history
gameHistory = AddGuessToHistoryQueue(currentGuess, gameHistory);
//Output history
OutputHistory(gameHistory, N);
}
} while (gameFinished == false);
//Ask to play again
playAgain = GetValueFromUser("Enter 0 or a positive value to play again, otherwise enter a negative value: ");
} while (playAgain >= 0);
}
/// <summary>
/// Gets a guess line from the user.
/// Validates each value using above procedure.
/// </summary>
/// <param name="codeLength">The length of the code being used.</param>
/// <param name="noOfColours">The number of colours allowed.</param>
/// <returns>The line entered.</returns>
static int[] GetGuessLine(int codeLength, int noOfColours)
{
int[] guessLine;
guessLine = new int[codeLength];
for (int count = 0; count < codeLength; count++)
{
//Get guessLine[count] from user
guessLine[count] = GetValueFromUserInRange(1, noOfColours, "Please enter guess at position " + count + ": ");
}
return guessLine;
}
/// <summary>
/// Compares the given guess to the given code.
/// Returns true if guess and code match exactly otherwise
/// returns false.
/// </summary>
/// <param name="guess">The guess being compared.</param>
/// <param name="code">The code to be compared against.</param>
/// <param name="codeLength">The length of the code and guess.</param>
/// <returns></returns>
static bool EvaluateGuess(int[] guess, int[] code, int codeLength)
{
bool correctGuess;
correctGuess = true;
for (int count = 0; count < codeLength; count++)
{
if (guess[count] != code[count])
{
//Found inconsistency
correctGuess = false;
break;
}
}
return correctGuess;
}
/// <summary>
/// Generates a hint through finding all matching values,
/// changing their values and incrementing the black pegs total.
/// Then calculates white pegs by checking for matching values again.
/// </summary>
/// <param name="guess">The guess requiring a hint.</param>
/// <param name="code">The code for the guess to be compared to.</param>
/// <param name="codeLength">The length of the code/guess.</param>
/// <returns>The hint generated.</returns>
static Hint GenerateHint(int[] guess, int[] code, int codeLength)
{
Hint newHint;
newHint.blackPegs = 0;
newHint.whitePegs = 0;
//Calculate blackPegs
for (int count = 0; count < codeLength; count++)
{
if (guess[count] == code[count])
{
newHint.blackPegs = newHint.blackPegs + 1;
//Hide values
guess[count] = 0;
code[count] = 0;
}
}
//Calculate white pegs
for (int guessCount = 0; guessCount < codeLength; guessCount++)
{
//Ensure current guess value hasn't been used
if (guess[guessCount] != 0)
{
//Check for matching value in code
for (int codeCount = 0; codeCount < codeLength; codeCount++)
{
if (guess[guessCount] == code[codeCount])
{
//Found match
newHint.whitePegs = newHint.whitePegs + 1;
//Hide values
guess[guessCount] = 0;
code[codeCount] = 0;
}
}
}
}
return newHint;
}
A:
This is a common mistake many developers make. Parameters can be passed as ByVal or ByRef (to use VB notation). But what this does is not exactly what most people assume it does.
For value types (e.g. int, etc - anything which resides in the stack). The value itself it copied into a new memory space, and passed into the method. Thus changes to the value do not affect the originating value.
For Reference types (e.g. objects, classes, etc - anything which resides in the heap). The pointer is copied and passed into the method. However, the pointer still points to the same object in memory. Thus changes to properties inside the object will still be reflected in the calling method. The only thing that wouldn't be reflected, is if you did this:
myObject = new Person();
At this point, the pointer passed into the method would be reset to point to a brand new object. But the original pointer from the calling method still points to the original object. Thus it wouldn't see these changes.
One of the easiest things to think about (and I'm not 100% sure if this is true, but it makes it easier to think about this). Is that the pointers to objects in the heap and stored in the stack. When you set byval or byref/ref this is acting on the object in the stack, not the object in the heap. i.e. Byval/ByRef only ever applies to the heap.
Edit
Here is a supporting answer from Jon Skeet to back this up. He also links to this article
Update
Additional info based on your comment. Your structs contain reference types (int[] is an array of ints - arrays are reference types) inside them, so they are automatically moved to the heap (as far as I understand it, at least).
This answer tackles it from a slightly different angle (structs being part of a class), but I think it gets the point across
|
{
"pile_set_name": "StackExchange"
}
|
Q:
django error when using wsgi and virtualenv: could not import settings
I've read a considerable number of posts on the issue of wsgi not seeing the Django settings.py file and the best I can conclude is that my Django project is not in my PYTHONPATH.
Complicating things is that I'm running an older version of Django at the system level but this project needs to be run in a virtualenv.
I've set up a virtualenv at /usr/local/pythonenv/election and my project is located at /usr/local/pythonenv/election/src/dev/election
My .wsgi file is in a /usr/local/pythonenv/election/src/dev/election/config/
I can run the Django server using $ python manage.py runserver
But when using apache and mod_wsgi, I get the error:
ImportError: Could not import settings 'election.settings' (Is it on sys.path? Does it have syntax errors?): No module named election.settings
Here's my .wsgi file:
import os
import sys
import site
sys.stdout = sys.stderr
HERE = env_root = os.path.abspath(os.path.dirname(__file__))
found = False
while env_root != '/':
env_root = os.path.abspath(os.path.dirname(env_root))
if os.path.exists(os.path.join(env_root, 'bin', 'activate')):
found = True
break
assert found, "didn't find a virtualenv in any parent of %s" % HERE
sitepackages_root = os.path.join(env_root, 'lib')
assert os.path.exists(sitepackages_root), "no such dir %s" % sitepackages_root
for d in os.listdir(sitepackages_root):
if d.startswith('python'):
site.addsitedir(os.path.join(sitepackages_root, d, 'site-packages'))
break
else:
raise RuntimeError("Could not find any site-packages to add in %r" % env_root)
os.environ['DJANGO_SETTINGS_MODULE'] = 'election.settings'
os.environ['PYTHON_EGG_CACHE'] = '/tmp/election-python-eggs'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Here's the traceback:
[Sat Jan 07 21:54:19 2012] [error] [client 192.168.150.122] File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py", line 33, in load_middleware
[Sat Jan 07 21:54:19 2012] [error] [client 192.168.150.122] for middleware_path in settings.MIDDLEWARE_CLASSES:
[Sat Jan 07 21:54:19 2012] [error] [client 192.168.150.122] File "/usr/lib/pymodules/python2.6/django/utils/functional.py", line 269, in __getattr__
[Sat Jan 07 21:54:19 2012] [error] [client 192.168.150.122] self._setup()
[Sat Jan 07 21:54:19 2012] [error] [client 192.168.150.122] File "/usr/lib/pymodules/python2.6/django/conf/__init__.py", line 40, in _setup
[Sat Jan 07 21:54:19 2012] [error] [client 192.168.150.122] self._wrapped = Settings(settings_module)
[Sat Jan 07 21:54:19 2012] [error] [client 192.168.150.122] File "/usr/lib/pymodules/python2.6/django/conf/__init__.py", line 75, in __init__
[Sat Jan 07 21:54:19 2012] [error] [client 192.168.150.122] raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
[Sat Jan 07 21:54:19 2012] [error] [client 192.168.150.122] ImportError: Could not import settings 'election.settings' (Is it on sys.path? Does it have syntax errors?): No module named election.settings
A:
Where are you adding '/usr/local/pythonenv/election/src/dev' to sys.path?
You have also made the rest of your WSGI file more complicated than it needs to be.
Make sure you go watch:
http://code.google.com/p/modwsgi/wiki/WhereToGetHelp?tm=6#Conference_Presentations
Also read:
http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
and use the activate_this method for activating the virtual environment as mentioned in the presentation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flexbox - Wrap Center Item on New Line First
I am using Flex Box to create a traditional float items list. I have three items structured like:
<section>
<div>
item one
</div>
<div>
item two
</div>
<div>
item three
</div>
</section>
with CSS:
section{
display: flex;
flex-wrap: wrap;
}
div{
width: 33%;
min-width: 200px;
border: 1px solid black;
}
In this current format, item three will always be the first child pushed to a new line if the width of the screen drops below a threshold.
Is there anyway to configure Flex Box so that item two is always the first to drop?
JSFiddle
A:
You can control the wrapping behavior and order of flex items in a media query:
revised fiddle
section {
display: flex;
}
div {
width: 33%;
min-width: 200px;
border: 1px solid black;
}
@media (max-width: 600px) {
section { flex-wrap: wrap; }
div:nth-child(2) { order: 1; }
}
<section>
<div>item one</div>
<div>item two</div>
<div>item three</div>
</section>
From the spec:
5.4. Display Order: the order property
Flex items are, by default, displayed and laid out in the same order as they appear in the source document. The
order property can be used to change this ordering.
The order property controls the order in which children of a flex container appear within the flex container, by
assigning them to ordinal groups. It takes a single <integer> value, which specifies which ordinal group the flex item
belongs to.
The initial order value for all flex items is 0.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does JPS tool get the name of the main class or jar it is executing
I am wondering, how does JPS tool get the name of the main class it is executed within jvm process. It is
jps -l
123 package.MainClass
456 /path/example.jar
I am talking specifically about Linux (I am not interested in Windows, and I have no Win machine to experiment on).
I could think of 2 ways
Connecting to the JVM in question which in turn tells it
From /proc file system
Regarding the first alternative, is it using local JMX connection? Still, it must go to /proc for the pids.
There is PID, so it must ask OS anyway
jps lists also itself
Regarding the second alternative, I feel this could be the correct one, because
On the command line, there is either -jar or MainClass
/proc knows wery well the PID
Before jps starts doind something, it has own folder in /proc
But, I am facing little problem here. When java command is very long (e.g. there is extremely long -classpath parameter), the information about the command line does not fit into space reserved for it in /proc. My system has 4kB for it, and what I learned elsewhere, this is hardwired in OS code (changing it requires kernel compilation). However, even in this case jps is still able to get that main class somewhere. How?
I need to find quicker way to get JVM process than calling jps. When system is quite loaded (e.g. when number of JVMs start), jps got stuck for several seconds (I have seen it waiting for ~30s).
A:
jps scans through /tmp/hsperfdata_<username>/<pid> files that contain monitors and counters of running JVMs. The monitor named sun.rt.javaCommand contains the string you are looking for.
To find out the format of PerfData file you'll have to look into JDK source code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Applied Math: Finding Roots
I am taking a Numerical Computation class, and we are currently learning about Newton's Method for finding the roots of a system of non-linear equations. I have no problems understanding how the algorithm works, but as an engineer I work better when I can think of a concrete application for concepts.
Can anyone give a few interesting "real world" examples of when finding the roots of a system of equations is useful?
A:
Interior-point algorithms for Linear Programming and related programs are a version of Newton's method. Apparently Linear Programs do arise in practice.
Trajectories of projectiles and spacecrafts are also found through solving systems of differential equations.
Roots of polynomials and eigenvalues of matrices are found numerically, since Gaussian elimination is not stable.
Non-linear equations frequently arise in physics and engineering. As you progress in your studies, you'll find out that most equations cannot be solved analytically (unless they're linear), and one needs resort to numerical methods.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Moving Spring Accessing Data with JPA getting started guide to something more complex
I was able to get the sample application running on my machine directly from the website: https://spring.io/guides/gs/accessing-data-jpa/.
This sample application gets you started with a simple implementation of the H2 embedded database.
It requires only two dependencies to run:
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.h2database:h2")
testCompile("junit:junit")
}
The Repository is declared here for your reference:
package hello;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
}
This repository is autowired into the configuration. All files are contained in the same package/directory. I'm assuming spring is smart enough to instantiate the correct instance of the bean implementing the CustomerRepository that provides the right connections to the h2database. I'm not sure how that is done here, but it works.
The code is here:
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
When it runs it looks like by default, it's building a JPA container with default hibernate persistence information and it runs fine.
However, when I decide to use this code as a baseline and move the CustomerRepository to another package, jpa, I'm no longer able autowire the repository into the application.
Adding @ComponentScan("jpa") to Application does not help:
.NoSuchBeanDefinitionException: No qualifying bean of type [jpa.CustomerRepository]
Adding @EnableJpaRepositories("jpa") to the Application yields a different error:
IllegalArgumentException: Not an managed type: class jpa.Customer
So, it looks like I can get away with a very minimalistic configuration with JPA/Hibernate/H2 as long as all of the relevant classes are in the same package.
My question is, do I have to immediately need to move toward a more complicated configuration when I want to move things into different packages, or is there to preserve this minimalism but still be able to split things apart.
A:
The easiest would be to keep the Application class in the root package of the package hierarchy and move the other classes to sub-packages.
org.example
|
--- Application.java
|
--- jpa
| |
| --- CustomerRepository.java
|
--- model
|
--- Customer.java
Alternatively, if you want every class in a sub-package of its own, such as:
org.example
|
--- bootstrap
| |
| --- Application.java
|
--- jpa
| |
| --- CustomerRepository.java
|
--- model
|
--- Customer.java
you will need to use @EntityScan as well.
@SpringBootApplication
@EnableJpaRepositories("org.example.jpa")
@EntityScan("org.example.model")
public class Application ...
See the official documentation for details.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Taking the real part of a complex equation for sea level
I have the following complex equation that gives sea level as a function of time and space:
$$ \zeta (x,t) = \left( \frac{hU_0}{\sqrt{gh}}\frac{e^{-idl}-e^{ikl}}{e^{idl}-e^{-idl}} \cdot e^{idx} - \frac{hU_0}{\sqrt{gh}}\frac{e^{ikl}-e^{idl}}{e^{idl}-e^{-idl}} \cdot e^{-idx} +\frac{hU_0k}{\sigma}e^{ikx} \right) \cdot e^{- i \sigma t},$$
where $d=\frac{\sigma}{\sqrt{gh}}$, $k$ is the wave number, $l$ is the length of the basin. This is in complex form, and my solution is the real part of this equation. My question is, do you know how to get to the real part? I have tried by first writing all $e^{i something}$ as $cos(something)+isin(something)$, then multiplying, adding... all of the parts and then finally just taking the bits that don't have the imaginary unit next to them, but the solution seems dodgy to me. I have checked it and can't find what (or if) I did wrong and I would appreciate it if somebody else could take a look at it.
The result I get is the following:
$$ Re[\zeta] =\frac{hU_0k}{\sigma} cos(kx-\sigma t)-\frac{hU_0}{\sqrt{gh}} \frac{cos(dx)}{sin(dl)}sin(kl-\sigma t)-\frac{hU_0}{\sqrt{gh}}\frac{cos(dl-dx)}{sin(dl)}sin(\sigma t). $$
A:
One thing I would expect to be useful is $e^{idl}-e^{-idl}=2i\sin(dl)$ since that's on your denominator.
$$ \zeta (x,t) = \left(A\frac{e^{-idl}-e^{ikl}}{e^{idl}-e^{-idl}} \cdot e^{idx} - A\frac{e^{ikl}-e^{idl}}{e^{idl}-e^{-idl}} \cdot e^{-idx} +Be^{ikx} \right) \cdot e^{- i \sigma t},$$
where $A= \frac{hU_0}{\sqrt{gh}}$ and $B=\frac{hU_0k}{\sigma}$ are real I assume.
Tidying up a bit:
$$ \zeta (x,t) = \frac{A}{2i\sin(dl)}\left(e^{-id(l-x)- i \sigma t}-e^{ikl+idx- i \sigma t} - e^{ikl-idx- i \sigma t}+e^{id(l-x)- i \sigma t}\right) +Be^{ikx- i \sigma t} $$
You can use that
$\mathrm{Re}(e^{ix})=\cos(x), \quad\mathrm{Im}(e^{ix})=\sin(x),\quad \mathrm{Re}(ie^{ix})=-\sin(x),\quad \mathrm{Im}(ie^{ix})=\cos(x). $
$$=-\frac{A}{2\sin(dl)}\left[-\sin(-d(l-x)-\sigma t)+\sin(kl+dx- \sigma t) +\sin(kl-dx-\sigma t)+\sin(d(l-x)-\sigma t)\right] +B\cos(kx-\sigma t) $$
$$= \frac{-A}{2\sin(dl)}\left[\sin(d(l-x)+\sigma t)+\sin(kl+dx- \sigma t) +\sin(kl-dx-\sigma t)-\sin(d(l-x)-\sigma t)\right] \\+B\cos(kx-\sigma t) $$
You can then pair up the sines then and use the sine addition rules.
$$\sin(A)\pm \sin(B)=2\sin\left(\frac{A\pm B}{2}\right)\cos\left(\frac{A\mp B}{2}\right)$$
I think it would be natural to pair the first and last terms and the middle two terms, because things will cancel.
$$= \frac{-A}{\sin(dl)}\left[\sin(kl- \sigma t)\cos(dx) +\cos(d(l-x))\sin(\sigma t)\right] +B\cos(kx-\sigma t) $$
Which is what you have I believe.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java Method for Formatting Text?
I'm currently taking Python, and I like the way one is able to insert variables into a string without doing
"+ var +" or
" ", var, " "
Example: "We can just go out at {} pm and go to {}.".format(5, "Bob's Burgers");
Is there a way to do it with Java?
A:
Yes. You could do
String s = String.format("We can just go out at %d pm and go to %s.", 5, "Bob's Burgers");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Prove that all the numbers in the table are even.
In each cell of a 20 x 20 table an integer is written , such that for every 7 rows and 7 columns that we consider the sum of these 49 cells (the cells where the rows and columns intersect) is an even number. Prove that all the numbers in the table are even.
A:
HINT to an alternate solution, partly inspired by @JaapScherphuis and partly inpsired by linear algebra (modulo $2$, i.e. in $\mathbb{F}_2$).
Let $A$ denote the original $20\times 20$ table, $R$ denote a subset of rows, $C$ denote a subset of columns, and
$$S(R,C) = \sum_{r \in R \\ c \in C} A_{r,c}$$
be the sum of numbers in the intersection of those rows and those columns.
(1) You are given that: $S(R,C)$ is even whenever $|R|=|C|=7$, i.e. there are $7$ rows and $7$ columns.
(2) Prove, by repeated applications of (1), that $S(R,C)$ is even whenever $|R|=7, |C|=2$.
(3) Prove, from (1) & (2) together, that $S(R,C)$ is even whenever $|R|=7, |C|=1$, i.e. for the single column case.
Now you go through the analogous process to shrink the number of rows:
(4) Prove, from (3), that $S(R,C)$ is even whenever $|R|=2, |C|=1$.
(5) Prove, from (3) & (4) together, that $S(R,C)$ is even whenever $|R|=|C|=1$, i.e. every cell is even. QED
BTW: this method also clearly shows that the result works only because $7$ itself is odd. If the initial condition were $S(R,C)$ is even whenever $|R|=|C|=6$, then (step 3) breaks down, and indeed there are many counter-examples, e.g. the all-odd grid, checkerboard of odds and evens, etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to update field values of a content type's nodes when when viewing a particular content type page
I'd essentially like to alter the values of a specific custom field of a few of nodes before they're displayed in a view on the 'page' of a specific content type.
The content type is that will be displayed is a park. When a park is viewed, one of the blocks shown is a view that fetches and shows several nodes that are also 'parks'.
This park content type has a field called proximity. I'd like to change the value of proximity (based on a mathematical formula) for all parks before the view is processed, so that I can use proximity in the view.
From what I understand so far, I should use a park_preprocess function, which calls some sort of hook to change the proximity values. Is this correct, and how would I do it?
A:
Thanks to Pushinder and Shirin for responding, and providing the start I needed! However both answers were lacking the detail I needed. I won't paste my entire code here, as it's too long, but I'll describe what I used and why:
hook_node_view was the right hook to call my function at the right time - before page load
$refN = $node->field_location_n[LANGUAGE_NONE][0]['value']; and the same for East were required to get the reference coordinates
Because I have several hundred nodes with coordinates, I couldn't load each one individually using load_node or collectively using load_node_multiple since this used far too many resources for every page load
Instead, I used db_query and field_attach_load together, as described in this answer: https://drupal.stackexchange.com/a/30906/20264 to effectively load just the values I needed
I then used foreach( $nodes as $nodei ) { to loop through all the results
$distance = sqrt( pow( $refN - $nodeiN, 2 ) + pow( $refE - $nodeiE, 2 ) ); was my proximity calculation
Then, only for results with a specified proximity would I update $node
Since I was using the Entity Reference module to record 'Nearby places' in my nodes, I used the following to update the entity references:
$node->field_nearby[LANGUAGE_NONE][$i] = array( "target_id" => $nodei->nid );
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Was the Stone of Minas Tirith still dangerous after Sauron was destroyed?
In the sad chapter of The Return of the King in which the Fellowship parts for the last time, Pippin says he wishes that they could use Palantiri to keep in touch. Aragorn dismisses this idea:
Only one now remains that you could use, for you would not wish to see what the Stone of Minas Tirith would show you. But the Stone of Orthanc the King [of Rohan, i.e., Eomer] will keep, to see what is passing in his realm, and what his servants are doing.
-The Lord of the Rings, The Return of the King, Book VI, Chapter 6: "Many Partings"
Aragorn doesn't say "I won't let you use the Stone of Minas Tirith", he says "You would not wish to see what it would show you", which sounds much more sinister - it gives me the impression that it would show Pippin something awful.
But why? We know that Sauron manipulated the Stone of Minas Tirith to show Denethor things which made him despair, and this is why Denethor became so screwy before he died; but Sauron is dead, and if he had a Stone in Barad-dûr, it should now be dormant and harmless.
Why would Pippin not wish to see what the Stone of Minas Tirith would show him? It is possible that what he saw would simply be boring and irrelevant to him (i.e., he would see Eomer looking into the Stone of Orthanc, or an empty room at Orthanc, or an empty room at Barad-Dur, none of which would be particularly interesting), but Aragorn makes it sound like something much darker was going on.
Was the Stone of Minas Tirith still dangerous to use despite the fact that Sauron was dead? If so, why?
A:
It wouldn't be dangerous, just unpleasant. From Return of the King:
Then Denethor leaped upon the table, and standing there wreathed in fire and smoke he took up the staff of his stewardship that lay at his feet and broke it on his knee. Casting the pieces into the blaze he bowed and laid himself on the table, clasping the palantír with both hands upon his breast. And it was said that ever after, if any man looked in that Stone, unless he had a great strength of will to turn it to other purpose, he saw only two aged hands withering in flame.
Return of the King Book 5 Chapter 7: "The Pyre of Denethor"
I interpret Aragorn's statement as meaning that looking into the stone would be a traumatic look at a man burning alive.
For Pippin, who spent a fair bit of time with Denethor during his stay in Minas Tirith, this would likely be even more traumatic.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Interrupt winProgressbar
Do you guys know, if there is any way, to interrupt a winProgressBar?
I tried to press Escape, but it would not stop the progress bar during calculations.
Thanks for any help
W
A:
You can press Alt + F4 , just like you would close any program in Windows.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How make a query in to Mongoid, 'where is not null'?
How make a query in to Mongoid, 'where is not null'?For example
where('comment_id IS NOT NULL')
how make it with mongoid?
A:
You can write using $ne
where(:comment_id.ne => nil)
Relevant documentation of queries.
A:
You can try this
Model.where(:comment_id.exists => true)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pass variable to included template in django
I am trying to pass variable to child template:
{% block footer %}
{% include '_footer.html' with var="foo" %}
{% endblock footer %}
but I am getting django error:
Exception Type: TemplateSyntaxError at /
Exception Value: expected token 'end of statement block', got 'with'
What am I doing wrong?
A:
you must declare variable first then include child template
{% block footer %}
{% with var="foo" %}
{% include "_footer.html" %}
{% endwith %}
{% endblock %}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but object given
I am trying to assert a drop down value under tab li. Here is my code for that:
await searchPage.enterSearch("/html/body/nw-search/nw-text-search/div/div/div/div/div[2]/input","Honda");
await element.all(by.css("body > nw-search > nw-text-search > div > div > div > div > div.autocomplete-wrapper > ul > li:nth-child(1) > ul li")).then(async function(items) {
expect(items.length).equals(5);
await expect(items[0].getText()).contain("honda: Civic");
});
However, while running the above code I am getting below error. Even though I am passing a string. I tried both single quotes and double quotes. :
AssertionError: object tested must be an array, a map, an object, a
set, a string, or a weakset, but object given
A:
Items is not an Array, it is ElementArrayFinder. Use count method instead of length.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Call Function in Different Class in Swift(fatal error)?
I have a class which is for bluetooth data receiving and I wonder to send the receiving data to class UIViewController and do the realtime plotting(CorePlot)
class BluetoothManager: NSObject {
func dataReceiving(value: [Int]){
for (var m=0 ; m<5 ; m++){
dataOne[m] = value[2*m]
dataTwo[m] = value[2*m+1]
}
MainController().plot(dataOne: [Int], dataTwo: [Int])
}
MainController class:
class MainController: UIViewController,CPTScatterPlotDataSource {
@IBOutlet weak var graphView: CPTGraphHostingView!
private var scatterGraph : CPTXYGraph? = nil
typealias plotDataType = [CPTScatterPlotField : Double]
private var dataForPlot = [plotDataType]()
func plot(dataOne: [Int], dataTwo: [Int]){
let newGraph = CPTXYGraph(frame: CGRectZero)
graphView.hostedGraph = newGraph
...
}
}
When the procedure goes to graphView.hostedGraph = newGraph , there will have a fatal error:
unexpectedly found nil while unwrapping an Optional value
I have tried call the plot function in the MainController class, it was worked!
Can anybody help me to fix this problem?
Thanks!
A:
You are creating a new instance of the MainController in the line
MainController().plot(dataOne: [Int], dataTwo: [Int])
Therefore the @IBOutlet weak var graphView: CPTGraphHostingView! is nil - therefore your code crashes.
You must not create a new instance of the MainController the way you currently do - either instantiate it via the storyboard, or pass in the correct nib file. For both cases you have to set the MainController as controller class in the IB and connect the outlet.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use gtkmm with EGL
I found this blog post that has an example on how to use EGL with GTK. However I use gtkmm on my project, therefore I need to find how to do things with it
I need to find these functions:
gdk_x11_display_get_xdisplay
gtk_widget_get_display
gdk_x11_window_get_xid
gtk_widget_get_window
gtk_widget_get_allocated_width
gtk_widget_get_allocated_height
on gtkmm. Their gtkmm probably return class instances, so I need to figure out how to get the C object these classes point to as well
If we look at the GTK functions, let's see an example:
Display* gdk_x11_display_get_xdisplay ()
It returns a Display*. Meanwhile, in the gtkmm for Display we see that gobj() returns the C object GdkDisplay*:
GdkDisplay* gobj ()
which is not the same object.
So, how to find the gtkmm versions of these functions?
UPDATE2:
based on the suggestions in the comment, I made a minimal reproducible example:
#include <iostream>
#include <gtkmm.h>
#include <epoxy/gl.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GL/gl.h>
class MyOpenGLArea : public Gtk::Window
{
public:
MyOpenGLArea()
{
set_title("Test");
set_default_size(640, 360);
add(vBox);
glArea.set_hexpand(true);
glArea.set_vexpand(true);
glArea.set_auto_render(true);
vBox.add(glArea);
glArea.signal_realize().connect(sigc::mem_fun(*this, &MyOpenGLArea::realize));
glArea.signal_render().connect(sigc::mem_fun(*this, &MyOpenGLArea::render), false);
glArea.show();
vBox.show();
};
public:
Gtk::GLArea glArea;
Gtk::Box vBox{Gtk::ORIENTATION_VERTICAL, false};
void realize()
{
EGLBoolean eglStatus;
EGLConfig eglConfig;
EGLint n_config;
EGLint context_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
eglDisplay = eglGetDisplay((EGLNativeDisplayType)gdk_x11_display_get_xdisplay(glArea.get_display()->gobj()));
eglStatus = eglInitialize(eglDisplay, NULL, NULL);
if (!eglStatus)
{
printf("Error at eglInitialize\n");
switch (eglStatus)
{
case EGL_BAD_DISPLAY:
printf("EGL_BAD_DISPLAY\n");
break;
case EGL_NOT_INITIALIZED:
printf("EGL_NOT_INITIALIZED\n");
break;
case EGL_FALSE:
printf("EGL_FALSE\n");
break;
}
}
eglStatus = eglChooseConfig(eglDisplay, context_attribs, &eglConfig, 1, &numConfigs);
if (!eglStatus)
{
printf("Error at eglChooseConfig\n");
switch (eglStatus)
{
case EGL_BAD_DISPLAY:
printf("EGL_BAD_DISPLAY\n");
break;
case EGL_BAD_ATTRIBUTE:
printf("EGL_BAD_ATTRIBUTE\n");
break;
case EGL_NOT_INITIALIZED:
printf("EGL_NOT_INITIALIZED\n");
break;
case EGL_BAD_PARAMETER:
printf("EGL_BAD_PARAMETER\n");
break;
case EGL_FALSE:
printf("EGL_FALSE\n");
break;
}
}
};
virtual bool render(const Glib::RefPtr<Gdk::GLContext> &context)
{
glDraw();
glFinish();
return true;
}
void glDraw()
{
}
private:
EGLDisplay eglDisplay;
EGLSurface eglSurface;
EGLContext eglContext;
int numConfigs;
};
int main(int argc, char **argv)
{
auto app = Gtk::Application::create(argc, argv, "");
MyOpenGLArea myOpenGLArea;
return app->run(myOpenGLArea);
}
Here's the output:
libEGL warning: DRI2: failed to authenticate
Error at eglChooseConfig
EGL_FALSE
Something is still not rigth with the display I get
A:
I need to find these functions:
gdk_x11_display_get_xdisplay
gtk_widget_get_display
gdk_x11_window_get_xid
gtk_widget_get_window
gtk_widget_get_allocated_width
gtk_widget_get_allocated_height
on gtkmm.
Some of these have easy-to-find wrappers in gtkmm. There is a naming system in place, after all. A GTK function named "gtk_<thing>_<action>" usually corresponds to the <action> method of the (capitalized) <Thing> class in the Gtk namespace – i.e. Gtk::<Thing>::<action>.
Gtk::Widget::get_display
Gtk::Widget::get_window
Gtk::Widget::get_allocated_width
Gtk::Widget::get_allocated_height
That leaves the X11 interaction. I am not aware of a C++ wrapper for the "x11" portion of GDK, so you might need to mix C and C++ APIs. Just be aware of several similarly-named classes. For example, Gtk::Window and Gdk::Window are distinct classes. Also, Display (without a namespace) and GdkDisplay are distinct classes. (In particular, Display is not part of GTK nor of GDK; it is part of X11.)
Based on how the system is supposed to work (meaning that I have not tested this), the following lines should be a way to invoke GDK's X11 interaction functions from gtkmm. These assume a variable has been declared as Gtk::GLArea glArea, such as the data member from the example code.
gdk_x11_display_get_xdisplay(glArea.get_display()->gobj());
gdk_x11_window_get_xid(glArea.get_window()->gobj());
The get_display method returns a smart pointer to a Gdk::Display. Calling the pointed-to object's gobj method gives a GdkDisplay* which could then be fed to gdk_x11_display_get_xdisplay. Similarly, get_window returns a smart pointer to a Gdk::Window, which can be converted to a pointer to the C object for gdk_x11_window_get_xid.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Formatando data e hora com Javascript?
Estou consumindo dados de uma API e gostaria de saber como faço para passar o seguinte valor de data e hora, para o padrão brasileiro.
O formato retornado é esse:
2017-01-05T14:35:17.437
mas eu gostaria que fosse exibido
05-01-2017
A:
Pode utilizar o momentjs que faz todo trabalho de formatação de data, cálculos, etc:
moment.locale('pt-br');
console.log(moment('2017-01-05T14:35:17.437').format('DD-MM-YYYY'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
mas, também pode ser feito com o puro javascript:
var data = '2017-01-05T14:35:17.437';
var parte = data.substring(0,10).split('-').reverse().join('-');
console.log(parte);
Referencias:
momentjs - Parse, validate, manipulate, and display dates in JavaScript.
JavaScript String substring() Method
JavaScript String split() Method
JavaScript Array reverse() Method
JavaScript Array join() Method
|
{
"pile_set_name": "StackExchange"
}
|
Q:
You don’t have permission to save the file “988BF072-A4B9-4ABE-9FB8-2F3A8EBC2E2C” in the folder “CoreSimulator”
This folder exists.
I've tried moving it to the trash (it reappears and then this message pops up).
I've reset all permission to all enclosed folders to R+W.
I've repaired permissions on my drive.
Plugging in a real phone works fine (probably not relevant).
A:
Just finished solving this problem. I think the main issue is that you are looking in the wrong place. These are the steps I took:
Make hidden folders visible by going to terminal and executing these two commands:
defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder
Go to /Users/myUsername/Library now it should be visible ( instead of myUsername you should have yours)
The Logs folder has no access permission, so change it. In case you can't do it manually, go to 3b.
3b. Open terminal. Write this command
sudo chmod 777 ~/Library/Logs
Be happy
P.S. In case you don't want to see hidden folder and files anymore,
execute this two lines in terminal:
defaults write com.apple.finder AppleShowAllFiles FALSE
killall Finder
A:
So your permissions are invalid. You should look in ~/Library/Logs/CoreSimulator and check what the ownership and permissions are set to and fix them.
If that doesn't work, update your question with explanation of what you tried and show the current ownership and permissions on the relevant paths.
A:
Turns out the actual folder for the log file didn't exist.
When looking in Console.app, filtering on CoreSimulator, I saw this:
3/15/15 9:50:52.840 AM iOS Simulator[7291]: Error opening
/Users//Library/Logs/CoreSimulator/iOS Simulator.log
When I went to the Logs directory, CoreSimulator wasn't there, so I:
sudo mkdir CoreSimulator
sudo chown <user>:staff CoreSimulator
touch CoreSimulator/iOS\ Simulator.log
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add button to user profile page in drupal
I start using drupal(7) 3 days ago and I have small task :
I'm using Profile2 Module to create 2 type of users (candite/employer) and I Want to create a button in the wiew page of the profile of employer.
I create new module for that to test if is an employer profil :
function ab_candidate_app_profile2_view_alter($build) {
$test = $build['field_company_name']['#object'];
if(isset($build))
if($test->type == 'employer_'){
// add the button here
}
}
Thank you for your help
EDIT : and whene i do var_dump($build) i get next result :
array (size=12)
'#view_mode' => string 'account' (length=7)
'field_company_name' =>
array (size=16)
'#theme' => string 'field' (length=5)
'#weight' => int 0
'#title' => string 'Name' (length=4)
'#access' => boolean true
'#label_display' => string 'above' (length=5)
'#view_mode' => string 'account' (length=7)
'#language' => string 'und' (length=3)
'#field_name' => string 'field_company_name' (length=18)
'#field_type' => string 'text' (length=4)
'#field_translatable' => string '0' (length=1)
'#entity_type' => string 'profile2' (length=8)
'#bundle' => string 'employer_' (length=9)
'#object' =>
object(Profile)[56]
public 'pid' => string '6' (length=1)
public 'type' => string 'employer_' (length=9)
public 'label' => string 'Employer ' (length=9)
public 'uid' => string '10' (length=2)
public 'created' => string '1411278976' (length=10)
public 'changed' => string '1411278976' (length=10)
protected 'entityType' => string 'profile2' (length=8)
protected 'entityInfo' =>
array (size=22)
...
protected 'idKey' => string 'pid' (length=3)
protected 'nameKey' => string 'pid' (length=3)
protected 'statusKey' => string 'status' (length=6)
protected 'defaultLabel' => boolean false
public 'field_company_name' =>
array (size=1)
...
public 'field_logo' =>
array (size=1)
...
public 'field_company_description' =>
array (size=1)
...
public 'field_country' =>
array (size=1)
...
public 'rdf_mapping' =>
array (size=0)
...
public 'entity_view_prepared' => boolean true
'#items' =>
array (size=1)
0 =>
array (size=3)
...
'#formatter' => string 'text_default' (length=12)
0 =>
array (size=1)
'#markup' => string 'adel' (length=4)
'field_logo' =>
array (size=16)
'#theme' => string 'field' (length=5)
'#weight' => int 2
'#title' => string 'Logo' (length=4)
'#access' => boolean true
'#label_display' => string 'above' (length=5)
'#view_mode' => string 'account' (length=7)
'#language' => string 'und' (length=3)
'#field_name' => string 'field_logo' (length=10)
'#field_type' => string 'image' (length=5)
'#field_translatable' => string '0' (length=1)
'#entity_type' => string 'profile2' (length=8)
'#bundle' => string 'employer_' (length=9)
'#object' =>
object(Profile)[56]
public 'pid' => string '6' (length=1)
public 'type' => string 'employer_' (length=9)
public 'label' => string 'Employer ' (length=9)
public 'uid' => string '10' (length=2)
public 'created' => string '1411278976' (length=10)
public 'changed' => string '1411278976' (length=10)
protected 'entityType' => string 'profile2' (length=8)
protected 'entityInfo' =>
array (size=22)
...
protected 'idKey' => string 'pid' (length=3)
protected 'nameKey' => string 'pid' (length=3)
protected 'statusKey' => string 'status' (length=6)
protected 'defaultLabel' => boolean false
public 'field_company_name' =>
array (size=1)
...
public 'field_logo' =>
array (size=1)
...
public 'field_company_description' =>
array (size=1)
...
public 'field_country' =>
array (size=1)
...
public 'rdf_mapping' =>
array (size=0)
...
public 'entity_view_prepared' => boolean true
'#items' =>
array (size=1)
0 =>
array (size=13)
...
'#formatter' => string 'image' (length=5)
0 =>
array (size=4)
'#theme' => string 'image_formatter' (length=15)
'#item' =>
array (size=13)
...
'#image_style' => string '' (length=0)
'#path' => string '' (length=0)
'field_company_description' =>
array (size=16)
'#theme' => string 'field' (length=5)
'#weight' => int 3
'#title' => string 'Description' (length=11)
'#access' => boolean true
'#label_display' => string 'above' (length=5)
'#view_mode' => string 'account' (length=7)
'#language' => string 'und' (length=3)
'#field_name' => string 'field_company_description' (length=25)
'#field_type' => string 'text_long' (length=9)
'#field_translatable' => string '0' (length=1)
'#entity_type' => string 'profile2' (length=8)
'#bundle' => string 'employer_' (length=9)
'#object' =>
object(Profile)[56]
public 'pid' => string '6' (length=1)
public 'type' => string 'employer_' (length=9)
public 'label' => string 'Employer ' (length=9)
public 'uid' => string '10' (length=2)
public 'created' => string '1411278976' (length=10)
public 'changed' => string '1411278976' (length=10)
protected 'entityType' => string 'profile2' (length=8)
protected 'entityInfo' =>
array (size=22)
...
protected 'idKey' => string 'pid' (length=3)
protected 'nameKey' => string 'pid' (length=3)
protected 'statusKey' => string 'status' (length=6)
protected 'defaultLabel' => boolean false
public 'field_company_name' =>
array (size=1)
...
public 'field_logo' =>
array (size=1)
...
public 'field_company_description' =>
array (size=1)
...
public 'field_country' =>
array (size=1)
...
public 'rdf_mapping' =>
array (size=0)
...
public 'entity_view_prepared' => boolean true
'#items' =>
array (size=1)
0 =>
array (size=3)
...
'#formatter' => string 'text_default' (length=12)
0 =>
array (size=1)
'#markup' => string 'teeeeeeeeeeeeeeeeeeeest' (length=23)
'field_country' =>
array (size=16)
'#theme' => string 'field' (length=5)
'#weight' => int 4
'#title' => string 'Country' (length=7)
'#access' => boolean true
'#label_display' => string 'above' (length=5)
'#view_mode' => string 'account' (length=7)
'#language' => string 'und' (length=3)
'#field_name' => string 'field_country' (length=13)
'#field_type' => string 'list_text' (length=9)
'#field_translatable' => string '0' (length=1)
'#entity_type' => string 'profile2' (length=8)
'#bundle' => string 'employer_' (length=9)
'#object' =>
object(Profile)[56]
public 'pid' => string '6' (length=1)
public 'type' => string 'employer_' (length=9)
public 'label' => string 'Employer ' (length=9)
public 'uid' => string '10' (length=2)
public 'created' => string '1411278976' (length=10)
public 'changed' => string '1411278976' (length=10)
protected 'entityType' => string 'profile2' (length=8)
protected 'entityInfo' =>
array (size=22)
...
protected 'idKey' => string 'pid' (length=3)
protected 'nameKey' => string 'pid' (length=3)
protected 'statusKey' => string 'status' (length=6)
protected 'defaultLabel' => boolean false
public 'field_company_name' =>
array (size=1)
...
public 'field_logo' =>
array (size=1)
...
public 'field_company_description' =>
array (size=1)
...
public 'field_country' =>
array (size=1)
...
public 'rdf_mapping' =>
array (size=0)
...
public 'entity_view_prepared' => boolean true
'#items' =>
array (size=1)
0 =>
array (size=1)
...
'#formatter' => string 'list_default' (length=12)
0 =>
array (size=1)
'#markup' => string 'Malaysia (MY)' (length=13)
'#pre_render' =>
array (size=1)
0 => string '_field_extra_fields_pre_render' (length=30)
'#entity_type' => string 'profile2' (length=8)
'#bundle' => string 'employer_' (length=9)
'#theme' => string 'entity' (length=6)
'#entity' =>
object(Profile)[56]
public 'pid' => string '6' (length=1)
public 'type' => string 'employer_' (length=9)
public 'label' => string 'Employer ' (length=9)
public 'uid' => string '10' (length=2)
public 'created' => string '1411278976' (length=10)
public 'changed' => string '1411278976' (length=10)
protected 'entityType' => string 'profile2' (length=8)
protected 'entityInfo' =>
array (size=22)
'label' => string 'Profile' (length=7)
'plural label' => string 'Profiles' (length=8)
'description' => string 'Profile2 user profiles.' (length=23)
'entity class' => string 'Profile' (length=7)
'controller class' => string 'EntityAPIController' (length=19)
'base table' => string 'profile' (length=7)
'fieldable' => boolean true
'view modes' =>
array (size=1)
...
'entity keys' =>
array (size=4)
...
'bundles' =>
array (size=2)
...
'bundle keys' =>
array (size=1)
...
'label callback' => string 'entity_class_label' (length=18)
'uri callback' => string 'entity_class_uri' (length=16)
'access callback' => string 'profile2_access' (length=15)
'module' => string 'profile2' (length=8)
'metadata controller class' => string 'Profile2MetadataController' (length=26)
'static cache' => boolean true
'field cache' => boolean true
'load hook' => string 'profile2_load' (length=13)
'translation' =>
array (size=0)
...
'schema_fields_sql' =>
array (size=1)
...
'configuration' => boolean false
protected 'idKey' => string 'pid' (length=3)
protected 'nameKey' => string 'pid' (length=3)
protected 'statusKey' => string 'status' (length=6)
protected 'defaultLabel' => boolean false
public 'field_company_name' =>
array (size=1)
'und' =>
array (size=1)
...
public 'field_logo' =>
array (size=1)
'und' =>
array (size=1)
...
public 'field_company_description' =>
array (size=1)
'und' =>
array (size=1)
...
public 'field_country' =>
array (size=1)
'und' =>
array (size=1)
...
public 'rdf_mapping' =>
array (size=0)
empty
public 'entity_view_prepared' => boolean true
'#language' => string 'en' (length=2)
'#page' => null
A:
I solve it by overrieding the user-profile.tpl.php with this code :
<?php print render($user_profile);
if(isset($user_profile['profile_employer_'])){
$account_info=menu_get_object('user');
$acount_id = $account_info->uid;
// var_dump($account_info);die();
echo '<a href="/jobPortal/Apply/'.$acount_id.'">Apply Now</a>';
}
?>
I overied this file in the next path :
C:\wamp\www\jobPortal\themes\bartik\templates\
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IEDriverServer sends text very slowly using Selenium to the search field
I'm using selenium and python on windows7.
My code:
import os
from selenium import webdriver
# get the path of IEDriverServer
#dir = os.path.dirname(__file__)
#ie_driver_path = dir + "\IEDriverServer.exe"
ie_driver_path = "C:\Python36\Scripts\IEDriverServer.exe"
# create a new Internet Explorer session
driver = webdriver.Ie(ie_driver_path)
driver.implicitly_wait(30)
driver.maximize_window()
# create a new Firefox session
#driver = webdriver.Firefox()
#driver.implicitly_wait(30)
#driver.maximize_window()
# navigate to the application home page
driver.get("http://demo-store.seleniumacademy.com/")
# get the search textbox
search_field = driver.find_element_by_name("q")
search_field.clear()
# enter search keyword and submit
search_field.send_keys("phones")
search_field.submit()
...
The code works but when opens Ie the digitation of "phones" is very slow (about 20 seconds). In firefox instead is almost instantaneous.
Why so? It is normal? I'm doing something wrong?
PS: also, where is it better to put my IEDriverServer.exe? Inside C:\Python36\Scripts so I have just one file for all my projects or inside each projects (like in the part commented out)?
A:
Yes, you observed it right.
Using 64-bit IEDriverServer.exe send_keys() populates the field with the character sequence very slowly.
@JimEvans in the article Screenshots, SendKeys, and Sixty-Four Bits mentions that ...there are a couple of issues with the Internet Explorer driver that have been around since IE10 was released....
Comments in the discussion IE x64 slow typing mentions that any fix would require "a massive rearchitecture of the IE driver's binary components, [so] no timeline is (or will be) available" for the delivery of a fix. What causes these issues? How are they related? Why would a fix be so darned difficult? The answers to those questions can all be summed up with a simple answer: "Windows Hooks."
Deep Dive
When you are running IE 10 or higher on a 64-bit version of Windows, by default the process which hosts the containing window that includes the browser chrome (address bar, navigation buttons, menus, etc.) is a 64-bit process. The process which hosts the window where content is actually rendered (within each tab) is a 32-bit process.
By default, the IE driver attempts to use a windows hook on the content-rendering window to make sure that a key-down message is properly processed before sending a key-up message. This is where the problem is. The windows hook is not installed, because a 32-bit process (the content-rendering process) can't execute 64-bit code. The only way to properly fix this will be to create a second (32-bit) executable to perform the wait for the key-down to be complete. Since this would amount to a massive rearchitecture of the IE driver's binary components, no timeline is (or will be) available for this change. This means that even when you are running 64-bit Windows, you're likely using a 32-bit version of IE to render the content. This is a powerful argument for continuing to use the 32-bit version of the IE driver for IE 10 and above: you're not actually running against a 64-bit version of IE.
If you insist that you must run the 64-bit version of IEDriverServer.exe, you have two possible workarounds. First, you can disable native events by setting the "nativeEvents" capability to false using whatever mechanism your language binding provides for this. A more accurate workaround from an input simulation perspective would be to enable the "requireWindowFocus" capability, though this also has a windows hook dependency, which may manifest in other ways.
Windows Hook
All Windows applications have a routine in them called a "message loop." The message loop repeatedly calls the GetMessage API function, and processes messages sent to the application as they arrive in its queue. Hooks are a feature of the Windows message handling system that allow a developer to intercept, examine, and modify the message being sent to the application. By installing a hook, a developer could, for example, validate that a certain message was processed by the window being hooked. Or they could modify a message sent to the window to represent that the operating system could do things it actually can't. It's a clever mechanism, but it does have a few requirements which is out of scope for this discussion.
Solution
Instead of 64-bit IEDriverServer executable try to use 32-bit IEDriverServer executable
Where to put IEDriverServer.exe?
You can put the IEDriverServer.exe anywhere within your system and pass the absolute location of the binary through the argument executable_path as follows (Windows OS example):
from selenium import webdriver
driver = webdriver.Ie(executable_path=r'C:\path\to\IEDriverServer.exe')
driver.get("https://www.facebook.com/")
print("Page Title is : %s" %driver.title)
driver.quit()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Postgres convert empty string to NULL
I run a Postgres database and would like to convert empty string into NULL.
The following snipped should do this with all columns, but it isn't working.
SELECT * FROM schema.table NULLIF(columnname,'');
The error message is:
ERROR: syntax error at or near "''"
LINE 2: NULLIF(columnname,'');
A:
The following snipped converts empty strings into NULL:
UPDATE schema.table SET columnname=NULL where columnname='';
This works for me.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Largest consecutive subsequence, return subsequence and length
I have a function that returns the length of the subsequence but I also need to return the subsequence itself but i'm having trouble getting it to work.
I have tried the following code but the subsequence only returns correctly if it's the first subsequence that is the longest.
If I use the following array the length of 10 is correct but it returns an incorrect subsequence of [1, 2, 3, 4, 10, 11, 12, 13, 14, 15]
int n = arr.length;
HashSet<Integer> S = new HashSet<Integer>();
HashSet<Integer> Seq = new HashSet<Integer>();
int ans = 0;
// Hash all the array elements
for (int i = 0; i < n; i++) {
S.add(arr[i]);
}
System.out.println(S);
// check each possible sequence from the start
// then update optimal length
for (int i = 0; i < n; ++i)
{
System.out.println("ARR " + i);
// if current element is the starting
// element of a sequence
if (!S.contains(arr[i]-1))
{
//System.out.println("INSIDE .CONTAINS");
// Then check for next elements in the
// sequence
int j = arr[i];
int t = 0;
while (S.contains(j)) {
System.out.println("ANS " + ans);
t++;
if (t > ans ) { Seq.add(j);}
j++;
// System.out.println("T " + t);
// System.out.println("SEQ <<<<<<< " + Seq );
}
// update optimal length if this length
// is more
if (ans < j-arr[i]) {
ans = j-arr[i];
}
}
}
System.out.println(Seq);
System.out.println(ans);
return ans;
A:
That seems like a rather roundabout way of determining a sequence.
I believe one of your flaws is here:
// if current element is the starting
// element of a sequence
if (!S.contains(arr[i]-1))
{
This is definitely flawed.
Let's say you have the input sequence {1,3,5,2,4,6}. There are no sequences of 2 or more in that list. However, inputs from 2 to 6 would pass your test of S.contains(arr[i]-1), as the S HashSet contains 1,2,3,4,5,6.
Here is what I would consider a much simpler way to find the longest sequence:
int longestLength = 0;
int longestStart = 0;
int currentStart = 0;
int currentLength = 1;
for(int i=1;i<arr.length;i++)
{
if (arr[i] == arr[i-1] + 1)
{
// this element is in sequence.
currentLength++;
if (currentLength > longestLength)
{
longestLength = currentLength;
longestStart = currentStart;
}
}
else
{
// This element is not in sequence.
currentStart = i;
currentLength = 1;
}
}
System.out.printlng(longestStart + ", " + longestLength);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What will be the $n^{th}$ term of this given series?
Given series is:
$$1+\frac{1\times x^2}{2\times 4}+\frac{1\times 3\times 5\times x^4}{2\times 4\times 6\times 8}+\frac{1\times 3\times 5\times 7\times 9\times x^6}{2\times 4\times 6\times 8\times 10\times 12}+.....\infty$$
I need to find it's $n^{th}$ term but am having trouble in dealing with increasing number of multiples in each step. Kindly Guide in How to proceed
A:
Hint: Your $n$th term (counting the first non-$1$ term as the first term and excepting the $0$th term) looks to be
$$x^{2n}\frac{1\times 3 \times \cdots \times (4n-3)}{2\times 4\times \cdots \times (4n)}.$$
This equals
$$x^{2n}\frac{1\times 2 \times \cdots \times (4n-2)}{\left(2\times 4\times \cdots \times (4n-2)\right)\left(2\times 4\times \cdots \times (4n)\right)}.$$
How can we represent this in terms of factorials?
A:
$$a_0=1, \quad \text{and }a_n=\frac{x^{2n}}{2}\left(\prod_{k=0}^{n-1} \frac{2k+1}{2k+4}\right) \text{ for } n\ge1.$$
A:
The general term will have, first of all, $x^{2n}$ in it, since we're looking at even powers of $x$. The denominator, in each case, is $2^{2n}(2n)!$. You can see this by separating out a factor of two from each multiplicand. The numerator of the coefficient appears to be $\frac{(4n-2)!}{2^{2n-1}(2n-1)!}$, but only for $n\geq 1$. Putting that all together, we have:
$$a_n=\frac{(4n-2)!}{2^{2n-1}(2n-1)!2^{2n}(2n)!}x^{2n} = \frac{(4n-2)!}{2^{4n-1}(2n)!(2n-1)!}x^{2n}, n\geq 1$$
To write out the entire series, you can use:
$$1+\sum_{n=1}^\infty \frac{(4n-2)!\,x^{2n}}{2^{4n-1}(2n)!(2n-1)!}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Simple update trigger on PostgreSQL returning errors
CREATE FUNCTION update_status() RETURNS TRIGGER AS '
BEGIN
SELECT status FROM animals
IF status = "Alive"
THEN
UPDATE animals SET status = "Sold" WHERE status="Alive";
END IF;
RETURN NULL;
END; ' LANGUAGE plpgsql;
CREATE TRIGGER updatetrigger AFTER UPDATE OF id_selling ON animals EXECUTE PROCEDURE update_status();
It says I'm not using the selected attributes, and I should use Perform instead of Select. But then it doesnt recognize the IF after the perform. I'm really new to these syntax, so it might be wrong. I think its clear what I want to do (and i believe it simple for someone with experience). Can you please help me with this problem?
A:
In standard SQL (and PostgreSQL), this is a quoted identifier (table name, column name, ...):
"Alive"
and this is a string literal:
'Alive'
You will be getting complaints about "unknown columns" because you're using the wrong quotes for your strings.
Functions are usually defined with dollar-quoting to avoid this sort of thing:
CREATE FUNCTION update_status() RETURNS TRIGGER AS $$
BEGIN
SELECT status FROM animals
IF status = 'Alive' THEN
UPDATE animals SET status = 'Sold' WHERE status = 'Alive';
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
Triggers have access to NEW and OLD to represent the previous/current state of the row and the new/updated state of the row, you should be consulting those instead of trying to SELECT to find the status:
CREATE FUNCTION update_status() RETURNS TRIGGER AS $$
BEGIN
IF NEW.status = 'Alive' THEN
UPDATE animals SET status = 'Sold' WHERE status = 'Alive';
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
You might want a little more in the WHERE clause for that UPDATE too, just WHERE status = 'Alive' seems a bit broad.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a function in sql server "isEmpty" return data if the select return empty result set
I have a table like this
EmpId No_of_days
1 24
2 28
6 24
7 30
8 10
9 15
when I write a select statement
SELECT No_of_days FROM _table WHERE EmpId = 3 or 4 or 5
I got an empty result set.
I want the result set return 0 days for employees 3 and 4 and 5
A:
You can use a values() construct & do left join :
select tt.empid, isnull(t.No_of_days, 0)
from ( values (3), (4), (5)
) tt (empid) left join
table t
on t.empid = tt.empid;
EDIT : If you have a more employees id then you have to maintain one staging table & do left join :
select tt.empid,
ISNULL(t.No_of_days, 0)
from table tt left join -- possible employee id table
[_table] t
on t.empid = tt.empid;
A:
Assuming that you have another table with all your employees in (if not, where are employees 3, 4 and 5 coming from?), you could use a LEFT JOIN onto your example table (_table):
SELECT e.empid,
ISNULL(t.No_of_days,0)
FROM Employee e --No idea what your employee table is actually called, so guessed.
LEFT JOIN _table t ON e.empid = t.empid;
This will provide rows for all your employees. If you wanted just 3, 4 and 5, then you would add your WHERE:
WHERE e.empid IN (3,4,5)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are these double negatives? "No it is not. No I don't think so."
A double negative is generally defined as two negative words in the same clause. In these examples:
"No it is not."
"No I don't think so."
is "No" considered a clause unto itself? Or is it in the same clause as the rest of the sentence, thus constituting a double negative?
A:
Yes, “no” is separate from the clause containing the verb. No, these are not double negatives.
Whether you consider “yes” and “no” clauses on their own is more contested, but it really doesn’t matter—they are not part of the clause that the double negatives would appear in. The fact that they (“yes” and “no”) are normally followed by a comma—and can perfectly well be followed by a period—indicates that they are separate entities:
No, it is not.
No. It is not.
In cases of double negations, such separations are not possible:
I ain’t got nothing against double negations.
*I ain’t got, nothing against double negations.
*I ain’t got. Nothing against double negations.
The last two of these are quite obviously not valid, since “I ain’t got” (or “I haven’t got”) is not a complete sentence.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can retrofit 2.3 can parse nested jsonObject and multiple Array with keys and values
As Couple day R&D, I found some solution can do this thing, However I can not show any response from JSON API with retrofit 2.3 version. I know this question could be duplicated, However, Could anybody help me. This is how JSON API look like
{
"GetInsertPageInfoResponse": {
"Request": {
"IsValid": "True",
"GetInsertPageInfoRequest": null
},
"GetInsertPageInfo": {
"1": [
{
"cat_name": "test1",
"image_thumb_path": "insertPage/thumb/taputapu",
"image_original_path": "upload/insertPage/original/book",
"cat_icon_path": "upload/insertPage/cat_icon/icon.png",
"cat_version": "8",
"item_id": "1",
"item_name": "01.jpg"
}
],
2: [
{
"cat_name": "test2",
"image_thumb_path": "upload/insertPage/thumb/taputapu",
"image_original_path": "photobook/upload/insertPage/original/book",
"cat_icon_path": "upload/insertPage/cat_icon/icon.png",
"cat_version": "6",
"item_id": "3",
"item_name": "08.jpg"
}
]
}
}}
This is what I tried to parse json, but it's still not working
public class APIClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
This is how I get the service
public interface APIService {
@GET("?Service=Core&Operation=GetInsertPageInfo")
Call<GetInsertPageInfoResponse> getInsertPageInfoCall();
}
public class APIUtils {
public static APIService getSOService() {
return APIClient.getClient(API_ROOT_URL).create(APIService.class);
}
}
I tried to use this POJOs
public class GetInsertPageInfoResponse {
@SerializedName("GetInsertPageInfoResponse")
@Expose
private GetInsertPageInfo getInsertPageInfo;
}
public class GetInsertPageInfo {
@SerializedName("GetInsertPageInfo")
@Expose
private Map<String, List<AsobieItem>> mPageInfo;
public Map<String, List<AsobieItem>> getmPageInfo() {
return mPageInfo;
}
public void setmPageInfo(Map<String, List<AsobieItem>> mPageInfo) {
this.mPageInfo = mPageInfo;
}
}
public class AsobieItem {
@SerializedName("cat_name")
@Expose
private String cateName;
@SerializedName("image_thumb_path")
@Expose
private String imageThumbPath;
@SerializedName("image_original_path")
@Expose
private String imageOriginalPath;
@SerializedName("cat_icon_path")
@Expose
private String catIconPath;
@SerializedName("cat_version")
@Expose
private String catVersion;
@SerializedName("item_id")
@Expose
private String itemId;
@SerializedName("item_name")
@Expose
private String itemName;
}
UPDATE!!
This is how I request by using retrofit 2 in Activity class:
APIService mApiService = APIUtils.getSOService();
public void callAPIGetInsertPageInfo() {
mApiService.getInsertPageInfoCall().enqueue(new Callback<GetInsertPageInfoResponse>() {
@Override
public void onResponse(Call<GetInsertPageInfoResponse> call, Response<GetInsertPageInfoResponse> response) {
if (response.isSuccessful()) {
Log.i("Response", response.body().toString());
Log.d("GetResponse", response.raw().toString());
} else {
int statusCode = response.code();
// handle request errors depending on status code
}
}
@Override
public void onFailure(Call<GetInsertPageInfoResponse> call, Throwable t) {
//TODO
}
});
}
When I Logged the Response, I see this error: Response ID 525295 is not served in this process.
A:
After couple day I found out by myself. I use the HashMap<> and List<List<Item>> to match with that kind of JSON API.
I declare a POJO with a List<Item> and a id to identify them
public class ListWithId {
private List<Item> items;
private int id;
public ListWithId(List<Item> items, int id){
this.items = items;
this.id = id;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
In the Activity.class I use this Object to strore all data into
private List<ListWithId> listTC;
public void callAPIGetInsertPageInfo() {
mApiService.getInsertPageInfoCall(Constants.CORE_PARAM, Constants.GET_RESPONSE_PARAM).enqueue(new Callback<GetInsertPageInfoResponse>() {
@Override
public void onResponse(Call<GetInsertPageInfoResponse> call, Response<GetInsertPageInfoResponse> response) {
if (response.isSuccessful()) {
for (Map.Entry<Integer, List<AsobieItem>> entry : response.body().getGetInsertPageInfo().getmPageInfo().entrySet()) {
listTC.add(new ListWithId(entry.getValue(), entry.getKey()));
}
mAdapter = new MyAdapter(Activity.this, listTC);
refreshAdapter();
// set adapter for list view
mListView.setAdapter(mAdapter);
} else {
int statusCode = response.code();
// handle request errors depending on status code
}
}
@Override
public void onFailure(Call<GetInsertPageInfoResponse> call, Throwable t) {
//TODO FAIL
}
});
}
When I get Logged to get the keys and values. It'll like this
Keys: 1
Values: "1":[{ListItem}, {ListItem}]
Keys: 2
Values: "2":[{ListItem2}, {ListItem2}]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ASP Button isn't working when OnClientClick is missing
i generated a page with an ASP Button which loads another page.
<asp:Button ID="ServerCredentials" runat="server" Text="Server Credentials" Font-Names="Verdana" Font-Size="12px" OnClick="Credential_Click" Width="135px"/>
Function which loads another page:
Protected Sub Credential_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Redirect("~/WebPage/Booking/ExchangeServer.aspx")
End Sub
This code only works when i registered on the page with exchange data.
when i am not registered, nothing happens.
But if i put a onclientclick with any function, it works again.
like this:
<asp:Button ID="ServerCredentials" runat="server" Text="Server Credentials" Font-Names="Verdana" Font-Size="12px" OnClientClick="return CheckDateVonBis()" OnClick="Credential_Click" Width="135px"/>
what is the difference between onclick and onclientclick?
how can i solve this problem?
A:
onclick for server side function and onclientclick for client side
OnClientClick : if you wish call javascript function
Link : http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.button.onclientclick(v=vs.80).aspx
OnClick : if you wish call code behind function declared in server side
Link : http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.button.onclick.aspx
|
{
"pile_set_name": "StackExchange"
}
|
Q:
3d camera calibration using opencv
I'm working on the calibration of a camera using opencv, I run the given sample project, my question is how to set the metric system in the input data for ex.:
<!-- The size of a square in some user defined metric system (pixel, millimeter)-->
<Square_Size>(1,10)</Square_Size>
does it mean that every pixel represent 10um ?
thanks in advance for you help
A:
Assuming you use the classic checkerboard for calibration, square size is the actual physical size of a square in that board. For example, if it is 10cm, you should put <Square_Size>10</Square_Size>. Alternatively, you could express it in inches and put <Square_Size>3.937</Square_Size>. This is the units that it refers to. The size is used by OpenCV to create the model coordinates and the units do not affect your resultant calibration parameters.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nvidia drivers installed, but not used
I have an Asus UL30JT. It has Nvidia Optimus technology which I am not really interested in.
I currently rarely use this laptop with it being connected to power. And I want to be able to play video at high res, play games and do some OpenCL coding.
In the BIOS I switched it to NVIDIA only (non windows 7).
Previously, this worked just fine, using the nvidia driver.
After upgrading everything was broken. I have added nomodeset and blacklist.nouveau=1 as kernel options.
The nvidia drivers install without error. However they are not found/used.
jockey-text -l
kmod:nvidia_310_updates - nvidia_310_updates (Proprietary, Enabled, Not in use)
kmod:nvidia_304_updates - NVIDIA binary Xorg driver, kernel module and VDPAU library (Proprietary, Disabled, Not in use)
kmod:nvidia_313_updates - NVIDIA binary Xorg driver, kernel module and VDPAU library (Proprietary, Disabled, Not in use)
kmod:nvidia_310 - NVIDIA binary Xorg driver, kernel module and VDPAU library (Proprietary, Disabled, Not in use)
kmod:nvidia_304 - NVIDIA binary Xorg driver, kernel module and VDPAU library (Proprietary, Disabled, Not in use)
Trying to load the module manually fails as well.
sudo modprobe nvidia
FATAL: Module nvidia not found.
Xorg.0.log show the following:
[ 12.028] Loading extension GLX
[ 12.028] (II) LoadModule: "nvidia"
[ 12.037] (WW) Warning, couldn't open module nvidia
[ 12.037] (II) UnloadModule: "nvidia"
[ 12.037] (II) Unloading nvidia
[ 12.037] (EE) Failed to load module "nvidia" (module does not exist, 0)
[ 12.037] (==) Matched nvidia as autoconfigured driver 0
[ 12.037] (==) Matched nouveau as autoconfigured driver 1
[ 12.037] (==) Matched vesa as autoconfigured driver 2
[ 12.037] (==) Matched modesetting as autoconfigured driver 3
[ 12.038] (==) Matched fbdev as autoconfigured driver 4
[ 12.038] (==) Assigned the driver to the xf86ConfigLayout
[ 12.038] (II) LoadModule: "nvidia"
[ 12.038] (WW) Warning, couldn't open module nvidia
[ 12.038] (II) UnloadModule: "nvidia"
[ 12.038] (II) Unloading nvidia
[ 12.038] (EE) Failed to load module "nvidia" (module does not exist, 0)
[ 12.038] (II) LoadModule: "nouveau"
[ 12.039] (WW) Warning, couldn't open module nouveau
I have installed the kernel headers, of the correct kernel.
I verified that the kernel options are in the grub configuration.
I have purged all nvidia packages and tried to reinstall (multiple times...)
Currently I am at a loss.
I have checked the following question:
Nvidia driver installation error
But nothing there worked for me.
A:
Okay, I found out of it.
I did a full apt-get purge nvidia* and apt-get dist-upgrade etc. But the thing that fixed it was actually to set the alternative correct. I guess this would've worked from the start. So here's how:
$ sudo update-alternatives --config x86_64-linux-gnu_gl_conf
Selection Path Priority Status
------------------------------------------------------------
0 /usr/lib/nvidia-310/ld.so.conf 9702 auto mode
1 /usr/lib/nvidia-310/ld.so.conf 9702 manual mode
* 2 /usr/lib/x86_64-linux-gnu/mesa/ld.so.conf 500 manual mode
As you see, for me, this setting was wrongly set. So I used 0 instead, and lo' and behold. Lots more nvidia- utilities in the PATH.
If you're not on 64-bit, then use i386 instead of x86_64.
A:
Install latest nvidia drivers
sudo apt-get install nvidia-313-updates
Generate /etc/X11/xorg.conf by executing
sudo nvidia-xconfig
Then execute
sudo software-properties-gtk which will show you a window like this
Select the latest driver from that list and then do
sudo reboot
|
{
"pile_set_name": "StackExchange"
}
|
Q:
EnumResourceNames issue - unknown error
I was recently working with resources from secondary libraries/binary modules and encountered a strange error.
I have two native WinAPI references:
[DllImport("kernel32.dll", SetLastError = true)]
public extern static bool EnumResourceNames(IntPtr hModule, int lpszType, EnumResNameProc lpEnumFunc, IntPtr lParam);
[DllImport("kernel32.dll", SetLastError=true)]
public extern static IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, int dwFlags);
When I call LoadLibraryEx, I am getting the IntPtr instance - just what I need:
IntPtr x = WinApi.LoadLibraryEx(@"D:\Software\Reflector\Reflector.exe",IntPtr.Zero,2);
Debug.WriteLine(x.ToInt32());
However, when I try to enumerate icon resources (defined by the ID = 3):
Debug.WriteLine(WinApi.EnumResourceNames(x, 3, new EnumResNameProc(ListCallback), IntPtr.Zero));
Debug.WriteLine(Marshal.GetLastWin32Error());
I am getting this error code (returned by GetLastError):
-532462766
This usually means there is an unknown error, as far as I know, but I am just curious - what could be the problem with listing resources from the executable?
A:
-532462766 == 0xe0434352. The last three hex pairs spell "CCR", a common trick that Microsoft programmers use to try to come up with an easily recognizable exception code. The exact meaning is quite mysterious, beyond it being commonly associated with managed code and seemingly being very low level in a sub-system that doesn't normally fail to produce a meaningful managed exception.
There is an excellent candidate reason for that mysterious exception, your EnumResources pinvoke declaration is wrong. The 2nd argument is IntPtr, not int. That has some odds of going kaboom on a 64-bit operating system.
Please post back if you ever figure out what CCR means.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
class Program {
static void Main(string[] args) {
try {
IntPtr module = LoadLibraryEx(@"C:\windows\system32\user32.dll", IntPtr.Zero, 2);
if (module == IntPtr.Zero) throw new Win32Exception();
if (!EnumResourceNames(module, (IntPtr)3, new EnumResNameProc(ListCallback), IntPtr.Zero))
throw new Win32Exception();
}
catch (Win32Exception ex) {
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
static bool ListCallback(IntPtr hModule, IntPtr type, IntPtr name, IntPtr lp) {
long idorname = (long)name;
if (idorname >> 16 == 0) Console.WriteLine("#{0}", idorname);
else Console.WriteLine(Marshal.PtrToStringAnsi(name));
return true;
}
public delegate bool EnumResNameProc(IntPtr hModule, IntPtr type, IntPtr name, IntPtr lp);
[DllImport("kernel32.dll", SetLastError = true)]
public extern static bool EnumResourceNames(IntPtr hModule, IntPtr type, EnumResNameProc lpEnumFunc, IntPtr lParam);
[DllImport("kernel32.dll", SetLastError = true)]
public extern static IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, int dwFlags);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Installing Baseboard Moulding with Brad Nailer
I am wanting to install my newly purchased wooden baseboard molding by using a Brad Nailer. I went to the Home Improvement store and bought what I thought was the correct tool. Turns out that the Brad Nailer I purchased requires an air compressor with it to work.
Long story short, I have done a bit of research and it seems like most people recommend using a pin/Brad nailer that can shoot 2" nails. I am wondering if it is a good idea to go ahead and return the brad nailer and get a cordless brad nailer instead. The problem is, these nail guns are insanely expensive so I want to make sure I am getting a tool that I can get my money back out of.
I know that you can use some of these nail guns to do other things as well like doors and crown molding etc.. My wife and I just purchased our first home and it is a very old home(90 years). We intend to remodel the entire house and we are about 30% of the way done. Is it worth the money to spend a couple hundred bucks on a finish/brad/nail gun, or should I find a way to borrow one/ rent one?
EDIT:
If there are any other recommendations for the installation of the baseboards, please go ahead and give some pointers. This is my first time installing them so I have only seen a video of someone doing it and so it would be nice to get some other input on the process.
A:
If you are renovating the whole house, or at least a good portion of it, I would purchase a nail gun over renting it or borrowing it. Owning it lets you use it when you need it, not like going to get a rental and returning it or being responsible for somebody elses' property. Get the compressor too, it does more than power nailers, it fills tires, blows dust off things big time, inflates balls for sports, etc.
Size your nails so it goes into the framing about 1". More is overkill, but a bit more works if that is the size of nails you have on hand. No finish nail needs to go in the framing more than 1 1/2" In that depth, the possibility of hitting wires or pipes grow. Kick plates that protect pipes and wires per the building code are only needed on wires and pipes closer than 1 1/4" from the face of the stud. That's why 1" is the sweet spot, good holding power and less chance to hit stuff in the wall. Using a nail that is too short will increase the chance of the trim coming loose.
Add up all the thicknesses of the material you are going through. In the case of a 1X6 baseboard and 1/2" sheetrock that is 1 1/4" of material, in my opinion a 2" (6D) nail is too short, it will need 8D nails (2 1/2" for the holding power required. With that size of nail, you will need a 15 or 16 gauge finish nailer. To set nails in the trim to the edge of a door jamb, an 18 gauge finish nailer will work there. With the larger nails around the edges holding the trim to the drywall you can go with a slightly smaller nail to hold the trim to the door or window jamb. 1 1/2" long is what I use there. You could use 2" but the chance of blowing out through the face of the jamb is high.
Big box stores usually have a combo kit, a compressor with 2 nail guns, a good deal, in my opinion.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Oracle database number type field not storing the value I put in
In oracle, when I try to save this value into a number type field: 37788024213340160 it gets converted to this: 3.77880242133402E16
Which is bad because it is rounding the value up, and I need it to keep the exact value that I put into the field.
Any idea how to stop this from happening?
In case this helps, here is the exact definition of the field in question (MIN_ID):
create table SUBGRP
(
ID NUMBER not null,
NAME VARCHAR2(128) not null,
MIN_ID NUMBER
)
A:
It's just a formatting / display issue:
SQL> create table subgrp (
2 id number not null,
3 name varchar2(128) not null,
4 min_id number
5 );
Table created.
SQL> insert into subgrp values ( 123, 'test', 37788024213340160 );
1 row created.
SQL> commit;
Commit complete.
SQL> select * from subgrp;
ID
----------
NAME
--------------------------------------------------------------------------------
MIN_ID
----------
123
test
3.7788E+16
SQL> col min_id format 999999999999999999999999999
SQL> /
ID
----------
NAME
--------------------------------------------------------------------------------
MIN_ID
----------------------------
123
test
37788024213340160
SQL>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to get node using xpath in soapUI
How can i access "AccountId" node from following response file using Xpath in soapUI 4.0.0?
Thanks in advance.
Response file is as follow,
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetResponse xmlns="http://www.xyz.com/cmw/tcm/account">
<GetResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Account>
<AccountId>14338049839</AccountId>
<AccountLabel>Spara Femman</AccountLabel>
<AccountRoleDTOList>
<AccountRole>
<AddressTypeId>REC</AddressTypeId>
<EndDay i:nil="true"/>
<ExtPosReference i:nil="true"/>
<HolderId>10533</HolderId>
<HolderName>TÄRNHOLMS HOTELL AB</HolderName>
<HolderTypeId>COR</HolderTypeId>
<IdentificationId>005164006917</IdentificationId>
<ReportProfileId>3</ReportProfileId>
<ReportProfileName>Standard</ReportProfileName>
<RoleDocumentPath i:nil="true"/>
<RoleId>HOL</RoleId>
<RoleName>Holder</RoleName>
<ShareOfAccount>100.00000</ShareOfAccount>
</AccountRole>
</AccountRoleDTOList>
<AccountTypeId>AGG</AccountTypeId>
<CloseDay i:nil="true"/>
<CurrencyId>SEK</CurrencyId>
<CustodianAccountId i:nil="true"/>
I have tried it by using following code... but it's not working
declare namespace i='http://www.w3.org/2001/XMLSchema-instance';
//i:GetResult[1]/Account[1]
But i am getting error like,
Missing content for xpath declare namespace i='http://www.w3.org/2001/XMLSchema-instance';
//i:GetResult[1]/Account[1] in response
A:
Try this
declare namespace i='http://www.w3.org/2001/XMLSchema-instance';
//i:GetResult[1]/i:Account[1]
OR
declare namespace i='http://www.w3.org/2001/XMLSchema-instance';
//i:GetResult[1]/*:Account[1]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Exception : Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL
I am not able to authenticate in symfony2 with the 'Employee' entity as it contains many mapping with other entities in my project. some of my mapping is as follows:
/**
* @var EmployeeDesignation
*
* @ORM\ManyToOne(targetEntity="EmployeeDesignation")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="employee_designation_id", referencedColumnName="id")
* })
*/
private $employeeDesignation;
/**
* @var EmployeeDesignation
*
* @ORM\ManyToOne(targetEntity="EmployeeType")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="employee_type_id", referencedColumnName="id")
* })
*/
private $employeeType;
Authentication works fine without any mapping. I have tried with 'Serialize()' and 'Unserialize()' methods in it like below:
class Employee implements AdvancedUserInterface, \Serializable {
/**
* serialize the username
* @return serialize
*/
public function serialize() {
return serialize($this->emailOfficial);
}
/**
* unserialize
* @param $data
*/
public function unserialize($data) {
$this->em = unserialize($data);
}
}
I am getting the following error after doing the above method:
You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.
I have tried this way so as to get rid of the previous error, which is as follows:
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL
So, can anybody please suggest a way to overcome from this problem?
A:
I have encountered something similar, and after some research, I tried the same things as you did.
But at some point, I found out that by setting the __sleep method, every thing worked fine.
class User implements PlayerInterface
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
...
public function __sleep()
{
return array('id');
}
...
Make sure that the field which is defined as @ORM\Id is part of the returned array.
Make sure to drop the browser cookie, since it uses the session.
I don't know exactly why it causes this when setting up a new association (mine was a ManyToMany), but It probably originate from this place:
// see Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse()
...
$event->getRequest()
->getSession()
->set('_security_'.$this->contextKey, serialize($token));
...
Hope this could help someone.
Edit:
References:
http://forum.symfony-project.org/viewtopic.php?f=23&t=35764
http://translate.google.com/translate?hl=en&sl=es&u=http://jonsegador.com/2012/03/error-con-symfony2-you-cannot-refresh-a-user-from-the-entityuserprovider-that-does-not-contain-an-identifier/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Array transformation with angular.forEach - AngularJS
I have data I'm fetching from a REST API that I want to create a new object using Angular before passing it back to my API using $http
orderItem: {
id: 159
name: Empanadas (Choice of 2)
description: Choice of Diced Beef; Spinach, Stilton and Onion; or Smoked Ham and Mozzarella
price: 700
available: 1
created_at: 2016-01-31 16:50:31
updated_at: 2016-01-31 16:50:31
menu_category_id: 41
restaurant_id: 11
menu_modifier_groups:
[ {
id: 9
name: Choose 2 Empanadas
instruction: null
min_selection_points: 2
max_selection_points: 2
force_selection: 1
created_at: 2016-02-01 01:03:35
updated_at: 2016-02-01 01:12:23
menu_item_id: 159
restaurant_id: 11
menu_modifier_items:
[ {
id: 34
name: Diced Beef
price: 0
created_at: 2016-02-01 01:04:08
updated_at: 2016-02-01 01:04:08
menu_modifier_group_id: 9
restaurant_id: 11
menu_item_id: 159
selected: true
} , {
id: 35
name: Smoked Salmon & Mozzarella
price: 0
created_at: 2016-02-01 01:04:37
updated_at: 2016-02-01 01:04:37
menu_modifier_group_id: 9
restaurant_id: 11
menu_item_id: 159
selected: true
} , {
id: 36
name: Stilton, Spinach and Onion
price: 0
created_at: 2016-02-01 01:05:05
updated_at: 2016-02-01 01:05:05
menu_modifier_group_id: 9
restaurant_id: 11
menu_item_id: 159
selected: false
} ]
} ]
}
As you can see I have orderItem which contains several menu_modifier_groups which then contain several menu_modifier_items
What I want to do is transform this data into;
cartItem and cartModifierItems
cartItem will be:
id: 159
name: Empanadas (Choice of 2)
description: Choice of Diced Beef; Spinach, Stilton and Onion; or Smoked Ham and Mozzarella
price: 700
available: 1
created_at: 2016-01-31 16:50:31
updated_at: 2016-01-31 16:50:31
menu_category_id: 41
restaurant_id: 11
cartModifierItems: // an array containing all menu_modifier_items from all the menu_modifier_groups where selected = true
And then cartModifierItems will be all menu_modifier_items from all the menu_modifier_groups where selected: true that way I'm left with cartItem and cartItem.cartModifierItems
Any help or guidance appreciated.
A:
Here's a function that accepts orderItem and outputs cartItem:
function makeCartItem(orderItem) {
var cartItem = angular.copy(orderItem)
delete cartItem.menu_modifier_groups
cartItem.cartModifierItems = orderItem.menu_modifier_groups.reduce(function(acc, menuModifierGroup) {
const selectedItems = menuModifierGroup.menu_modifier_items.filter(function(item) {
return item.selected
})
return acc.concat(selectedItems)
}, [])
return cartItem
}
// {
// "id": 159,
// "name": "Empanadas (Choice of 2)",
// "description": "Choice of Diced Beef; Spinach, Stilton and Onion; or Smoked Ham and Mozzarella",
// "price": 700,
// "available": 1,
// "created_at": "2016-01-31 16:50:31",
// "updated_at": "2016-01-31 16:50:31",
// "menu_category_id": 41,
// "restaurant_id": 11,
// "cartModifierItems": [
// {
// "id": 34,
// "name": "Diced Beef",
// "price": 0,
// "created_at": "2016-02-01 01:04:08",
// "updated_at": "2016-02-01 01:04:08",
// "menu_modifier_group_id": 9,
// "restaurant_id": 11,
// "menu_item_id": 159,
// "selected": true
// },
// {
// "id": 35,
// "name": "Smoked Salmon & Mozzarella",
// "price": 0,
// "created_at": "2016-02-01 01:04:37",
// "updated_at": "2016-02-01 01:04:37",
// "menu_modifier_group_id": 9,
// "restaurant_id": 11,
// "menu_item_id": 159,
// "selected": true
// }
// ]
// }
Your question isn't really about angular, but more about data transformation in JavaScript. Check out the methods and functions I've used to achieve the result:
angular.copy. Creates a deep object copy. In conjunction with delete I made a new orderItem-derived copy without menu_modifier_groups:
var cartItem = angular.copy(orderItem)
delete cartItem.menu_modifier_groups
{
"id": 159,
"name": "Empanadas (Choice of 2)",
"description": "Choice of Diced Beef; Spinach, Stilton and Onion; or Smoked Ham and Mozzarella",
"price": 700,
"available": 1,
"created_at": "2016-01-31 16:50:31",
"updated_at": "2016-01-31 16:50:31",
"menu_category_id": 41,
"restaurant_id": 11
}
Array.prototype.reduce. When called on menu_modifier_groups, it accumulates every value into new array (second argument) returned from the function passed as a first argument.
Array.prototype.filter. Filters menu_modifier_items by a function passed into it. If any traversed item has truish selected, then it gets picked.
Array.prototype.concat. Combines accumulator array with selected items array into a new array that contains both.
JSBin.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jquery click background pos Y + count++
I have a div with overflow hidden with a set height and inside I have an image with position relative and top: 0px
I would like to know how I can add a count to css position top: 0px so every time the user click on the "up button", the image moves by 10px up within the div.
I can't seem to get the count++ to work, please see JS Fiddle here: http://jsfiddle.net/michelm/wE2Tz/
//var count = 10++;
$('#button_up').click(function(){
$('#banner img').css('top', '-10px') ;
});
$('#button_down').click(function(){
$('#banner img').css('top', '10px');
});
A:
Try with:
$('#button_up').click(function(){
$('#banner img').css('top', '-=10px') ;
});
$('#button_down').click(function(){
$('#banner img').css('top', '+=10px');
});
Working example here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Router.use() requires middleware function but got a string?
I have looked on the forums and have tried fixing everything I could, but still can't seem to get it to work. I am wanting to use router instead of having to use app.get. I have another project in which I am doing the same thing and it works just fine. So I am a little confused as to why this one isn't working. Thank you very much.
Here is my app.js:
var express = require("express");
var app = express();
var indexRoutes = require("./routes/index.js");
app.use("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use("/", indexRoutes);
app.listen(process.env.PORT, process.env.IP, function() {
console.log("server started on port : " + process.env.PORT);
});
Here is the route I am using:
var express = require("express");
var router = express.Router();
var multer = require("multer");
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads');
},
filename: function(req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({storage: storage}).single('userPhoto');
router.get("/", function(req, res) {
res.render("index");
});
router.post("/uploads", function(req, res) {
upload(req, res, function(err) {
if(err) {
return res.send("error uploading file");
}
res.end("file is uploaded");
});
});
module.exports = router;
A:
This obviously isn't right:
app.use("view engine", "ejs");
It should be:
app.set("view engine", "ejs");
FWIW, if you closely look at the stack trace that accompanied the error, you would have found the exact line in app.js that triggered the error:
TypeError: Router.use() requires middleware function but got a string
at Function.use (/private/tmp/node_modules/express/lib/router/index.js:458:13)
at EventEmitter.<anonymous> (/private/tmp/node_modules/express/lib/application.js:220:21)
at Array.forEach (native)
at EventEmitter.use (/private/tmp/node_modules/express/lib/application.js:217:7)
at Object.<anonymous> (/private/tmp/t/app.js:5:5) <--- there!
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
error: not an enclosing class: MainActivity
Here is my code I am getting Error: error: not an enclosing class: MainActivity. Please help me what is the issue in my code.
public class MyFirebaseMessagingSerivce extends FirebaseMessagingService {
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN", s);
}
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
public void onCreate() {
super.onCreate();
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MainActivity.this, new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult)
{
String updatedToken = instanceIdResult.getToken();
Log.e("Updated Token",updatedToken);
}
});
}
}
A:
Can we use this one in FirebaseMessagingService?
No the FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener() method is used to get token inside activity
The onNewToken() method is used to get token inside FirebaseMessagingService
For more information check this answer of Frank van Puffelen how onNewToken and FirebaseInstanceId.getInstance().getInstanceId() will work
Also check this for FirebaseMessagingService
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MainActivity.this, new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult)
{
String updatedToken = instanceIdResult.getToken();
Log.e("Updated Token",updatedToken);
}
});
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Consuming WCF service from Business Logic Layer
I have a solution with the following structure:
Domain (.NET 4.6.1)
DAL (.NET 4.6.1)
BLL (.NET Core 2.0)
API (.NET Core 2.0)
I have a requirement to submit data to an external WCF service. I personally do not have a lot of experience with WCF as I have been working with REST APIs. So to try out consuming a WCF service, I have set up a .NET core console application in and added a connected service reference to it. This resulted in a generated Reference.cs with the following classes:
IWebService
IWebServiceChannel
SendResponse
GetResponse
WebServiceClient (implementing IWebService)
I was thinking about creating a SubmissionService class in the BLL layer to submit data to the WCF service, so I moved IWebService from the console app to the BLL layer to inject into the class and perform unit testing. The attributes defined on the IWebService requires a reference to System.ServiceModel which comes with a lot of baggage and it does not make sense to reference it in my BLL layer.
I am not sure where to put the WCF client in my project structure. I have been investigating this issue and the only viable solution I can think of is to create a class library project purely for the WCF client and reference that in my BLL layer to have access to IWebService and mock it for testing. Has anyone been in the same situation? Any help is greatly appreciated.
A:
You are missing a 'layer', namely the Composition Root. (for a more detailed explanation, see section 4.1 of this book).
You can define your own application-specific abstraction that allows the BLL to talk with the WCF service (through that abstraction). That abstraction can be located in the BLL.
Within your Composition Root, you can create an adapter on top of that application-specific abstraction that calls into the WCF service, using the WCF client, which can be generated inside the Composition Root as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to customize Bootstrap in rails 4
I am using Bootstrap with my rails app.
Here is my application.scss
*= require_tree .
*= require_self
*/
@import "bootstrap-sprockets";
@import "bootstrap";
@import "colors";
@import "custom";
so after importing bootstrap i import custom.scss
Here i have strange behaviour.
In custom.scss i have:
@import "colors";
.navbar-default {
background: $primary-color;
a {
color: $white;
}
}
So my navbar-default background color is overwritten to my primary-color, but link color is still default. Inspecting in browser i see that my custom style for link is crossed and default is used. Very strange.
A:
The selector used by Bootstrap is this .navbar-default .navbar-nav>li>a which is more specific than your selector (.navbar-default a) and so it will always take precedent.
Try this...
.navbar-default {
background: $primary-color;
.navbar-nav {
>li {
>a {
color: $white;
}
}
}
}
DEMO
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Overlaying two plots using ggplot2 in R
There are two data frames - df1 & df2 from which I need to create line plot using ggplot2 and display on the same graph.
df1
x y
2 30
4 25
6 20
8 15
df2
x y
2 12
4 16
6 20
8 24
for plotting the first df,
p1 <- ggplot( df1, aes(x = df1[,1] , y = log(df1[,2]) ) )
p1 <- p1 + geom_line(aes(y = log(df1[,2])))
p1
how do we get a same plot overlay on same graph for data frame df2
A:
If you redefine data, that will change where that geom layer is sourcing from. ggplot will always look to the initializing call for the aesthetic mappings and try to inherit from there, so you don't need to redfine aes() unless you want to change/add a mapping.
Also no need to use the df[,2] syntax, ggplot is already looking inside df1 as soon as you set data = df1.
df1 <- data.frame(x = seq(2, 8, by = 2),
y = seq(30, 15, by = -5))
df2 <- data.frame(x = seq(2, 8, by = 2),
y = seq(12, 24, by = 4))
ggplot(df1, aes(x, log(y))) +
geom_line() +
geom_line(data = df2, color = "red") # re-define data and overwrite top layer inheritance
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Phtml block in sales email template from admin
I'm trying to add a phtml block to the sales email using the admin area to edit the template. In Magento 1.x this worked fine, however I'm not sure how to do this the same way in Magento 2.3x?
I've added {{block class='Magento\\Framework\\View\\Element\\Template' area='frontend' template='Vendor_Module::email/ordertrustpilot_afs.phtml'}}
to the template, however I get an error in the log for main.CRITICAL: Invalid template file: 'Vendor_Module::email/ordertrustpilot_afs.phtml' in module: '' block's name: 'magento\framework\view\element\template_0' [] []
Where should I place the phtml file in Magento 2.3x for this to work as intended?
Many thanks
EDIT:
Following Amitkumar's advice I can now output using phtml, however I now need to see why the code in the phtml does not work. I'm using the same code as I did in Magento 1.x which is now obviously wrong.
echo "START"; works at the beginning of the phtml and shows in the email content, however the rest of the code doesn't seem to execute or produce an output or an error.
The code used is below and should output various order details needed to send to Trust Pilot to automate product reviews:
<?php echo "START"; ?>
<?php $finalorderid = $this->getIncrementId() ?>
<?php $_order = $this->getOrder(); ?>
<?php if (!empty($_order)): ?>
<?php $orderId = $_order->getIncrementId(); ?>
<?php $orderRecipientName = $_order->getCustomerName(); ?>
<?php $orderRecipientEmail = $_order->getCustomerEmail(); ?>
<?php $productsData = ""; ?>
<?php $i=0; foreach ($_order->getAllItems() as $_ship): ?>
<?php $_item = Mage::getModel('catalog/product')->load($_ship->getProductId()); ?>
<?php $productsData .= ($i == 0) ? "{" : ",{" ?>
<?php $productsData .= '"productUrl": "'.Mage::getBaseUrl().$_item->getData('url_key').'.html",'; ?>
<?php $productsData .= '"imageUrl": "'.$_item->getImageUrl().'",'; ?>
<?php $productsData .= '"name": "'.$_item->getName().'",'; ?>
<?php $productsData .= '"sku": "'.$_item->getSku().'",'; ?>
<?php $productsData .= '}'; $i++;?> <?php endforeach; ?>
<?php echo '<script type="application/json+trustpilot">{'; ?>
<?php echo '"templateId": "599c4755e05df80becabb8ae",'; ?>
<?php echo '"locale": "en-GB",'; ?>
<?php echo '"recipientEmail": "'.$orderRecipientEmail.'",'; ?>
<?php echo '"recipientName": "'.$orderRecipientName.'",'; ?>
<?php echo '"referenceId": "'.$orderId.'"'; ?>
<?php if (!empty($productsData)): ?>
<?php echo ', "products": ['; ?>
<?php echo $productsData; ?>
<?php echo ']'; ?>
<?php endif; ?>
<?php echo '}'; ?>
<?php echo '</script>'; ?>
<?php endif; ?>
A:
Please refer to this answer
Add custom block in transnational email.
Let me know if it is not working
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Nginx still serving static files although website access is blocked
I have nginx installed on my centos server. I have blocked all external access to a test website I am working on. With this code.
location / {
auth_basic "Administrator Login";
auth_basic_user_file /home/config-files/.htpasswd;
}
The problem is it's not blocking access to static files. I can still access files like this.
wp-admin/images/icons32-vs-2x.png
wp-admin/css/colors/midnight/colors.min.css
wp-content/themes/testtheme/style.css
Why Nginx is not blocing access to these files.
EDIT Here is full virtual host file.
server {
listen 80;
server_name www.domainname.com;
root /home/myuser/domainname.com/public;
index index.html index.php;
access_log /home/myuser/domainname.com/logs/access.log;
error_log /home/myuser/domainname.com/logs/error.log;
location ~ /\.svn/* {
deny all;
}
location ~ \.(htaccess|htpasswd) {
deny all;
}
location ~ \.conf$ {
deny all;
}
location / {
try_files $uri $uri/ /index.php?$args;
auth_basic "Administrator Login";
auth_basic_user_file /home/config-files/.htpasswd;
}
location ~ \.(css|js) {
rewrite ^(.*/?)([a-z]+)-([0-9]+)\.(css|js)$ /$1$2.$4 last;
}
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
location ~* \.(js|css)$ {
expires 30d;
log_not_found off;
}
location ~* \.(?:ico|gif|jpe?g|png|svg)$ {
expires 180d;
add_header Pragma public;
add_header Cache-Control "public";
log_not_found off;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$; #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000;
}
rewrite ^(.*)/undefined$ /$1 permanent;
rewrite ^(.*)/undefined/$ /$1 permanent;
}
A:
nginx is matching 'location' sections not by order but by most-specific, read here. It is then applying only the best-matching location section to the request, and none of the others. Therefore, "location /" will only act on requests that are not matched by any of the other location sections (all of them being more specific).
Try to put the auth directives outside any location bracket, straight into server{}.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
No such property: pom for class: Script1
I'll say it right away: I never worked with Maven/Groovy, however, recently I got the job to write a script that automatically creates an enum out of a .properties file.
I use the GMavenPlus plugin for this. I already wrote the script modelled after the answer to this question. The reason why I can't use the same pom as in the answer is because it uses GMaven, which was discontinued.
Now, when I am trying to run it over cmd I get the Error
Failed to execute goal org.codehaus.gmavenplus:gmavenplus-plugin:1.5:execute <create-enum> on project gui: Error occurred while calling a method on a Groovy class
from classpath. InvocationTargetException: No such property: pom for class: Script1 -> [Help 1]
And here are the important parts of my pom.xml:
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>create-enum</id>
<phase>generate-sources</phase>
<goals>
<goal>execute</goal>
</goals>
</execution>
</executions>
<configuration>
<scripts>
<script><![CDATA[
import java.io.File
import com.cclsd.gdg.client.EnumGenerator
File dir = new File( pom.basedir,
"src/main/resources/com/cclsd/gdg/client")
new EnumGenerator(
new File( pom.build.directory,
"generated-sources/enums"),
new File(dir,
"properties/config.properties"),
new File(dir,
"EnumTemplate.txt"),
"com.cclsd.gdg.client.data",
"PropertyEnum"
)
]]></script>
</scripts>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<!-- any version of Groovy \>= 1.5.0 should work here -->
<version>2.4.7</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.codehaus.gmavenplus
</groupId>
<artifactId>
gmavenplus-plugin
</artifactId>
<versionRange>
[1.0.0,)
</versionRange>
<goals>
<goal>execute</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute>
<runOnIncremental>false</runOnIncremental>
</execute>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
Note: everything under the pluginmanagement tag I got from the official m2e site and should cause the script to be executed at the generate-sources phase
I really need someone to help me here, I literally couldn't find a single thing on Google about this error. Also a comprehensive tutorial about executing scripts in maven over all would be nice.
Have a nice day ~Crowley
Edit: it also displays the warning The POM for is invalid, transitive tendencies (if any) will not be available, enable debug logging for more details
A:
You are accessing a pom property in your script, which are not provided by the gmaven plugin. In this kind of script, you can use a project properties, which is an instance of MavenProject.
For example :
File dir = new File(project.basedir, "src/main/resources/com/cclsd/gdg/client")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What doesn vintage mean in "1980-vintage person"?
What does vintage mean in "1980-vintage person"?
I lookup up in dictionary, but still cannot find one meaning or usage that fits here.
A:
This sentence is probably a noun usage of vintage, meaning the year that a wine was made. For example, the following sentence refers to wine produced in 1983.
The 1983 vintage was one of the best
If taken literally, a 1980-vintage person is therefore somebody that was born in 1980, however it might also be used to refer to somebody born in approximately 1980, or even in the 1980's.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Optimize ucallwords function
The ucwords function in PHP doesn't consider non-whitespace to be word boundaries. So, if I ucwords this-that, I get This-that. What I want is all words capitalized, such as This-That.
This is a straightforward function to do so. Anyone have suggestions to improve the runtime?
function ucallwords($s)
{
$s = strtolower($s); // Just in case it isn't lowercased yet.
$t = '';
// Set t = only letters in s (spaces for all other characters)
for($i=0; $i<strlen($s); $i++)
if($s{$i}<'a' || $s{$i}>'z') $t.= ' ';
else $t.= $s{$i};
$t = ucwords($t);
// Put the non-letter characters back in t
for($i=0; $i<strlen($s); $i++)
if($s{$i}<'a' || $s{$i}>'z') $t{$i} = $s{$i};
return $t;
}
My gut feeling is that this could be done in a regular expression, but every time I start working on it, it gets complicated and I end up having to work on other things. I forget what I was doing and I have to start over. What I'd really like to hear is that PHP already has a good ucallwords function that I can use instead.
A:
A regular expression is easy for this:
$s = 'this-that'; //Original string to uppercase.
$r = preg_replace('/(^|[^a-z])[a-z]/e', 'strtoupper("$0")', $s);
This assumes that $s is lower case. You can use a-zA-Z in the second line to match upper and lower case letters. Alternately, you can wrap $s in the second line with strtolower($s).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Format for a url that goes to Google image search?
I have a web page which has links at the bottom like this:
- <a href='http://www.google.com/q?rome+photos'>photos of rome</a>
- <a href='http://www.google.com/q?paris+photos'>photos of paris</a>
- <a href='http://www.google.com/q?london+photos'>photos of london</a>
The idea is that if somebody clicks we go to Google search image page and we search for those images of those cities.
The questions are:
what's the right URL for starting an image search in Google
is there a place in Google documentation where I can find this ? (I searched and could not find it)
does Google restrict this type of usage for some reasons?
Edit:
The 3rd point is very important to me:
it's okay to work out the url from blogs and others but the question remains:
is google okay with this ?
will it ever discourage this approach ?
if so then all my urls would become suddenly worth nothing
A:
url: https://www.google.com/search?tbm=isch&q=findSomeImage,
Nothing official that I'm aware of, but this blog has some documentation.
Nope, no limit you should worry about if you're manually clicking the urls. (I'm sure google has some kind of flood protection against bots, though)
So, the only change you have to make, is to add the tbm=isch option to your urls.
A:
http://www.google.com/search?q=<SEARCH TERM>&tbm=isch
The tbm=isch is the internal google search parameter that determines what kind of search to perform. There doesn't seem to be any official documentation on it, but this page has a decent write up:
Google Search Request Params
EDIT:
It looks like if you don't include the "/search" part of the string, it fills the google searchbox, but doesn't actually execute the search.
A:
Use the "images" keyword instead of "search" (this should also work for "videos", "maps", etc.)
http://www.google.com/images?q=your+search+terms
https://productforums.google.com/d/msg/websearch/No-YWMdgFp8/l_SNghlwCV0J
Update
Following Chris F Carroll's comment below, I had a look with Fiddler. The /images request results in a 301 (moved permanently) response with the redirect URL in the format www.google.com/search?q=search+terms&tbm=isch as described by other answers here.
Contrary to what I said above (taken from the linked article), the /video request doesn't work. /maps does work, and doesn't result in a redirect.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Visualforce Remoting Exception: Error parsing json response: 'Unexpected token <'. Logged in?
I am trying to use VF remoting in a public site and get the error 'Visualforce Remoting Exception: Error parsing json response: 'Unexpected token <'. Logged in?' when viewing page from a public site guest user context. The remoting is being used by a jquery autocomplete component.
If I test the page from a non-url redirected, sys admin perspective it works as expected.
The site does use URL rewrites, and the site guest user profile has access to all information being searched in the database. It seems to be an authentication issue? If anyone has seen anything like this and has any suggestions re resolution they'd be most appreciated. Im stuck!
Cheers,
CH
A:
Ok - looks like someone else sorted this and I just stumbled onto their great response.
The issue lies in the url rewriter class, and the mapping from an external 'pretty' url to an internal url with '/apex/' in it makes SF decide it needs to be logged in whilst accessing the remoting logic.
Thus, when the VF remoting request is made we need to ignore it and let it pass unchanged. Per the great solution writeup at following link,you check the inbound url for contains 'apexremote' as indicator of whether to exclude from mapping logic.
See https://developer.salesforce.com/forums/ForumsMain?id=906F000000099DOIAY for more details.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
.NET Speech recognition of predefined text
I'm developing an application where the user read some predefined text and we use a speech recognition engine the transcript what he said. Then we compare the result with the predefined text to find which sentence or part of the text he is reading.
We were using Nuance NDev as our Speech Recognition engine but it cost too much now and we are trying to find another alternative.
So I was experimenting with the .NET speech recognition engine, but I was not able to find a way to achieve this.
From my test:
The dictation grammar is good because it translate every word the user says, but the result is really chaotic so it's almost impossible to find a match.
The mix of GrammarBuilder and Choises class is more like a command => action type of thing and it does not translate all the words the user says, it just search for one particular word/command and prints it.
So what I was wondering is if there is a way to get a grammar with the dictation like behaviour but only with a subset of words, like all the words in my predefined text or something that lets me set words/sentences to help the recognition engine.
For exemple if I give the engine this predefined text :
One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin.He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections.
It will only be able to return words from this text. So the recognition will be easier and more accurate.
If you have any ideas on how to achieve this or any other alternative, I'm all ears. The only limitation, is that it must support english and french language.
Thanks.
A:
One option would be to try pocketsphinx engine from CMUSphinx through interop C# bindings. It allows you to specify a language model compiled from the text, it will accurately detect the words then.
Models for French and English are available.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why wxwidgets draw loosely the circles or rounded polygons?
For example, if I draw this circle
is clearly imprecise and ugly. Is there any way to adjust the sensitivity of the draw?
edit:
I can summarize to:
self.da = wx.Panel(self, -1, size=(-1, 800))
self.da.Bind(wx.EVT_PAINT, self.paint)
self._buffer = wx.EmptyBitmap(500,500) # creating empty buffer
dc = wx.MemoryDC(self._buffer) # to handle the buffer
dc.SetBackground( wx.Brush("White") ) # setting background
dc.DrawCircle(50,40,100) #drawing circle
def paint(self, evt):
dc = wx.BufferedPaintDC(self.da, self._buffer) #on paint event draw this
A:
You can use wx.GCDC because it support anti-aliased drawing
Try this:
buffer = wx.EmptyBitmap(500,500) # creating empty buffer
dc = wx.MemoryDC(buffer) # to handle the buffer
dc = wx.GCDC(dc)
dc.SetBackground( wx.Brush("White") ) # setting background
dc.DrawCircle(50,40,100) #drawing circle
dc.DrawCircle(200,200,100) #drawing circle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does polarization and/or grounding of outlets affect time for breakers to trip?
I'm trying to understand all the differences between newer and older receptacles.
Newer ones tend to be polarized and many receptacles and wires come with grounding conductors. How do these technologies affect the performance of breakers as a safety feature in circuits?
I read someplace that grounding increases the speed at which a breaker trips when there is a problem like a short circuit. I'm not sure that makes sense to me. If there's a short circuit and no ground, the conductor would heat up/increase in amperage, tripping a breaker. If there's a short circuit and ground, most excess amperage would safely find its way out of the circuit through ground, reducing the chance that stray amperage would cause damage someplace, but not necessarily 'tripping a breaker faster'.
I'm still learning about the benefits of polarizing receptacles so I can't comment much on how I'd expect those to affect breakers tripping.
A:
When you talk about the safety function of "breakers", one generally expects to be talking about overcurrent protection. There is also ground-fault (residual current) protection in GFCI/RCD+overcurrent combo breakers, and there is arc-fault protection in AFCI+overcurrent combo breakers.
There are several kinds of safety at work here.
Polarization
Is generally about life safety. The general idea is that of the two conductors, hot and neutral, one of them is fairly near earth potential because neutral is pegged to earth in the main service. You are unlikely to be shocked if you get between neutral and earth, as there'll only be a volt or two of difference there.
Therefore on a polarized machine, the "hot" part of the machine is made innermost - the least likely for you to come in contact with.
This will not make overcurrent protection more likely to trip. If a faulty polarized machine came in contact with a well-grounded feature like a water pipe, the part coming into contact is more likely to be at neutral potential, which will not make overcurrent protection trip.
It may make GFCI protection trip, and the arcing could cause AFCI to trip.
Grounding/Earthing
This is about both life safety and fire prevention.
The idea of grounding is that if the machine has an internal problem, and "hot" goes somewhere it should not be going, the first place it will go is the grounded surfaces/chassis/etc. This impacts life safety because the "hot" goes to ground instead of via a human to another ground. Electricity takes all paths in proportion to their conductivity (1/resistance), and the ground provides a very, very good path which should carry virtually all of the current.
So yes, ground gives a very good path for a faulting device to trip the overcurrent device. You were told correctly.
It impacts fire protection because if it flows enough current to start a fire, the current will be efficiently carried back to the main panel and through the neutral-ground bonding back to source (neutral), allowing high currents to flow, which the breaker will detect and overcurrent trip. In other words, the goal is to turn a ground fault into a bolted ground fault and assure a trip. Without this grounding, a much lesser amount of current could flow, not assuring a trip.
A GFCI breaker will trip on even a very small leakage current. Again, ground helps even a small current find its way back, to assure that the GFCI will trip. By giving current a path to arc against, this also helps an AFCI trip.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Popover not showing on first click for dynamically generated content
I'm trying to get a popover for my webpage. It doesn't work for me on the first click but however works fine thereafter. I realize that it gets instantiated on the first click and therefore doesn't show up. Is there a better way to instantiate it, given that I'm using id's that are generated at runtime. I have looked at similar questions but they don't seem to work for me. Here is the code I have written,
<table id="userInfo">
<thead>
<tr>
<th>UserGroup</th>
</tr>
</thead>
<tbody>
<% @userdetails.each do |user| %>
<tr>
<td>
<a class='user_show_more' data-placement='left' id='<%= user %>'>[+]</a>
<!-- popover table starts here -->
<div id="<%= user %>_popover" style="display: none">
<table>
<thead>
<tr>
<th>UserNames</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<%= user['name'] %>
</td>
</tr>
</tbody>
</table>
</div>
<!-- popover ends here -->
<% user['group'] %>
</td>
</tr>
<% end %>
</tbody>
</table>
And my javascript code looks like this,
$('.user_show_more').on('click', function (e) {
var $this = $(this)
var popover_id = '#'+$this.attr("id");
$(popover_id).popover({
html : true,
content: function() {
var popover = '#'+$this.attr("id")+'_popover';
return $(popover).html();
}
});
});
A:
You can add two click handlers to your popovers. The first one uses 'one' and the second one uses 'on'.
https://jsbin.com/kegovebufu/1/edit?html,js,console,output
HTML
<button type="button"
class="btn btn-lg btn-danger"
data-toggle="popover"
id="Temp"
>Stuff</button>
<script type="text/html" id="Temp_popover">
<div>
<table>
<thead>
<tr>
<th>UserNames</th>
</tr>
</thead>
<tbody>
<tr>
<td>blah</td>
</tr>
</tbody>
</table>
</div>
</script>
Javascript
function PopoverClick()
{
$(this).popover('toggle');
}
$('[data-toggle="popover"]').one('click',function(e){
console.log('once');
var _this = $(this);
_this.popover(
{
html:true,
content: function()
{
return $('#'+$(this).attr("id")+'_popover').html();
},
trigger: 'manual',
placement:'right'
}).popover('show');
_this.on('click',PopoverClick);
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
java, convert string to double for any locale
I know that there is already a similar question about this, but this one is a bit different.
Say we have a string, and we know it can be converted to a double, but we know nothing about the locale of it. Maybe its locale is English (with dot as separator) or French (with comma as separator), or something else.
So, how do I convert it to the right double value?
A:
If you want to parse a number from the "users" (default) locale, then maybe this could help you:
double number = java.text.NumberFormat.getInstance().parse(stringNumber).doubleValue();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python - C embedded Segmentation fault
I am facing a problem similar to the Py_initialize / Py_Finalize not working twice with numpy .. The basic coding in C:
Py_Initialize();
import_array();
//Call a python function which imports numpy as a module
//Py_Finalize()
The program is in a loop and it gives a seg fault if the python code has numpy as one of the imported module. If I remove numpy, it works fine.
As a temporary work around I tried not to use Py_Finalize(), but that is causing huge memory leaks [ observed as the memory usage from TOP keeps on increasing ]. And I tried but did not understand the suggestion in that link I posted. Can someone please suggest the best way to finalize the call while having imports such as numpy.
Thanks
santhosh.
A:
I recently faced a very similar issue and developed a workaround that works for my purposes, so I thought I would write it here in the hope it might help others.
The problem
I work with some postprocessing pipeline for which I can write a own functor to work on some data passing through the pipeline and I wanted to be able to use Python scripts for some of the operations.
The problem is that the only thing I can control is the functor itself, which gets instantiated and destroyed at times beyond my control. I furthermore have the problem that even if I do not call Py_Finalize the pipeline sometimes crashes once I pass another dataset through the pipeline.
The solution in a Nutshell
For those who don't want to read the whole story and get straight to the point, here's the gist of my solution:
The main idea behind my workaround is not to link against the Python library, but instead load it dynamically using dlopen and then get all the addresses of the required Python functions using dlsym. Once that's done, one can call Py_Initialize() followed by whatever you want to do with Python functions followed by a call to Py_Finalize() once you're done. Then, one can simply unload the Python library. The next time you need to use Python functions, simply repeat the steps above and Bob's your uncle.
However, if you are importing NumPy at any point between Py_Initialize and Py_Finalize, you will also need to look for all the currently loaded libraries in your program and manually unload those using dlclose.
Detailed workaround
Loading instead of linking Python
The main idea as I mentioned above is not to link against the Python library. Instead, what we will do is load the Python library dynamically using dlopen():
#include
...
void* pHandle = dlopen("/path/to/library/libpython2.7.so", RTLD_NOW | RTLD_GLOBAL);
The code above loads the Python shared library and returns a handle to it (the return type is an obscure pointer type, thus the void*). The second argument (RTLD_NOW | RTLD_GLOBAL) is there to make sure that the symbols are properly imported into the current application's scope.
Once we have a pointer to the handle of the loaded library, we can search that library for the functions it exports using the dlsym function:
#include <dlfcn.h>
...
// Typedef named 'void_func_t' which holds a pointer to a function with
// no arguments with no return type
typedef void (*void_func_t)(void);
void_func_t MyPy_Initialize = dlsym(pHandle, "Py_Initialize");
The dlsym function takes two parameters: a pointer to the handle of the library that we obtained previously and the name of the function we are looking for (in this case, Py_Initialize). Once we have the address of the function we want, we can create a function pointer and initialize it to that address. To actually call the Py_Initialize function, one would then simply write:
MyPy_Initialize();
For all the other functions provided by the Python C-API, one can just add calls to dlsym and initialize function pointers to its return value and then use those function pointers instead of the Python functions. One simply has to know the parameter and return value of the Python function in order to create the correct type of function pointer.
Once we are finished with the Python functions and call Py_Finalize using a procedure similar to the one for Py_Initialize one can unload the Python dynamic library in the following way:
dlclose(pHandle);
pHandle = NULL;
Manually unloading NumPy libraries
Unfortunately, this does not solve the segmentation fault problems that occur when importing NumPy. The problems comes from the fact that NumPy also loads some libraries using dlopen (or something equivalent) and those do not get unloaded them when you call Py_Finalize. Indeed, if you list all the loaded libraries within your program, you will notice that after closing the Python environment with Py_Finalize, followed by a call to dlclose, some NumPy libraries will remain loaded in memory.
The second part of the solution requires to list all the Python libraries that remain in memory after the call dlclose(pHandle);. Then, for each of those libraries, grab a handle to them and then call dlcloseon them. After that, they should get unloaded automatically by the operating system.
Fortunately, there are functions under both Windows and Linux (sorry MacOS, couldn't find anything that would work in your case...):
- Linux: dl_iterate_phdr
- Windows: EnumProcessModules in conjunction with OpenProcess and GetModuleFileNameEx
Linux
This is rather straight forward once you read the documentation about dl_iterate_phdr:
#include <link.h>
#include <string>
#include <vector>
// global variables are evil!!! but this is just for demonstration purposes...
std::vector<std::string> loaded_libraries;
// callback function that gets called for every loaded libraries that
// dl_iterate_phdr finds
int dl_list_callback(struct dl_phdr_info *info, size_t, void *)
{
loaded_libraries.push_back(info->dlpi_name);
return 0;
}
int main()
{
...
loaded_libraries.clear();
dl_iterate_phdr(dl_list_callback, NULL);
// loaded_libraries now contains a list of all dynamic libraries loaded
// in your program
....
}
Basically, the function dl_iterate_phdr cycles through all the loaded libraries (in the reverse order they were loaded) until either the callback returns something other than 0 or it reaches the end of the list. To save the list, the callback simply adds each element to a global std::vector (one should obviously avoid global variables and use a class for example).
Windows
Under Windows, things get a little more complicated, but still manageable:
#include <windows.h>
#include <psapi.h>
std::vector<std::string> list_loaded_libraries()
{
std::vector<std::string> m_asDllList;
HANDLE hProcess(OpenProcess(PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ,
FALSE, GetCurrentProcessId()));
if (hProcess) {
HMODULE hMods[1024];
DWORD cbNeeded;
if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
const DWORD SIZE(cbNeeded / sizeof(HMODULE));
for (DWORD i(0); i < SIZE; ++i) {
TCHAR szModName[MAX_PATH];
// Get the full path to the module file.
if (GetModuleFileNameEx(hProcess,
hMods[i],
szModName,
sizeof(szModName) / sizeof(TCHAR))) {
#ifdef UNICODE
std::wstring wStr(szModName);
std::string tModuleName(wStr.begin(), wStr.end());
#else
std::string tModuleName(szModName);
#endif /* UNICODE */
if (tModuleName.substr(tModuleName.size()-3) == "dll") {
m_asDllList.push_back(tModuleName);
}
}
}
}
CloseHandle(hProcess);
}
return m_asDllList;
}
The code in this case is slightly longer than for the Linux case, but the main idea is the same: list all the loaded libraries and save them into a std::vector. Don't forget to also link your program to the Psapi.lib!
Manual unloading
Now that we can list all the loaded libraries, all you need to do is find among those the ones that come from loading NumPy, grab a handle to them and then call dlclose on that handle. The code below will work on both Windows and Linux, provided that you use the dlfcn-win32 library.
#ifdef WIN32
# include <windows.h>
# include <psapi.h>
# include "dlfcn_win32.h"
#else
# include <dlfcn.h>
# include <link.h> // for dl_iterate_phdr
#endif /* WIN32 */
#include <string>
#include <vector>
// Function that list all loaded libraries (not implemented here)
std::vector<std::string> list_loaded_libraries();
int main()
{
// do some preprocessing stuff...
// store the list of loaded libraries now
// any libraries that get added to the list from now on must be Python
// libraries
std::vector<std::string> loaded_libraries(list_loaded_libraries());
std::size_t start_idx(loaded_libraries.size());
void* pHandle = dlopen("/path/to/library/libpython2.7.so", RTLD_NOW | RTLD_GLOBAL);
// Not implemented here: get the addresses of the Python function you need
MyPy_Initialize(); // Needs to be defined somewhere above!
MyPyRun_SimpleString("import numpy"); // Needs to be defined somewhere above!
// ...
MyPyFinalize(); // Needs to be defined somewhere above!
// Now list the loaded libraries again and start manually unloading them
// starting from the end
loaded_libraries = list_loaded_libraries();
// NB: this below assumes that start_idx != 0, which should always hold true
for(std::size_t i(loaded_libraries.size()-1) ; i >= start_idx ; --i) {
void* pHandle = dlopen(loaded_libraries[i].c_str(),
#ifdef WIN32
RTLD_NOW // no support for RTLD_NOLOAD
#else
RTLD_NOW|RTLD_NOLOAD
#endif /* WIN32 */
);
if (pHandle) {
const unsigned int Nmax(50); // Avoid getting stuck in an infinite loop
for (unsigned int j(0) ; j < Nmax && !dlclose(pHandle) ; ++j);
}
}
}
Final words
The examples shown here capture the basic ideas behind my solution, but can certainly be improved to avoid global variables and facilitate ease of use (for example, I wrote a singleton class that handles the automatic initialization of all the function pointers after loading the Python library).
I hope this can be useful to someone in the future.
References
dl_iterate_phdr: https://linux.die.net/man/3/dl_iterate_phdr
PsAPI library: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684894(v=vs.85).aspx
OpenProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx
EnumProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682629(v=vs.85).aspx
GetModuleFileNameEx: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683198(v=vs.85).aspx
dlfcn-win32 library: library: https://github.com/dlfcn-win32/dlfcn-win32
A:
I'm not quite sure how you don't seem to understand the solution posted in Py_initialize / Py_Finalize not working twice with numpy. The solution posted is quite simple: call Py_Initialize and Py_Finalize only once for each time your program executes. Do not call them every time you run the loop.
I assume that your program, when it starts, runs some initialization commands (which are only run once). Call Py_Initialize there. Never call it again. Also, I assume that when your program terminates, it has some code to tear down things, dump log files, etc. Call Py_Finalize there. Py_Initialize and Py_Finalize are not intended to help you manage memory in the Python interpreter. Do not use them for that, as they cause your program to crash. Instead, use Python's own functions to get rid of objects you don't want to keep.
If you really MUST create a new environment every time you run your code, you can use Py_NewInterpreter and to create a sub-interpreter and Py_EndInterpreter to destroy that sub-interpreter later. They're documented near the bottom of the Python C API page. This works similarly to having a new interpreter, except that modules are not re-initialized each time a sub-interpreter starts.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.