text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Svnsync slave to master
Hj, alll
- I'm have to svn 1.6 on 2 server centos : Master: 1.9, Slave: 1.12
- I'm use svnsync create a slave repo of master repos.
- All svnsync Master server to Slave server very good.
Have a problem is SVN Master die? i'm change use to Slave server.
But after svn Master = OK, i'm want to sync db Slave -->> Master????
And help will be greate, thanks a lot.
A:
i'm want to sync db Slave -->> Master
It's impossible, svnsync is unidirectional sync. You must
Create dump of added revisions on slave
Load dump to master
| {
"pile_set_name": "StackExchange"
} |
Q:
va_arg not incrementing C++
I have a bug with my printf() function im implementing for OS. Basically the problem is, it dosent increment through the list. For example lets say i have:
printf("%d %d",19,58);
what will show on my OS is :
19 19
the 58 for some reason is not going thourgh. I have debugged this for quite some time, but cant find problem :( . Here is the stdio.c++:
#include "stdio.h"
static size_t terminal_row = 0;
static size_t terminal_column = 0;
static uint16_t* VideoMemory =((uint16_t*)0xb8000);
static bool continue_ex = false;
SerialPort sp_std_io;
void printf(char *str, ...)
{
va_list arg;
va_start(arg, str);
for(int32_t i=0;str[i]!='\0'; ++i)
{
putchar(str[i],str[i+1],arg);
}
va_end(arg);
}
void strcat(char *destination, const char *source)
{
int x = 0;
while (destination[x] != '\0')
{
x++;
}
for (int i=0; source[i] != '\0'; i++)
{
destination[x++] = source[i];
}
destination[x] = '\0';
}
void put_char_helper_neg(char chr)
{
const size_t index = (terminal_row * VGA_WIDTH + terminal_column);
terminal_column++;
VideoMemory[index]= (VideoMemory[index] & 0xFF00)|chr;
}
void putstring_t(char str)
{
size_t index = (terminal_row * VGA_WIDTH + terminal_column);
terminal_column++;
VideoMemory[index]= (VideoMemory[index] & 0xFF00)|str;
}
void putchar(char str,char next_str, va_list arg)
{
if(!continue_ex)
{
uint32_t ch_per;
char* str_use,str_use_space;
const char per = '%';
if(str == '\b')
{
terminal_column--;
}
const size_t index = (terminal_row * VGA_WIDTH + terminal_column);
char space = ' ';
switch(str)
{
case '\n':
terminal_row++;
terminal_column = 0;
break;
case '\b':
VideoMemory[index]= (VideoMemory[index] & 0xFF00)|space;
break;
case '%':
switch(next_str)
{
case 'd':
ch_per = va_arg(arg,int);
if(ch_per<0)
{
ch_per = -ch_per;
put_char_helper_neg('-');
}
str_use = itoa(ch_per);
terminal_column++;
for(int32_t i=0;str_use[i]!='\0'; ++i)
{
putstring_t(str_use[i]);
}
// sp_std_io.write_number_serial(ch_per);
// sp_std_io.write_string_serial(str_use);
continue_ex = true;
break;
default:
terminal_column++;
VideoMemory[index]= (VideoMemory[index] & 0xFF00)|per;
}
break;
default:
terminal_column++;
VideoMemory[index]= (VideoMemory[index] & 0xFF00)|str;
break;
}
}
else
{
continue_ex = false;
}
}
int32_t strlen(int8_t* str)
{
int32_t l=0;
while(str[l]!='\0')l++;
return l;
}
char *itoa(int val)
{
uint8_t *ptr;
static uint8_t buffer[16];
ptr = buffer + sizeof(buffer);
*--ptr = '\0';
if (val == 0)
{
*--ptr = '0';
}
else while (val != 0)
{
*--ptr = (val % 10) + '0';
val = val / 10;
}
return((char*)ptr);
}
and stdio.h:
#ifndef _STD_LIB_H_
#pragma once
#define _STD_LIB_H_ 1
#include <stddef.h>
#include <stdint.h>
#include <stdarg.h>
#include "math.h"
#include "serial.h"
static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 25;
//static int num_count_viedo_memory = 0;
void printf(char *str,...);
void putchar(char str,char next_str,va_list arg);
int32_t strlen(int8_t *str);
void strcat(char * Dest, char const * Src);
//int8_t* str_cat(int8_t *dest, const int8_t *src);
void reverse(char str[], int32_t length);
char* itoa(int val);
#endif
Like i described above , it is not incrementing through the args for some reason. Help would be appreciated! :)
A:
Pass arg into your putchar function by reference instead of by value:
void putchar(char str,char next_str, va_list& arg)
What's happening is that it gets incremented inside your putchar function, but then the function returns and it has no effect on the variable in printf because putchar is passed a copy rather than a reference to it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proper phrase for "ending someone's curiosity"
I'm looking for a word or phrase to be used with the word curiosity which will mean that someone's curiosity ends after obtaining enough information on the thing he was curious about.
Example:
He was curious about what is inside the box. His friend opened the box. He saw inside the box and that ......... his curiosity.
A:
The word you are looking for is "satisfy":
He saw inside the box and that satisfied his curiosity.
Example from merriam-webster.com:
The movie failed to satisfy her curiosity about the assassination.
| {
"pile_set_name": "StackExchange"
} |
Q:
Iterative solving of linear systems and relationship to Jacobi/Gauss-Seidel
In a numerics lecture, we were presented both the Gauss–Seidel as well as the Jacobi method used to iteratively solve linear systems of equations of the form $Ax = b$, which I understand and am able to apply.
In the lecture, we were additionally presented with the following bit of information, which I don't understand the significance of:
The problem $Ax=b$ can be solved using a fixed-point iteration based
on the Banach fixed-point theorem, by performing the following trivial
transformations: $$Ax=b \Leftrightarrow 0 = (b-Ax) \Leftrightarrow 0 =
\omega (b-Ax) \Leftrightarrow x = x+\omega (b-Ax)$$ where $w > 0$.
This defines a iteration function $g$: $$g(x) = (I - \omega A)x +\omega b$$ The iteration sequence $x^{(n+1)} = g(x^{(n)})$ then
converges against $x$. Such a $\omega$ can be found if $A$ is positive
definite and symmetric.
My question is: How does this relate to the two methods I mentioned before? Are those methods special cases of this theorem? If not, is this new method something one can actually use to solve a problem in an exam? How can I find the $\omega$ needed for this to work?
A:
The Jacobi and Gauss-Seidel methods also come from rewriting the linear system as a fixed point problem, based in particular additive decompositions $A = L+D+U$. So the comment just provides an alternative way of obtaining an equivalent fixed point problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
flask Template Inheritance tutorial
I am running through the flask tutorial and I can not seem to get the Template Inheritance to work. below are the examples of my code
My base.html is:
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
my child Temp is:
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome to my awesome homepage.
</p>
{% endblock %}
my flask script is:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template("base.html")
if __name__ == "__main__":
app.debug = True
app.run()
Is there something specifically I should be doing regarding how I am incorporating the child template? Or should I be rendering the base template differently?
A:
Jinja extends works (superficially) like Python subclassing. You don't get an instance of a subclass when you instantiate a parent class, and you don't get the result of a child template when rendering the base template. Render the child template instead.
return render_template('child.html')
| {
"pile_set_name": "StackExchange"
} |
Q:
Responsive Menu (Bootstrap) - Buttons inline
I have two Buttons on the right side of my navbar, in the responsive menu the buttons are arranged among themselves.
Is it possible to make the Buttons inline, so the two buttons are on top in the first row.
<ul class="nav navbar-nav navbar-right">
<li>
<p class="navbar-btn btn-space btn-top-space">
<a href="https://url.com" target="_blank" title="Customer Payment Panel (CPP)" class="btn-sm btn-info">
<span class="glyphicon glyphicon-user"></span> <strong>Customer Panel</strong> (CPP)
</a>
</p>
</li>
<li>
<p class="navbar-btn btn-top-space">
<a href="https://url.com" target="_blank" title="Control Panel (Plesk)" class="btn-sm btn-success">
<span class="glyphicon glyphicon-cog"></span> <strong>Control Panel</strong> (Plesk)
</a>
</p>
</li>
</ul>
A:
You can try like this.
You have to add custom media style.
Css-
@media (max-width: 767px) {
.nav.top-nav li{
display:inline-block;
}
}
Html -
<ul class="nav top-nav navbar-nav navbar-right">
<li>
<p class="navbar-btn btn-space btn-top-space">
<a href="https://url.com" target="_blank" title="Customer Payment Panel (CPP)" class="btn-sm btn-info">
<span class="glyphicon glyphicon-user"></span> <strong>Customer Panel</strong> (CPP)
</a>
</p>
</li>
<li>
<p class="navbar-btn btn-top-space">
<a href="https://url.com" target="_blank" title="Control Panel (Plesk)" class="btn-sm btn-success">
<span class="glyphicon glyphicon-cog"></span> <strong>Control Panel</strong> (Plesk)
</a>
</p>
</li>
</ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to apply a style to an embedded SVG?
When an SVG is directly included in a document using the <svg> tag, you can apply CSS styles to the SVG via the document's stylesheet. However, I am trying to apply a style to an SVG which is embedded (using the <object> tag).
Is it possible to use anything such as the following code?
object svg {
fill: #fff;
}
A:
Short answer: no, since styles don't apply across document boundaries.
However, since you have an <object> tag you can insert the stylesheet into the svg document using script.
Something like this, and note that this code assumes that the <object> has loaded fully:
var svgDoc = yourObjectElement.contentDocument;
var styleElement = svgDoc.createElementNS("http://www.w3.org/2000/svg", "style");
styleElement.textContent = "svg { fill: #fff }"; // add whatever you need here
svgDoc.getElementById("where-to-insert").appendChild(styleElement);
It's also possible to insert a <link> element to reference an external stylesheet:
var svgDoc = yourObjectElement.contentDocument;
var linkElm = svgDoc.createElementNS("http://www.w3.org/1999/xhtml", "link");
linkElm.setAttribute("href", "my-style.css");
linkElm.setAttribute("type", "text/css");
linkElm.setAttribute("rel", "stylesheet");
svgDoc.getElementById("where-to-insert").appendChild(linkElm);
Yet another option is to use the first method, to insert a style element, and then add an @import rule, e.g styleElement.textContent = "@import url(my-style.css)".
Of course you can directly link to the stylesheet from the svg file too, without doing any scripting. Either of the following should work:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="my-style.css" type="text/css"?>
<svg xmlns="http://www.w3.org/2000/svg">
... rest of document here ...
</svg>
or:
<svg xmlns="http://www.w3.org/2000/svg">
<defs>
<link href="my-style.css" type="text/css" rel="stylesheet"
xmlns="http://www.w3.org/1999/xhtml"/>
</defs>
... rest of document here ...
</svg>
Update 2015: you can use jquery-svg plugin for apply js scripts and css styles to an embedded SVG.
A:
You can do this without javsscrpt by putting a style block with your styles inside the SVG file itself.
<style type="text/css">
path,
circle,
polygon {
fill: #fff;
}
</style>
A:
If the only reason for using the tag to inlcude the SVG is that you do not want to clutter your source code with the markup from the SVG, you should take a look at SVG injectors like SVGInject.
SVG injection uses Javascript to inject an SVG file inline into your HTML document. This allows for clean HTML source code while making the SVGs fully styleable with CSS. A basic example looks like this:
<html>
<head>
<script src="svg-inject.min.js"></script>
</head>
<body>
<img src="image.svg" onload="SVGInject(this)" />
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel: Show message(alert) on all open tabs, if session variable changed
Laravel Version: 5.2.45
PHP Version: ^5.4
I have a session variable named f_year. It stores the financial year in the session. This can be changed by the user. On changing the f_year, the session is reset and page is reloaded.
The problem is that, user changes the f_year in one tab and without refreshing the other tab, saves the data. And the year is mismatched.
Is it possible to show an alert on other open tabs: Your Financial Year has changed. Please reload the page to continue.
A:
Well, the other day I ran into a similar issue. What I did was I first set the cookie and a session variable (using PHP). Then I used the JQuery to get the cookie value. The JQuery cookie method, fetches the current cookie set(irrespective of the browser tab).
Then I compared these two values and alerted the user about the mismatched settings.
Hope that helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
React, Jest tdd with typescript
React, Jest tdd with typescript
Hi
I'm looking at some simple TDD tutorial but I'm trying to use typescript but the tutorials are not in typescript.
The simple exmaple is Class component with a header and a counter.
The test just test that the components load without crashing and clicking the counter increases the counter state.
I have a setup function that creates a shallow ri render the App component
When I call the setup function in the it statement I get the following error.
const setup: (state: IState, props?: {}) => ShallowWrapper<any, Readonly<{}>, React.Component<{}, {}, any>>
Expected 1-2 arguments, but got 0.ts(2554)
App.test.tsx(15, 16): An argument for 'state' was not provided.
Peek Problem
No quick fixes available
How can I fix this typescript error
App.tsx
import React, {Component} from 'react';
import './App.css';
interface IState{
counter: number
}
interface IProps{
}
class App extends Component<IState, {}> {
state = {
counter: 0
}
render(){
return (
<div data-test='componentApp'>
<h1 data-test='counter'>The counter is {this.state.counter}</h1>
<button
data-test='button'
onClick={() => this.setState({counter: this.state.counter + 1})
}>Increment Counter</button>
</div>
)
}
}
export default App;
App.text.tsx
import React from 'react';
import App from './App';
import "./setupTests"
import { shallow } from "enzyme";
interface ITest{
warpper: String,
val: String
}
interface IState{
counter: number
}
const setup = (state:IState, props={}) => {
const wrapper = shallow(<App {...state} {...props}/>)
if(state) wrapper.setState(state)
return wrapper
}
const findByTestAttr = (wrapper:any, val:string) => {
return wrapper.find(`[data-test="${val}"]`);
}
describe('App Component', () => {
it('renders without crashing', () => {
const wrapper = setup() //Error here
const componentApp = findByTestAttr(wrapper, 'componentApp')
expect(componentApp.length).toBe(1)
});
it('renders incerment button', () => {
const wrapper = setup() //Error here
const button = findByTestAttr(wrapper, 'button')
expect(button.length).toBe(1)
})
it('renders counter display', () => {
const wrapper = setup() //Error here
const counter = findByTestAttr(wrapper, 'counter')
expect(counter.length).toBe(1)
})
it('counter starts at 0', () => {
const wrapper = setup(); //Error here
const initialCounterState = wrapper.state('counter');
expect(initialCounterState).toBe(0)
})
it('clicking button increments counter display', () => {
const counterHere = 7
const wrapper = setup(null, {counterHere})
const button = findByTestAttr(wrapper, 'button');
button.simulate('click')
const counter = findByTestAttr(wrapper, 'counter')
expect(counter.text()).toContain(counter+1)
})
})
A:
Well, this error does not derive from TypeScript, you're simply not passing any state in setup. Try instantiating wrapper like const wrapper = setup({counter: 0}). As a side note, I discourage using shallow as it exposes the components' internals (which you are leveraging by calling the setState), it's a nasty con of using that for rendering. Instead, try using mount.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pandas groupby multiple columns take average of another based on condition
I'm stuck on this and similar posts are creating a bit of a black hole for me. I'm still learning..
I would like to take the mean of a group that meets a condition. My data looks like this:
user date Flag Value
0 ron 12/23/2016 'flag' 10
1 ron 12/21/2016 'n/a' 25
2 ron 12/23/2016 'flag' 10
3 ron 12/21/2016 'n/a' 3
4 andy 12/22/2016 'flag' 5
5 andy 12/22/2016 'flag' 1
I'd like to groupby user + Flag and create a new column 'Avg' that takes only the Avg values of 'flag'. So the data would look like this:
user date Flag Value Avg
0 ron 12/23/2016 'flag' 10 10
1 ron 12/21/2016 'n/a' 25 10
2 ron 12/23/2016 'flag' 10 10
3 ron 12/21/2016 'n/a' 3 10
4 andy 12/22/2016 'flag' 5 3
5 andy 12/22/2016 'flag' 1 3
I have something like this, but have tried many different variations:
groups = sample.groupby(['user','Flag'])
flag = sample.groupby(['user','Flag'])['Value'].transform('mean')
sample.loc[:,'Avg'] = np.select([flag.eq('flag'), groups.transform('mean')])
Guidance is appreciated..
A:
Here's a solution with groupby and map:
df['Avg'] = df['user'].map(df[df['Flag']=="'flag'"] # use "flag" only if you don't have `'` in the data'
.groupby('user')['Value'].mean())
Output:
user date Flag Value Avg
0 ron 12/23/2016 'flag' 10 10
1 ron 12/21/2016 'n/a' 25 10
2 ron 12/23/2016 'flag' 10 10
3 ron 12/21/2016 'n/a' 3 10
4 andy 12/22/2016 'flag' 5 3
5 andy 12/22/2016 'flag' 1 3
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Schema.org’s "url" property on a Product page without adding a visual link
After a bit of research I found recommendations as in:
<div itemscope itemtype="http://schema.org/Product">
<a itemprop="url" href="URLOFPRODUCT">Link</a>
</div>
But I am trying to avoid linking to the product, on the product page.
Another approach I've noticed is the use of meta tags but outside the head, which is a big 'no no'.
Any suggestions?
A:
For providing a URL in Microdata, you must use "a URL property element". Currently these are:
a, area, audio, embed, iframe, img, link, object, source, track, and video.
a and link are the only "generic" elements from this set.
If you don’t want to provide a visual link (by using a), go with link (which is typically hidden in browser default stylesheets). This is not "a big 'no no'", as link elements are allowed in the body if used for Microdata.
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql / ajax: run mysql query on div click using ajax and return echoed data back to ajax?
i have the following form:
<form action="process_promo.php" method="post">
<input type="text" name="promo" id="promo">
<div class="promo_check"></div>
</form>
i am then using ajax to perform a check to see if the text entered in the promo input field matches that which is in my database with mysql.
heres my ajax:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.promo_check', function() {
var promo = $("#promo").val();
// Returns successful data submission message when the entered information is stored in database.
$.post("process_promo.php", {
promo1: promo,
}, function(data) {
if(data == 'wrong') {
alert('wrong');
}else{
if(data == 'correct') {
alert('correct');
} } }
});
});
});
</script>
and finally here's my mysql query in process_promo.php:
<?php
$servername = "localhost";
$username = "mark";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$promo = $_POST['promo'];
$query = "SELECT * FROM supplier_users WHERE promo_code = '$promo' AND username = 'mark'";
$result = mysql_query($query);
if (mysql_num_rows($result)>0) {
echo "correct";
}else{
echo "wrong";
}
?>
if the query returns true and the text in my input field matches the text in my database i am asking it to echo out 'correct' else if it returns false i am asking it to echo 'wrong' and then alert me of the relevant outcome in my ajax.
For some reason i am not getting any alert message and as far as i can tell nothing is happening.
Please can someone show me where i am going wrong, thanks in advance
A:
Do the following:
Include the latest version of the jQuery library once only.
Add a button to your form and use return false to prevent the default
submit event.
Make sure you close your braces {} correctly in your jQuery. (You have an additional closing brace } in your jQuery)
Add your ajax above your form.
Give this a try:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(document).on('click', '.promo_button', function() {
var promo = jQuery('#promo').val();
jQuery.post("process_promo.php", {promo: promo,},
// Pass your variable (promo) to the function
function(promo) {
// If your variable is empty
if(!promo) {
alert('wrong');
}
else{
// Pass the results back to your page
jQuery('.promo_check').html(promo);
}
}
);
// Prevent default form submit
return false
});
});
</script>
<form action="" method="post">
<input type="text" name="promo" id="promo">
<button class="promo_button">>></button>
<div class="promo_check"></div>
</form>
Your PHP code looks OK and should run fine. However, you can add error reporting:
error_reporting(-1);
ini_set('display_errors', 'On');
to the top of the php page to catch any pesky bugs.
Remember that you can use your Chrome's network panel to check your POST requests. This can often help a lot.
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Ito Isometry formula
How would I use the Ito Isometry formula to compute,
$$E\left [ \left ( \int_{0}^{t}g(s,W_s)dW_s \right )^2 \right ]$$
for the case $g(t,W_t)=(1+t^2+W_t)$ with $W_t$ being Brownian motion.
I would really appreciate any help on this. Thanks
A:
I write a solution, also as an exercise for me...
Step 1: apply Ito isometry
$I=E[\left(\int_0^t g(s,W_s) dW_s\right)^2]=E[(\int_0^t g(s,W_s)^2 ds]$
Step 2: Insert and expand
$I=E[\int_0^t (1+s^4+W_s^2 +2s^2+2sW_s+2W_s )ds]$
Step 3: Exchange expectation with integral
This way we can prove that:
$E[\int_0^t W_s ds]=\int_0^t E[W_t]ds=0$
$E[\int_0^t sW_s ds]=\int_0^t sE[W_t]ds=0$
$E[\int_0^t W^2_s ds]=\int_0^t E[W^2_s] ds=\int_0^t s ds=t^2/2$
The rest is just deterministic integrals:
$I=t+t^5/5+t^2/2+2t^3/3$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find child of a GameObject or the script attached to child GameObject via script
I know this is a bit of a stupid question, but how would I reference the child (a cube) of a game object via script(the script is attached to the gameObject). (the equivalent to something like GetComponent)
A:
Finding child GameObject by index:
You can get the first child of a GameObject with the GetChild function.
GameObject originalGameObject = GameObject.Find("MainObj");
GameObject child = originalGameObject.transform.GetChild(0).gameObject;
You can get other children by providing index number of the child GameObject such as 1,2,3, to the GetChild function.
and if its a child of a child in the original gameobject? would I just
have to repeat it or would it just be the nth one down
You find the child first, then find the child of that child from the reference.
Let's say this is OriginalGameObject/Prefab hierarchy:
OriginalGameObject
child1
child2
child3
childOfChild3
As you can see the OriginalGameObject is the parent of child1, child2 and child3. childOfChild3 is the child of child3.
Let's say you want to access the childs and you only have reference to OriginalGameObject which is the parent GameObject:
//Instantiate Prefab
GameObject originalGameObject = Instantiate(prefab);
//To find `child1` which is the first index(0)
GameObject child2 = originalGameObject.transform.GetChild(0).gameObject;
//To find `child2` which is the second index(1)
GameObject child2 = originalGameObject.transform.GetChild(1).gameObject;
//To find `child3` which is the third index(2)
GameObject child3 = originalGameObject.transform.GetChild(2).gameObject;
The index starts from 0 so the real index number is index-1 just like arrays.
Now, to get the reference of childOfChild3 which is the child of child3 but you only have reference to OriginalGameObject which is the parent GameObject:
First of all, get reference of child3 then get childOfChild3 from it.
GameObject mychild = originalGameObject.transform.GetChild(2).gameObject;
GameObject childOfChild3 = mychild.transform.GetChild(0).gameObject;
Finding [all] child GameObject by index with loop:
To loop through all the child of originalGameObject:
GameObject originalGameObject = Instantiate(prefab);
for (int i = 0; i < originalGameObject.transform.childCount; i++)
{
GameObject child = originalGameObject.transform.GetChild(i).gameObject;
//Do something with child
}
You can also find child by name with the transform.FindChild function. I wouldn't recommend that you can do that. It seems slow and will conflict when multiple child share the-same name. That's why you use GetChild.
Finding child GameObject by name:
GameObject child1 = originalGameObject.transform.FindChild("child1").gameObject;
GameObject child2 = originalGameObject.transform.FindChild("child2").gameObject;
GameObject child3 = originalGameObject.transform.FindChild("child3").gameObject;
To find childOfChild3, you can easily do that with the '/' just like you do with a file directory. You provide the parent/child then name. The parent of childOfChild3 is child3. So, we use, childOfChild3/child3 in FindChild function.
GameObject childOfChild3 = originalGameObject.transform.FindChild("child3/childOfChild3").gameObject;
Finding scripts/components attached to child GameObject:
If all you want is the script that is attached to the child GameObject, then use GetComponentInChildren:
MyScript childScript = originalGameObject.GetComponentInChildren<MyScript>();
If there are more than one child with the-same script and you just want to get all the scripts attached to them, then use GetComponentsInChildren:
MyScript[] childScripts = originalGameObject.GetComponentsInChildren<MyScript>();
for (int i = 0; i < childScripts.Length; i++)
{
MyScript myChildScript = childScripts[i];
//Do something with myChildScript
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Plant identification with purple flowers
This plant is on northern California Zone 9. During day the flower blooms, and in the evening the flower closes itself. The flowers are purple in color and has a long green stem.
A:
This is "salsify", or "Tragopogon porrifolius", to be "scientific" about it.
Pretty, right? They are actually selling plugs of it here, but I have it in my front "lawn", and it is a pretty noxious weed. Big, too. Some of the taller specimens can grow up to above my waist.
This picture doesn't quite do justice to their full size.
Per Wikipedia, it's in the daisy family. The flowers are sort of pretty, and they mature into the characteristic daisy puffball composed of seeds on little parachutes of fluff. In the case of salsify the puffballs are maybe 3-4 inches in diam. (quite striking really, as they are an interesting shade of coppery brown), and the seeds themselves are abt. a quarter inch long. This reproductive strategy (the parachute method) is very effective, so don't let these plants go to seed unless you want to start a salsify farm.
Don't laugh! Supposedly you can eat the long slender taproot (which, by the way, isn't easy to dig out completely from your lawn):
But I will tell you I tasted it. Maybe I didn't clean it as well as I should have, but I washed it as best I could, and it still tasted like dirt.
I didn't have this recipe from http://www.junedarville.com/roasted-salsify.html at the time though, so maybe I should try it again.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I disable/hide command box in batch file prompt?
How do I disable/hide the command box in the command prompt window brought up by a batch file?
Also how to force window to stay on top?
A:
The short answer is: you can't with regular command prompt.
The long answer is: you can with 3rd party applications or with the help of scripting as described in this answer https://superuser.com/questions/62525/run-a-completly-hidden-batch-file on Superuser (which by the way is the correct place for this type of questions)
Edit:
After further comments, the OP clarified that he wants to disable the close/minimize buttons on command prompt window, not the actual window. This was answered here, and unfortunately you cannot:
disabling the cmd close button by batch command
| {
"pile_set_name": "StackExchange"
} |
Q:
Ignore responses to ignored users in chat
Chat provides the ability to ignore users. However, it doesn't force everyone else to ignore them. ;) As such, you can still see responses to that user.
It might be nice if "Ignore this user" provided an option to also ignore responses to that user's posts, and potentially all posts with @ignored_user.
A:
Ehhh I do not really like this idea.
I have ignored users before, but when I see others' comments back to them I decide that I might want to take them out of cherem and actually participate in the discussion.
If I see it going nowhere, then I might put them back into my ignored user list.
Other than that I don't think we should penalize ourselves from seeing other people's sometimes insightful responses to the aforementioned ignored user.
A:
I support this. If you have 3-4 "busy" people on ignore and the chat room is busy, you may as well give up on trying to follow the conversation streams and come back later when there's nobody around.
If I have someone on ignore, I don't really give two hoots what they're talking about or if they're saying something interesting or if someone else has said something interesting in response to them. They're on ignore for a reason.
A:
This is a problem with most chat systems, where you see one sided conversations. Luckily SO cuts down on the confusion with the @username format.
I oppose blocking the messages from a user who is replying to a blocked user, as you may be missing a good message. After all, you're not blocking the replier. What I propose as a compromise is a way to highlight that the replier is replying to a message from a user who you have blocked. One way of doing this might be a red strike through in the @reply. For example:
Resorath: @imajerk I don't think we should revive Hitler and make him our president.
(Except the @name would be red)
| {
"pile_set_name": "StackExchange"
} |
Q:
ANT build script CSSlint output xml
Is that any way to export CSSlint output to a valid XML format with ant build script?
I modified project.properties file in: tool.csslint.opts = --format=lint-xml section, but I think this is not enough, because csslint needs to specify output file like so:
csslint --format=lint-xml test.css > results.xml
How can I modify ant target to work?
Thank you.
A:
Basics: Ant already has an output property. So you can just add the format option and output it to a file specified as an output property on the apply element. in an h5bp project this will output "output.xml" to the root of your project.
<apply dir="${dir.source}/${dir.css}"
executable="java" parallel="true"
failonerror="true" output="output.xml">
<fileset dir="./${dir.source}/">
<include name="**/${dir.css}/*.css"/>
<exclude name="**/*.min.css"/>
<exclude name="**/${dir.publish}/"/>
</fileset>
<arg value="-jar" />
<arg path="./${dir.build.tools}/${tool.rhino}" />
<arg path="./${dir.build.tools}/${tool.csslint}" />
<arg value="--format=lint-xml" />
<srcfile/>
</apply>
| {
"pile_set_name": "StackExchange"
} |
Q:
Active Admin and Stripe Membership Plans
I'm trying to Add membership plans in stripe using active admin.
I was able to add it during creation of column. But now i want to edit the created subscription.
Here is my active admin page.. How should the controller for update and destroy be?
ActiveAdmin.register SubscriptionPlan do
menu priority: 10
permit_params :name, :amount, :interval
index do
selectable_column
default_actions
column :name
column :amount
column :interval
end
form do |f|
f.inputs "Subscription Plan" do
f.input :name
f.input :amount
f.input :interval, as: :select, collection: ["week","month","year"]
end
f.actions
end
controller do
def create
create! do |format|
Stripe::Plan.create(
:amount => params[:subscription_plan][:amount].to_i,
:interval => params[:subscription_plan][:interval],
:name => params[:subscription_plan][:name],
:currency => 'usd',
:id => params[:subscription_plan][:name]
)
end
end
def update
update! do |format|
end
end
def destroy
destroy! do |format|
end
end
end
end
A:
Yea i myself found a solution for this..
on edit i got its value by passing the created id of stripe plan and with it i edited the Json and saved it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to "store" a template parameter pack without expanding it?
I was experimenting with C++0x variadic templates when I stumbled upon this issue:
template < typename ...Args >
struct identities
{
typedef Args type; //compile error: "parameter packs not expanded with '...'
};
//The following code just shows an example of potential use, but has no relation
//with what I am actually trying to achieve.
template < typename T >
struct convert_in_tuple
{
typedef std::tuple< typename T::type... > type;
};
typedef convert_in_tuple< identities< int, float > >::type int_float_tuple;
GCC 4.5.0 gives me an error when I try to typedef the template parameters pack.
Basically, I would like to "store" the parameters pack in a typedef, without unpacking it. Is it possible? If not, is there some reason why this is not allowed?
A:
Another approach, which is slightly more generic than Ben's, is as follows:
#include <tuple>
template <typename... Args>
struct variadic_typedef
{
// this single type represents a collection of types,
// as the template arguments it took to define it
};
template <typename... Args>
struct convert_in_tuple
{
// base case, nothing special,
// just use the arguments directly
// however they need to be used
typedef std::tuple<Args...> type;
};
template <typename... Args>
struct convert_in_tuple<variadic_typedef<Args...>>
{
// expand the variadic_typedef back into
// its arguments, via specialization
// (doesn't rely on functionality to be provided
// by the variadic_typedef struct itself, generic)
typedef typename convert_in_tuple<Args...>::type type;
};
typedef variadic_typedef<int, float> myTypes;
typedef convert_in_tuple<myTypes>::type int_float_tuple;
int main()
{}
A:
I think the reason it's not allowed is that it would be messy, and you can work around it. You need to use dependency inversion and make the struct storing the parameter pack into a factory template able to apply that parameter pack to another template.
Something along the lines of:
template < typename ...Args >
struct identities
{
template < template<typename ...> class T >
struct apply
{
typedef T<Args...> type;
};
};
template < template<template<typename ...> class> class T >
struct convert_in_tuple
{
typedef typename T<std::tuple>::type type;
};
typedef convert_in_tuple< identities< int, float >::apply >::type int_float_tuple;
A:
I've found Ben Voigt's idea very useful in my own endeavors. I've modified it slightly to make it general to not just tuples. To the readers here it might be an obvious modification, but it may be worth showing:
template <template <class ... Args> class T, class ... Args>
struct TypeWithList
{
typedef T<Args...> type;
};
template <template <class ... Args> class T, class ... Args>
struct TypeWithList<T, VariadicTypedef<Args...>>
{
typedef typename TypeWithList<T, Args...>::type type;
};
The name TypeWithList stems from the fact that the type is now instantiated with a previous list.
| {
"pile_set_name": "StackExchange"
} |
Q:
Xpath, strip @src extraction?
In Xpath 1.0, guess this is impossible, but I give it a shot..
XML
<img src="/media/brand_microsoft.png">
Xpath:
//div[@id='logo']/img/@src
Output becomes:
/media/brand_microsoft.png
Is it anyway of excluding /media/brand_ and .png? So I just get:
microsoft
A:
You can try this :
substring-before(substring-after(/img/@src, '/media/brand_'), '.png')
substring-before :
Returns the start of string1 before string2 occurs in it
Example: substring-before('12/10','/')
Result: '12'
substring-after :
Returns the remainder of string1 after string2 occurs in it
Example: substring-after('12/10','/')
Result: '10'
[Reference]
UPDATE :
tested in http://www.freeformatter.com/xpath-tester.html with :
xml input :
<img src="/media/brand_Barcardi_Breezer.png"/>
xpath expression :
substring-before(substring-after(/img/@src, '/media/brand_'), '.png')
ouput :
'Barcardi_Breezer'
| {
"pile_set_name": "StackExchange"
} |
Q:
Gradient cross borders for navigation menu
I am trying to add gradient cross borders with no luck as shown in the attached example using classes.
Cross Border image example
Below is my code.
Any help will be appreciated.
<li class="newnav-links col-sm-6 dropdown-left dropdown-top">/li>
<li class="newnav-links col-sm-6 dropdown-right dropdown-top">/li>
<li class="newnav-links col-sm-6 dropdown-left dropdown-middle">/li>
<li class="newnav-links col-sm-6 dropdown-right dropdown-middle">/li>
<li class="newnav-links col-sm-6 dropdown-left dropdown-bottom">/li>
<li class="newnav-links col-sm-6 dropdown-right dropdown-bottom">/li>
A:
* {
box-sizng : border-box;
}
ul {
list-style: none;
}
li {
width: 40%;
float: left;
position: relative;
padding:15px;
}
.newnav-links.dropdown-left.dropdown-top::after {
background: rgba(0, 0, 0, 0) linear-gradient(#ffffff, #dddddd,
#999999,#333333, #000000, #000000, #000000) repeat scroll 0 0;
}
.newnav-links.dropdown-left.dropdown-bottom::after {
background: rgba(0, 0, 0, 0) linear-gradient(#000, #000,
#000,#333333, #999, #ddd, #fff) repeat scroll 0 0;
}
li::after {
bottom: 0;
content: "";
height: 100%;
position: absolute;
right: 0;
width: 1px;
}
li.dropdown-right.dropdown-top::after {
display: none;
}
.newnav-links.dropdown-left.dropdown-middle::after {
background:#000000;
}
.dropdown-right::before {
background: rgba(0, 0, 0, 0) linear-gradient(to right, #000000, #000000,
#666666, #999999, #ffffff, #ffffff) repeat scroll 0 0;
bottom: 0;
content: "";
height: 1px;
left: 0;
position: absolute;
width: 100%;
}
.dropdown-left::before {
background: rgba(0, 0, 0, 0) linear-gradient(to left, #000000, #000000,
#666666, #999999, #ffffff, #ffffff) repeat scroll 0 0;
bottom: 0;
content: "";
height: 1px;
right: 0;
position: absolute;
width: 100%;
}
li.dropdown-bottom::before {
display: none;
}
<ul>
<li class="newnav-links dropdown-left dropdown-top">link1</li>
<li class="newnav-links dropdown-right dropdown-top">link2</li>
<li class="newnav-links dropdown-left dropdown-middle">link3</li>
<li class="newnav-links dropdown-right dropdown-middle">link4</li>
<li class="newnav-links dropdown-left dropdown-bottom">link5</li>
<li class="newnav-links dropdown-right dropdown-bottom">link6</li>
</ul>
| {
"pile_set_name": "StackExchange"
} |
Q:
ObjectifyService.begin() throws IllegalStateException
I'm trying to use google cloud datastore for my maven project, but I'm in a bit of trouble.
When I execute
Consumer consumer=new Consumer(username+password,username,password,name,email) {
ofy().save().entity(consumer).now(); }
It stops in ObjectifyFilter.class at
try (Closeable closeable = ObjectifyService.begin()) { ..
and it throws
java.lang.IllegalStateException at
com.google.appengine.repackaged.com.google.common.base.Preconditions.checkState(Preconditions.java:443)
at
com.google.appengine.api.datastore.DatastoreServiceGlobalConfig$Builder.build(DatastoreServiceGlobalConfig.java:233)
at
com.google.appengine.api.datastore.DatastoreServiceGlobalConfig.fromEnv(DatastoreServiceGlobalConfig.java:311)
at
com.google.appengine.api.datastore.DatastoreServiceGlobalConfig.getConfig(DatastoreServiceGlobalConfig.java:47)
at
com.google.appengine.api.datastore.DatastoreServiceFactoryImpl.getAsyncDatastoreService(DatastoreServiceFactoryImpl.java:19)
at
com.google.appengine.api.datastore.DatastoreServiceFactoryImpl.getAsyncDatastoreService(DatastoreServiceFactoryImpl.java:9)
at
com.google.appengine.api.datastore.DatastoreServiceFactory.getAsyncDatastoreService(DatastoreServiceFactory.java:32)
at
com.googlecode.objectify.ObjectifyFactory.createRawAsyncDatastoreService(ObjectifyFactory.java:133)
at
com.googlecode.objectify.ObjectifyFactory.createAsyncDatastoreService(ObjectifyFactory.java:121)
at
com.googlecode.objectify.impl.ObjectifyImpl.createAsyncDatastoreService(ObjectifyImpl.java:246)
at
com.googlecode.objectify.impl.ObjectifyImpl.createWriteEngine(ObjectifyImpl.java:257)
at
com.googlecode.objectify.impl.SaverImpl.entities(SaverImpl.java:60)
at com.googlecode.objectify.impl.SaverImpl.entity(SaverImpl.java:35)
at it.units.view.ConsumerView.createConsumer(ConsumerView.java:43)
at it.units.controller.login.processRequest(login.java:45) at
it.units.controller.login.doPost(login.java:92) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at
org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:867)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1623)
at
com.googlecode.objectify.ObjectifyFilter.doFilter(ObjectifyFilter.java:48)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
at
com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
at
com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
at
com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
at
com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
at
com.google.appengine.tools.development.jetty9.StaticFileFilter.doFilter(StaticFileFilter.java:123)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
at
com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
at
com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
at
com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
at
com.google.appengine.tools.development.DevAppServerRequestLogFilter.doFilter(DevAppServerRequestLogFilter.java:44)
at
org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1602)
at
org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:540)
at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146)
at
org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
at
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at
org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257)
at
org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1588)
at
org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)
at
org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1345)
at
org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)
at
org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:480)
at
org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1557)
at
org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)
at
org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1247)
at
com.google.appengine.tools.development.jetty9.DevAppEngineWebAppContext.doScope(DevAppEngineWebAppContext.java:94) at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)
at
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at
com.google.appengine.tools.development.jetty9.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:595)
at
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:502) at
org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:364) at
org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:260)
at
org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
at
org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:118)
at
org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:333)
at
org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:310)
at
org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:168)
at
org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:126)
at
org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:366)
at
org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:765)
at
org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:683)
at java.lang.Thread.run(Thread.java:748)
The entities register operation goes through. It occurs when server starts:
public void contextInitialized(ServletContextEvent event) {
ObjectifyService.register(Consumer.class);
ObjectifyService.register(Administrator.class);
ObjectifyService.register(Uploader.class);
ObjectifyService.register(File.class);
}
but after that I can't visualise the entities in the datastore. Should I see them, right? (I'm sure it does register operations, I checked that in debug mode)
Can someone help me?
A:
Thanks for your help! I solved by adding
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.14.v20181114</version>
</plugin>
| {
"pile_set_name": "StackExchange"
} |
Q:
Groovy multiple assignment with a map
I am having a problem doing a multiple assignment statement for values in a map.
def map = [a:1,b:2]
(map.a, map.b) = [3,4]
this throws an exception:
expecting ')', found ',' at line: 2, column: 7
However, this works fine:
def a = 1
def b = 2
(a, b) = [3,4]
A:
Actually, you can do this if you cheat and use .with:
Map map = [a: 1, b:2]
map.with {
(a, b) = [3, 4]
}
assert map.a == 3
assert map.b == 4
A:
It doesn't support that.
http://groovy.codehaus.org/Multiple+Assignment
currently only simple variables may be the target of multiple assignment expressions, e.g.if you have a person class with firstname and lastname fields, you can't currently do this:
(p.firstname, p.lastname) = "My name".split()
| {
"pile_set_name": "StackExchange"
} |
Q:
records on Access database are all the same in my code
I have written the following code to generate some security codes but these codes doesnt save correctly in access and all records are the same.although I traced my code and each time a different code is genrated but these diffrent codes doesnt save in access.just first code saves corectly and other records saves like first record
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = myconn;
label7.Text = "";
int[] s = new int[15];
int[] a = { 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] b = { 0, 0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
int[] result1 = new int[13];
int[] result2 = new int[13];
int f = Convert.ToInt32(textBox1.Text);
int m = Convert.ToInt32(textBox2.Text);
double sum1 = 0;
double div1 = 0;
double sum2 = 0;
double div2 = 0;
int z = Convert.ToInt32(textBox2.Text) - Convert.ToInt32(textBox1.Text);
if (z >= 400)
{
Form1 h = new Form1();
h.Close();
}
while (f <= m)
{
int l = f;
for (int i = 0; i <= 3; i++)
{
s[i] = 2;
}
s[4] = 0;
s[5] = 1;
for (int i = 12; i >= 6; i--)
{
s[i] = l % 10;
l = l / 10;
}
for (int i = 0; i <= 12; i++)
{
result1[i] = s[i] * a[i];
result2[i] = s[i] * b[i];
sum1 += result1[i];
sum2 += result2[i];
}
div1 = sum1 / 11;
div2 = sum2 / 11;
double value1 = div1;
int r = (int)((value1 - (int)value1) * 10);
double value2 = div2;
int o = (int)((value2 - (int)value2) * 10);
if (r == 9)
{
s[13] = 0;
}
else
{
s[13] = r + 1;
}
if (o == 9)
{
s[14] = 0;
}
else
{
s[14] = o + 1;
}
string we = "";
for (int q = 0; q <= 14; q++)
{
we += s[q];
}
cmd.Parameters.AddWithValue("@SP", we);
cmd.CommandText = "INSERT INTO [Counter](SubscriptionCode)" + " VALUES (@SP)";
myconn.Open();
cmd.ExecuteNonQuery();
myconn.Close();
f++;
label7.Text += " \n ";
}
A:
Check if the command is updated with the correct value on each iteration
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP json_encode function is not working on ajax call
In page load I am calling this function
function myFunction(selectedCinemaID) {
$.ajax({
type: "POST",
url: "show_details.php",
data: {cinema_id: selectedCinemaID }
}).done(function( show_list ) {
console.log(show_list.length);
});
And my code in show_details.php
$query = "SELECT * FROM `show` WHERE cinema_id=2;";
$result = mysql_query($query);
if($result){
$show_list = array();
while($row = mysql_fetch_array($result)){
array_push ($show_list, array($row['id'], $row['cinema_id'], row['show_time']));
}
echo json_encode($show_list);
} else {
echo mysql_error();
}
In my database I have only two row and three column but the length showed in the console is 64. But according to the database length should be 2. console.log(show_list) output [["2","2","2014-11-01 01:00:00"],["3","2","2014-11-01 04:00:00"]] but it seems everything here is treated as an array element or string. What is wrong in this code?
A:
You haven't told jquery that you're sending JSON. As such, it'll treat the json text that the server is sending as text. That means
console.log(show_list.length);
is outputting the length of the json string, not the count/size of the array you're building in PHP.
You need either
$.getJSON(....);
or
$.ajax(
dataType: 'json'
...
)
However, note that if your mysql query fails for any reason, then outputting the mysql error message as your are will cause an error in jquery - it'll be expecting JSON, and you could potentially be sending it a mysql error message, which is definitely NOT json.
Once you switch to JSON mode, you should never send anything OTHER than json:
if (query ...)
output json results
} else {
echo json_encode(array('error' => mysql_error()));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
AttributeError: 'module' object has no attribute 'Open'
I am running the following code which I found on: GDAL - Perform Simple Least Cost Path Analysis which I adapted to my case, but I get the following error when running the code in the python console of QGIS. I am rather new to the programming & QGIS world so if somebody would be able to help me that would be wonderful!
import gdal, osr
import osgeo.gdal
osgeo.gdal.GetDriverByName
from skimage.graph import route_through_array
import numpy as np
def raster2array(rasterfn):
raster = gdal.Open(rasterfn)
band = raster.GetRasterBand(1)
array = band.ReadAsArray()
return array
def coord2pixelOffset(rasterfn,x,y):
raster = gdal.Open(rasterfn)
geotransform = raster.GetGeoTransform()
originX = geotransform[0] # East/West location of Upper Left corner
originY = geotransform[3] # North/South location of Upper Left corner
pixelWidth = geotransform[1] # X pixel size
pixelHeight = geotransform[5] # Y pixel size
xOffset = int((x - originX)/pixelWidth)
yOffset = int((y - originY)/pixelHeight)
return xOffset,yOffset
def createPath(CostSurfacefn,costSurfaceArray,startCoord,stopCoord):
# coordinates to array index
startCoordX = startCoord[0]
startCoordY = startCoord[1]
startIndexX,startIndexY = coord2pixelOffset(CostSurfacefn,startCoordX,startCoordY)
stopCoordX = stopCoord[0]
stopCoordY = stopCoord[1]
stopIndexX,stopIndexY = coord2pixelOffset(CostSurfacefn,stopCoordX,stopCoordY)
# create path
indices, weight = route_through_array(costSurfaceArray, (startIndexY,startIndexX), (stopIndexY,stopIndexX),geometric=True,fully_connected=True)
indices = np.array(indices).T
path = np.zeros_like(costSurfaceArray)
path[indices[0], indices[1]] = 1
return path
def array2raster(newRasterfn,rasterfn,array):
raster = gdal.Open(rasterfn)
geotransform = raster.GetGeoTransform()
originX = geotransform[0] # East/West location of Upper Left corner
originY = geotransform[3] # North/South location of Upper Left corner
pixelWidth = geotransform[1] # X pixel size
pixelHeight = geotransform[5] # Y pixel size
cols = array.shape[1]
rows = array.shape[0]
driver = gdal.GetDriverByName('GTiff')
outRaster = driver.Create(newRasterfn, cols, rows, gdal.GDT_Byte)
outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
outband = outRaster.GetRasterBand(1)
outband.WriteArray(array)
outRasterSRS = osr.SpatialReference()
outRasterSRS.ImportFromWkt(raster.GetProjectionRef())
outRaster.SetProjection(outRasterSRS.ExportToWkt())
outband.FlushCache()
def main(CostSurfacefn,outputPathfn,startCoord,stopCoord):
costSurfaceArray = raster2array(CostSurfacefn) # creates array from cost surface raster
pathArray = createPath(CostSurfacefn,costSurfaceArray,startCoord,stopCoord) # creates path array
array2raster(outputPathfn,CostSurfacefn,pathArray) # converts path array to raster
if __name__ != "__main__":
CostSurfacefn = "Administratief_perseel_1polygoon_PXLKOST_6000_6000.tif"
startCoord = (174084.004,176969.786)
stopCoord = (173697.916,175206.172)
outputPathfn = 'Path.tif'
main(CostSurfacefn,outputPathfn,startCoord,stopCoord)
Error Code:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/c)QGIS/CLIP_AGIV_GRBgis_e40179/Projects/python_console_scripts/least_cost_path0.1.py", line 77, in <module>
main(CostSurfacefn,outputPathfn,startCoord,stopCoord)
File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/c)QGIS/CLIP_AGIV_GRBgis_e40179/Projects/python_console_scripts/least_cost_path0.1.py", line 65, in main
costSurfaceArray = raster2array(CostSurfacefn) # creates array from cost surface raster
File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/c)QGIS/CLIP_AGIV_GRBgis_e40179/Projects/python_console_scripts/least_cost_path0.1.py", line 9, in raster2array
raster = gdal.Open(rasterfn)
AttributeError: 'module' object has no attribute 'Open'
I assume there is a problem with opening the file that I want to analyze "Administratief_perseel_1polygoon_PXLKOST_6000_6000.tif" but I just don't know how to resolve this..
A:
import gdal is deprecated, gdal, ogr, osr etc are now part of the osgeo package. Try changing this:
import gdal, osr
import osgeo.gdal
osgeo.gdal.GetDriverByName
To this:
from osgeo import gdal, osr
| {
"pile_set_name": "StackExchange"
} |
Q:
Differences between JPA and JPA2
Does anyone have a list of the changes between JPA 1 and JPA 2?
I have read about the Criteria queries and other changes, but I would like a "what's new" kind of reference.
Thanks
A:
Google returns many results, including this and this blog posts. The summary (copied from the former) is:
Added support for persistently ordered lists using OrderColumn and provider-managed ordering column
Defined support for foreign key mapping strategy for unidirectional one-to-many relationships
Added clear method to EntityManager interface to allow entities to be evicted from the persistence context; added CLEAR cascade option.
Added Cache interface.
Added support for pessimistic locking and new lock mode types.
Added overloaded find and refresh methods added to support locking with standardized and vendor-specific properties and hints.
Added standardized hint javax.persistence.lock.timeout for use in locking configuration.
Added the standardized properties javax.persistence.jdbc.driver, javax.persistence.jdbc.url, javax.persistence.jdbc.user, javax.persistence.jdbc.password for use in persistence unit and entity manager factory configuration.
Added Query getNamedParameters and getPositionalParameters methods.
A:
JPA2 also adds typesafe query api. see http://www.ibm.com/developerworks/java/library/j-typesafejpa/
A:
There is also a pdf version of Mike Keith's presentation "What's New and Exciting in JPA 2.0" from Jazoon 2009.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert a PDF with a filled form to a JPEG image using ImageMagick and preserving the form data?
I'm trying to convert this PDF to a JPEG image via ImageMagick (v 6.8.7-0): https://dl.dropboxusercontent.com/u/10351891/cd.pdf
I didn't find any working solution to preserve the filled data inside the PDF.
This is one of the commands tried:
convert -colorspace CMYK -alpha off -interlace none -density 300x300 -quality 100 cd.pdf[0] cd_image.jpg
Since ImageMagick use Ghostscript for the conversion I've also update it to the last version (v 9.10) but nothing changed.
The command always print out a few warnings:
"Warning: considering '0000000000 XXXXX n' as a free entry"
"/BBox has zero width or height, which is not allowed."
Did someone find a way to convert it?
More information:
I used Preview for Mac to fill out the form.
On production, we use Ubuntu not Mac OS X and the PDF is not filled by me, but It's sent to us prefilled
A:
It is a known issue that Max OS X PDF Preview does not support AcroForms properly, see this blog post that contains some details: Script to Fix Mac OSX Preview.app Form Fill and Save.
Among other errors, your PDF form fields have a missing piece of information: the appearance stream (a set of instructions that tell the viewer how the field value is supposed to be rendered when it is not being edited).
If you can specify which PDF viewer should be used for editing the forms, then avoid Mac OS X preview. If you need to support Mac OS X preview, then you can try to re-generate this information programmatically with any PDF library that allows filling out forms, or you can apply a form flattening process instead (converting the "dynamic" text into static) before exporting as jpeg.
Examples:
If you have access to a Windows box and Adobe Acrobat, you can try
with the script mentioned before.
If you have access to a Windows box and purchasing a commercial
library is an option, you can try with Amyuni PDF
Creator
(Disclaimer: I work for Amyuni Technologies). for regenerating the
appearance stream you will need to enumerate the form fields,
retrieve their values, set an empty value to them, then re-assign
them the original values. For doing form flattening, you will have to
set the annotation attribute of each form field to false.
If you have access to a Linux box and a library with a GPL license is
not an issue, you can try creating a Java application with iText, the
method
PdfStamper.setFormFlattening(boolean)
seems to do what you need.
| {
"pile_set_name": "StackExchange"
} |
Q:
Exchange principle in terms of states and coordinates?
I have seen the exchange principle written in two ways, one in terms of coordinates and the other in terms of states:
If $\psi_{AB}(1,2)$ represents particle $A$ in state $1$ and particle $B$ in state $2$ then for bosons:
$$\psi_{AB}(1,2)=\psi_{AB}(2,1)$$ and for fermions: $$\psi_{AB}(1,2)=-\psi_{AB}(2,1)$$
and
If $\psi_{AB}(\vec x_1, \vec x_2)$ represents particle $A$ at $\vec x_1$ and particle $B$ at $\vec x_2$ then for bosons:
$$\psi_{AB}(\vec x_1,\vec x_2)=\psi_{AB}(\vec x_2,\vec x_1)$$ and for fermions: $$\psi_{AB}(\vec x_1,\vec x_2)=-\psi_{AB}(\vec x_2,\vec x_1)$$
Do both these tell us the exactly same information (i.e. may one hold when the other doesn't) and can this be shown?
A:
In the first convention, by state they mean total state (including spatial and spin components) but for the second convention, by state they mean only spatial component. This means that the first convention has more information and hence more restrictive. Particles can be at the same place (following the second convention) yet have different spin states (not following the first convention). So, the second convention is a subset of the first convention by being less restrictive.
By the end of the day, however, fermions should have an antisymmetric total state and bosons should have a symmetric total state.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to connect multiple devices to same Thing in AWS-IOT?
I am working on a project to install 100+ nodes of temperature sensors in an area, all of which perform the same function. The data they publish is the sensor id and the reading. I am using AWS-IOT for the backend.
Now, to do so, I think I will need to create 1 'thing' per node in aws-iot which I believe is extremely hard to maintain and unscalable.
So my question here is, how to connect multiple nodes to same 'thing' in AWS-IOT so that the cluster is easy to manage. Is there any alternate way to manage the cluster efficiently? Any inputs are welcome. Thanks.
A:
Faced with a similar dilemma and the impracticality of creating too many 'things' on the AWS IoT administration console; I've done some research and found that connecting multiple devices to the same 'thing' is strongly discouraged by AWS.
Anyway its not possible to keep two different nodes using the same MQTT id connected to the same thing (the last connected node with the same id kicks out the previously connected node), although you can use your client ID with the help of some code.
I learned that actually you don't need a 'thing' to connect to AWS IoT, just a certificate will do; and that you can create elements on AWS IoT service by code.
So, in summary; facing a similar question myself, I ran across this information below, found it useful in my case and sharing it here.
https://forums.aws.amazon.com/thread.jspa?threadID=234102
| {
"pile_set_name": "StackExchange"
} |
Q:
Partial differential equation, mixed derivatives
What can be concluded from following equation:
$$\frac{\partial f(x,y)}{\partial x}-\frac{\partial g(x,y)}{\partial y} = 0$$
where $f(x,y)$ and $g(x,y)$ are functions of two independent variables $x,y$. Does it generally imply that
$$\frac{\partial f(x,y)}{\partial x}=\frac{\partial g(x,y)}{\partial y}=a(x)b(y)$$ for some functions $a(x), b(y)$? Thanks for answer.
A:
No.
It implies that there exists a function $F(x,y)$ such that $\partial_x F(x,y)=g(x,y),\partial_y F(x,y)=f(x,y)$. Since
$$\partial_x\partial_y F(x,y)=\partial_y g(x,y)=\partial_x f(x,y)=\partial_y\partial_x F(x,y)$$
In general you can not separate $F(x,y)$ into $a(x)b(y)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Aggregate (function = mean) for duplicate sample ID, but keep string columns
I would like to average numerical columns for samples that have duplicate sample IDs, without losing string columns.
I have managed to take averages for duplicate sample IDs using the aggregate function, but first I have to remove the non-numerical columns from the dataset to get it to work. I would like to keep these descriptive columns in.
Creating a fake dataset:
ID<-c("QYZ","MMM","QYZ","bb2","gm6","gm6","YOU","LLL","LLL","LLL")
values<-c(1,2,4,5,5,6,8,9,6,4)
Levels<-c("A","B","A","C",'D','D',"C","y","y","y")
Exampledata<-data.frame(ID,values,Levels)
Here is the code I have tried:
Exampledata2<- aggregate(Exampledata[,-3], by = list(Exampledata$ID), mean, na.rm=TRUE)
Exampledata2 looks like this after the code:
Group.1 ID values
bb2 NA 5.000000
gm6 NA 5.500000
LLL NA 6.333333
MMM NA 2.000000
QYZ NA 2.500000
YOU NA 8.000000
But I would like it to look like this:
ID values Levels
MMM 2 B
QYZ 2.5 A
bb2 5 C
gm6 5.5 D
YOU 8 C
LLL 6.33 y
Note that the Levels are the same between duplicated sample IDs.
A:
Is this what you're looking for? I looks like you need to include levels in your group by statement if you want it to carry forward.
aggregate(Exampledata["values"], by = list(ID = ID, Levels = Levels), mean, na.rm=TRUE)
Here's the same thing with data.table
as.data.table(Exampledata)[, .(values = mean(values)), .(ID, Levels)]
| {
"pile_set_name": "StackExchange"
} |
Q:
How I can ignore feature in behat?
I am using behat with laravel.
I have some features which I want to ignore in tests.
So I have inside features folder:
- a.feature
- b.feature
- c.feature
I want to exclude feature c from testing. At the moment if I want to exclude feature c from tests I have to rename it - for example to "c.feature.tmp".
Is there some more intelligent way ... something like in java or .NET we have @Ignore annotation.
A:
You can give the features you don't want to test a tag like @notesting and then run behat like this.
behat --tags '~@notesting'
The ~ sign is a NOT operator.
Or like @grzegorz-zadja mentioned you can also use test suites.
In your feature file right above your Feature: you can put tags. Just add @notesting there. See the documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Staggered columns in WrapPanel or Custom Panel
I've been trying for a while now and I can't seem to replicate this model without using a grid. I've tried making some simple custom panels and a wrappanel that makes a new column after n pixels or n number of items which works; however, I'm unable to find a way to stagger each column.
Here's an image of what I'm trying to do:
I've made solutions that use a Grid that do stagger the columns however what I need is a panel that uses columns only and is fluid like a listview where if an item is added, moved, or removed the other items move accordingly (based on index).
A:
Because you want your Panel somewhat like a "living" list the solution needs 2 steps. First implement a panel that is able to arrange the items the way you want. Second add a manager that handles changes of the list. Furtunately all that is quite easy. This manager already exists, its the ItemsControl. Just feed in your ObserableCollection to the ItemsControl.
<ItemsControl Margin="10" ItemsSource="{Binding YoursItemsObserableCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<local:StaggeredPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="18"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</DataTemplate.Resources>
<Grid>
<Ellipse Fill="Silver" Width="40" Height="40"/>
<StackPanel>
<TextBlock Margin="3,3,3,0" Text="{Binding Path=Name}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
class StaggeredPanel : Panel
{
protected override Size MeasureOverride (Size availableSize)
{
foreach (var childo in InternalChildren)
{
FrameworkElement child = childo as FrameworkElement;
if (child != null)
{
var childMaxSize = new Size (double.PositiveInfinity, availableSize.Height);
child.Measure (childMaxSize);
}
}
return availableSize;
}
protected override Size ArrangeOverride (Size finalSize)
{
double x = 0;
double y = 0;
bool shift = true;
double shiftOffset;
if (InternalChildren.Count > 0)
{
FrameworkElement offsetChild = InternalChildren[0] as FrameworkElement;
shiftOffset = offsetChild.DesiredSize.Height / 2;
for (int i = 0; i < InternalChildren.Count; i++)
{
FrameworkElement child = InternalChildren[i] as FrameworkElement;
if (child != null)
{
double finalY = y;
if (shift)
{
finalY += shiftOffset;
}
shift = !shift;
child.Arrange (new Rect (new Point (x, finalY), child.DesiredSize));
x += child.DesiredSize.Width;
double nextWidth = 0;
if (i + 1 < InternalChildren.Count)
{
FrameworkElement nextChild = InternalChildren[i + 1] as FrameworkElement;
nextWidth = child.DesiredSize.Width;
}
if (x + nextWidth > finalSize.Width)
{
shift = true;
x = 0;
y += child.DesiredSize.Height;
}
}
}
}
return finalSize; // Returns the final Arranged size
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Integrating functions in real analysis
The following is a True/False problem from an exam I got back:
If $f'(x)=1$ for each $x\in\mathbb{R}$ and $f(2)=7$ then $f(-2)=-7$.
I said false for this problem, but it was marked wrong. My reasoning for this was to treat this as an initial value problem. First, integrate $f'(x)$ so that $f(x)=\int f'(x)dx=x+c$. Next solve for $c$ from $f(2)=7$. Thus $2+c=7\implies c=5$. So our function is $f(x)=x+5$ where $f'(x)=1\forall x\in\mathbb{R}$ and $f(2)=7$. Both of the statements in the AND statement in the hypothesis are true, therefore the hypothesis is true. Next, checking $f(-2)=3\neq-7$ therefore the conclusion of the implication is false. Here we have True imply false, therefore the implication is false.
Is there an error in my rationale?
A:
Your argument is correct. Besides, note that$$\frac{f(2)-f(-2)}{2-(-2)}=\frac{14}4=\frac72.$$But, by the mean value theorem, that quotient should be $1$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Late 70s Early 80s Children's SF Book Series
Basic premise was a space-crew who were in some sort of rescue role. The books in the series featured a space-ship which was illustrated as very similar to the "Discovery" from "2001", but was based from a 10,000 person wheel-shaped space colony. The crew wore track-suit style outfits (70s futuristic trope) and they had an alien that was a pink blob which communicated via a small computer attached to it, which printed out messages.
One adventure has the crew encountering a ship full of the pink blob aliens.
In another they have to rescue a colony on Venus by dropping the alien into a jammed landing dome.
In another the ship goes out of control and they encounter a long-lost space-colony where the inhabitants have grown into giants.
My local library only ever seemed to have a few books from the whole series. Some of the titles on the cover end-notes sounded quite good.
A:
This is a series called Galaxy 1 by, among others, Harriette Sheffer Abels, published by Crestwood House. It follows the adventures of Emergency Spaceship EM88. The pink blob with the computer is named Amorf. Here's a link to the Google books entries.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does 2>&1 do in this php snippet?
Regarding this code
public function invoke($url)
{
exec('wget 2>&1', $output);
print_r($output);
}
What does the 2>&1 do in this command? I found this on SO but the 2>&1 was not explained
wget is a linux command and I'm running it from PHP using exec().
The code above works. I just need to insert the $url in the correct place and understand the 2>&1.
Related Links
GNU Documentation on Wget
A:
You have several output streams.
The 2 most common are STDOUT (standard output) and STDERR (error output).
Normally you only see the STDOUT output. With exec this is also the only stream that it catches.
Now: the command 2>&1 means litteraly that you pass the output that would go to STDERR to the same output as the normal output. In this case to the exec function of PHP (but mostly to your shell).
This is mostly used when you want to daemonize your apps, and sent all the output to /dev/null, but it can also be used for this case (that you can see everything with PHP).
| {
"pile_set_name": "StackExchange"
} |
Q:
Lemma for proving Zermelo's theorem
I'm trying to understand the following lemma in Bourbaki's set theory (chapter III, §2,no. 3,Lemma 3):
Lemma 3: Let $E$ be a set, let $S$ be a subset of $P(E)$, and let $p$ be a mapping of $S$ into $E$ such that $p(X)\notin X$ for all $X\in S$. Then there exists a subset $M$ of $E$ and a well-ordering $\Gamma$ on $M$ such that, if $x\leq y$ denotes $y\in \Gamma(x)$ and $S_x$ denotes the segment $]\leftarrow,x[$,
for all $x\in M$ we have $S_x\in S$ and $p(S_x)=x$;
$M\notin S$
(note that "segment" means "initial segment")
The following figure, shows a very simplistic scenario:
The conditions of the lemma are satisfied in the mapping shown ($p(X)\notin X$ for all $X\in S$), however, any ordered $M\subset E$ that you take, will have segments that are not in $S$ (e.g. $\emptyset$). So what's the conclusion 1 of the lemma all about?
A:
If $\emptyset\notin S$ (as in your example), one can choose $M=\emptyset$ and condition 1 becomes trivial. Otherwise, $M$ cannot be empty, it has a least element $a$, which is $p(\emptyset)$ by condition 1. If $A= \{a\}$ is not in $S$, one can choose $M=A$, otherwise $M$ has a second element, which is $p(A)$, etc. More generally, if $x\in M$, and $B$ is the set of elements $\le x$, either $B\in S$, case where $p(B)$ is the successor of $x$ or $B\notin S$, case where $M=B$.
The proof of the lemma is a clever use of the uniqueness property given by condition 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
href field missing when I get the page using jsoup or htmlunit
I'm trying to parse google images search result.
I'm trying to get the href attribute of an element. I've noticed that the href field is missing when I get the page programmatically (this happens with both jsoup and htmlunit).Comparing the element of the page got programmatically through java and the element of the page loaded by the actual browser, the only difference is, indeed, the href field that is missing (the rest is the same).
The href attribute (IMAGE_LINK) is the following: /imgres?imgurl=http%3A%2F%2Fcdn.zonarutoppuden.com%2Fns%2Fpeliculas-naruto-shippuden.jpg&imgrefurl=http%3A%2F%2Fwww.zonarutoppuden.com%2F2010%2F10%2Fnaruto-shippuden-peliculas.html&docid=JR8NPqKrF3ac_M&tbnid=0EPPOYQcflXkMM%3A&w=900&h=600&bih=638&biw=1275&ved=0ahUKEwih9O2e88_OAhWMExoKHRLGAGQQMwg2KAMwAw&iact=mrc&uact=8
Maybe some issue with the javascript engine? Or maybe some kind of algorithm anti-parsing used by the website?
Snippet Java Code:
WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.waitForBackgroundJavaScript(50000);
HtmlPage page1=null;
try {
// Get the first page
page1 = webClient.getPage(URL);
System.out.println(page1.asXml());
} catch (FailingHttpStatusCodeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Snippet Html Code (Real Browser):
<a jsaction="fire.ivg_o;mouseover:str.hmov;mouseout:str.hmou" class="rg_l" style="width: 134px; height: 201px; left: 0px; background: rgb(128, 128, 128);" href="IMAGE_LINK"> CONTENT... </a>
Snippet Html Code (Page got programmatically):
<a jsaction="fire.ivg_o;mouseover:str.hmov;mouseout:str.hmou" class="rg_l" style="width: 134px; height: 201px; left: 0px; background: rgb(128, 128, 128);"> CONTENT... </a>
Thank you.
A:
For each search result there is a <div class="rg_meta">containing a JSON object, which also holds the url. Using a JSON parser like json-simple to parse the object, the following code prints the image urls:
String searchTerm = "naruto shippuden";
String searchUrl = "https://www.google.com/search?site=imghp&tbm=isch&source=hp&biw=1920&bih=955&q=" + searchTerm.replace(" ", "+") + "&gws_rd=cr";
try {
Document doc = Jsoup.connect(searchUrl)
.userAgent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36")
.referrer("https://www.google.com/").get();
JSONObject obj;
for (Element result : doc.select("div.rg_meta")) {
// div.rg_meta contains a JSON object, which also holds the image url
obj = (JSONObject) new JSONParser().parse(result.text());
String imageUrl = (String) obj.get("ou");
// just printing out the url to demonstate the approach
System.out.println("imageUrl: " + imageUrl);
}
} catch (IOException e1) {
e1.printStackTrace();
}catch (ParseException e) {
e.printStackTrace();
}
Output:
imageUrl: http://ib3.huluim.com/show_key_art/1603?size=1600x600®ion=US
imageUrl: http://cdn.zonarutoppuden.com/ns/peliculas-naruto-shippuden.jpg
imageUrl: http://www.saiyanisland.com/news/wp-content/uploads2/2014/12/Naruto-Sasuke.jpg
...
Update
Since jsAction doesn't seem to play nicely with htmlUnit, I would propose to use phantomJs. Just download the binary for your OS and create a script file.
create a page.js file:
var page = require('webpage').create();
var fs = require('fs');
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36';
page.zoomFactor = 0.1;
page.viewportSize = {
width: 1920,
height: 1080
};
var divCount="-1";
var topPosition=0;
var unchangedCounter=0;
page.open('https://www.google.com/search?site=imghp&tbm=isch&source=hp&q=naruto+shippuden&gws_rd=cr', function(status) {
console.log("Status: " + status);
if(status === "success") {
window.setInterval(function() {
var newDivCount = page.evaluate(function() {
var divs = document.querySelectorAll(".rg_di.rg_bx.rg_el.ivg-i");
return divs[divs.length-1].getAttribute("data-ri");
});
topPosition = topPosition + 1080;
page.scrollPosition = {
top: topPosition,
left: 0
};
if(newDivCount===divCount){
page.evaluate(function() {
var button = document.querySelector("#smb");
console.log("buttontype:"+typeof button);
if(!(typeof button === "undefined")) {
button.click();
return true;
}else{
return false;
}
});
if(unchangedCounter===5){
console.log(newDivCount);
var path = 'output.html';
fs.write(path, page.content, 'w');
phantom.exit();
}else{
unchangedCounter=unchangedCounter+1;
}
}else{
unchangedCounter=0;
}
divCount = newDivCount;
}, 500);
}
});
Now we execute the script file with phantomJs and parse the result as before with jsoup:
try {
Process process = Runtime.getRuntime().exec("bin\\phantomjs page.js"); //change path to phantomjs binary and your script file
process.waitFor();
Document doc = Jsoup.parse(new File("output.html"),"UTF-8"); // output.html is created by phantom.js, same path as page.js
for (Element element : doc.select("div.rg_di.rg_bx.rg_el.ivg-i a")) {
System.out.println(element.attr("href"));
}
System.out.println("Number of results: " + doc.select("div.rg_di.rg_bx.rg_el.ivg-i a").size());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Output:
/imgres?imgurl=http%3A%2F%2Fib3.huluim.com%2Fshow_key_art%2F1603%3Fsize%3D1600x600%26region%3DUS&imgrefurl=http%3A%2F%2Fwww.hulu.com%2Fnaruto-shippuden&docid=OgW4j66rp7CKkM&tbnid=SElXvYDJj9cR6M%3A&w=1600&h=600&bih=10800&biw=19200&ved=0ahUKEwjX2PXmptPOAhULVxoKHXfmDg8QMwgzKAAwAA&iact=mrc&uact=8
/imgres?imgurl=http%3A%2F%2Fcdn.zonarutoppuden.com%2Fns%2Fpeliculas-naruto-shippuden.jpg&imgrefurl=http%3A%2F%2Fwww.zonarutoppuden.com%2F2010%2F10%2Fnaruto-shippuden-peliculas.html&docid=JR8NPqKrF3ac_M&tbnid=0EPPOYQcflXkMM%3A&w=900&h=600&bih=10800&biw=19200&ved=0ahUKEwjX2PXmptPOAhULVxoKHXfmDg8QMwg0KAEwAQ&iact=mrc&uact=8
...
Number of results: 463
Update: passing the url as a parameter to the script
Script page.js
var page = require('webpage').create();
var fs = require('fs');
var system = require('system');
var url = "";
var searchParameter = "";
if (system.args.length === 3) {
url=system.args[1];
searchParameter=system.args[2];
}
if(url==="" || searchParameter===""){
phantom.exit();
}
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36';
page.zoomFactor = 0.1;
page.viewportSize = {
width: 1920,
height: 1080
};
var divCount="-1";
var topPosition=0;
var unchangedCounter=0;
page.open(url, function(status) {
console.log("Status: " + status);
if(status === "success") {
window.setInterval(function() {
var newDivCount = page.evaluate(function() {
var divs = document.querySelectorAll(".rg_di.rg_bx.rg_el.ivg-i");
return divs[divs.length-1].getAttribute("data-ri");
});
topPosition = topPosition + 1080;
page.scrollPosition = {
top: topPosition,
left: 0
};
if(newDivCount===divCount){
page.evaluate(function() {
var button = document.querySelector("#smb");
if(!(typeof button === "undefined")) {
button.click();
return true;
}else{
return false;
}
});
if(unchangedCounter===5){
var path = searchParameter+'.html';
fs.write(path, page.content, 'w');
phantom.exit();
}else{
unchangedCounter=unchangedCounter+1;
}
}else{
unchangedCounter=0;
}
divCount = newDivCount;
}, 500);
}else{
phantom.exit();
}
});
Java code
try {
//change path to phantomjs binary and your script file
String phantomJSPath = "phantomjs" + File.separator + "bin" + File.separator + "phantomjs";
String scriptFile = "page.js";
String searchTerm = "naruto+shippuden";
String urlParameter = "https://www.google.com/search?site=imghp&tbm=isch&source=hp&gws_rd=cr&q="+searchTerm;
Process process = Runtime.getRuntime().exec(phantomJSPath + " " + scriptFile + " " + urlParameter + " " + searchTerm);
process.waitFor();
Document doc = Jsoup.parse(new File(searchTerm + ".html"),"UTF-8"); // output.html is created by phantom.js, same path as page.js
for (Element element : doc.select("div.rg_di.rg_bx.rg_el.ivg-i a")) {
System.out.println(element.attr("href"));
}
System.out.println("Number of results: " + doc.select("div.rg_di.rg_bx.rg_el.ivg-i a").size());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a realm model
I am creating a model in Realm like this:
import Realm
class Contact:RLMObject {
dynamic var nameLabel=""
dynamic var image=""
dynamic var isSelected=false
dynamic var phone=""
}
But I don't want to use isSelected area in database. It is just a variable not important. Can I use this model as a database without isSelected variable?
A:
Just mark it as an ignored property and it won't be persisted:
import Realm
class Contact: RLMObject {
dynamic var nameLabel = ""
dynamic var image = ""
dynamic var isSelected = false
dynamic var phone = ""
override class func ignoredProperties() -> [AnyObject]? {
return ["isSelected"]
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
I have a C# Multiview and everytime I click on the last menu item it gives me an error
I have a C# Multiview and everytime I click on the last menu item it gives me an error and stops running in Visual Studio 2010. The error is 'ActiveViewIndex is being set to '8'. It must be smaller than the current number of View controls '8'. For dynamically added views, make sure they are added before or in Page_PreInit event.'
CODE
<div>
<asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick" Orientation="Horizontal" style="left: 0px; position: relative; top: 18px; font-family:Arial;" Height="38px" Width="800px" >
<StaticMenuStyle HorizontalPadding="0px" VerticalPadding="0px" />
<StaticSelectedStyle BackColor="#EAEAEA" BorderColor="#000000" />
<Items>
<asp:MenuItem Text="about us" Value="0" Selected="True"></asp:MenuItem>
<asp:MenuItem Text="events" Value="1"></asp:MenuItem>
<asp:MenuItem Text="contact us" Value="2"></asp:MenuItem>
<asp:MenuItem Text="patio" Value="3"></asp:MenuItem>
<asp:MenuItem Text="customers" Value="4"></asp:MenuItem>
<asp:MenuItem Text="family" Value="5"></asp:MenuItem>
<asp:MenuItem Text="swans" Value="6"></asp:MenuItem>
<asp:MenuItem Text="swim" Value="7"></asp:MenuItem>
<asp:MenuItem Text="bonus" Value="8"></asp:MenuItem>
</Items>
<StaticHoverStyle BackColor="Silver" />
<StaticMenuItemStyle BorderColor="#EAEAEA" BorderStyle="Solid" BorderWidth="1px" />
</asp:Menu>
</div>
<div style="width: 800px; height: 450px; background-color: #EAEAEA; border:1px solid #000000; padding:10px 10px 0px 10px; font-family: Arial;" >
<asp:MultiView ID="MultiView1" runat="server">
<asp:View ID="View1" runat="server"></asp:View>
<asp:View ID="View2" runat="server"></asp:View>
<asp:View ID="View3" runat="server"></asp:View>
<asp:View ID="View4" runat="server"></asp:View>
<asp:View ID="View5" runat="server"></asp:View>
<asp:View ID="View6" runat="server"></asp:View>
<asp:View ID="View7" runat="server"></asp:View>
<asp:View ID="View8" runat="server"></asp:View>
</asp:MultiView>
</div>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
MultiView1.ActiveViewIndex = 0;
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
MultiView1.ActiveViewIndex = Int32.Parse(Menu1.SelectedValue);
}
Any help would be super duper.
A:
You have 9 menu-items and 8 views
MultiView1.ActiveViewIndex = 8
would fail since the ActiveViewIndex is zero-based (as you correctly implemented)
you could evaluate the length of the MultiView1.Views first and then set the ActiveViewIndex
int index = Int32.Parse(Menu1.SelectedValue)
if (MultiView1.Views.Count > index)
{
MultiView1.ActiveViewIndex = index
}
perhaps you should check if index is not -1 and larger or equal than 0.
| {
"pile_set_name": "StackExchange"
} |
Q:
Performance metrics on SQL Server Profiler and sp_trace commands
Are there any metrics available that indicate the varying performance of using MS SQL Profiler against the sp_trace commands on SQL Server 2008. Most articles and writers seem to suggest that using sp_trace commands would be more efficient but is their any empirical evidence for this under varying workloads.
A:
I believe the reason you hear this suggestion is because SQL Server Profiler is merely the GUI front end that runs on top of SQL Trace
From Brad McGeHee's Mastering SQL Server Profiler:
What may be a surprise to many DBAs and developers is that SQL Server
Profiler is only a GUI designed to work with another feature of SQL
Server called SQL Trace. It is SQL Trace that is actually doing most
of the work when it comes to capturing SQL Server events and storing
them for later use. SQL Trace is a feature of SQL Server that can be
accessed indirectly with the Profiler GUI, system stored procedures,
or programmatically using Server Management Objects (SMO).
In essence, SQL Trace is a very simple tool. Its job is just to
capture SQL Server-related communication between a client and SQL
Server. It acts similarly to a specialized network sniffer that
captures traffic on the network related to SQL Server and allows you
to see exactly which events are being sent from the client to SQL
Server.
| {
"pile_set_name": "StackExchange"
} |
Q:
Split collection into multiple collections
I want to create new list of list on basis of a single list.
I have a list like
public class OfficeLocator
{
public String id{ get; set; }
public string Geography{ get; set; }
public string Country{ get; set; }
public string State{ get; set; }
public string OfficeName{ get; set; }
}
I am trying to prepare an tree structured list
GeographyName="Asia",
{
Country = "China",
{
State = "Hunan",
{
{
OfficeId = "1",
OfficeName = "Office 1"
},
{
OfficeId = "2",
OfficeName = "Office 2"
}
},
State = "Hubei"
{
{
OfficeId = "3",
OfficeName = "Office 3"
}
}
},
Country = "India",
{
State = "Maharashtra",
{
{
OfficeId = "4",
OfficeName = "Office 4"
},
{
OfficeId = "5",
OfficeName = "Office 5"
}
},
State = "Punjab"
{
{
OfficeId = "6",
OfficeName = "Office 6"
}
}
},
},
GeographyName="Europe",
{
Country = "UK",
{
State = "York",
{
{
OfficeId = "7",
OfficeName = "Office 7"
},
{
OfficeId = "8",
OfficeName = "Office 8"
}
}
}
}
I tried using some group by on Geography and Country.
But I am not getting the required output.
I can use looping logic to get the result, but I want to avoid it and try something with linq.
A:
Something like this?
var allRegionGroups = allOfficeLocators
.GroupBy(ol => ol.Geography)
.Select(gGroup => new
{
GeographyName = gGroup.Key,
Countries = gGroup
.GroupBy(ol => ol.Country)
.Select(cGroup => new
{
Country = cGroup.Key,
States = cGroup
.GroupBy(ol => ol.State)
.Select(sGroup => new
{
State = sGroup.Key,
OfficeList = sGroup
.Select(ol => new { OfficeId = ol.id, ol.OfficeName })
.ToList()
})
.ToList()
})
.ToList()
})
.ToList();
How you can access all properties of the anonymous types:
foreach (var region in allRegionGroups)
{
string geographyName = region.GeographyName;
var allCountries = region.Countries;
foreach (var c in allCountries)
{
string country = c.Country;
var allStates = c.States;
// and so on...
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
update only related products programatically - magento 2
I follow this answer for update related products, It works but it will delete cross sell and upsell products of parent. is this default behavior or did I something wrong?
//For testing load one product
$target=$this->productRepository->getById(501);
//Here I collect related skus list programatically
.........................................
..........................................
$skuLinks = explode(",",$related);
$obj = \Magento\Framework\App\ObjectManager::getInstance();
foreach($skuLinks as $skuLink) {
$productLink = $obj->create('Magento\Catalog\Api\Data\ProductLinkInterface')
->setSku($target->getSku())
->setLinkedProductSku($skuLink)
->setPosition(1)
->setLinkType('related');
$linkData[] = $productLink;
}
//Set Product Link
$target->setProductLinks($linkData);
$this->productRepository->save($target);
//checking, it only display the related skus, previously it shows related,upsell,crossell
$links=$target->getProductLinks();
foreach($links as $link)
{
echo $link->getLinkType().' - '.$link->getLinkedProductSku().'<br>';
}
A:
All links will be overwritten, if you call ProductInterface::setLinks method.
You can try to add new links in already existed product links array.
Example:
$links = $product->getProductLinks();
$links[] = $newLink;
$product->setProductLinks($links);
$this->productRepository->save($product);
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding the arc length of the parabola $y=x^2 \; from \; (0,0)\;to\;(1,1)$
As the title says, I need to find the arc length of that. This is what I have so far (I'm mostly stuck on the integration part): $${dy\over dx}=2x \Rightarrow L=\int_0^1 \sqrt{1+(2x)^2}dx$$
Substitute $$x=\tan\theta, \qquad dx=\sec^2\theta\,d\theta ,$$
giving $$\int_0^1 \sqrt{1+(2\tan\theta)^2}\sec^2\theta\,d\theta=\int_0^1 \sqrt{1+4\tan^2\theta}\sec^2\theta\,d\theta$$
That is where I'm stuck. Any help is appreciated, thank you.
A:
Let $2x = \tan\theta$ instead. Then, the integral becomes $\displaystyle \int_0^{\arctan 2} \sqrt{1+\tan^2 \theta} \cdot \dfrac14\sec^2\theta \ \mathrm d\theta$ which is equal to $\displaystyle \frac14 \int_0^{\arctan2} \sec^3\theta \ \mathrm d\theta$.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the best way to create a Pandas MultiIndex from a list of dictionaries?
I have an iterative process that runs with different parameter values each iteration and I want to collect the parameter values and results and put them in a Pandas dataframe with a multi-index built from the sets of parameter values (which are unique).
Each iteration, the parameter values are in a dictionary like this say:
params = {'p': 2, 'q': 7}
So it is easy to collect them in a list along with the results:
results_index = [
{'p': 2, 'q': 7},
{'p': 2, 'q': 5},
{'p': 1, 'q': 4},
{'p': 2, 'q': 4}
]
results_data = [
{'A': 0.18, 'B': 0.18},
{'A': 0.67, 'B': 0.21},
{'A': 0.96, 'B': 0.45},
{'A': 0.58, 'B': 0.66}
]
But I can't find an easy way to produce the desired multi-index from results_index.
I tried this:
df = pd.DataFrame(results_data, index=results_index)
But it produces this:
A B
{'p': 2, 'q': 7} 0.18 0.18
{'p': 2, 'q': 5} 0.67 0.21
{'p': 1, 'q': 4} 0.96 0.45
{'p': 2, 'q': 4} 0.58 0.66
(The index did not convert into a MultiIndex)
What I want is this:
A B
p q
2 7 0.18 0.18
5 0.67 0.21
1 4 0.96 0.45
2 4 0.58 0.66
This works, but there must be an easier way:
df = pd.concat([pd.DataFrame(results_index), pd.DataFrame(results_data)], axis=1).set_index(['p', 'q'])
UPDATE:
Also, this works but makes me nervous because how can I be sure the parameter values are aligned with the level names?
index = pd.MultiIndex.from_tuples([tuple(i.values()) for i in results_index],
names=results_index[0].keys())
df = pd.DataFrame(results_data, index=index)
A B
p q
2 7 0.18 0.18
5 0.67 0.21
1 4 0.96 0.45
2 4 0.58 0.66
A:
I ran into this recently and it seems there's a slightly cleaner way than the accepted answer:
results_index = [
{'p': 2, 'q': 7},
{'p': 2, 'q': 5},
{'p': 1, 'q': 4},
{'p': 2, 'q': 4}
]
results_data = [
{'A': 0.18, 'B': 0.18},
{'A': 0.67, 'B': 0.21},
{'A': 0.96, 'B': 0.45},
{'A': 0.58, 'B': 0.66}
]
index = pd.MultiIndex.from_frame(pd.DataFrame(results_index))
pd.DataFrame(results_data, index=index)
Outputs:
A B
p q
2 7 0.18 0.18
5 0.67 0.21
1 4 0.96 0.45
2 4 0.58 0.66
| {
"pile_set_name": "StackExchange"
} |
Q:
Making an email function in Python
I'm working on a project right now that requires the capability to send emails. My problem is that whenever I put the emailing code into a function, it stops working.
Here's the function (excluding the actual email and password information of course):
import smtplib, ssl
port = 465
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "password"
message = """\
Subject: Subject
This is the email body"""
def send(msg):
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg)
print("SENT")
if __name__ == "__main__":
send(message)
this doesn't even give me errors, it just doesn't work. However, if I do it like this, everything works fine:
import smtplib, ssl
port = 465
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "password"
message = """\
Subject: Subject
This is the email body"""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
print("SENT")
Any thoughts on why this is happening?
A:
The only difference I can see is the whitespace before your subject line in the email's contents. Try removing it such that your snippet is as follows:
import smtplib, ssl
port = 465
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "password"
message = """\
Subject: Subject
This is the email body"""
def send(msg):
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg)
print("SENT")
if __name__ == "__main__":
send(message)
Seeing as this is the only real difference in your two snippets, this is my best idea as to what is going wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to correctly bson.MarshalJSON(myStruct) with an ObjectID?
When I take my grab a post form my db and try and render it to JSON I run into some problems:
type PostBSON struct {
Id bson.ObjectId `bson:"_id,omitempty"`
Title string `bson:"title"`
}
// ...
postBSON := PostBSON{}
id := bson.ObjectIdHex(postJSON.Id)
err = c.Find(bson.M{"_id": id}).One(&postBSON)
// ...
response, err := bson.MarshalJSON(postBSON)
The MarshalJSON doesn't handle hexing Id (ObjectId) for me . Thus I get:
{"Id":{"$oid":"5a1f65646d4864a967028cce"}, "Title": "blah"}
What is the correct way to clean up the output?
{"Id":"5a1f65646d4864a967028cce", "Title": "blah"}
Edit: I wrote my own stringify as described here.
Is this a performant solution?
And is it idiotmatic go?
func (p PostBSON) String() string {
return fmt.Sprintf(`
{
"_id": "%s",
"title": "%s",
"content": "%s",
"created": "%s"
}`,
p.Id.Hex(),
p.Title,
p.Content,
p.Id.Time(),
)
A:
You can implement a MarshalJSON to satisfy json.Marshaler interface, e.g.:
func (a PostBSON) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{
"id": a.Id.Hex(),
"title": a.Title,
}
return json.Marshal(m)
}
| {
"pile_set_name": "StackExchange"
} |
Q:
PyQt5 can't create Tabbars or Tabs
I have been struggling to learn PyQt5 (and object oriented programming). In my current script I need to create a tabbed interface but can't seem to manage it. I suspect the problem is related to OOP (I am a novice). "self" seems to be the problem, and I kind of know what that means but not enough to be able to fix it. Below is my latest attempt. It seems like I am using the "wrong self", from elsewhere in the script. I want very much to understand object oriented programming - thanks in advance to anyone kind enough to help!
Some of the code/errors are:
code:
tabbar = QTabBar()
tab1 = QTabWidget()
tabbar.addTab(tab1, 'tab1')
error:
TypeError: arguments did not match any overloaded call:
addTab(self, str): argument 1 has unexpected type 'QTabWidget'
addTab(self, QIcon, str): argument 1 has unexpected type 'QTabWidget'
And here's the code:
class App(QMainWindow):
def launch(self, filepath):
subprocess.run(filepath)
def newLauncher(self, matrix):
pass # cut for brevity
def __init__(self):
super(App, self).__init__()
tabbar = QTabBar()
tab1 = QTabWidget()
index = tabbar.addTab(tab1, 'tab1')
self.initUI()
def initUI(self):
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
A:
It is good that you want to learn about OOP, but that is not the main problem in this case, but it seems that you do not read the documentation. If we check that it is a QTabBar it would see that it refers to the top part of the QTabWidget, it is that part with buttons.
You do not have to use QTabBar but QTabWidget, QTabWidget has the addTab method that requires as a first parameter the widget that will be displayed on a page, and as a second parameter a title that will appear on the buttons.
Another mistake that I see in your code is that you create the widget but not setting it as part of another widget are just local variables that we know are deleted when the function is finished.
Since you are using QMainWindow you must set QTabWidget as part of a central widget, for this we can use the layouts.
import sys
from PyQt5.QtWidgets import *
class App(QMainWindow):
def __init__(self):
super(App, self).__init__()
centralWidget = QWidget()
lay = QVBoxLayout(centralWidget)
tab = QTabWidget()
lay.addWidget(tab)
for i in range(5):
page = QWidget()
tab.addTab(page, 'tab{}'.format(i))
self.setCentralWidget(centralWidget)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
| {
"pile_set_name": "StackExchange"
} |
Q:
"Access Point Name settings not available for this user"
This was probably an issue before but only became an issue when I changed providers in a foreign country. Running CM12.1 nightlies.
I can't connect to data and get the above message when I try to manually enter the APN settings.
I have tried:
The other fix on this site to change permission in com.android.providers.telephony to 660 from 751 but that resulted in non-stop error messages from the phone app.
Upgrade to the latest nightly with the new SIM inside. No change in service or in ability to change APN
Delete the data and cache for the settings app
Wipe cache and Dalvik cache.
Downgrading to CM 11 milestone
A:
edit: I should mention this fixed issues with Sprint for me, but perhaps googling in this vein could lead to finding a similar fix for other carriers.
tl;dr: I booted to recovery (TWRP), wiped, flashed CM12.1, 5.1 GApps, and the sprint.zip file from this XDA post and got LTE back.
I'm not positive my issue was the same, but the symptoms are very similar so I'm adding the solution I found. My LTE was working fine on CM12 and CM12.1 for perhaps 3+ months. My phone battery died overnight a couple days ago, and when I powered it on the next morning it didn't have LTE anymore.
Not only that, but I was getting the "APN settings not available for this user" under Settings -> Mobile Networks -> APN settings. After googling, and googling, and googling, I think I tried about every solution suggested for this issue:
setting /data/data/com.android.providers/telephony/database/telephony.db to higher permissions (e.g. 761)
deleting telephony.db and telephony.db-journal and letting the system re-create it (theoretically in the "proper" manner)
using *#*#4636#*#* and playing with the preferred network (LTE/GSM/CDMA, LTE only, etc.)
Turning on wifi, rebooting, waiting a while, and then turning it off and trying to connect to data
Adding a custom APN, which often wouldn't even save if I had the "APN settings not available for this user", and didn't seem to do anything otherwise.
I even went back to stock (upgrading radios and firmware in the process) by applying the latest RUU here. This updated my radios (I was on 3.31.651.2), and allowed me to update PRL/profile while I was at it. I didn't even have LTE from the stock ROM.
I ran into post where someone mentioned "the Sprint APN fix" so I googled for that and ran into this post, which points to this XDA post with the fix.
Downloading that file (sprint.zip) worked great for me, despite that post being ~2 years old. I just did the following:
boot into TWRP, wipe as usual as if installing a new ROM
flash CM12.1 (I used the most recent M8 snapshot from 09-01-2015)
flash 5.1 GApps
flash the sprint.zip file
wipe cache/dalvik
Rebooted and had LTE right away during setup. Soooo relieved, as this was killing me. I'm still puzzled as to how it could have gotten goofed from a previously working setup, but at least it's behaving now. Hope this helps others.
A:
sigh factory reset did the trick.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get rid of Christmas Animation from mobile screen
I am seeing a Christmas animation on my mobile screen from 25th Dec 2012. I have no idea how did it come to my mobile. Because I rarely use internet on my mobile. And I used Internet last time at least 2-3 months before.
It automatically appears after some mins and eats my battery. I have checked all running and installed application. But none of them giving me any clue about this animation.
I am doubtful that this is the animation from Go launcher or Go SMS. but not confirmed.
I also have scanned my mob for spyware and antivirus. But nothing found.
A:
As previously mentioned it's from Go Launcher. There is, however a setting to disable it.
Go to Preferences and there should be an option to disable the Christmas animation. I can no longer find it in mine but I do know it was there when the animation was appearing.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pandas groupby two columns and get max value
Pandas groupby two columns and get max value
I have grouped data with multiindex
Model VehicleType VehicleType
100 sedan 278
wagon 109
coupe 2
convertible 1
145 small 19
... ...
zafira sedan 22
small 11
suv 7
convertible 1
coupe 1
I need to get max value of count (right column) with corresponding model and VehicleType, like this:
Model VehicleType VehicleType
100 sedan 278
145 small 19
... ...
zafira sedan 22
Thanks for solutions!
A:
Use DataFrameGroupBy.idxmax for indices by maximum value and then select by DataFrame.loc:
df = df.loc[df.groupby(level=0)['VehicleType'].idxmax()]
print (df)
VehicleType
Model VehicleType
100 sedan 278
145 small 19
zafira sedan 22
| {
"pile_set_name": "StackExchange"
} |
Q:
navigate away alert without saving modifications
I'm developing a website in php.
I want to show a message something like javascript alert, when a user tries to edit or add something in a form and tries to navigate to some other section without saving the modification, i want to show a message to them,
that you are about to navigate about from this page, your modifications are not saved, do you want to continue?
how can i do this??
any one have an idea ???please share it with me..
Thanks
A:
Use the beforeunload event. Pseudo-code:
window.onbeforeunload = function(e){
e = e || window.event;
// check if the user has edited sth
if(userHasEditedSomething()){
var msg = "You have unsaved changed. Do you want to navigate away from this page?";
e.returnValue = msg;
return msg;
}
}
Your job is to implement the userHasEditedSomething function that will return true when the user has unsaved changes (filled-in form fields) and false otherwise.
most of the browsers support this event
| {
"pile_set_name": "StackExchange"
} |
Q:
Deformation of $\mathbb{P}^1 \times \mathbb{P}^1$
I learnt that $\mathbb{P}^1 \times \mathbb{P}^1$ is rigid, but can be deformed to a non-rigid Hirzebruch surface $S$. Suppose $\pi: M \to B$ is such deformation such that $\mathbb{P}^1 \times \mathbb{P}^1 \cong M_{t_0}$ and $S \cong M_{t_1}$.
I want to understand the meaning of "rigidity". Does this mean that:
(1) there exists an open set $t_0 \in U \subseteq B$, such that for all $t\in U$, $M_t \cong \mathbb{P}^1 \times \mathbb{P}^1$? (Or maybe more strongly, $M_U \cong U \times (\mathbb{P}^1 \times \mathbb{P}^1)$?); or (2) only the first order deformation of $\mathbb{P}^1 \times \mathbb{P}^1$ is trivial (because $H^1(\mathbb{P}^1 \times \mathbb{P}^1, \Theta)$ = 0), and it could well happen that no matter how $t \in B$ closes to $t_0$, $M_t$ may not isomorphism to $\mathbb{P}^1 \times \mathbb{P}^1$?
If (1) is the meaning of "rigidity", then I feel it is strange that for some $t$, $M_t$ "suddenly" becomes NOT the same as $\mathbb{P}^1 \times \mathbb{P}^1$. Moreover, I think the construction of aforementioned deformation is by considering extension of vector bundles $V, W$, and ${\rm Ext}^1(W,V)$ is the base $B$. So for $t \neq t_0$, the extension will never be trivial, and hence the corresponding variety should not be the same as $\mathbb{P}^1 \times \mathbb{P}^1$.
If (2) is the meaning of "rigidity", and suppose $\mathfrak{M} \to \mathfrak{B}$ is the Kuranishi family of $\mathbb{P}^1 \times \mathbb{P}^1$. Then I guess $T_{\mathfrak B, t_0} \cong H^1(\mathbb{P}^1 \times \mathbb{P}^1, \Theta) = 0$. But according to the previous discussion, $\mathfrak B$ is not of dimensional $0$. Hence $t_0$ must be singular at $\mathfrak B$. (By the way, is there a way to compute the dimension of Kuranishi space?)
My knowedge of deformation theory is floppy. Any comment/reference is very well appreciated!
A:
Rigidity means, if you have a family $F$ of surfaces such that one $f\in F$ of them is $\mathbb P^1 \times \mathbb P^1$, then there is an open set $U\subseteq F, U \ni f$ each of whom is $\mathbb P^1 \times \mathbb P^1$.
The source of confusion, I think, is in mixing up "family of varieties" with "moduli space of complex varieties with a fixed underlying real manifold" (or somesuch). In the latter, we want all the varieties to be nonisomorphic. Most families one meets are not of this type.
For a simpler example than yours, consider the conics $xy=t z^2$ in $\mathbb P^2$, $t\in \mathbb A^1$. They're all isomorphic except for $t=0$. I hope it seems less strange that $M_t$ is suddenly different there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails Email with Unsubscribe link
I am working on a Rails 4.2 app that has recurring weekly events that people register for. They will get a reminder email before each event (so weekly). I want a one click unsubscribe link on the email. This seems like a common task but I haven't found a good current solution. Some directions I have seen are to use MessageVerifier which was new to Rails 4.1 and doesn't require saving a token string to compare to in the database. What are the steps to accomplish this. I have a user model and an event model. Emails are sent to registered users who signed up for the recurring event.
A:
Here is the solution I came up with for an unsubscribe link for regular emails sent to subscribers. It uses MessageVerifier.
1. Generate a cryptographic hash of the user.id
In my Events controller I have a send_notice action that sends the email. I'll create a variable for the unsubscribe link and pass it to the mailer.
# app/controller/events_controller.rb
def send_notice
...
@unsubscribe = Rails.application.message_verifier(:unsubscribe).generate(@user.id)
EventMailer.send_notice(@event, @user, @unsubscribe).deliver_later
end
This takes the user id and generates a signed and encoded string variable @unsubscribe. Message verifier turns the user id into an indecipherable string of characters by mixing it with your secret_key_base (found in the file config/secrets.yml), and the name that you give the message (in this case I'm calling it :unsubscribe but it could be any name) as what they call a salt, and running it through an algorithm called SHA1. Make sure your secret_key_base stays secure. Use environmental variables to store the value in production.
In the last line we pass the @unsubscribe variable to the mailer along with @event and @user variables.
2. Add the @unsubscribe hash variable to the mailer
# app/mailers/event_mailer.rb
def send_notice(event, user, unsubscribe)
@event = event
@user = user
@unsubscribe = unsubscribe
mail(to: user.email, subject: "Event Info")
end
3. Put the unsubscribe link in the email
# app/views/events_mailer/send_notice.html.erb
...
<%= link_to "Unsubscribe", settings_unsubscribe_url(id: @unsubscribe) %>.
Notice the (id: @unsubscribe) argument added. This will append the encoded user id to the end of the URL beginning with a ? in what is known as a query param.
4. Add routes
Add a route that takes the user to an unsubscribe page. Then another route for when they submit the unsubscribe.
# config/routes.rb
get 'settings/unsubscribe'
patch 'settings/update'
5. Add a subscription field to the User model
I opted to add a subscription boolean (true/false) field to the user model but you can set it up many different ways. rails g migration AddSubscriptionToUsers subscription:boolean.
6. Controller - Decode the user_id from the URL
I opted to add a settings controller with an unsubscribe and an update action. Generate the controller rails g controller Settings unsubscribe.
When the user clicks on the unsubscribe link in the email it will go to the url and append the encoded User ID to the URL after the question mark as a query param. Here's an example of what the link would look like: http://localhost:3000/settings/unsubscribe?id=BAhpEg%3D%3D--be9f8b9e64e13317bb0901d8725ce746b156b152.
The unsubscribe action will use MessageVerifier to unsign and decode the id param to get the actual user id and use that to find the user and assign it to the @user variable.
# app/controllers/settings_controller.rb
def unsubscribe
user = Rails.application.message_verifier(:unsubscribe).verify(params[:id])
@user = User.find(user)
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
flash[:notice] = 'Subscription Cancelled'
redirect_to root_url
else
flash[:alert] = 'There was a problem'
render :unsubscribe
end
end
private
def user_params
params.require(:user).permit(:subscription)
end
7. Views
Add the unsubscribe page that includes a form to cancel your subscription.
# app/views/settings/unsubscribe.html.erb
<h4>Unsubscribe from Mysite Emails</h4>
<p>By unsubscribing, you will no longer receive email...</p>
<%= form_for(@user, url: settings_update_path(id: @user.id)) do |f| %>
<%= f.hidden_field(:subscription, value: false) %>
<%= f.submit 'Unsubscribe' %>
<%= link_to 'Cancel', root_url %>
<% end %>
There are a number of ways you can set this up. Here I use the form_for helper routed to the settings_update_path with an added argument of id: @user.id. This will append the user id to the URL when sending the form as a query param. The Update action will read it to find the user and update the Subscription field to false.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multithreaded application with database read - each thread unique records
I have a .net application which basically reads about a million of records from database table each time (every 5 minutes), does some processing and updates the table marking the records as processed.
Currently the application runs in single thread taking about top 4K records from DB table, processes it, updates the records, and takes the next.
I'm using dapper with stored procedures. I'm using 4K records for retrieval to avoid DB table locks.
What would be the most optimal way for retrieving records in multiple threads and at the same time ensuring that each thread gets a new 4K records?
My current idea is that i would first just retrieve the ids of the 1M records. Sort the ids by ascending, and split them into 4K batches remembering lowest and highest id in a batch.
Then in each thread i would call another stored procedure which would retrieve full records by specifying the lowest and highest ids of records retrieved, process that and so on.
Is there any better pattern i'm not aware of?
A:
I find this problem interesting partly because I'm attempting to do something similar in principle but also because I haven't seen a super intuitive industry standard solution to it. Yet.
What you are proposing to do would work if you write your SQL query correctly.
Using ROW_NUMBER / BETWEEN it should be achievable.
I'll write and document some other alternatives here along with benefits / caveats.
Parallel processing
I understand that you want to do this in SQL Server, but just as a reference, Oracle implemented this as a keyword which you can query stuff in parallel.
Documentation: https://docs.oracle.com/cd/E11882_01/server.112/e25523/parallel002.htm
SQL implements this differently, you have to explicitly turn it on through a more complex keyword and you have to be on a certain version:
A nice article on this is here: https://www.mssqltips.com/sqlservertip/4939/how-to-force-a-parallel-execution-plan-in-sql-server-2016/
You can combine the parallel processing with SQL CLR integration, which would effectively do what you're trying to do in SQL while SQL manages the data chunks and not you in your threads.
SQL CLR integration
One nice feature that you might look into is executing .net code in SQL server. Documentation here: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/introduction-to-sql-server-clr-integration
This would basically allow you to run C# code in your SQL server - saving you the read / process / write roundtrip. They have improved the continuous integration regarding to this as well - documentation here: https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services?view=sql-server-2017
Reviewing the QoS / getting the logs in case something goes wrong is not really as easy as handling this in a worker-job though unfortunately.
Use a single thread (if you're reading from an external source)
Parallelism is only good for you if certain conditions are met. Below is from Oracle's documentation but it also applies to MSSQL: https://docs.oracle.com/cd/B19306_01/server.102/b14223/usingpe.htm#DWHSG024
Parallel execution improves processing for:
Queries requiring large table scans, joins, or partitioned index scans
Creation of large indexes
Creation of large tables (including materialized views)
Bulk inserts, updates, merges, and deletes
There are also setup / environment requirements
Parallel execution benefits systems with all of the following
characteristics:
Symmetric multiprocessors (SMPs), clusters, or massively parallel
systems
Sufficient I/O bandwidth
Underutilized or intermittently used CPUs (for example, systems where
CPU usage is typically less than 30%)
Sufficient memory to support additional memory-intensive processes,
such as sorts, hashing, and I/O buffers
There are other constraints. When you are using multiple threads to do the operation that you propose, if one of those threads gets killed / failed to do something / throws an exception etc... you will absolutely need to handle that - in a way that you keep until what's the last index that you've processed - so you could retry the rest of the records.
With a single thread that becomes way simpler.
Conclusion
Assuming that the DB is modeled correctly and couldn't be optimized even further I'd say the simplest solution, single thread is the best one. Easier to log and track the errors, easier to implement retry logic and I'd say those far outweigh the benefits you would see from the parallel processing. You might look into parallel processing bit for the batch updates that you'll do to the DB, but unless you're going to have a CLR DLL in the SQL - which you will invoke the methods of it in a parallel fashion, I don't see overcoming benefits. Your system will have to behave a certain way as well at the times that you're running the parallel query for it to be more efficient.
You can of course design your worker-role to be async and not block each record processing. So you'll be still multi-threaded but your querying would happen in a single thread.
Edit to conclusion
After talking to my colleague on this today, it's worth adding that with even with the single thread approach, you'd have to be able to recover from failure, so in principal having multiple threads vs single thread in terms of the requirement of recovery / graceful failure and remembering what you processed doesn't change. How you recover would though, given that you'd have to write more complex code to track your multiple threads and their states.
| {
"pile_set_name": "StackExchange"
} |
Q:
Implementing a counter in VHDL
The following code implements a two digit counter and displays the output on seven segments. As can be seen, in each clock cycle, the value has to be changed but the simulation results doesn't show such thing. To reduce the code size, I only put 0 and 1 in the seven segment driver.
library ieee;
use ieee.std_logic_1164.all;
entity two_digit_counter is
port( clk: in std_logic;
x, y: out std_logic_vector( 6 downto 0 ));
end;
architecture x of two_digit_counter is
begin
process( clk )
variable d1 : integer range 0 to 9 := 0;
variable d2 : integer range 0 to 9 := 0;
begin
if (clk'event and clk = '1') then
if d1 = 9 then
d1 := 0;
d2 := d2 + 1;
elsif d2 = 9 then
d2 := 0;
d1 := 0;
else
d1 := d1 + 1;
end if;
end if;
case d1 is
when 0 => x <= "1111110"; -- 7E
when 1 => x <= "0110000"; -- 30
end case;
case d2 is
when 0 => x <= "1111110";
when 1 => x <= "0110000";
end case;
end process;
end;
A:
Unfortunately your d2 counter doesn't work properly besides the missing assignments to y:
d2 the bottom trace should hold each value for 10 counts of d1 (here shown as ten seconds. The if statements aren't comprehensive and should be changed. d1 is showing up incorrectly as well.
Fix that by nesting the two counter if statements:
process (clk)
variable d1 : integer range 0 to 9 := 0;
variable d2 : integer range 0 to 9 := 0;
begin
if rising_edge(clk) then
-- if d1 = 9 then
-- d1 := 0;
-- d2 := d2 + 1;
-- elsif d2 = 9 then
-- d2 := 0;
-- d1 := 0;
-- else
-- d1 := d1 + 1;
-- end if;
if d1 = 9 then -- nested if statements
d1 := 0;
if d2 = 9 then
d2 := 0;
else
d2 := d2 + 1;
end if;
else
d1 := d1 + 1;
end if;
end if;
case d1 is
when 0 => x <= "1111110"; -- 7E
when 1 => x <= "0110000"; -- 30
when 2 => x <= "1101101"; -- 6D
when 3 => x <= "1111001"; -- 79
when 4 => x <= "0110011"; -- 33
when 5 => x <= "1011011"; -- 5B
when 6 => x <= "1011111"; -- 5F
when 7 => x <= "1110000"; -- 70
when 8 => x <= "1111111"; -- 7F
when 9 => x <= "1111011"; -- 7B
end case;
case d2 is
when 0 => y <= "1111110"; -- WAS assignment to x
when 1 => y <= "0110000"; -- ""
when 2 => y <= "1101101";
when 3 => y <= "1111001";
when 4 => y <= "0110011";
when 5 => y <= "1011011";
when 6 => y <= "1011111";
when 7 => y <= "1110000";
when 8 => y <= "1111111";
when 9 => y <= "1111011";
end case;
end process;
And that produces:
Your question's other answers could have pointed this out if your question had provided a Minimal, Complete and Verifiable example.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a transparent border using CSS in a subclass?
I am trying to create a transparent border around the page number 1 shown below in the image. I've created a subclass span tag so that I could target only that element but it seems not be working. I found some similar question saying to create a space in the CSS but still it is not working.
Like the one below.
HTML (Please ignore jsp tags)
<display:setProperty name="paging.banner.full" value='<span class="pagelinks"> <a href="{1}"> <img src="../images/integration/FastLeft.jpg"/> </a> <a href="{2}"> <img src="../images/integration/SlowLeft.jpg"/> </a> | Page {5} of {6} | <a href="{3}"> <img src="../images/integration/SlowRight.jpg"/> </a> <a href="{4}"> <img src="../images/integration/FastRight.jpg"/> </a></span>'/>
<display:setProperty name="paging.banner.first" value='<span class="pagelinks"> <img src="../images/integration/FastLeft.jpg"/> <img src="../images/integration/SlowLeft.jpg"/> | Page <span class="pageNumberBorder">{5}</span> of {6} | <a href="{3}"> <img src="../images/integration/SlowRight.jpg"/> </a> <a href="{4}"> <img src="../images/integration/FastRight.jpg"/> </a></span>'/>
<display:setProperty name="paging.banner.last" value='<span class="pagelinks"> <a href="{1}"> <img src="../images/integration/FastLeft.jpg"/> </a> <a href="{2}"> <img src="../images/integration/SlowLeft.jpg"/> </a> | Page {5} of {6} | <img src="../images/integration/SlowRight.jpg"/> <img src="../images/integration/FastRight.jpg"/> </span>'/>
CSS
.pagelinks .pageNumberBorder {
border: 1px solid transparent;
}
JS Fiddle
A:
The border in the seccond Picture isnt Transparent. Remove it
.pagelinks .pageNumberBorder {
border: 1px solid;
}
It will work now: JSFiddle
But an a Border around a Page Number suggests an Input Field for changing the Page. If you dont have this implemented i would not use a Border there.
For JSP Pagination look here
| {
"pile_set_name": "StackExchange"
} |
Q:
Orchestrating different bounded contexts, whose responsibility is it?
I have 3 separated services using different databases with REST interfaces:
First service: Information about Customers
Second service: Information about Customer Trades
Third service: Information about Customer Documentation
Problem:
Every customer has a Status that should be evaluated based on his trades and documents.
Which service should be responsible for this evaluation and how should I implement the orchestration between the other services?
A:
If you can, I'd create a 4th service. This way you have a service that returns what you need, avoiding the problem (and over chattiness) of calling 2 services and merging the result set. Otherwise, if you don't have access to be able to create a 4th service, maybe write a proxy service that through one call, calls the other 2 services and uses data caching to cache data where possible, to try help cut down on multiple calls in the future for commonly queried customers.
| {
"pile_set_name": "StackExchange"
} |
Q:
game in Unity3d scaling objects with mouse in c sharp
I'm making a game in unity3d in C#
I would like to be able to make an object smaller by clicking on it with the left mouse button and bigger with right mouse button. The problems with this code are: 1. it doesn't allow to scale down unless its been scaled up 2. if there are multiple objs, they all get affected once they've been clicked on. I've tried a few different ways to do it and I'm guessing it's something to do with the resize bool. Your help is much appreciated
using UnityEngine;
using System.Collections;
public class Scale : MonoBehaviour
{
public GameObject obj;
private float targetScale;
public float maxScale = 10.0f;
public float minScale = 2.0f;
public float shrinkSpeed = 1.0f;
private bool resizing = false;
void OnMouseDown()
{
resizing = true;
}
void Update()
{
if (resizing)
{
if (Input.GetMouseButtonDown(1))
{
targetScale = maxScale;
}
if (Input.GetMouseButtonDown(0))
{
targetScale = minScale;
}
obj.transform.localScale = Vector3.Lerp(obj.transform.localScale, new Vector3(targetScale, targetScale, targetScale), Time.deltaTime*shrinkSpeed);
Debug.Log(obj.transform.localScale);
if (obj.transform.localScale.x == targetScale)
{
resizing = false;
Debug.Log(resizing);
}
}
}
}
A:
using UnityEngine;
using System.Collections;
public class Scale : MonoBehaviour {
public float maxScale = 10.0f;
public float minScale = 2.0f;
public float shrinkSpeed = 1.0f;
private float targetScale;
private Vector3 v3Scale;
void Start() {
v3Scale = transform.localScale;
}
void Update()
{
RaycastHit hit;
Ray ray;
if (Input.GetMouseButtonDown (0)) {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit) && hit.transform == transform) {
targetScale = minScale;
v3Scale = new Vector3(targetScale, targetScale, targetScale);
}
}
if (Input.GetMouseButtonDown (1)) {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit) && hit.transform == transform) {
targetScale = maxScale;
v3Scale = new Vector3(targetScale, targetScale, targetScale);
}
}
transform.localScale = Vector3.Lerp(transform.localScale, v3Scale, Time.deltaTime*shrinkSpeed);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Executar query que concatene parametros (@p) no Firebird
Estou necessitando executar uma query em que o valor a ser concatenado dever ser passado como parâmetro para a consulta.
SELECT t.id || @p || t.nome FROM Test t;
Mas ao executar esta consulta ele retorna o seguinte erro: Dynamic SQL Error.
No MySQL essa mesma ideia funciona da seguinte forma:
SELECT CONCAT(t.id, @p, t.nome) FROM Test t;
Gostaria de saber se há alguma forma de fazer esse tipo de concatenação no Firebird? Pois pelo que percebi o operador || é que causa esse problema quando é utilizado um parâmetro.
Obs¹: É necessário que o valor a ser concatenado como separador seja passado por parâmetro.
Obs²: Eu sei que se eu fizer a concatenação do valor na query isso funciona, ficando a query a ser executada dessa forma: select t.id || 'stringparaseparar' || t.nome from Test t;, mas em meu caso como citado anteriormente é necessário que esse valor seja passado por parâmetro. Ex: set @p = 'stringparaseparar'.
Para esclarecer melhor o motivo dessa necessidade acompanhe essa outra questão que descreve a origem desse problema.
A:
Neste caso você deve fazer um cast do parâmetro para varchar:
SELECT t.id || cast(:p as varchar(10)) || t.nome FROM Test t;
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS Enterprise App: Distribute Over the air : Untrusted Enterprise Developer
I have uploaded my .ipa and manifest.plist to my server (say : https: // www.xxxxxxx . xom/app/). And I created a install page in that server.
In that install html page I have the hyper link to download my app
<a href="itms-services://?action=download-manifest&url=http s: // xxxxxxx.com/ios/manifest.plist">
Download My iOS App
</a>
If I try to install the app through this install page, the app get downloaded and installed. When I tap the app, it shows "untrusted Enterprise developer". And also I cant able to see "Profile and device management" in the setting app
Kindly help me how can i get rid of this "Untrusted Enterprise Developer"
Note:
I have already installed different certificate in my phone. Thats why It is not showing for my phone. But it is working in other iPhones
A:
In general settings of your iphone you could see Device management. Move into the section and trust your enterprise developer account.
| {
"pile_set_name": "StackExchange"
} |
Q:
Alignment off: A gap between inline-block elements with nothing in it
I have a pseudo-grid of inline-block elements to display on my homepage, but there is a gap between two of them which I cannot account for. There is no element, no margin, no br, no nothing that I can find between these elements forcing them apart. The inspect tools for Chrome are just highlighting the container behind when I mouse into the gap. I've tried fiddling with the margins, but I haven't managed to get the top left element (New Booking) to play nicely with the one under it (Membership Plan). The margins of all the other elements are nicely spaced as I want them to be.
Fiddle with the code displaying the problem: https://jsfiddle.net/8b779myb/
Any suggestions?
.home-container {
margin-top: 120px;
width: 800px;
}
.home-container a {
display: inline-block;
color: black;
text-decoration: none;
width: 350px;
height: 100px;
margin: 10px;
padding: 10px;
border: solid 1px #25561B;
background-color: #F9FBF9;
}
.home-container a h2 {
text-align: center;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
margin: 10px;
}
.home-container #new-booking {
height: 242px;
float: left;
}
.home-container #new-booking #car-new-booking {
display: block;
width: 250px;
margin: 10px auto 20px;
}
.home-container #next-booking {} .home-container #all-bookings {} .home-container #membership-plans {} .home-container #browse-bays {}
<div class="home-container">
<a id="new-booking" href="/new-booking">
<img id="car-new-booking" src="{{ url_for('static', filename='images/car-new-booking.png') }}" alt="new-booking-image" />
<h2>New Booking</h2>
</a>
<a id="next-booking">
<h2>Next Booking:</h2> Time, Car, Bay
</a>
<a id="all-bookings" href="/my-bookings">
<h2>View All Bookings</h2>
<br />Bookings to Date: {{ user.num_bookings }}
</a>
<a id="membership-plans">
<h2>Membership Plan:</h2> {{ user.plan }}
</a>
<a id="browse-bays" href="/list-bays">
<h2>Browse Bays</h2>
<br />Home Bay: {{ user.homebay }}
</a>
</div>
A:
Add this;
.home-container #membership-plans {
float:left;
}
It will make the space between the element the same as the rest of your elements. It was just being pushed to the left previously by the other a's you've used. With the added code the element is supposed to be left and that's why it fixed your spacing issue.
https://jsfiddle.net/8b779myb/
| {
"pile_set_name": "StackExchange"
} |
Q:
Generic Repository design
Hi I am attempting to create a generic repository above EF4. Rather than going different Repository & UnitOfWork implementation, I wish to create a repository class which will maintain the state of ObjectContext within itself. My interface looks like:
/// <summary>
/// Contract for base generic repository
/// </summary>
public interface IRepository
{
ActionResult SaveData<TEntity>(TEntity entityObj, bool commitTransaction) where TEntity : IEntity, new();
ActionResult SaveData<TEntity>(ICollection<TEntity> entityObjects, bool commitTransaction) where TEntity : IEntity, new();
ActionResult DeleteData<TEntity>(TEntity entityObj, bool commitTransaction) where TEntity : IEntity, new();
ActionResult DeleteData<TEntity>(ICollection<TEntity> entityObjects, bool commitTransaction) where TEntity : IEntity, new();
ICollection<TEntity> SelectAll<TEntity>() where TEntity : IEntity, new();
ICollection<TEntity> SelectByCondition<TEntity>(Func<TEntity, bool> condition) where TEntity : IEntity, new();
}
ActionResult is class which tells me whether a particular transaction was executed successfully. Now I didn't wanted to maintain the transaction state outside repository. So with every save/delete we can pass the bool value. For the first time, the transaction object can be checked internally and then when I call my last transaction I can send committransaction true, which will call SaveChanges() function.
My question is: Is this approach good by design? What problems can I face?
A:
I see a lot of problems with this implementation.
Explicitly telling each save and delete operation to commit or not is cumbersome and error prone. Just accidentally set one operation to false and your break atomicy. Controlling transactions should not be done at that level.
The SelectByCondition takes a Func<T, bool> predicate, which means the complete database table must be loaded and filtered in memory. A better design would be to use Expression trees.
You say you defined a "repository class which will maintain the state of ObjectContext within itself" but in fact you defined a unit of work :-), because repository is used for one single type of object.
Every method takes the TEntity type argument, while this would be better suited at the interface level, because then you would be following the repository design pattern. Example: IRepository<TEntity>. Such design would make the usage type safe.
Take a look at this article. It describes a (fairly abstract) way of implementing unit of works and repositories while allowing you to LINQ query over them and allowing them to be unit testable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it necessary to pass iterator by const reference
class T
{
unordered_map<string, int> table;
...
void updateA(const unordered_map<string, int>::iterator& iter)
{
iter->second = 100;
}
void updateB(unordered_map<string, int>::iterator iter)
{
iter->second = 100;
}
};
Question> Which function is better(i.e. updateA or updateB)? If you have a better one, please propose.
Thank you
A:
1) First, to answer the question in the title, is it necessary to pass iterators by (const) reference: No. An iterator acts as a proxy for the data item in the container, regardless of whether or not the iterator itself is a copy of or a reference to another iterator. Also in the case when the iterator gets invalidated by some operation performed on the container, whether you maintain it by copy or reference will not make a difference.
2) Second, which of the two options is better.
I'd pass the iterator by copy (i.e. your second option).
The rule of thumb is: Pass by reference if you either want to modify the original variable passed to the function, or if the object you pass is large and copying it involves a major effort.
Neither is the case here: Iterators are small, lightweight objects, and given that you suggested a const-reference, it is also clear that you don't want to make a modification to it that you want reflected in the variable passed to the function.
3) As a third option, I'd like you to consider adding const to your second option:
void updateC(const unordered_map<string,int>::iterator iter)
{
iter->second = 100;
}
This ensures you won't accidentally re-assign iter inside the function, but still allows you to modify the original container item referred to by iter. It also may give the compiler the opportunity for certain optimizations (although in a simple situation like the one in your question, these optimizations might be applied anway).
| {
"pile_set_name": "StackExchange"
} |
Q:
Saving changes made in a webpart
I currently have a webpart with a table which loads documents in itself. Every row has a checkbox control in the first cell. (Default: unchecked)
I am using a second webpart which has a button. If the button is clicked the webpart should load all document rows which are checked. I want the button webpart to show this results.
The first problem i encountered was that once everything was loaded and the
void button_Click(object sender, EventArgs e)
event was fired the second webpart lost the first webpart as a provider. I solved this issue by saving the provider in
Page.Session["provider"]
But this saves the old provider with the old table in which no row is selected. How do i make sure that the changes in the first webpart will be saved when a event from the second webpart is fired? And will be available in the second webpart for use.
A:
If the provider you're talking about is set up using web part connections then a post back shouldn't break that link, but you may be breaking the golden rule regarding web part connections which is:
The provider should be able to provide the data as early as possible
The consumer should use the data as late as possible
This is to avoid the race condition where the consumer tries to use the data before the provider has them.
So your second web part may not be able to use the data in the click event which is very early in the page life cycle. It can the instead set a flag which you can then use in a later event like 'OnPreRender`
| {
"pile_set_name": "StackExchange"
} |
Q:
How does init determine which devices to modprobe?
I'm building a totally custom initramfs for a netbooting project and in the process learning a lot about it, but I'm a little puzzled by the loading of modules.
I know modprobe can be used to load modules, but how does it decide which modules to load?
What I have right now is the initramfs booting up and running a shell in virtual box. But lsmod shows no modules loaded. What I need init to do is load the right modules for the networking so that I can get the networking up.
If I modprobe e1000 I actually get the correct module loaded.
In looking through the Ubuntu boot process I can't see how Ubuntu decides it should load up e1000. I would've thought it'd just modprobe every available network card driver, but it doesn't appear to be doing that.
I'm guessing that UDEV has something to do with it?
A:
I know modprobe can be used to load modules, but how does it decide
which modules to load?
When the kernel needs a feature that is not resident in the kernel, the kernel module daemon kmod1 execs modprobe to load the module in. modprobe is passed a string in one of two forms.
A module name like softdog or ppp.
A more generic identifier like char-major-10-30
So, let me explain what I found in my system rather than pasting from the link.
cat /proc/modules - This command lists what modules are loaded and the list is a pretty huge list.
Now, during the start up of the system, as I had already mentioned, the kmod daemon executes the modprobe to load the modules. We could specify the module to be loaded in either of 2 ways as already discussed. If we have specified a generic identifier, it will look for that entry in /etc/modprobe.conf for alias. So, in my /etc/modprobe.conf, I have an alias as below.
alias eth0 tg3
So, I ran the below command to check what is tg3 in my system.
-bash-3.2$ cat /proc/modules | grep tg3
tg3 139225 0 - Live 0xf8bd1000
Next, modprobe looks through the file /lib/modules/version/modules.dep, to see if other modules must be loaded before the requested module may be loaded. This file is created by depmod -a and contains module dependencies.
Lastly, modprobe uses insmod to first load any prerequisite modules into the kernel, and then the requested module. modprobe directs insmod to /lib/modules/version/[3], the standard directory for modules. insmod is intended to be fairly dumb about the location of modules, whereas modprobe is aware of the default location of modules, knows how to figure out the dependencies and load the modules in the right order.
But how is the new hardware detected?
These rings are created by CPU and not by OS. Any OS kernel operates in Ring 0 which is most privileged level and can communicate directly to the hardware and the CPU. Rings 1 and 2 are commonly used for device drivers. And ring 3 is used for user-space applications (media players, web servers and anything else user can communicate to directly). Device drivers are a “bridge” between user-space applications and hardware.
Linux kernel constantly scans all your computer bus’es for any changes and new hardware. Once any change on any bus is detected magic begins.
The Magic
EXPORT HARDWARE INFORMATION TO USERSPACE (SYSFS)
*NOTIFY USERSPACE TOOLS THAT HARDWARE IS AVAILABLE (UEVENT AND UDEVD)
Yeah, your assumption is correct. udev has something to do with the magic :)*
PROCESS UEVENTS, MATCH THEM AGAINST RULES IN /ETC/UDEV/RULES.D/ AND
POPULATE /DEV DIRECTORY (UDEVD AND UDEV)
LOAD DEVICE DRIVERS (UDEV, MODPROBLE)
NOTIFY USERSPACE APPLICATIONS (THROUGH D-BUS)
Udevd is just a daemon standing in between the Kernel and all the udev
system and perform some important functions (I’ll mention them later).
The udev daemon (udevd) is started at startup then reads and parses
all the rules found in /etc/udev/rules.d/ and keep these rules in
memory (udev database) for further usage by udev. Later udevd start to
listen on the netlink for uevents comming from Kernel driver core.
References
http://www.tldp.org/LDP/lkmpg/2.6/html/x44.html
http://blogas.sysadmin.lt/?p=141
| {
"pile_set_name": "StackExchange"
} |
Q:
How to break or stop ruby_block running in loop cause of "subscribes"
Hi have a recipe where I am trying to check if a service is running and accessible.
So I have a "ruby_block" which checks if service is running if not it "notifies" to "execute" block to start it, once execute block starts the service I need to again check if it running by calling "ruby_block" using "subscribes"
But when service fails to start "ruby_block" goes in unstoppable loop.
Below is recipe which describes the workflow
ruby_block 'check_if_Service_running' do
block do
# ...some logic to check service
# generates a return code 301 if successful or any other value if fails and
# assign it to an attribute check eg. value = return_code
end
notifies :run, 'execute['start_service']', :immediately
subscribes :run,'execute[Start_Service]', :immediately
end
execute 'Start_Service' do
#...code to start the service
action :nothing
not_if { value == 301 }
end
So in this case when Services fails to start even after execute block, ruby_block keeps on running and notify "execute" block and so on
note: when service starts successfully it does show expected behavior
But some times when service does not start it goes in loop
Please help me here to stop "ruby_block" being going in loop cause of subscribes for more than 2 times and stop everything (loop) if service felt to start
Any help will be appreciated!
A:
Make a custom resource instead, you want more explicit control over things than the DSL will give you.
| {
"pile_set_name": "StackExchange"
} |
Q:
! Package amsmath Error: \tag not allowed here
I want to use \tag in my LaTex file at https://www.sharelatex.com/.
For example, I want to do:
If $x \equiv x' \pmod{N}$ and $y \equiv y' \pmod{N}$, then: $xy \equiv x'y' \pmod{N}\tag{Substitution rule}$.
I look at a previous question on this website, \numcases with \tag, and found the answer insufficient for my problem.
I still get the ! Package amsmath Error: \tag not allowed here. error even though I am only importing the following:
\usepackage{textcomp,geometry,graphicx,hyperref,empheq}
I have two questions:
(1) Why does the amsmath package cause an error when \tag is used?
(2) How do I add customized tags to my equations without causing errors?
Thank you for any help you can provide on this!
EDIT:
This is a made-up example as requested:
Now solve for $E[X]$:\newline
\hspace{30pt} $E[X] = 1 + E[X] - p \cdot E[X]$\newline
\hspace{30pt} $0 = 1 - p \cdot E[X]\tag{"xyz"}$\newline
\hspace{30pt} $p \cdot E[X] = 1\tag{"xyy"}$\newline
\hspace{30pt} $E[X] = \frac{1}{p}\tag{"xzy"}$\newline\newline
Note the \tag parts were added in afterwards because they caused errors.
Then I want to say, based on "xyz" and "xyy", I can prove "abc".
A:
You're still using inline math. (La)TeX distinguishes between math that is supposed be written on a line of text, delimited by $ ... $ or \( ... \), and displayed math, which is placed on its own paragraph.
For a single unnumbered, displayed equation you can use \[ ... \], for a numberered equation there is \begin{equation} ... \end{equation}. For sets of equations, or multiline equations, amsmath provides several environment, including align and gather, as well as the starred forms align* and gather* that are unnumbered.
Displayed equations are by default centered, to make them left-aligned add fleqn as an option to amsmath or the document class, e.g. \usepackage[fleqn]{amsmath}.
For more information about amsmath, read the manual. For math typesetting in general, you could take a look at Herbert Voss' Mathmode.
A demonstration with your example:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
Now solve for $E[X]$:
\begin{gather}
E[X] = 1 + E[X] - p \cdot E[X] \\
0 = 1 - p \cdot E[X]\tag{"xyz"} \\
p \cdot E[X] = 1\tag{"xyy"} \\
E[X] = \frac{1}{p}\tag{"xzy"}
\end{gather}
Now solve for $E[X]$:
\begin{align}
E[X] &= 1 + E[X] - p \cdot E[X] \\
0 &= 1 - p \cdot E[X]\tag{"xyz"} \\
p \cdot E[X] &= 1\tag{"xyy"} \\
E[X] &= \frac{1}{p}\tag{"xzy"}
\end{align}
\end{document}
A:
These are still inline equations. You need to use
\[ formula \]
of
\begin{equation}
formula
\end{equation}
to make your formulas display style. Read about it here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Specifying a Client to use with dask.config
The new Dask configuration encourages the use of a named scheduler. This works well for threads, multiprocessing, etc. It also deprecates the use get, which is reasonable. However it does raise the following question.
If one has a few different Dask Distributed Clients, which could be used for a computation, how does one pick a single Client to use within a context?
A:
As of dask.__version__ == 0.18.1 there isn't a solid answer for this. There are two functional answers today, but it's not clear how this will resolve itself in the future.
Keep using get=
with dask.config.set(get=my_preferred_client.get):
...
Use distributed.client.temp_default_client
from distributed.client import temp_default_client
with temp_default_client(my_preferred_client):
...
However I wouldn't expect either of these methods to survive forever. There has been talk of building another protocol around schedulers, but this work has not been done (as of 2018-06-29, as always, you should check documentation for up-to-date answers).
| {
"pile_set_name": "StackExchange"
} |
Q:
Can we use Css Grid frameworks with any design?
What are cons to use Grid based approach? Where everything is in proportions?
Does it all make some restrictness? I'm not talking about non-sematic classes, unneeded css code, table- feel structure.
My question is about to work with fix proportions. in grid based system everything increase and decrease in proportions?
I think we can only use grid based framework if we are doing both thing PSD design and XHTML css coding?
A:
If you are not designing the site, I highly suggest not using a grid or any other tools that would alter the design (proportionately or otherwise). Leave the design to the designer, and handle development, trying to get your finished design as close as possible to the finished mockup from the designer.
Nother irritates me more than when I have handed off a design to a developer, and he "adjusts" it because of some improvement he thought relevant.
If your designer doesn't use a grid, talk to him about it. If he prefers to continue without a grid, then don't force a grid on his design.
| {
"pile_set_name": "StackExchange"
} |
Q:
Solutions/Algorithms to cut an object from image- Android
Folks,
First I'd like you guys to have a look at this app "Image cut": https://play.google.com/store/apps/details?id=jp.zx1234567890.imagecut.
This app very neatly cuts an object of importance from a user defined area
inside an image. You can simple sketch an area around the object you want to
cut out by moving around your finger on the screen. Then the app takes out
the object with a great preciseness.
I am no Image Processing kid, but I can try playing with algorithms.My question is
to all you Image-Processing/Algorithm guys that how should I go about implementing
this. I mean if you can describe how complex problem is this to solve and how should I
approach this problem. I did google around but wasn't able to get a concrete picture
of the possible solution. Since the above mentioned app has achieved this, it seems the problem
should be solvable. I'll highly appreciate any help here.
Thank you!
A:
The problem you are trying to solve is called "semi-supervised image segmentation" (I am sure other names exist). Specifically you are trying to perform a "binary segmentation", labeling the pixels with two classes (foreground and background).
OpenCV contains an algorithm called GrabCut, that would work quite well with the example image in the app. The object that is extracted is very different from the background
GrabCut is very resource hungry, so you need to be smart about using it on a phone (e.g. resize the input image). Maybe you should play around with it on a desktop computer first.
| {
"pile_set_name": "StackExchange"
} |
Q:
Knockout input validation w/ CSS animation
I've created a number-only input validator for my app that's using KnockoutJS. When the user presses an illegal key (letter) I want the target input to flash the CSS animation on each illegal keypress. As it currently stands it just fires the animation once and I'm not sure why.
Example: http://codepen.io/anon/pen/oIamG/
Anyone any ideas?
A:
The problem is that you need to reset you CSS animation. In order to do that, you'd need to remove the animation and then add it again.Move the -webkit-animation properties to the input like
input {
border: 2px solid black;
padding: 8px;
/* 0.2s is used, just to see the effect, the animation needs to be */
-webkit-animation-duration: 0.2s;
-webkit-animation-direction:forwards;
-webkit-animation-timing-function:ease-in-out;
}
@-webkit-keyframes inputValidationBorder {
0% { border: 2px solid red; }
100% { border: 2px solid black; }
}
Then use the following binding:
ko.bindingHandlers.numeric = {
init: function (element, valueAccessor) {
$(element).bind('webkitAnimationEnd', function(){
this.style.webkitAnimationName = '';
});
$(element).on('keydown', function (event) {
// allow backspace, delete, tab, escape, enter/return and period.
// if input is a letter then disable keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
element.style.webkitAnimationName= 'inputValidationBorder';
event.preventDefault();
}
});
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Cancan showing all transactions instead of only authorized
I'm using cancan and I have this in the UserTransactionsController
class UserTransactionsController < ApplicationController
load_and_authorize_resource
def index
@company = Company.find(params[:company_id]
@user_transactions = @company.user_transactions.order("date DESC").all
...
And in ability.rb I have:
can [:read], UserTransaction do |ut|
ut.company_user.user.id == user.id
end
The line ut.company_user.user.id == user.id never seems to get hit. And it is always showing all user transactions, also those for other users.
A:
@rept, when you use the load_and_authorize_resource method, you don't need to create @user_transactions variable, that's what the method does based on the ability.rb file.
you are rewriting the @user_transactions that load_and_authorize_resource creates with the line:
@user_transactions = @company.user_transactions.order("date DESC").all
if you need to fetch users transactions that belong to that particular company you are fetching, you can use the accessible_by scope that cancan provides as:
@user_transactions = @company.user_transactions.accessible_by(current_ability).order("date DESC").all
this should help if you haven't figured it out by now, you can read more on cancan documentation on this topic here: https://github.com/ryanb/cancan/wiki/Fetching-Records
| {
"pile_set_name": "StackExchange"
} |
Q:
A remark on projections in von Neumann algebras
Let $M$ be a von Neumann algebra and $e,f$ be projections in $M$. For a given central projection $z\in M$, is the following true?
$$z(e\vee f)=ze\vee zf$$
A:
Assume $M\subset B(H)$.
I think this is pretty straightforward. Looking at the range subspaces,
$$
z(e\vee f)H=z(\overline{\text{span}}\{eH\cup fH\})=\overline{\text{span}}\{zeH\cup zfH\}=(ze\vee zf)H.
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to model one-to-one relationships in AngularJS with Restangular
I have a companies collection with a country_id field that refers to _idin a countries collection.
Companies as follow:
{
name: "acme",
address: "zossener straße 123",
postalCode: "10961",
city: "berlin",
country_id: "56d58d68ab68b5cf3f72788e"
}
Countries as follow:
{
_id: "56d58d68ab68b5cf3f72788e",
name: "Germany"
}
What I'm trying to do, is to replace the country_id of Companies to Countries.name. So for each company I want the country name, not the country ID. I'm using Restangular. My controller:
// creates a Restangular object of the 'companies' endpoint for later use
var Companies = Restangular.all('companies');
// for later pushing the countries
$scope.allCompanies = [];
// queries companies collection
Companies.getList().then(function(companies) {
$scope.companies = companies;
// iterates each company to get the country name
for (var i = 0; i < $scope.companies.length; i++) {
// prepares temp object to be pushed to $scope.allCompanies
var buffer = {
name: $scope.companies[i].name,
address: $scope.companies[i].address,
postalCode: $scope.companies[i].postalCode,
city: $scope.companies[i].city,
countryId: $scope.companies[i].country_id
};
// queries countries collection passing country_id
var Country = Restangular.one('countries', $scope.companies[i].country_id);
Country.get().then(function(country) {
// sets country name for temp object based on country_id
buffer.country = country.name;
// pushes buffer to $scope.allCompanies
$scope.allCompanies.push(buffer);
});
};
When running, $scope.allCompanies shows all companies with only one country, which is the last country assigned to buffer. I assume that there's something wrong with promises, but not sure. Any help? Thanks in advance.
A:
You can wrap the logic that retrieves the country in a function. This way, the function keeps the correct reference of buffer without being affected by the change of i:
// creates a Restangular object of the 'companies' endpoint for later use
var Companies = Restangular.all('companies');
// for later pushing the countries
$scope.allCompanies = [];
// queries companies collection
Companies.getList().then(function(companies) {
$scope.companies = companies;
function setCountryName(buffer){
// queries countries collection passing country_id
var Country = Restangular.one('countries', buffer.countryId);
Country.get().then(function(country) {
// sets country name for temp object based on country_id
buffer.country = country.name;
});
return buffer;
}
// iterates each company to get the country name
for (var i = 0; i < $scope.companies.length; i++) {
// prepares temp object to be pushed to $scope.allCompanies
var buffer = {
name: $scope.companies[i].name,
address: $scope.companies[i].address,
postalCode: $scope.companies[i].postalCode,
city: $scope.companies[i].city,
countryId: $scope.companies[i].country_id
};
// pushes buffer to $scope.allCompanies
$scope.allCompanies.push(setCountryName(buffer));
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular or Typescript strange behaviour
I'm facing very strange problem for me. I prepared stackblitz demo for this purposes.
What the problem is:
Select Filter Two from selector
Go back to Filter One using the same selector
Type in Filter One input some random values e.g. 123
Press Test 1 button.
The unexpected behavior is that the input field is cleared. Take a look at implementation how onTest1 method is implemented and then how onTest2 method is implemented. When You press Test 2 button then the input from Filter One stays but look at the differences between onTest1 and onTest2 implementation. It's only difference in order. In test1 the value is set to the filter at index 0 and then null is set to the filter at index 1.
In test2 the null is set to the filter at index 1 and then value is set to the filter 0.
Can somebody explain this strange behaviour? I'm facing much bigger problem with this and this is only an iceberg for Stackoverflow help purposes. Currently I'm using Angular 5.2.5 and I'm testing on Macbook OSX 10.12.6 with Google Chrome 67.0.3396.99.
A:
You're using FormControl in a way that's not intended and you've exposed a side effect.
The reason why the bug only appears after you selected Filter Two and then go back to Filter One is because that causes the input to subscribe to the second FormControl without unsubscribing to the original control it was bound to.
So the reason the value changes to blank in Test 1 is because first you set filter[0] to the value, then the input element is updated to show the value, then you set filter[1] to null and then the input element is updated to show null.
You should change your code to use NgModel on the input or use Reactive Forms as it is intended.
Further Explanation
I checked in GitHub and the issue is in FormControlDirective. When the @input is changed It calls setupControl from shared and in there it listens to changes on the valueAccessor to udpate the view. The problem comes because, as far as I can tell, there is no place where some sort of teardown method is called if there was already a value previously set.
Alternative Approach
I don't know why you were using FormControl to begin with, but if the filters must be of type FormControl then the simplest thing you could do is the following.
<input matInput [ngModel]="selectedFilter.control.value"
[ngModelChange]="selectedFilter.control.setValue($event)" />
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS Image Background Position
I want a layout like this. Please take a look the image
As you can see, i have top bar and footer bar. Since footer bar is solid bar, i can just use div and fill the solid color.
But for the top bar, I have to use image as an background inside div. And here is the image of top bar.
What I want to do is, the black square box (logo) should be fixed at the right corner and the bar should repeat according to the width of the screen.
Please kindly provide me the css for the top bar. Thank you.
Edit: Sorry about my careless. Here is my code.
<html>
<head>
</head>
<body style="margin:0px">
<div style="width:100%; height:100%">
<div style="position:absolute; top:10px; background:url(bglogo.png); width:100%; height:100px"></div>
<div style="position:absolute; bottom:0px; width:100%; height:20px; background:#000"></div>
</div>
</body>
</html>
A:
Don't use an image for the entire top bar. Handle it in exactly the same way as the bottom bar, but with a few additions.
You should do it as I'm suggesting because the logo should be a clickable link.
The HTML should be similar to this:
<div id="topBar">
<a id="logo" href="/"><img src="logo.png" alt="whatever" /></a>
</div>
With this CSS:
#topBar {
position: relative;
}
#logo {
position: absolute;
top: -10px;
right: 0
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ios - local notification not updating badge number when application is closed
I have noticed that when a local notification is being received in an ios device, the notification appears in the Notification Center but the app badge number is not updated when the app is closed.
I need to touch the notification in the Notification Center for the local push message to be transferred to the app.
Is this the normal behavior? Can this be solved by using remote push notifications?
A:
You can utilize the applicationIconBadgeNumber parameter in a UILocalNotification object.
Basically:
localNotificationObject.applicationIconBadgeNumber++;
Example:
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [[NSDate date] dateByAddingTimeInterval:20];
localNotification.alertBody = @"Some Alert";
//the following line is important to set badge number
localNotification.applicationIconBadgeNumber++;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
But the issue with this is that the badge number doesn't increment on subsequent (multiple) local notifications (there's a scenario here but for simplicity sake, lets just say the badge stays 1 even after 2 or more, back to back, local notifications).
In this case, Yes... Push Notification seems to be the way to go
(but be aware that Push Notifications aren't always reliable... check: link)
Well... to use Push Notifications for proper badge number updates, you should know that you can send a badge count in the Push Notification's payload.
When this push notification is received, the badge count is changed by iOS to the badge count specified in the Push Notification (& the app need not be open for this).
Example (continued):
Set applicationIconBadgeNumber to 0 as it helps in certain scenarios (optional)
- (void)applicationWillResignActive:(UIApplication *)application {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
Extra:
You can also manually set the badge number when you terminate/close or resign the application.
Generally... in any or all of the following methods:
-applicationWillResignActive
-applicationDidEnterBackground
-applicationWillTerminate (set badgeNumber when app closes)
Example:
- (void)applicationWillResignActive:(UIApplication *)application {
//Called when the application is about to move from active to inactive state.
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:[[[UIApplication sharedApplication] scheduledLocalNotifications] count]];
//...
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate.
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:[[[UIApplication sharedApplication] scheduledLocalNotifications] count]];
//...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
MessageDigest ArrayIndexOutOfBoundsException
I use MessageDigest to calculate the md5 signature in my project, but during the performance test it throws an ArrayIndexOutOfBoundsException.
I have found a few posts that suggest this is because MessageDigest is a singleton and not thread safe. Does anyone know how I can get around this problem, or if there is an equivalent MessageDigest class that is thread safe?
A:
somebody says that this is beacause MessageDigest is singleton
That would be your MessageDigest object. Not the class itself. MessageDigest.getInstance() always returns a new instance: see the Javadoc.
and not thread save.
Thread safe.
Now, anyone knows how to solve this problem
Don't share your MessageDigest instance among multiple threads. Don't even make it a class member, make it a local variable in the method(s) that call it.
| {
"pile_set_name": "StackExchange"
} |
Q:
didRecieveMemoryWarning in ARC (iOS / Obj-C)
I have an iOS (Obj-C) project that uses ARC (Automatic Reference Counting). According to Apple Documentation, and pure experimentation, you cannot have statements such as:
[UIThingamabob release];
This was previously the way to release items after being allocated or retained. Now I do know that you have to manage how IB objects are created in the
@property (nonatomic, retain) IBOutlet ...
portion of your header file.
I've been using the above statement as it is (with the nonatomic and retain (or strong- what's the difference anyway, how are they used?) properties) for all of my IB items. When I test on an iOS Device, I'll randomly get a UIAlertView (that I created for debugging purposes) that only displays when the didRecieveMemoryWarning event is fired.
Some of my BETA testers are bombarded with these views nonstop until they manage to quit the app.
My question is, what do I put in the didRecieveMemoryWarning event since I can't release objects? If there isn't anything to put there, then are these errors occurring due to the way I create my objects with the @property function?
A:
You should use @property (nonatomic, weak) IBOutlet... for all of your IBOutlets. If you use strong, the outlet is retained by the view controller and by it's superview. When the view disappears, the view controller still has a reference to that outlet which is no longer visible. You could set the outlet property to nil in -viewDidUnload or by using weak setting the pointer to nil is done automatically when the view disappears.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to update uploaded image using codeigniter. Must be from database as well as from the directory
I am new to codeigniter. I have gone through many posts uploaded. I became able to update image link from the database and the new image which I selected get uploaded successfully but I am not being able to delete (unlink) the older image at the same time.
Here is my controller:
public function admin_profile_image()
{
if($this->session->userdata('login_answer') != null){
if('ADMIN'==$this->session->userdata('forredirect'))
{
$config['upload_path'] = './assets/uploads/profile_uploads/';
$config['allowed_types'] = 'jpeg|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->upload->initialize($config);
if($this->upload->do_upload('updateprofileimg'))
{
$image_data = $this->upload->data();
$profile_img = base_url("assets/uploads/profile_uploads/".$image_data['file_name']);
$data = array(
'profile_photo'=>$profile_img
);
$this->load->model('update/updateAdmin');
if(!$this->updateAdmin->updateAdminImg($data))
{
$this->session->set_flashdata('profile_img_update_success','Profile photo updated successfully.');
redirect('update/admin_profile');
}
else
{
return FALSE;
}
}
else{
$this->session->set_flashdata('profile_img_update_unsuccess','Profile photo could not updated. Please try again.');
redirect('update/admin_profile');
}
}
}else{
return redirect('search');
}
}
Here is model:
public function updateAdminImg($data)
{
$this->db->set($data);
$this->db->where('login_id',$this->session->userdata('login_id'));
unlink($data);
$this->db->update('admin',$data);
}
Here is the view:
<?php echo form_open_multipart('update/admin_profile_image');?>
<div class="row">
<div class="col-lg-6">
<label>Browse and Choose New Profile Image (Image size, Image dimension):
</label>
<div class="form-group" style="line-height:33px;">
<input type="file" name="updateprofileimg" class="btn-primary btn-block">
</div>
</div>
<label class="col-lg-6 text-danger">
<?php if(isset($error)){ echo $error; } ?>
</label>
</div>
<?php echo form_submit(['type'=>'submit','class'=>'btn btn-primary','value'=>' Update']); ?>
<?php echo form_reset(['type'=>'reset','class'=>'btn btn-warning','value'=>' Reset ']); ?>
<?php echo form_close(); ?>
A:
Controller
public function admin_profile_image()
{
$this->load->model('update/updateAdmin');
if($this->session->userdata('login_answer') != null){
if('ADMIN'==$this->session->userdata('forredirect'))
{
//First, Get old image from database
$old_image = $this->updateAdmin->get_old_image($this->session->userdata('login_id')); //Required parameter for image
$image_with_path = 'file-path/'.$old_image;
if(file_exists($image_with_path)){
unlink($image_with_path);
}
$config['upload_path'] = FCPATH.'assets/uploads/profile_uploads'; //If your file uploading folder outside the application folder
//$config['upload_path'] = APPPATH.'assets/uploads/profile_uploads'; //If your file uploading folder inside the application folder
$config['allowed_types'] = 'jpeg|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if($this->upload->do_upload('updateprofileimg'))
{
$image_data = $this->upload->data();
$profile_img = base_url("assets/uploads/profile_uploads/".$image_data['file_name']);
$data = array(
'profile_photo'=>$profile_img
);
if(!$this->updateAdmin->updateAdminImg($data))
{
$this->session->set_flashdata('profile_img_update_success','Profile photo updated successfully.');
redirect('update/admin_profile');
}
else
{
return true;
}
}
else{
$this->session->set_flashdata('profile_img_update_unsuccess',$this->upload->display_errors());
redirect('update/admin_profile');
}
}
}else{
return redirect('search');
}
}
Model
public function updateAdminImg($data)
{
$this->db->set($data);
$this->db->where('login_id',$this->session->userdata('login_id'));
$this->db->update('admin');
}
public function get_old_image($login_id){
return $this->db->get_where('admin', ['login_id' => $login_id])->row()->profile_photo;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Query To Return Column Name And Date
I have a SQL Table that houses the date that a student was assigned and completes one of three exams. I am in need of a way to query the table and return the column name of the exam the student needs to take and the date it was assigned.
For example, these are my desired query results:
Joe - exam1date - 01-30-2018
James - exam2date - 03-02-2018
Javier - exam3date - 04-01-2018
And this is DDL for my table:
Create Table Information
(
fname varchar(100)
,exam1date date
,exam1complete date
,exam2date date
,exam2complete date
,exam3date date
,exam3complete date
)
Insert Into Information (fname, exam1date)
Values ('joe', '2018-01-30')
INSERT INTO Information (fname, exam1date, exam1complete, exam2date)
Values ('james', '2018-02-14', '2018-02-21', '2018-03-02')
INSERT INTO Information (fname, exam1date, exam1complete, exam2date, exam2complete, exam3date)
VALUES ('javier', '2018-01-01', '2018-01-14', '2018-03-01', '2018-03-12', '2018-04-01')
What would a query be that can returned my desired result set from the above table schema?
A:
I guessing that you need the examdate of the last exam that does not have a complete date?
Query
SELECT fname,
CASE
WHEN exam1complete IS NULL THEN 'exam1date'
WHEN exam2complete IS NULL THEN 'exam2date '
ELSE 'exam3date' END AS columnname,
CASE
WHEN exam1complete IS NULL then exam1date
WHEN exam2complete IS NULL then exam2date
ELSE exam3date END AS examdate
FROM Information;
Result
fname columnname examdate
joe exam1date 2018-01-30
james exam2date 2018-03-02
javier exam3date 2018-04-01
| {
"pile_set_name": "StackExchange"
} |
Q:
Electron how apply style on primary window when second window closes?
I have a preferences window where I define colors, then I trigger an alert when window closes
window.on('close', function () {
window = null
writePreferences(inputs)
win.webContents.send("PREFERENCE_SAVED", 'saved')
})
Then on my front-end js I have this
ipcRenderer.on(PREFERENCE_SAVED, (event , data) => {
document.querySelector('html').style.setProperty("--background", "orange")
})
A:
The syntax for sending and receiving messages is:
To send from the window to the renderer:
win.webContents.send('asynchronous-message', 'message');
To receive the message in renderer:
ipcRenderer.on('asynchronous-message', function (event, message) {
// Do your background color changing here.
});
So your code would become something like this:
Main:
window.on('close', function () {
window = null
writePreferences(inputs)
win.webContents.send('asynchronous-message', "PREFERENCE_SAVED");
})
Renderer:
ipcRenderer.on('asynchronous-message', function (event, message) {
if (message == 'PREFERENCE_SAVED') {
document.querySelector('html').style.setProperty("--background", "orange");
}
});
ipcRenderer.on Docs
win.webContents.send Docs
| {
"pile_set_name": "StackExchange"
} |
Q:
Immediately scale up Kubernetes Statefulset/Deployment to full capacity
currently we scaled one of our statefulsets to have 11 replicas. Our current updateStrategy is
updateStrategy:
type: RollingUpdate
If we deploy the statefulset from scratch, Kubernetes starts them one after another. To start one replica it needs around 5 Minutes. So in total we wait 55 Minutes just to fill up the capacity.
Is there a way to fill up the capacity at once when starting from scratch? So that all 11 replicas will start simultaneously?
Upgrades on the already existing statefulset should be handled via RollingUpdate due to failure safety.
Best wishes,
Stephan
A:
we found the answer hiding deep in the documentation:
https://kubernetes.io/docs/tutorials/stateful-application/basic-stateful-set/#parallel-pod-management
https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#pod-management-policies
Pod Management Policies
In Kubernetes 1.7 and later, StatefulSet allows you to relax its ordering guarantees while preserving its uniqueness and identity guarantees via its .spec.podManagementPolicy field.
OrderedReady Pod Management
OrderedReady pod management is the default for StatefulSets. It implements the behavior described above.
Parallel Pod Management
Parallel pod management tells the StatefulSet controller to launch or terminate all Pods in parallel, and to not wait for Pods to become Running and Ready or completely terminated prior to launching or terminating another Pod. This option only affects the behavior for scaling operations. Updates are not affected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filter in grid with custom renderer
I have a problem with filter in my module in admin grid.
My problem is:
Filter for columns with custom renderer not working.
public function _prepareColumns()
{
$this->addColumn('entity_id', array(
'header' => 'ID',
'index' => 'entity_id',
'width' => '30px'
));
$this->addColumn('author', array(
'header' => 'Author',
'index' => 'author',
'renderer' => 'Test_Block_Adminhtml_Vj_Renderer_Author'
));
renderer is
class Test_Block_Adminhtml_Vj_Renderer_Author extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object $row)
{
$value = $row->getData($this->getColumn()->getIndex());
$autor = Mage::getModel('test/test')->load($value);
return ($author->getName() . ' ' . $author->getSurname());
}
}
Author in grid is showing fine for example 'George Bush', but if i try write to filter (for example 'Bu') filter return zero row. :-/
Any idea?
Thx.
A:
This article may help... http://www.atwix.com/magento/grid-filter-for-columns/
On your addColumn() call for the custom field, add something like...
'filter_condition_callback' => array($this, '_myCustomFilter'),
Then add the filter method (changing the "where()" as needed)...
protected function _myCustomFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$this->getCollection()->getSelect()->where(
"my_field like ?"
, "%$value%");
return $this;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Selecting only even numbers in php output
I am trying to select and display only the even number in a separate output from this below
function toms($c,$first = 0,$second = 1)
{
$toms = [$first,$second];
for($i=1;$i<$c;$i++)
{
$toms[] = $toms[$i]+$toms[$i-1];
}
return $toms;
}
echo "<pre>";
print_r(toms(33));
?>
currently this outputs
array
(
[0] => 0
[1] => 1
[2] => 1
[3] => 2
[4] => 3
[5] => 5
[6] => 8
[7] => 13
[8] => 21
[9] => 34
[10] => 55
[11] => 89
[12] => 144
[13] => 233
[14] => 377
[15] => 610
[16] => 987
[17] => 1597
[18] => 2584
[19] => 4181
[20] => 6765
[21] => 10946
[22] => 17711
[23] => 28657
[24] => 46368
[25] => 75025
[26] => 121393
[27] => 196418
[28] => 317811
[29] => 514229
[30] => 832040
[31] => 1346269
[32] => 2178309
[33] => 3524578
)
Anyone know how I can display only the even numbers returned, so I would want to have 2, 8, 34 and so on
thank you
A:
You can use array_filter
print_r(array_filter(toms(33), function($number){
return $number % 2 == 0;
}));
Or if you want to filter out 0:
print_r(array_filter(toms(33), function($number){
return $number != 0 && $number % 2 == 0;
}));
A bit more readable:
$isEvenNumber = function($number) {
return $number % 2 == 0;
}
$numbers = toms(33);
$filtered_numbers = array_filter($numbers, $isEvenNumber);
var_dump($filtered_numbers);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access subclass static methods from Class token?
The concept I'm having trouble with is how can I pass a token (such as Apple.class) into a method, and then get access to the subclass's static methods so I can retrieve generic information about the subclass?(in this case a generic image of an apple)
Here's some Java-like psudocode:
abstract class Food {
}
class Apple extends Food {
static Image getImage(){
return (generic image of an apple);
}
}
class Onion extends Food {
static Image getImage(){
return (generic image of an onion);
}
}
void arrayManager(Class<? extends Food> foodToken){
useImage(foodToken.getImage()); // <-- can't access static methods from Class token
storeType(foodToken);
}
//... executing code ...
arrayManager(Apple.class);
arrayManager(Onion.class);
The executing code needs to tell the arrayManager() what kinds of foods it wants stored. The arrayManager() method displays a simple generic image and stores the token for later reference. But I can't find a way to get a generic image of the specific subclass.
If the arrayManager() method wanted to instantiate the passed in token, then no problem, I could just:
foodToken.newInstance();
And then I could call a non-static version of GetImage().
But it seems absurd to have to instantiate a Food type object (either before the arrayManager() call or afterward) when I just want a static method to give me a generic image not associated with a specific Apple instance. If I store the token and instantiate temporarily to retrieve the image, I have to instantiate and then throw the object away every time I need something from a static method of that subclass. If I instantiate and store the actual object instead of the token, I'm faced with storing thousands of identical objects just to get generic information.
I've been struggling with versions of this issue for weeks. So far I haven't found anything that seems to include the issue of the token having to pass into a method. If my methodology is all wet I'm open to other ways of going about things. I'm hoping I don't have to use a bulky piece of reflection code.
Thank you for reading.
A:
You can do this with reflection: (assuming you're in the same package)
Method m = foodToken.getMethod("getImage");
Image image = (Image) m.invoke(null);
If you're outside of the package, the methods may not be accessible (as defined in your example, at least), but you can use reflection to fix that, too. Use getDeclaredMethod instead of getMethod in that case, and call setAccessible(true) to make it accessible to the caller.
| {
"pile_set_name": "StackExchange"
} |
Q:
Syntax error when killing process tree through Python
I am trying to kill a process tree using this shell command:
kill -TERM -- -3333
so in python I use subprocess:
subprocess.call(['kill', '-TERM', '--', '-3333'])
the process is terminated as expected but I get this message:
ERROR: garbage process ID "--".
Usage:
kill pid ... Send SIGTERM to every process listed.
kill signal pid ... Send a signal to every process listed.
kill -s signal pid ... Send a signal to every process listed.
kill -l List all signal names.
kill -L List all signal names in a nice table.
kill -l signal Convert between signal numbers and names.
Why do I get this message and what am I doing wrong?
I am using Python 2.6.5 on Ubuntu 10.04.
A:
You are passing the kill command an argument it doesn't recognise. You could simply drop the --:
subprocess.call(['kill', '-TERM', '-3333'])
You probably should be passing in the PID without a dash as well, if -- is not supported, neither will a negative PID; at which point you'd be signalling just the single process.
Note that you are not executing this through a shell, while your shell probably has its own kill command implementation, Python instructs the OS to find the first kill binary executable on the path instead. The shell built-in may accept -- but that's not the command you are executing here.
If you must use the shell built-in, then you'll have to set shell=True and pass in a string command line:
subprocess.call('kill -TERM -- -3333', shell=True)
This uses /bin/sh; you can set a different shell to run the command through with the executable argument:
subprocess.call('kill -TERM -- -3333', shell=True, executable='/bin/bash')
Last but not least, you may not need the kill command at all. Python can send signals directly with the os.kill() function:
import os, signal
os.kill(3333, signal.SIGTERM)
and the os.killpg() function can send a signal to a process group:
import os, signal
os.killpg(3333, signal.SIGTERM)
| {
"pile_set_name": "StackExchange"
} |
Q:
Update Jenkins which is currently running as a Linux service
How do I update jenkins from a existing jenkins install running as a Linux service without loosing any jobs or config?
A:
First, you need to find where your jenkins.war file is installed:
locate jenkins.war
On my Centos machine, it's here: /usr/share/jenkins/jenkins.war
Stop the Jenkins service:
service jenkins stop
Next, you can backup the existing jenkins.war file:
cd /usr/share/jenkins
mv jenkins.war jenkins-1.586.war
And to finish, please copy the new jenkins.war file in the same location:
cp jenkins.war /usr/share/jenkins/jenkins.war
Restart the Jenkins service:
service jenkins start
It should work and you should retrieve your Jenkins configuration (which is stored in your Jenkins home folder).
| {
"pile_set_name": "StackExchange"
} |
Q:
iphone app submitting fails
I'm attempting to submit my app,
and I'm getting no record found for the app on itunesconnect...
I have added the app on itunesconnect,
and have set up all the app ID, CRS, etc.
Why could it be?
Please help me out...
A:
What state your application has?
To be able to upload a binary application must have "Waiting For Upload" status - you need to push "Ready to Upload Binary" on application page in itunes connect.
| {
"pile_set_name": "StackExchange"
} |
Q:
LinQtoExcel using asp fileupload
im having problems with this function. so basically a user will upload an excel file .xls (2003 version) then once the import button is clicked it will read the excel file and import it into the sql database.
here is my code
protected void btnImport_Click(object sender, EventArgs e)
{
Business.Student student = new Business.Student();
int errorCount = 0;
int successCount = 0;
string successTotal;
int missinglastname = 0;
int missingfirstname = 0;
int missingmiddlename = 0;
if (filebiometrics.HasFile == false)
{
}
else
{
string pathToExcelFile = filebiometrics.FileName;
var excelFile = new ExcelQueryFactory(pathToExcelFile);
IEnumerable<string> worksheetnames = excelFile.GetWorksheetNames();
string worksheetName = excelFile.GetWorksheetNames().ToArray()[0];
var import = from a in excelFile.Worksheet<Business.Student.StudentList>(worksheetName) select a;
//var emptyfield = excelFile.Worksheet<Business.Employees.EmployeeImport>().Where(x => x.Surname != null).ToList();
excelFile.AddMapping<Business.Student.StudentList>(x => x.studentnumber, "Student Number");
excelFile.AddMapping<Business.Student.StudentList>(x => x.firstname, "Firstname");
excelFile.AddMapping<Business.Student.StudentList>(x => x.lastname, "Lastname");
excelFile.AddMapping<Business.Student.StudentList>(x => x.middlename, "Middlename");
string missing = "Missing!";
foreach (var a in import)
{
if (a.studentnumber == 0)
{
}
if (a.lastname == null)
{
a.lastname = missing;
missinglastname = missinglastname + 1;
}
if (a.firstname == "")
{
a.firstname = missing;
missingfirstname = missingfirstname + 1;
}
if (a.middlename == null)
{
missingmiddlename = missingmiddlename + 1;
}
else if (student.CheckExistingStudentNumber(a.studentnumber))
{
errorCount = errorCount + 1;
}
else
{
student.Create(a.studentnumber, a.firstname, a.lastname, a.middlename);
successCount = successCount + 1;
successTotal = "Total imported record: " + successCount.ToString();
}
}
txtLog.InnerText = "Total duplicate record: " + errorCount.ToString() +
Environment.NewLine +
"Total missing data on Firstname column: " + missingfirstname.ToString() +
Environment.NewLine +
"Total missing data on Lastname column: " + missinglastname.ToString() +
Environment.NewLine +
"Total missing data on middlename column: " + missingmiddlename.ToString() +
Environment.NewLine +
Environment.NewLine +
"Total imported record: " + successCount.ToString();
filebiometrics.Attributes.Clear();
}
}
im always getting this error
the error is in this line 'IEnumerable worksheetnames = excelFile.GetWorksheetNames();'
can somebody help me with this?
A:
Your error message is self explanatory. Error is at this line:-
var excelFile = new ExcelQueryFactory(pathToExcelFile);
ExcelQueryFactory expects the full file path but you are just passing the excel file name using string pathToExcelFile = filebiometrics.FileName; and obviously it is not able to read the file.
You need to read the excel file which user is uploading and save it to the server and then read it like this:-
string filename = Path.GetFileName(filebiometrics.FileName);
filebiometrics.SaveAs(Server.MapPath("~/") + filename);
var excelFile = new ExcelQueryFactory(Server.MapPath("~/") + filename);
| {
"pile_set_name": "StackExchange"
} |
Q:
TaxonomyClientService.GetTermSets 400 bad request
What is wrong with this SOAP request? I keep on getting 400 bad request error.
<S:Body>
<GetTermSets xmlns="http://schemas.microsoft.com/sharepoint/taxonomy/soap/">
<sharedServiceIds>
<termStoreIds>
<termStoreId>27a0a321-083f-4688-8b6e-d86b7ab42de9</termStoreId>
</termStoreIds>
</sharedServiceIds>
<termSetIds>
<termSetIds><termSetId>cb1b9444-159d-48c3-b9a7-19ebd612e796</termSetId></termSetIds>
</termSetIds>
<lcid>1033</lcid>
<clientTimeStamps>
<timeStamps><timeStamp>2304823424</timeStamp></timeStamps>
</clientTimeStamps>
<clientVersions><versions><version>1</version></versions></clientVersions>
</GetTermSets>
</S:Body>
A:
I was struggling with this for a long time as well, and had extrapolated the same request from all the examples that I could find online.
But I managed to get it working by looking up "MS-EMMWS" (my working example below)
MS-EMMWS - Protocol Examples
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetTermSets xmlns="http://schemas.microsoft.com/sharepoint/taxonomy/soap/">
<sharedServiceIds><sspIds><sspId>0d18c636-63d4-452b-b094-6de97ee5159d</sspId></sspIds>
</sharedServiceIds><termSetIds><termSetIds><termSetId>48508451-17d5-4bdb-b1c9-7f096f680352</termSetId></termSetIds></termSetIds><lcid>1033</lcid>
<clientTimeStamps><dateTimes><dateTime>1900-01-01T00:00:00</dateTime></dateTimes></clientTimeStamps>
<clientVersions><versions><version>0</version></versions></clientVersions></GetTermSets>
</soap:Body>
</soap:Envelope>
| {
"pile_set_name": "StackExchange"
} |
Q:
Group authorization using Azure AD ADAL.JS - NodeJS, ReactJS
I've seen that when using ADAL.js, you cannot get group membership claims due to some URL limitation.
https://github.com/AzureAD/azure-activedirectory-library-for-js/issues/239
I am using oauth-bearer authentication from the frontend, that is, the frontend triggers a login via the AD login page.
The client then pass the access token to the backend.
What I want to do:
I want to filter some data in my backend endpoints depending on group membership.
e.g. if you are a member of group "London" in AD, you should only see things related to London in our DB queries.
Super simple using e.g. Okta or Auth0, not so much with Azure AD.
I also want to accomplish the same thing on the frontend, that is, show and hide menu items depending on group membership.
(All access is still checked on backend also)
The documentation is sparse and not very helpful.
"You should use Graph API".
How?, how do I talk to graph api using the token I get from the frontend?
This is the setup I have for my Node+Express endpoints:
app.use(
"/contacts",
passport.authenticate("oauth-bearer", { session: true }),
contacts
);
How, where and when should I call the graph API here?
Our system is super small so I don't mind using session state.
Can I fetch this information when the user logs in?
How should that flow be? client logs in, once logged in, call the backend and request the groups?
A:
When you get the access token from Azure AD after the user logged in, you can find the group membership of the user by doing a GET request to https://graph.microsoft.com/v1.0/me/memberOf with the access token like this:
function getGroupsOfUser(accessToken, callback) {
request
.get('https://graph.microsoft.com/v1.0/me/memberOf')
.set('Authorization', 'Bearer ' + accessToken)
.end((err, res) => {
callback(err, res);
});
}
This sample assumes you are using the NPM package superagent.
And the required permissions to call this API are listed here.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I tell which gummi enemy encounters have been completed?
When exploring the world map in a gummi ship, there's enemies that can be fought. I've already defeated most enemies in Straight Way Galaxy, so I am trying to find the ones I haven't encountered yet.
Is there a way to tell if I have completed an enemy encounter?
A:
To add to Faxter's answer, you can add a marker to already completed missions. So if you see an enemy, with the help of the starts + the markers you can realise if you already completed it. You don't even have to leave the menu, as the marker shows even while you are paused.
I know it's not much, but it really seems like the developers just totally missed that feature.
A:
I have encountered the same problem and here is what I found out so far:
When travelling in the inter-world space with your ship, there is no sure-fire way to tell if you have already completed a mission that you see in front of you or on the mini-map with the Heartless-symbol.
You can however look at your Gummi mission list by opening your menu and selecting Information > Gummi Records. It will show you the star-rankings of all missions in your current area. That way you can at least see which kind of star-rating the missions have that you still need to find.
For example:
In your Gummi mission list, you can tell that you still need a mission that is rated with three red stars. Flying around space, you now know that you can skip anything that has a different star rating than the one you are looking for (e.g. five red stars or three orange stars).
I know that is not very satisfying, but as far as I can tell - there is nothing better the game is offering you.
Last tip:
Gummi missions appear to spawn in the same location every time. So if you keep track of where you already where, you should be able to tell if you already did a certain mission based on their location.
| {
"pile_set_name": "StackExchange"
} |
Q:
Data.frame para ts dados diários no R
Não estou conseguindo transformar a cotação diária do câmbio para ts.
dados <- read.table("C:/Econometria/Cambio/cambio.txt", header=T, dec=",")
ts(dados), start=c(1994,01,01), freq=1) # Quando faço isso ele muda os dados, acaba aparecendo valores que não estão no arquivo
Também usei xts(dados, as.Date(dados, format='%m/%d/%Y')
Alguém poderia me ajudar?
str(dados)
'data.frame': 5103 obs. of 1 variable:
$ X1: Factor w/ 4142 levels "-","0,829","0,831",..: 86 81 70 65 74 77 74 74 77 83 ...
dput(dados)
... , "3,9245", "3,9552"), class = "factor")), .Names = "X1", class = "data.frame", row.names = c(NA,
-5103L))
A:
Diogo, o problema é que os seus valores não estão como número, e sim como factor (fatores).
Isso está ocorrendo na hora de ler a base de dados porque o R está interpretando o seu dado como texto (e não como número) e transformando em factor.
Se você observar a informação que você deu com o str, o primeiro level é um traço "-". Provavelmente é isso o que está causando o problema. Sugiro você substituir esses valores por zero antes de proceder novamente à leitura.
PS: Por curiosidade, se você quiser entender porque fatores transformados em números viram "outros" números, sugiro ler essa pergunta: Erro ao converter números. Como converter fatores para números? .
| {
"pile_set_name": "StackExchange"
} |
Q:
Do photons interact or not directly?
All I am asking about is photon (EM wavepacket) photon (EM wavepacket) interaction.
I have read this question:
If photon-photon interactions are impossible, how are higher harmonics generated?
where Danielshank says:
As far as we know photons do not directly interact with each other.
Yet another way to say this is that if a photon is moving along, the existence of a second photon has absolutely no influence over the first photon's path.
Photon-Photon Interactions
where JEB says:
Regarding the photons zinging around in front of you: as particles, they do interact in photon-photon scattering with a negligible cross section in the visible. As electromagnetic waves, their field strengths add linearly, which is the mechanism for con/de-structive interference; however, that only occurs when the waves are coherent. These waves are incoherent and "pass though" one-and-other.
Why do two-photon interactions only occur at extremely high energies?
So one of them says they do not directly interact, the other one says they do interact. This is a contradiction.
What I do not understand mostly, is that photons do not interact directly, two crossing photons will not scatter off (only on the second order).
Question:
Do photons interact or not directly?
A:
At "tree level," the photon interacts with particles that have electric charge. Since photons don't themselves carry electric charge, there aren't first-order photon-photon interactions.
At higher energies, or in more precise measurements, higher-order corrections make this simple statement less accurate. Some fraction of the wavefunction for a free photon includes virtual particle-antiparticle pairs (a phenomenon known as vacuum polarization), and those virtual charged particles may interact with other photons in the electromagnetic field. This is the lowest-order contribution to photon-photon scattering.
A:
According to non-relativistic QM and classical EM alone, there should not be any photon-photon scattering. The reason for this is that neither non-relativistic QM nor classical EM provide any cause-and-effect mechanism by which photons would scatter off of other photons. Simply put, the photons do not have any charge, therefore no coulombic repulsion or attraction against other photons which do not have any charge either. With regard to electron-photon scattering, at least the electron can provide some charge that leads to scattering in some way.
The quote that you mention above that seems to indicate that photon-photon scattering is impossible is ignoring additional information provided by Quantum Electrodynamics.
Quantum Electrodynamics provides some rather obscure ways that photon-photon scattering can occur. I won't drone on with the highly technical details about how this process happens, as they justify an entire discussion of their own.
So to answer your question more directly, yes it is theoretically possible, although ordinary QM and classical EM theory don't provide the answer.
As far as experimental verification of photon-photon scattering, the wikipedia article here goes into a bit more detail, with links to the original articles I'm sure.
Lastly, the traditional "bent rays of starlight during a solar eclipse" experiments that first validated the theory of General Relativity could be considered a photon-photon scattering experiment in the broadest sense possible (i.e. the scattering mechanism is gravitational). I'm not going to dwell on this because this isn't what most people are talking about when they mention photon-photon scattering.
Thanks for your question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Return the last evaluated object from a file
Is it possible to return the last evaluated object from a Ruby file?
Suppose I have a file like:
# app.rb
def foo
"Hello, world!"
end
foo
Then, I would expect something like this behavior:
# other_file.rb
require_relative!('foo') # => "Hello, world!"
Instead of the require_relative's true returned value, we fetch the last evaluated object of the required file.
Is there a way to have a require_relative!-like behavior?
A:
It sounds like a bad practice. Ruby files are storages of ruby code, not data.
Idiomatically you should create a Ruby file with class or module, require it and call some function from it.
# foo.rb
module Foo
extend self
def foo
"bar"
end
end
# irb
require 'foo'
Foo.foo
#=> bar
Otherwise, as @sawa mentioned, you should read file as a string and eval it. Which is idiomatically wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Turing Machines decide on computability?
Can a Turing Machine decide whether an arbitrary real number is computable or not? Does this even follow from the solution of the Halting problem? If not, who proved it?
A:
A real number cannot be input into a Turing machine, since it is an infinite object. There are various models for providing a Turing machine with oracle access to real numbers, but these are by definition computable.
You could imagine a Turing machine given a ZFC definition of a real number, and in that case it's undecidable. For example, given a Turing machine $T$, you could define a number $x$ as follows: if $T$ doesn't halt in $n$ steps then the $n$th bit of $x$ is zero. Otherwise, it is the $n$th bit of Chaitin's constant. So $x$ is computable if and only if $T$ never halts.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.