text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Why do XS subs use const char *?
A lot of Perl XS code uses const char * as the return value of an XS sub but never just char *. For example:
const char *
version(...)
CODE:
RETVAL = chromaprint_get_version();
OUTPUT: RETVAL
code from xs-fun
Can someone explain why const is preferred? In my testing, the returned scalar is modifiable whether const is used or not.
A:
It's only for clarity. The chromaprint_get_version function returns a const char *, so the XSUB should be defined with a const char * return type as well. If you have a look at the built-in typemap, it doesn't make a difference whether you use const char *, char *, or even unsigned char *. They all use the T_PV typemap. In all cases, the XSUB will return an SV containing a copy of the C string, which is always modifiable.
| {
"pile_set_name": "StackExchange"
} |
Q:
$f'=e^{f^{-1}}$, again
This question is a spin-off of this one, in which the OP asks whether there is a solution $f:\mathbb R\to\mathbb R$ of the functional equation (not exactly an ODE) $f'=e^{f^{-1}}$, where $f^{-1}$ is the compositional inverse of $f$. The posted answer exploits the growth of $f(x)$ when $x\to-\infty$ and obtains a contradiction, which resolves the question nicely, but also invites the following question: what if we restrict to $f:\mathbb R_{\ge0}\to\mathbb R_{\ge0}$ and impose $f(0)=0$? This idea has been explored in the comments, where a formal power series expansion is obtained for $f$ which does not seem to converge for any $x\ne0$.
Taking another approach, we can use an iteration scheme starting from $f_1(x)=x$ and inductively solve the ODE $f_{n+1}'=e^{f_n^{-1}}$ with the initial condition $f_{n+1}(0)=0$ to obtain $f_{n+1}$, much in the spirit of Picard iteration. Explicitly, for example, we have
$f_2'=e^x$ and $f_2=e^x-1$;
$f_3'=e^{\ln(x+1)}=1+x$ and $f_3=x+x^2/2$;
$f_4'=e^{\sqrt{1+2x}-1}$ and $f_4=e^{\sqrt{1+2x}-1}(\sqrt{1+2x}-1)$
and the next iteration produces non-elementary functions. It is clear that the sequence $(f_{2k-1})_{k\ge1}$ is increasing, $(f_{2k})_{k\ge1}$ is decreasing, and $f_{2k-1}<f_{2k}$, so there are respective limits $f_-=\lim_{k\to\infty} f_{2k-1}$ and $f_+=\lim_{k\to\infty} f_{2k+1}$, with $f_-\le f_+$. It is also clear that from $n\ge2$ on the function $f_n'=e^{f_{n-1}^{-1}}$ is positive and increasing, so $f_n$ is increasing and convex, which can be passed to the limit to show that both $f_-$ and $f_+$ are also increasing and convex. As such they are continuous, and by Dini's theorem $f_{2k-1}$ converges to $f_-$ locally uniformly and similarly for $f_+$. Furthermore, the inequality $|x-y|\le |f_n(x)-f_n(y)|$ (as $f_n'=e^{f_{n-1}^{-1}}\ge1$) can also be passed to the limit. Then the following chain of inequalities:
$|f_-^{-1}(x)-f_{2k-1}^{-1}(x)|\le |x-f_-(f_{2k-1}^{-1}(x))|=|f_{2k-1}(f_{2k-1}^{-1}(x))-f_-(f_{2k-1}^{-1}(x))|$
shows that $f_{2k-1}^{-1}$ converges locally uniformly to $f_-^{-1}$, which then implies $f_{2k}'$ converges locally uniformly to $e^{f_-^{-1}}$. Hence $f_+'=e^{f_-^{-1}}$, and similarly $f_-'=e^{f_-^{-1}}$. From this it can be shown that $f_{2k-1}$ converges to $f_-$ locally in $C^\infty$, so both $f_-$ and $f_+$ are smooth functions, and they form an orbit of order at most 2 of the above iteration scheme. Moreover it can be shown that the first $n$ terms of the Taylor expansion of $f_n$ agrees with what have been calculated formally in the previous comments, so both $f_-$ and $f_+$ have the same Taylor expansion as calculated using formal power series expansion.
In light of the above, a priori the following three scenarios can happen:
$f_-\neq f_+$ and we have a genuine orbit of order 2, consisting of two functions having the same Taylor expansion at 0 but not being identical.
$f_-=f_+$ is an actual solution to the equation $f'=e^{f^{-1}}$, but it is merely $C^\infty$ but not analytic, having a divergent power series expansion at 0.
$f_-=f_+$ is an actual solution to the equation $f'=e^{f^{-1}}$, and it is analytic on a neighborhood of 0; we are just misled by the first 100 or so terms of the Taylor expansion.
Now finally comes the question: which of the above scenario is the reality? In the first two scenarios, one can also ask what is the growth rate of $f_-(x)$ and $f_+(x)$ as $x\to+\infty$.
A:
There is no analytic local solution at $0$ to $f'=e^{f^{-1}}$, $f(0)=0$, that is, the formal power series solution is diverging. Together with the solution given in comments by fedja, this means the actual scenario is 2. For convenience of notation, I shall consider the equivalent equation
$$\begin{cases} g' =e^{g\circ g}, \\ g(0)=0,
\end{cases}$$
satisfied by $g(x):=-f^{-1}(-x)$ (Indeed, by the rule of the derivative of an inverse, $(f^{-1})'(x)={1\over f'(f^{-1}(x))}=e^{-f^{-1}(f^{-1}(x))}$ so that $g'(x) =e^{g(g(x))}$; see also Tom Copeland's previous answer here.)
Indeed, assume by contradiction the formal power series solution $x+{1\over2}x^2+{1\over2}x^3+{2\over3}x^4+\&c.$ to the above equation has a positive radius of convergence. Then, it extends uniquely by analytic continuation to a maximally-defined analytic function, still denoted $g$ (that is, defined on the largest positive interval $[0,a)$, for some $0<a\le+\infty$).
Note that the Taylor series of $g$ at $0$ has non-negative coefficients. This follows immediately by induction, equating the coefficients of $g'$ and $e^{g\circ g}$; incidentally, this series is the EGF of the positive integer sequence OEIS A214645, as also remarked here. As a consequence (check the details below), $g$ is totally monotonic on $[0,a)$; in particular $g'(x)>g'(0)=1$ and $g(x)>x$ for all $0<x<a$, and $g$ is invertible.
Then observe that $\log( g'( g^{-1}(x))$ is a well-defined analytic function on the interval $g[0,a)$, and coincides with $g$ locally at $0$. By the maximality of $[0,a)$ we have thus $g[0,a)\subset[0,a)$, but, due to the inequality $g(x)>x$ on $(0,a)$, this inclusion is only possible if $a=+\infty$, so that $g$ is unbounded. On the other hand, arguing as in Christian Remling's previous answer, since $e^{-g(g(t))}g'(t)=1$ and $g(t)\ge t$, we have for any $x\ge0$
$$x=\int_0^{x}e^{-g(g(t))}g'(t)dt=\int_0^{g(x)}e^{-g(s)}ds\le \int_0^{+\infty}e^{-s}ds=1 ,$$
a contradiction.
$$*$$
Rmk 1. To justify the total monotonicity of $g$, note that, as a general elementary fact, a real analytic function on an interval $I$, whose Taylor series at some point $x_0\in I$ has non-negative coefficients, has Taylor series with non-negative coefficients ay any point $x\in I$, $x\ge x_0$. Indeed, this is clear for $x_1\ge x_0$ within the radius of convergence of $x_0$, and since there is a uniform radius of convergence at any $y\in [x_0,x]$, one reaches $x$ by finitely many steps $x_0<x_1<\dots<x_n=x$.
$$*$$
Rmk 2. The very same argument works for other differential-functional equations like e.g.
$$\begin{cases} g' =1 + {g\circ g}, \\ g(0)=0,
\end{cases}$$
that generates the sequence OEIS A001028.
As before, a maximally-defined analytic solution $g$, if any, must be totally monotonic and defined for all $x\ge0$, for otherwise $ g'\circ g^{-1} -1$ would be a proper extension of it. Then we reach a contradiction as before, with one more step needed: since we have ${ g'(t)\over 1+g(g(t))}=1$ and $g(t)\ge t$ for any $t\ge0$, we also have, for any $x\ge0$
$$x=\int_0^{x}{ g'(t)dt\over 1+g(g(t))}=\int_0^{g(x)}{ dt\over 1+g(t)}\le\int_0^{g(x)}{ dt\over 1+t}=\log(1+g(x)) ,$$
whence $e^x\le 1+ g(x)$; if we plug this into the latter inequalities again, we get
$$x=\int_0^{g(x)}{ dt\over 1+g(t)}\le \int_0^{g(x)}e^{-t}dt\le 1 ,$$
as before. By comparison, the same conclusion also holds for $g'=F( {g\circ g})$ with any $F$ analytic and totally monotonic on $(-\epsilon,+\infty)$, and with $F(0)=1$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Transform smarty Boolean value to human readable value.('Yes'/'No' or 'True'/'False')
I'm using Smarty to generate some tables, and at one point I'm printing out variable values that have been passed from php file. The problem is that some of these variables are Boolean values and they render as "1" or "". This was my attempt to transform these Boolean values to a human readable format. It does not work. How can can I check if a variable is a Boolean value?
{if $val2.$value_index === true}Yes
{else if $val2.$value_index === false}No
{else}{$val2.$value_index->value}{/if}
A:
Use the PHP var_export() function as a smarty modifier for your boolean variables.
Set the second parameter to true, so var_export() returns the variable representation instead of outputting it.
To check if your variable is a boolean, use the PHP is_bool() function.
Your Smarty code should look like this:
{if is_bool($val2.$value_index)}
{$val2.$value_index|var_export:true}
{/if}
A:
I'm not exactly familiar with this, but it looks as though that should be:
{if $val2.$value_index->value === true}Yes
{elseif $val2.$value_index->value === false}No
{else}{$val2.$value_index->value}{/if}
| {
"pile_set_name": "StackExchange"
} |
Q:
Php, static variables for trait itself only, how?
its possible to have static variables for traits:
Trait Example
{
public static $var;
}
class X
{
use Example;
}
class Y
{
use Example;
}
however, the problem is when more class would want to use this trait, I get a fatal error:
Example and X define the same property ($var) in the composition of Y. This might be incompatible, to improve maintainability consider using accessor methods in traits instead. Class was composed
how to define this static variable just for the trait itself?
A:
Traits can define both static members and static methods. however You can not reassign trait properties.
From PHP manual http://php.net/traits
See Example #12 Conflict Resolution
If a trait defines a property then a class can not define a property with the same name, otherwise an error is issued. It is an E_STRICT if the class definition is compatible (same visibility and initial value) or fatal error otherwise.
The solution would be to override properties in the class
Trait Example
{
public static $var;
}
class X
{
use Example;
public static $var;
}
class Y
{
use Example;
public static $var;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Formula to combine variable and cell references
I have been looking for hours for a solution but couldn't find any. I am an absolute beginner in VBA and couldn't figure this out for myself. The thing I would like to do is that VBA enters in a cell a formula that will contain a value extracted from a variable and then subtracts all the below cells. The cells below could change which would affect the overall value so I need to leave it as dynamic. (e.g: Cell A1 should look like this: =500-A2-A3-A4.. etc).
The code looks like this at the moment. So far it only enters the value from the variable
crnt = Cells(5, "D").Value
Range("E60").Select
ActiveCell.Offset(0, crnt - 1).Activate
rev = ActiveCell.Value
Range("E9").Select
ActiveCell.Offset(0, crnt - 1).Select
ActiveCell.Value = rev
A:
You might want this one:
InVal = 500 ' input value
Cells("A1").FormulaLocal = "=" & CStr(InVal) & "-A2-A3-A4"
or in a loop
Dim InVal() as Variant
InVal = Range("M60:Z60").Value
For i = LBound(InVal) to UBound(InVal)
Cells(1, i + 1).FormulaLocal = "=" & CStr(Val(InVal(i))) & "-" & Cells(2, i + 1).Address & "-" & Cells(3, i + 1).Address & "-" & Cells(4, i + 1).Address
Next i
All you need to do is to play with .Address and the strings to compile the formula.
| {
"pile_set_name": "StackExchange"
} |
Q:
Migrating from PVM to MPI
I'm working on migrating a project from PVM to MPI. I wanted to ask if anyone here has done so before and if there exists any tutorials or manuals on the correspondance between functions in PVM and MPI.
A:
Chapter 9 of the useful book Using MPI talks pretty explicitly about comparing PVM and MPI and what you'd have to do to port.
They're both message-passing libraries, and if you're mostly using point-to-point communications or basic collectives, the port should be quite straightforward. PVM though always had a lot more support for dynamic processes creation and management than even recent MPI standards have had, and if your code relies heavily on those sorts of features, it will be harder.
A:
I have a lot of resources I've been using over the past few days
MPJ Papers
mpj: enabling parallel simulations in java
MPJ MIT
MPJ java docs
Google Scholar MPI
Hope it helps!
No problem with MPI by the way each processor runs synchronously in parallel with all the other processors, and every processor shares a different address space. (You can experiment this for yourself with java.util.Date and run System.out.println statements to the console and you'll see when you send something and receive something using point-to-point or unblocked communication, the process will recieve at the same time it was sent in a synchronous fashion). Send and recieve is better to think about when your at the dinner table and you ask a relative to give you a fork, you would recieve the fork at the same as it is being sent (i.e. being handed directly to you).
| {
"pile_set_name": "StackExchange"
} |
Q:
Heroku Puma Sidekiq Running 167% crititcal r14 memory quota exceeded on 3 web dynos with one visitor
I am running Puma 3.4, Rails 4.2.6, Sidekiq 4.2.2, Redis Mini, on 3 dynos (standard 1x) on Heroku. I am doing simple Beta testing and I cannot seem to optimize my puma-dyno situation. I get High Response Time Alerts and Critical Memory Quota alerts when one user is on the site (I am using New Relic to monitor).
I have added Puma Worker Killer to try to diagnose this, but no help.
I have everything set using Environment variables (max_threads, concurrency, etc) and I've scoured the internet for how to config.
I am setting options in database.yml, sidekiq.rb, puma.rb, puma_worker_killer.rb and sidekiq.yml, so I might be setting things in too many places.
Since I'm running 3 Standard 1x web dynos for one user I know that something is wrong.
config/puma.rb
before_fork do
require 'puma_worker_killer'
ActiveRecord::Base.connection_pool.disconnect!
PumaWorkerKiller.config do |config|
config.ram = ENV['PUMA_WORKER_KILLER_RAM'] || 1024 # mb
config.frequency = 5 # seconds
config.percent_usage = 0.98
config.rolling_restart_frequency = 12 * 3600 # 12 hours in seconds
end
PumaWorkerKiller.start
end
workers Integer(ENV['WEB_CONCURRENCY'] || 5)
min_threads_count = Integer(ENV['MIN_THREADS'] || 1)
threads_count = Integer(ENV['RAILS_MAX_THREADS'] || 5)
threads min_threads_count, threads_count
preload_app!
rackup DefaultRackup
port ENV['PORT'] || 5000
environment ENV['RACK_ENV'] || 'development'
on_worker_boot do
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.establish_connection
end
end
config/initializers/sidekiq.rb
require 'sidekiq'
redis_url = ENV['REDISTOGO_URL']
redis_config = {
url: redis_url,
namespace: 'oct',
}
Sidekiq.configure_server do |config|
config.redis = { url: ENV["REDISTOGO_URL"], namespace: 'oct', size: ENV["SIDEKIQ_SERVER_CONNECTIONS"].to_i || 6}
config.error_handlers << Proc.new do |exception, context_hash|
SidekiqErrorService.new(exception, context_hash).notify
end
end
Sidekiq.configure_client do |config|
config.redis = { url: ENV["REDISTOGO_URL"], namespace: 'oct', size: ENV["REDIS_CLIENT_CONNECTION_SIZE"].to_i || 2}
end
config/sidekiq.yml
:verbose: false
:concurrency: <%= ENV["WEB_CONCURRENCY"] %>
production:
:timeout: <%= ENV["SIDEKIQ_TIMEOUT"] %>
development:
:timeout: 30
:queues:
- [highest, 2]
- medium
- lowest
- mailers
config/initializers/puma_worker_killer.rb
PumaWorkerKiller.enable_rolling_restart
config/database.yml
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV["DB_POOL"] || ENV['RAILS_MAX_THREADS'] || 5 %>
development:
<<: *default
database: myapp_development
username: myapp
password: myapp
host: localhost
port: 5432
test:
<<: *default
database: myapp_test
username: myapp
password: myapp
host: localhost
port: 5432
my current environment settings
Memory 125-167% (on web dynos, not worker dynos)
WEB_CONCURRENCY: 4
DB_POOL: 15
SIDEKIQ_SERVER_CONNECTIONS: 25
MIN_THREADS: 1
RAILS_MAX_THREADS: 5
REDIS_CLIENT_CONNECTION_SIZE: 1
SIDEKIQ_TIMEOUT: 30
DATABASE_REAP_FREQ: 5
PUMA_WORKER_KILLER_RAM: 1535
I also tried to use this helper
http://manuelvanrijn.nl/sidekiq-heroku-redis-calc/
but it made it worse, 300% + memory usage
WEB_CONCURRENCY: 45
DB_POOL: 15
SIDEKIQ_SERVER_CONNECTIONS: 47
MIN_THREADS: 1
RAILS_MAX_THREADS: 5
REDIS_CLIENT_CONNECTION_SIZE: 1
SIDEKIQ_TIMEOUT: 30
DATABASE_REAP_FREQ: 5
PUMA_WORKER_KILLER_RAM: 1535
A:
For a Rails 4, you have too many puma workers even at 4 (45 is impossibly high for that tier). Standard-1x dynos have 512MB. Trying dropping WEB_CONCURRENCY down to 2 and I suspect that you'll see a large enough reduction in memory consumption to prevent R14s.
If you're still having trouble after switching WEB_CONCURRENCY to 2 you will need to do some memory optimizations or drop it down to 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between a line segment inside and outside of a concave polygon?
My question is about the creation of visibility graphs in surfaces with multiple convex and concave polygons. My problem is that i am not able to classify whether the line segments connecting the nodes of the same polygon go through or don't go through this polygon. As seen in the picture below:
I'd need to separate the orange, invalid lines from the blue, valid lines. I hope somebody can provide me a solution to this problem with a suitable algorithm that can be implemented in python.
Or for even complexer polygons?:
difficult polygon
A:
This code accepts A and B as two vertices and checks if the line joining them lies completely inside , partially inside or completely outside the polygon. This is based on mathematical fact that for a line with eqn. F(X,y):Ax+By+C the point x1,y1 will lie on the line if F(x1,y1)=0
On one side of line if F(x1,y1)>0
On other side of line if F(x1,y1)<0
L=[] #list of all the vertices of the polygon as (x,y) tuples in order
A=()
B=()
# A and B are tuples of coordinates of points joking diagonal to check
def eqn(A,B):
X1=A[0];Y1=A[1]
X2=B[0];Y2=B[1]
return(X2-X1,Y1-Y2,X1*Y2-X2*Y1)
def check(Y,X,C,y,x):
if(Y*y+X*X+C>0):
return 1
elif(Y*y+X*X+C<0):
return -1
else:
return 0
Y,X,C=eqn(A,B)
#get parameters of diagonal joining A and B
a=L.index(A)
b=L.index(B)
L1=[]
L2=[]
if(a>b):
L1=L[b+1:a]
L2=L[a+1:]+L[:b]
elif(b>a):
L1=L[a+1:b]
L2=L[b+1:]+L[:a]
#so I have split the list into two lists L1 and L2 containing vertices in cyclic order on either side of the diagonal
k=1
m=0
val1=check(Y,X,C,L1[0][1],L1[0][0])
val2=check(Y,X,C,L2[0][1],L2[0][0])
if(val1==val2):
k=0
m=1
else:
# I have to check F(x,y) for each point in list L1 and L2 it should be of one sign for all elements in L1 and of other sign for all elements in L2 for line to lie completely inside polygon
for t in L1:
if(check(Y,X,C,t[1],t[0])!=val1):
k=0
m=0
for s in L2:
if(check(Y,X,C,s[1],s[0])!=val2):
k=0
m=0
if(k==0):
print('the diagonal passes outside')
else:
print('the diagonal lies completely inside the polygon')
if(m==1):
print('the diagonal lies completely outside the polygon')
I have written the code hope it works as required,but there maybe errors:o,the logic is correct,there may be syntax or other errors you have to take care of(I can help in that case) I have excluded one case if the two points chosen are consecutive,then it is obviously the side of the polygon(trivial to check).
| {
"pile_set_name": "StackExchange"
} |
Q:
Rank by 2 different levels of partitioning/grouping
I have this set of data using Microsoft SQL Server Management Studio
Category|pet name| date |food price|vet expenses|vat
A | jack |2017-08-28| 12.98 | 2424 |23
A | jack |2017-08-29| 2339 | 2424 |23
A | smithy |2017-08-28| 22.35 | 2324 |12
A | smithy |2017-08-29| 123.35 | 2432 |23
B | casio |2017-08-28| 11.38 | 44324 |32
B | casio |2017-08-29| 2.24 | 3232 |43
B | lala |2017-08-28| 343.36 | 42342 |54
B | lala |2017-08-29| 34.69 | 22432 |54
C | blue |2017-08-28| 223.02 | 534654 |78
C | blue |2017-08-29| 321.01 | 6654 |67
C | collie |2017-08-28| 232.05 | 4765 |43
C | collie |2017-08-29| 233.03 | 4654 |65
What I want to do is rank by food price, but group by category, order by category, pet name, date and then rank by vet expenses, but group by category, order by category, pet name, date and then rank by vat, but group by category, order by category, pet name, date.
I'm thinking this will be a join statement for the table above?
Something exactly like below:
Category|pet name| date |food price|vet expenses|vat|Rankfp|Rankve|Rankvat
A | jack |2017-08-28| 12.98 | 2424 |23 | 2 | 1 |1
A | jack |2017-08-29| 2339 | 2424 |23 | 1 | 2 |1
A | smithy |2017-08-28| 22.35 | 2324 |12 | 1 | 2 |2
A | smithy |2017-08-29| 123.35 | 2432 |22 | 2 | 1 |2
B | casio |2017-08-28| 11.38 | 44324 |32 | 2 | 1 |2
B | casio |2017-08-29| 2.24 | 3232 |43 | 2 | 2 |2
B | lala |2017-08-28| 343.36 | 42342 |54 | 1 | 2 |1
B | lala |2017-08-29| 34.69 | 22432 |54 | 1 | 1 |1
C | blue |2017-08-28| 223.02 | 534654 |78 | 2 | 1 |1
C | blue |2017-08-29| 321.01 | 6654 |67 | 1 | 1 |1
C | collie |2017-08-28| 232.05 | 4765 |43 | 1 | 2 |2
C | collie |2017-08-29| 233.03 | 4654 |65 | 2 | 2 |2
NB: this is not needed in the final output but to make it more readable I have ordered the outcome by category, pet name, date:
Category|pet name| date |food price|vet expenses|vat|Rankfp|Rankve|Rankvat
A | jack |2017-08-28| 12.98 | 2424 |23 | 2 | 1 |1
A | smithy |2017-08-28| 22.35 | 2324 |12 | 1 | 2 |2
A | jack |2017-08-29| 2339 | 2424 |23 | 1 | 2 |1
A | smithy |2017-08-29| 123.35 | 2432 |22 | 2 | 1 |2
B | casio |2017-08-28| 11.38 | 44324 |32 | 2 | 1 |2
B | lala |2017-08-28| 343.36 | 42342 |54 | 1 | 2 |1
B | lala |2017-08-28| 343.36 | 42342 |54 | 1 | 2 |1
B | lala |2017-08-29| 34.69 | 22432 |54 | 1 | 1 |1
C | blue |2017-08-28| 223.02 | 534654 |78 | 2 | 1 |1
C | collie |2017-08-28| 232.05 | 4765 |43 | 1 | 2 |2
C | blue |2017-08-29| 321.01 | 6654 |67 | 1 | 1 |1
C | collie |2017-08-29| 233.03 | 4654 |65 | 2 | 2 |2
The code I have below only ranks by category, but does not group by food price, vet expenses and vat.
RANK ()OVER(PARTITION BY [Category], [Date] order by [Category] ,[Pet Name],[Date]) as 'Rank'
Would it be a case of grouping the costs separately then left joining the rankings on to the original data?
(I will be using pivots and slicers in excel so want to have all the data on one table/query)
A:
After walking away with some time to refresh my brain i had a eureka moment and solved this. It was actually easy when I thought about it.
so
the code to get the desired table goes something like this:
select *
, rank ()OVER(PARTITION BY [Category], [date] order by [food price], [Category] ,[pet name],[date]) as 'Rankfp'
, rank ()OVER(PARTITION BY [Category], [date] order by [vet expenses], [Category] ,[pet name], [date]) as 'Rankve'
, rank ()OVER(PARTITION BY [Category], [date] order by [vat], [Category] ,[pet name], [date]) as 'Rankvat'
from petcost
order by [category, [pet name]
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I hide or diminish VS2017's vertical lines in the editor
Visual Studio 2017 uses quite bright, dashed, vertical lines within code's indentation to highlight the extent of various scopes.
How can I turn these off, or make them less vivid?
A:
You can reduce the intensity of these lines:
In VS2017, go to menu Tools, Options....
Navigate to Environment/Fonts and Colors and scroll to select the Structure Guide Lines display item.
Click custom, then drag down the black arrow to the right of the dialog until you see a colour you like.
A:
You can also turn them off completely from Tools\Options, Text Editor, General, Show structure guide lines.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bad reputation of reputation
For the record: the post below is not to defend the point where I am standing. That's why I feel I am entitled to bring this up.
Every now and then, reputation is brought up in discussions as an argument. Used wrongly in my opinion, for reasons pointed out below.
Not the only reason, but an important one was the question here http://meta.askubuntu.com/a/15662/72216, where the question at a certain point moved to a reputation/motivation discussion. The question wasn't reputation- motivated, but even if it were, it shouldn't (have) be(en) an argument at all.
As a general rule, when working in teams, to make sure the team is productive, we need to make sure each and every member of the team has his or her own personal interest in a good result of the team. This interest may and will vary.
The formula of the SE sites understands this extremely well. That's one of the reasons the reputation system exists, and why we have a personal reputation record on SE sites.
The site obviously stresses on the importance of the personal reputation; not only are privileges directly related to reputation, but together with the general information of moderator candidates for example, detailed information is displayed on the candidates' reputation, the average reputation per post and so on.
Of course, we may hope that the motivation to answer (or ask) questions is not purely reputation based, and to prevent misunderstandings, mine isn't. However, as long as we post quality Q's and A's, keep the site's rules, maintain general rules of decensy and good behaviour, our personal motivation is totally irrelevant to the site.
Nevertheless, on a regular base, in discussions, "chasing reputation" is implicitely or explicitely mentioned as a bad thing, a sign of bad behaviour, doing it for the wrong reasons. As mentioned, in itself, chasing reputation, even if it is the only motivation to create good content, is perfectly fine and needs no defense at all.
So, in a nutshell, please don't use chasing reputation as an argument to prove you're right or someone else is wrong. What counts is good content and constructive behaviour. The motivation under the hood is no one's business but the poster's.
A:
Sometimes, when I close my eyes in a daydream, I see a little green rectangle top left. The sign of joy!
I'm not a mind reader, but I think it's probably hypocritical for people to mutter disapprovingly about others "chasing reputation". Like my mother told me at school where I got bullied for always putting my hand up to give the answer "They're just jealous."
Problems might arise, I guess, when the overall glory of AU is damaged somehow by the way people behave, or needed effort (like reviewing and editing) is not made because it doesn't contribute to reputation.
In that case, I think people should be complaining about the problem, and not the motivation, since, as you say, what others are thinking is private and unknowable...
Moreover, we are not all the same, and it takes many different folks to make a glorious SE site, and many people do those non-rep-earning tasks, and as long as there are enough people doing them, then there isn't a problem...
In short I agree with you and am just rambling...
Better get back to writing quick answers to easy questions ploughing through the Close Votes Review Queue...
A:
Reputation isn't just imaginary numbers on the screen. It's a number which says something important. It says that you helped people. So of course people like to "chase" it (or at least appreciate it when they get it). Why do people spend hours on AU helping people? It's not because they make money from it (mostly). It's not because there's (usually) some tangible, real life benefit to them immediately. It's mostly because they like the feeling of having helped someone. Of course! If you spend hours writing good answers and helping strangers with problems, and there's no feedback, then that's not a good feeling. So reputation is very important! It tells you that you helped people and that your work was useful. The feeling of having contributed to something useful can often be more valuable to us than even money.
Someone may say "your motive shouldn't just be reputation". But I think reputation really is a type of feedback showing you that you helped people. If someone said "Your motive shouldn't just be to know that you've helped people", then I would say, "Yes, it's an entirely decent motive to be on AU with the intention of trying to help people and wanting to have a solid affirmation that you actually did help people."
I think almost everyone here agrees with this, including the people you were having a discussion with in the post you linked to in OP (I was actually one of those people.)
I would suggest that it's hardly possible to be after only reputation. Reputation isn't "only" reputation. It's a symbol of something. Is anyone after just the number? I doubt it. The number itself would be totally meaningless if it didn't represent something. I believe what people are truly after is what the number represents. And I think that's a perfectly fine thing to be "after."
Otherwise it just seems meaningless. For example, let's say you spend lots of time and energy figuring out an excellent answer to a tough problem. OP abandons the post, and doesn't give any feedback to the answer. Very few other people notice the answer, and it just gets lost without any upvotes. Thankfully this doesn't happen very often. Because when we have worked hard at something, we need affirmation that it was actually helpful. And that is exactly what that little +100 or +200 symbol on the top tells you. That you helped people.
Finally, you can even spend your reputation to help others. Let's say a user has posted a really tough problem that you don't know the answer to. If you post a large bounty on it, it might just motivate people to put up the effort to find a solution to the tough problem. That's actually getting people to put in effort into something. That's something we pay lots of money for in the real world.
So, reputation is really important! I dare assert that without it, AU would be much, much weaker than it is today. And I don't blame anyone in the slightest, for chasing it. That would be like blaming a social worker for "chasing" the smiles on the faces of the people he/she was helping.
I often help my real life friends with their computers. I'll willingly admit that one of my motives is the feeling of having helped someone, and knowing that they are thankful. Reputation is the AU equivalent of that, and I think it's an entirely appropriate motive.
It's true that many of us might use reputation as food for our egos, etc, obsessing over it. Human nature can be like that. But unless a user is putting on a truly bizarre show, I think we should hesitate before suggesting that other users are in such a state. It's mostly quite hard to know what's actually going on in the mind of another person. So in this regard I believe we should mostly give everyone the benefit of the doubt.
| {
"pile_set_name": "StackExchange"
} |
Q:
Injecting JpaRepository directly
Im looking for a way intercept all requests going to all the defined methods.
(defined=whatever is on the JpaRepository interface).
so for example when someone calls repo.findAll() I will be able to run a generic code before and after.
(generic=same code of all the entities).
So what I did is created a generic class and implemented methods in JpaRepository and then intercept all the requests.
@Repository
public class BaseJpaRepository<T> implements JpaRepository<T, Long> {
@Autowired
private JpaRepository<T, Long> repository;
@Override
public List<T> findAll() {
//run some code here
List<T> res = repository.findAll();
//run some code here
return res;
}
// all other methods here...
}
this is the interface to inject into services:
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
}
this is the Bean
@Repository
public class UserRepositoryBean extends BaseJpaRepository<User> implements JpaRepository<User, Long> {
}
The problem is that private JpaRepository<T, Long> repository; is not injecting, I assume that this is because spring needs the Entity type in bootstrap time.
I also tried to inject explicit type it to the constructor if UserRepositoryBean and pass it to the parent. but its unsatisfied.
@Repository
public class UserRepositoryBean extends BaseJpaRepository<User> implements JpaRepository<User, Long> {
public UserRepositoryBean(JpaRepositry<User, Long> repo){super(repo);}
}
Any way to intercept all the Spring jpa methods?
Thanks
A:
First you define basic interface that all your custom repositories will be inherited from
@NoRepositoryBean
interface BaseJpaRepository<T, ID> extends JpaRepository<T, ID> {
// You can also declare any generic methods here,
// and override (intercept) them in BaseJpaRepositoryImpl as well
}
And it's implementation as well
@NoRepositoryBean
class BaseJpaRepositoryImpl<T, ID>
extends SimpleJpaRepository<T, ID>
implements BaseJpaRepository<T, ID> {
public BaseJpaRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager em) {
super(entityInformation, em);
}
// One of 'defined' methods inherited from SimpleJpaRepository (and in turn from JpaRepository)
@Override
public List<T> findAll() {
//run some code here
List<T> res = super.findAll();
//run some code here
return res;
}
// other 'defined' methods to intercept ...
}
Your custom repository would then look just as usual except that it is now derived from your BaseJpaRepository interface instead of Spring's JpaRepository
@Repository
interface UserRepository extends BaseJpaRepository<User, Long> {
}
To make it all work, let's modify following annotation that is usually placed onto some @Configuration class or onto @SpringBootApplication-ed class
@EnableJpaRepositories(
basePackages = {"org.example.repositories"},
repositoryBaseClass = BaseJpaRepositoryImpl.class
)
P.S. Another viable approach is to use Spring AOP. You can also check out similar Question here
| {
"pile_set_name": "StackExchange"
} |
Q:
wmd markdown code problem
i m using wmd markdown editor in my project and i have a problem with code tags:
if i enter a code snippet , markdown does not convert to html correctly it converts in "<p>" tags but if i enter some text else first and then code snippet it converts correctly in "<code>" tags
is this a bug of wmd markdown editor? and how can i solve this problem?
A:
I was actually working on this for my fixed version of WMD edit. Using regex you can quickly lop off the leading and trailing <p> tags which are most notably the causers of a lot of problems:
html = html.replace(/^<p>/g, '').replace(/<\/p>$/g, '');
To enforce this in wmd..
(I'm asuming you're using the SO fork of wmd editor) Find this part of the code and change it as follows:
var convertToHtml = function(){
if (wmd.showdown) {
var markdownConverter = new wmd.showdown.converter();
}
var text = inputBox.value;
var callback = function(){
inputBox.value = text;
};
if (!/markdown/.test(wmd.wmd_env.output.toLowerCase())) {
if (markdownConverter) {
inputBox.value = markdownConverter.makeHtml(text);
// Add this line here:
inputBox.value= inputBox.value.replace(/^<p>/g, '').replace(/<\/p>$/g, '');
top.setTimeout(callback, 0);
}
}
return true;
};
Untested, but you should get the idea.
| {
"pile_set_name": "StackExchange"
} |
Q:
Select all columns of a dataframe as a StructType
In pyspark, I have two dataframes, dfA and dfB, with complex schemas. A common column in the schemas is 'time'. I'd like to make a new dataframe that is the union of these two, so that I can sort on time, however I don't want to lose anything in the original dataframes. I can't figure out how to get everything from one of the original dataframes and group it together in a new structType of the union.
That is, if I have
# dfA
root
|--time
|--fieldA
|--fieldB
# dfB
root
|--time
|--fieldC
|--fieldD
I'd like to create a union dataframe that has schema
# root
|--time
|--dfA
|--time
|--fieldA
|--fieldB
|--dfB
|--time
|--fieldC
|--fieldD
After the union, the fields dfA and dfB will null sometimes, depending on which of the original dataframes the row came from.
I imagine I could define the common schema by doing
common_schema = T.StructType([T.StructField('time', T.TimestampType()),
T.StructField('dfA', dfA.schema, True),
T.StructField('dfB', dfB.schema, True)])
But then I get stuck on the syntax for how to select everything from a dataframe as a column. I'm looking for something like
commonA = dfA.select('time',
F.col('*').alias('dfA'))
commonB = dfB.select('time',
F.col('*').alias('dfB'))
common_df = commonA.union(commonB)
But this is an illegal use of '*'
A:
Select all columns of a dataframe as a StructType
from pyspark.sql.functions import struct, lit
commonA = dfA.select("time", struct(*[c for c in df.columns]).alias("dfA"))
commonB = dfB.select("time", struct(*[c for c in df.columns]).alias("dfB"))
but this cannot be unioned as described. You could:
commonA_ = commonA.select("time", "dfA", lit(None).cast(dfB.schema).alias("dfB"))
commonB_ = commonB.select("time", lit(None).cast(dfA.schema).alias("dfA"), "dfB")
commonA_.union(commonB_)
but it sounds you are looking for something more like outer join
dfA.alias("A").join(dfB.alias("B"), ["time"], "fullouter")
| {
"pile_set_name": "StackExchange"
} |
Q:
Determine whether a Python function is already implemented in C extension
Suppose I have a Python program that runs slow- after profiliing and I have identified the bottleneck. One particular function from a 3rd party module I imported is particularly slow.
For this particular case, I know that function is implemented in Python (Used Eclipse and it's easy to jump to the function definition). So I know that I can convert that function into Cython as a speed-up option. (If it is already implemented in C, there is no point in writing it in Cython...).
If I don't have an IDE, what would be an easy option to determine this?
I know that I can go to the directory where the module is installed and infer that it is in C if the module is in .so. But is there any alternative?
Thanks
A:
Check whether it is an instance of types.FunctionType:
>>> import types
>>> isinstance(len, types.FunctionType)
False
>>> def mylen(): pass
...
>>> isinstance(mylen, types.FunctionType)
True
Probably you'd be safer to check for isinstance(X, (types.FunctionType, types.LambdaType).
C functions are instances of builtin_function_or_method:
>>> len.__class__
<type 'builtin_function_or_method'>
>>> np.vdot.__class__
<type 'builtin_function_or_method'>
You can access this type as types.BuiltinFunctionType/types.BuiltinMethodType.
Alternatively you can check whether the function has a __code__ attribute. Since C functions do not have bytecode, they can't have __code__.
Note sometimes what seems like a function is actually a class, e.g. enumerate but some 3rd party library may do the same. This means that you should also check whether a class is implemented in C or not. This one is harder since all classes are instances of type. A way may be to check whether the class has a __dict__ in its dir, and if it doesn't have you should check for __slots__.
Something like the following should be pretty accurate:
def is_implemented_in_c(obj):
if isinstance(obj, (types.FunctionType, types.LambdaType)):
return False
elif isinstance(obj, type):
if '__dict__' in dir(obj): return False
return not hasattr(obj, '__slots__')
# We accept also instances of classes.
# Return True for instances of C classes, False for python classes.
return not isinstance(obj, types.InstanceType)
Example usage:
>>> is_implemented_in_c(enumerate)
True
>>> is_implemented_in_c(len)
True
>>> is_implemented_in_c(np.vdot)
True
>>> is_implemented_in_c(lambda x: True)
False
>>> is_implemented_in_c(object)
True
>>> class A(object):
... __slots__ = ('a', 'b')
...
>>> is_implemented_in_c(A)
False
| {
"pile_set_name": "StackExchange"
} |
Q:
Summarize ndarray by 2d array in Python
I want to summarize a 3d array dat using indices contained in a 2d array idx.
Consider the example below. For each margin along dat[:, :, i], I want to compute the median according to some index idx. The desired output (out) is a 2d array, whose rows record the index and columns record the margin. The following code works but is not very efficient. Any suggestions?
import numpy as np
dat = np.arange(12).reshape(2, 2, 3)
idx = np.array([[0, 0], [1, 2]])
out = np.empty((3, 3))
for i in np.unique(idx):
out[i,] = np.median(dat[idx==i], axis = 0)
print(out)
Output:
[[ 1.5 2.5 3.5]
[ 6. 7. 8. ]
[ 9. 10. 11. ]]
A:
To visualize the problem better, I will refer to the 2x2 dimensions of the array as the rows and columns, and the 3 dimension as depth. I will refer to vectors along the 3rd dimension as "pixels" (pixels have length 3), and planes along the first two dimensions as "channels".
Your loop is accumulating a set of pixels selected by the mask idx == i, and taking the median of each channel within that set. The result is an Nx3 array, where N is the number of distinct incides that you have.
One day, generalized ufuncs will be ubiquitous in numpy, and np.median will be such a function. On that day, you will be able to use reduceat magic1 to do something like
unq, ind = np.unique(idx, return_inverse=True)
np.median.reduceat(dat.reshape(-1, dat.shape[-1]), np.r_[0, np.where(np.diff(unq[ind]))[0]+1])
1 See Applying operation to unevenly split portions of numpy array for more info on the specific type of magic.
Since this is not currently possible, you can use scipy.ndimage.median instead. This version allows you to compute medians over a set of labeled areas in an array, which is exactly what you have with idx. This method assumes that your index array contains N densely packed values, all of which are in range(N). Otherwise the reshaping operations will not work properly.
If that is not the case, start by transforming idx:
_, ind = np.unique(idx, return_inverse=True)
idx = ind.reshape(idx.shape)
OR
idx = np.unique(idx, return_inverse=True)[1].reshape(idx.shape)
Since you are actually computing a separate median for each region and channel, you will need to have a set of labels for each channel. Flesh out idx to have a distinct set of indices for each channel:
chan = dat.shape[-1]
offset = idx.max() + 1
index = np.stack([idx + i * offset for i in range(chan)], axis=-1)
Now index has an identical set of regions defined in each channel, which you can use in scipy.ndimage.median:
out = scipy.ndimage.median(dat, index, index=range(offset * chan)).reshape(chan, offset).T
The input labels must be densely packed from zero to offset * chan for index=range(offset * chan) to work properly, and the reshape operation to have the right number of elements. The final transpose is just an artifact of how the labels are arranged.
Here is the complete product, along with an IDEOne demo of the result:
import numpy as np
from scipy.ndimage import median
dat = np.arange(12).reshape(2, 2, 3)
idx = np.array([[0, 0], [1, 2]])
def summarize(dat, idx):
idx = np.unique(idx, return_inverse=True)[1].reshape(idx.shape)
chan = dat.shape[-1]
offset = idx.max() + 1
index = np.stack([idx + i * offset for i in range(chan)], axis=-1)
return median(dat, index, index=range(offset * chan)).reshape(chan, offset).T
print(summarize(dat, idx))
| {
"pile_set_name": "StackExchange"
} |
Q:
Sorting HealthKit data by date
I'm trying to get pulse data from HealthKit and sort them by date for use in a line chart. I'm running a 'for loop' to get the correct dates and put the results in an array before putting the results in the chart but it seems like they get put in a random order and I don't understand why.
class Pulse {
var pulse = 0.0
var startDate = Date()
}
var pulseData: [Pulse] = []
func getHeartBeatsForAWeek() {
for i in 1...7 {
getHeartBeats(startDate: date.getStartOfSpecificDateByAddingToToday(day: -i), endDate: date.getStartOfSpecificDateByAddingToToday(day: -i + 1))
}
}
func getHeartBeats(startDate: Date, endDate: Date) {
PulseHelper.shared.averageHearthRate(startDate: startDate, endDate: endDate) { (data) in
DispatchQueue.main.async {
self.pulseData.append(data)
self.updateGraph()
}
}
}
Here is my function for fetching the heart rate:
func averageHearthRate(startDate: Date, endDate: Date, completion: @escaping (Pulse) -> Void) {
let typeHeart = HKQuantityType.quantityType(forIdentifier: .heartRate)
let startDate = startDate
let endDate = endDate
let predicate: NSPredicate? = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: HKQueryOptions.strictEndDate)
let query = HKStatisticsQuery(quantityType: typeHeart!, quantitySamplePredicate: predicate, options: .discreteAverage, completionHandler: {(query: HKStatisticsQuery, result: HKStatistics?, error: Error?) -> Void in
DispatchQueue.main.async(execute: {() -> Void in
let quantity: HKQuantity? = result?.averageQuantity()
let beats: Double? = quantity?.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute()))
print("Got: \(String(format: "%.f", beats!)) from \(startDate)")
let pulse = Pulse.init()
pulse.pulse = beats!
pulse.startDate = startDate
completion(pulse)
})
})
PermissionsHelper.shared.store.execute(query)
}
This is what I get when I print the results:
Got: 82 from 2019-03-30 23:00:00 +0000
Got: 74 from 2019-03-31 22:00:00 +0000
Got: 73 from 2019-03-25 23:00:00 +0000
Got: 74 from 2019-03-27 23:00:00 +0000
Got: 70 from 2019-03-26 23:00:00 +0000
Got: 74 from 2019-03-29 23:00:00 +0000
Got: 108 from 2019-03-28 23:00:00 +0000
I'd like them to get in correct order.
A:
Just after adding an element to your array, you need to use the sort() function.
Here you can find the documentation about all the ways you can implement it.
In this situation, if pulseData is an array of Date ( [Date] ), you just need to call:
self.pulseData.sort()
EDIT:
As you could see in the link to documentation I posted, there are several ways to use the sort() function in order to apply your sorting rule to a custom object.
In this situation, let's assume you have this class:
class Pulse {
var pulse: Double = 0.0
var startDate = Date()
init(p: Double,d: Date) {
self.pulse = p
self.startDate = d
}
}
Create an array of Pulse objects:
let pulse1 = Pulse(p: .., d: Date(...))
let pulse2 = Pulse(p: .., d: Date(...))
var pulseData: [Pulse] = [pulse1, pulse2]
You can sort the array in this way:
//Ascending order
pulseData.sort(by: {$0.startDate < $1.startDate})
| {
"pile_set_name": "StackExchange"
} |
Q:
Not able to append command line variable in shell script
Here is my code:
export ALLOW_RPM_UPGRADE=True
path='/opt/rpm/latest/'
echo $1
file=$1
echo $file
dest=${path}${file}
echo $dest
cp $source $dest
Problem:
The three echo statements are printing the same value.
The third one is not appending path to $dest variable.
A:
This is because I had created shell script on windows machine. Before executing it on linux we need to covert it through DOS2Unix utility. OR Just create shell script on Linux and save.
After this it is working fine.
Thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
Read multiple files in Hive table by date range
Let's imagine I store one file per day in a format:
/path/to/files/2016/07/31.csv
/path/to/files/2016/08/01.csv
/path/to/files/2016/08/02.csv
How can I read the files in a single Hive table for a given date range (for example from 2016-06-04 to 2016-08-03)?
A:
Assuming every files follow the same schema, I would then suggest that you store the files with the following naming convention :
/path/to/files/dt=2016-07-31/data.csv
/path/to/files/dt=2016-08-01/data.csv
/path/to/files/dt=2016-08-02/data.csv
You could then create an external table partitioned by dt and pointing to the location /path/to/files/
CREATE EXTERNAL TABLE yourtable(id int, value int)
PARTITIONED BY (dt string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
LOCATION '/path/to/files/'
If you have several partitions and don't want to write alter table yourtable add partition ... queries for each one, you can simply use the repair command that will automatically add partitions.
msck repair table yourtable
You can then simply select data within a date range by specifying the partition range
SELECT * FROM yourtable WHERE dt BETWEEN '2016-06-04' and '2016-08-03'
| {
"pile_set_name": "StackExchange"
} |
Q:
Set method for java not working
So for my assignment it needs to look like this: Assignment
The problem I am facing with this is the setIndent isn't setting the indent but when I mainly change int indent = 20; it will add the indent to the boxes. Also I am confused as to why Rectangle@6bdf28bb is appearing in my code.
Here is my code for the assignment.
Client
// Use this client to help test your Rectangle class for Lab13
// Download it into the same folder as your Rectangle.java file.
// Add other tests if you want to.
public class RectangleClient {
public static void main( String[] args ) {
Rectangle box1 = new Rectangle( 4, 5 );
box1.setIndent(-1);
System.out.println( box1 );
Rectangle box2 = new Rectangle( 6, 12, '+', 'X' );
box2.setIndent( 5 );
System.out.println( box2 );
Rectangle box3 = new Rectangle( 11, 20, '$', 'o' );
box3.setIndent( 20 );
System.out.println( box3 );
}
}
Class
//Using rectangle class to test
public class Rectangle {
public double length;
public double width;
public char fill = ' ';
public char pen = '*';
public int indent;
//Set variables
public void setLength(double len){
if (len <= 0){
throw new IllegalArgumentException("Invalid length for Rectangle object");
}
else{
length = len;
}
}
public void setWidth(double wid){
if (wid <=0){
throw new IllegalArgumentException("Invalid width for Rectangle object");
}
else{
width = wid;
}
}
public void setPen(char c){
pen = c;
}
public void setFill(char c){
fill = c;
}
public void setIndent(int n){
if (n < 0){
indent = 0;
}
else {
indent = n;
}
}
//Get variables
public double getLength(){
return length;
}
public double getWidth(){
return width;
}
public double getIndent(){
return indent;
}
//Main method
public Rectangle (){
int count = 0;
String indents = "";
String topBottom = "";
String middle = "";
String line = "";
//Creates the indent string
while (count<indent){
indents = indents + " ";
count++;
}
//Top boarder and bottom one
count = 0;
while (count<width){
topBottom += pen;
count++;
}
//Fill inside square
width = width - 2;
count = 0;
while (count<width){
middle += fill;
count++;
}
//Prints square
line = pen + middle + pen;
count = 0;
while (count<length){
if (count == 0 || count == length - 1){
System.out.println(indents + topBottom);
count++;
}
else{
System.out.println(indents + line);
count++;
}
}
}
// using default or set fill and boarder
public Rectangle (double l, double w){
int count = 0;
String indents = "";
String topBottom = "";
String middle = "";
String line = "";
//Creates the indent string
while (count<indent){
indents = indents + " ";
count++;
}
//Top boarder and bottom one
count = 0;
while (count<w){
topBottom += pen;
count++;
}
//Fill inside square
w = w - 2;
count = 0;
while (count<w){
middle += fill;
count++;
}
//Prints square
line = pen + middle + pen;
count = 0;
while (count<l){
if (count == 0 || count == l - 1){
System.out.println(indents + topBottom);
count++;
}
else{
System.out.println(indents + line);
count++;
}
}
}
//To set values without using .setWidth etc
public Rectangle (double l, double w, char p, char f){
int count = 0;
String indents = "";
String topBottom = "";
String middle = "";
String line = "";
//Creates the indent string
while (count<indent){
indents += " ";
count++;
}
//Top boarder and bottom one
count = 0;
while (count<w){
topBottom += p;
count++;
}
//Fill inside square
w = w - 2;
count = 0;
while (count<w){
middle += f;
count++;
}
//Prints square
line = indents + p + middle + p;
topBottom = indents + topBottom;
count = 0;
while (count<l){
if (count == 0 || count == l - 1){
System.out.println(topBottom);
count++;
}
else{
System.out.println(line);
count++;
}
}
}
}
The error I'm getting is that it is not adding the indents and the random Rectangle@2ff4f00f
A:
You want to move the printing process of your Rectangle outside of the constructor, otherwise it'll always print immediately upon the use of new Rectangle(...), before you're able to use Rectangle#setIndent(int).
You should instead set the Rectangle fields' values with your constructor, and then have a separate method for printing the Rectangle.
For instance, your constructor which is used to define a specific Rectangle with a custom width, length, pen and fill:
public Rectangle(double l, double w, char p, char f) {
this.length = l;
this.width = w;
this.pen = p;
this.fill = f;
}
This would set the Rectangle instance's fields to the values parsed as arguments when using new Rectangle(...). (Note, you might want to redo your other constructors to comply with this as well).
To visualize it, you could try add the following code to your Rectangle class
@Override
public String toString() {
return getClass().getSimpleName() + "[w: " + width + "; l: " + length +
"; p: " + pen + "; f: " + fill + "; indent: " + indent + "]";
}
And then use the following in your RectangleClient
Rectangle box1 = new Rectangle(4, 5, '+', 'X');
System.out.println(box1);
box1.setIndent(50);
System.out.println(box1);
It should print
Rectangle[w: 5.0; l: 4.0; p: +; f: X; indent: 0]
Rectangle[w: 5.0; l: 4.0; p: +; f: X; indent: 50]
Since we removed the logic for printing the box from the constructor, we should add it somewhere else. With a separate method for printing the Rectangle, you could do something similar to
public void printRectangle() {
int count = 0;
String indents = "";
String topBottom = "";
String middle = "";
String line = "";
// Creates the indent string
while (count < indent) {
indents += " ";
count++;
}
// Top boarder and bottom one
count = 0;
while (count < this.width) {
topBottom += this.pen;
count++;
}
// Fill inside square
this.width = this.width - 2;
count = 0;
while (count < this.width) {
middle += this.fill;
count++;
}
// Prints square
line = indents + this.pen + middle + this.pen;
topBottom = indents + topBottom;
count = 0;
while (count < this.length) {
if (count == 0 || count == this.length - 1) {
System.out.println(topBottom);
count++;
} else {
System.out.println(line);
count++;
}
}
}
This is basically just the logic from your constructor, just with the exception that instead of using the local variables (passed as arguments), we use the Rectangle instance's field values instead (e.g. this.width instead of w).
Maybe your instructor explicitly wanted you to override the #toString() method, and inside the overridden method, you'd have your logic for printing the Rectangle. If that is the case, you'd of course just move the logic from the #printRectangle() to the overridden #toString() method, which would allow you to use System.out.println(box1) (replace the previous sampled #toString() method, of course).
@Override
public String toString() {
// Logic from #printRectangle() here
}
If you choose to override #toString(), you should not use System.out.println in the logic, but rather build a string, which you'll return at the end of the #toString() logic. You could take a look at StringBuilder for this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Inequality problem: with $x,y,z>0$, show that $\frac{x^5}{y^3}+\frac{y^5}{z^3}+\frac{z^5}{x^3}\geq x^2+y^2+z^2$
I am studying AM-GM inequalities in school and have this problem:
With $x,y,z>0$ show that $\frac{x^5}{y^3}+\frac{y^5}{z^3}+\frac{z^5}{x^3}\geq x^2+y^2+z^2$.
A:
Idea behind the solution
By AM-GM you have for each $\alpha, \beta, \gamma \in \mathbb N$
$$\frac{\alpha\frac{x^5}{y^3}+\beta\frac{y^5}{z^3}+\gamma\frac{z^5}{x^3}}{\alpha+\beta+\gamma}\geq \sqrt[\alpha+\beta+\gamma]{(\frac{x^5}{y^3})^\alpha(\frac{y^5}{z^3})^\beta(\frac{z^5}{x^3})^\gamma}$$
Then by symmetry you can permute circularly the coefficients and add the inequalities.
Now, set the RHS $=x^2$. This yields
$$5 \alpha -3 \gamma = 2\alpha+2\beta+2\gamma \\
5 \beta- 3 \alpha=0 \\
5 \gamma -3 \beta =0
$$
Since the third equation is the sum of the first two (this comes from the fact that your inequality is homogeneous) your system has infinitely many solutions. Solving you get
$$9 \alpha =15 \beta =25 \gamma$$
In particular the following is a solution:
$$\alpha=25 \\
\beta =15 \\
\gamma=9$$
The solution
By AM-GM you have
$$\frac{25\frac{x^5}{y^3}+15\frac{y^5}{z^3}+9\frac{z^5}{x^3}}{49}\geq \sqrt[49]{(\frac{x^5}{y^3})^{25}(\frac{y^5}{z^3})^{15}(\frac{z^5}{x^3})^{9}}=x^2\\
\frac{9\frac{x^5}{y^3}+25\frac{y^5}{z^3}+15\frac{z^5}{x^3}}{49}\geq \sqrt[49]{(\frac{x^5}{y^3})^{9}(\frac{y^5}{z^3})^{25}(\frac{z^5}{x^3})^{15}}=y^2\\
\frac{15\frac{x^5}{y^3}+9\frac{y^5}{z^3}+25\frac{z^5}{x^3}}{49}\geq \sqrt[49]{(\frac{x^5}{y^3})^{15}(\frac{y^5}{z^3})^{9}(\frac{z^5}{x^3})^{25}}=z^2\\
$$
Add them together.
A:
By AM-GM $$2x^5+3y^5\geq5\sqrt[5]{(x^5)^2(y^5)^3}=5x^2y^3,$$ which gives
$$\frac{x^5}{y^3}\geq\frac{5x^2-3y^2}{2}.$$
Id est, $$\sum_{cyc}\frac{x^5}{y^3}\geq\sum_{cyc}\frac{5x^2-3y^2}{2}=\sum_{cyc}x^2.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
What library or project generator to use for a first STM32F3 project?
I'm about to start my first STM32 project. (I have previously used atmega MCUs, and have decades of experience with C, mostly server-side.)
There seem to be three choices, given that I want to develop on the command-line in Linux, using make.
an STM32CubeMX generated makefile project,
an STM32CubeMX generated makefile project, including FreeRTOS, or
a makefile project using libopencm3.
The application will process and send messages on 4 or more serial ports, using different protocols. Occasionally GPIOs will be set or cleared.
My questions are:
Why does libopencm3 exist? Why would someone choose it over an STM32CubeMX-generated makefile project.
Is learning FreeRTOS worthwhile for such a project?
A:
There are no good free project generation tools that I know. I worked mostly with STM32CubeMX and I can tell you that it's surely useful (expecially for novices) but long from being something you can trust on. I found lots of bugs in it in the years, some has been fixed, others are still in there. IMHO, in general, you should use code generator tool with care better as a training instrument maybe taking snippets of code out of them.
I've used FreeRTOS a lot and I can tell you I feel good with it. Maybe it's not good as as a commercial grade product but surely it's well documented and easy to handle. Haven't had any problem with it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nullpointer exception error for using split and comma operators
I want to store the values HTRANS and HBURST in one list and 2'b00 and 3'b000 in another list. But i am getting a null pointer exception in the code which i have written, I have written an SSCCE for the same, please help.
import java.util.ArrayList;
import java.util.List;
public class SSCCE1 {
public static void main(String[] args) {
List<String> bins = new ArrayList<String>();
bins.add("HTRANS = 2'b00 to 2'b11");
bins.add("HTRANS = 2'b00 to 2'b11, HBURST = 3'b000 to 3'b111");
String[] bins_splitcomma = null;
String temp;
for(int i =0; i < bins.size(); i++) {
temp = bins.get(i);
if(temp.contains(",")) { // if element of bins contains comma, case 2.
bins_splitcomma = temp.split(",");
}
else {
bins_splitcomma[0] = temp; // if element of bins does not contain a comma, case 1.
}
}
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at codecoveragetool.SSCCE1.main(SSCCE1.java:28)
Java Result: 1
My full code:
String temp1;
String[] bins_splitcomma = null;
String[] bins_split;
List<String> bins_name = new ArrayList<String>();
List<String> bins_bitrange = new ArrayList<String>();
//List<String> bins_bits = new ArrayList<String>();
ArrayList<ArrayList<String>> bins_bits = new ArrayList<ArrayList<String>>();
List<String> bins = dataStr.get("bins");
System.out.println(bins);
for(int i =0; i < bins.size(); i++) {
temp1 = bins.get(i);
if(temp1.contains(",")) {
bins_splitcomma = temp1.split(",");
}
else {
bins_splitcomma = new String[]{temp1};
}
for(int j = 0; j < bins_splitcomma.length; j++) {
bins_split = bins_splitcomma[j].split("="); // HBURST = 3'b000 to 3'b111
if(!(bins_name.contains(bins_split[0].trim()))) {
bins_name.add(bins_split[0].trim()); // HBURST
bins_bitrange.add(bins_split[1].trim()); // 3'b000 to 3'b111
ArrayList<String> tempo = returnBits(bins_split[1].trim()); // [3'b000, 3'b001, 3'b010, 3'b011, ... , 3'b111]
bins_bits.add(tempo);
}
}
}
A:
Your line
bins_splitcomma[0] = temp;
is trying to set an element of a null array as defined in your line
String[] bins_splitcomma = null;
A:
As you first element does not contain ,, so your code will go in else statement which will try to put value at 0th position of bins_splitcomma. But you never initialized it. Try this code
...
else {
if (bins_splitcomma == null) {
bins_splitcomma = new String[5];
}
bins_splitcomma[0] = temp; // if element of bins does not contain a comma, case 1.
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Showing that a topological space is ${\rm T}_1$
Let $X$ be a topological space and let $\Delta = \{(x,x) : x\in X \}$ be the diagonal of $X\times X$ (with the product topology).
I was asked to prove that $X$ is ${\rm T}_1$ if and only if $\Delta$ can be written as intersection of open subsets of $X\times X$.
I think is better (maybe easier) to use the well-known result "$X$ is ${\rm T}_1$ if and only if $\{x\}$ is a closed set $\forall x\in X$".
What I've done:
Assuming that $X$ is ${\rm T}_1$, let $Y=(X\times X) \setminus\Delta$ and note that (trivially)
$$Y = \bigcup_{y\in Y} \{y\}.$$
Then
$$\Delta = (X\times X) \setminus Y = (X\times X) \setminus \left(\bigcup_{y\in Y} \{y\} \right) = \bigcap_{y\in Y} (X\times X)\setminus \{y\},$$
where $(X\times X)\setminus\{y\}$ is open since each $\{y\}$ is closed.
The other direction seems be a bit harder, I've tried unsuccessfully. Any ideas?
Thanks in advance.
A:
Suppose that
$$\Delta = \bigcap \{O_i: i\in I\}$$ for some index set $I$, and all $O_i$ open in $X \times X$.
Let $x\neq y$, to show $T_1$-ness, we need to find an open set $O$ of $X$ that contains $x$ but misses $y$. So consider $(x,y)$, which is not in $\Delta$, so there is an $i \in I$ such that $(x,y)\notin O_i$.
Now $(x,x) \in \Delta \subseteq O_i$, so by using the product base we can find an open set of the form $U\times V$ that contains $(x,x)$ and sits inside $O_i$.
But then $O=U \cap V$ contains $x$ but not $y$, as $y \in U \cap V$ would imply $(x,y) \in U \times V \subseteq O_i$, while we had $(x,y) \notin O_i$ by choice of $i$. So we have our open set as required.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you define a generic getter method in Typescript with multiple overloads?
I'm trying to define a method that operates as a getter, taking an optional parameter. The getter provides access to an object of type T, and should return either the entire object, or a property on that object.
The challenge is that I am trying to defined the method in two places, first in an interface, and second in the actual implementation.
Here's my approach:
// Getter defines both overloads
interface StoreGetter {
<T>(): T;
<T, K extends keyof T>(prop: K): T[K];
}
// Store has a generic type, and exposes that type and properties on that type
interface Store<T> {
get: StoreGetter;
// Either one works individually
// get: <T>() => T;
// get: <T, K extends keyof T>(prop: K) => T[K];
}
export function makeStore<T>(initial: T): Store<T> {
let value: T = initial;
// Apparently, you can only define overloads via a function declaration
// function get<T>(): T;
// function get<T, K extends keyof T>(prop: K): T[K];
function get(prop?: keyof T) {
if (typeof prop !== 'undefined') {
return value[prop];
}
return value;
}
return {
get,
};
}
const store = makeStore({
text: '',
items: [],
num: 1
});
// Argument of type '"text"' is not assignable to parameter of type 'never'.(2345):
store.get('text')
// Object is of type 'unknown'.(2571)
store.get().
Unfortunately, the two definitions seem to clobber each other.
How can I define this method with overloads, and have correct type inference for both calls?
A:
After many failed attempts, I've discovered one configuration that produces the expected inferences:
interface StoreGetter<T> {
(): T;
<K extends keyof T>(props: K): T[K];
}
interface Store<T> {
get: StoreGetter<T>;
set: (val: any | T) => void;
}
export function makeStore<T>(initial: T): Store<T> {
let value: T = initial;
let listeners: Function[] = [];
function get(): T;
function get<K extends keyof T>(prop: K): T[K];
function get(prop?: keyof T): T | T[keyof T] {
if (typeof prop !== 'undefined') {
return value[prop];
}
return value;
}
return {
get,
set: (val: any) => {
value = {
...value,
...val,
};
listeners.forEach(fn => fn(value));
}
};
}
const store = makeStore({
text: '',
items: [],
num: 1
});
// Both work with type inference
store.get('text').toUpperCase
store.get().items
Still hoping to find a way to do it with an inline/anonymous function.
On a positive note, this approach works seamlessly in a declarations file (e.g., store.d.ts), enabling the use of a single declaration:
interface StoreGetter<T> {
(): T;
<K extends keyof T>(props: K): T[K];
}
interface Store<T> {
get: StoreGetter<T>;
}
export function makeStore<T>(initial: T): Store<T>;
export function useStore<T>(store: T, prop?: string): [T|any, (newState: T|any) => void];
And then in a separate JS file:
const store = makeStore({
keypresses: 0,
text: '',
arrows: [],
});
// Both inferred:
store.get('keypresses').toFixed
store.get().arrows.push
This produces the expected annotations in VS code:
| {
"pile_set_name": "StackExchange"
} |
Q:
C: My struct's properties don't change when referenced from an Array?
I'm having trouble with an array in C that is supposed to hold several structs I defined earlier;
The Struct:
typedef struct
{
bool alive;
struct Vector velocity;
struct Vector acceleration;
struct Coordinate position;
float mass;
int ID;
}Sprite;
The Array:
Sprite Sprites[10];
To make creating structs easier, I have a function that creates them for me:
Create Struct Function:
Sprite createNewSpriteWithID(int ID, int Mass)
{
Sprite newSprite;
newSprite.ID = ID;
newSprite.mass = Mass;
newSprite.velocity = VectorWithZero();
newSprite.acceleration = VectorWithZero();
newSprite.alive = 1;
int index = returnAvailableSpriteIndex();
if (index < 11 && index > -1){
Sprites[index] = newSprite;
printf("Sprite inserted at Index: %d\n",index);
spriteCount += 1;
} else {
printf("Notice: Sprite not added");
}
return Sprites[index]; // FIXED MY BAD
}
This function makes me a new Struct, and then I assign values to some of the properties. However, I do not do this to position, because I want to change this myself.
The Problem:
The issue is that when I attempt to change the positions myself, they are not reflected in the array.
int main(int argc, const char * argv[]) {
// Create a test Sprites.
Sprite Sprite_A;
// Set Sprite Positions and parameters
Sprite_A = createNewSpriteWithID(1,300);
setPositionForSprite(&Sprite_A,100,100);
printf("\nPOS: %f, %f\n",Sprite_A.position.x,Sprite_A.position.y);
return 0;
}
I call a function called setPositionForSprite, which assigns a position to the position property of the passed sprite pointer.
Set Position:
void setPositionForSprite(Sprite *S, float x, float y)
{
S->position.x = x;
S->position.y = y;
}
This is where the problem becomes apparent. When I sprite the position shortly after assigning it in Main, it comes out as intended
100,100
However, when I print the Sprites[index_of_Sprite_A], it gives me garbage values. Why is this happening?
I can fix it by changing the change-position line inside main to:
setPositionForSprite(&Sprites[0],100,100);
But It is unfeasible as I have to recall what the index was.
Why doesn't changing the properties of my struct variable change them in the array?
A:
In your createNewSpriteWithID() function, you're returning 1.
Again, Sprite newSprite; is local to createNewSpriteWithID(). You cannot return the address of newSprite, either.
Instead, you need to have a pointer to Sprite, allocate memory dynamically and return that pointer. Along with that, you need to change the return type of createNewSpriteWithID() to Sprite * and collect the same in another Sprite *.
Also, with a definition like Sprite Sprites[10];
if (index < 11 && index > -1){
Sprites[index]....
is wrong. Array index in c starts from 0. You need to change to
if (index < 10 && index > -1){
EDIT
well, your changes are not reflected in the original array because, from your createNewSpriteWithID() function, you're returning the array element value which is then collected in a local variable inside your main(). When you call setPositionForSprite(), you're passing the address of the local variable in the main(), so the change is being reflected in the local variable in the main(), not in the array element.
To rectify, use a pointer [i.e., return the address of the element in the array], as I suggested above.
| {
"pile_set_name": "StackExchange"
} |
Q:
XDocument: Create custom declaration
I want to create Windows Media Player playlist files with XDocument. Therefore I have to create this declaration:
<?wpl version="1.0"?>
However, the XDeclaration object doesn't allow to replace "xml" with "wpl". Is there a proper way to handle this?
A:
That's a processing instruction, not an XML declaration.
new XProcessingInstruction("wpl", "version=\"1.0\"")
Your document is still an XML document, so you can additionally include <?xml version="1.0"?> at the top, but that's optional.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get my android USSD program to work
am building a simple dialler to help me check my account balance but for some unknown reasons am getting some errors, i have a button on my xml which i have set its onclick element to sendMessage1 , but am getting error on my code with the phoneNum[1] telling me cannot reslove symbol phoneNum[1]. this is my code
/**Called when the user clicks the Send button */
public void sendMessage1(View view){
//example phoneNum[1] = "*556";
String encodedHarsh = Uri.encode("#");
startActivity(new Intent
("android.intent.action.DIAL",
Uri.parse("tel:"+ phoneNum[1]+ encodedHarsh)));
//Do something in response to button
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mtn);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_mtn, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
A:
You have to do it doing this :
String encodedHarsh = "*" + "556" + Uri.encode("#");
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:" + encodedHarsh)));
Note, don't forget to add uses-permisions on manifest
| {
"pile_set_name": "StackExchange"
} |
Q:
Uploading Image to Firebase Storage and Database
I want to put the download URL of images into my Firebase Database. I can upload the Image into storage but I can't figure out how to get the URL into my database with the rest of the "post".
@IBOutlet weak var titleText: UITextField!
@IBOutlet weak var authorText: UITextField!
@IBOutlet weak var mainText: UITextView!
@IBOutlet weak var dateText: UITextField!
@IBOutlet weak var myImageView: UIImageView!
var ref:FIRDatabaseReference?
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func uploadImage(_ sender: Any) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.photoLibrary
image.allowsEditing = false
self.present(image, animated: true)
{
//after its completed
}
}
@objc(imagePickerController:didFinishPickingMediaWithInfo:) func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
myImageView.image = image
}
else
{
//error
}
self.dismiss(animated: true, completion: nil)
let storageRef = FIRStorage.storage().reference().child("myImage.png")
if let uploadData = UIImagePNGRepresentation(self.myImageView.image!){
storageRef.put(uploadData, metadata: nil, completion:
{
(metadata, error) in
if error != nil {
print("error")
return
}
print(metadata)
//how do I put the download URL in the metadata into my database
}
)
}
}
@IBAction func addPost(_ sender: Any) {
if self.titleText.text != "" && self.authorText.text != "" && self.mainText.text != "" && self.dateText.text != ""
{
ref?.child("Posts").childByAutoId().setValue(["Title": titleText.text,"Article": mainText.text, "Author": authorText.text, "Date": dateText.text, "myImageURL": myImageURL])
//the myImageURL part is where I get an error
self.performSegue(withIdentifier: "post", sender: self)
}
else{
let alertController = UIAlertController(title: "Oops!", message: "Field left blank", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
A:
Organize your upload and save funcs like this:
func uploadMedia(completion: @escaping (_ url: String?) -> Void) {
let storageRef = FIRStorage.storage().reference().child("myImage.png")
if let uploadData = UIImagePNGRepresentation(self.myImageView.image!) {
storageRef.put(uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("error")
completion(nil)
} else {
completion((metadata?.downloadURL()?.absoluteString)!))
// your uploaded photo url.
}
}
}
Next just connect to FIRDatabase and save it to your node.
@IBAction func addPost(_ sender: Any) {
if self.titleText.text != "" && self.authorText.text != ""
&& self.mainText.text != "" && self.dateText.text != "" {
uploadMedia() { url in
guard let url = url else { return }
ref?.child("Posts").childByAutoId().setValue([
"Title" : titleText.text,
"Article" : mainText.text,
"Author" : authorText.text,
"Date" : dateText.text,
"myImageURL" : url
])
}
}
You can also look at my answer about uploading data and saving URL's to database
Hope it helps
A:
For Updated Firebase Version And Swift 4.2 Code :
func uploadMedia(completion: @escaping (_ url: String?) -> Void) {
let storageRef = Storage.storage().reference().child("\(Auth.auth().currentUser?.uid ?? "").png")
if let uploadData = self.imgUploadView.image?.jpegData(compressionQuality: 0.5) {
storageRef.putData(uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("error")
completion(nil)
} else {
storageRef.downloadURL(completion: { (url, error) in
print(url?.absoluteString)
completion(url?.absoluteString)
})
// completion((metadata?.downloadURL()?.absoluteString)!))
// your uploaded photo url.
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to configure db-reverse-engineer plugin
I am a total Grails noob trying to configure the db-reverse-engineer plugin for my first project. Documentation for the plugin indicates that I need to configure it, but I don't see where I am supposed to edit configuration.
Is there a configuration file in my project I need to edit? I have searched through the ./grails-app/conf folder for grails.plugin (the prefix for this plugin's configuration) and found nothing. An SO or Google search for how to configure grails plugins also returns void. I know this is a lame question, but how do I configure this plugin? Is there a UI I need to use, or are there files somewhere to edit?
A:
You need to configure your database in grails-app/conf/DataSource.groovy. In particular, you'll need to provide the JDBC URL, the database dialect and the databases's username and password.
You'll also have to add some extra db-reverse-engineer configuration to grails-app/conf/Config.groovy. This file will already exist. Just append the new properties at the end.
Finally, run the reverse engineer script to generate your domain classes:
grails db-reverse-engineer
| {
"pile_set_name": "StackExchange"
} |
Q:
Mapping deeply nested array properties
Example jsFiddle
I have a model that is a Calendar at the root level. This Calendar contains many days, each Day contains an Event, each Event contains attendees and each Attendee has 0 or more Intolerances.
So it looks like this:
function Calendar(data) {
this.days = ko.observableArray(data.days);
}
function Day(data) {
this.date = ko.observable(data.date);
this.event = ko.observable(data.event);
this.daysToEvent = ko.computed(function () {
var diff = Math.abs(new Date(), this.date());
return (((diff / 1000) / 60) / 60) / 24;
}, this);
}
function Event(data) {
this.name = ko.observable(data.name);
this.attendees = ko.observableArray(data.attendees);
}
function Attendee(data) {
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
this.intolerances = ko.observable(data.intolerances);
}
function Intolerance() {
this.id = ko.observable(data.id);
}
I'm passing a JSON string to this model and using the ko.mapping plugin (just started using it) to wire it all up. What I'm not understanding though is how can I tell the plugin to use my objects during mapping?
I'm aware of the mapping options param, but at the moment I'm a newbie so not really "getting it" so to speak. I've attempted with this:
var viewModel = {
calendar: null,
loadCalendar: function () {
ko.mapping.fromJSON(json, {
create: function (opts) {
return new Calendar({ days: opts.data.calendar })
}
}, viewModel.calendar);
}
};
Which gets my my Calendar object and the days, but how (and what is the most correct way) do I further map my classes down the tree?
A:
You can put the mapping code inside the ViewModels themself:
function Calendar(data) {
this.days = ko.observableArray();
// update the current ViewModel with the given data
if (data) {
ko.mapping.fromJS(data, {
days: {
// tell the mapping plugin how to create the days
create: function(options) {
return new Day(options.data);
}
}
}, this);
}
}
function Day(data) {
this.date = ko.observable();
this.event = ko.observable();
if (data) {
ko.mapping.fromJS(data, {
event: {
create: function(options) {
return new Event(options.data);
}
}
}, this);
}
this.daysToEvent = ko.computed(function () {
var diff = Math.abs(new Date(), this.date());
return (((diff / 1000) / 60) / 60) / 24;
}, this);
}
...
| {
"pile_set_name": "StackExchange"
} |
Q:
TypeScript no error on non-matching return value
Why doesn't TypeScript complain about this?
async GetCategoriesBySet(set: Set): Promise<Result<Array<ProductCategory>>> {
let categories: Array<ProductCategory> = []
if (!set.theme || !set.subtheme || !set.title) {
return Promise.resolve(new Result<Array<ProductCategory>>({res: null, err: "Set data is not valid"}))
}
categories.push(await this.GetCategory(set.theme, {parent: (await this.GetCategory('Themes')).id}))
return categories
}
The return value, categories, is of type Array<ProductCategory>, not a Promise, or even the wrapping Result class. So why is it happy to let me make this mistake? (And is there any way to get it to complain?)
Thanks in advance
A:
The return value, categories, is of type Array, not a Promise,
All async functions return a Promise. This is a part of the JavaScript spec. If you return a constant it is essentially Promise.resolveed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flood fill algorithm
I am implementing a flood fill algorithm using Python and NumPy. I have written the following fill function which works fine:
def fill(self, data, xsize, ysize, x_start, y_start):
stack = [(x_start, y_start)]
while stack:
x, y, stack = stack[0][0], stack[0][1], stack[1:]
if data[x, y] == 1:
data[x, y] = 2
if x > 0:
stack.append((x - 1, y))
if x < (xsize - 1):
stack.append((x + 1, y))
if y > 0:
stack.append((x, y - 1))
if y < (ysize - 1):
stack.append((x, y + 1))
I wanted to implement a way that would eliminate the need to re-check a point if it had already been checked. By creating a new list of checked points and then comparing to see if the current point is already in that list, but this ended up making it slower and I wanted to understand if there is a more efficient way to improve upon my existing implementation.
A:
Instead of using a list to store your points (which has an \$O(n)\$ look-up time), you can use a set object which has an \$O(1)\$ look-up time. For more information regarding Pythonic time complexity, you can look here.
I have a couple comments on your style:
Instead of x and y, I would use column/col and row. Even though x and y are mathematical coordinate names, I still prefer to be more explicit.
Group declarations are OK in the right circumstances, like unpacking an iterator or defining groups of like variables. The way you do this doesn't quite fit into the 'right circumstances' category: you are assigning and then slicing.
To get a better implementation, there are a couple of options:
Split the statement into its components (assigning x, y and slicing the list)
Calling list.pop() to do both at the same time
These two options, in terms of efficiency, are probably identical. So, its up to you to choose which one you want to use. Here is their syntax:
# 2 statements.
col, row = stack[0]
stack = stack[1:]
# Using `pop`.
col, row = stack.pop(0)
In Python 3, use the * operator to unpack the list
This option is the least applicable (due to your comments below). However, for reference here is that syntax:
(col, row), *stack = stack
This assigns the first element of the stack to (col, row) and the rest to itself, effectively popping off the first element.
P.S. Congratulations. This is probably my shortest review on this site.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to recursively traverse a tree and create a list of visited nodes in python
I have defined a class Tree which consists of a list of TreeNodes as below:
class Tree(object):
def __init__(self, name, nodes):
self.name = name
self.nodes = nodes
class TreeNode(object):
def __init__(self, name, parent):
self.name = name
self.parent = parent
As you can see, for each TreeNode I only define a single parent node. However, I want to write a Tree method that gives me a list of all parent nodes of a target node called targetNodeName (the output list should also include targetNodeName itself). For this, I have written a recursive function that iterates until a node with no parent is found (i.e. the root node) while building a list called results.
def allParents(self, targetNodeName, results):
currentNode = next((node for node in self.nodes if node.name == targetNodeName))
results.append(currentNode.name)
if (currentNode.parent == None):
print results
return results
else:
return results.append(self.allParents(currentNode.parent, results))
However my recursive function does not perform as intended. I give an example where I first define a three-level, 7-node tree and then call the allParents method to get all parent nodes of node 'N7' i.e. ['N7', 'N3', 'N1'].
# create nodes
myTreeNodes = []
myTreeNodes.append(TreeNode(name = 'N1', parent = None))
myTreeNodes.append(TreeNode(name = 'N2', parent = 'N1'))
myTreeNodes.append(TreeNode(name = 'N3', parent = 'N1'))
myTreeNodes.append(TreeNode(name = 'N4', parent = 'N2'))
myTreeNodes.append(TreeNode(name = 'N5', parent = 'N2'))
myTreeNodes.append(TreeNode(name = 'N6', parent = 'N3'))
myTreeNodes.append(TreeNode(name = 'N7', parent = 'N3'))
myTree = Tree(name = 'ST1', nodes = myTreeNodes)
a = myTree.allParents(targetNodeName = 'N7', results = [])
print a
> ['N7', 'N3', 'N1']
> None
Although it prints out the correct list of parent nodes -note the 'debug' print command in the function- (i.e. ['N7', 'N3', 'N1']), the function returns None, meaning that i am dropped off the function with nothing to return. How can I fix this?
A:
Use is for checking if the value equals None or not.
The allParents method can be simplified as following:
def allParents(self, targetNodeName):
currentNode = next(node for node in self.nodes
if node.name == targetNodeName)
if currentNode.parent is None:
return [currentNode.name]
else:
return [currentNode.name] + self.allParents(currentNode.parent)
| {
"pile_set_name": "StackExchange"
} |
Q:
Perl GetOptions Function
My Perl Script retrieves the argument in the below way. Have Getoptions function to retrieve the command line arguments.
./test.pl -mode report -writeid 12 13 23......
$rc=GetOptions( 'mode=s' => \$cmdParams{mode}
,'writeid:i{1,}' => \@writeid
,'h|?|help' => \$help
);
The problem is when i have alphanumeric characters in the writeid option it's not failing. Writeid is defined as integer ( i{1,}) and it can receive 1 to many values. It doesn't fail when i have alphanumeric character in the second value.
./test.pl -mode report -writeid 12 A3 23......
What is the workaround i can do?
A:
As you are using the GetOptions function I assume you are using GetOpts::Long, the trouble with the "{1,}" one or more quantity in the option specification is that once you've successfully matched an integer, you've "succeeded". if you removed the quantitive spec and just ran with 'writeid:i' => \@writeid, each write_id would have to be preceded by the flag on the command line and so you would get an error state when it failed to parse.
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql CREATE TRIGGER after insert on Update column with count
it gives error. I don't understand why.
CREATE TRIGGER `estatecat_piece` AFTER INSERT ON `estate`
FOR EACH ROW
BEGIN
UPDATE estate_category set piece = (Select count(*) from estate where estate.estatecat_id=new.estatecat_id);
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '' at line 1
-EDIT-
agian error...
mysql> DELIMITER ; CREATE TRIGGER `estatecat_piece` AFTER INSERT ON `estate` FOR EACH ROW BEGIN UPDATE estate_category set piece = (Select count(*) from estate where estate.estatecat_id=new.estatecat_id); END; DELIMITER ;
mysql>
mysql> show triggers;
Empty set (0,00 sec)
_ LAST ATTEMPT'S ERROR _
mysql> DELIMETER $$ -> CREATE TRIGGER estatecat_piece
-> AFTER INSERT ON estate FOR EACH ROW
-> BEGIN
-> UPDATE estate_category set piece = (Select count(*) from estate where estate.estatecat_id=new.estatecat_id) where estatecat_id=new.estatecat_id;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMETER $$
CREATE TRIGGER estatecat_piece
AFTER INSERT ON estate FOR EACH ROW ' at line 1
A:
The immediate issue with your first statement is that it has BEGIN without a corresponding END. In this case, END should be at the very end of the CREATE TRIGGER statement.
Once you add the END keyword, the statement becomes technically correct, but you will have trouble executing it in MySQL. The reason is that semicolons, while being standard statement delimiters in SQL, are also treated by MySQL in a special way. MySQL splits the input text at semicolons and sends each part of the text to the server separately. The server thus receives incomplete, syntactically incorrect pieces and returns an error. See here for more details:
Defining Stored Programs
So, to prevent MySQL from doing that, you need to instruct it to use a different symbol as a delimiter – that is what the DELIMITER command is for. Consequently, your second attempt should be something like this:
DELIMITER $$
CREATE TRIGGER `estatecat_piece`
AFTER INSERT ON `estate`
FOR EACH ROW
BEGIN
UPDATE estate_category set piece = (Select count(*) from estate where estate.estatecat_id=new.estatecat_id);
END$$
DELIMITER ;
The first DELIMITER command tells MySQL to parse the input text until $$ is encountered from that point on. Your CREATE TRIGGER should, therefore, end with the $$ symbol so that MySQL can consume it in its entirety and send the whole statement to the server. Finally, the second DELIMITER command restores the standard delimiter for MySQL to resume normal processing of your commands.
There is also a simpler solution, but it works only in cases similar to yours. The trigger body in your case consists of a single statement. That allows you to omit the keywords BEGIN and END from your statement and, as a result, avoid using the DELIMITER command at all:
CREATE TRIGGER `estatecat_piece`
AFTER INSERT ON `estate`
FOR EACH ROW
UPDATE estate_category set piece = (Select count(*) from estate where estate.estatecat_id=new.estatecat_id);
The above trigger will work exactly the same.
On a different note, your UPDATE statement may have a flaw: as currently written, it will update the piece column in every row with the same row count – that of the category matching the inserted row. If the table has multiple rows, each for a different category, you probably need to introduce a filter on new.estatecat_id to your UPDATE statement, similar to the filter in the subquery, in order to update only the corresponding piece value:
UPDATE
estate_category
SET
piece = (
SELECT
COUNT(*)
FROM
estate
WHERE
estate.estatecat_id=new.estatecat_id
)
WHERE
... /* specify the necessary column name */ = new.estatecat_id
;
| {
"pile_set_name": "StackExchange"
} |
Q:
When is my date of birth?
___4,_4,_4
This is my real date of birth, because it looks unique, I try to do a simple operation, and I get a number 222.
In fact it is able to solved without looking at the hint, but I'm trying to make this puzzle easy.
Hint:
??+?4+,?4+,?4 = 141
When is my date of birth? And how is the number 222 obtained
from the calculation results?
The main purpose of this puzzle is not just for someone to answer it, but I hope someone can also improve what is needed
A:
From the hint:
We start from $??+?4+?4+?4 = 141$, or in better notation $AB+C4+D4+E4 = 141$.
Taking everything modulo 10, we get $B+12\equiv1$, so $B=9$.
Since $D4$ is a month, we must have $D=0$ (there is no 14th month).
Assuming you're not from the distant past or future (e.g. born in the 10th or 30th century), we must have $A=1$.
Now the equation is $19+C4+04+E4=141$, so $C+E=11$. We also know that $E$ must be $0$ or $1$ or $2$, so the only option is $C=9,E=2$.
So your date of birth is
1994/04/24 or 24 April 1994.
If you want feedback, I would say that this isn't doable without the hint. Certainly not uniquely solvable, when you don't specify what types of operations are allowed. Following this site's generic advice on formation-of-numbers questions, I'd advise you to restrict the possible operations which are permitted to be used in getting from the birthdate to 222. E.g. is it just $+,-,\times,\div$? Are $\sqrt{},!,\lfloor\,\rfloor, \exp$ also allowed? You need to have a clear finite list, otherwise there are too many thinking-outside-the-box possibilities.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is nesting ARM Thumb2 "IT" instructions well defined?
If I have an ARM Thumb 2 instruction stream that looks like the following:
itt NZ
mov r1,r2
it MI
mov r3,r4
The IT block of the first IT instruction contains mov and a second it. Is this sequence allowable, or is it undefined behavior?
A:
An IT block must not contain another IT instruction. The result of your code is unpredictable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Vertical scroll Scintilla Textbox during Text Changed event
Setting a Scintilla.Net textbox with a string and scrolling to last line doesn't work.
This Q & A How make autoscroll in Scintilla? has the answer but it wont work at the same time as setting the text.
Bare bones repro:
private void button1_Click(object sender, EventArgs e)
{
string s = RandomString(400);
scintilla1.Text = s + " " + s + " " + s + " " + s + " " + s;
scintilla1.Scrolling.ScrollBy(0, 10000); //<-doesn't work (but does work eg in a Button2_click)
}
private static Random random = new Random((int)DateTime.Now.Ticks);
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
Does anyone know how to scroll vertically down to end line after setting the text?
A:
Well you can try to put Refresh() after adding the text;
scintilla1.Text = s + " " + s + " " + s + " " + s + " " + s;
scintilla1.Refresh();
for this case i found out that you will need to Refresh() twice depend on the length of the string you put on the textbox.
| {
"pile_set_name": "StackExchange"
} |
Q:
Time conversion Not working properly?
I am using the ionic time picker in my project. When I select the time picker it passes a value to the controller. For example when I select 09:00pm, the console shows 79200. If I select 07:00pm the console shows 68400. I want to convert the value to 12 hrs format. I have followed some steps, but it's not working for me.
My code:
var a = new Date($scope.timePickerObject12Hour.inputEpochTime*1000);
console.log(a);
var b = moment.utc(a).format("HH:mm");
console.log(b)
$scope.timePickerObject12Hour.inputEpochTime = val;
console.log(val);
//var yourDateObject = new Date();
var selectedTime = new Date();
var amPmHour = $filter('date')(selectedTime, 'hh');
console.log(amPmHour);
$scope.time = $filter('date')(new Date(val*1000), 'hh:mma');
console.log($scope.time);
console.log('Selected epoch is : ', val, 'and the time is ', selectedTime.getUTCHours(), ':', selectedTime.getUTCMinutes(), 'in UTC');
I tried the code above, but nothing is working. Below i have added my origional code:
$scope.timePickerObject12Hour.inputEpochTime = val;
console.log(val);
console.log('Selected epoch is : ', val, 'and the time is ', selectedTime.getUTCHours(), ':', selectedTime.getUTCMinutes(), 'in UTC');
on the first console.log i am getting 68400,
for second console log I am getting 68400 and the time is 19:00 in UTC. How to convert 12 hr format for the selected time?
A:
I assume you want the result as a string. Here is a simple implementation with moment.js:
var secs = 68400;
console.log(moment().startOf('day').add(secs, 'seconds').format("h:mm a"));
Will output "7:00 pm"
See in plunker http://plnkr.co/edit/D0ai2PpEhnuJkTYblW29?p=preview
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I calculate the intersection between two cosine functions?
$f(x) = A_1 \cdot \cos\left(B_1 \cdot (x + C_1)\right) + D_1$
$g(x) = A_2 \cdot \cos\left(B_2 \cdot (x + C_2)\right) + D_2$
Is it possible at all to solve this analytically? I can start doing this but I get stuck half way.
$A_1 \cdot \cos\left(B_1 \cdot (x + C_1)\right) + D_1 = A_2 \cdot \cos\left(B_2 \cdot (x + C_2)\right) + D_2$
$\Longleftrightarrow A_1 \cdot \cos\left(B_1 \cdot (x + C_1)\right) - A_2 \cdot \cos\left(B_2 \cdot (x + C_2)\right) = D_2 - D_1$
I'm not sure how to use arccosine on this expression. Therefore I'm asking for help to solve this.
Thanks in advance!
A:
Substituting $\xi:=B_1(x+C_1)$ brings it to the fundamental form
$$ \cos (\xi) = p\cos (a\xi+b)+q$$
with $p=\frac{A_2}{A_1}$, $q=\frac{D_2-D_1}{A_1}$, $a=\frac{A_2}{B_1}$ and $b=\frac{C_2-C_1}{B_1}$. As far as I know, this form cannot be solved analytically in general.
| {
"pile_set_name": "StackExchange"
} |
Q:
Loading assemblies and its dependencies
My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory.
Is there a way to tell the runtime that the dlls are in a seperate subfolder?
A:
One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event.
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method.
EDIT:
Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool.
A:
You can use the <probing> element in a manifest file to tell the Runtime to look in different directories for its assembly files.
http://msdn.microsoft.com/en-us/library/823z9h8w.aspx
e.g.:
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="bin;bin2\subbin;bin3"/>
</assemblyBinding>
</runtime>
</configuration>
| {
"pile_set_name": "StackExchange"
} |
Q:
error in ajax and json array
I'm going to develop an interactive map (google maps).The coordinates parse via ajax from json,but i get error
JSON Format
{"Level":[{"route":[{"lat":39.105251,"lgn":26.551727},
{"lat":39.105247125,"lgn":26.551774625}...],"balls":
[{"lat":39.105239375,"lgn":26.551869875},{"lat":39.10524325,"lgn":26.55182225}]},
{"route":[{........},{.....}...],"balls":[{........},{.....}...]}]}
AJAX REQUEST
$.ajax({
type: "GET",
url: "getcoordp?q=2",
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
$.each(data.Level, function(i,Level){
$.each(data.route, function(index, route) {
alert(data.lat)
});
});
}
});
ERROR
Uncaught TypeError: Cannot read property 'length' of undefined
any help?
A:
Replace below
$.each(data.route, function(index, route)...
With
$.each(Level.route, function(index, route) {
alert(route.lat)
});
This will fix your issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Top down car game (game-maker)
I'm new to programming on game-maker and programming in general. This is probably very easy but i'm unsure of how to go about things.
I am programming a simple top-down car game in which the car drives (forward) by it's self and is steered with the left and right mouse buttons. I attempted to get the car to drive on it's own with:
speed = 3
This, although making the car go forward, stopped the steering from working somehow and now the car rotates instead of actually turning around the corner.
How can i get the car to drive on it's own and still be able to turn the car?
A:
You should not change image_angle, but direction instead. Image_angle is juste what you see, direction is the real physics direction.
Replace the code in your link by :
direction = direction + 2;
image_angle = direction;
Like this, you turn the car, and then align the image on the car orientation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Inserting Related MySQL Data with AUTO_INCREMENT
I'm looking at a database that has 3 tables into which I have to insert data:
resource
id (AUTO_INCREMENT)
name
resource_item
id (AUTO_INCREMENT)
name
resource_id (FK ref resource.id)
resource_item_business_function
id (AUTO_INCREMENT)
business_function_name
resource_item_id
What I'm struggling with is the fact that this must be scripted. I'm only inserting 1 resource record so I can script the insert into the resource table easily enough. I have ~20 resource_item records to insert for that resource and I can even do that easily enough using the LAST_INSERT_ID() function. The question is...how do I insert into resource_item_business_function?
I have no idea how to insert the proper resource_item_id into each resource_item_business_function record. Any thoughts would be much appreciated.
A:
You would need to use LAST_INSERT_ID() after each insert into resource_item. So your final script could look something like this:
SET AUTOCOMMIT=0;
SET @RESOURCE_ID=0;
INSERT INTO resource ( NULL, "Some Name");
SELECT LAST_INSERT_ID() INTO @RESOURCE_ID;
INSERT INTO resource_item ( NULL, "Some Name", RESOURCE_ID );
INSERT INTO resource_item_business_function ( NULL, "Some Name", LAST_INSERT_ID() );
...etc...
INSERT INTO resource_item ( NULL, "Some Name", RESOURCE_ID );
INSERT INTO resource_item_business_function ( NULL, "Some Name", LAST_INSERT_ID() );
COMMIT;
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Calendar API server to server Rails
I want insert events in my calendar after some user's actions. That's why I'm want use server-to-server authorization with Google API. I wrote next code:
require 'google/apis/calendar_v3'
require 'googleauth'
require 'google/api_client/client_secrets'
require 'google/api_client'
Initialize the client
client = Google::Apis::CalendarV3::CalendarService.new
load and decrypt private key
key = G.load_from_pkcs12('google_secrets.json', 'notasecret')
generate request body for authorization
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/calendar',
:issuer => '....',
:signing_key => key)
fetch access token
client.authorization.fetch_access_token!
# load API definition
service = client.discovered_api('calendar', 'v3')
# there is a place for variable "event" declaration
client.execute(:api_method => service.event.insert,
:parameters => { '....' => 'primary' },
:event => event)
But when I try to use that code, i recive next answer:
cannot load such file -- google/api_client (LoadError)
I'm understand that maybe I must use previous version of gem google-api-client(<0.9) for get rid of that error. But don't know how i must make insert event with syntax of < 0.9 google api version.
A:
I found solution.
Use for it api v.0.8.2 and see next page:
Rails + Google Calendar API events not created
| {
"pile_set_name": "StackExchange"
} |
Q:
More than one tab bar in an app?
I have developed an app that has work successfully for the last 4 months using iOS 4.3 and under. Since iOS 5 however the tightening of view hierarchy has left my app dead in the water. The app starts with a tab bar as its main view with 5 tabs. When the user selects a row on a tableview on the first tab it pushes onto another tabbar with 3 tabs which gives specific information about that selection. This structure worked fine but obviously broke when testing on iOS 5.
My question is: Is it bad design to utilize 2 or more tab bars in one application? I don't mean "bad design" in the grand scheme of things because that is subjective. I mean in a practical sense where it is specifically forbidden or not recommended.
A:
have a look at this:
iOs Human Interface Guideline
Yes, I think that it's not recommended.
For example:
Use a tab bar to give users access to different perspectives on the same set of data or different subtasks related to the overall function of your app. When you use a tab bar, follow these guidelines:
Don’t use a tab bar to give users controls that act on elements in the current mode or screen. If you need to provide controls for your users, use a toolbar instead (for usage guidelines, see “Toolbar”).
In general, use a tab bar to organize information at the application level. A tab bar is well-suited for use in the main app view because it’s a good way to flatten your information hierarchy and provide access to several peer information categories or modes at one time.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change background Color on external element drop based on it's id: Fullcalendar?
I am trying to change background Color of the external element on drop. So how to do that?
My code is following and I wanted to do something like if I drop red then red color of element on drop. If I drop green then...... so basically, based on it's id it change the color of element. As if you see then when you drop anything on week calendar, it's by default color is getting blue but it should transform to red as you are dropping red for ex.
Any help will be really useful thanks guys
Here is my code:
jsFiddle link http://jsfiddle.net/jimil/8hqe3wxd/2/
A:
My suggestion would be to add a data-attribute to the draggable components, not rely on their class (since theres more in their class than just the color)
and then when building the little dragged components in the external events section, set a color attribute (either red, orange, purple or the actual css color)
http://jsfiddle.net/8hqe3wxd/4/
in the fiddle, observe i added data attributes to the html:
<div class='fc-event orange' id="1" data-color="orange">Orange</div>
<div class='fc-event red' id="2" data-color="red">Red</div>
<div class='fc-event purple' id="3" data-color="purple">Purple</div>
and added a line to the external events config
color: $(this).data('color')
this is storing what color you want each draggable to be, and setting that color when building the little calendar element.
hopefully this is what you want
| {
"pile_set_name": "StackExchange"
} |
Q:
itextsharp: java to vb.net
i am trying to change the font on a pdftable and i have this hint in java but need some help to put it into vb.net
PdfPTable table = new PdfPTable(3);
table.AddCell("Cell 1");
PdfPCell cell = new PdfPCell(new Phrase("Cell 2", new Font(Font.HELVETICA, 8f, Font.NORMAL, Color.YELLOW)));
A:
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Module Module1
Sub Main()
Dim table As New PdfPTable(3)
table.AddCell("Cell 1")
Dim f As New Font(Font.HELVETICA, 8.0F, Font.NORMAL, Color.YELLOW)
Dim ph As New Phrase("Cell 2", f)
Dim cell As New PdfPCell(ph)
End Sub
End Module
| {
"pile_set_name": "StackExchange"
} |
Q:
What is wrong with this definition of a discrete random variable?
(note regarding notation for function application: I sometimes write $f(x)$ as $f.x$, to simplify brackets)
I begin by defining the key pieces of the random variable definition, in a way that is more detailed than necessary, for the sake of pedagogy.
A "random variable" isn't random or a variable. It is a surjective function between a sample space $S$ and a set of real values in a set $V \subset \mathbb{R}$. Let $X$ be some such function. Even though $X$ is surjective and thus does not necessarily have an inverse, we will still be interested in the co-function: $\tilde{X}: V \rightarrow A \subset S$, which maps a value in $V$ to some subset of elements in $S$ in this way:
$$\tilde{X}.v = \bigcup\{A \subset S: X.A = v\}$$
Recall that a probability function $P$ over $S$ maps subsets of $S$ to a real numbers in $U$, where $U$ is such that $U \subset [0, 1]$, and $\sum U = 1$. This means that $P.\tilde{X}: V \rightarrow A \subset S \rightarrow U$ is a probability function on the set $V$, governed by the structure of $P$ on $S$.
The function $p_X = P.\tilde{X}$ is called the "mass" function if $S$ is finite in size.
Let $S = \{A, B, C\}$, and let $V = \{1, 2\}$. Let $P$ be a probability function over $S$ such that $P(A) = P(B) = P(C) = 1/3$.
Let $X$ be a random variable such that $X: R \subseteq S \rightarrow V$, such that: $X.\{A, B\} = 1 = X.\{B, C\}$ and $X.\{A, C\} = 2$. Let $p_X$ be the probability mass function for the RV $X$.
How will $p_X$ be defined? Note that $p_X = P.\tilde{X}$. So we first need to construct $\tilde{X}$. There is two values in $V$:
\begin{align}
&\tilde{X}.1 = \bigcup \{E \subset S : X.E = 1\} = \{A, B\} \cup \{B, C\} = \{A, B, C\} \\
&\tilde{X}.2 = \bigcup \{E \subset S : X.E = 2\} = \{A, C\}
\end{align}
So:
\begin{align}
&p_{X}.1 = P.\tilde{X}.1 = P.\{A, B, C\} = 1 \\
&p_{X}.2 = P.\tilde{X}.2 = P.\{A, C\} = 2/3
\end{align}
What is the sum of $p_{X}$ over all the values it can take?
\begin{align}
\sum_{y \in V} p_{X}.y = p_{X}.1 + p_{X}.2 = 1 + 2/3 = 5/3
\end{align}
Shouldn't the sum of $p_X$ over all its values sum to $1$ though? What am I doing wrong?
A closer reading of my textbook suggests the following:
1) a random variable is simply any function from a sample space, to a subset of the real numbers.
2) a random variable is a discrete random variable if for a set of finite or countably infinite values $\{k_1, k_2, \dots\}$, where $\{k_i\} \subset \mathbb{R}$, we have that $\sum_{i} P.\tilde{X}.k_i = 1$.
What is a random variable for which an appropriate $\{k_i\}$ satisfying point 2 has not been defined called? This is what I constructed in the first part of the question.
An easy way to fix the problem would be to renormalize $P.\tilde{X}.v$ by what it sums to be:
$$ P.\tilde{X}.1 = 1/(5/3) = 3/5, \; P.\tilde{X}.2 = 2/3/(5/3) = 2/5$$
What would such renormalization be called?
A:
your mistake is your definition of X. As it is a function from S, you need to set X for each element of S and not for subsets of S. Ie you need to define
$X.A, X.B, X.C$ (and not $X.\{A,C\}$, $X.\{A,B\}$ or $X.\{B,C\}$) so the sum of probabilities will be consistent.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reshaping a tensor with more than one uknown diemnsions
I need to be able to reshape a tensor only on its last axis:
(None, 4) --> (None, 2, 2),
which at time of execution can have instances like these:
(128, 10, 4) --> (128, 10, 2, 2)
(128, 4) --> (128, 2, 2)
Is there a straight forward solution or I need to iterate on the first axes (by excluding the last one), and considering the case that it can be None?
A:
You can do that like this:
my_tensor = ...
new_shape = tf.concat([tf.shape(my_tensor)[:-1], [2, 2]], axis=0)
my_tensor_reshaped = tf.reshape(my_tensor, new_shape)
| {
"pile_set_name": "StackExchange"
} |
Q:
Change view frame in landscape using autolayout in storyboard
I am very new to AutoLayout. I have one problem. I need to change the frame of any UIView when moving form portrait to landscape mode.
For example: If I have one UILabel with frame (100,100,100,30) in portrait mode. And I want to change its frame to (400,400,100,30) if rotate iPad to landscape mode. I want to do this using storyboard and auto layout.
I want to avoid coding for this.
A:
I try this one :
First check Use AutoLayout
Move your mouse point to UILabel and drag right side with Ctrl Key and select Trailing space to container
Move your mouse point to UILabel and drag left side with Ctrl Key and select Leading space to container
This is your output :
Check it. :)
| {
"pile_set_name": "StackExchange"
} |
Q:
AVAudioRecorder shows time delay for recording sound in IOS 5
I am using AVAudioRecorder to record sound in 'wav' format. My code works fine for ios 4 and recording is done perfectly. But in case of ios 5, a time delay of 3-4 seconds occur in 2 out of 10 attempts for recording sound. I also used : [audioRecorder prepareToRecord] function in order to start the recording without delay.
Is there any bug in my code or somrthing else... Please guide me..
My code is:
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10];
[recordSettings setObject:[NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey];
[recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey];
[recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
[recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *recDir = [paths objectAtIndex:0];
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audio%d.wav", recDir,nextCount]];
NSError *error = nil;
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];
audioRecorder.delegate=self;
if(!audioRecorder){
NSLog(@"recorder: %@ %d %@", [error domain], [error code], [[error userInfo] description]);
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle: @"Warning" message: [error localizedDescription]
delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
[audioRecorder prepareToRecord];
audioRecorder.meteringEnabled = YES;
BOOL audioHWAvailable = audioSession.inputIsAvailable;
if (! audioHWAvailable) {
UIAlertView *cantRecordAlert =
[[UIAlertView alloc] initWithTitle: @"Warning" message: @"Audio input hardware not available" delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[cantRecordAlert show];
[cantRecordAlert release];
return;
}
[audioRecorder prepareToRecord];
[audioRecorder recordForDuration:(NSTimeInterval) 25];
[recordSettings release];
}
else
{
[recordButton setBackgroundImage:[UIImage imageNamed:@"record.png"] forState:UIControlStateNormal];
self.recordBtn=NO;
[audioRecorder stop];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
}
A:
The problem was with AVAudioSession. Every time when i record the video, i create a session for recording:
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
and this was the problem sometimes session takes time to start and recording was delayed by 3-4sec. So, i created the session in viewdidload and make it global and the problem was resolved. Thanks to the suggestion by hotpaw2 on a similar kind of link...
| {
"pile_set_name": "StackExchange"
} |
Q:
Color every second row of the table
I need to color every second row in my table.
I would love it to look like on the attached image
Any ideas how to do this?
A:
EVEN AND ODD RULES
One way to improve the readability of large tables is to color alternating rows. For example, the table below has a light gray background for the even rows and white for the odd ones. The rules for that are extremely simple:
Css:
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
Check here google 1st result
| {
"pile_set_name": "StackExchange"
} |
Q:
what is up with this "modified 2 hours ago by Community" questions in the "active" list
When I check the "active" questions, there are often questions included that are considered "active" because there were "modified N hours ago" and the modifying user is "Community".
If open the question, I don't see any edit N hours ago, in fact most of the time the last activity was weeks, months or even years ago.
Can anyone please clarify what is going on here?
Personally I find it very inconvenient to see these long-time-inactive questions in the active stream, as sometimes I don't notice it's an old question until after I answer it :)
A:
A question without an accepted answer will be "modified" by the system from time to time so that it pops back up and gets looked at again. It will keep looking for an answer until it has an accepted answer.
This happens on all the SE sites.
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom JSON Result in ASP.NET MVC
I created custom ActionResult (simplified):
public class FastJSONResult : ActionResult
{
public string JsonData { get; private set; }
public FastJSONResult(object data)
{
JsonData = JSON.Instance.ToJSON(data);
}
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/json";
response.Output.Write(JsonData);
}
}
And use it from my WebApi controller:
public ActionResult GetReport()
{
var report = new Report();
return new FastJSONResult(report);
}
Now the problem is, despite the fact that in FastJSONResult constructor my object serializes perfectly, ExecuteResult never gets called and in response I end up with object like
{"JsonData":"{my json object as a string value}"}
What am I doing wrong?
A:
Solved it with custom formatter (simplified to post less code)
public class FastJsonFormatter : MediaTypeFormatter
{
private static JSONParameters _parameters = new JSONParameters()
{
public FastJsonFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
SupportedEncodings.Add(new UTF8Encoding(false, true));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var task = Task<object>.Factory.StartNew(() => JSON.Instance.ToObject(new StreamReader(readStream).ReadToEnd(), type));
return task;
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
var task = Task.Factory.StartNew(() =>
{
var json = JSON.Instance.ToJSON(value, _parameters);
using (var w = new StreamWriter(writeStream)) w.Write(json);
});
return task;
}
}
In WebApiConfig.Register method:
config.Formatters.Remove(config.Formatters.JsonFormatter);
config.Formatters.Add(new FastJsonFormatter());
And now I receive json object properly:
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting Distinct Count from two tables
I have two tables for example
table1 as
╔══════════╦════════════╗
║ id ║ login_id ║
╠══════════╬════════════╣
║ 1 ║ 2 ║
║ 2 ║ 2 ║
║ 3 ║ 2 ║
║ 4 ║ 1 ║
╚══════════╩════════════╝
and table2 as
╔══════════╦════════════╗
║ id2 ║ login_id ║
╠══════════╬════════════╣
║ 1 ║ 3 ║
║ 2 ║ 1 ║
║ 3 ║ 2 ║
║ 4 ║ 1 ║
╚══════════╩════════════╝
I need to get the count of column login_id from the two tables where there is no duplicate
I have tried
SELECT COUNT(DISTINCT t1.login_id), COUNT(DISTINCT t2.login_id) FROM table1 as t1 JOIN table2 AS t2
I got
COUNT(DISTINCT t1.login_id) 2
COUNT(DISTINCT t2.login_id) 3.
Is there any way that I can the output to be only 3.
Hope that it's clear to understand what I want.
A:
Use UNION :
select count(*)
from (select login_id
from table1 union -- WILL REMOVE DUPLICATE
select login_id
from table2
) t;
| {
"pile_set_name": "StackExchange"
} |
Q:
How can telnet connect to an arbitrary port?
Through telnet I am able to connect to any server at any port, how does it work? Is there a telnet server daemon running on that server?
If there is, shouldn't the daemon listen on a specific port? why can I connect to an arbitrary port on that server?
Why can I telnet to 127.0.0.1 at 80 port and get a response from my Nginx without a telnet daemon running on my Ubuntu?
A:
The telnet client doesn't do any special processing. It opens a TCP connection to the remote server on any port you specify, forwards through this connection anything you type and puts on screen anything that it receives from the server.
When you telnet 127.0.0.1 80 it opens a connection to port 80 of localhost where usually a web server is already listening (nginx in your case).
An HTTP client knows how to craft an HTTP request and send it through the connection. The telnet client doesn't know anything about HTTP but if you know the protocol you can manually craft a request and type it and the telnet client will happily send it for you through the connection. If the program at the other end (the web server) understands the request it will send a response back. Again, the telnet client doesn't understand a bit of the response (it's just data to it) but it happily puts the response on screen.
You can use telnet to connect to any port of a (remote or local) computer, as long as there is a server application that is listening on that port.
There is a telnet server, it usually listens on port 23 if I remember correctly and when a connection is established to it it launches a pseudo-terminal program that handles a login session on the server (the exact program it launches to handle the session depends on the OS). If the login succeeds, the telnet client then talks with the pseudo-terminal program that passes the keys you type to a remote shell; the output produced by the shell goes back to you through the pseudo-terminal -> TCP connection -> telnet client.
The telnet server is deprecated by the SSH protocol that does the same thing (and many others) but everything that goes through the connection is encrypted on each end before sending and decrypted on the other end before being used. This adds privacy and security to the services already provided by the telnet server.
The telnet client, however, is still useful because it can be used to test the functionality of servers that use unencrypted text protocols like HTTP, SMTP, POP3, IMAP etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Xcode 5-DP5 Crashing when distributing
I have been struggling past 4 days trying to Publish an app to App Store. But every single time I go on Xcode
Project->Archive-> Distribute/Validate
Have downloaded the right profile from iTunes Developer Center.
It crashes every time.
I have tried removing the itunnesconnect DB file that I read from previous posts but I couldnt find it
$ rm ~/Library/Developer/Xcode/connect1.apple.com 4.6.1.db
Got
$ rm: /Users/{_USER_}/Library/Developer/Xcode/connect1.apple.com: No such file or directory
$ rm: 4.6.1.db: No such file or directory
Also tried running:
mkdir ~/Library/Developer/Xcode/OldPortalDBs; mv ~/Library/Developer/Xcode/connect1.apple.com* ~/Library/Developer/Xcode/OldPortalDB
Getting similar error (As the file is indeed nonexistent. However this options were for Xcode 4
Here is the Details to the Crash: http://www.ipaste.org/NCj
I am running the following:
Mac OS X 10.9 Mavericks
XCode 5-DP5
MacBook Air Mid 2013
PhoneGap/Cordova 3.0
Any help would be mostly appreciated, thank you
A:
Developer center clearly states that you cannot use any Developer Preview version to submit app to the App Store:
Xcode 5 Developer Preview cannot be used to submit apps to the iOS or Mac App Store.
Continue to use the publicly released version of Xcode to compile and submit apps to the App Stores.
Source: Login to iOS dev center, choose iOS SDK Beta tab, see the "Read Me Before Downloading" section.
| {
"pile_set_name": "StackExchange"
} |
Q:
Postgres change number format
in Postgres I use this query:
UPDATE managers SET phone_number = replace(phone_number, '\m86', '3706');
unfortunately the field is long and query fails. I need to change all numbers beginning with 86 to start with 3706...
I tried many Postgres functions, but it is not obvious do they have the fumction I need.
the error is:
ERROR: function replace(bigint, unknown, unknown) does not exist
LINE 1: UPDATE managers SET phone_number = replace(phone_number, '\m...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
table definition:
CREATE TABLE public.managers(
phone_number bigint,
email_report boolean,
)
A:
As was pointed out in the comments, if you use a regex replace it becomes much easier to articulate what a number is which starts with 86. The pattern for that is just ^86 and the replacement is 3706. Consider the following query:
UPDATE managers
SET phone_number = REGEXP_REPLACE(phone_number::text, '^86', '3706')::int
| {
"pile_set_name": "StackExchange"
} |
Q:
Golang Struct Won't Marshal to JSON
I'm trying to marshal a struct in Go to JSON but it won't marshal and I can't understand why.
My struct definitions
type PodsCondensed struct {
pods []PodCondensed `json:"pods"`
}
func (p *PodsCondensed) AddPod(pod PodCondensed) {
p.pods = append(p.pods, pod)
}
type PodCondensed struct {
name string `json:"name"`
colors []string `json:"colors"`
}
Creating and marshaling a test struct
fake_pods := PodsCondensed{}
fake_pod := PodCondensed {
name: "tier2",
colors: []string{"blue", "green"},
}
fake_pods.AddPod(fake_pod)
fmt.Println(fake_pods.pods)
jPods, _ := json.Marshal(fake_pods)
fmt.Println(string(jPods))
Output
[{tier2 [blue green]}]
{}
I'm not sure what the issue is here, I export json data for all my structs, the data is being stored correctly and is available to print. It just wont marshal which is odd because everything contained in the struct can be marshaled to JSON on its own.
A:
This is a common mistake: you did not export values in the PodsCondensed and PodCondensed structures, so the json package was not able to use it. Use a capital letter in the variable name to do so:
type PodsCondensed struct {
Pods []PodCondensed `json:"pods"`
}
type PodCondensed struct {
Name string `json:"name"`
Colors []string `json:"colors"`
}
Working example: http://play.golang.org/p/Lg3cTO7DVk
Documentation: http://golang.org/pkg/encoding/json/#Marshal
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between cranio and teschio
I am studying the difference between "cranio m" and "teschio m" (the m stands for masculine).
Hypothesis number one: "cranio m" refers to set of bones of a person that is alive; "teschio m" is a symbol of skull, "teschio m" can be used to refer to a pirate flag.
Hypothesis number two: "cranio m" refers to a skull of a person that is alive or dead, if still has human tissue other than bones. "Teschio m" is used to refer to a skull of a person that has no other human tissue but the bones.
Am I right?
Thank you.
A:
A famous passage from Rosmunda by Vittorio Alfieri
ROSMUNDA. [...]
Nol vegg'io sempre, a quella orribil cena
(banchetto a me di morte) ebro d'orgoglio,
d'ira, e di sangue, a mensa infame assiso,
ir motteggiando? e di vivande e vino
carco, nol veggio (ahi fera orrida vista!)
bere a sorsi lentissimi nel teschio
dell'ucciso mio padre? indi inviarmi
d'abborrita bevanda ridondante
l'orrida tazza? E negli orecchi sempre
quel sanguinoso derisor suo invito
a me non suona? Empio ei dicea: «Col padre bevi,
Rosmunda». [...]
The phrase “Bevi Rosmunda dal teschio di tuo padre” is commonly associated to it, coming from a parody by Achille Campanile of Alfieri's tragedy (see Wikipedia). This should make clear that teschio is not just a symbol.
According to the Treccani dictionary the word is used to denote the bones of the head, almost exclusively for dead bodies of human beings or animals. It comes from Latin testulum (pottery vase), like testa (head) comes from testum.
The word cranio refers to the anatomic part and can be used both for living and dead bodies.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding multiple columns to a table in sqllite
Can i add multiple columns to a table in a single query execution, using alter table?
A:
No,you can't add multiple columns in single query execution. SQLite supports a limited subset of ALTER TABLE.therefore you have to add them one by one.
see documentation at sqlite
| {
"pile_set_name": "StackExchange"
} |
Q:
Date convert in Java
I want to compare two dates, for that i convert the string to date format.But during the conversion the date format changed to "02/01/2013" and "03/01/2014".It makes error in my logic.any one please tell me to how to compare two days in my date format.
String fdate="01/02/2012";
String tdate="01/03/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date frmdt=new Date(fdate);
String s1 = sdf.format(frmdt);
Date todt=new Date(tdate);
String s2 = sdf.format(todt);
Date frmdate = sdf.parse(s1);
Date todate = sdf.parse(s2);
if(frmdate.compareTo(todate)<=0){
//process;
}
A:
Try this:
String fs = "01/02/2012";
String ts = "01/03/2013";
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
sdf.setLenient(false);
Date fdate = sdf.parse(fs);
Date tdate = sdf.parse(ts);
if (fdate.before(tdate) || f.date.equals(tdate)) {
//process;
}
You've got too much going on. It's much simpler.
A:
It seems to me that you should be calling SimpleDateFormat.parse instead:
// Using the US locale will force the use of the Gregorian calendar, and
// avoid any difficulties with different date separator symbols etc.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // Avoid DST complications
sdf.setLenient(false);
Date fromDate = sdf.parse(fromDateText);
Date toDate = sdf.parse(toDateText);
// Alternatively: if (!fromDate.after(toDate))
if (fromDate.compareTo(toDate) <= 0) {
...
}
I'd actually suggest that you use Joda Time if at all possible, where you could use a LocalDate type to more accurately represent your data.
| {
"pile_set_name": "StackExchange"
} |
Q:
Azure Javascript - Wait for Function Completion
I'm using Azure Mobile Services and am running a javascript backend. However, since the backend is in node.js, everything is executed asynchronously and I don't know how to halt the execution of a function.
I'm trying to delete a club if there hasn't been a comment in it within the past 24 hours, and here's my code:
var clubs = tables.getTable('Club');
clubs.read(
{
success: function(club){
var now = new Date().getTime();
for(var i=0;i<club.length;i++){
var deleteClub = true;
comments.where({ClubId: club[i].id}).read(
{
success:function(comment){
var timeDiff = (now-comment[i].Time.getTime())/(1000*60*60);
console.log("Comment in table: "+timeDiff);
if(timeDiff<24){
deleteClub=false;
}
}
}
);
if(deleteClub){
console.log("deleting club: "+club[i].Title);
//clubs.del(club[i]);
}else{
console.log("saving club: "+club[i].Title);
}
}
}
}
);
The if statement executes before the delete club variable is updated, so it's always true, but I need the if statement's execution to be delayed until after all of the comments have been looped through.
A:
Since the callback you get is asynchronous, you can't use any information you're getting in that callback in synchronous code after the where call.
Since we want to handle things on a club-by-club basis, first we'll move the handling of clubs into its own function. This avoids the problem that by the time we get our callback from read, i will have been incremented.
Your code seems to assume success is called repeatedly, once for each comment. I don't think that's likely to be the case, more likely it's called once, with a list/array of the matching comments.
If so, then splitting off club handling to its own function and then looping the found comments should do it:
var clubs = tables.getTable('Club');
clubs.read(
{
success: function(allClubs){ // <== Note plural
var now = new Date().getTime();
for (var i = 0; i < allClubs.length; i++) {
handler(now, allClubs[i]); // <== Move handling off to a handler
}
}
}
);
function handler(now, club) { // <== Unlike `i` above, `club` won't change because it's
// a function argument that we never assign to
comments.where({ClubId: club.id}).read(
{
success: function(comments){ // <== Note the plural
var deleteClub = true;
for (var i = 0; i < comments.length; ++i) {
var timeDiff = (now-comments[index].Time.getTime())/(1000*60*60);
console.log("Comment in table: "+timeDiff);
if(timeDiff<24){
deleteClub=false;
}
}
if (deleteClub){
console.log("deleting club: "+club.Title);
//clubs.del(club);
}else{
console.log("saving club: "+club.Title);
}
}
}
);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Get vocabulary list in Galago
I am using Galago retrieval toolkit (a part of the Lemur project) and I need to have a list of all vocabulary terms in the collection (all unique terms). Actually I need a List <String> or Set <String> I really appreciate to let me know how can I obtain such a list?
A:
The `DumpKeysFn' class seems to give all the keys (unique terms) of the collection. The code should be like this:
public static Set <String> getAllVocabularyTerms (String fileName) throws IOException{
Set <String> result = new HashSet<> ();
IndexPartReader reader = DiskIndex.openIndexPart(fileName);
if (reader.getManifest().get("emptyIndexFile", false)) {
// do something!
}
KeyIterator iterator = reader.getIterator();
while (!iterator.isDone()) {
result.add(iterator.getKeyString());
iterator.nextKey();
}
reader.close();
return result;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Both replication masters stop by themselves
I did a master/master replication with MySQL on a Gentoo OVH Release 2, all work fine in my test phase. I put it in production, the replication works fine for 1 or 2 days, but this morning, I don't know why, my slave stops running!
So now the log position is bad. I can't just restart slave and my replication doesn't work.
I want a master/master replication to make a backup server with an IP failover, so only one server is writing/reading in the database at same time.
When I go to MySQL and click on Show slave status, I see an error like:
Error 'Duplicate entry '411465' for key 1' on query. Default database .... etc.
Did this error stop my replication? If yes, why do I get this error? The second server does nothing on the database, so normally, there is no problem with the autoincrement, right?
A:
The provided error Error 'Duplicate entry '411465' for key 1' on query means that the slave read and attempted to execute a binary log event to insert a row that already existed, ie. the same value 411465 for your primary key.
The most likely cause of this is the the insert was executed on the slave. To diagnose the query, you would use mysqlbinlog and use the binary log coordinates from SHOW SLAVE STATUS. This will give you the server-id that the query originated from, which will match either your main master or 'passive' master.
Once you determine the query, you can identify the row on the server that is throwing the slave error to determine next steps. You can choose to :
skip the entry using SET GLOBAL sql_slave_skip_counter=1 to proceed to the next binary log statement
Delete the specific row on the server and start slave to have the statement run from replication.
However, you need to take steps to understand how the mismatch occurred, or you're going to run into this again. This will require some more detective work from your end using mysqlbinlog.
If, as you say, only one master is writeable at a time, you should ensure the following:
passive master is read_only=1 and your failover solution is able to modify read_only.
the user that your application runs as (or any other non-trusted user) does not have the SUPER privilege. Any user with SUPER privilege can execute statements even on read_only=1 servers.
setup pt-table-checksum to ensure the data is in sync on both servers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python/sqlite3: is there a way to make database schema figure?
Very new to sql and thus new to sqlite3. I'm setting up a relational database and need a visual for peer review prior to populating with actual data. (That is, I am setting up all the tables and fields, with primary and foreign keys, but there are no records for now.)
Is there a way to make a figure that visually shows the relationships between the tables? (Example internet grab below--or maybe linked because I am new user.) Using sqlite3 and python. Bonus points if it looks better than the crummy Access visual!
schema plot figure
A:
one possible solution to making relational diagrams in Python is ERAlchemy. As of the time of this posting, I did not see any other pure Python solution.
https://pypi.org/project/ERAlchemy/
| {
"pile_set_name": "StackExchange"
} |
Q:
lua meta-object protocol model: lua-coat vs loose
There is someone who uses lua-coat or loose routinely?
Which is more mature, stable, bugfree -> "better"?
Is one of them enough mature for the production environment?
lua-coat - activity none - last updated Nov.2010 - marked as beta
loose - activity none - last updated in Dec.2008 - ???
Any experience?
(looking for an answer from someone who has real experience with them :)
A:
Disclaimer: I have no direct experience with any of those libraries, but I've got some experience creating my own OOP lib.
Of the two libraries you have proposed, lua-coat seems better. My two main reasons:
It's got some fairly recent commits
It's got automated tests. IMHO Any serious lib should have them(*), but it's specially important in OOP libs; keeping track of all the things that can go wrong in a refactoring is just impossible without automated testing.
(*) My lib also has tests, mind you. They are just on a different repo, for now.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot access server running in container from host
I have a simple Dockerfile
FROM golang:latest
RUN mkdir -p /app
WORKDIR /app
COPY . .
ENV GOPATH /app
RUN go install huru
EXPOSE 3000
ENTRYPOINT /app/bin/huru
I build like so:
docker build -t huru .
and run like so:
docker run -it -p 3000:3000 huru
for some reason when I go to localhost:3000 with the browser, I get
I have exposed servers running in containers to the host machine before so not sure what's going on.
A:
From the information provided in the question if you see logs of the application
(docker logs <container_id>) than the docker application starts successfully and it looks like port exposure is done correctly.
In any case in order to see ports mappings when the container is up and running you can use:
docker ps
and check the "PORTS" section
If you see there something like 0.0.0.0:3000->3000/tcp
Then I can think about some firewall rules that prevent the application from being accessed...
Another possible reason (although probably you've checked this already) is that the application starts and finishes before you actually try to access it in the browser.
In this case, docker ps won't show the exited container, but docker ps -a will.
The last thing I can think of is that in the docker container itself the application doesn't really answer the port 3000 (I mean, maybe the startup script starts the web server on some other port, so exposing port 3000 doesn't really do anything useful).
In order to check this you can enter the docker container itself with something like docker exec -it <container_id> bash
and check for the opened ports with lsof -i or just wget localhost:3000 from within the container itelf
| {
"pile_set_name": "StackExchange"
} |
Q:
Balance between "right tool for the job" and familiarity
So when choosing what language to use for a project, in an ideal world the language is chosen because it's the right tool for the job. However, I often prefer to use a language that I am fluent in rather than one I would have to learn or that I am only conversational in. Of course language fluency also entails knowledge of the applicable libraries in the language. Just because I really like a fairly general-purpose language like Java doesn't mean I should always use it, but at the same time it doesn't mean I should break out something like Perl every time there's some text processing to be done. How does one find the balance here?
A:
Wow that is a VERY hard question when taken out of the world of theory and into the world of production.
In Theory
Simple. Always use the best tool for the job, and just learn what you need to.
In Practice
Not only is there the question of your fluency there are a host of other business questions that need to be asked before you can answer this :
Cost of purchasing the "correct tooling"
Cost of supporting this - people need to be trained
Cost of learning curve
Integration cost with other products ( now and into the future )
... etc
Outside of the theory there are serious ramifications for your technology choice.
Now I am not saying don't pick the correct tool - just make sure the correct tool will be able to break even on its cost implication.
If this is a personal project - always use the "correct" tool - so when you are faced with this decision in the business context you can make a better informed call.
A:
I think familiarity is not given enough credit. Your familiarity very well influences what the right tool is. You have to use the tool to complete your project. Furthermore, using something you enjoy can without a doubt exceed any shortcomings in it's fitness because you'll be more excited to get work done and you'll have better results.
http://headrush.typepad.com/creating_passionate_users/2006/08/when_the_best_t.html
A:
This isn't really resolvable except as a business question. However, a lot of business questions are made only looking at short-term numbers, which is a mistake with things like this.
My general approach:
If it's a small or short-term thing, always write it in the familiar tools.
If it's a big, long-term thing, look at the cost-benefit tradeoff of learning a new tool.
If you aren't sure, treat it as a short term thing until you have evidence that it's a long-term thing. Then go and look at the decision again.
Three things to keep in mind as you think about cost and benefit: One, people in a hurry tend to short-change the future. Two, maintenance costs are the lion's share of the costs for any successful system. Three, good developers like learning things, and keeping your developers happy is a good long-term investment.
| {
"pile_set_name": "StackExchange"
} |
Q:
html inside php mail
I have the following html codes for my email.
$headers = "From: jmedalla20@gmail.com \r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/html; charset=ISO-8859-1 \r\n";
$message = <<<EOD
<!DOCTYPE html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=utf-8 />
<link rel=stylesheet type=text/css href=logo.jpg/>
</head>
<body>
<img src=../../img/logo.jpg style=left: 0;position: absolute; width: 75px;/>
<body style=padding: 0 0 0 100px;position: relative;>
{date(F d, Y )} <br><br>
<b> {$row_Recordset1['First Name']} {$row_Recordset1['Middle Initial']} {$row_Recordset1['Last Name']}</b><br>
{$row_Recordset1['Position']}<br>{$row_Recordset1['Company Name']}<br>{$row_Recordset1['Corporate Address']}<br><br>
<p>Dear {$row_Recordset1['Last Name']}:</p>
// the rest of the letters
</body>
</html>
EOD;
I've had a few test runs and all that displays is
{date(F d, Y )}
Dear :
I don't think the codes are being recognized. Any suggestions?
EDIT: The html is working. it's just the php codes which are not working I guess
A:
Yes, you cannot insert function calls like that. To insert the date, create a variable before this snippet of code that says $date = date(). Then you can use that variable in the string.
Apparently $row_Recordset1['Last Name'] is empty, doesn't exist, contains an empty string or whitespace or a piece of HTML. Hard to tell what exactly, since we don't have your data, nor the piece of code that assigns a value to $row_Recordset1.
Nevertheless, the e-mail is interpreted as HTML, or otherwise you would see chunks of HTML instead of merely this text. So that part is working well.
| {
"pile_set_name": "StackExchange"
} |
Q:
"Sneaked off" vs "sneaked into" vs "sneaked away."
I often get confused about which one to use. Example:
He sneaked [...] to the rear of the ship.
Or maybe all of them have a different connotation?
A:
Sneak denotes stealthy movement:
verb (past and past participle sneaked or informal , chiefly North
American snuck)
1 [NO OBJECT, WITH ADVERBIAL OF DIRECTION] Move or go in a furtive or
stealthy way:
Various directional adverbs can refine the sense of stealthy movement:
In He sneaked away to the rear of the ship, away suggests motion from the point of reference--a literal or metaphorical distance:
adverb
1.0 To or at a distance from a particular place or person:
she landed badly, and crawled away...
1.1 At a specified distance:
when he was ten or twelve feet away he stopped
1.2 At a specified future distance in time:
the wedding is only weeks away
1.3 Towards a lower level; downwards:
in front of them the land fell away to the river
1.4 Conceptually to one side, so as no longer to be the focus of attention:
the Museum has shifted its emphasis away from research towards exhibitions
In He sneaked off to the rear of the ship, off also suggests motion from the point of reference:
1.0 away from the place in question; to or at a distance:
the man ran off
1.1 Away from the main route:
turning off for Ripon
3.0 Starting a journey or race; leaving:
we’re off on holiday tomorrow
In He sneaked into the rear of the ship, into expresses motion to enclosure--literal or metaphorical:
preposition
1.0 Expressing movement or action with the result that someone or something becomes enclosed or surrounded by something else:
cover the bowl and put it into the fridge
2.0 Expressing movement or action with the result that someone or something makes physical contact with something else:
he crashed into a parked car
3.0 Indicating a route by which someone or something may arrive at a particular destination:
the narrow road which led down into the village
Oxford Dictionaries Online
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ and Lua - Unprotected Error (bad callback)? How is this possible
I'm working with LuaJIT's FFI and I'm getting very strange results. This returns a PANIC: Unprotected Error (bad callback):
function idle(ms)
myDLL.myDLL_idle(session, ms)
end
But this simple print has fixed the problem.
function idle(ms)
print("anything")
myDLL.myDLL_idle(session, ms)
end
Another extremely odd solution is to use myDLL.myDLL_idle() inside the main function. How can this even be possible? It's not like I can just do any arbitrary function either if I put the call in a function, the only ones guaranteed to work are a print and sleep.
function idle(ms)
myDLL.myDLL_idle(session, ms)
end
myDLL.myDLL_idle(session, ms) -- works
idle(ms) -- doesn't work (unless first line of idle() is a print statement)
It's doing the same thing but just in another function. And the print fixing it if I try putting it in a function method just add to the complete weirdness of this. This is a huge problem.
A:
According to the documentation, LuaJIT doesn't allow an FFI-call to be JIT-compiled if the FFI-code calls a C function that calls back into Lua via a stored callback. In most cases LuaJIT will detect those calls and avoid compilation, but if it doesn't, it aborts with the "bad callback" error message. The extra print helped, because it prevented JIT-compilation (print is not compiled atm.).
The proposed solution (instead of calling print) is to explicitly stop the FFI-call from being JIT-compiled using the jit.off function.
| {
"pile_set_name": "StackExchange"
} |
Q:
AVAssetImageGenerator provides images rotated
When obtaining a UIImage of a video via AVAssetImageGenerator, I'm getting back images rotated (well, technically they're not) when the video is shot in portrait orientation. How can I tell what orientation the video was shot and then rotate the image properly?
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
NSError *err = NULL;
CMTime time = CMTimeMake(0, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
[generate release];
UIImage *currentImg = [[UIImage alloc] initWithCGImage:imgRef];
A:
The easiest way is to just set the appliesPreferredTrackTransform property on the image generator to YES, then it should automatically do the transformation for you.
A:
The copy and paste solution to create image with the recording orientation using the previous answer.
AVURLAsset* asset = [AVURLAsset URLAssetWithURL:url options:nil];
AVAssetImageGenerator* imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
CGImageRef cgImage = [imageGenerator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:nil error:nil];
UIImage* image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
A:
Here is the solution in swift version 4:
func thumbnailImageForFileUrl(_ fileUrl: URL) -> UIImage? {
let asset = AVAsset(url: fileUrl)
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
do {
let thumbnailCGImage = try imageGenerator.copyCGImage(at: CMTimeMake(1, 60), actualTime: nil)
return UIImage(cgImage: thumbnailCGImage)
} catch let err {
print(err)
}
return nil
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Cygwin permissions on Windows 7
I suppose this question is related to a previous answer on Cygwin permissions, but I have failed to work out how the answer can be applied to my situation.
I am finding that when I edit a file (~/.screenrc in this case), I can make one change and then the permissions and ownership are reset. This is what I am doing after I make a single change to reset permissions again:
Chi Site - ~/wd
Sun Jul 30 - 03:12 PM > ls -la ~/.screenrc ; chown -R RobertMarkBram:Users ~/.screenrc ; chmod 777 ~/.screenrc ; ls -la ~/.screenrc
----rwxrwx+ 1 Administrators None 1921 Jul 30 15:12 /home/RobertMarkBram/.screenrc
-rwxrwxrwx+ 1 RobertMarkBram Users 1921 Jul 30 15:12 /home/RobertMarkBram/.screenrc
I read in the previous answer on Cygwin permissions about changing the set up of paths in /etc/fstab. This is what I have there, but it has not made a difference:
none /cygdrive cygdrive binary,posix=0,user 0 0
none / cygdrive binary,posix=0,user 0 0
These are my mount points:
Chi Site - ~/wd
Sun Jul 30 - 03:20 PM > mount
C:/cygwin/bin on /usr/bin type ntfs (binary,auto)
C:/cygwin/lib on /usr/lib type ntfs (binary,auto)
C:/cygwin on / type ntfs (binary,auto)
C: on /c type ntfs (binary,posix=0,user,noumount,auto)
D: on /d type ntfs (binary,posix=0,user,noumount,auto)
A:
This is a case of PEBKAC.. I had done too much messing around with permissions and didn't know how to get back.
Firstly, under Windows Explorer > that folder > properties > security I noticed there was a NULL SID there that I removed.. my own user didn't have all rights anymore but the the EVERYONE group did. Then I followed advice on this social.technet.microsoft.com post: Permissions all messed up on folders within my profile on Windows 8
cd /d c:\[folders or files you would like to reset permission]
icacls * /T /Q /C /RESET
It took awhile but restored permissions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Book stacking brain teaser
I've been given a puzzle, and I just can't work out an answer. Can you help?
I'd also like to know your thought process for solving, as this matters more than the correct answer. Does it belong to a pattern of puzzles?
The scenario is this:
There are six books by six different authors - J,K,L,M,N and O - which are to be placed on a bookcase with six shelves.
The shelves are numbered from one, the highest, to six, the lowest, and exactly one book will be placed on each shelf.
The book K must be on the second shelf below the book J
The book O must be placed on either the first or sixth shelf.
The book L cannot be placed on either the shelf immediately above or the shelf immediately below the book by M.
Which one of the following is TRUE?
K and L CANNOT be placed on shelves three and four respectively
M and N CANNOT be placed on shelves three and four respectively
J and M CANNOT be placed on shelves three and four respectively
L and K CANNOT be placed on shelves three and four respectively
N and J CANNOT be placed on shelves three and four respectively
Thanks!
A:
I think that the answer is:
$2$ and is only constrained by the first rule (about J and K).
J and K have exactly 1 shelf between them. That means that they span 3 shelves. So, no matter the arrangement, either J or K must be one of the shelves 3 or 4.
So, any solution that fills both 3 and 4 with neither J nor K can't happen.
A:
The true statement is:
2. M and N CANNOT be placed on shelves three and four respectively.
Why?
Book J can only occupy shelves 1, 2, 3, 4. Book K can only occupy shelves 3, 4, 5, 6. No matter where you place J and K, shelves 3 and 4 will always be occupied by one or the other. Proof: J on shelf 1, K on shelf 3. J on shelf 2, K on shelf 4. K on shelf 5, J on shelf 3. K on shelf 6, J on shelf 4.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to programatically add/remove nodes from main graph in Tensorboard?
Tensorboard seems to arbitrarily select which nodes belong to the main graph and which do not. During graph visualization I can manually add/remove the nodes but it is tedious to do it every run.
Is there a way to programmatically embed this information (which nodes belong on the main graph) during writing the graph summary?
A:
According to this github issue , it's not feasible at the moment.
And according to this quote :
Thanks @lightcatcher for the suggestion. @danmane, please take a look
at this issue. If it is something we will not do in the short-term
maybe mark it contributions welcome. If it is something you are
planning to include in your plugin API anyways, please close the issue
to keep the backlog clear.
, and the status of the issue (contributions:welcomed), it's not something that is to be expected in the short term.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Read data from generic repository in ASP.NET controller class?
I am using ASP.NET mvc 5 in visual studio 2013 and tending to read data from function table (SQL Server) in the controller class via generic repository. I have IGenericRepository which has IQueryable one function, I have GenericRepository class where i am implementing this interface. I got FunctionContext which is inherited from baseContext. The reason i have baseContext so all the dbcontexts can use one path to hit database but same time keep number of table limited to business need.
I have manage to implement genericRepository but seems getting null data against _dbSet while debugging in GenericRepository and I cant read data in controller class either there plus getting error on
"var query"
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
many thanks in advanced....
Generic Repository Interface
public interface IGenericRepository<TEntity> : IDisposable
{
IQueryable<TEntity> GetAll();
}
Generic Repository
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
protected DbSet<TEntity> _DbSet;
private readonly DbContext _dbContext;
public GenericRepository()
{
}
public GenericRepository(DbContext dbContext)
{
this._dbContext = dbContext;
_DbSet = _dbContext.Set<TEntity>();
}
public IQueryable<TEntity> GetAll()
{
return _DbSet;
}
public void Dispose()
{
}
}
BaseContext
public class BaseContext<TContext> : DbContext where TContext : DbContext
{
static BaseContext()
{
Database.SetInitializer<TContext>(null);
}
protected BaseContext()
: base("name = ApplicationDbConnection")
{ }
}
FunctionContext
public class FunctionsContext : BaseContext<FunctionsContext>
{
public DbSet<App_Functions> Functions { get; set; }
}
Function Mapping class
[Table("Functions")]
public class App_Functions
{
public App_Functions()
{
}
[Key]
public int Function_ID { get; set; }
[StringLength(50)]
[Required]
public string Title { get; set; }
public int Hierarchy_level { get; set; }
}
Function Domain class
public class Functions
{
public Functions()
{
}
public int Function_ID { get; set; }
public string Title { get; set; }
public int Hierarchy_level { get; set; }
}
Controller class
public class HomeController : Controller
{
public ActionResult Index()
{
using (var repository = new GenericRepository<Functions>(new FunctionsContext()))
{
?????????????????????????????????
var query = repository.GetAll().Select(x => new Functions
{
Function_ID = x.Function_ID,
Title = x.Title,
Hierarchy_level = x.Hierarchy_level
});
foreach(var item in query)
{
var a2 = item.Title;
}
}
return View();
}
}
A:
The type parameter on your repository constructor is incorrect. It should be
new GenericRepository<App_Functions>(new FunctionsContext()))
Because App_Functions is the type of the entity.
| {
"pile_set_name": "StackExchange"
} |
Q:
What do I do when my ASP.Net website is not allowed to perform some operations defined by the security policy of my web hosting service?
My asp.net site coded in C# is running fine on my local system but when I uploaded the files on the httpdocs folder through plesk I am getting the following error:
Server Error in '/' Application.
________________________________________
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0246: The type or namespace name 'Xyz' could not be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 1: <%@ Application Language="C#" %>
Line 2: <%@ Import Namespace="xyz" %>
Line 3: <%@ Import Namespace="System.Web.Optimization" %>
Line 4: <%@ Import Namespace="System.Web.Routing" %>
Source File: g:\PleskVhosts\xyz.com\httpdocs\Xyz\Global.asax Line: 2
Show Detailed Compiler Output:
C:\Windows\SysWOW64\inetsrv> "C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe" /t:library /utf8output /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Deployment\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Deployment.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Services\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.Extensions\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel\v4.0_4.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.DynamicData\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.DynamicData.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Activities.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.ApplicationServices\v4.0_4.0.0.0__31bf3856ad364e35\System.Web.ApplicationServices.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_4.0.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activation\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activation.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.DataAnnotations\v4.0_4.0.0.0__31bf3856ad364e35\System.ComponentModel.DataAnnotations.dll" /R:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll" /out:"C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\ba70df64\8ad7fdd9\App_global.asax.8gpjfmvi.dll" /debug- /optimize+ /w:4 /nowarn:1659;1699;1701;612;618 /warnaserror- "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\ba70df64\8ad7fdd9\App_global.asax.8gpjfmvi.0.cs" "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\ba70df64\8ad7fdd9\App_global.asax.8gpjfmvi.1.cs"
Microsoft (R) Visual C# Compiler version 4.0.30319.17929
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.
g:\PleskVhosts\xyz.com\httpdocs\Xyz\Global.asax(2,11): error CS0246: The type or namespace name 'Xyz' could not be found (are you missing a using directive or an assembly reference?)
g:\PleskVhosts\xyz.com\httpdocs\Xyz\Global.asax(3,22): error CS0234: The type or namespace name 'Optimization' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)
g:\PleskVhosts\xyz.com\httpdocs\Xyz\Web.config(24,21): error CS0234: The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
________________________________________
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18056
Any help would be great.
## New error
****Server Error in '/' Application.
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Delegate.DelegateConstruct(Object target, IntPtr slot) +0
Owin.Loader.DefaultLoader..ctor(Func`3 next, Func`2 activator, IEnumerable`1 referencedAssemblies) +69
Microsoft.Owin.Host.SystemWeb.OwinBuilder.GetAppStartup() +65
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +28
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +418
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18056****
A:
You need to right click on your Project, and then select "Publish". You can either publish to the file system so you can alter your Web.config before you upload it to godaddy, or you could just set it to publish to the godaddy site. I'd choose the file system approach. One step at a time.
As you said in your comments, "I added all files and folders except for the solution file in the Projects folder", that doesn't do anything. To execute from that, it needs to run from within the Visual Studio IDE. To properly set up where all of the files are supposed to be for production use, you must Publish your web project.
A:
Had the same problem, the error can be fixed using the web.config. Add the level="Full" level into trust element, like so:
<system.web>
...
<trust level="Full" />
...
</system.web>
| {
"pile_set_name": "StackExchange"
} |
Q:
Which File Is Missing? "i686-apple-darwin11-llvm-g++-4.2: No such file or directory"
I'm getting the following error from my compiler:
g++ -c -m32 tracecone.cpp -I/usr/X11R6/include -I/usr/X11/include/GL -I/Users/owner/Documents/raytrace/Graphics -I../RayTrace -I/Users/owner/Documents/raytrace/Graphics -I/Users/owner/Documents/raytrace/VrMath -I/Users/owner/Documents/raytrace/OpenglRender -I/Users/owner/Documents/raytrace/RaytraceMgr
g++ -o -m32 tracecone ../RayTrace/RayTraceData.o tracecone.o /Users/owner/Documents/raytrace/OpenglRender/GlutRenderer.o /Users/owner/Documents/raytrace/RaytraceMgr/SceneDescription.o -L/usr/X11/lib -L/usr/X11R6/lib -L/Users/owner/Documents/raytrace/Graphics -L/Users/owner/Documents/raytrace/VrMath -lglut -lGLU -lGL -lX11 -lXext -lXmu -lXext -lXmu -lXt -lXi -lSM -lICE -lraygraph -lvrmath
i686-apple-darwin11-llvm-g++-4.2: tracecone: No such file or directory
make: *** [tracecone] Error 1
However, I am not sure which file it's saying is not there. Does it mean tracecone? or one of the library files? Either way, it looks like everything is right where it should be.
What could cause this error?
Here is my make file:
PROG = tracecone
RBASE= /Users/owner/Documents/raytrace
GDIR=$(RBASE)/Graphics
MDIR=$(RBASE)/VrMath
ODIR=$(RBASE)/OpenglRender
MANDIR=$(RBASE)/RaytraceMgr
CFLAGS = -w -s -O2 -ansi -DSHM
XLIBS = -lX11 -lXext -lXmu -lXext -lXmu -lXt -lXi -lSM -lICE
LIBS = -lglut -lGLU -lGL
RAYLIBS = -lraygraph -lvrmath
INCLS = -I/usr/X11R6/include -I/usr/X11/include/GL
INCL1 = -I$(GDIR) -I../RayTrace -I$(GDIR) -I$(MDIR) -I$(ODIR) -I$(MANDIR)
LIBDIR = -L/usr/X11/lib -L/usr/X11R6/lib -L$(GDIR) -L$(MDIR)
#source codes
SRCS = $(PROG).cpp
#substitute .cpp by .o to obtain object filenames
OBJS = $(SRCS:.cpp=.o)
#in ../Graphics
OBJOD = $(ODIR)/GlutRenderer.o
OBJO = GlutRenderer.o
OBJMAND = $(MANDIR)/SceneDescription.o
OBJMAN = SceneDescription.o
OBJ_temp = ../RayTrace/RayTraceData.o
#$< evaluates to the target's dependencies,
#$@ evaluates to the target
$(PROG): $(OBJS)
g++ -o -m32 $@ $(OBJ_temp) $(OBJS) $(OBJOD) $(OBJMAND) $(LIBDIR) $(LIBS) $(XLIBS) $(RAYLIBS)
$(OBJS):
g++ -c -m32 $*.cpp $(INCLS) $(INCL1)
$(OBJ1):
cd $(GDIR); g++ -m32 -c $*.cpp $(INCLS)
$(OBJM):
cd $(MDIR); g++ -m32 -c $*.cpp $(INCLS)
$(OBJO):
cd $(ODIR); g++ -m32 -c $*.cpp $(INCLS)
$(OBJMAN):
cd $(MANDIR); g++ -m32 -c $*.cpp $(INCLS)
clean:
rm $(OBJS)
clean1:
rm $(OBJD1)
Thanks in advance.
A:
You should place your target right after -o flag:
g++ -o $@ -m32 ...
Flag -o means output and in case of g++ -o tracecone ... you'll specify tracecone as output, but in case g++ -o -m32 tracecone ... you are specifying -m32 as output and tracecone as one of the object files. And g++ says that there is no such object file because there is actually no such file.
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript, changing page content
I'm trying to do an example in which I use javascript to change a page content. Suppose I have a page as :
<html>
<head>
</head>
<body>
<select id="a96780" multiple="multiple" name="a96780" size="3" value="deneme">
<option selected="selected" value="#ANY">ALL</option>
<option value="1111294">Ex1</option>
<option value="1111292">Ex2</option>
<option value="1111290">Ex3</option>
</select>
</body>
</html>
I would like to be able to close all the options, Ex1, Ex2, Ex3 (set their type's to hidden or by other means) when the page loads. In order to achieve this I followed the instructions online however failed to do so by doing:
<script type="text/javascript">
function myFunction()
{
var selectBox = document.getElementById("a96780");
alert("smt");
alert(selectBox.name);
}
myFunction();
</script>
In the script above, I'm trying to print out the name of the element to confirm that I actually have a hold of it. Last line however is never printed. How can I comfirm that I have a initialized the element as selectBox and how should I proceed from there. Would the option values be enough to refer to the items: "Ex1, Ex2 and Ex3" ?
edit 1 : I have absolutely no link to the html, I can not modify the body tag nor can put any buttons that can start myFunction thereby whatever I do, I must do it by js only. Besides this it would also be wonderful if you can lead me regarding how I should proceed. For instance can I refer to the option items from their values ?
A:
My solution was :
<html>
<head>
<script type="text/javascript">
function initialTypeCorrection()
{
var selectBox = document.getElementById("a96780");
if(selectBox != null)
{
var options = selectBox.getElementsByTagName("option");
for (var i = 0; i < options.length; i ++)
{
// Alternative 1
if(options[i].value=="1111294" || options[i].value=="1111292" || options[i].value=="1111290")
{
options[i].disabled = "true";
options[i].text = "";
}
}
}
}
window.onload = initialTypeCorrection;
</script>
</head>
<body>
<select id="a96780" multiple="multiple" name="a96780" size="4">
<option selected="selected" value="#ANY">all</option>
<option value="1111294">a1</option>
<option value="1111292">a2</option>
<option value="1111290">a3</option>
</select>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this flex item have its height limited?
I've stumbled across something that happens to my flex child items, illustrated in this JSFiddle.
This is the code:
<div style="position:absolute; top:10px; left:10px; background-color:yellow; height:50px; width:200px; display:flex; flex-direction:column;">
<div style="overflow:hidden;">inner div text<br>inner div text<br>inner div text<br>inner div text<br>inner div text</div>
</div>
<div style="position:absolute; top:10px; left:250px; background-color:green; height:50px; width:200px;">
<div style="overflow:hidden;">inner div text<br>inner div text<br>inner div text<br>inner div text<br>inner div text</div>
</div>
<div style="position:absolute; top:200px; left:100px; border:1px solid black; height:300px; width:300px; overflow:hidden;">
<div style="overflow:hidden;">
Why does the inner div on the yellow left have its height limited to that of its container, but not the inner div on the green right? As far as I can tell there are 4 things combined that trigger this:<br>1) the container has position:absolute<br>
2) the container has a fixed height/width<br>
3) the container is flexbox<br>
4) the flex item has overflow:hidden<br><br>But I can't find anything exactly in the flexbox spec to cause this behaviour. Why is it happening?
</div>
</div>
Basically, the flex item inside a flexbox container with a fixed height is getting its height limited to that of the flexbox container when overflow:hidden is set. On the other hand, an equivalent div inside a fixed height non-flex container just expands to the size of its content.
Where in the flexbox spec is this behaviour specified? Is it just a browser quirk? That seems unlikely as it happens in Firefox, Chrome, and IE. Assuming it is well-defined flexbox behaviour, I'd like to know exactly how and when it is triggered. Also note that when you remove overflow:hidden from the child (not the container), its height stops getting limited.
A:
OK, I think I figured out what's happening.
Up until flexbox, there was no way to cause an element to be smaller than the size of its content without explicitly settings its width/height. With flexbox, there is a second way.
Para 9.11 of the flexbox spec talks about how to calculate a flex-item's cross size. Basically if the flex item has align-self: stretch set (which in my example it does), it will try to fill the container's flex line (in my example the vertical line, ie. height). This is implicitly setting the flex item's height, without explicitly using the height property. The container itself needs to have a definite height, too, to be handed down to the flex item (in my example the container's height is explicitly set through the height CSS attribute, which I guess ultimately needs to be done at some point in the chain).
However, two conditions need to be met: the browser needs to want to resize the item, and the item needs to be resizable.
To make the browser want to resize the item, it needs to be a flex item that meets the conditions mentioned above for its cross size (which ultimately may determine its width or height) to be calculated by the browser with relation to its container's cross size.
To make the item resizable in this context, it needs to both not have flex-shrink set to 0 (note that flex:none is shorthand for setting flex-shrink to 0, amongst other things), and have overflow:hidden set (presumably giving the browser "permission" to resize the flex item such that its content will be larger than it, and get hidden). Only then will the browser actually resize the flex item itself.
This is notably different behaviour to what happens outside the flexbox model, where the child of a fixed height/width container may have it content clipped, but it will retain the necessary size to hold its content. Part of the content will merely be hidden. Here, the flex item really is being (potentially) resized to be smaller than its content, which has quite important implications (particularly if you want a child element to have a scrollbar for its content).
| {
"pile_set_name": "StackExchange"
} |
Q:
appium driver throws Exception when using regex?
I am using appium to do some ui automation.I am having problems with regex;
WebDriverException throwed with the code,and the element totally exists:
phonedriver.findElement(By.xpath("//android.view.View[matches(@text,'sometext\\d+')]"))
Here are exception message:
An unknown server-side error occurred while processing the command. Original error: java.lang.IllegalStateException: Unable to evaluate expression. See cause
Here are my capability info:
Capabilities {appActivity: com.tencent.mm.ui.LauncherUI, appPackage: com.tencent.mm, deviceName: 127.0.0.1:62001, fastReset: false, fullReset: false, newCommandTimeout: 999999, noReset: true, platformName: Android, platformVersion: 5.1.1, resetKeyboard: true, udid: 127.0.0.1:62001}
Here are my pom:
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>7.3.0</version>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
A:
You have two issues:
matches() is only available in XPath 2.0 and not 1.0 see: http://www.w3.org/TR/xquery-operators/#func-matches
Selenium, but also Chrome and Firefox browser are using Xpath 1.0.
You can try any Xpath 2.0 functions in the JS-console of the browser and it will show you an error. e.g.: $x("lower-case('ABC')")
to get the text use . or text() e.g $x("//*[contains(text(),'bob')]")
As a solution for your problem, you can get all elements containing your text "//android.view.View[contans(text(),'sometext')]") and then loop through them in JAVA to find the correct one
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this a wrong way of doing things? answering questions just for bounty?
So I am in need of more rep as you can clearly see. But I do not want to answer questions just because there is a bounty on them because of the times my questions (bounty less) have been answered well. So is it wrong to just target bountified (sp) questions? Does it go against some rule aside from morality?
A:
If you can answer them, answer them!
Bountied questions are on the "featured" tab. This is mostly done to attract more attention, because the OP is looking for a (good) answer.
So, no, this is perfectly normal to answer the questions on which a bounty is set. However, it is common to see an extensive answer being posted, rather than a quick-n-dirty one.
A:
There's no obligatory minimum level of participation on a Stack Exchange site. It's neither immoral nor against prevailing community standards, even if you didn't participate at all. Of course, we appreciate it when someone contributes to this community; it's a good thing. But it is by no means obligatory.
Since there's no obligation to participate at all, there's certainly no obligation to answer any particular kind of question. Every time you post a valuable answer, you're helping the community. Even if you only or mostly answered bountied questions, you would be helping the community. (Assuming your answers are good, that is.) There's nothing wrong with this.
With that said, focusing on bountied questions to the total exclusion of non-bountied isn't necessarily the course of action that will achieve your goals best. Why?
If you want reputation, you can get it by posting good answers to lots of questions. Most bountied questions are especially difficult to answer well (though there are exceptions). You can get lots of reputation from answering bountied questions but you can get lots more by answering plenty of "easier" questions.
If you want to help people, and you see a question and know the answer, then you might as well post it, whether or not the question has a bounty. When a question has a bounty, you're not guaranteed to get it just by posting an answer. Whether or not a question has a bounty, you can gain reputation by having your answers upvoted.
Of course, complications sometimes arise in that some answers take significant time and effort to compose. You might choose to focus more on bountied questions, while still also answering some non-bountied questions.
Most people are interested in reputation points and in helping people, to varying degrees. However much each one interests you, it makes sense to consider answering non-bountied questions as well as bountied ones.
Finally, please note that answers are not the only way to help. In particular, asking good questions is an important way to contribute. Sometimes people worry that they've asked too many questions and not posted enough answers. But a question is a positive contribution to the community, assuming it is asked well. (In this way, questions are like answers--good questions and answers help us all.)
| {
"pile_set_name": "StackExchange"
} |
Q:
vector::erase(remove(....)) is not working
I came up with a program
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> a = {1,2,3,7,1,5,4};
vector<int> b = {6,7,4,3,3,1,7};
a.erase(remove(a.begin(),a.end(),a[0]),a.end());
b.erase(remove(b.begin(),b.end(),b[0]),b.end());
return 1;
}
For this specific example, my GNU gdb Ubuntu states that at return 1 line: a = {2,3,7,1,5,4} which is not expected (only deletes one 1), and b = {7,4,3,3,1} which is not expected.
My expectation is a and b should be a=2,3,7,5,4 and b=7,4,3,3,1,7.
What's going on here?
A:
std::remove takes the third argument by reference and it invalidates references into the range it works on (in the sense that it shifts stuff around and thus changes values of elements in the range). The problem is that you change a[0], the reference argument, during the call, which you must not do.
To fix this, pass a copy instead:
a.erase(remove(a.begin(),a.end(),int{a[0]}),a.end());
| {
"pile_set_name": "StackExchange"
} |
Q:
Cron Tasks on load balanced web servers
I'm looking for better solution to handling our cron tasks in a load balanced environment.
Currently have:
PHP application running on 3 CentOS servers behind a load balancer.
Tasks that need to be run periodically but only on a single machine at a time.
Good old cron set up to run those tasks on the first server.
Problems if the first server is out of play for whatever reason.
Looking for:
Something more robust and de-centralized.
Load balancing the tasks so multiple tasks would run only once but on random/different servers to spread the load.
Preventing not having the tasks run when the first server goes down.
Being able to manage tasks and see aggregate reports ideally using a web interface.
Notifications if anything goes wrong.
The solution doesn't need to be implemented in PHP but it would be nice as it would allow us to easily tweak it if needed.
I have found two projects that look promissing. GNUBatch and Job Scheduler. Will most likely further test both but I wonder if someone has better solution for the above.
Thanks.
A:
You can use this small library that uses redis to create a temporary timed lock:
https://github.com/AlexDisler/MutexLock
The servers should be identical and have the same cron configuration. The server that will be first to create the lock will also execute the task. The other servers will see the lock and exit without executing anything.
For example, in the php file that executes the scheduled task:
MutexLock\Lock::init([
'host' => $redisHost,
'port' => $redisPort
]);
// check if a lock was already created,
// if it was, it means that another server is already executing this task
if (!MutexLock\Lock::set($lockKeyName, $lockTimeInSeconds)) {
return;
}
// if no lock was created, execute the scheduled task
scheduledTaskThatRunsOnlyOnce();
To run the tasks in a de-centralized way and spread the load, take a look at: https://github.com/chrisboulton/php-resque
It's a php port of the ruby version of resque and it stores the data in the same exact format so you can use https://github.com/resque/resque-web or http://resqueboard.kamisama.me/ to monitor the workers and see reports
A:
Assuming you have a database available not hosted on one of those 3 servers;
Write a "wrapper" script that goes in cron, and takes the program you're running as its argument. The very first thing it does is connect to the remote database, and check when the last time an entry was inserted into a table (created for this wrapper). If the last insertion time is greater than when it was supposed to run, then insert a new record into the table with the current time, and execute the wrapper's argument (your cron job).
Cron up the wrapper on each server, each set X minutes behind the other (server A runs at the top of the hour, server B runs at 5 minutes, C at 10 minutes, etc).
The first server will always execute the cron first, so the other two servers never will. If the first server goes down, the second server will see it hasn't ran, and will run it.
If you also record in the table which server it was that executed the job, you'll have a log of when/where the script was executed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java Program to make Tic Tac Toe not working
For my programming class I'm supposed to make a program that simulates a game of tic tac toe. My teacher provided all the methods and said we shouldn't need to add any or take any away, and told us we shouldn't change the playGame method, but no matter what I do there seems to be some sort of disconnect between the playGame method and the processComputerMove/processHumanMove methods. Whenever I try to run the program, it seems like those methods just get skipped over entirely even if they have nothing in them but a simple print statement. I was wondering how to fix this. Here's my (unfinished and not working) code so far:
import java.util.*;
public class TicTacToe {
private static Scanner keyboard = new Scanner(System.in);
private static char[] board = new char[9];
// *******************************************************
public static void main(String[] args) {
String answer;
System.out.println("Welcome to Tic-Tac-Toe!!");
System.out.print("Do you want to play a game? (Y/N) ");
answer = keyboard.next();
if (answer.charAt(0) == 'Y' || answer.charAt(0) == 'y' ) {
playGame();
} else if (answer.charAt(0) == 'N' || answer.charAt(0) == 'n'){
System.out.println("Goodbye!");
}
}
// *******************************************************
private static void playGame() {
char currentPlayer = determineFirstPlayer();
System.out.println("The computer is X, the human is O.\n");
initializeGameBoard();
while (!isDone()) {
if (currentPlayer == 'c' || currentPlayer == 'C') { // the computer
processComputerMove();
currentPlayer = 'h'; // the human
} else {
displayGameBoard();
processHumanMove();
currentPlayer = 'c'; // the computer
}
}
displayGameBoard();
System.out.println("Game over!");
}
public static char determineFirstPlayer() {
System.out.print("Who would you like to make the first move? (h = human/c = computer) ");
String response = keyboard.next();
char player = response.charAt(0);
return player; // return 'c' or 'h' as appropriate
}
// *******************************************************
private static void initializeGameBoard() {
String playBoard = " | | \n---+---+---\n | | \n---+---+---\n | | ";
board[0] = playBoard.charAt(2);
board[1] = playBoard.charAt(6);
board[2] = playBoard.charAt(10);
board[3] = playBoard.charAt(13);
board[4] = playBoard.charAt(17);
board[5] = playBoard.charAt(21);
board[6] = playBoard.charAt(24);
board[7] = playBoard.charAt(28);
board[8] = playBoard.charAt(32);
}
// *******************************************************
private static void processComputerMove() {
Random rand = new Random();
int array = rand.nextInt(8);
int comp = rand.nextInt(8);
if (board[array] != 'X' || board[array] != 'O') {
board[array] = 'X';
System.out.println("The computer chooses cell "+board[array]+".");
} else {
board[array] = board[comp];
board[comp] = 'X';
}
}
// *******************************************************
private static void processHumanMove() {
System.out.println("Enter an empty position number (0-8) ");
int position = keyboard.nextInt();
if (board[position] != 'X' || board[position] != 'O') {
board[position] = 'O';
} else {
System.out.println("Error! Must enter an empty position from 0-9.");
}
}
// *******************************************************
private static void displayGameBoard() {
System.out.println(" "+board[0]+" | "+board[1]+" | "+board[2]+" \n---+---+---\n "+board[3]+" | "+board[4]+" | "+board[5]+" \n---+---+---\n "+board[6]+" | "+board[7]+" | "+board[8]+" ");
}
// *******************************************************
private static boolean isDone() {
isComputerWin();
isHumanWin();
isTie();
if (isComputerWin()) {
return true;
} else if(isHumanWin()) {
return true;
} else if (isTie()) {
return true;
} else {
return false;
}
}
// *******************************************************
private static boolean isComputerWin() {
if ((board[0] == 'X' && board[1] == 'X' && board[2] == 'X') || (board[0] == 'X' && board[3] == 'X' && board[6] == 'X') ||
(board[0] == 'X' && board[4] == 'X' && board[8] == 'X') || (board[3] == 'X' && board[4] == 'X' && board[5] == 'X') ||
(board[1] == 'X' && board[4] == 'X' && board[7] == 'X') || (board[2] == 'X' && board[5] == 'X' && board[8] == 'X') ||
(board[6] == 'X' && board[7] == 'X' && board[8] == 'X') || (board[6] == 'X' && board[4] == 'X' && board[2] == 'X')){
return true;
} else {
return false; // return true or false as appropriate
}
}
// *******************************************************
private static boolean isHumanWin() {
if ((board[0] == 'O' && board[1] == 'O' && board[2] == 'O') || (board[0] == 'O' && board[3] == 'O' && board[6] == 'O') ||
(board[0] == 'O' && board[4] == 'O' && board[8] == 'O') || (board[3] == 'O' && board[4] == 'O' && board[5] == 'O') ||
(board[1] == 'O' && board[4] == 'X' && board[7] == 'O') || (board[2] == 'O' && board[5] == 'O' && board[8] == 'O') ||
(board[6] == 'O' && board[7] == 'O' && board[8] == 'O') || (board[6] == 'O' && board[4] == 'O' && board[2] == 'O')){
return true;
} else {
return false; // return true or false as appropriate
}
}
// *******************************************************
private static boolean isTie() {
if (!((board[0] == 'O' && board[1] == 'O' && board[2] == 'O') || (board[0] == 'O' && board[3] == 'O' && board[6] == 'O') ||
(board[0] == 'O' && board[4] == 'O' && board[8] == 'O') || (board[3] == 'O' && board[4] == 'O' && board[5] == 'O') ||
(board[1] == 'O' && board[4] == 'X' && board[7] == 'O') || (board[2] == 'O' && board[5] == 'O' && board[8] == 'O') ||
(board[6] == 'O' && board[7] == 'O' && board[8] == 'O') || (board[6] == 'O' && board[4] == 'O' && board[2] == 'O')) ||
!((board[0] == 'X' && board[1] == 'X' && board[2] == 'X') || (board[0] == 'X' && board[3] == 'X' && board[6] == 'X') ||
(board[0] == 'X' && board[4] == 'X' && board[8] == 'X') || (board[3] == 'X' && board[4] == 'X' && board[5] == 'X') ||
(board[1] == 'X' && board[4] == 'X' && board[7] == 'X') || (board[2] == 'X' && board[5] == 'X' && board[8] == 'X') ||
(board[6] == 'X' && board[7] == 'X' && board[8] == 'X') || (board[6] == 'X' && board[4] == 'X' && board[2] == 'X'))) {
return true;
} else {
return false;
}
}
}
EDIT: shoot, I accidentally posted before I was done typing. I think the error is in processComputerMove/processHumanMove methods, because even when I put just print statements in there, nothing shows up from them when I run the program.
A:
Your isTie() method is one of the culprits.
Looking at it with a debugger, I observe that your boolean statements to check for a "tie" condition are evaluation to true every time.
Yes, I mean this monster statement:
(!((board[0] == 'O' && board[1] == 'O' && board[2] == 'O') || (board[0] == 'O' && board[3] == 'O' && board[6] == 'O') ||
(board[0] == 'O' && board[4] == 'O' && board[8] == 'O') || (board[3] == 'O' && board[4] == 'O' && board[5] == 'O') ||
(board[1] == 'O' && board[4] == 'X' && board[7] == 'O') || (board[2] == 'O' && board[5] == 'O' && board[8] == 'O') ||
(board[6] == 'O' && board[7] == 'O' && board[8] == 'O') || (board[6] == 'O' && board[4] == 'O' && board[2] == 'O'))
The actual evaluation is false, but since you negate it, you flip the value to true, thus short-circuiting your entire expression, causing you to (eventually) return true.
My gut tells me that your definition of a tie is skewed - wouldn't a tie be easier defined as neither a human win, nor a computer win?
If we trim down the isDone() method to only look at isHumanWin and isComputerWin (as well as get rid of the useless method calls at the top), and delete the unnecessary isTie method, we get a (mostly) playable Tic-Tac-Toe game. It kind of peters out towards the fourth move, but that is an exercise to the reader.
private static boolean isDone() {
return isComputerWin() || isHumanWin();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ArcGIS API - call function onClick()
I have managed to get my tiled maps working using the ArcGIS javascript API. However, I want to be able to switch layers (showing different years). I created a function that will do this:
require(["esri/map",
"esri/layers/ArcGISTiledMapServiceLayer",
"esri/geometry/Point",
"esri/SpatialReference",
"dojo/domReady!"],
function (Map, Tiled, Point, SpatRef) {
...
function veranderTiled(jaar){
map_Thema_2.removeAllLayers();
tiled = new Tiled(
"http://tiles.arcgis.com/tiles/nSZVuSZjHpEZZbRo/arcgis/rest/services/Historische_tijdreis_"+jaar+"/MapServer");
map_Thema_2.addLayer(tiled);
}
...
});
I want to call this function when I, say, press a button at a random place on my page. Like this:
<input name="" type="button" onClick="veranderTiled(2015)" value="Ander jaar" />
The function itself works fine, but I cannot seem to call it from anywhere outside of the require(...) part. I am not sure how javascript handles such accessibility (mostly used to C++), but I do wonder what I should change in order to be able to call this function from outside this particular script.
Edit: as expected, the console returns that the function is not defined. Is there a way to point it to the right location (something like map.veranderTiled(2015)?)
A:
This is an issue of scope - as you surmised, the function is only defined within the scope of the require callback.
There are typically 2 ways to solve this problem.
The first is to give the button an ID and assign it the event handler within the require callback (assuming that either your scripts are at the end of body or you have required dojo/domReady! to wait for the body to load first):
require(..., function (...) {
...
document.getElementById('veranderTiledButton').onclick = function () {
veranderTiled(2015);
};
});
(You could also use dojo/on to hook up the event, though it's not crucial in this case.)
The second way is to make the function globally available, which is generally discouraged since the global variable scope quickly becomes the wild west if your code does this sporadically:
var veranderTiled; // Declare outside to be globally available
require(..., function (...) {
...
// Define inside to be able to use loaded modules
veranderTiled = function (jaar) {
...
};
...
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make a for loop slower?
setInterval(()=>{
for (j = 0; j < obj.length; j++) {
}
})
I have this loop setup, is there any way to make the for loop go slower? obj length can be as big as 200-400 arrays. Jquery answers accepted.
A:
Promise based delay:
const delay = x => new Promise(res => setTimeout(res, x));
(async () => {
for (let j = 0; j < 10; j++) {
console.log(j);
await delay(1000);
}
})();
(Furthermore, i believe that jQuery should never be used.)
| {
"pile_set_name": "StackExchange"
} |
Q:
&& Syntax Error AGP for Dummies
So, I am currently learning off of the Android Game Programming For Dummies book, and have run into the problem where (On page 128) I'm given the code
case MotionEvent.ACTION_DOWN:
if (X > (screenW-playButtonUp.getWidth())/2 &&
X < ((screenW-playButtonUp.getWidth())/2) +
playButtonUp.getWidth()) &&
Y > (int)(screenH*0.45) &&
Y < (int)(screenH*0.45) +
playButtonUp.getHeight()) {
playButtonPressed = true;
}
break;
and the 4th to 6th lines are accompanied by the error "Syntax error on token "&&", throw expected". I have no idea on how to fix this, I'd really appreciate any alternatives or help.
A:
The parentheses are messed up. Specifically, the second ) in this line:
// -- This one
// v
playButtonUp.getWidth()) &&
matches the ( starting the if condition, meaning the && after it is not part of the condition. Remove that extra ).
Here's a parentheses analysis:
if (X > (screenW-playButtonUp.getWidth())/2 && // ( = 3, ) = 2; Nested level: 1
X < ((screenW-playButtonUp.getWidth())/2) + // ( = 3, ) = 3; Nested level: 1
playButtonUp.getWidth()) && // ( = 1, ) = 2; Nested level: 0
Y > (int)(screenH*0.45) && // ( = 2, ) = 2; Nested level: 0
Y < (int)(screenH*0.45) + // ( = 2, ) = 2; Nested level: 0
playButtonUp.getHeight()) { // ( = 1, ) = 2; Nested level: -1?!?
playButtonPressed = true; // Total ( = 12, ) = 13
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display comma delimited JSON value as a list?
Say I have an array like this:
var ARTISTS: Artist[] = [
{
"name": "Barot Bellingham",
"shortname": "Barot_Bellingham",
"reknown": "Royal Academy of Painting and Sculpture",
"bio": "Some bio here...",
"friends": "James, Harry, Bob"
}
Is it possible to display values for the key “friends” as an unordered list where each friend would be it’s own list item, e.g.:
<ul>
<li>James</li>
<li>Harry</li>
<li>Bob</li>
</ul>
I do realize the "friends" would be better stored as a nested array in order to display as a list, but I'm looking into this as a potential workaround for another issue.
Thank you!
P.S. I'm using Angular 2.
A:
You can use String.prototype.split() to get an array of friends.
var arrayOfFriends = Artist[0].friends.split(", ");
// arrayOfFriends = ['James', 'Harry', 'Bob']
From there loop over the array and create your list
| {
"pile_set_name": "StackExchange"
} |
Q:
AlertDialog.Builder How Can I Access the the 'PositiveButton'?
I am using AlertDialog.Builder to create a dialog with a EditText and two buttons, 'OK' and 'Cancel'. I create the OK and Cancel buttons with AlertDialog.Builder.setPositiveButton() and .setNegativeButton() respectively. The purpose of the dialog is to request an I.P. address from the user.
Initially I want to have the OK button disabled and attach to the EditText an OnKey listener so that when the user types the onKey listener is called and I can check the current EditText value with a regular expression for a valid IP address. Should a valid IP address be entered I'd then want to enable the OK button, but as I use the setPositiveButton() I have no idea what the id of the button is.
Can I get the id of the OK button?
A:
You dont need the id of the button,all you need is to implement DialogInterface.onClickListener()
In the onKeyListener() you add some test if the field is filled with correct input or not
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(enabled);
And for the click listener of the OK button. Remember that you need to set the button before you do .getButton()
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
//Do what you want when the user presses the Ok button
}});
| {
"pile_set_name": "StackExchange"
} |
Q:
Error while compiling static Qt 5.10.0 with PostgreSQL
I'm trying to compile Qt 5.10.0 with PostgreSQL 10 (or 9.2, but same error) using mingw on Windows 7.
However when I include the psql include and lib dirs I always get the following Error after mingw32-make:
g++ -c -fno-keep-inline-dllexport -O2 -std=c++1z -fno-exceptions -Wextra -Wall -
W -Wvla -Wdate-time -DUNICODE -D_UNICODE -DWINVER=0x0601 -D_WIN32_WINNT=0x0601 -
DQT_MOC -DQT_NO_CAST_FROM_ASCII -DQT_NO_CAST_FROM_BYTEARRAY -DQT_NO_COMPRESS -DQ
T_NO_FOREACH -DQT_NO_NARROWING_CONVERSIONS_IN_CONNECT -DQT_USE_QSTRINGBUILDER -D
QT_NO_EXCEPTIONS -DQT_NO_DEBUG -DQT_BOOTSTRAP_LIB -DQT_VERSION_STR="\"5.10.0\""
-DQT_VERSION_MAJOR=5 -DQT_VERSION_MINOR=10 -DQT_VERSION_PATCH=0 -DQT_BOOTSTRAPPE
D -DQT_NO_CAST_TO_ASCII -I. -I. -I..\..\..\include -I..\..\..\include\QtCore -I.
.\..\..\include\QtCore\5.10.0 -I..\..\..\include\QtCore\5.10.0\QtCore -I..\..\..
\include\QtXml -I..\..\..\include\QtXml\5.10.0 -I..\..\..\include\QtXml\5.10.0\Q
tXml -IC:\POSTGRESQL\10\include -I..\..\..\mkspecs\win32-g++ -o .obj\release\m
oc.o moc.cpp
In file included from symbols.h:33:0,
from parser.h:32,
from moc.h:32,
from moc.cpp:30:
token.h:65:7: error: expected identifier before 'void'
F(THIS) \
^
token.h:216:33: note: in definition of macro 'CREATE_ENUM_VALUE'
#define CREATE_ENUM_VALUE(Name) Name,
^
...
token.h:263:1: error: expected declaration before '}' token
};
^
Makefile.Release:314: recipe for target '.obj/release/moc.o' failed
I googled and found a thread on the qt forums where someone had the same Error, but no solution:
https://forum.qt.io/topic/66218/trubble-with-static-qt5-6-0-with-qt-sql-psql-compiling-from-source
My configure command looks like this:
configure -prefix C:\Qt\Static\5.10.0 -static -release -nomake tests -nomake examples -confirm-license -I"C:\POSTGRESQL\10\include" -L"C:\POSTGRESQL\10\lib" -opensource -qt-zlib -qt-libpng -qt-libjpeg -sql-psql -opengl desktop
the compilation works just fine if I remove
-I"C:\POSTGRESQL\10\include"
-L"C:\POSTGRESQL\10\lib"
but without psql obviously.
Any ideas on how to resolve this issue would be highly appreciated, thanks.
A:
It seems like you haven't built Qt recently (post 5.8) - the -I and -L configuration syntax is no longer supported.
For me postgres just works, all I need is the -sql-psql configuration flag and the library in my system path.
If that alone doesn't work, you could specify the paths via the addition of the following configuration flags:
PSQL_INCDIR=C:\POSTGRESQL\10\include
PSQL_LIBDIR=C:\POSTGRESQL\10\lib
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL multiple rows in single row
Hi everyone I have this table and I want to show result in single row group by client id and show availability for stock 1 and 2.
Here is my table
id client stock material quantity availability date
62 56 1 0 0 100 2017-12-16 23:55:01
63 56 2 0 0 900 2017-12-16 23:55:01
64 56 1 100 -20 80 2017-12-16 23:55:20
65 56 1 80 100 180 2017-12-16 23:56:06
66 56 1 180 200 380 2017-12-16 23:56:21
67 56 1 380 500 880 2017-12-16 23:58:11
68 56 1 880 -580 300 2017-12-16 23:58:38
69 56 2 900 -90 810 2017-12-17 23:59:18
Outcome I want is get result from last date, group by client id and combine stock 1 and stock 2 to single row
client availability1 availability2
56 300 810
I try this query
SELECT
historys.id
,(CASE WHEN historys.stock = 1 THEN availability END) AS availability1
,(CASE WHEN historys.stock = 2 THEN availability END) AS availability2
FROM historys
GROUP BY historys.client
ORDER by historys.id
The result is
id availability1 availability2
56 NULL 810
I will be grateful if someone help me. Thanks.
A:
You need to filter to the right rows before the aggregation. Here is one method:
SELECT h.client,
MAX(CASE WHEN h.stock = 1 THEN h.availability END) AS availability1
MAX(CASE WHEN h.stock = 2 THEN h.availability END) AS availability2
FROM historys h
WHERE h.date = (SELECT MAX(h2.date) FROM historys h2 WHERE h2.stock = h.stock)
GROUP BY h.client
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a guide for when to cluster GitLab EE, for example when you reach a certain number of users or projects?
Using a private GitLab EE server, what is the best practice to use when scaling up the number of servers in your cluster? For example: "For every x users or y projects, then you should consider adding another server to the cluster."
A:
GitLab have defined recommendations for the Hardware Requirements for application servers to cater for a range of users here:
https://gitlab.com/gitlab-org/gitlab-ee/blob/master/doc/install/requirements.md#hardware-requirements
You may want to consider taking a look at the High Availability guidance for clustering, if you plan to exceed those thresholds or if you require redundancy should one of your application servers hosting your GitLab instance go offline:
https://about.gitlab.com/high-availability/
Note, that due to the decentralised nature of git, it is highly conducive to working offline. Your users will only require connectivity to the GitLab instance when syncing branches or managing issues and merge requests via the Web interface.
| {
"pile_set_name": "StackExchange"
} |
Q:
Popup window link launching in window as well as in the browser tab
I'm working on a website built using Laravel and AngularJS.
I want a certain link to open in a popup window.
The javascript code is
function popitup(url) {
newwindow=window.open(url,'test','height=400,width=550');
if (window.focus) {newwindow.focus()}
return false;
}
and the link is
<a ui-sref="test({id:test.id})" class="btn btn-primary fright" onclick="return popitup(this.href)" oncontextmenu="return false;">Resume</a>
when I click on the button the popup works fine but the link also opens up in the tab where I clicked it, but I don't want it to.
Is there a way to do it?
A:
I would guess ui-sref will also bind a click-event and that event will trigger before yours.
You could skip the ui-sref and put the url in a data-attribute or inside the onclick-attribute. You could get the url using $state.href() instead. Then the problem may disappear.
Edit
You could bind it to a scope function and skip onclick all toghether. Something like this:
In the Controller (Also make sure you include $state in the controller first):
$scope.popitup = function(stateName, options) {
var url = $state.href(stateName, options);
newwindow=window.open(url,'test','height=400,width=550');
if (window.focus) {newwindow.focus()}
}
And in the HTML you invke the popuitup function with the state name and its parameters:
<a ng-click="popitup('test', {id:test.id})"
class="btn btn-primary fright" oncontextmenu="return false;">Resume</a>
Also see documentation for state.href.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Sharing with Subject E-Mail/Whatsapp
I am using android native sharing with this code:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "I like to share with you some stuff.");
intent.putExtra(Intent.EXTRA_SUBJECT, "I like to share with you.");
intent.setType(CONTENT_TYPE_TEXT);
startActivity(Intent.createChooser(intent, "Share");
When I use E-Mail as the sharing channel, I get what i want:
Subject: I like to share with you.
Text: I like to share with you some stuff.
When I use WhatsApp as the sharing channel, I get the following text:
I like to share with you.
I like to share with you some stuff.
What do I expect when sharing with Whatsapp:
I like to share with you some stuff.
Is there any option/flag indicating a sharing channel to suppress the subject, if the sharing channel does not support a subject basically.
E.g. E-Mail supports subjects -> Use the provided intent extra.
WhatsApp does not support subjects -> Do not use the provided intent extra.
A:
Using queryIntentActivities() method of PackageManager class, you can set the intent extras based on package name.
For more info, check this link: How to filter specific apps for ACTION_SEND intent (and set a different text for each app)
| {
"pile_set_name": "StackExchange"
} |
Q:
doing .length on json array returns undefined
I have following json encoded array coming from ajax call
{"country":{"0":"United States of America","United States of America":{"states":{"0":"Alaska","Alaska":{"cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"]}}}}}
Following is my ajax code
$.ajax({
method: "POST",
url: "test.php",
data: "action=2",
cache: 'false',
success: function(abcd){
alert(abcd);
var obj = new Array();
var obj = $.parseJSON(abcd);
alert(obj.country.length);
}
});
When i try using obj.country[0] it returns "United States of America". But when i try to get the length of the array using obj.country.length it returns undefined.
I have browsed a couple of posts and only difference i could see was use of dataType: json and using header() to define content type to json on .php page. I have tried both methods but that didn't work out either. And on .php page i have declared following as array:
$data = array();
$data['country'] = array();
$data['country']['United States of America'] = array();
$data['country']['United States of America']['states'] = array();
$data['country']['United States of America']['states']['Alaska']['cities'] = array();
A:
This is because obj.country isn't an array, but an object.
An object is enclosed in curly braces ({}) and an array in square ones ([]). See http://json.org/ for more information.
In your example content, "cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"] would be an array, which you can call with obj["country"]["United States of America"]["states"]["Alaska"]["cities"].
So, judging from your example this would work:
$us['name'] = "United";
$alaska['name'] = "Alaska";
$alaska['cities'] = array("city1", "city2");
$us['states'] = array($alaska)
$data = array($us);
I expect it would render like [{"name": "United", "states": [{"name":"Alaska", "cities": ["city1","city2"]}]}].
I'm sure it could be done better or more compact though, I don't have much experience with PHP in this regard.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery dataTables - How to clone a header to create a footer
I am using JSON to create data for DataTable but also the header. However, I noticed the footer is not created. So I need to it manually. My idea is to clone the header to create the footer but I dont' know how to do it.
I'm using the following code :
$.getJSON("http://127.0.0.1/info", function( data ) {
$(document).ready(function() {
$('#log').html( '<table class="display compact" id="log-data" width="100%"></table>' );
var table = $('#log-data').dataTable( {
"dom": '<"tblContainerT"T><"tblContainerTop"lf><rt><"bottom"ip>',
"tableTools": {
"sSwfPath": "/swf/copy_csv_xls_pdf.swf",
"TableToolsInit.sTitle": "data-export".
},
"data": data['tbody'],
"columns": data['thead'],
"lengthMenu":[[25,200,500,-1],[25,200,500,"All"]],
'fnInitComplete' : function () {
$("thead tr").clone().appendTo($("tfoot tr")) ;
}
});
new $.fn.dataTable.FixedHeader( table, {
bottom: true
});
});
});
The relevant part is the following :
'fnInitComplete' : function () {
$("thead tr").clone().appendTo($("tfoot tr")) ;
}
It's not working so something is going wrong. Do you know how to do it ?
Let me know if you need more information.
A:
It is hard to say when we dont know how your markup is.
If you have <tfoot></tfoot> only :
fnInitComplete : function() {
$("thead tr").clone().appendTo($("tfoot")) ;
}
demo -> http://jsfiddle.net/gu5qvjag/
If you have <tfoot><tr></tr></tfoot> :
fnInitComplete : function() {
$("thead tr th").each(function(i, th) {
$(th).clone().appendTo($("tfoot tr"));
});
}
demo -> http://jsfiddle.net/uj5dpbua/
Update. Sad to say, overlooked that the <table> itself is generated by code too :(
fnInitComplete : function() {
$("#log-data").append('<tfoot></tfoot>');
$("#log-data thead tr").clone().appendTo($("#log-data tfoot")) ;
}
| {
"pile_set_name": "StackExchange"
} |