text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Find the smallest $3$ digit number when divided by $7$ given the following conditions?
My Approach
I could solve the problem till this.
Numbers are given of the form $7k+3$ and $6k+5$, so I took $\text{lcm}(7,5)k-4=35k-4$. To be the smallest number $35k- 4 \leq 100 = 35k < 104$.
$\Rightarrow k< \frac{104}{35} \Rightarrow k=2$.
But I am not getting to any $3$ digit number.
A:
If $x$ leaves a remainder of $3$ when divided by $7$, a remainder of $1$ when divided by $5$, and a remainder of $5$ when divided by $6$, then $x$ must satisfy the system of congruences
\begin{align*}
x & \equiv 3 \pmod{7} \tag{1}\\
x & \equiv 1 \pmod{5} \tag{2}\\
x & \equiv 5 \pmod{6} \tag{3}
\end{align*}
The first congruence implies $x = 7k + 3$ for some $k \in \mathbb{Z}$. Substituting $7k + 3$ into the second congruence yields
$$7k + 3 \equiv 1 \pmod{5} \Rightarrow x = 5(7k + 3) + 1 = 35k + 16$$
Substituting $35k + 16$ into the third congruence yields
$$35k + 16 \equiv 5 \pmod{6} \Rightarrow x = 6(35k + 16) + 5 = 210k + 101$$
The smallest three-digit integer of this form is $101$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get TaskManager containers registered with Job Manager container for flink?
Trying to play with flink docker image for the first time. I am following instructions at https://hub.docker.com/_/flink which says
You can run a JobManager (master).
$ docker run --name flink_jobmanager -d -t flink jobmanager
You can also run a TaskManager (worker). Notice that workers need to register
with the JobManager directly or via ZooKeeper so the master starts to
send them tasks to execute.
$ docker run --name flink_taskmanager -d -t flink taskmanager
Can someone explain how does this taskmanager register with the jobmanager from these commands?
Thanks
A:
In order to start a Flink cluster on Docker I would strongly recommend to use docker-compose whose config file you can also find here.
If you want to set up a Flink cluster using docker manually, then you have to start the containers so that they can resolve their names. First you need to create a custom network via
docker network create my-network
Next, you have to start the jobmanager with this network and configure the name as well as the hostname to be same. That way Flink will bind to the hostname which is resolvable.
docker run --name jobmanager --hostname jobmanager --rm --net my-network -d -t flink jobmanager
Last but not least, we need to start the taskmanager and tell him the name of the JobManager. This is done by setting the environment variable JOB_MANAGER_RPC_ADDRESS to `jobmanager.
docker run --name taskmanager --net my-network -e JOB_MANAGER_RPC_ADDRESS=jobmanager -t -d flink taskmanager
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does an IEnumerable require a call to ToList to update the listview?
I'm sure there is good explanation for this. I'm guessing it has something to do with me having a cold and missing something obvious...
I have a simple window:
<Window x:Class="WpfIdeas.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:w="clr-namespace:WpfIdeas"
Title="Window1" Height="300" Width="315">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" x:Name="btnAddObject" Click="btnAddObject_Click">Add Object</Button>
<ListView Grid.Row="1" ItemsSource="{Binding Objects}">
</ListView>
</Grid>
</Window>
the code behind the window is:
using System.Windows;
namespace WpfIdeas
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new ObjectVM();
}
private void btnAddObject_Click(object sender, RoutedEventArgs e)
{
(DataContext as ObjectVM).AddObject();
}
}
}
And its DataContext is set to be the following class:
class ObjectVM : INotifyPropertyChanged
{
private readonly List<ObjectModel> objects = new List<ObjectModel>();
//public IEnumerable<ObjectModel> Objects { get { return objects } } //doesn't work
public IEnumerable<ObjectModel> Objects { get { return objects.ToList() } } //works
private Random r = new Random();
public void AddObject()
{
ObjectModel o = new ObjectModel(r);
objects.Add(o);
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Objects"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
The ObjectModel class is in fact a struct that generates a 14 character string when it is instantiated. It's ToString() method just outputs this string.
As the code is above, when I click the "Add Object" button then a new string appears in the ListView.
However if I remove the ToList() call in the Objects property, nothing is ever displayed in the ListView. It just remains blank.
Why is this?
A:
Using Collection Objects as a Binding Source:
You can enumerate over any collection that implements the IEnumerable interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the INotifyCollectionChanged interface. This interface exposes an event that must be raised whenever the underlying collection changes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does the patch keyword in Dart do?
Can someone explain what the patch keyword does? For example, in
math_patch.dart I see
patch num pow(num x, num exponent) => MathNatives.pow(x, exponent);
patch double atan2(num a, num b) => MathNatives.atan2(a, b);
patch double sin(num x) => MathNatives.sin(x);
patch double cos(num x) => MathNatives.cos(x);
What does this mean? What are _patch.dart files for?
A:
The patch mechanism is used internally (and is only available
internally, not to end users) to provide different implementations of
core library functionality.
For the math library that you have below, the platform independent
library source in lib/math declares these methods as external.
external methods get their implementation from a patch file. There
is a patch file in the VM in runtime/lib/math_patch.dart, which
supplies the implementation for the VM and there is a patch file in
the dart2js compiler in
lib/compiler/implementation/lib/math_patch.dart, which supplies the
dart2js implementation.
The external keyword is understood by the analyzer and doing it this
way allows only the shared part to be in the SDK and be understood by
the tools. That means that the SDK can have lib/math instead of having
lib/math/runtime and lib/math/dart2js, which makes the SDK cleaner and
easier to understand.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Finding the matrix of a linear transformation from an upper triangular matrix to an upper triangular matrix.
The question that I am trying to solve is as follows:
Find the matrix $A$ of the linear transformation
$T(M)=
\begin{bmatrix}
7 & 3 \\
0 & 1
\end{bmatrix}
M$
from $U^{2×2}$ to $U^{2×2}$ (upper triangular matrices) with respect to the basis
$\left\{ \begin{bmatrix}
1 & 0 \\
0 & 0
\end{bmatrix},\begin{bmatrix}1&1\\ 0&0\end{bmatrix},\begin{bmatrix}0&0\\0&1\end{bmatrix}\right\}$
$A=\begin{bmatrix} \cdot&\cdot&\cdot\\\cdot&\cdot&\cdot\\ \cdot&\cdot&\cdot\end{bmatrix}$
I don't know how to interpret this question. I would have thought that the matrix $A$ is $\begin{bmatrix}
7 & 3 \\
0 & 1
\end{bmatrix}$ because that is the matrix which defines the linear transformation $T$. I am surprised that the required answer is $A\in M_{3\times 3}$. How can a basis with elements $\in M_{2\times 2}$ form a matrix $\in M_{3\times 3}$?
A:
Upper triangular matrices
$
\begin{bmatrix}
a&b\\
0&c
\end{bmatrix}
$
form a vector space with canonical basis:
$
e_1=\begin{bmatrix}
1&0\\
0&0
\end{bmatrix}
\quad
e_2=\begin{bmatrix}
0&1\\
0&0
\end{bmatrix}
\quad
e_3=\begin{bmatrix}
0&0\\
0&1
\end{bmatrix}
$
that is isomorphic to $\mathbb{R}^3$ by:
$
e_1\rightarrow\vec e_1=\begin{bmatrix}
1\\0\\0
\end{bmatrix}
\quad
e_2\rightarrow\vec e_2=\begin{bmatrix}
0\\1\\0
\end{bmatrix}
\quad
e_3\rightarrow \vec e_3=\begin{bmatrix}
0\\0\\1
\end{bmatrix}
$
Your linear transformation $T$ is defined as a matrix multiplication:
$
T(M)=\begin{bmatrix}
7&3\\
0&1
\end{bmatrix}
\begin{bmatrix}
a&b\\
0&c
\end{bmatrix}
=
\begin{bmatrix}
7a&7b+3c\\
0&c
\end{bmatrix}
$
so, in this canonical representation, it is given by the matrix $T_e$ such that:
$
T_e\vec M=\begin{bmatrix}
7&0&0\\
0&7&3\\
0&0&1
\end{bmatrix}
\begin{bmatrix}
a\\
b\\
c
\end{bmatrix}=
\begin{bmatrix}
7a\\
7b+3c\\
c
\end{bmatrix}
$
Now you want a representation of the same transformation in a new basis:
$
e'_1=
\begin{bmatrix}
1&0\\
0&0
\end{bmatrix}
\rightarrow\vec e'_1=\begin{bmatrix}
1\\0\\0
\end{bmatrix}
\quad
e'_2=\begin{bmatrix}
1&1\\
0&0
\end{bmatrix}\rightarrow\vec e'_2=\begin{bmatrix}
1\\1\\0
\end{bmatrix}
\quad
e'_3=\begin{bmatrix}
0&0\\
0&1
\end{bmatrix}\rightarrow \vec e'_3=\begin{bmatrix}
0\\0\\1
\end{bmatrix}
$
This transformation of basis is represented by the matrices
$
S=
\begin{bmatrix}
1&1&0\\
0&1&0\\
0&0&1
\end{bmatrix}
\qquad
S^{-1}=
\begin{bmatrix}
1&-1&0\\
0&1&0\\
0&0&1
\end{bmatrix}
$
So the matrix that represents the transformation $T$ in the new basis is:
$
T_{e'}=S^{-1}T_eS=
\begin{bmatrix}
7&0&-3\\
0&7&3\\
0&0&1
\end{bmatrix}
$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I get the value of td using hierarchy?
<tr>
<td>#</td>
<td>2009</td>
<td><a class="delete_this">Click</a></td>
</tr>
I want to use jquery and get the text of 2nd (second) "td" when clicking the anchor. I want the "td" in the same tr as the anchor...
How do I do this?
So far I have
$(document).ready(function(){
$(".delete_this').click(function(){
var myNUmber = $(this).parent()....///And this i should write the code to get the text for second td in tr where the anchor belongs to
})
})
A:
Here's a few ways:
$(this).parent().siblings("td:eq(1)").text()
If your looking for the cell before you can do it this way:
$(this).parent().prev().text()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting data from two dates in SQLite using EditText
I can't figure out how to use EditText in my Activity to search sqlite for a date range. I think I need to somehow make editText1 and 2 strings but I have no idea how to do that in my database.
In sqlite
public ArrayList<HashMap<String, String>> getAllsaleweekly() {
ArrayList<HashMap<String, String>> wordList;
GregorianCalendar gc = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd");
String today = sdf.format(gc.getTime());
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM INSERTS WHERE saleDate BETWEEN '2012-Aug-16' AND '2013-Aug-21'";
This works perfect except I don't want those static values of 2012-Aug-16' AND '2013-Aug-21. I shows up perfectly in my arrayList by it's just static dates from sqlite.
In my Activity I have two editText...
EditText editText1,editText2;
edittext1 =(EditText)findViewById(R.id.editText1);
edittext2 =(EditText)findViewById(R.id.editText2);
and I have an onClick for Button bydate
bydate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
ArrayList<HashMap<String, String>> saleList = controller.getAllsaleweekly();
ListAdapter adapter = new SimpleAdapter(whatever.this,whateverList, R.layout.whatever, new String[] {"whatever","whatever", "whatever", "whatever","whatever","whatever", "whatever"}, new int[] { R.id.whatever, R.id.whatever, R.id.whatever, R.id.whatever,R.id.whatever, R.id.v, R.id.whatever});
setListAdapter(adapter);
}});
A:
On button click you can get the value of Editext
String value1 = edittext1.getText().toString();
String value2 = edittext2.getText().toString();
Then
controller.getAllsaleweekly(value1,value2);
Change
public ArrayList<HashMap<String, String>> getAllsaleweekly(String date1,String date2)
{
// use date1 and date 2 here
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are the benefits of covariance and contravariance?
C# 4.0 is going to support covariance and contravariance. But I don't clearly understand the benefits of this new feature. Can you explain me (clearly) why we need it?
A:
They just allow you to do some things that are conceptually valid, and formally acceptable, but aren't currently allowed because of language constraints. For example:
IEnumerable<int> ints = new List<int> { 1, 2, 3 };
Action<IEnumerable<object>> PrintThings =
x => { foreach(var thing in x) Console.WriteLine(thing); };
PrintThings(ints); // doesn't compile right now :( will compile in 4.0
There's no fundamental reason why this can't work or shouldn't work; it just happens to not be allowed in the language. By allowing it, you make programmers' lives easier when such an operation would be natural for them to perform.
A:
There are alot of misconceptions out there as to how and what will work in 4.0. The best explanation I've read so far was written my Marc Gravell. See his blog post here:
http://marcgravell.blogspot.com/2009/02/what-c-40-covariance-doesn-do.html
Just to reiterate, alot of ppl think this will work in 4.0:
public class Base{}
public class Derived : Base {}
..in some other class
List<Derived> derived....
public void Method(List<Base> b){}
Even in 4.0, you will not be able to pass the List into this method. As Marc points out, that's what Generic constraints are there for, and can be done since 2.0
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Property of the sequence of primes
Let $p_n$ denote the $n$-th prime number. Does anyone know a proof of the following property?
$$\forall n, n', \ p_n p_{n'} \geq p_{n+n'}$$
I'm surprised I can't find anything on this while I believe it should be something people could find interesting (if it's true). The case $n=1$ (i.e. $p_n=2$) is equivalent to Bertrand's postulate.
A:
Assume $n\leq m$ (here I use $m$ instead of $n'$). By Rosser's theorem we have that $p_np_m>n\ln n\cdot m\ln m=nm\ln n\ln m$. For $n,m>8$ we have $nm\geq\frac{n+4}{2}\cdot m=\frac{1}{2}nm+2m\geq 2n+2m$. We further have for $n>e^2$ $\ln n\ln m>2\ln m=\ln m+\ln m\geq\ln n+\ln m$, so $p_np_m>nm\ln n\ln m> 2(n+m)(\ln n+\ln m)>2(n+m)\ln nm>2(n+m)\ln(n+m)=(n+m)\ln(n+m)+(n+m)\ln(n+m)>(n+m)\ln(n+m)+(n+m)\ln\ln(n+m)>p_{n+m}$ where last equality is one mentioned here and holds for $n+m\geq 6$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to redirect http request to another internal machine based on URL
I have a windows 2008 server at home (on a vmware server) along with other virtual machines, I want to open port 80 in my firewall, but I want to redirect the request to the correct vm. for example if the request is http://myserver/SVN I want it to go to my svn vm, if it's for http://myserver/Blog I want to go to another vm.
what's the best approach?
And How hard is it to have https redirects as well?
A:
You could use a reverse proxy. If you're using apache, this is what a basic reverse proxy setup would look like for http://myservers. This let you map directories to backend or even remote servers.
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /svn http://svnvm
ProxyPassReverse /svn http://svnvm
ProxyPass /blog http://blogvm
ProxyPassReverse /blog http://blogvm
Edit: fixed formatting
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Configure gson to serialize Calendar type for wcf web service
I have an object that contains a Calendar type representing the CreatedOn date. I have gotten the adapter to display the milliseconds, but I"m not sure how to output the device configured timezone information as well.
WCF expects dates to be in the following format: "CreatedOn":"\/Date(1305003600000-0500)\/"
This is what I currently have:
Gson gson = new GsonBuilder()
.registerTypeAdapter(GregorianCalendar.class, new JsonSerializer<GregorianCalendar>() {
public JsonElement serialize(GregorianCalendar date, Type type, JsonSerializationContext context) {
return new JsonPrimitive("/Date(" + date.getTimeInMillis() + ")/");
}
}).create();
A:
Ended up doing the following:
Gson gson = new GsonBuilder()
.registerTypeAdapter(GregorianCalendar.class, new JsonSerializer<GregorianCalendar>() {
public JsonElement serialize(GregorianCalendar date, Type type, JsonSerializationContext context) {
return new JsonPrimitive("\\/Date(" + date.getTimeInMillis() + "-0000)\\/");
}
}).create();
When I add my object to the HttpPost request as json StringEntity, I fix the escaped backslashes:
String json = gson.toJson(data).replace("\\\\/", "\\/");
I would still be interested in a "better" way of accomplishing this, if it exists...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Embedding OpenEJB in a TestCase using javax.ejb.embeddable.EJBContainer
Embedding OpenEJB in a TestCase using javax.ejb.embeddable.EJBContainer.
EJBContainer container = EJBContainer.createEJBContainer();
always returns "null".
How to instantiate the EJBContainer and get the context for looking up EJB 3.0 local stateless session Bean for unit testing?
I would like to get the context from the created container rather than from initial context, how it can be done?
A:
In OpenEJB, the OpenEJB 4.0.0 -beta is found to be supporting java ee embeddable API and with this we can embed the container in our testcase like,
EJBContainer ejbContainer = EJBContainer.createEJBContainer();
In previous versions of OpenEJB we can't do like this and hence we use "LocalInitialContextFactory" to create the context.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I need text to stay inside a container without using the tag over and over
I am trying to get my text to stay inside my box without going outside of it.
I don't want to use the <br> tag over and over. So I am trying to make it so it makes a new line automatically.
CSS
#NewsPosts {
position: relative;
bottom: 0px;
top: -925px;
font-size: 20px;
margin-left: 10;
margin-right: 10;
text-indent: 5;
}
HTML
<!--NewsPosts-->
<div id="NewsPosts">
<div align = "center">
<p>html text goes here</p>
</div>
</div>
Here's an example:
A:
Use the width CSS property:
#example-autowrap{
width:40%;
}
http://jsfiddle.net/91efphoL/ is a working example of this
To make it fit into your background like in the image link you posted, just make sure that the element containing text is a child of the background element, and it should work, with or without the width
If you want it to be centered, and for some reason you CAN'T put it as a child of the background element, then you should just add margin:0 auto. This attempts to set both the right and left margins to the same value, effectively centering it
|
{
"pile_set_name": "StackExchange"
}
|
Q:
internal server error heroku
im developing a application in ruby with sinatra. evrything worked finely until i put it on heroku. heroku gives me internal server error but no error code ):
currently my workstation is a windows computer.
my log loooks like this: http://i.imgur.com/Xd3QAms.png
config.ru
require 'tilt/haml'
require 'sass/plugin/rack'
require '4c96748'
run Sinatra::Application
gemfile
source 'https://rubygems.org'
ruby '2.2.3'
gem 'sinatra', '1.1.0'
procfile
web: bundle exec rackup config.ru -p $PORT
4c96748.rb
require 'sinatra'
require 'tilt/haml'
get '/' do
haml :index
end
pleaase help me, what do i need to do?
A:
try following in your 6c96748.rb
require 'rubygems'
require 'sinatra'
require 'haml'
get '/' do
haml :index
end
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to send json to php file to save on server
Im developing a javascript/php/ajax application and have stumbled across some problems.
Im confident at javascript and ajax but my php is a little rusty.
My aim is to get a json file from the server, modify it using javascript, and then save this modified json back to the server.
After some research it was obvious that the modified json file must be sent to a php file, this php file will then do the saving.
HOW do i send a json string from javascript to php? OR how do I get the php file to pick up the json variable from the javascript?
im assuming the php will be something like:
<?php
$json = $_POST["something"];
?>
but how do i send or "post" the javascript variable to the php file?
I was thinking about creating a hidden html form, setting a hidden textbox to the json string, then posting the html form
But surely there must be a way without including the html middle man?
Im looking for answer WITHOUT jQuery. Seeing as this is an application i would like a relieve the dependancy of jQuery.
A:
You would need to create a XMLHttp-Request like this:
xmlhttp.open( "POST", url, false );
xmlhttp.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8'
);
xmlhttp.send("data=yaystuff!")
So you can send it. In PHP just get the $_POST['data'] variable and do some json_decode() on it, if you send JSON :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android 2.3 maintain ListView position when using Fragments
I have been trying to find a solution to this. How do I maintain the ListView position when I am using Fragments and someone rotates the device.
The rotation itself resets everything and it's back to 0 again. I can get it to work with the multiple examples when I am using normal Activities, but how do I do it when I am inside a specific Fragment?
A:
Make sure that you do not call setAdapter() again on rotation or after any operation you do. Always call notifyDataSetChange() and your list will remain at the same point
Other workaround can be that you save the position of the current list item and call setSelection(position) for what you want to keep
|
{
"pile_set_name": "StackExchange"
}
|
Q:
when running the 'build' task of generator-gulp-webapp (with gulp-jade) produces an empty index.html
I have added gulp-jade to the standard configuration and added a 'templates' task, that i used in the 'serve' and in the 'build' tasks.
When i run the build, everything looks fine, but the produced index file is empty.
I don't know how to fix this, please give a look at my gulpfile, maybe it's a trivial question, but very important to me. Thanks.
// generated on 2016-03-14 using generator-gulp-webapp 1.1.1
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import jade from 'gulp-jade';
import browserSync from 'browser-sync';
import del from 'del';
import {stream as wiredep} from 'wiredep';
const $ = gulpLoadPlugins();
const reload = browserSync.reload;
gulp.task('templates', function() {
var locals = 'app/jade';
gulp.src('app/jade/*.jade')
.pipe(jade({
locals: locals
}))
.pipe(gulp.dest('app/'))
});
gulp.task('styles', () => {
return gulp.src('app/styles/*.scss')
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe($.sass.sync({
outputStyle: 'expanded',
precision: 10,
includePaths: ['.']
}).on('error', $.sass.logError))
.pipe($.autoprefixer({browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']}))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('.tmp/styles'))
.pipe(reload({stream: true}));
});
gulp.task('scripts', () => {
return gulp.src('app/scripts/**/*.js')
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe($.babel())
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/scripts'))
.pipe(reload({stream: true}));
});
function lint(files, options) {
return () => {
return gulp.src(files)
.pipe(reload({stream: true, once: true}))
.pipe($.eslint(options))
.pipe($.eslint.format())
.pipe($.if(!browserSync.active, $.eslint.failAfterError()));
};
}
const testLintOptions = {
env: {
mocha: true
}
};
gulp.task('lint', lint('app/scripts/**/*.js'));
gulp.task('lint:test', lint('test/spec/**/*.js', testLintOptions));
gulp.task('html', ['styles', 'scripts'], () => {
return gulp.src('app/*.html')
.pipe($.useref({searchPath: ['.tmp', 'app', '.']}))
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', $.cssnano()))
.pipe($.if('*.html', $.htmlmin({collapseWhitespace: true})))
.pipe(gulp.dest('dist'));
});
gulp.task('images', () => {
return gulp.src('app/images/**/*')
.pipe($.if($.if.isFile, $.cache($.imagemin({
progressive: true,
interlaced: true,
// don't remove IDs from SVGs, they are often used
// as hooks for embedding and styling
svgoPlugins: [{cleanupIDs: false}]
}))
.on('error', function (err) {
console.log(err);
this.end();
})))
.pipe(gulp.dest('dist/images'));
});
gulp.task('fonts', () => {
return gulp.src(require('main-bower-files')('**/*.{eot,svg,ttf,woff,woff2}', function (err) {})
.concat('app/fonts/**/*'))
.pipe(gulp.dest('.tmp/fonts'))
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('extras', () => {
return gulp.src([
'app/*.*',
'!app/*.html'
], {
dot: true
}).pipe(gulp.dest('dist'));
});
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));
gulp.task('serve', ['templates','styles', 'scripts', 'fonts'], () => {
browserSync({
notify: false,
port: 9000,
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
}
}
});
gulp.watch([
'app/*.html',
'.tmp/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/jade/**/*.jade', ['templates']);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/scripts/**/*.js', ['scripts']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
gulp.task('serve:dist', () => {
browserSync({
notify: false,
port: 9000,
server: {
baseDir: ['dist']
}
});
});
gulp.task('serve:test', ['scripts'], () => {
browserSync({
notify: false,
port: 9000,
ui: false,
server: {
baseDir: 'test',
routes: {
'/scripts': '.tmp/scripts',
'/bower_components': 'bower_components'
}
}
});
gulp.watch('app/scripts/**/*.js', ['scripts']);
gulp.watch('test/spec/**/*.js').on('change', reload);
gulp.watch('test/spec/**/*.js', ['lint:test']);
});
// inject bower components
gulp.task('wiredep', () => {
gulp.src('app/styles/*.scss')
.pipe(wiredep({
ignorePath: /^(\.\.\/)+/
}))
.pipe(gulp.dest('app/styles'));
gulp.src('app/*.html')
.pipe(wiredep({
exclude: ['bootstrap-sass'],
ignorePath: /^(\.\.\/)*\.\./
}))
.pipe(gulp.dest('app'));
});
gulp.task('build', ['lint','templates','html','images','fonts'], () => {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('default', ['clean'], () => {
gulp.start('build');
});
A:
The locals variable should be an object
gulp.task('templates', function() {
var locals = {
myValue: "myValue"
};
gulp.src('app/jade/*.jade')
.pipe(jade({
locals: locals
}))
.pipe(gulp.dest('app/'))
});
I cannot get exactly what you are trying to do here, are you trying to read multiple locals files from 'app/jade' folder?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Count columns satisfying a multiple OR statement and an AND statement
I would like to count the number of columns, in each row of a data frame, that satisfy a multiple OR condition.
In the first 100 columns of my data frame I have "codes" (that are integers). Let's say I want the number of columns where the value is either 111,112 or 113.
I tried
rowSums(mydata[,1:100]==111 | mydata[,1:100] == 112 | mydata[,1:100] == 113)
This works, but as I have a lot of codes to check I would prefer to use an %in% statement like
rowSums(mydata[,1:100] %in% c(111,112,113))
but this does not work and I haven't been able to find the appropriate syntax. (I looked at other questions about %in% but I didn't find any answer that solved my problem.)
The second part of the question is, how to add an AND condition on other columns ? Something like
rowSums(mydata[,1:100] %in% c(111,112,113) & mydata[,101:200] %in% c("a","b","c"))
?
A:
The %in% operator doesn't work with data.frame. We could loop through the columns using lapply/sapply/vapply and do the %in%. After we are get the logical index in a list, we get the elementwise sum (+) using Reduce. This would also work even if there are NA values as %in% uses match with argument nomatch=0L while == returns NA for NA values.
Reduce(`+`, lapply(mydata[1:5], `%in%` ,111:113))
#[1] 2 3 2 4 2 1 3 0 1 2 1 2 1 2 0 1 1 3 2 2
which is equal to rowSums
rowSums(mydata[1:5] ==111 | mydata[1:5] == 112 | mydata[1:5] == 113)
#[1] 2 3 2 4 2 1 3 0 1 2 1 2 1 2 0 1 1 3 2 2
For the second part of the question, we can construct the & with Map and then use Reduce to get the +.
We use two logical lists (lapply(mydata[1:5], ...) and lapply(mydata[6:10], ...)) as input for Map. The & will compare the corresponding list elements and return TRUE if both are TRUE or else FALSE to return a single list. From there, we can use Reduce as stated before.
Reduce(`+`, Map(`&`, lapply(mydata[1:5], `%in%` ,111:113),
lapply(mydata[6:10], `%in%`, letters[1:3])))
#[1] 0 1 1 0 1 0 1 0 0 0 1 1 1 0 0 0 0 2 1 0
The equivalent rowSums code would be
rowSums((mydata[1:5] ==111 | mydata[1:5] == 112 | mydata[1:5] == 113) &
(mydata[6:10]=='a' | mydata[6:10]=='b' | mydata[6:10]=='c'))
#[1] 0 1 1 0 1 0 1 0 0 0 1 1 1 0 0 0 0 2 1 0
NOTE: Here I created a small example dataset of 10 columns. The first 5 are 'numeric', followed by 5 'character' columns.
data
set.seed(24)
mydata <- as.data.frame(matrix(sample(111:120, 5*20, replace=TRUE),
ncol=5))
set.seed(42)
mydata2 <- as.data.frame(matrix(sample(letters[1:10], 5*20,
replace=TRUE), ncol=5), stringsAsFactors=FALSE)
mydata <- cbind(mydata, mydata2)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ios push notification and IDFA issue
In my ios app I've used
uuid = [[ASIdentifierManager sharedManager] advertisingIdentifier]
as udid for my push notification.
Today when I tried to publish my app, itunes asks me:
This app uses the Advertising Identifier to (select all that apply):
Serve advertisements within the app.
Attribute this app installation to a previously served advertisement.
Attribute an action taken within this app to a previously served
advertisement.
I use the uuid only for push notification.
which of the 3 options should I choose?
Thanks in advance.
A:
[[UIDevice currentDevice] identifierForVendor]
Is the better choice. You offer one single identifier for a device, even if the settings are reset.
The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps on the same device that come from different vendors, and for apps on different devices regardless of vendor.UIDevice#identifierForVendor
For more explanation, heres a good summary: iOS6 UDID - What advantages does identifierForVendor have over identifierForAdvertising?
So, in case you do not use the advertisingIdentifier at all for advertising, you shouldn't make use of this => unfortunately, your question regarding the 3 approaches is obsolete.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sort strings by value and add to list
I have this list of log files that I want to sort by the date inside each one: as you can see, there is after LOG_ a number which is the key I want to sort the string.
The date is in yyyymmdd format.
LOGS\LOG_20190218_91_02.LOG
LOGS\LOG_20190218_91_05.LOG
LOGS\LOG_20190218_91_00.LOG
LOGS\LOG_20190218_91_22.LOG
LOGS\LOG_20190218_91_10.LOG
LOGS\LOG_20190219_56_22.LOG
LOGS\LOG_20190219_56_24.LOG
LOGS\LOG_20190219_56_25.LOG
LOGS\LOG_20190219_56_26.LOG
LOGS\LOG_20190219_56_03.LOG
LOGS\LOG_20190220_56_22.LOG
LOGS\LOG_20190220_56_07.LOG
LOGS\LOG_20190220_56_13.LOG
LOGS\LOG_20190220_56_17.LOG
LOGS\LOG_20190220_56_21.LOG
I tried various approaches:
extract the date value, add them to list, distinct them (using set) and, by each one, take the string/filepath and add it to a list. The problem is that dates could vary in size (here there are only 3, but they could be more). So using fixed lists is (maybe) out of scope.
verify each string and check with the previous/next to see if the date changed. If changed, then add all the previous paths/string to a list. Still same problem but maybe this approach could be improved.
manually copy-paste the files in folders for each date and then work with them. This is out of scope by now because we are talking about huge files (gigs).
What I would like to understand is how the second soulution could be implemented. How can properly store the files/strings with same date in a own list ?
Expected result...
list20190218 = [all LOG files with 20190218 value in name]
list20190219 = [all LOG files with 20190219 value in name]
list20190220 = [all LOG files with 20190220 value in name]
...but with a variable number of lists.
Thanks
A:
A clean way to do this would be using dictionaries. In this case the keys would be the dates and the values would be the corresponding list. In order to group the elements in the list you could use itertools.groupby. You also need to specify that you want to group the list using the date, for that you can extract the date substring from each string in the key argument:
from itertools import groupby
from operator import itemgetter
d = {k:list(v) for k,v in groupby(data, key=lambda x: itemgetter(1)(x.split('_')))}
Then simply do:
d['20190220']
['LOGS\\LOG_20190220_56_22.LOG\n',
'LOGS\\LOG_20190220_56_07.LOG\n',
'LOGS\\LOG_20190220_56_13.LOG\n',
'LOGS\\LOG_20190220_56_17.LOG\n',
'LOGS\\LOG_20190220_56_21.LOG']
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to create a new column to a pandas dataframe that was created after using apply()?
After I read a excel file:
import pandas as pd
In:
df = pd.read_excel('file.xlsx')
df = df.drop('Unnamed: 0', 1)
df
Out:
A B C D E
0 2345 typeA NO http://www.example.com/...
2 23423 483 NO http://www.example.com/...
3 234234 typeC NO http://www.example.com/...
4 2343 typeA NO http://www.example.com/...
5 23423 typeA NO http://www.example.com/...
6 234 typeA NO http://www.example.com/...
I am applying several functions to several pandas dataframe columns that where created after adding more columns with apply():
In:
df['E'] = df['D'].apply(checker)
df
Out:
A B C D E
0 2345 typeA NO http://www.example.com/... OK
1 234 483 NO http://www.example.com/... FALSE
2 23423 483 NO http://www.example.com/... OK
3 234234 typeC NO http://www.example.com/... OK
4 2343 typeA NO http://www.example.com/... OK
5 23423 typeA NO http://www.example.com/... FALSE
6 234 typeA NO http://www.example.com/... OK
Then I did: df = df[df.E == 'OK'] and df = df.loc[df.E =='OK']
Then, I am applying to the above dataframe a new function:
In:
df['F'] = df['D'].apply(new_function_foo)
Although it actually works as I want I got this warning:
Out:
/usr/local/lib/python3.5/site-packages/ipykernel/__main__.py:10: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
I checked the documentation, and I tried to follow up the instructions:
df['F'] = df.loc[['E']].apply(function_foo)
And
df['ColF'] = df.loc[:,'ColE'].apply(function_foo)
However, I do not understand how to solve the above warning. Therefore, how can I apply functions correctly?.
A:
You can use any method you like if you are okay with copying the dataframe. For example if you do this:
df = df[df.E == 'OK'].copy()
there will be no error when you do something like this:
df['F'] = df['D'].apply(new_function_foo)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laço for a partir do index 1 array java
Tenho uma função que faz um laço for em um array de String.
Preciso que o laço inicie a partir do index[1] desse array.
Porém não estou conseguindo.
String arquivo[] = arquivoDecodificado.split("\r\n|\r|\n");
for(String linha: arquivo ) {
String[] linhaQuebrada= linha.split(";");
Pessoas idPessoa = pessoasService.buscarPessoaComCnpj(linhaQuebrada[0],idEntidade);
operadoraCart.setEntidade(ent);
operadoraCart.setPessoa(idPessoa);
operadoraCartaoService.cadastrar(operadoraCart);
}
Preciso que ele comece o laço a partir de arquivo[1]
A:
Acredito que poderia fazer assim:
String arquivo[] = arquivoDecodificado.split("\r\n|\r|\n");
for(int i = 1; i < arquivo.length; ++i ) {
String[] linhaQuebrada= arquivo[i].split(";");
Pessoas idPessoa = pessoasService.buscarPessoaComCnpj(linhaQuebrada[0],idEntidade);
operadoraCart.setEntidade(ent);
operadoraCart.setPessoa(idPessoa);
operadoraCartaoService.cadastrar(operadoraCart);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I intercept and correct keypresses at a low level?
I keep typing "t eh" instead of " the" which is, of course, annoying in the amount of time it takes me to correct myself.
The obvious answer is "Learn to type, noob!" or at least to type more slowly and/or more correctly. This error is frighteningly consistent so it appears I've trained my muscle memory for that pattern already.
But I'm wondering if it's possible to write a small, windows portable script or application that, when it detects the incorrect sequence, backspaces and corrects it automatically at a layer where it would apply to any keyboard input.
Does C# have access to that layer of the OS that intercepts keypresses systemwide?
Will I run into UAC issues with Vista?
Am I re-inventing the wheel (ie, are there open source tools I can modify or use out of the box)?
In DOS this sort of thing was quite easy and one could make TSRs (Terminate and Stay Resident) programs that would, for instance, give you a calculator onscreen with a special keypress. Not to mention the many, many practical joke programs based on this concept (dial "M" for monster!)...
I would, of course, never suggest such a utility could be used that way for co-workers...
-Adam
A:
On windows you could use AutoHotKey. That allows you to create little scripts or macros to automate and correct things like mistypes.
One use was posted on lifehacker which took the common mistyped words and corrected them. It is at http://lifehacker.com/192506/download-of-the-day-universal-autocorrect
UPDATE Per Comment: This is Free software and windows only as far as I know.
The above script is just an example of what it can do. There are a slew of scripts available at AutoHotkeys Site
A:
I suggest AutoHotKey. If you've never used it before, have a quick read of the tutorial: http://www.autohotkey.com/docs/Tutorial.htm
The feature you are looking for is called "hotstrings." http://www.autohotkey.com/docs/Hotstrings.htm
In your case, your script would look something like:
::teh::the
That's it! Add other things you want corrected on additional lines. AutoHotkey scripts can be compiled so you don't have to install AutoHotKey on all of your machines.
It's a very cool program. It's primary use (for making custom hotkeys) rocks! These scripts are system wide so you'll also probably want to make a hotkey to be able to turn them off too!
EDIT: In a comment, it was mentioned that he actually types "t eh" (with a space in it) and I wondered if something additional would be needed for it to work. I just tested it and it works fine. Just install autohotkey, and create a file with the .AHK extension. In that file put in the following line
::t eh::the
and save the file. Then double-click on the AHK file to load AutoHotKey with your script (you'll see a green square in your system tray to let you know it is running). It should work fine!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Passing objects between classes in Java
I'm new to Java and I am doing a homework on constructing Decision Trees. After 2 days of continuous coding, I finally built the tree and verified it manually. But I'm stuck on validating the tree, because, everytime I try to pass the "node" object to the Validator class, it is null. I tried all sorts of previous suggestions and nothing seems to work. I need someone to point out my mistake and why its a mistake. Here is a short portion of the code that will explain what I'm trying to achieve.
Please advice on how I should go about this.
//Node Class to represent a node in the tree
public class DecisionTreeNode
{
String attribute;
boolean isLeaf;
DecisionTreeBranch[] branches; //Another class to represent branch from a node
//Default constructor for a Node: With attributes, label and isLeaf condition
public DecisionTreeNode(String attribute)
{
this.attribute = attribute;
this.isLeaf = true;
}
............
}
//Tree class with logic to build the tree
public class BuildDecisionTree
{
public PrepareFile config; //Need this object to get a arraylist of values to construct the tree
DecisionTreeNode root;
BuildDecisionTree(PrepareFile config)
{
this.config = config;
}
//Construct Decision Tree
public void buildDecisionTree()
{
root = myDecisionTreeAlgorithm(config.getExamples(), config.getAttributes());
System.out.println("\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Decision tree was constructed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
root.printDecisionTree("");
}
//This is the validator where is want both the "config" and the "root" objects
import java.util.List;
public class DecisionTreeValidator
{
PrepareFile config;
DecisionTreeNode node;
BuildDecisionTree bTree;
public DecisionTreeValidator(BuildDecisionTree bTree, PrepareFile config)
{
this.bTree = bTree;
this.node = bTree.root; //I tried adding a getter function in BuildDecisionTree class and returned the root, even then this was null. Like below
//this.node = bTree.buildDecisionTree(); //made the return type of the buildDecisionTree function as "DecisionTreeNode"
this.config = config;
this.examples = config.getExamples();
}
public boolean validateSingleExample(Example example)
{
boolean result = true;
while(node.isLeaf == false) //THIS IS WHERE I GET THE NULL POINTER EXCEPTION
...........................
}
}
//Main class
public class PredictRestaurant
{
public static void main(String[] args)
{
PrepareFile config = new PrepareFile();
BuildDecisionTree bTree = new BuildDecisionTree(config);
DecisionTreeValidator validator = new DecisionTreeValidator(bTree, config);
boolean isTrain = true;
config.setTreeParameters();
bTree.buildDecisionTree();
}
}
A:
I figured out what the issue was. It wasnt related to the node being null. the node wasnt null.
when i traverse the tree and hit the leaf node, I was still checking for branches. corrected it now. Its working perfect. Thank you all for your recommendations. It helped me learn.
I will now remove the "logic" for tree building.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In Blazor dealing with unexpected results from the api web server
I'm developing a fairly simple Blazor app using a lot of default template functionality, and I can't figure out how to handle an ActionResult from the server that isn't the normal return value.
On the server side I've slightly modified the default controller template to look something like this:
public async Task<ActionResult<MyData>> GetSession(int id)
{
var myData= await FetchMyData(id);
if (myData== null)
{
return NotFound();
}
return myData;
}
That check for a null value was in the original template - it seems like a good idea so I kept it. On the client side my code looks like this:
public async Task<MyData> GetMyData(int id)
{
return await Http.GetJsonAsync<MyData>("/api/MyData/" + id);
}
It all works quite well, except the client side code doesn't handle the case where the server side returns a "NotFound()" result. It's not a show stopper, but it's driving me crazy that I don't know how to do it.
It seems that the GetJsonAsync() call on the client is silently unwrapping the return Value from the ActionResult wrapper (I guess?). Does that mean if I want to handle a NotFound condition I should be using a different httpclient function and maybe deserializing the object Value myself? If so, anyone want to volunteer an example?
Or am I missing something and there's an easier way?
It seems stupid to check for a condition on the server side just to send the client a warning that ultimately results in an unhandled exception.
A:
I tried Henk Holterman's suggestion of just adding a try/catch, and it turns out the exception that was thrown had the information I wanted - that is the status being returned by the server. So what I should have done was this:
public async Task<MyData> GetMyData(int id)
{
try
{
return await Http.GetJsonAsync<MyData>("/api/MyData/" + id);
}
catch (System.Net.Http.HttpRequestException e)
{
.... process the exception
}
}
Turns out HttpRequestException has the HResult, which is what I was looking for.
Thanks Henk.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails 4 — How to populate a user model from JSON API?
Firstly, I am new to rails so sorry if there is anything that I don't understand correctly. I am wondering how can I populate a model with data fetch thru an API.
Context: I am using a OAuth2 authentication with omniauth/devise.
In my User controller client-side (opposite to the provider), I fetched all users who logged in at least once is this "client app" and I want to display them. Obviously, anytime a new user logged in to the client app I don't store all his information in the client database to avoid duplicate. All I am storing is the user_id along with its access token.
Therefore, I was thinking that after fetching all users data I could populate them to a user model before passing it to the view. What would be the best way of doing such a thing?
I was looking into the Named Scope but it is not clear to me how to apply it to my particular scenario. For instance, it would be great to be able to fetch an populate all users in my model using something like this:
# ApiRequest is a container class for HTTParty
get = ApiRequest.new.get_users(User.all) // here "get" is a JSON array of all users data
response = get.parsed_response['users']
User.populate(response).all # would something like this possible? If yes, is Named Scope the appropriate solution?
Thank you very much in advance for you help.
A:
Let's say that response is an array of attribute hashes:
[{'id' => 1, 'name' => 'Dave'}, {'id' => 2, 'name' => 'Bill'}]
You can map this into an array of Users with:
users = response.map{|h| User.new(h)}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Acesso negado ao diretório
Olá,
Eu tenho um projeto pequeno que esta funcionando perfeitamente. Após terminar a programação eu gerei um instalador usando o Microsoft Visual Studio Installer Project.
O projeto instala corretamente mas quando tento usar, ele da acesso negado ao diretório.
Esta instalado dentro da pasta "Arquivo de Programa" e o programa manipula arquivos dentro desta pasta.
Então como faço para dar acesso de administrador dentro da pasta para o executável da aplicação.
Normalmente acesso os arquivos assim:
var pathArqFinal = Environment.CurrentDirector + "\Filename.txt";
Muito obrigado.
Raimundo
A:
Se fosse possivel editar o que esta dentro de arquivos de programa sem permissão elavada seria uma baita brecha de segurança, o que recomendo no minimo é você usar a pasta do nivel do usuário, mas para cada usuário será gerado um .txt (depende do que você já fez e precisa):
var pathArqFinal = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\Filename.txt";
Conforme site da microsoft: https://docs.microsoft.com/pt-br/dotnet/api/system.environment.specialfolder?view=netframework-4.8
O diretório que serve como um repositório comum para dados específicos do aplicativo para o usuário móvel atual. Um usuário móvel trabalha em mais de um computador em uma rede. O perfil de um usuário móvel é mantido em um servidor na rede e é carregado em um sistema quando o usuário faz logon.
Se for para todos usuário poderia usar o CommonApplicationData, assim:
var pathArqFinal = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\Filename.txt";
O diretório que serve como um repositório comum para dados específicos do aplicativo que são usados por todos os usuários.
Desta forma vai ser um arquivo usado por todos, o problema disto é que precisará tomar cuidado com "condição corrida", pois múltiplas instâncias do aplicativo poderão se atrapalhar ao gravar.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is chart using last record data?
I have this ChartField class
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
public class ChartField {
private int x;
private int y;
}
and MyChart class have a List of ChartField
import java.util.List;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MyChart {
private List<ChartField> chartFields;
}
This is the code how i generate the report.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
public class TestReport {
public static void main(String[] args) {
String source = "reports/test_report.jasper";
try {
List<MyChart> listMyCharts = new ArrayList<>();
{
MyChart myChart = new MyChart();
List<ChartField> chartFields = new ArrayList<>();
myChart.setChartFields(chartFields);
{
chartFields.add(new ChartField(2, 3));
chartFields.add(new ChartField(5, 6));
chartFields.add(new ChartField(7, 9));
chartFields.add(new ChartField(11, 12));
chartFields.add(new ChartField(12, 16));
chartFields.add(new ChartField(17, 22));
}
listMyCharts.add(myChart);
}
{
MyChart myChart = new MyChart();
List<ChartField> chartFields = new ArrayList<>();
myChart.setChartFields(chartFields);
{
chartFields.add(new ChartField(5, 4));
chartFields.add(new ChartField(7, 8));
chartFields.add(new ChartField(12, 5));
chartFields.add(new ChartField(15, 18));
chartFields.add(new ChartField(18, 21));
chartFields.add(new ChartField(34, 55));
}
listMyCharts.add(myChart);
}
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(listMyCharts);
Map<String, Object> map = new HashMap<>();
JasperPrint jp = JasperFillManager.fillReport(source, map, dataSource);
JasperViewer.viewReport(jp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is the design of test_report.jrxml
as you can see i put table and chart in detail band. My expectation is the detail band can repeat my listMyCharts object (see TestReport class)
JRDatasource expression of table is
new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{chartFields})
as you can see i use the same JRDatasource that tabel use in this chart.
This is the test_report.jrxml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.2.0.final using JasperReports Library version 6.2.0 -->
<!-- 2016-03-05T12:51:11 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name="master_report_template"
pageWidth="595" pageHeight="842" columnWidth="555"
leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20"
uuid="a488f074-1b9d-4cc7-95d4-51323412d4b2">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<style name="Table_TH" mode="Opaque" backcolor="#F0F8FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
<topPen lineWidth="0.5" lineColor="#000000"/>
<leftPen lineWidth="0.5" lineColor="#000000"/>
<bottomPen lineWidth="0.5" lineColor="#000000"/>
<rightPen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="Table_CH" mode="Opaque" backcolor="#BFE1FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
<topPen lineWidth="0.5" lineColor="#000000"/>
<leftPen lineWidth="0.5" lineColor="#000000"/>
<bottomPen lineWidth="0.5" lineColor="#000000"/>
<rightPen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="Table_TD" mode="Opaque" backcolor="#FFFFFF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
<topPen lineWidth="0.5" lineColor="#000000"/>
<leftPen lineWidth="0.5" lineColor="#000000"/>
<bottomPen lineWidth="0.5" lineColor="#000000"/>
<rightPen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<subDataset name="Dataset1" uuid="8c5a7d5e-8685-4dae-b33b-b816e12907c4">
<queryString>
<![CDATA[]]>
</queryString>
<field name="x" class="java.lang.Integer"/>
<field name="y" class="java.lang.Integer"/>
</subDataset>
<queryString>
<![CDATA[]]>
</queryString>
<field name="chartFields" class="java.util.List"/>
<background>
<band splitType="Stretch"/>
</background>
<detail>
<band height="202" splitType="Stretch">
<property name="com.jaspersoft.studio.unit.height" value="pixel"/>
<componentElement>
<reportElement x="10" y="10" width="220" height="76" uuid="41604712-0359-4058-8a74-30677eb774df">
<property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
</reportElement>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components"
xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetRun subDataset="Dataset1" uuid="6ad6bedb-dae4-4eb4-9f4e-57a0c04e73d5">
<dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{chartFields})]]></dataSourceExpression>
</datasetRun>
<jr:column width="100" uuid="6a31d692-e928-497f-a168-a31c12620680">
<property name="com.jaspersoft.studio.components.table.model.column.name" value="Column1"/>
<jr:columnHeader style="Table_CH" height="30" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="100" height="30" uuid="897b63dd-e6ee-4329-9382-495c9b9a4286"/>
<textElement>
<font size="14"/>
</textElement>
<text><![CDATA[x]]></text>
</staticText>
</jr:columnHeader>
<jr:detailCell style="Table_TD" height="30">
<textField>
<reportElement x="0" y="0" width="100" height="30" uuid="f6b7583f-e131-4ce4-bc8c-fdc83f4515dc"/>
<textElement>
<font size="14"/>
</textElement>
<textFieldExpression><![CDATA[$F{x}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="100" uuid="19cfc888-0988-42a7-a729-dd673a6c078d">
<property name="com.jaspersoft.studio.components.table.model.column.name" value="Column2"/>
<jr:columnHeader style="Table_CH" height="30" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="100" height="30" uuid="08a3e523-4c8b-4374-ab60-16c3cc577060"/>
<textElement>
<font size="14"/>
</textElement>
<text><![CDATA[y]]></text>
</staticText>
</jr:columnHeader>
<jr:detailCell style="Table_TD" height="30">
<textField>
<reportElement x="0" y="0" width="100" height="30" uuid="99c2e10d-1cf3-4975-99b9-b1f1f6c55571"/>
<textElement>
<font size="14"/>
</textElement>
<textFieldExpression><![CDATA[$F{y}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
</jr:table>
</componentElement>
<xyLineChart>
<chart evaluationTime="Report">
<reportElement x="260" y="0" width="294" height="200" uuid="19cc8a02-7aa3-4518-96f8-71a636b626cf"/>
<chartTitle/>
<chartSubtitle/>
<chartLegend/>
</chart>
<xyDataset>
<dataset>
<datasetRun subDataset="Dataset1" uuid="32ba4e38-1819-47f9-bbd6-4a4381e367a5">
<dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{chartFields})]]></dataSourceExpression>
</datasetRun>
</dataset>
<xySeries autoSort="true">
<seriesExpression><![CDATA["SERIES 1"]]></seriesExpression>
<xValueExpression><![CDATA[$F{x}]]></xValueExpression>
<yValueExpression><![CDATA[$F{y}]]></yValueExpression>
</xySeries>
</xyDataset>
<linePlot>
<plot/>
<categoryAxisFormat>
<axisFormat/>
</categoryAxisFormat>
<valueAxisFormat>
<axisFormat/>
</valueAxisFormat>
</linePlot>
</xyLineChart>
</band>
</detail>
</jasperReport>
This is the result of the report that i successfully generated. You can see the table is repeated as i want.
My question is
But why the heck the chart does not follow the table instead used the last data?
A:
On the chart tag you are using evaluationTime="Report" this means
Report: A constant specifying that an expression should be evaluated at the end of the filling process.
At the end of filling process the $F{chartFields} is the last record.
Solution
Replace it with evaluationTime="Now" or remove it (this is default)
Now A constant specifying that an expression should be evaluated at
the exact moment in the filling process when it is encountered.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Matrix Equation: Reduced Row Echelon Form
Given a matrix $A$ and its reduced row echelon form $R$, how can one find an invertible matrix $P$ such that $PA=R$?
I was given a $4\times4$ matrix $A$, I found $R$, and I tried to find $P$ by inspection. Since it was too difficult, I tried finding $P^{-1}$ by inspection because $A=P^{-1}R$ and succeeded (the greater number of zeros helps tremendously).
However, is there a more reliable method?
A:
A matrix can be reduced with some sequence of three elementary row operations: swapping rows, multiplying a row by a constant, and adding one row to another. Luckily for us, each of these operations is linear, so each can be represented as a matrix multiplication. Then we just have to chain all of those matrix multiplications together.
Here's an example. Say we want to reduce the following matrix:
$$
A=
\left(\begin{array}{ccc}
0 & 1 & 5 \\
1 & 0 & 3 \\
3 & 0 & 9 \\
\end{array}\right)
$$
There are many ways we could get to the reduced row echelon form, but let's start by dividing the third row by three.
$$
P_1A =
\left( \begin{array}{ccc}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & \frac{1}{3}
\end{array} \right)
\left(\begin{array}{ccc}
0 & 1 & 5 \\
1 & 0 & 3 \\
3 & 0 & 9
\end{array}\right)
=
\left(\begin{array}{ccc}
0 & 1 & 5 \\
1 & 0 & 3 \\
1 & 0 & 3
\end{array}\right)
$$
Then let's subtract the second row from the third.
$$
P_2(P_1A)=
\left( \begin{array}{ccc}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & -1 & 1
\end{array} \right)
\left(\begin{array}{ccc}
0 & 1 & 5 \\
1 & 0 & 3 \\
1 & 0 & 3
\end{array}\right)
=
\left(\begin{array}{ccc}
0 & 1 & 5 \\
1 & 0 & 3 \\
0 & 0 & 0
\end{array}\right)
$$
Finally, let's swap the first two rows.
$$
P_3(P_2P_1A)=
\left( \begin{array}{ccc}
0 & 1 & 0 \\
1 & 0 & 0 \\
0 & 0 & 1
\end{array} \right)
\left(\begin{array}{ccc}
0 & 1 & 5 \\
1 & 0 & 3 \\
0 & 0 & 0
\end{array}\right)
=
\left(\begin{array}{ccc}
1 & 0 & 3 \\
0 & 1 & 5 \\
0 & 0 & 0
\end{array}\right)
$$
Great, we got to the row echelon form using three elementary operations. Notice that now we can find our permutation matrix by composing these operation matrices.
$$
P=P_3P_2P_1=
\left( \begin{array}{ccc}
0 & 1 & 0 \\
1 & 0 & 0 \\
0 & 0 & 1
\end{array} \right)
\left( \begin{array}{ccc}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & -1 & 1
\end{array} \right)
\left( \begin{array}{ccc}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & \frac{1}{3}
\end{array} \right)
=
\left( \begin{array}{ccc}
0 & 1 & 0 \\
1 & 0 & 0 \\
0 & -1 & \frac{1}{3}
\end{array} \right)
$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Conflicting types in a 2D array (C)
I am making my first C program, and it utilizes a 2D array, and the code seems weird to me. First, why do I have to store "White" in [1][6]? I tried [0][6], but the compiler complains and won't run but when I call it in printf, it's [0][6]. Also, when trying to store "Bl" in codes [2][6], it says conflicting type for codes. Any help would be appreciated, thanks.
int main (int argc, const char * argv[]) {
for (q=0; q<=457; q++) {
for (w=0; w<=6; w++) {
codes[q][w] = 0;
}
}
char codes[1][6] = {'W','h','i','t','e','\0'};
char codes[2][6] = {'B','l,'\0'};
printf("%c\n", codes[0][0]);
A:
You are confusing two tasks that you need to perform. One task is to declare a variable, and tell the compiler what type it's going to hold. The second task is to put data into it.
You are doing both tasks at the same time, and this is confusing you. In your first statement you are telling the compiler, "codes is a 2-dimensional, 1x6 array. By the way, here are the values to put into it: "White"." Your second sattement says, "codes is a 2-dimensional, 2x6 array. By the way, put "BI" into it."
The compiler is complaining and saying, "It can't be a 2x6 array, becuase you already told me it's a 1x6 array."
What you need is something like this:
char codes[2][6] = { {'W','h','i','t','e','\0'}, {'B','l,'\0'} };
You would then get your 'W' by looking at codes[0][0], etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
do you know any manual which explains how can I update the component called remository? I'm in joomla 1.5
I just updated my joomla from 1.0.12 to 1.5 but the component remository doesn't appear in my components in joomla 1.5. I have readed in internet that I have to update remository but I don't know how keep my documents in the new version of remository that is 3.53
Thanks so much
A:
I found a solution
http://remository.com/forum/func,view/id,13245/catid,24/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Problem with exiftool and geosync, possibly related to daylight saving time
I wanted to geotag all my vacation photos with exiftool as follows:
exiftool -geotag "*.gpx" \
-geosync "19:25:42Z@IMG_7882.jpg" \
-geosync "09:16:34Z@IMG_9798.jpg" \
-ext .jpg .
where IMG_7802.jpg is a photo of my computer clock displaying 20:25:42 MEZ on 01 March 2018 (=19:25:42 Zulu), and similarly IMG_9798.jpg is a photo of my computer clock displaying 11:16:34 MESZ on 31 March 2018 (=09:16:34 Zulu). I used two such (bracketing) reference images in order to account for drift (and, indeed, the camera clock seems to have gained 26 seconds during that month).
The adjustment went fine for the reference images:
$ exiftool -datetimeoriginal -gpsdatetime IMG_7882.jpg
Date/Time Original : 2018:03:01 20:25:42
GPS Date/Time : 2018:03:01 19:25:42Z
$ exiftool -datetimeoriginal -gpsdatetime IMG_9798.jpg
Date/Time Original : 2018:03:31 10:17:00
GPS Date/Time : 2018:03:31 09:16:34Z
But for intermediate images, the computed GPS time is significantly off, e.g. by about half an hour in the following example (a GPS time of approximately 14:32Z is what I'd expect)
$ exiftool -datetimeoriginal -gpsdatetime IMG_8888.jpg
Date/Time Original : 2018:03:17 15:32:22
GPS Date/Time : 2018:03:17 15:04:13.45312997Z
Accordingly, the computed longitudes and latitudes are quite far off as well.
My educated guess is that the problem is related to the daylight saving time that started in Germany between the two reference images. Apparently, exiftool interpretes DateTimeOriginal in local time (so first MEZ = +0100 and later MESZ = +0200) whereas the camera clock just keeps on ticking (approximately with a +0100 offset throughout).
Q: How can I tell exiftool to not assume that the camera clock (DateTimeOriginal) follows any daylight saving time rules?
A:
Yes, the problem ultimately comes from the DST switching and the fact that the DateTimeOriginal is interpreted as local time (hence subject to DST changes). There seem to be several ways to workaround the problem
A) change the local time zone
I.e., change the locale settings so that your system is in a time zone that does not switch DST during the time interval and then invoke exiftool as in the OP.
However, I won't recommend this. You'd also have to be careful that the selected DST-less time zone is not too far off or else exiftool might be off by a full day with some of its guesses. It seems that West Africa Time (as used in Nigeria) would have worked in my specific situation.
B) Add Time zone information to DateTimeOriginal first
I.e., first run
exiftool '-DateTimeOriginal<$DateTimeOriginal+01:00' -ext .jpg .
as +01:00 was effectively the camara's time zone all along.
This might have been advisable anyway to prevent future confusion about the time the images were taken. Then again, we are about to add the unambiguous and adjusted GPS time anyway.
I ended up doing
C) Use -geotime and explicit reference times with time zone specification
... as in
exiftool -geotag "*.gpx" \
-geosync "19:25:42Z@2018:03:01 20:25:42+01:00" \
-geosync "09:16:34Z@2018:03:31 10:17:00+01:00" \
'-geotime<${DateTimeOriginal}+01:00' \
-ext .jpg .
This tells exiftool to use DateTimeOriginal with specified time zone instead of interpreted as local time. Unfortunately, this only applies to the times read from the images being modified, not for the times read form the reference images (even if one changes the parameter order), so that the explicit times (with time zone) had to be used instead of file references.
Actually, since my refernce images had already been assigned correct GPS times from the first experiments, what I really did was a mix of B and C: I did the adjustment suggested in "B" only for the two reference images:
$ exiftool '-DateTimeOriginal<$DateTimeOriginal+01:00' IMG_7882.jpg IMG_9798.jpg
so that their DateTimeOriginal data had time zone info:
$ exiftool -datetimeoriginal -gpsdatetime IMG_7882.jpg
Date/Time Original : 2018:03:01 20:25:42.00+01:00
GPS Date/Time : 2018:03:01 19:25:42Z
$ exiftool -datetimeoriginal -gpsdatetime IMG_9798.jpg
Date/Time Original : 2018:03:31 10:17:00.00+01:00
GPS Date/Time : 2018:03:31 09:16:34Z
After that I could use the reference images by their file names
exiftool -geotag "*.gpx" \
-geosync "IMG_7882.jpg" \
-geosync "IMG_9798.jpg" \
'-geotime<${DateTimeOriginal}+01:00' \
-ext .jpg .
produces the desired result for the GPS times (and consequently for the GPS coordinates) also for intermediate images:
$ exiftool -datetimeoriginal -gpsdatetime IMG_8888.jpg
Date/Time Original : 2018:03:17 15:32:22
GPS Date/Time : 2018:03:17 14:32:08.114220008Z
|
{
"pile_set_name": "StackExchange"
}
|
Q:
aChartEngine Line Graph setYAxisMax for add padding to graph
I'm tryng to add some padding in my graph by setting up min and max values to X and Y axis.
my XYMultipleSeriesRenderer code is below:
// custom render
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
// background
renderer.setBackgroundColor(Color.parseColor("#ffffff"));
renderer.setMarginsColor(Color.parseColor("#ffffff"));
renderer.setPointSize(pointStrokeWidth);
renderer.setPanEnabled(true, true);
//renderer.setPanEnabled(false);
renderer.setShowLegend(false);
// renderer.setZoomEnabled(false);
renderer.setInScroll(true);
renderer.setClickEnabled(true);
renderer.setXLabels(0);
// setscale
// renderer.setScale((float) 1.5);
//renderer.setShowAxes(true);
// label padding and size
renderer.setShowCustomTextGrid(true);
renderer.setLabelsTextSize(20);
renderer.setXAxisMin(-0.2f);
double maxX = dashboard.getDaysDashboard().size()-0.9F;
renderer.setXAxisMax(maxX);
renderer.setYAxisMin(-0.3f);
double maxY = dashboard.maxNumberOfContent()-5.0F;
Log.d(TAG, "max y: "+maxY);
renderer.setYAxisMax(maxY);
// y
renderer.setYLabelsPadding(20);
renderer.setYLabelsAlign(Align.LEFT);
// x
renderer.setXLabelsPadding(20);
renderer.setXLabelsAlign(Align.CENTER);
// margins - an array containing the margin size values, in this order:
// top, left, bottom, right
int[] margins = {10, 30, 0, 10 };
renderer.setMargins(margins);
If I set differents maxX values, I can see that my graph change. If I change maxY value, graph didn't change! I try by setting +/-1 at the max Y value of the lines, or adding +/-100, I try with int or double but nothing! Why isn't change my graph padding by changing Y axis values?
A:
I solved with this code:
// * ASSIX Y *
renderer.setYLabels(0);
renderer.setYLabelsPadding(35);
renderer.setYLabelsAlign(Align.RIGHT);
// Y max
renderer.setYAxisMax(dashboard.maxNumberOfContent());
// set ASSY numbers label
int unit = dashboard.maxNumberOfContent() / 5;
for (int i = 0; i <= 5; i++) {
String yLabel = "" + unit * i;
renderer.addYTextLabel((unit*i), yLabel);
}
renderer.addYTextLabel(dashboard.maxNumberOfContent(), dashboard.maxNumberOfContent()+"");
renderer.setYAxisMax(dashboard.maxNumberOfContent()+(unit/2));
// * ASSIX X *
renderer.setXLabels(0);
renderer.setXLabelsPadding(0);
renderer.setXLabelsAlign(Align.CENTER);
// X max
double maxX = dashboard.getDaysDashboard().size() - 0.9F;
renderer.setXAxisMax(maxX);
// X days label
ArrayList<String> dayNames = getWeekDaysDashboard();
for (int i = 0; i < days.size(); i++) {
renderer.addXTextLabel(days.get(i), dayNames.get(i));
}
// CUSTOM STYLE LINE CHART
// * background
renderer.setBackgroundColor(Color.parseColor("#ffffff"));
renderer.setMarginsColor(Color.parseColor("#ffffff"));
renderer.setPointSize(pointStrokeWidth);
renderer.setInScroll(true);
renderer.setClickEnabled(true);
renderer.setZoomEnabled(false, false);
renderer.setPanEnabled(false, false);
renderer.setShowLegend(false);
renderer.setShowAxes(true);
// label padding and size
renderer.setShowCustomTextGrid(true);
renderer.setLabelsTextSize(40.0f);
renderer.setXAxisMin(-0.2f);
int yMin = -(unit/5);
Log.d(TAG, "ymin: "+yMin+" // unit: "+unit);
if (yMin < 1) {
yMin = -1;
}
renderer.setYAxisMin(yMin);
// *** margins: top, left, bottom, right
int[] margins = { 10, 60, 10, 30 };
renderer.setMargins(margins);
(This do the trick: renderer.setYAxisMax(dashboard.maxNumberOfContent()+(unit/2)); )
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How To Sort Out 3rd Party Technic Clones From LEGO Originals?
I've recently bought bulk parts, and wish to sort out the official LEGO pieces from the inferior quality 3rd party clones.
On bricks I can easily spot-out the clones, becasue they don't sport the "LEGO" logo on the studs.
So, I'm looking for an easy way to spot-out fakes on non-studded pieces like this Technic Bushing:
My tip off is that some of the Bushings don't grip well to various axles, thus giving me the idea that these Bushings too, might be some inferior quality 3rd party clones.
Some of the Bushings have VERY tiny writings with the "LEGO" logo.
Does this mean all pieces without the logo are clones?
Has LEGO branded all parts (even the smallest) with a logo?
Has it been doing so from many years back?
I suspect it could be more complicated, for example, many stud-less parts like this thin part:
have some numbers and the copyright "(c)" sign, but no "LEGO" logo. I've checked many pieces. Some large ones have "LEGO Group" written on it.
So, regarding authenticity, would the logo matter?
Maybe I'm into perfection too much, but I'd like to sort-out my collection form the fakes, and preferably without breaking out the 10x monocle lens.
What would you advice?
A:
Regarding the Bushings, I think the loss of their gripping/clutching power has less to due with a phantom cloning agent, and more to due with the quality of the official LEGO piece, and how plastic degrades over time.
My collection has Bushings that are weak too, but its due to age (over 25+ years) and normal play. Mine are not clones.
Now the issue with copyright holders is a little different. LEGO doesn't hold the patent design for the classic brick, becasue they didn't invent it, so now it's a friggin' free for all with clone "bricks" manufacturers.
As for non-brick designs like the Technic Bush, and that thin blue piece, LEGO owns those, and could bring forward litigation to copyright infringers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Switch Statements in Javascript based on input text value
I am trying to accomplish the following currently and am not very familiar with Javascript so I am hoping I could get some good suggestions and answers for the following as I have gotten such great help with my Javescript questions here before.
Basically I have an input field where the user will enter a value. Once that value is entered I want to provide the user some information in a div, prior to them submitting the value to the Ajax handler. I would also like to have the values presented to them on each change of the input fields text. I have 3 different types of data being submitted so for each type I would like to present different information sets to the user based on what their input contains. For this I use a switch, but the switch is currently not working as it appears below.
function createLinks() {
var sv = document.getElementById('sv').value // Input Text
var div = document.getElementById('svResult');
switch (true) {
case (sv.indexOf('1') >= 0):
div.innerHTML="1 Links: ";
break;
case (sv.indexOf('2') >= 0):
div.innerHTML="2 Links: ";
break;
case (sv.indexOf('3') >= 0):
div.innerHTML="3 Links: ";
break;
}
//div.innerHTML=sv.value;
}
<div>
<form>
<label for="sv">Server:</label>
<input type="text" id="sv" size="16" title="Coming Soon" onchange="createLinks()"/>
<input type="submit" style="margin-left: 10px;" value="Search" class="button1"/>
</form>
<div id="svResult"></div>
</div>
When I just display the sv.value in the div assigned to the div variable it displays correctly, but when the switch is introduced I do not get any output. The switch is based on the return of each case statement being either true or false, but there is probably something simple I am missing.
I did see this which helped get the input value into the variable correctly, but focuses more on if statements.
A:
In the HTML, there is no need for an ID attribute and form controls must have a name to be successful. You can also pass a reference to the element from the listener:
<input type="text" name="sv" size="16" title="Coming Soon" onchange="createLinks(this)">
Then the script can be something like:
function createLinks(el) {
var value = el.value;
var div = document.getElementById('svResult');
if (value.indexOf('1') != -1) {
div.innerHTML = '1 Link';
} else if (value.indexOf('2') != -1) {
div.innerHTML = '2 Links';
} else if (value.indexOf('3') != -1) {
div.innerHTML = '3 Links';
}
} else {
div.innerHTML = '';
}
}
The above will return on the first match, so an input of '123' will report "1 link". Also, the change event is dispatched when the control loses focus, which might be later than you want.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where does the algebraic closure enter into Block's Theorem?
When applying Block's Theorem on the structure of differentiably simple rings to Lie algebras most authors require an algebraically closed field, but I can see no reference to algebraic closure in Block's paper. What extra does the algebraic closure give? I apologise for asking such a basic (and perhaps easy) question but I've talked to a number of other algebraists and asked this on another forum without getting any answer.
A:
Block's theorem does not require the base field $k$ to be algebraically closed but one has to be careful when $k$ is imperfect. Then $k$ will admit field extensions of the form $K=k(a)$ with $a\not\in k$ and $a^p\in k$. Note that $K$ will become a truncated polynomial ring in one variable over a field extension $L=k(b)$ with $b^p=a^p$. If $p>2$ then the $k$-Lie algebra $\mathfrak{g}=\mathfrak{sl}_2\otimes_k K$ is simple of dimension
$3p$ (but not absolutely simple) and ${\rm Der}_k(K)$ is a nontrivial $k$-form of the Witt algebra $W(1;\underline{1})$ (such twisted forms can only exist over imperfect fields). By Block's theorem, the derivation algebra of $\mathfrak{g}$ is the semidirect product ${\rm Der}_k(K)\ltimes {\rm ad}\,\mathfrak{g}$
of dimension $4p$ over $k$ but it is not isomorphic to ${\rm Id}\otimes_k W(1;\underline{1})\ltimes ({\rm ad}\,\mathfrak{sl}_2)\otimes_k k[X]/(X^p)$ over $k$. However, such an isomorphism will exist over $L$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do i add whatsapp api link to email orders using the customer phone number?
I would like to add whatsapp link to admin complete orders email, that takes the customer phone number, and adds it to the whatsapp api link.
The idea is that, when i receive notification about order, i can contact my customer using whatsapp and let him know i got his order.
so it should look like this:
api.whatsapp.com/send?phone= {{customer phone number}} &text=...
A:
Add the follows code snippet in your active theme's functions.php and changes the text messages as per you.
function add_wp_link_woocommerce_completed_order_email( $order, $sent_to_admin, $plain_text, $email ) {
if ( $email->id == 'customer_completed_order' || $email->id == 'new_order' ) {
$link = 'https://wa.me/'.$order->get_billing_phone( 'edit' ).'/?text='.urlencode( 'your text messages' );
echo '<div style="margin-bottom: 40px;">
<h2>'.__( 'Customer WhatsApp link', 'text-domain' ) .'</h2>
<p><a href="'.$link.'" target="_blank">'.__( 'Contact', 'text-domain' ).'</a></p>
</div>';
}
}
add_action( 'woocommerce_email_customer_details', 'add_wp_link_woocommerce_completed_order_email', 99, 4 );
|
{
"pile_set_name": "StackExchange"
}
|
Q:
compgen : ignoring case
I'm trying to implement a custom bash completion as described here. However, it seems that compgen is case-sensitive. Is there a way to turn it case-insensitive in that context ?
A:
I would modify the example from the link you mentioned into something like this:
_foo()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD],,}" # this downcases the result
prev="${COMP_WORDS[COMP_CWORD-1],,}" # here too
opts="--help --verbose --version"
if [[ ${cur} == -* ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
fi
}
complete -F _foo foo
For more info refer to the bash documentation or the bash hackers site.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery: Proper Syntax For Prepending HTML
I'm new to jQuery and I'm trying to prepend some HTML. However, I keeping getting syntax error via DreamWeaver.
Here is my code:
<script type='text/javascript'>
$(document).ready(function(){
$(".contentpadded").prepend($unoslider);
var $unoslider = $('
<ul id="unoslider" class="unoslider">
<li><img src="templates/{$template}/img/cloud-hosting.jpg" alt="" /></li>
<li><img src="templates/{$template}/img/green-hosting.jpg" alt="" /></li>
<li><img src="templates/{$template}/img/trusted-partners.jpg" alt="" /></li>
</ul>
'),
});
</script>
I can't figure out what's wrong with it. Any suggestions?
A:
You should concatenate the strings, also note that there is a redundant , in your code.
var $unoslider = $('<ul id="unoslider" class="unoslider">'+
'<li><img src="templates/{$template}/img/cloud-hosting.jpg" alt=""/></li>' +
'<li><img src="templates/{$template}/img/green-hosting.jpg" alt="" /></li>' +
'<li><img src="templates/{$template}/img/trusted-partners.jpg" alt="" /></li>' +
'</ul>');
$(".contentpadded").prepend($unoslider);
Note that you should first define the variable and then append it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to vertical center a div in a div with unknow height?
I created a div container which contains a div for image and a div for text. The parent div's height is set to text div's height automatically. I don't want to set a actual height to the container. What I want is to center the image div vertically in the container, and when I changing the window size horizontally, the image will also change its size, but still at the middle of the container. How should I do?
I've tried 'table-cell', 'inline-block', 'vertical-align: middle', 'position: absolute' methods, but they didn't work.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="container">
<div class="img">
<img src="img.jpg">
</div>
<div class="text">
<h3>Heading</h3>
<p>
Bacon ipsum dolor amet leberkas pancetta porchetta tenderloin ground round, shoulder doner. Ribeye corned beef ground round tri-tip chicken kevin. Shankle burgdoggen ham hock t-bone brisket jowl pork chop tongue pork belly jerky ham tail venison. Filet mignon porchetta short loin swine fatback, turducken meatball ham hock tongue corned beef pancetta hamburger boudin tenderloin burgdoggen.
</p>
<br>
<p>
Strip steak landjaeger ham hock, pig picanha cow beef ribs drumstick prosciutto ball tip chicken cupim tongue salami. Cupim flank kielbasa, strip steak pork buffalo boudin. Turducken meatball sausage short ribs bacon pig venison t-bone hamburger. Strip steak alcatra boudin burgdoggen cupim. Leberkas frankfurter swine prosciutto hamburger ball tip.
</p>
<br>
<p>
Cupim buffalo pork loin, pork chop picanha corned beef turkey sausage cow chuck ham hock flank. Pork belly frankfurter meatloaf andouille spare ribs jowl leberkas venison salami capicola sausage kevin chuck. Flank beef ribs fatback, strip steak bresaola turducken biltong salami boudin tongue spare ribs pastrami shoulder frankfurter cupim.
</p>
</div>
</div>
</body>
*{
box-sizing: border-box;
}
.container{
padding: 0 5vw;
overflow: auto;
}
.img{
width: 25%;
float: left;
}
.img>img{
width: 100%;
}
.text{
width: 75%;
float: left;
padding: 0 0 0 2em;
}
A:
Simply use display:flex for your parent class and align:self:center for image class. I hope this solution will work for you.
* {
box-sizing: border-box;
}
.container {
padding: 0 5vw;
overflow: auto;
display: flex;
}
.img {
width: 25%;
float: left;
align-self: center;
}
.img>img {
width: 100%;
}
.text {
width: 75%;
float: left;
padding: 0 0 0 2em;
}
.text h1 {
margin: 0 0 20px;
}
<div class="container">
<div class="img">
<img src="https://via.placeholder.com/350x350">
</div>
<div class="text">
<h3>Heading</h3>
<p>Bacon ipsum dolor amet leberkas pancetta porchetta tenderloin ground round, shoulder doner. Ribeye corned beef ground round tri-tip chicken kevin. Shankle burgdoggen ham hock t-bone brisket jowl pork chop tongue pork belly jerky ham tail venison. Filet mignon porchetta short loin swine fatback, turducken meatball ham hock tongue corned beef pancetta hamburger boudin tenderloin burgdoggen. </p>
<p>Strip steak landjaeger ham hock, pig picanha cow beef ribs drumstick prosciutto ball tip chicken cupim tongue salami. Cupim flank kielbasa, strip steak pork buffalo boudin. Turducken meatball sausage short ribs bacon pig venison t-bone hamburger. Strip steak alcatra boudin burgdoggen cupim. Leberkas frankfurter swine prosciutto hamburger ball tip. </p>
<p>Cupim buffalo pork loin, pork chop picanha corned beef turkey sausage cow chuck ham hock flank. Pork belly frankfurter meatloaf andouille spare ribs jowl leberkas venison salami capicola sausage kevin chuck. Flank beef ribs fatback, strip steak bresaola turducken biltong salami boudin tongue spare ribs pastrami shoulder frankfurter cupim. </p>
<p>Bacon ipsum dolor amet leberkas pancetta porchetta tenderloin ground round, shoulder doner. Ribeye corned beef ground round tri-tip chicken kevin. Shankle burgdoggen ham hock t-bone brisket jowl pork chop tongue pork belly jerky ham tail venison. Filet mignon porchetta short loin swine fatback, turducken meatball ham hock tongue corned beef pancetta hamburger boudin tenderloin burgdoggen. </p>
<p>Strip steak landjaeger ham hock, pig picanha cow beef ribs drumstick prosciutto ball tip chicken cupim tongue salami. Cupim flank kielbasa, strip steak pork buffalo boudin. Turducken meatball sausage short ribs bacon pig venison t-bone hamburger. Strip steak alcatra boudin burgdoggen cupim. Leberkas frankfurter swine prosciutto hamburger ball tip. </p>
<p>Cupim buffalo pork loin, pork chop picanha corned beef turkey sausage cow chuck ham hock flank. Pork belly frankfurter meatloaf andouille spare ribs jowl leberkas venison salami capicola sausage kevin chuck. Flank beef ribs fatback, strip steak bresaola turducken biltong salami boudin tongue spare ribs pastrami shoulder frankfurter cupim. </p>
<p>Bacon ipsum dolor amet leberkas pancetta porchetta tenderloin ground round, shoulder doner. Ribeye corned beef ground round tri-tip chicken kevin. Shankle burgdoggen ham hock t-bone brisket jowl pork chop tongue pork belly jerky ham tail venison. Filet mignon porchetta short loin swine fatback, turducken meatball ham hock tongue corned beef pancetta hamburger boudin tenderloin burgdoggen. </p>
<p>Cupim buffalo pork loin, pork chop picanha corned beef turkey sausage cow chuck ham hock flank. Pork belly frankfurter meatloaf andouille spare ribs jowl leberkas venison salami capicola sausage kevin chuck. Flank beef ribs fatback, strip steak bresaola turducken biltong salami boudin tongue spare ribs pastrami shoulder frankfurter cupim. </p>
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I map local branches to remote branches with different prefixes in git?
We're working with a semi-centralized git repository here where I work. Each developer has their own subtree in the central git repository, so it looks something like this:
master
alice/branch1
alice/branch2
bob/branch1
michael/feature
release/1.0
release/1.1
Working locally in my tree I have topic/feature, which corresponds to michael/feature in the central tree.
I've been using
git push origin topic/feature:michael/feature
to push my changes to the remote tree. However, this is cumbersome and prone to mistakes (e.g. omitting the developer name, misspelling the feature name, etc.).
I'm looking for a cleaner way to do this. For instance, "git push". I suspect that setting a different remote with a modified fetch refspec will do it, but I'm not sure how exactly to do it. I'm also not sure how to modify my current branch definitions to use the different remote.
My current .git/config looks something like:
[remote "origin"]
url = git://central/git/project
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "topic/feature"]
remote = origin
merge = refs/heads/michael/project
Edit: I'd also like to apply this to pulls/fetches. But does the branch.<name>.merge take care of that?
I'll continue to research this and post here if I find something, but I'm hoping to get some other good ideas.
Edit 2: I've decided I'll keep local and remote branch names the same. It appears it will be the least work and least prone to future problems.
A:
In your [remote "origin"] section, add one line per mapping. Including master to master.
push = refs/heads/master:master
push = refs/heads/topic/feature:michael/feature
I'm not sure how to do it with the git-config command.
Be aware that from now on, all branches are pushed at the same when you do a straight git push (with no params).
Would you care to explain why you don't keep the same branch names locally and remotely?
A:
If you can, I suggest you use the same branch names locally & remotely. Then git push will push all of your local branches to corresponding branches in the central repository.
To use different prefixes in local and remote repos, you need to add a mapping to your config file each time you create a new feature branch. The command to set up the mapping for topic/BRANCH_NAME is
git config remote.origin.push refs/heads/topic/BRANCH_NAME:michael/BRANCH_NAME
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is "Why problem X exists" duplicate of "How to solve problem X"?
This question: Why cat, grep and other commands can't understand files starting with minus sign? was marked as duplicate of this question: How do I delete a file whose name begins with "-" (hyphen a.k.a. dash or minus)?
disclaimer: I posted an elaborate answer for the why-question.
The text of the how-question is straight forward: how to solve the problem?
The text of the why-question reads more like a rant. One sentence in the text actually does ask how to solve the problem. The title is, IMO, dominating the question: why does the problem exists?
If it really is a duplicate then when the answers are merged the answers of one question should also answer the other question. In this case my answer for the why-question feels very out of place in the how-question. As well as the answers for the how-question feel very incomplete in the why-question.
Is it policy that why-questions are generally considered duplicate of how-questions?
If I edit the text of the why-question to remove that little reference to "how" and enfore the "why", would it be reopened?
A:
The question is not really asking why cat --1 isn't working: the asker did understand that this was because cat is interpreting --1 as an option. The real question is
Is there any universal workaround different from not using such file names?
So yes, the question is a duplicate. Unfortunately, the earlier question has pretty poor answers, inherited from the early days of the site, with a lot of upvotes but not much in the way of explanations. Your answer is a lot better (though still incomplete, as you don't explain the peculiarity of - or why quotes don't help).
There's no rule that the newer question has to be closed as a duplicate of the older one. It's the typical case, but in general the question with the worse answers should be closed as a duplicate of the question with the better answers. So we should invert the duplicate closure.
(Unless there's already another better duplicate? I thought I remembered an answer by Stephane Chazelas that went through all of this, but I can't find it.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Could not find any resources appropriate for the specified culture or the neutral culture?
I can't run my application. I receive the following error:
Could not find any resources appropriate for the specified culture or
the neutral culture. Make sure
"NETScoreCore.Resources.Shared.SharedStrings.resources" was correctly
embedded or linked into assembly "NETScoreCore" at compile time, or
that all the satellite assemblies required are loadable and fully
signed.
The code that throws this error is the following line, which ran correctly before, but now throws this error:
return ResourceManager.GetString("For_business",resourceCulture);
A:
Though you don't seem to have asked a question yet, here's an attempt for an answer. Google shows me this KB article from Microsoft, it's possible that you just hit that bug.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iPhone's power button doesn't lock, shows Swipe to Power Off instead
My iPhone SE, running iOS 12.4 reached its lower battery limits and went dead. I, foolishly pressed power button and then it stayed in an Apple Logo screen → power off → Apple Logo, loop for a while till I could get hold of the charger. After plugging in and letting it get some power, I observed the following:
It vibrated 3-4 times as if I removed and plugged in the power again which I didn't.
Pressing the power button once shows the Swipe To Power Off screen after a second or so. Doing it twice gives the same result.
To be able to lock it, I use the assistive touch method but that works only when I tap the Lock Screen icon twice.
How can I get my power button to start locking the screen again ?
Is there anything else I can do except connecting the charger, if it goes dead again, to power it up ?
I bought it 2.5 years ago, and don't have AppleCare. Its battery capacity is 94%.
A:
The button seems to have fixed itself. I used assistive touch to lock it
Locking an iPhone if button is broken?
and kept checking if power button is working or not. Often it shows the swipe to power off screen, but that's okay. Somehow battery capacity became 84%.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Place Caret at end of ContentEditable Div does not work
I am trying to send the caret at the end of a contenteditable, which works fine, except that it is not placed at the end if I insert an empty <span></span> element and the end.
<div contenteditable>
<span>Start</span>
<span></span>
</div>
The Caret is placed at Start, but not on the new line.
This is the code I am using to place the caret at the end:
PlaceCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
Where el is the contenteditable div.
Thanks for your help.
A:
You had some syntax errors on the snippet.
I fixed them, ran it, and it worked. Caret is in the end.
However, I'm not exactly sure what you meant (if you want the caret at the end of the new line or the first line.)
In order for the caret to be at the end of the new line, you need to effectively "create" a new line. span is an inline element. span won't start a new line without some CSS rule. div will. Also, it needs sone content in order for it to take effect.
placeCaretAtEnd(document.querySelector("div[contenteditable]"));
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
<div contenteditable>
<span>Start</span>
<span style="display: block;">New Line</span>
</div>
Something extra, contenteditable is a boolean attribute. you can omit the ="true" part and simply put the attribute. See this.
Edit:
If you want a new line without any text on it use <br> (twice - since span comes before it. If it was <div>Start</div> you could have used only 1)
placeCaretAtEnd(document.querySelector("div[contenteditable]"));
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
<div contenteditable>
<span>Start</span>
<br><br>
<span></span>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I delete the contents a directory, without deleting the directory itself? Here's what I've tried so far
I'm making a button that reads a file path then deletes the files within the folder. It's currently deleting the entire directory. Here's my code:
public void deleteFiles(string Server)
{
string output = "\\\\" + Server + "\\F\\Output";
string input = "\\\\" + Server + "\\F\\Input";
string exceptions = "\\\\" + Server + "\\F\\Exceptions";
new System.IO.DirectoryInfo(input).Delete(true);
new System.IO.DirectoryInfo(output).Delete(true);
new System.IO.DirectoryInfo(exceptions).Delete(true);
}
A:
Would just deleting the directory and recreating it work? Or do you want to preserve permissions?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Emploi du verbe "procrastiner" pour rendre l'idée de "remettre aux calendes grecques"
L'expression "remettre aux calendes grecques" est-elle répandue/reconnue ?
Peut-on couramment rendre son sens avec le verbe "procrastiner" ?
A:
Oui! Elle est très usuelle mais forcément pas au sens de procrastiner qui signifie plus remettre à plus tard, à demain. On le fera sûrement mais... un autre jour, alors que :
Comme tu le sais mieux que nous... les Grecs n'ayant pas de calendes... remettre aux calendes grecques signifie très exactement qu'on ne le fera... ni demain ni un autre jour... mais bien qu'on ne le fera jamais.
Note que le français connaît aussi dans le genre la remise sine die. C'est une certaine forme de procrastination. On le fera certainement un jour mais... juste... on sait pas dire précisément lequel.
NDaCOSwt : Et... parce que ce sujet m'a amusé... finalement... les choses que ne n'admets de faire qu'à titre posthume... c'est de la procrastination ou de la remise aux calendes grecques ?
Bon! Je vous autorise trancher : c'est du foutage de gueule! Mais bon... ce sujet en était-il exempt ?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compiling shaders in PyQt
I can't get a basic shader program working in PyQt. I think this should at least compile the shader code correctly (I'm no expert here), but addShaderFromSourceFile() always returns false no matter what I try. The shader program log is always empty too.
I'm on Ubuntu 12.04, and I can compile and run GLSL shader programs in C++. So I don't think it's a system issue.
File shader.vert
void main(void)
{
gl_Position = ftransform();
}
File shader.frag
void main(void)
{
gl_FragColor = vec4(1.0,0.0,0.0,1.0);
}
File test_shaders.py
from OpenGL.GL import *
from OpenGL.GLU import *
from PyQt4 import QtCore, QtGui
from PyQt4.QtOpenGL import *
class ExampleQGLWidget(QGLWidget):
def __init__(self, parent):
QGLWidget.__init__(self, parent)
self.shaderProgram = QGLShaderProgram()
print self.shaderProgram.addShaderFromSourceFile(QGLShader.Vertex, "shader.vert")
print self.shaderProgram.addShaderFromSourceFile(QGLShader.Fragment, "shader.frag")
print self.shaderProgram.log()
self.shaderProgram.link()
glViewport(0,0, 640, 480)
def paintGL(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
self.shaderProgram.bind()
def resizeGL(self, w, h):
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
def initializeGL(self):
glClearColor(0.0, 0.0, 0.0, 1.0)
glClearDepth(1.0)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
class TestContainer(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
widget = ExampleQGLWidget(self)
self.setCentralWidget(widget)
if __name__ == '__main__':
app = QtGui.QApplication(['Shader Example'])
window = TestContainer()
window.show()
app.exec_()
A:
The OpenGL context isn't setup inside the constructor, it's only valid and current inside the paintGL, resizeGL and initializeGL methods, so you should load and compile shaders inside the initializeGL method, and not anywhere else.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using QStyle to set global default minimum QPushButton height
Is it possible to define a default minimum height for a QPushButton through a custom application wide QStyle?
I know this can be achieved using stylesheets, but I rather not use them because of performance reasons.
A:
You might consider looking at the QApplication::globalStrut property, which is designed to provide a minimum size for any user-interactive UI element. Ideally, it would do what you want (and possibly more). However, I have seen times when this was ignored, either by the widget or the style drawing the widget, so in practice it has been somewhat less than useful.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
gdk_display_get_name: assertion 'GDK_IS_DISPLAY (display)' failed trying to run pidgin
I compiled and installed pidgin on my MacOSx Mavericks, everything seem to went fine on make install but when I try to start pidgin from terminal
I get following error:
$ pidgin
(Pidgin:68719): Gdk-CRITICAL **: gdk_display_get_name: assertion 'GDK_IS_DISPLAY (display)' failed
Pidgin 2.10.11
** (Pidgin:68719): WARNING **: cannot open display: unset
can anyone help getting rid of this message ?
A:
So to install Pidgin first I ran ./configure with following arguments. --disable-screensaver --disable-sm --disable-gtkspell --disable-gstreamer --disable-vv --disable-meanwhile --disable-avahi --disable-dbus --disable-nss --disable-gnutls then I ran make to build a compile for my osx mavericks. then make install . In doing all the proces I discovered I need boost python binding, for which I installed boost via macports using sudo port install libboost . But when I tried to run Pidgin I got the above error mentioned in the post, so I discovered Pidgin cannot find the display required. For which I had to install XQuartz restarting installing XQuartz took a while and I relogged in and then Pidgin worked. On my OSx now the value of DISPLAY environment variable points to /tmp/launch-DXOhcE/org.macosforge.xquartz:0
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ASP.Net Email and Account validation
i was wondering if any one can advise me on how i can go about implementing a email and account validation feature in my ASP.net website. so when a user creates an account, an email is sent to the email address used, and the user needs to verify that email address to be able to logon.
thanks
A:
Suggested workflow..
Create an account for the user in your database and mark the account as "to be validated"
Produce a random key, maybe a GUID and add it to the users account
Email the random key to the user along with a unique URL, e.g www.myurl.com/validateuser.aspx?userid=45532
To email using asp.net use the system.net.mail namespace - lots of bits on the internet about this.
On validateuser.aspx ask user to enter key sent to them in email.
Check if keys match. If so update db record to "validated"
Edit
By the way, there is a nice answer here on Stack Overflow if you are using forms auth
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Random double loop in python
What i would like to do is create a random double loop in python
For example for (N,N)=(2,2)
the program shoud give:
0 1
0 0
1 1
1 0
or another example
0 0
1 1
1 0
0 1
What i have done so far is this:
r1 = list(range(2))
r2 = list(range(2))
random.shuffle(r1)
random.shuffle(r2)
for i in r1:
for j in r2:
# do something with i
This however does not give the desired result because i want i's to be shuffled too and not give for example all (1,x) sequentially.Any ideas?
A:
Shuffle the product of the ranges, not each individual range.
import itertools
pairs = list(itertools.product(r1, r2)) # [(i,j) for i in r1 for j in r2]
random.shuffle(pairs)
for i, j in pairs:
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select from Array to get ID based on Name
Here is my var_dump:
array(2) {
[1]=>
object(stdClass)#382 (3) {
["name"]=>
string(12) "Other fields"
["sortorder"]=>
string(1) "1"
["id"]=>
int(1)
}
[3]=>
object(stdClass)#381 (3) {
["name"]=>
string(6) "custom"
["sortorder"]=>
string(1) "2"
["id"]=>
int(3)
}
}
I need some PHP to select the 2nd object, obviously it wont always be the 2nd object, so I need to select it based on its ["name"] which will always be "custom".
The below code give's me all the names but I just want "custom" and the get the ID of custom.
foreach ($profilecats as $cat) {
$settings .= $something->name;
}
A:
foreach ($profilecats as $cat) {
if ($cat->name == 'custom') {
echo $cat->id;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Separating GUI and DAO via REST Webservices and Spring
I have a general question about the correct (or maybe: the best) way to handle data from GUI to DAO.
I built a project where GUI input is being validated and sent directly to a DAO class which handles (via Hibernate) the database updates/inserts.
Now I decided to split DAO and GUI up into two separate projects and use a REST WS with Spring integration to handle the data. I considered this, because I thought this might be a good idea for future projects (advantage of course being the complete separation of the GUI from DAO).
For the moment I have a bit of a problem of making this all work (Spring error creating bean xStreamMarshaller). But before I try unnecessarily I wanted to know: Is that really a good approach?
Is this really a correct way or am I doing something completely unnecessary?
A:
I think this post can be useful for you:
Spring MVC RESTful multiple view - 404 Not Found
I like the idea to work with restful, because you can really split the application not just in the back-end, but in the front-end as well. This way you can just get JSON in your javascript. But of course each case is different each other.
Follows a video about the subject: Designing a REST-ful API Using Spring 3
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I pass a value to a PHP script using AJAX?
I am trying to learn web design with a search function using MySql. I want make it to 2 steps selection however, I have run into a problem which really confuses me since I don't have a strong background to design. I am trying to be as specific as possible to make the question clear.
test.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>count</title>
<link rel="stylesheet" type="text/css" href="dbstyle.css">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'>
</script>
</head>
<body>
<form id="serc" method="post" action="">
<input type="radio" value="typeA" name="comments" onclick="expr()">Good
<input type="radio" value="typeB" name="comments" onclick="expr()">Bad
</form>
<form id="form1" name="form1" method="post" style="visibility:hidden">
<p>please select reason:</p>
<input type="checkbox" class="check" name="checkbox[]" value="COL 8">aaa<br />
<input type="checkbox" class="check" name="checkbox[]" value="COL 9">bbb<br />
<input type="checkbox" class="check" name="checkbox[]" value="COL 10" >ccc<br />
<button id="aaa" type="submit" class="butt" name="sub2" style="visibility:hidden">Submit</button>
</form>
<?php
$comm = $_POST["gender"];
$reas = $_POST["checkbox"];
if($comm){$respond = $_POST['comments'];
echo $respond;
}
<script src="limit.js"></script>
</body>
</html>
limit.js
//click to get Value
$("input[type='Radio']").click(function(){
var radioValue = $("input[name='comments']:checked").val();
$("#serc").css("display", "none");
$("#form1").css("visibility", "visible");
});
//limit multiple selection up to 4
$("input:checkbox").click(function() {
var bol = $("input:checkbox:checked").length;
if(bol == 4){
$("input:checkbox").not(":checked").attr("disabled",bol);
$("#aaa").css("visibility", "visible");
}
else {
$("#aaa").css("visibility", "hidden");
$("input:checkbox").removeAttr("disabled");
}
});
// return value
function expr()
{
var radioValue = $("input[name='comments']:checked").val();
var dataTosend= radioValue;
$.ajax({
url: 'index.php',
type: 'POST',
data: dataTosend,
async: true,
success: function (data) {
alert(data)
},
});
}
The function will be:
First stage select from radio item, onclick use jQuery to hide the selection items and also get radioValue from the jQuery by Ajax way to send to php use.
Second stage select 4 items from checkbox, and submit to run search field.
I expect load the radioValue back to php as a variable but seems it didn't get the value.
Any help would be appreciated.
A:
You must send data using key value pair like this:
function expr(){
var radioValue = $("input:radio[name='comments']").val();
var dataTosend= {'radioValue': radioValue};
$.ajax({
url: 'index.php',
type: 'POST',
data: dataTosend,
async: true,
success: function (data) {
alert(data)
},
});
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Google app script ActiveCell manipulation
All this function intended to do is paste value the cell which the cursor is on. Can't get it to paste value
function fix_values(){
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName('Time')
var cell = sheet.getActiveCell()
var value = cell.getValue()
cell.setValue(value)
cell.setFontColor('blue')
cell.setNumberFormat("m/d/yy hh:mm")
Logger.log(value)
}
what am I doing wrong?
A:
Have you used the debugger to check what each line is returning?
I suspect that sheet.getActiveCell() is returning cell A1 no matter which cell is active. It's been a known issue.
See Issue 3496 Try the workarounds suggested at #23 and #41 or Issue 3110 workaround at #2
|
{
"pile_set_name": "StackExchange"
}
|
Q:
unmerge arbitrary merge in cvs/svn
In CVS and/or SVN is there a way of unmerging an arbitrary merge (as in, not necessarily the last merge)
Let's say tere are 4 branches: trunk, feature1, feature2, feature3.
All feature* branches are merged into trunk one by one. Is there any way of cleanly 'unmerging' any of the feature branches?
How would you go about doing this?
A:
In Subversion you can use a so called reverse merge.
svn merge -c -MergedRev URL/trunk
The "-MergedRev" defines the revision where you merged the branch into the trunk which is usually exact a single revision.
svn merge -c -24567 URL/trunk
In CVS this can be done using instructions at http://dev.usw.at/manual/cvs/cvs-general/cvstrain-6.7.4.html. Since CVS has independent revisions for each file, the reverse merge would need to be performed for every affected file
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jquery animation not working in android
I have html doc with jquery animation looks very much alike: http://tympanus.net/Tutorials/LittleBoxesMenu/
and it works fine on browser but not working on android WebView .
Why not?
Is there some catch with jquery and android?
EDIT: did some testing on iPhone and everything is working just fine, still no idea why not working in android
A:
Ok, problem solved, quite simple at the end, in android app imported apache.cordova package, extended PhoneGap class and simply loaded URL. And that was it.
package voi.tii.yu;
import org.apache.cordova.*;
import android.os.Bundle;
public class PhonegapActivity extends DroidGap {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/page2/index.html");
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MongoDB Fails to Upgrade on Linux Mint, Post-Installation Script Returned Error
So I ran into a fun little problem today with updating my instance of MongoDB using the package manager. Every time it tried to update, it would give me an error of E: mongodb-10gen: subprocess installed post-installation script returned error exit status 1
Everything else upgrades fine in the package manager.
A:
The error was saying it wasn't able to sucessfully run the post-installation script; essentially it couldn't restart the database after it was upgraded. In my case, that's because the DB was already running. Shutting down and upgrading normally fixed my issue and allowed my package manager to fully upgrade.
mongo
use admin
db.runCommand('shutdown')
exit (after this you should be inside the shell)
sudo apt-get update
sudo apt-get upgrade
Voila, now your MongoDB install should be upgraded and running.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
GWT: Populating a page from datastore using RPC is too slow
Is there a way to speed up the population of a page with GWT's UI elements which are generated from data loaded from the datastore? Can I avoid making the unnecessary RPC call when the page is loaded?
More details about the problem I am experiencing: There is a page on which I generate a table with names and buttons for a list of entities loaded from the datastore. There is an EntryPoint for the page and in its onModuleLoad() I do something like this:
final FlexTable table = new FlexTable();
rpcAsyncService.getAllCandidates(new AsyncCallback<List<Candidate>>() {
public void onSuccess(List<Candidate> candidates) {
int row = 0;
for (Candidate person : candidates) {
table.setText(row, 0, person.getName());
table.setWidget(row, 1, new ToggleButton("Yes"));
table.setWidget(row, 2, new ToggleButton("No"));
row++;
}
}
...
});
This works, but takes more than 30 seconds to load the page with buttons for 300 candidates. This is unacceptable.
The app is running on Google App Engine and using the app engine's datastore.
A:
You could do a lot of things, I will just list them in order that will give you the best impact.
FlexTable is not meant for 300 rows. Since your table is so simple, you should consider generating the HTML by hand, and then using simple HTML widget. Also, 300 rows is a lot of information - consider using pagination. The DynaTable sample app shows you how to do this.
It looks like you are using one GWT module per page. That is the wrong approach to GWT. Loading a GWT module has some non-trivial cost. To understand what I mean, compare browser refresh on gmail v/s the refresh link that gmail provides. That is the same cost you pay when every page in your website has a distinct GWT module.
If the list of candidates is needed across views, you can send it along with the HTML as a JSON object, and then use the Dictionary class in GWT to read it. This saves you the RPC call that you are making. This approach is only recommended if the data is going to be useful across multiple views/screens (like logged in users info)
Check how long your RPC method call is taking. You can enable stats in GWT to figure out where your application is taking time.
You can also run Speed Tracer to identify where the bottleneck is. This is last only because it is obvious FlexTable is performing a lot of DOM manipulations. In general, if you don't know where to start, Speed Tracer is a great tool.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
React - Show button in just one tab
I have a parent component with some buttons and tabs. I would like the buttons to NOT appear in one of those tabs. This seems rather simple, but I have no idea how to achieve this.
Please consider this code:
import React from 'react';
import {Tabs, Tab} from '../components';
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
editMode: false,
showButtons: true
}
}
showEditOption = () => { this.setState({ editMode: true }) }
hideEditOption = () => { this.setState({ editMode: false}) }
render() {
return (
<React.Fragment>
<div title="Company">
{this.state.showButtons
? !this.state.editMode ?
<button onClick={this.showEditOption}>Edit</button>
:
<React.Fragment>
<button onClick={this.hideEditOption} >Cancel</button>
<button disabled={disabled} onClick={this.handleFormSubmit} >Save</button>
</React.Fragment>
: null
}
</div>
<Tabs startingKey="company" className={styles.tabs}>
<Tab label='company' key='company'>
content 1 // show buttons here
</Tab>
<Tab label='users' key='users'>
content 2 // and not here
</Tab>
</Tabs>
</React.Fragment>
)
}
}
How can I achieve this?
Thank you :)
A:
So, I am assuming what you wanted to say was that you have a button outside your tabs element and you want to show those buttons only when one tab was selected.
I would store the selected tab in state somewhere:
this.state = {
editMode: false,
showButtons: true,
selectedTab: ''
}
Show the buttons only when the particular tab is selected:
{this.state.showButtons && this.state.selectedTab === 'company'
? !this.state.editMode ?
<button onClick={this.showEditOption}>Edit</button>
:
<React.Fragment>
<button onClick={this.hideEditOption} >Cancel</button>
<button disabled={disabled} onClick={this.handleFormSubmit} >Save</button>
</React.Fragment>
: null
}
Finally modify Tabs element to change state on tab change:
<Tabs startingKey="company" className={styles.tabs} onSelect={key => this.setState({ selectedTab: key })} >
Hope this was what you wanted.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to hide bottom-navigation-bar in Acces 2007
How can I hide this bar (see picture) in Access 2007?
hide this bar http://img217.imageshack.us/img217/2125/hideob.jpg
A:
Set the Form.NavigationButtons property to False.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use fat jar for different hue workflows
My intention is to use one fat jar for many different hue managed oozie jobs by calling its different main classes.
Everything works just fine if I put it in every respective workflow directory like this:
/user/hue/oozie/workspaces/hue-oozie-1439883696.08/myJobs.jar
But I cant figure out where I am supposed to put it, so all workflows can access it. Always getting an java.lang.ClassNotFoundException, as oozie cant find the jar.
/user/hue/oozie/workspaces/workflows/jobname/lib/myJobs.jar
looked promising, but doesn't seem to be right, too.
A:
Do You have Installed Shared Lib for Oozie, I belive You having Shared Lib Enabled by parameter like "
oozie.use.system.libpath = true
in the properties of Jobs, after Instaling Shared Lib Location in HDFS and place the Jar It Will Work.
Also Anothere Option: Check The Hadoop ClassPath Confiuration.
If The Fat Jar Local Location,is available in Local Nodes and the CLassPath need to be updated with the Same Local location and hadoop need to be restart to take the effect, then start the Oozie Job, and check Job Console the Required Jar should be reflecting there.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to properly set sessions in HttpContext?
I am using:
if (string.IsNullOrEmpty(myHttpContext.Request.QueryString["code"]))
{
if (myHttpContext.Session == null || myHttpContext.Session["code"] == null)
{
OutputError("Code", "Invalid code.");
}
else
{
code = myHttpContext.Session["code"].ToString();
}
}
else
{
code = myHttpContext.Request.QueryString["code"];
myHttpContext.Session.Add("code", code);
}
However I keep getting the error:
Object reference not set to an instance of an object.
For:
myHttpContext.Session.Add("code", code);
All I want to do is set a simple session, someone please help this is driving me crazy.
A:
Has your IHttpHandler (ashx) class implemented IRequireSessionState? Otherwise the Session object will not be accessible.
public class MyHandler : IHttpHandler, IRequireSessionState
{
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext ctx)
{
// your code here
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a general-case sweep line algorithm for line segment intersection?
I'm looking for a sweep line algorithm for finding all intersections in a set of line segments which doesn't necessarily require the general position constraint of Bentley-Ottman's algorithm (taken from Wikipedia):
No two line segment endpoints or crossings have the same x-coordinate
No line segment endpoint lies upon another line segment
No three line segments intersect at a single point.
Is there any sweep line solution to this problem? If not, is there any other algorithm that solves this problem in $\mathcal{O}((n+k) \log(n))$?
A:
Usually these algorithms can be adapted to the general case, but the details are messy and hard to get right. Another option is perturbation:
Move each line segment by some small amount in all directions.
Extend the segments slightly on both ends.
If you choose your parameters carefully (i.e., small enough), you are likely to have all the same intersections, but you will be in general position with probability 1. How small is small depends on your input, and this is a limitation of this approach, but in practice you can probably heuristically choose a small enough perturbation.
Implementing this using "virtual infinitesimals", you can come up with a version of Bentley–Ottman that doesn't require general position. The idea is to do the perturbation by some infinitesimal amount, and record the results formally (e.g. $1$ goes to $1+\epsilon$, where $\epsilon$ is an infinitesimal). When running the algorithm, you will need to compare values which involve these infinitesimals, which you can do formally (for example, $1+\epsilon < 1 + 2\epsilon$).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are user defined types (UDTs) available in an Azure SQL database managed instance?
Is it possible to create user defined types and user defined table types in an Azure SQL database managed instance?
A:
User-defined types are supported in Azure SQL Database except those based on a CLR assembly, which is not supported.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In C#, how does one implement an abstract class that calls itsself in a function e.g. such as a class of Addable objects?
Say we want to define a class that allows basic arithmatic, called 'Addable'. Addable things can be added.
abstract class Addable
{
public abstract Addable Add(Addable X, Addable Y)
}
What is the correct way to implement an Addable? The following doesn't work, it gives:
Number does not implement inherited abstract member Addable.Add(Addable, Addable).
class Number : Addable
{
public int Value;
public Number(int Val)
{
Value = Val;
}
public Number Add(Number X, Number Y)
{
return new Number(X.Value + Y.Value);
}
}
I think the problem is that Add takes (Number,Number) as its arguements which aren't generic enough, but I do not know how to proceed.
Edit: As some people have requested to know what this is to be used for, let me elaborate.
I am using an algorithm that relies on taking the maximum of several objects. Depending on the use case, these objects are numbers, or distributions. To stay with the example above I will pretend I need to add these numbers or distributions. So I want to have code that looks something like:
Addable LongAlgorithm(Addable X, Other parameters)
{
... // Lots of code that may contain X
Z = Add(X,Y)
... // Code Using Z.
return Answer // Answer is of the same type as X in the input.
}
Edit 2: With the feedback given this question seems to be drifting into the realm of "Interface vs Base class". Perhaps others who read this question might find that question illuminating.
I hope the question is clear, I am new to S.O. and although I have tried to stick to the guidelines as much as possible, I will be happy to modify the question to make it clearer.
A:
It all depends on why you want that Addable base class, and how it will be used. It's worth updating your question to explain this. Here's one possibility, which might not meet your use-case:
public interface IAddable<T>
{
T Add(T x, T y);
}
public class Number : IAddable<Number>
{
public int Value { get; set; }
public Number(int value)
{
Value = value;
}
public Number Add(Number other)
{
return new Number(Value + other.Value);
}
}
You could of course use an abstract base class as well here, if there was a need:
public abstract class Addable<T>
{
public abstract T Add(T x, T y);
}
If you want to make sure that types can only do class Foo : IAddable<Foo> and not class Foo : IAddable<Bar>, then you can add a generic type restriction:
public interface IAddable<T> where T : IAddable<T>
{
T Add(T x, T y);
}
In response to your edit:
Use my types from above and do this:
T LongAlgorithm<T>(T x, Other parameters) where T : IAddable<T>
{
... // Lots of code that may contain x
T z = x.Add(y);
... // Code Using z
return z;
}
Note that I've changed your Add method so that it's an instance method, which adds itself to another instance.
If you wanted to keep the signature as Add(x, y), you probably want something like this:
public class Number
{
public int Value { get; set; }
public Number(int value)
{
Value = value;
}
}
public interface IAdder<T>
{
T Add(T x, T y);
}
public class NumberAdder : IAdder<Number>
{
public static readonly NumberAdder Instance = new NumberAdder();
private NumberAdder() { }
public Number Add(Number x, Number y)
{
return new Number(x.Value + y.Value);
}
}
T LongAlgorithm<T>(T x, IAdder<T> adder, Other parameters)
{
... // Lots of code that may contain x
T z = adder.Add(x, y);
... // Code Using z
return z;
}
Then call it like
Number z = LongAlgorithm(new Number(3), NumberAdder.Instance, ...);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Asus G550 no sound
I have no sound coming from the notebook (on windows it works), if I plug in a headset it does work flawlessly.
Reading up on the issue I couldn't find any working solution. But seen people love to see ALSA info, so here it is: http://www.alsa-project.org/db/?f=cfe46c697339f6aec2ce1b9919b5ded493051b58
A:
From alsa-info, your internal soundcard is the second one, HDMI output being the first: Install and run "pavucontrol" (pulse audio volume control) . Launch it from multimedia menu, go to the "output devices" tab, and click the green "define as alternative" button that is near the second soundcard (HDA Intel PCH ).
If it still doesn't work, look also "configuration" tab and change profile.
Some people here have reported problems with dual boot and windows8: if affected, you have to completely switch off computer from Windows 8 and/or disable "fast boot" in Windows8.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How are the O_SYNC and O_DIRECT flags in open(2) different/alike?
The use and effects of the O_SYNC and O_DIRECT flags is very confusing and appears to vary somewhat among platforms. From the Linux man page (see an example here), O_DIRECT provides synchronous I/O, minimizes cache effects and requires you to handle block size alignment yourself. O_SYNC just guarantees synchronous I/O. Although both guarantee that data is written into the hard disk's cache, I believe that direct I/O operations are supposed to be faster than plain synchronous I/O since they bypass the page cache (Though FreeBSD's man page for open(2) states that the cache is bypassed when O_SYNC is used. See here).
What exactly are the differences between the O_DIRECT and O_SYNC flags? Some implementations suggest using O_SYNC | O_DIRECT. Why?
A:
O_DIRECT alone only promises that the kernel will avoid copying data from user space to kernel space, and will instead write it directly via DMA (Direct memory access; if possible). Data does not go into caches. There is no strict guarantee that the function will return only after all data has been transferred.
O_SYNC guarantees that the call will not return before all data has been transferred to the disk (as far as the OS can tell). This still does not guarantee that the data isn't somewhere in the harddisk write cache, but it is as much as the OS can guarantee.
O_DIRECT|O_SYNC is the combination of these, i.e. "DMA + guarantee".
A:
Please see this lwn article for a clear description of the roles of O_DIRECT and O_SYNC and their impact on data integrity:
https://lwn.net/Articles/457667/
A:
Actuall under linux 2.6, o_direct is syncronous, see the man page:
manpage of open, there is 2 section about it..
Under 2.4 it is not guaranteed
O_DIRECT (Since Linux 2.4.10)
Try to minimize cache effects of the I/O to and from this file. Ingeneral this will degrade performance, but it is useful in special situations, such as when applications do their own caching. File
I/O is done directly to/from user-space buffers. The O_DIRECT flag on its own makes an effort to transfer data synchronously, but does not give the guarantees of the O_SYNC flag that data and necessary metadata are transferred. To guarantee synchronous I/O, O_SYNC must be used in addition to O_DIRECT. See NOTES below for further discussion.
A semantically similar (but deprecated) interface for block devices is described in raw(8).
but under 2.6 it is guaranteed, see
O_DIRECT
The O_DIRECT flag may impose alignment restrictions on the length and address of userspace buffers and the file offset of I/Os. In Linux alignment restrictions vary by file system and kernel version and might be absent entirely. However there is currently no file system-independent interface for an application to discover these restrictions for a given file or file system. Some file systems provide their own interfaces for doing so, for example the XFS_IOC_DIOINFO operation in xfsctl(3).
Under Linux 2.4, transfer sizes, and the alignment of the user buffer and the file offset must all be multiples of the logical block size of the file system. Under Linux 2.6, alignment to 512-byte boundaries suffices.
O_DIRECT I/Os should never be run concurrently with the fork(2) system call, if the memory buffer is a private mapping (i.e., any mapping created with the mmap(2) MAP_PRIVATE flag; this includes memory allocated on the heap and statically allocated buffers). Any such I/Os, whether submitted via an asynchronous I/O interface or from another thread in the process, should be completed before fork(2) is called. Failure to do so can result in data corruption and undefined behavior in parent and child processes. This restriction does not apply when the memory buffer for the O_DIRECT I/Os was created using shmat(2) or mmap(2) with the MAP_SHARED flag. Nor does this restriction apply when the memory buffer has been advised as MADV_DONTFORK with madvise(2), ensuring that it will not be available to the child after fork(2).
The O_DIRECT flag was introduced in SGI IRIX, where it has alignment restrictions similar to those of Linux 2.4. IRIX has also a fcntl(2) call to query appropriate alignments, and sizes. FreeBSD 4.x introduced a flag of the same name, but without alignment restrictions.
O_DIRECT support was added under Linux in kernel version 2.4.10. Older Linux kernels simply ignore this flag. Some file systems may not implement the flag and open() will fail with EINVAL if it is used.
Applications should avoid mixing O_DIRECT and normal I/O to the same file, and especially to overlapping byte regions in the same file. Even when the file system correctly handles the coherency issues in this situation, overall I/O throughput is likely to be slower than using either mode alone. Likewise, applications should avoid mixing mmap(2) of files with direct I/O to the same files.
The behaviour of O_DIRECT with NFS will differ from local file systems. Older kernels, or kernels configured in certain ways, may not support this combination. The NFS protocol does not support passing the flag to the server, so O_DIRECT I/O will only bypass the page cache on the client; the server may still cache the I/O. The client asks the server to make the I/O synchronous to preserve the synchronous semantics of O_DIRECT. Some servers will perform poorly under these circumstances, especially if the I/O size is small. Some servers may also be configured to lie to clients about the I/O having reached stable storage; this will avoid the performance penalty at some risk to data integrity in the event of server power failure. The Linux NFS client places no alignment restrictions on O_DIRECT I/O.
In summary, O_DIRECT is a potentially powerful tool that should be used with caution. It is recommended that applications treat use of O_DIRECT as a performance option which is disabled by default.
"The thing that has always disturbed me about O_DIRECT is that the whole interface is just stupid, and was probably designed by a deranged monkey on some serious mind-controlling substances."---Linus
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get the set inside nested JsonNode using Jackson
I have a below JSON structure. which I need to parse using the Jackson library. I am building a web-service, which accept below JSON in a POST method's BODY.
{
"organization": {
"products": [
"foo",
"bar",
"baz"
]
},
"mission" : "to be the best in domain"
}
Till, now I was having simple JSON body, which wasn't having nested and JSON element, like in this case organization is another JSON node which contains a Set of products.
This JSON keys are not mandatory, And I am accepting/storing organization JSON in JsonNode. And doing below checks.
If organization is null.
If organization is not null and it has products key.
But after that I don't know how to fetch the set of boards from this JsonNode and store it in Java's HashSet.
My expected O/P should be to have a set of boards extracted from my organization JsonNode.
P.S. :- I think I have to use the ObjectMapper but couldn't find a direct way of getting the Set. Looks like I need to use some JsonParser with which I am not very familier.
A:
You can create DTOs(Data Transfer Objects) for your purpose. The nested objects could have the structure as below:
class Organization {
List<String> Products;
.....
}
class WebOrganizationRequest {
Organization organization;
String mission;
}
By creating objects in this way you are mapping your JSON objects to classes and Jackson will typecast the JSON as an instance of WebOrganizationRequest when you pass it in the controller with WebOrganizationRequest as the request body type.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Парсер на PHP
Нужно отпарсить большое количество xml-ек. Делаю через DOM. В результате получил ожидаемый результат, но лишь для первой xml. При этом в остальных xml количество полей (<Field>) отличается. Допустим в одной xml полей 10,в другой может быть 12-15.
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>XML-разборщик</title>
</head>
<body>
<?php
$doc = new DOMDocument();
$doc->load('7035_983300001.xml');
$nObject=$doc->getElementsByTagName('Object')->item(0);
$nField=$doc->getElementsByTagName('Field')->item(0);
$nField1=$doc->getElementsByTagName('Field')->item(1);
$nField2=$doc->getElementsByTagName('Field')->item(2);
$nField3=$doc->getElementsByTagName('Field')->item(3);
$nField4=$doc->getElementsByTagName('Field')->item(4);
$nField5=$doc->getElementsByTagName('Field')->item(5);
$nField6=$doc->getElementsByTagName('Field')->item(6);
//Object
if ($nObject->hasAttributes()) {
echo "Атрибуты тега 'Object':<br>";
foreach ($nObject->attributes as $attr) {
echo "<b>".$attr->nodeName.":</b> ".$attr->nodeValue."<br>";
}
}
$nName = $nObject->getElementsByTagName('Name')->item(0);
echo "<b>".$nName->nodeName.":</b><em>".$nName->nodeValue."</em>";
//end Object
echo "<br><br>";
//Field
if ($nField->hasAttributes()) {
echo "Атрибуты тега 'Records':<br>";
foreach ($nField->attributes as $attr) {
echo "<b>".$attr->nodeName.":</b> ".$attr->nodeValue."<br>";
}
}
$nName = $nField->getElementsByTagName('Name')->item(0);
echo "<b>".$nName->nodeName.":</b><em>".$nName->nodeValue."</em>";
echo "<br>";
$nValue = $nField->getElementsByTagName('Value')->item(0);
echo "<b>".$nValue->nodeName.":</b><em>".$nValue->nodeValue."</em>";
//end Field
echo "<br><br>";
//Field1
if ($nField1->hasAttributes()) {
foreach ($nField1->attributes as $attr) {
echo "<b>".$attr->nodeName.":</b> ".$attr->nodeValue."<br>";
}
}
$nName = $nField1->getElementsByTagName('Name')->item(0);
echo "<b>".$nName->nodeName.":</b><em>".$nName->nodeValue."</em>";
echo "<br>";
$nValue = $nField1->getElementsByTagName('Value')->item(0);
echo "<b>".$nValue->nodeName.":</b><em>".$nValue->nodeValue."</em>";
//end Field1
echo "<br><br>";
//Field2
if ($nField2->hasAttributes()) {
foreach ($nField2->attributes as $attr) {
echo "<b>".$attr->nodeName.":</b> ".$attr->nodeValue."<br>";
}
}
$nName = $nField2->getElementsByTagName('Name')->item(0);
echo "<b>".$nName->nodeName.":</b><em>".$nName->nodeValue."</em>";
echo "<br>";
$nValue = $nField2->getElementsByTagName('Value')->item(0);
echo "<b>".$nValue->nodeName.":</b><em>".$nValue->nodeValue."</em>";
//end Field2
echo "<br><br>";
//Field3
if ($nField3->hasAttributes()) {
foreach ($nField3->attributes as $attr) {
echo "<b>".$attr->nodeName.":</b> ".$attr->nodeValue."<br>";
}
}
$nName = $nField3->getElementsByTagName('Name')->item(0);
echo "<b>".$nName->nodeName.":</b><em>".$nName->nodeValue."</em>";
echo "<br>";
$nValue = $nField3->getElementsByTagName('Value')->item(0);
echo "<b>".$nValue->nodeName.":</b><em>".$nValue->nodeValue."</em>";
//end Field3
echo "<br><br>";
//Field4
if ($nField4->hasAttributes()) {
foreach ($nField4->attributes as $attr) {
echo "<b>".$attr->nodeName.":</b> ".$attr->nodeValue."<br>";
}
}
$nName = $nField4->getElementsByTagName('Name')->item(0);
echo "<b>".$nName->nodeName.":</b><em>".$nName->nodeValue."</em>";
echo "<br>";
$nValue = $nField4->getElementsByTagName('Value')->item(0);
echo "<b>".$nValue->nodeName.":</b><em>".$nValue->nodeValue."</em>";
//end Field4
echo "<br><br>";
//Field5
if ($nField5->hasAttributes()) {
foreach ($nField5->attributes as $attr) {
echo "<b>".$attr->nodeName.":</b> ".$attr->nodeValue."<br>";
}
}
$nName = $nField5->getElementsByTagName('Name')->item(0);
echo "<b>".$nName->nodeName.":</b><em>".$nName->nodeValue."</em>";
echo "<br>";
$nValue = $nField5->getElementsByTagName('Value')->item(0);
echo "<b>".$nValue->nodeName.":</b><em>".$nValue->nodeValue."</em>";
//end Field5
echo "<br><br>";
//Field6
if ($nField6->hasAttributes()) {
foreach ($nField6->attributes as $attr) {
echo "<b>".$attr->nodeName.":</b> ".$attr->nodeValue."<br>";
}
}
$nName = $nField6->getElementsByTagName('Name')->item(0);
echo "<b>".$nName->nodeName.":</b><em>".$nName->nodeValue."</em>";
echo "<br>";
$nValue = $nField6->getElementsByTagName('Value')->item(0);
echo "<b>".$nValue->nodeName.":</b><em>".$nValue->nodeValue."</em>";
//end Field6
?>
</body>
</html>
ВОПРОС: Как сделать так, чтобы с помощью этого кода можно было бы отпарсить все xml-ки независимо от количества полей в них? Чтобы парсил все существующие поля... Данный код парсит только конкретно указанное количество полей.
A:
<?php
$doc = new DOMDocument();
$doc->load('7035_983300001.xml');
$nObject=$doc->getElementsByTagName('Object')->item(0);
//как-то так
while($doc->getElementsByTagName('Field')->item($i))
{
$nName = $nField->getElementsByTagName('Name')->item($i);
echo "<b>".$nName->nodeName.":</b><em>".$nName->nodeValue."</em>";
echo "<br>";
$nValue = $nField->getElementsByTagName('Value')->item($i);
echo "<b>".$nValue->nodeName.":</b><em>".$nValue->nodeValue."</em>";
//end Field5
echo "<br><br>";
//Field6
if ($nField->hasAttributes()) {
foreach ($nField->attributes as $attr) {
echo "<b>".$attr->nodeName.":</b> ".$attr->nodeValue."<br>";
}
}
$i++;
}
Нафига каждый пункт руками прописывать?
ps в коде возможны ошибки, так nxj тут только логика твоего скрипта, дальше сам домозгуй.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add dynamically select aliases inside a query
Context: Given the fact that the following query :
$queryBuilder = $this->createQueryBuilder("cv")
->leftJoin('cv.user', 'u')
->where('cv.game = :game')
->setParameter('game', $game);
Will trigger 1+X distinct queries (one to get all the CV, then if u.user is used in the template, will trigger X other queries to fetch users).
If I want to optimize and to reduce those multiple unoptimized queries to 1 single query, i'll do so :
$queryBuilder = $this->createQueryBuilder("cv")
->select('cv, u')
->leftJoin('cv.user', 'u')
->where('cv.game = :game')
->setParameter('game', $game);
This Way, i'll be able to save X queries.
Now, my problem is in my repository, I have conditional joins and I want to chain the select aliases at different places in my code.
Like (simplified example) :
$queryBuilder = $this->createQueryBuilder("cv")
->select('cv, u')
->leftJoin('cv.user', 'u')
->where('cv.game = :game')
->setParameter('game', $game);
if ($myCondition === true) {
$queryBuilder->add('select', 'l');
$queryBuilder->join('cv.level', 'l');
}
But it seems that the add->('select') does not stack like an addWhere().
Are there any other solutions than using a custom solution like this :
$queryBuilder = $this->createQueryBuilder("cv")
->leftJoin('cv.user', 'u')
->where('cv.game = :game')
->setParameter('game', $game);
$aliases = array('cv', 'u');
if ($myCondition === true) {
$aliases[] = 'l';
$queryBuilder->add('select', 'l');
$queryBuilder->join('cv.level', 'l');
}
$queryBuilder->select(implode(',', $aliases);
Thanks.
A:
// Replace
$queryBuilder->add('select', 'l');
// With
$queryBuilder->addSelect('l');
And a bit of unsolicited advice. I know how much "un optimized queries" bother most people, including myself. However, consider doing some bench marks on large data sets. It's surprising how fast lazy loading is. Very little difference even with thousands of queries.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
$\omega$-limit set of a point $x \in X$
I would like to verify whether the following definition of the $\omega$-limit set of a point $x \in X$ is correct:
$$\omega(x) = \{ y \in M : \exists \text{ sequence }\{t_j\}, \text{ where } t_j \rightarrow \infty, \text { such that } \varphi_{t_j} (x) \rightarrow y \text{ as } j \rightarrow \infty \}.$$
The context is ODEs, so $M$ is the phase space.
A:
Given a point $x \in M$, its $\omega$-limit set with respect to a flow $\varphi_t$ is defined by
$$
\omega(x)=\bigcap_{y \in \gamma(x)} \overline {\gamma^+(y)},
$$
where
$$
\gamma(x)=\big\{\varphi_t(x): t \in \mathbb R\big\}\quad\text{and}\quad\gamma^+(y)=\big\{\varphi_t(y): t >0\big\}.
$$
When $M$ is for example a smooth manifold (or simply $\mathbb R^n$), one can show that
$$
\omega(x)=\big\{y\in M:\text{there exists a sequence $t_k \to +\infty$ such that $\varphi_{t_k}(x) \to y$ when $k \to \infty$}\big\}.
$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SOIL not linking correctly
I am linking SOIL in my library but when I compile I get these linker errors:
1>LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
1>libSOIL.lib(stb_image_aug.o) : error LNK2019: unresolved external symbol __alloca referenced in function _stbi_zlib_decode_noheader_buffer
1>libSOIL.lib(image_helper.o) : error LNK2019: unresolved external symbol _sqrtf referenced in function _RGBE_to_RGBdivA2
I did link libSOIL.lib in the addition dependencies.
A:
Fixed the error.
Although I'm using VC2010, I built the VC8 libraries. I then added SOIL.lib instead of libSOIL.lib. Errors went away.
A:
The unresolved symbol errors, error LNK2019, are from the symbols in libgcc.lib or another standard library implementation (see here for the Microsoft Options) not being linked to. alloca and sqrtf are both standard library functions.
If you aren't linking to a standard library, then link to one by adding it to your linker library path.
From the warning above warning LNK4098, it is more likely you are linking to a standard library but the linker doesn't know which on to load.
Recommend LINKER arguments to make this problem go away (tell the linker to choose a specific standard library) are /NODEFAULTLIB:"MSVCRT" /NODEFAULTLIB:"LIBCMT.
See the following links for additional information and resources
Linker Tools Warning LNK4098
Linking problems SOLVED
Default Libraries in Visual C++
Resolving LNK4098: defaultlib 'MSVCRT' conflicts with Stack Overflow Question
A:
I was having the same issue (using Visual Studio 2013 with vc120 toolset), I solved it downloading the SOIL library from the official site and instead of renaming libSOIL.a to SOIL.lib I ran the VC8 solution inside the official zip (that creates you the SOIL.lib)´then I copied it to my project and the problems went away.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Hover de um elemento e capturar outra tag
Preciso fazer um hover num parágrafo e trocar a cor da tag link, como consigo fazer isso?
p:hover a {
color:red;
}
<a href="#">Título</a>
<p>Passar o mouse troca a cor do link acima</p>
A:
No css não existe um meio de trocar a cor do item anterior apenas trocar a cor dos itens abaixo do dentro do elemento, sugiro que você troque a ordem dos elementos para que possa usar o marcador + do css.
O marcado + selecione o proximo elemento definido após ele como no exemplo abaixo:
a:hover + p {
color: red;
}
<a href="">hover me</a>
<p> change color<p>
Resumo: Ao ativar o hover no elemento a, altere a cor do elemento p que vier em seguida.
Todavia você pode fazer isso com javascript/jquery usando a função prev():
$('p:hover').prev('a').css('color', 'red');
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Alert an array value that results from an AJAX call
I am having some difficulty trying to alert a value which is the result of an ajax call. The code below is working to the extent that grid.onClick will alert the value of row, but for the life of me I cannot figure out how to alert the value of latitude and/or longitude.
function showGridSalesResult(){
var data = [];
var r_from = $('#min_val').val();
var r_to = $('#max_val').val();
var p_from = $('#from_year').val();
var p_to = $('#to_year').val();
var type = $('#sf3').val();
var municipality = $('#SaleCity').val();
$(document).ready(function(){
jqXHR = $.ajax({
url: sURL + "search/ajaxSearchResult",
type: "POST",
data: 'r_from='+r_from+'&r_to='+r_to+'&p_from='+p_from+'&p_to='+p_to+'&type='+type+'&up_limit='+up_limit+'&low_limit='+low_limit+'&municipality='+municipality,
dataType: 'json',
success: function(json){
$.each(json, function(i,row){
data[i] = {
address: row.Address,
municipality: row.Municipality,
geoencoded: row.geoencoded,
latitude: parseFloat(row.geolat),
longitude: parseFloat(row.geolong)
};
});
grid = new Slick.Grid("#myGridMap", data, columns, options);
grid.invalidate();
grid.render();
grid.resizeCanvas();
grid.onClick = function (e, row, cell){
alert(row); // THIS WORKS
alert(data[row].latitude); // THIS DOES NOT WORK
}
setMarkers(map, data);
}
});
});
}
Can someone please help me to figure out how I can alert the latitude and longitude values?
A:
Checking the documentation :
https://github.com/mleibman/SlickGrid/wiki/Slick.Grid#wiki-getCellFromEvent
you should use :
var cell = grid.getCellFromEvent(e);
var latitude = data[cell.row].latitude;
alert(latitude);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Oracle: using "as of" clause with table aliases?
I can run this flashback query with no problem:
select x from a as of timestamp sysdate;
But if I use a table alias I get an error.
select foo.x from a foo as of timestamp sysdate;
ORA-00933: SQL command not properly ended
How can I use "as of" with table aliases?
A:
The table alias follows the "as of" clause.
select x from a as of timestamp sysdate foo;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Calculate sunrise and sunset times for a given GPS coordinate within PostgreSQL
I want to classify timestamp data types in a PostgreSQL table with regards to whether they can be considered "at day" or "at night". In other words I want to be able to calculate sunrise and sunset times accurately, given a particular GPS position.
I know plpgsql and plpython.
A:
Take a look at these links:
Calulating sunrise and sunset in Python;
Skyfield project (new incarnation of PyEphem)
PyEphem project;
astral project;
A:
I know this is yonks old, but I thought I'd share since I found no quick solution.
This uses the Sun class (see below), which I constructed by following this link.
from Sun import Sun
coords = {'longitude' : 145, 'latitude' : -38 }
sun = Sun()
# Sunrise time UTC (decimal, 24 hour format)
print sun.getSunriseTime( coords )['decimal']
# Sunset time UTC (decimal, 24 hour format)
print sun.getSunsetTime( coords )['decimal']
It seems to be accurate to within a few minutes, at least where I live. For greater accuracy, the zenith param in the calcSunTime() method could use fine tuning. See the above link for more info.
# save this as Sun.py
import math
import datetime
class Sun:
def getSunriseTime( self, coords ):
return self.calcSunTime( coords, True )
def getSunsetTime( self, coords ):
return self.calcSunTime( coords, False )
def getCurrentUTC( self ):
now = datetime.datetime.now()
return [ now.day, now.month, now.year ]
def calcSunTime( self, coords, isRiseTime, zenith = 90.8 ):
# isRiseTime == False, returns sunsetTime
day, month, year = self.getCurrentUTC()
longitude = coords['longitude']
latitude = coords['latitude']
TO_RAD = math.pi/180
#1. first calculate the day of the year
N1 = math.floor(275 * month / 9)
N2 = math.floor((month + 9) / 12)
N3 = (1 + math.floor((year - 4 * math.floor(year / 4) + 2) / 3))
N = N1 - (N2 * N3) + day - 30
#2. convert the longitude to hour value and calculate an approximate time
lngHour = longitude / 15
if isRiseTime:
t = N + ((6 - lngHour) / 24)
else: #sunset
t = N + ((18 - lngHour) / 24)
#3. calculate the Sun's mean anomaly
M = (0.9856 * t) - 3.289
#4. calculate the Sun's true longitude
L = M + (1.916 * math.sin(TO_RAD*M)) + (0.020 * math.sin(TO_RAD * 2 * M)) + 282.634
L = self.forceRange( L, 360 ) #NOTE: L adjusted into the range [0,360)
#5a. calculate the Sun's right ascension
RA = (1/TO_RAD) * math.atan(0.91764 * math.tan(TO_RAD*L))
RA = self.forceRange( RA, 360 ) #NOTE: RA adjusted into the range [0,360)
#5b. right ascension value needs to be in the same quadrant as L
Lquadrant = (math.floor( L/90)) * 90
RAquadrant = (math.floor(RA/90)) * 90
RA = RA + (Lquadrant - RAquadrant)
#5c. right ascension value needs to be converted into hours
RA = RA / 15
#6. calculate the Sun's declination
sinDec = 0.39782 * math.sin(TO_RAD*L)
cosDec = math.cos(math.asin(sinDec))
#7a. calculate the Sun's local hour angle
cosH = (math.cos(TO_RAD*zenith) - (sinDec * math.sin(TO_RAD*latitude))) / (cosDec * math.cos(TO_RAD*latitude))
if cosH > 1:
return {'status': False, 'msg': 'the sun never rises on this location (on the specified date)'}
if cosH < -1:
return {'status': False, 'msg': 'the sun never sets on this location (on the specified date)'}
#7b. finish calculating H and convert into hours
if isRiseTime:
H = 360 - (1/TO_RAD) * math.acos(cosH)
else: #setting
H = (1/TO_RAD) * math.acos(cosH)
H = H / 15
#8. calculate local mean time of rising/setting
T = H + RA - (0.06571 * t) - 6.622
#9. adjust back to UTC
UT = T - lngHour
UT = self.forceRange( UT, 24) # UTC time in decimal format (e.g. 23.23)
#10. Return
hr = self.forceRange(int(UT), 24)
min = round((UT - int(UT))*60,0)
return {
'status': True,
'decimal': UT,
'hr': hr,
'min': min
}
def forceRange( self, v, max ):
# force v to be >= 0 and < max
if v < 0:
return v + max
elif v >= max:
return v - max
return v
A:
Use Astral (current version 1.6). The first example in the documentation shows the calculation of sunrise and sunset for a given location. A simpler example with custom latitude and longitude would be:
from datetime import date
import astral
loc = astral.Location(('Bern', 'Switzerland', 46.95, 7.47, 'Europe/Zurich', 510))
for event, time in loc.sun(date.today()).items():
print(event, 'at', time)
Gives:
noon at 2018-03-12 12:39:59+01:00
sunset at 2018-03-12 18:30:11+01:00
sunrise at 2018-03-12 06:49:47+01:00
dusk at 2018-03-12 20:11:39+01:00
dawn at 2018-03-12 05:08:18+01:00
Then you can maybe use this as a starting point for writing your own postgres (or postgis) functions using plpython instead of plr.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
String was not recognized as a valid DateTime with the format of "MM/dd/yyy hh:mm:ss tt"
I'm trying to convert a string into a DateTime in C#, but I'm getting this error:
System.FormatException: 'String was not recognized as a valid DateTime.'
The error is in the next line:
DateTime endTime = DateTime.ParseExact(endDate, "MM/dd/yyyy hh:mm:ss tt", null);
My endDate variable has the following info: "10/03/2017 06:52:48 AM"
What am I doing wrong?
A:
When you use null as an IFormatProvider, all DateTime parsing methods use CurrentCulture settings of your computer.
There are a few possibilities that you get exception. For example, your CurrentCulture might not have AM as it's AMDesignator property.
Instead of that, use a proper culture like InvariantCulture.
DateTime endTime = DateTime.ParseExact("10/03/2017 06:52:48 AM",
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to use mysql command in ssh?
I am trying to import a sql file using command line: mysql -u USERNAME -p DATABASENAME < FILENAME.sql,
but I am not familiar with mysql command line.
I use ssh to connect to server, after connected, it shows: [tamp@need ~]$, i input mysql, it shows: -bash: mysql: command not found,
so what is the problem? what should I do?
A:
It looks like mysql client is not installed on the server (or at least its binary is not in the right PATH); you should ask the system administrator to install it. If you're the administrator, well.. you should install it by your own, depending on which OS is installed on the host, you'd need a different procedure. For example, on debian based system you likely would run:
apt-get install mysql
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Azure Blob Trigger Not Firing
I am creating an Azure Blob Storage Trigger which is supposed to run every time a new file is dropped into the blob.
{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "myblob",
"type": "blobTrigger",
"direction": "in",
"path": "blob/{blobname}.{blobextension}",
"connection": "PROPER_CONNECTION_STRING_IS_HERE"
}
]
}
Once I upload this to my function app though, nothing happens when I drop a file in the blob. When I run the code/test portion of the function app, I am able to confirm that the code exists and runs. The problem is that it doesn't run automatically when I drop a file into the blob.
A:
From the information you gave, I think you might write the connection string directly after the connection.
If you develop in the cloud, you should write connection string in app setting.
Then you need to add the configured variable name to the back of the connection.
If your approach is the same as above, then I suggest you to check if the path in your Function.json is configured correctly.
Or as Akash mentioned in the comments, if you use a blob-only account, or if your application has specialized needs, you can use Event Grid trigger.
If it has not solved your problem, please give more information and I will try my best to help you solve this problem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
remove index.php from a specific url on Nginx server
I was struggling last few hours tying to find a decent way to remove index.php from a specific url that is being served over https. The reason why I want to remove the index.php is that when a url is served over https it works fine and no issues. However, when any person type at the end of the url index.php, the https can be changed to http so the SSL is useless on that url as encrypted information can't be made in that case.
This is the question I made before to get my SSL work, but that doesn't include the index.php being served over https My question about SSL for specific url
so now I have two options to go with and I don't know how to go with them. The first is to hide index.php for the url that is being served over https. And the 2nd is to made some modification to that code I used in my previous question so that https can be used even if index.php is typed in the url.
any help would be appreciated since I have no clue how to do anything here!!
Thanks
Update: it doesn't seem that the solution I provided works well when Nginx folder protection "auth_basic and auth_basic_user_file" are used.
A:
surprisingly I found one solution out of the options I was after. I got the 2nd option to work, not the first one since I had a lot of struggle to force hiding / removing index.php
All I had to do is to force SSL to server https for index.php, and the changes were simple.
The original code was:
server {
listen 80;
server_name example.com;
# normal http settings
location /secure_area/ {
return 301 https://$http_host$request_uri$is_args$query_string;
}
}
And the changes I got is this:
server {
listen 80;
server_name example.com;
# normal http settings
location ~* ^/secure_area/ {
return 301 https://$http_host$request_uri$is_args$query_string;
}
}
so the change was from location / to location ~* ^/
I hope it is going to be useful for anyone run into this issue.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to lowercase and replace spaces in bash?
In PHP:
$output = preg_replace("/[^a-z]/","_",strtolower($input));
How to do the same in a BASH script?
A:
Are you looking for Pattern substitution (${parameter/pattern/string}) and Case Modification (${parameter,,pattern})? If so, you will find more in man bash under the topic of Parameter Expansion.
$ a="FOO BAR BLUB"
$ tmp=${a// /_}
$ echo ${tmp,,}
foo_bar_blub
One thing to note though is that the BASH version uses patterns instead of regular expressions. For examplem, the pattern * is similar to the regular expression .*. And the pattern ? is ..
A:
Requires bash4 (tested with 4.3.48).
Assuming you never want a upper case character in the value of the variable output, I would propose the following:
typeset -l output
output=${input// /_}
typeset -l output: Defines the variable to be lowercase only. From man bash:
When the variable is assigned a value, all upper-case characters are converted to lower-case.
output=${input// /_}: replaces all spaces with a underscore.
BTW: There is also typeset -u variable to define it as "all upercase".
See man bash.
Update: While revisiting, I realized that my answer matches the question question title, but not the PHP code. In the PHP example, all characters that are not a-z are replaced with a underscore. So, if input contains a colon or a comma, those would also be replaced by underscore.
So here is code that also matches that:
typeset -l output
output=${input//[^a-z]/_}
Finally a quote from the answer of @micha-wiedenmann :
One thing to note though is that the BASH version uses patterns instead of regular expressions. For example, the pattern * is similar to the regular expression .*. And the pattern ? is ..
Check the man-page and search for "Pattern Matching".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Database design, relationship between user and order model
I am building a web application that has users and orders. I have a question about how to handle the relationship between the two.
An order belongs to a user. But here's the twist, a user can optionally choose to outsource an order to another user.
When an order is outsourced, the original user still remains the owner and only he can modify certain things like price, quantity etc on the order.
The user the order is outsourced to can view some of the order information and can update specific properties on the order like marking as fulfilled.
An outsourced order should show up on both users "orders index".
All the users are "equal" meaning on certain orders a user might be the owner and on others he might be fulfilling the order. A user can also fulfill his own orders.
It doesn't seem like a true many to many relationship as one of the users doesn't really own the order, he just has limited access to it.
What would be the simplest way to handle this order/users relationships? I would like to avoid using a complete permission system, is there a way to simply handle this with an "outsourced" table? How about having a user_id and outsourced_to field on the order table?
Thanks for your input!
If it's of any help, the application uses Laravel.
A:
It seems like your Orders table has two separate relationships with the Users table.
Orders have an owns/owned-by relationship to Users.
Users(1) -- owns -- (*)Orders
One User can own many Orders. One Order is owned by only one User
Then there is a completely separate outsourced-to relationship between Orders and Users.
Orders(*) -- outsourced-to -- (1)Users
(Here I assume that an Order can only be outsourced to one other User. A User may have many Orders outsourced to them.)
The best way to represent this is to have the Orders table have a 'owner' foreign key column into the Users table and another 'outsourced_to' foreign key column also to the Users table.
What columns of Orders the outsourced user can edit will be controlled by the code and not by the dB.
A separate outsourced table will be needed only if Orders can be outsourced to multiple Users at the same time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Polite Answers to "What else can I do for you? "
Suppose that I call a company's call center for help.
And near the end of the conversation, the staff asks a question like "what else can I do for you ?".
How can I give a polite answer to this sort of question if that was the only problem I had and it is now solved so I need no more help ?
Can I say "that's it for now" ?
A:
That's it for now.
That's all for now.
(You can even throw in a 'thank you' or a 'thanks', in order to save those phrases from disappearing. I was being sarcastic, but in truth you can include them.
Nothing else, thank you. (Here the 'thank you' is encouraged, else the 'nothing else' could seem too abrupt.)
Not now, thank you (very much). (Added after OP's comment.)
You can add 'Have a super day' or 'Have a great day' if you want. These specific terms may only be appropriate in American English, I'm not for certain.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
UserControl window won't close
I have a problem with one of my UserControl Windows.
I have a MainWindow and when a specific situatuin appears, another UserControl will open.
It has two Buttons which sends a command and after that it should be closed.
Right now it only opens the Window and sends the command, but doesn't close it afterwards.
I hope you can help me.
Code:
xaml:
C#:
Code to open the UserControl:
Window window = new Window();
window.Content = new MsgBox();
window.ShowDialog();
Button declaration:
public DelegateCommand OkBtn { get; set; }
Buttonfunction added to button:
OkBtn = new DelegateCommand<object>(OkBtnFkt);
In this Buttonfunction there should be something like: window.Close();
What I have tried:
Window.Close();
Sends the Window.close through the dispatcher to the UI
A:
I found an answer.
This post had the answer for me :
http://www.codeproject.com/Questions/91746/Close-WPF-user-control-inside-WPF-form-application
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scrollbars & resizable are not appearing in onclick="window.open"
I'm trying to open a new window using onclick="window.open" for some reason the scrollbars & resizable Are not working in IE11,and it's working fine in but do work fine Chrome.
<div class="editor-field editorholder" style="height: auto;">
<a href="@Url.Action("QuickView", "Home", new { id = @Model.UniqueKey })" class="btn-mvc" onclick="window.open(this.href,'targetWindow','toolbar=0','location=0','status=0','menubar=0,','scrollbars=yes','resizable=yes','width=100','height=100'); return false;">
<span class="glyphicon glyphicon-folder-open" aria-hidden="true"></span>
</a>
</div>
A:
Finally i found a solution:
onclick="window.open(this.href, 'popupwindow', 'width=1280 height=800 resizable scrollbars menubar=yes'); return false;"
thank you
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to build an old grails project
trying to build an old grails 2.0.0 project, it seems that it can't properly resolve all dependencies. I guess this is because it looks for them at svn.codehaus...
How to I have to update my dependencies to build the project again?
A:
I succeeded by upgrading my project to Grails 2.0.4 - silly me, I should have done this first...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I decipher what this code does based on the comments and naming?
I'm exploring a large Java library, and came across this code. I'm wondering what the @Override is for, along with the # symbol in the comments.
Is this an incomplete function? It looks like that since it returns false always.
/* (non-Javadoc)
* @see cascadas.supervision.components.SensorDataReady#evaluate(cascadas.ace.event.Event, cascadas.ace.session.Contract, cascadas.ace.session.Session, cascadas.ace.session.Session)
*/
@Override
public boolean evaluate(Event inputMessage, Contract contract,
Session executionSession, Session globalSession) {
// TODO Auto-generated method stub
return false;
}
I appreciate any tips.
A:
For what the pound (#) means, see the documentation for the @see Javadoc tag. It basically designates a package.class#member.
The (non-Javadoc) part designates that this method will inherit its Javadoc from the Javadoc of one of its superclasses. The method comment is basically directing you to SensorDataReady#evaluate for this method's Javadoc.
@Override is an annotation. See its Javadoc.
As for the method itself, it looks like Eclipse-generated code. Eclipse puts the TODO comment there to remind a developer to implement the overridden method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reading the 2nd entry of a .json
I am trying to read the density entry of a list of arrays within a .json file. He's a small portion of the file from the beginning:
["time_tag","density","speed","temperature"],["2019-04-14 18:20:00.000","4.88","317.9","11495"],["2019-04-14 18:21:00.000","4.89","318.4","11111"]
This is the code I have thus far:
with open('plasma.json', 'r') as myfile:
data = myfile.read()
obj = json.loads(data)
print(str(obj['density']))
It should print everything under the density column but I'm getting an error saying that the file can't be opened
A:
First, you json file is not correct. If you want to read it with a single call obj = json.load(data), the json file should be:
[["time_tag","density","speed","temperature"],["2019-04-14 18:20:00.000","4.88","317.9","11495"],["2019-04-14 18:21:00.000","4.89","318.4","11111"]]
Notice the extra square bracket, making it a single list of sublists.
This said, being obj a list of lists, there is no way print(str(obj['density'])) will work. You need to loop on the list to print what you want, or convert this to a dataframe before.
Looping directly
idx = obj[0].index('density') #get the index of the density entry
#from the first list in obj, the header
for row in obj[1:]: #looping on all sublists except the first one
print(row[idx]) #printing
Using a dataframe (pandas)
import pandas as pd
df = pd.DataFrame(obj[1:], columns=obj[0]) #converting to a dataframe, using
#first row as column header
print(df['density'])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
webkit Center equivalent for IE and edge
Is it correct to use display: block to center buttons on IE or should I look for a way using WebKit-center for other browsers?
@media screen and (max-width: 767px) {
.flex {
display:inline-block;
}
.flex_height {
display:inline-block;
}
.grid_8 {
background-repeat:no-repeat;
width:98%;
margin-left:1%;
margin-right:1%;
text-align:-webkit-center;
text-align:-moz-center;
margin-left:auto;
margin-right:auto;
}
}
<div class="grid_8">
<button type="button" class="button_home mobile_on">
*php code to generate text for a button here*
</button>
</div>
A:
An inline-block will wrap to the width of its content, so there's no point on centering a button inside an inline-block.
See:
.inline-block {
display: inline-block;
background-color: red;
}
<div class="inline-block">
<button>Button Label</button>
</div>
<p><em>As you can see, the button is already centered inside the red inline-block.</em></p>
Instead, you could use a regular block (not inline) element with text-align: center to center the button.
div {
background-color: red;
text-align: center;
}
<div>
<button>Button Label</button>
</div>
Or, if you really need this inline-block element, then you'll have to wrap it all in an outer wrapper:
.wrapper {
text-align: center;
}
.inline-block {
display: inline-block;
background-color: red;
}
<div class="wrapper">
<div class="inline-block">
<button>Button Label</button>
</div>
</div>
Besides that, you could also use some hacks as relative positioning, negative margins or transforms. But, I'd try to keep it simple.
.inline-block {
display: inline-block;
position: relative;
left: 50%;
}
#blue {
background-color: blue;
margin-left: -41px; /* Magic number. Not recommended! */
}
#red {
background-color: red;
transform: translateX(-50%); /* Much better, but still... */
}
<div>
<div id="blue" class="inline-block">
<button>Button Label</button>
</div>
</div>
<div>
<div id="red" class="inline-block">
<button>Button Label</button>
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a Javascript client for Ethereum, like Geth?
Ethereum's Github has ethereumjs-lib. It appears to be a collection of modules, but is it also a client like Geth? If so, how can one run this Javascript client?
A:
Yes, there are 3 official clients in Golang, C++ and Python. And there are 4 unofficial clients in Java, Haskell, JavaScript and most recently Rust.
To answer your question, the full node client implementation in JavaScript is the node-blockchain-server of the ethereumjs project.
The node-blockchain-server aims to provide a full Ethereum node implementation. It is in a pretty rough state at the moment, but at least can download the blockchain.
In oposite to other client implementations, for JavaScript you need to add a couple of libraries to get a fullstack client. Check out keythereum for managing keys and ethereumjs-tx for creating transactions with them.
The full list of libraries (23) in the ethereumjs project can be found on their homepage.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Jacobian of the solution from scipy.optimize is not equal to fjac of scipy.optimize.OptimizeResult
When finding the root of the function using scipy.optimize.root() with argument jac = True, the OptimizeResult.fjac returns the values of Jacobian which are incorrect with the Jacobian of the solution.
For example,
# objective function
def fun(x):
return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, 0.5 * (x[1] - x[0])**3 + x[1]]
# function returns Jacobain at x
def jac(x):
return np.array([[1 + 1.5 * (x[0] - x[1])**2, -1.5 * (x[0] - x[1])**2],
[-1.5 * (x[1] - x[0])**2,
1 + 1.5 * (x[1] - x[0])**2]])
from scipy import optimize
sol = optimize.root(fun, [0, 0], jac=jac)
After the solution is converged, sol.fjac is different from jac(sol.x)? I wouldn't able to understand what fjac denotes from OptimizeResult?
Any insights and corrections are much appreciated :)
A:
I checked using the debugger, and under the hood the default algorithm scipy.optimize.root uses is the _minpack.hybrj function. If you look at the documentation for fsolve (which also uses hybrj), it specifies:
fjac
the orthogonal matrix, q, produced by the QR factorization of the final approximate Jacobian matrix, stored column wise
It thus seems like scipy's documentation is incomplete.
Source: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.fsolve.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Force to show invalid-feedback in Bootstrap 4
Let's say I have HTML like this:
...
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="invalidCheck">
<label class="form-check-label" for="invalidCheck">
Agree to something
</label>
</div>
<div class="invalid-feedback">
I am outside of `form-check`!
</div>
</div>
...
I want to force to show the <div class="invalid-feedback">... without using JavaScript (want to use Bootstrap CSS only). And I know I can use CSS classes like was-validated or is-invalid, but invalid-feedback is outside of form-check. Is there an easy and simple way to show invalid-feedback by adding Bootstrap related CSS classes?
I found one solution:
<div class="invalid-feedback d-block">
Now I am visible!
</div>
But I feel like it's a hacky solution. Please advise!
A:
Use display classes to display it manually for example d-block
use it like so
<div class="valid-feedback d-block">
or
<div class="invalid-feedback d-block">
Find more in documentation
A:
There are better ways.
1)
Look into a was-validated class, that you can set on the form like so
<form action="..." class="was-validated" method="POST" novalidate>
When set on the form it displays validation feedback and also colorcodes the input field.
Just add it conditionally on your form, when validation failed on the server side.
2)
Or you can use some JavaScript to be in control of what is displayed. You can add this class dynamically
$('form').addClass('was-validated');
and you can also dynamically check if the form is valid like so
if ($('form').checkValidity()) {...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Style Two Sentences Differently Which Are Part of the same HTML tag
If i have a list item with no internal / child html, but which has two sentences of text, is there any way of styling the sentences individually without adding extra html tags?
For instance
Hello Everyone. How are you?
I appreciate I can add paragraph tags or spans around each line with JS, but wanted to make sure there is no way of doing this with CSS first.
It's dynamically created content in a client's Wordpress site so a CSS solution is preferable.
Thanks
Emily.
A:
The closest thing you can get with just CSS is ::first-line.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create basic animation
How can I create basic animation in Java?
Currently i am trying to implement a basic animation program using swing in Java.
But i am not getting whether my logic for program in correct or not.
My program implements Runnable, ActionListener interfaces and also extends JApplet.
I want to know that, is it necessary to differentiate start method of JApplet and Runnable?
And if yes then why..?
My program is basic balloon program, when I click on start button balloons start moving upward and comes to floor again. This will be continue till i press stop button.
Here is my code.
public class Balls extends JApplet implements Runnable{
private static final long serialVersionUID = 1L;
JPanel btnPanel=new JPanel();
static boolean flag1=true;
static boolean flag2=true;
static boolean flag3=false;
static int h;
static int temp=10;
Thread t=new Thread(this);
JButton start;
JButton stop;
public void init()
{
try
{
SwingUtilities.invokeAndWait(
new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Can't create GUI because of exception");
System.exit(0);
}
}
private void makeGUI() {
start=new JButton("start");
stop=new JButton("stop");
btnPanel.add(start);
btnPanel.add(stop);
add(btnPanel,BorderLayout.NORTH);
}
public void run()
{
while(true)
{
if(flag1)
{
repaint();
flag1=false;
}
else
{
try
{
wait();
flag3=true;
}
catch(InterruptedException e)
{
JOptionPane.showMessageDialog(null,"Error ocuured !!\n Exiting..");
System.exit(0);
}
}
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int h=Integer.parseInt(getParameter("height"));
if (flag1)
{
g.setColor(Color.RED);
g.fillOval(10,h,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,h,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h,60,40);
g.setColor(Color.pink);
g.fillOval(370,h,65,45);
flag1=false;
}
else
{
g.setColor(Color.RED);
g.fillOval(10,h-temp,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h-temp,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h-temp,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,355,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h-temp,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h-temp,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h-temp,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h-temp,60,40);
g.setColor(Color.pink);
g.fillOval(370,h-temp,65,45);
if(flag2 && temp<=400)
{
temp+=10;
if(temp==400)
{
flag2=false;
}
}
else if(!flag2)
{
temp-=10;
if(temp==10)
{
flag2=true;
}
}
else
{
}
}
}
public void start()
{
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t.start();
if(flag3)
{
notify();
}
}
});
stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
flag1=false;
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
repaint();
t=null;
}
}
});
}
}
A:
1) Use SwingTimer as recommended instead of your Runnable implementation.
2) Read about custom painting , and here
3) draw at the JPanel instead of on JFrame
I have changed your code, examine it. I think, that it does what you want.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Balls extends JApplet {
private static final long serialVersionUID = 1L;
JPanel btnPanel = new JPanel();
static boolean flag1 = true;
static boolean flag2 = true;
static boolean flag3 = false;
static int h;
static int temp = 10;
JButton start;
JButton stop;
private Timer timer;
public void init() {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
makeGUI();
}
});
}
private void makeGUI() {
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
});
start = new JButton("start");
stop = new JButton("stop");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.start();
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.stop();
}
});
btnPanel.add(start);
btnPanel.add(stop);
add(new MyPanel(), BorderLayout.CENTER);
add(btnPanel, BorderLayout.NORTH);
}
class MyPanel extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = Integer.parseInt(getParameter("height"));
if (flag1) {
g.setColor(Color.RED);
g.fillOval(10, h, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, h, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h, 65, 45);
flag1 = false;
} else {
g.setColor(Color.RED);
g.fillOval(10, h - temp, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h - temp, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h - temp, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, 355, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h - temp, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h - temp, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h - temp, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h - temp, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h - temp, 65, 45);
if (flag2 && temp <= 400) {
temp += 10;
if (temp == 400) {
flag2 = false;
}
} else if (!flag2) {
temp -= 10;
if (temp == 10) {
flag2 = true;
}
} else {
}
}
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does my heading not change using Core Location?
I'm using a WiFi iPad 1st gen with iOS 5.1.1
I have set up Core Location similar to this blog post:
http://blog.objectgraph.com/index.php/2012/01/10/how-to-create-a-compass-in-iphone/
In:
- (void)locationManager:(CLLocationManager*)manager
didUpdateHeading:(CLHeading*)heading
I log the true heading value:
NSLog(@"heading: %f", manager.heading.trueHeading);
The result is always "true heading: -1.000000" no matter which direction I point the iPad.
I've rotated the device on all 3 axis and enabled location services in settings.
Any ideas on why this doesn't work? Does heading reporting not work on an iPad 1st gen?
A:
Here is what helped in my case :
Select Location Services (under privacy settings)
Select System Services at the bottom of the list of apps (in the Location Services)
Turn your Compass Calibration ON
It seems that this way, the trueheading-values no longer turn out to be -1 !
(see picture below) !
|
{
"pile_set_name": "StackExchange"
}
|
Q:
integrate tus-node-server into feathersjs with express
I have an existing and properly working Feathers project is in the most recent feathers cli ("Buzzard") structure. Now I am trying add tus-node-server as upload server. As you can find in the link their instructions to set it up as express middleware are as follows:
const tus = require('tus-node-server');
const server = new tus.Server();
server.datastore = new tus.FileStore({
path: '/files'
});
var app = express();
const uploadApp = express();
uploadApp.all('*', server.handle.bind(server));
app.use('/uploads', uploadApp);
app.listen(port, host);
Following these instructions I tried adding this to my app.js file:
// tus node server
const tus = require('tus-node-server');
const tusServer = new tus.Server();
tusServer.datastore = new tus.FileStore({
path: '../uploads'
});
const uploadApp = express();
uploadApp.all('*', tusServer.handle.bind(tusServer));
app.use('/uploads', uploadApp);
For completeness I give the entire app.js file:
const path = require('path');
const favicon = require('serve-favicon');
const compress = require('compression');
const cors = require('cors');
const helmet = require('helmet');
const logger = require('winston');
const feathers = require('@feathersjs/feathers');
const configuration = require('@feathersjs/configuration');
const express = require('@feathersjs/express');
const socketio = require('@feathersjs/socketio');
const middleware = require('./middleware');
const services = require('./services');
const appHooks = require('./app.hooks');
const channels = require('./channels');
const sequelize = require('./sequelize');
const authentication = require('./authentication');
const app = express(feathers());
// Load app configuration
app.configure(configuration());
// Enable CORS, security, compression, favicon and body parsing
app.use(cors());
app.use(helmet());
app.use(compress());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(favicon(path.join(app.get('public'), 'favicon.ico')));
// Host the public folder
app.use('/', express.static(app.get('public')));
// Set up Plugins and providers
app.configure(express.rest());
app.configure(socketio({
wsEngine: 'uws',
timeout: 120000
}));
app.configure(sequelize);
// Configure other middleware (see `middleware/index.js`)
app.configure(middleware);
app.configure(authentication);
// Set up our services (see `services/index.js`)
app.configure(services);
// Set up event channels (see channels.js)
app.configure(channels);
// tus node server
const tus = require('tus-node-server');
const tusServer = new tus.Server();
tusServer.datastore = new tus.FileStore({
path: '../uploads'
});
const uploadApp = express();
uploadApp.all('*', tusServer.handle.bind(tusServer));
app.use('/uploads', uploadApp);
// Configure a middleware for 404s and the error handler
app.use(express.notFound());
app.use(express.errorHandler({ logger }));
app.hooks(appHooks);
module.exports = app;
I get this error:
# npm start
> [email protected] start /home/usr/api_server
> node src/
/home/usr/api_server/node_modules/@feathersjs/express/lib/index.js:11
throw new Error('@feathersjs/express requires a valid Feathers application instance');
^
Error: @feathersjs/express requires a valid Feathers application instance
at feathersExpress (/home/usr/api_server/node_modules/@feathersjs/express/lib/index.js:11:11)
at Object.<anonymous> (/home/usr/api_server/src/app.js:70:19)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Module.require (module.js:604:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/home/usr/api_server/src/index.js:3:13)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:617:3
How should this be setup? How to integrate this best into Feathers? From this I get the impression that Services & Hooks setup is preferable to a setup as middleware!?
A:
For reference, the solution from the GitHub issue is to use require('@feathersjs/express').original or require('express') to initialize the application:
const createExpressApp = require('express');
const uploadApp = createExpressApp();
uploadApp.all('*', tusServer.handle.bind(tusServer));
app.use('/uploads', uploadApp);
Or by accessing require('@feathersjs/express').original (the express module @feathersjs/express relies on) in your app like this:
const uploadApp = express.original();
uploadApp.all('*', tusServer.handle.bind(tusServer));
app.use('/uploads', uploadApp);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
LaTeX/MathJax support would be nice?
Several StackExchange sites have support for mathematical formulae using MathJax (LaTeX syntax).
Many Code-Golf challenges are mathematical in nature. Equations come up very often in discussions.
Therefore, I think it would be very useful to enable support for this on here as well?
Test to see if it is enabled yet: $ \LaTeX $
A:
Although I don't think MathJax is necessary for codegolf.SE (in contrast to math.SE), I think it would be neat to have it. So I've checked some questions / answers to see how MathJax would be used on this site:
Easy indexing / exponentiation by $A_i$ instead of A<sub>i</sub> (example)
Symbols for number sets (\mathbb{N} and \mathbb{R})
Nicer Big-O notation (\mathcal{O}(n^2) instead of O(n^2))
\cdot instead of * (example)
Nicer variables (It's easier to recognize $n$ as a variable than n)
A way around that can be used by single people who want to have this in their answer is including images like this answer does.
codegolf.SE could also generate images for formulas instead of loading MathJax. But this might cause other problems. Here is how it can be done (link).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Problem in getting months in ceiling or floor in SQL Server
In SQL Server, I am trying to get number of months between two dates.
I want the solution like this:
if output came to 4.2 months, then return 4 months
if output came to 4.5 months, then return 5 months
if output came to 4.9 months, then return 5 months
A:
If you are assuming days of month to be 30 days.
DATEDIFF return integer difference days.
So, you can try to use CAST(days as decimal) let the day number be float number, then do ROUND get your result.
select ROUND(CAST(DATEDIFF(dd,OPENDATE,MATURITYDATE)as decimal) /30,0 )
from T
sqlfiddle
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.