text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How do you axiomatize topology via nets?
Let $X$ be a set and let ${\mathcal N}$ be a collection of nets on $X.$
I've been told by several different people that ${\mathcal N}$ is the collection of convergent nets on $X$ with respect to some topology if and only if it satisfies some axioms. I've also been told these axioms are not very pretty.
Once or twice I've tried to figure out what these axioms might be but never came up with anything very satisfying. Of course one could just recode the usual axioms regarding open sets as statements about nets and then claim to have done the job. But, come on, that's nothing to be proud of.
Has anyone seen topology axiomatized this way? Does anyone remember the rules?
A:
Yes. This is given in Kelley's General Topology. (Kelley was one of the main mathematicians who developed the theory of nets so that it would be useful in topology generally rather than just certain applications in analysis.)
In the section "Convergence Classes" at the end of Chapter 2 of his book, Kelley lists the following axioms for convergent nets in a topological space $X$
a) If $S$ is a net such that $S_n = s$ for each $n$ [i.e., a constant net], then $S$ converges to $s$.
b) If $S$ converges to $s$, so does each subnet.
c) If $S$ does not converge to $s$, then there is a subnet of $S$, no subnet of which converges to $s$.
d) (Theorem on iterated limits): Let $D$ be a directed set. For each $m \in D$, let $E_m$ be a directed set, let $F$ be the product $D \times \prod_{m \in D} E_m$ and for $(m,f)$ in $F$ let $R(m,f) = (m,f(m))$. If $S(m,n)$ is an element of $X$ for each $m \in D$ and $n \in E_m$ and $\lim_m \lim_n S(m,n) = s$, then $S \circ R$ converges to $s$.
He has previously shown that in any topological space, convergence of nets satisfies a) through d). (The first three are easy; part d) is, I believe, an original result of his.) In this section he proves the converse: given a set $S$ and a set $\mathcal{C}$ of pairs (net,point) satisfying the four axioms above, there exists a unique topology on $S$ such that a net $N$ converges to $s \in X$ iff $(N,s) \in \mathcal{C}$.
I have always found property d) to be unappealing bordering on completely opaque, but that's a purely personal statement.
Addendum: I would be very interested to know if anyone has ever put this characterization to any useful purpose. A couple of years ago I decided to relearn general topology and write notes this time. The flower of my efforts was an essay on convergence in topological spaces that seems to cover all the bases (especially, comparing nets and filters) more solidly than in any text I have seen.
http://math.uga.edu/~pete/convergence.pdf
But "even" in these notes I didn't talk about either the theorem on iterated limits or (consequently) Kelley's theorem above: I honestly just couldn't internalize it without putting a lot more thought into it. But I've always felt/worried that there must be some insight and content there...
A:
(too long for a comment to Pete's answer)
Garrett Birkhoff was my Ph.D. advisor. Let me provide a few remarks
of a historical nature.
From a 25-year-old Garrett Birkhoff we have: Abstract 355, "A new
definition of limit" Bull. Amer. Math. Soc. 41 (1935) 636.
(Received September 5, 1935)
According to the report of the meeting (Bull. Amer. Math. Soc. 42
(1936) 3) the paper was delivered at the AMS meeting in New York on
October 26, 1935.
In the abstract we find what would nowadays be called convergence
of a filter base. (See also Definition 4 in Birkhoff's 1937 paper.)
Birkhoff remarked to me once that Bourbaki never acknowledged his
(Birkhoff's) priority.
It seems that some time after Birkhoff's talk, his father (G. D. Birkhoff)
remarked that it reminded him of a paper of Moore and Smith. So
young Garrett read Moore and Smith, and in the end adopted their
system for the subsequent paper, calling it "Moore-Smith convergence
in general topology". Since that Annals of Mathematics paper was
received April 27, 1936, one can only imagine young Garrett working
furiously for 6 months converting his previous filter-base material
into the Moore-Smith setting!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IndexOutOfBoundsException when adding to ArrayList
I'm gettgin java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3 exception when calling list.add(location, item); JavaDoc for the add method says that:
If the location is equal to the size of this List, the object is added
at the end.
I am totally confused since it also says that IndexOutOfBoundsException should be thrown when location < 0 || location > size() but even in the exception location and size are equal.
EDIT: I copy-paste full javadoc here, to see what makes me uncomfortable about this.
public abstract void add (int location, E object)
Added in API level 1
Inserts the specified object into this List at the specified location. The object is inserted before the current element at the specified location. If the location is equal to the size of this List, the object is added at the end. If the location is smaller than the size of this List, then all elements beyond the specified location are moved by one position towards the end of the List.
Parameters
location - the index at which to insert.
object - the object to add.
Throws
UnsupportedOperationException - if adding to this List is not supported.
ClassCastException - if the class of the object is inappropriate for this List.
IllegalArgumentException - if the object cannot be added to this List.
IndexOutOfBoundsException - if location < 0 || location > size()
EDIT #2: Requested actual code:
Date newDate = sourceDateFormatter.parse(newTime.getDate());
Date date;
int insert = -1;
do {
insert++;
date = sourceDateFormatter.parse(list.get(insert).getDate());
} while(date.compareTo(newDate) < 0);
list.add(insert, newTime);
A:
As I posted my method I've noticed the problem. For whatever reason my logcat points to the .add(index, object); method when I click on the link, but in reality it is the .get(index); that throws the exception, and that perfectly makes sense.
Made a bit of a tweaking, now this code works as intended:
Date newDate = sourceDateFormatter.parse(newTime.getDate());
Date date;
int insert = 0;
do {
date = sourceDateFormatter.parse(list.get(insert).getDate());
} while(date.compareTo(newDate) < 0 && ++insert < list.size());
list.add(insert, newTime);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does my GPO not apply?
I have a GPO hierarchy like this:
On the client machine, using gpresult -r, I see Global has applied fine. However, Disable Control.exe hasn't.
The settings I am trying to configure:
Scope and filtering:
There is no VMI filtering.
I have made sure of the following:
The link is enabled.
The user logged in on the client machine, is a member of OU_One.
I forced the update with gpupdate/force.
Why is Global being applied, but Disable Control.exe not?
A:
Based on your answers in the comments and chat, I think you're making this much more complex than it needs to be. You should not be using Loopback processing unless you have very specific reasons you need it.
To make the GPO block the Control Panel from all users in the Contractors group on any computer, you will want to:
Remove the Loopback part of the GPO
Remove Authenticated Users from the GPO security filtering
Remove the OU_One OU link
Add the GPO to whatever OU contains the actual users that are in the Contractors OU (note that the Security Filtering means you could apply this GPO at the Domain level, if the contractors are spread out too much)
Security Filtering only uses groups as a way to organize things (users, computers, etc). The things (users, computers, etc) must still be in an OU the GPO is linked to.
Loopback filtering is generally used for things like changing User policies on Terminal (Remote Desktop) servers, where you want to apply user settings but only on specific computers.
A:
Group Policy, despite it's name, does not apply to security groups. Group Policy applies to users and computers. You can filter Group Policy so that it only applies to specific users or computers by adding those users or computers to security groups and then using those security groups as a filter for your GPO.
Your problem is that the security group that this user is a member of is in your target OU, but the user account for this user is not in the target OU. You need to move the user account for this user into the target OU. You don't need, and should remove, the loopback policy processing setting from the GPO.
Additionally, you have Authenticated Users in the filter for the GPO, which means the GPO will apply to all users that are in the scope of management of the GPO (all users that are in your OU). You need to remove Authenticated Users from the security filter of the GPO. When you do, make sure to follow the instructions at the link below to make sure that your GPO is configured appropriately.
https://support.microsoft.com/en-us/help/3163622/ms16-072-security-update-for-group-policy-june-14--2016
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Missing Database Connection cakephp
I can't connect my cakephp application with mysql database. when I run it in localhost it works but when I move to a remote server it doesn't and it gives this error:
Missing Database Connection
I tried these solutions but it was vain in all cases:
Commented out : skip-networking.
edited the LocationMatch bloc in the htppd-xamp.conf yet still no
changes
Below is the code of the connection to the DB:
<?php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => '51.254.205.243',
'login' => 'login',
'password' => 'pwd',
'database' => 'db',
'prefix' => '',
'encoding' => 'utf-8'
);
}
If you really know what is going on and how to fix this issue, I would be grateful to learn from you.
Regards
A:
Change host to 127.0.0.1 / localhost
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why can't I link to spdlog library installed with conan
I have a simple CMake project and try to use the spdlog library (version 1.5.0) installed by conan.
But when building I get the following error:
undefined reference to `spdlog::get(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
I'm not sure if the problem comes from my setup, conan or the spdlog library.
Can anyone help me where to look?
My local setup:
Ubuntu 19.04,
QT Creator,
Clang 9 (in the IDE and conan),
conan 1.24.0
A:
Please start first with the "Getting Started" from the Conan docs https://docs.conan.io/en/latest/getting_started.html, make sure it works, and then, start from there to do your own examples.
In the getting started you will have an example of consuming existing libraries in ConanCenter. There is also a prominent "Important" notice that says:
If you are using GCC compiler >= 5.1, Conan will set the compiler.libcxx to the old ABI for backwards compatibility. You can change this with the following commands:
$ conan profile new default --detect # Generates default profile detecting GCC and sets old ABI
$ conan profile update settings.compiler.libcxx=libstdc++11 default # Sets libcxx to C++11 ABI
Basically the default auto-detected profile is using libstdc++, while your compiler is mostly likely using libstdc++11. You need to change the default profile with:
$ conan profile update settings.compiler.libcxx=libstdc++11 default
And then do "conan install" again, and build.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
reducing migration time of a large size postgresql database
We have a postgresql 9.4 DB server that handles 2 DBs, each ~800GB. No replication is implemented yet.
We reduced pg_dump time with using -j & -Fd options to about 2 hours.
The problem is, we need to separate DBs, so we setup a fresh new server with Postgresql 9.6, but pg_restore takes a very long time (~2 days). I tried parallel pg_restore using -j (4, 8, 16, although VM has a 4 core CPU and 16GB of RAM) and tuned some parameters in posotgresql.conf like shared_buffers, effective_cache_size, work_mem, maintenance_work_mem, wal_buffers and so forth, but they didn't have any significant effect on reducing time of restore.
Even, I tried to restore data and schema separately, but same results.
I think the problem is we have many tables with 15M records that all have index and indices will increase restore time but I'm not sure of that
We thought about replication, so we do not have any significant downtime (after sync is complete, we can stop old/master server and change replica/slave to acts as a master server), but as version of postgresql servers is not same, it didn't work out! Updating main server postgresql version to 9.6 and then start replication will take such a time!
Any advice and suggestions will be greatly appreciated!
A:
Bit of a FAQ.
pg_upgrade with --link (but understand that you can't easily go back);
Logical streaming replication with pglogical
Trigger-based logical replication with Londiste etc
Search for zero or low downtime PostgreSQL major version upgrade.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Showing a frame of buttons after clicking on action uiitembar of navigation controller
I want to create some thing like this:
When client click on the right button of the navigationcontorller (action button) a frame of buttons appear (like the image) and client select on of them. By selecting which one a new operation will done.
I'm a new on iphone and monotouch. is the frame a predefined component in iphone. if yes what is its name, and how i can use it. And if it is not a predefined component how i can create such a frame in my app?
A:
That is an UIActionSheet. There is a MonoTouch sample that demonstrates how to use it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Quantum entanglement continuous measurement
Is there a possibility (if not real than at least theoretical) that we could measure the spin of an electron continously over some (even very short) period of time, so that it does not change during the measurement?
I'm thinking maybe of something like observing it continuously...
Is it achievable?
A:
You can do a quantum zero type measurement if the spin of that particle has a well defined single particle spin state and you zeno it to stay in that state.
But this would require that it not have its spin entangled with any other particle (in order to have the well defined single particle spin state).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clean way to glob for files recursively in python
Given the following directory structure:
myDir
file1.c
file2.c
subDirA
file3.c
subDirB
file4.c
I want to find *.c files with glob, or another similarly efficient method (not using the os.walk method documented elsewhere).
The problem I encounter is that, given the path myDir I can't get all c files recursively in one line of code.
glob.glob('myDir/*.c', recursive=True)
only yields file1 and file2. And
glob.glob('myDir/**/*.c', recursive=True
only yields file3 and file4.
Is there a nice clean way to combine those two statements into one? It sure seems like there would be.
A:
Using pathlib:
from pathlib import Path
Path('/to/myDir').glob('**/*.c')
As for why glob didn't work for you:
glob.glob('myDir/**/*.c', recursive=True)
^
|___ you had a lower d here?
Make sure you're running it from within the parent of myDir and that your Python version is 3.5+.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change the status bar background color in SwiftUI?
I have a ZStack which has Color.orange set on it:
struct HomeView: View {
init() {
UITabBar.appearance().barTintColor = UIColor.orange
}
var body: some View {
ZStack {
Color.orange
TabView {
Settings()
.tabItem {
Image(systemName: "gear")
Text("Settings")
}
MapKitView()
.tabItem {
Image(systemName: "location.circle.fill")
Text("Home")
}
ProfileView()
.tabItem {
Image(systemName: "person")
Text("Profile")
}
}
.font(.headline)
}
}
}
and in this ZStack I have a TabView with child views that all have orange ZStacks. However these child views, including Settings() and MapKitView() shown below, do not have an orange status bar.
Settings()
struct Settings: View {
var body: some View {
ZStack {
Color.orange
VStack {
NavigationView {
...
}
}
}
}
}
MapKitView()
struct MapKitView: UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
return mapView
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MapKitView>) {
}
}
How can I make the status bar orange across all my views?
A:
ZStack {
...
}
.edgesIgnoringSafeArea(.vertical) // or .top
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Possible to get query parameters of the
As an example, I have the following html:
<body>
<script src="code.js?q=xyz"></script>
</body>
I want to be able to read the q=xyz query parameter from within code.js. I tried:
console.log(window.location.href)
But it gives me the html document's URL, not code.js's URL (I could then parse the URL for the query parameters).
Is there any way to get an imported JavaScript file's query parameters from within that JavaScript? I know I could read the query parameters on a server and then send back JavaScript that has the query parameters embedded, but I don't want that. I want to be able to put JavaScript files on CDNs that can be configured via query parameters.
A:
You could use document.currentScript.src to access the <script>'s src-attribute and then extract the query parameter. For older browsers (such as IE 11) access the src-attribute by:
var scripts = document.getElementsByTagName('script');
var src = scripts[scripts.length - 1].src;
This will return the src-attribute of the last executed script.
In some cases the last executed script is not the current script (for example, if a script manipulates other <script>-elements), and therefore it's a bit unreliable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Slight rendering bug in Chrome (Linux) - View count and title overlap
Definitely not a huge issue, but a little bit jarring on the latest Chrome release under Ubuntu Linux 9.10. Yes, technically still Beta (by Google's standards) but the bug appears to be in WebKit, which is definitely not.
If there's 3 or more digits in the view count, it overflows its box and hits the title of the question in some cases.
This still happens if I zoom the whole page in/out so it's not like I just have some non-standard font sizes set.
Hope this helps.
A:
100% font width related.
Here's a screenshot of your Linux results (bottom) with Firefox/Windows (top):
As you can see -- the font being used by the browser is absurdly wide.
The stylesheet defines:
Trebuchet MS, Helvetica, sans-serif
This has come up before, but it's really hard to "fix" without changing the font, as the Windows and OSX fonts the browser chooses are fairly similar (if not identical) in width.
EDIT: based on recommendations here I changed it to:
Trebuchet MS, Liberation Sans, DejaVu Sans, sans-serif
A:
Despite widespread belief to the contrary, a font stack of Arial, Helvetica, sans-serif will not fall back to the default sans serif font on a typical linux box (Ubuntu included). Instead, the Helvetica font gets hijacked and replaced with something the distro thinks is reasonably similar. To find out what font that is, just run 'fc-match helvetica' from the command line. On default configured Ubuntu systems, this will generally be Nimbus Sans L, which does not match Helvetica very well, imho.
So you can either remove Helvetica from your stack (not usually a good option) or you can add an explicit linux replacement, such as Liberation Sans or DejaVu Sans. (Liberation is the better choice metrically and gaining popularity but not as common as DejaVu or Bitstream Vera).
A:
The problem is with the fonts you're specifying in your CSS here and their order (Trebuchet MS, Helvetica, sans-serif).
The browser will go through the fonts in this list and use the first one it knows about. On Windows, Mac OS X, and some Linux installs (those with the Microsoft fonts installed) this will be Trebuchet.
For some odd configurations where Trebuchet is not installed on the machine but Helvetica is, you will get Helvetica. This might happen on some very old, default installs of Mac OS X that did not include Trebuchet (I don't have a box up to check).
On Most default Linux installs, the browser will end up on "sans-serif", which is whatever has been configured as the default sans font in the browser. Since different fonts have different weights for a given point size, this could end up being nearly any width.
There really are two solutions to this. One, change the design to not assume a fixed width for a piece of text -- this would probably require some significant layout changes. The other, specify a fonts list that has fonts of equal or similar weights, in order of preference, where each platform you want to support is guaranteed to have at least one of these fonts installed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
current lat long
I want to display current location weather in my php website. Is it possible to fetch the current location(latitude,longitude) of a client computer.
Or what else we can do with weather ?
Thanks
A:
If you are using one of the newer browser versions that utilises the geolocation api you can use javascript to find the latitude and longitude as follows:
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
}, function() {
alert("Geolocation Failed");
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
r - apply function to each row of a data.table
I'm looking to use data.table to improve speed for a given function, but I'm not sure I'm implementing it the correct way:
Data
Given two data.tables (dt and dt_lookup)
library(data.table)
set.seed(1234)
t <- seq(1,100); l <- letters; la <- letters[1:13]; lb <- letters[14:26]
n <- 10000
dt <- data.table(id=seq(1:n),
thisTime=sample(t, n, replace=TRUE),
thisLocation=sample(la,n,replace=TRUE),
finalLocation=sample(lb,n,replace=TRUE))
setkey(dt, thisLocation)
set.seed(4321)
dt_lookup <- data.table(lkpId = paste0("l-",seq(1,1000)),
lkpTime=sample(t, 10000, replace=TRUE),
lkpLocation=sample(l, 10000, replace=TRUE))
## NOTE: lkpId is purposly recycled
setkey(dt_lookup, lkpLocation)
I have a function that finds the lkpId that contains both thisLocation and finalLocation, and has the 'nearest' lkpTime (i.e. the minimum non-negative value of thisTime - lkpTime)
Function
## function to get the 'next' lkpId (i.e. the lkpId with both thisLocation and finalLocation,
## with the minimum non-negative time between thisTime and dt_lookup$lkpTime)
getId <- function(thisTime, thisLocation, finalLocation){
## filter lookup based on thisLocation and finalLocation,
## and only return values where the lkpId has both 'this' and 'final' locations
tempThis <- unique(dt_lookup[lkpLocation == thisLocation,lkpId])
tempFinal <- unique(dt_lookup[lkpLocation == finalLocation,lkpId])
availServices <- tempThis[tempThis %in% tempFinal]
tempThisFinal <- dt_lookup[lkpId %in% availServices & lkpLocation==thisLocation, .(lkpId, lkpTime)]
## calcualte time difference between 'thisTime' and 'lkpTime' (from thisLocation)
temp2 <- thisTime - tempThisFinal$lkpTime
## take the lkpId with the minimum non-negative difference
selectedId <- tempThisFinal[min(which(temp2==min(temp2[temp2>0]))),lkpId]
selectedId
}
Attempts at a solution
I need to get the lkpId for each row of dt. Therefore, my initial instinct was to use an *apply function, but it was taking too long (for me) when n/nrow > 1,000,000. So I've tried to implement a data.table solution to see if it's faster:
selectedId <- dt[,.(lkpId = getId(thisTime, thisLocation, finalLocation)),by=id]
However, I'm fairly new to data.table, and this method doesn't appear to give any performance gains over an *apply solution:
lkpIds <- apply(dt, 1, function(x){
thisLocation <- as.character(x[["thisLocation"]])
finalLocation <- as.character(x[["finalLocation"]])
thisTime <- as.numeric(x[["thisTime"]])
myId <- getId(thisTime, thisLocation, finalLocation)
})
both taking ~30 seconds for n = 10,000.
Question
Is there a better way of using data.table to apply the getId function over each row of dt ?
Update 12/08/2015
Thanks to the pointer from @eddi I've redesigned my whole algorithm and am making use of rolling joins (a good introduction), thus making proper use of data.table. I'll write up an answer later.
A:
Having spent the time since asking this question looking into what data.table has to offer, researching data.table joins thanks to @eddi's pointer (for example Rolling join on data.table, and inner join with inequality), I've come up with a solution.
One of the tricky parts was moving away from the thought of 'apply a function to each row', and redesigning the solution to use joins.
And, there will no doubt be better ways of programming this, but here's my attempt.
## want to find a lkpId for each id, that has the minimum difference between 'thisTime' and 'lkpTime'
## and where the lkpId contains both 'thisLocation' and 'finalLocation'
## find all lookup id's where 'thisLocation' matches 'lookupLocation'
## and where thisTime - lkpTime > 0
setkey(dt, thisLocation)
setkey(dt_lookup, lkpLocation)
dt_this <- dt[dt_lookup, {
idx = thisTime - i.lkpTime > 0
.(id = id[idx],
lkpId = i.lkpId,
thisTime = thisTime[idx],
lkpTime = i.lkpTime)
},
by=.EACHI]
## remove NAs
dt_this <- dt_this[complete.cases(dt_this)]
## find all matching 'finalLocation' and 'lookupLocaiton'
setkey(dt, finalLocation)
## inner join (and only return the id columns)
dt_final <- dt[dt_lookup, nomatch=0, allow.cartesian=TRUE][,.(id, lkpId)]
## join dt_this to dt_final (as lkpId must have both 'thisLocation' and 'finalLocation')
setkey(dt_this, id, lkpId)
setkey(dt_final, id, lkpId)
dt_join <- dt_this[dt_final, nomatch=0]
## take the combination with the minimum difference between 'thisTime' and 'lkpTime'
dt_join[,timeDiff := thisTime - lkpTime]
dt_join <- dt_join[ dt_join[order(timeDiff), .I[1], by=id]$V1]
## equivalent dplyr code
# library(dplyr)
# dt_this <- dt_this %>%
# group_by(id) %>%
# arrange(timeDiff) %>%
# slice(1) %>%
# ungroup
|
{
"pile_set_name": "StackExchange"
}
|
Q:
.htaccess/mod_rewrite: running Angular app in sub-folder?
I've
a light index.php which provides simple pages and
a more complex/heavy Angular 8.0 app, stored in the sub-folder /app.
Example URLs:
/ ......................... works: index.php, loads home page
/my-blog-post.html ........ works: index.php, loads a blog post
/any-page.htm ............. works: index.php, loads a page
/app ...................... works: home page of the Angular app
/app/login ................ DOES "NOT" WORK: sub-page of the Angular app
Folder structure:
app/dist/app ........................................... Angular App (built files)
app/dist/app/3rdpartylicenses.txt
app/dist/app/4-es5.86e9c53554535b1b46a8.js
app/dist/app/4-es2015.bb174fcd0205a5f23647.js
app/dist/app/5-es5.b8f3fede0599cda91cf0.js
app/dist/app/5-es2015.f4890df5957b350d78ca.js
app/dist/app/favicon.ico
app/dist/app/index.html
app/dist/app/main-es5.8059496aa1855103a2ad.js
app/dist/app/main-es2015.0629f594e2c4c056133c.js
app/dist/app/polyfills-es5.943113ac054b16d954ae.js
app/dist/app/polyfills-es2015.e954256595c973372414.js
app/dist/app/runtime-es5.f2faa6ae2b23db85cc8d.js
app/dist/app/runtime-es2015.f40f45bfff52b2130730.js
app/dist/app/styles.3ff695c00d717f2d2a11.css
.htaccess ..............................................
index.php ..............................................
app/dist/app/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>App</title>
<base href="/app/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles.3ff695c00d717f2d2a11.css"></head>
<body>
<app-root></app-root>
<script src="runtime-es2015.f40f45bfff52b2130730.js" type="module"></script><script src="polyfills-es2015.e954256595c973372414.js" type="module"></script><script src="runtime-es5.f2faa6ae2b23db85cc8d.js" nomodule></script><script src="polyfills-es5.943113ac054b16d954ae.js" nomodule></script><script src="main-es2015.0629f594e2c4c056133c.js" type="module"></script><script src="main-es5.8059496aa1855103a2ad.js" nomodule></script></body>
</html>
Problem:
It's possible to reach /app and afterwards app/login by clicking a link within the Angular App. It is not possible to reach the URL directly via the browsers address bar:
app/login does not work when called directly (error below)
app/ -> click Login-link -> app/login works
.htaccess
RewriteEngine on
RewriteBase /
# Page
RewriteRule ^(.*).html$ /index.php?module=page&slug=$1
# Blog
RewriteRule ^(.*).htm$ /index.php?module=blog&slug=$1
# Angular app
RewriteRule ^app/$ app/dist/app/index.html [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/(.*) app/dist/app/$1 [L]
# Remove www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
# Force https
RewriteCond %{HTTPS} on
Error
# /var/log/apache2/myproject_error.log
AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
I think the bug is somewhere in the routing of Angular app part of the .htaccess. index.php and the Angular app themselves work perfectly fine.
Edit
After setting imports: [RouterModule.forRoot(routes, {useHash: true})] it works with #, but I'd like to avoid the HashLocationStrategy.
Any idea?
Thanks in advance!
A:
Have it this way:
RewriteEngine on
RewriteBase /
# remove www and turn on https in same rule
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]
# Page
RewriteRule ^([^./]+)\.html$ index.php?module=page&slug=$1 [L,QSA,NC]
# Blog
RewriteRule ^([^./]+)\.htm$ index.php?module=blog&slug=$1 [L,QSA,NC]
# Angular app
RewriteRule ^app/$ app/dist/app/index.html [L,NC]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/(.+)$ app/dist/app/$1 [L,NC]
Make sure to test it after clearing your browser cache or test in a new browser.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding custom fields to a subscription response using the faye ruby server
I'm trying to write a proof-of-concept chat application using faye (the chat example which is included in the distribution).
In my proof-of-concept I want to send a full history of a chat channel when a client subscribes to a channel. My current idea was to implement this using a custom field in the subscription response message.
After checking the bayeux protocol definition it seems, that a 'ext' field is allowed in a subscription response message.
But I was unable to add anything to this ext field using a server extension.
class ServerLog
def incoming(message, callback)
puts " msg: #{message}"
unless message['channel'] == '/meta/subscribe'
return callback.call(message)
end
# the following line changes absolutely nothing
message['ext'] = 'foo'
callback.call(message)
end
end
App.add_extension(ServerLog.new)
Although the setting of the ext field doesn't crash the server, it has absolutely no effect on the subscription response message. I've even checked using Wireshark (just to be sure the js client doesn't ignore some fields).
A:
My mistake was using the 'incoming' method, and not 'outgoing'.
class ServerLog
def outgoing(message, callback)
puts " out: #{message}#"
unless message['channel'] == '/meta/subscribe'
return callback.call(message)
end
if message['subscription'] == '/chat/specialchannel'
message['ext'] ||= {}
message['ext']['specialattribute'] = 'special value'
end
callback.call(message)
end
end
App.add_extension(ServerLog.new)
This example will add the specialattribute to the ext field of the subscription response message (if the channel is /chat/specialchannel).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to display a loading bar for images with jQuery?
I have images on my page.
I want to show a loading bar on my page, showing the progress of the downloaded images.
How can I do this?
A:
I have written a jQuery plugin to register callbacks for images loading.
You would use it like so...
var loading = $('<div id="loading" />').appendTo('body');
$('body').waitForImages(function() {
loading.remove();
}, function(loaded, all) {
loading.html(((loaded / all) * 100) + '% loaded');
});
jsFiddle.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I cannot calculate a division in my SQL code
The following code works without problems:
select donem, mekankodu, count(yayin_kodu) yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) yys
from
( select donem,
bayi_adi,
bayi_kodu,
x.mekankodu,
mekan_adi,
mekan_tipi,
yayin_kodu,
yayin_adi,
sum(x.b2b_dagitim + x.b2b_transfer) sevk,
sum(x.b2b_iade) iade,
sum(x.b2b_dagitim + x.b2b_transfer - x.b2b_iade) satis
from mps_view2 x
where x.donem = '200910'
and x.yayin_kodu in (93,95,98,99,103,174,307,309,311,489,491,495,533,534,538,605,641,642,650,2539,
2697,4560,5049,5772,5950,5980,7318,7440,8086,8524,11161,12707,12708,12709,14376,
15107,15309,15633)
and x.mekankodu in (31851,38569,7123,7403,7481)
group by donem, bayi_adi, bayi_kodu, mekankodu, mekan_adi, mekan_tipi, yayin_kodu, yayin_adi
order by donem, bayi_kodu, mekan_adi, yayin_adi
)
group by donem, mekankodu
When I want to include yc/yss in my result table, I arrange the SELECT part as follows:
select donem, mekankodu, count(yayin_kodu) yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) yys,
yc/yys yo
but it gives
ORA-00904 Error: YYS: Invalid
identifier.
What should I do?
A:
Use a with statement:
with subquery_name as
(
select
donem,
mekankodu,
count(yayin_kodu) as yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) as yys
from
...
)
select
donem,
mekankodu,
yc,
yys,
yc/yys as yo
from
subquery_name
This is a very useful feature of PL/SQL. You're trying to access a generated column within the same query, which is not possible. A with statement will allow you to calculate a new column based on another calculated column as you are doing here.
A:
You cannot refer to other columns in the same select.
Use a sub-select:
select donem, mekankodu, yc, yys, yc/yys yo
from
(
select donem, mekankodu, count(yayin_kodu) yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) yys,
yc/yys yo
from ...
) Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
regular express : how to exclude multiple character groups?
I have a set of urls :
/products
/categories
/customers
Now say a customers is named john, and I want to help john to reach his own account page with a shorter url:
before : /customers/john
after : /john
(suppose customer names are unique)
I'm trying to figure out a proper regex dispatcher so all customers can have this feature :
/marry
/james
/tony-the-red-beard
here is what I got now(in PHP) :
'/^\/([^(products|categories|admin)].+)$/' => /customers/$1
This doesn't seem to work. Anybody can help me?
A:
What you need here is a negative lookahead assertion. What you want to say is "I want to match any string of characters, except for these particular strings." An assertion in a regex can match against a string, but it doesn't consume any characters, allowing those character to be matched by the rest of your regex. You can specify a negative assertion by wrapping a pattern in (?! and ).
'/^\/(?!products|categories|admin)(.+)$/'
Note that you might want the following instead, if you don't allow customers names to include slashes:
'/^\/(?!products|categories|admin)([^/]+)$/'
A:
This is entirely the wrong way to go about solving the problem, but it is possible to express fixed negative lookaheads without using negative lookaheads. Extra spacing for clarity:
^ (
( $ | [^/] |
/ ( $ | [^pc] |
p ( $ | [^r] |
r ( $ | [^o] |
o ( $ | [^d] |
d ( $ | [^u] |
u ( $ | [^c] |
c ( $ | [^t] |
t ( $ | [^s] ))))))) |
c ( $ | [^au] |
a ( $ | [^t] |
t ( $ | [^e] |
e ( $ | [^g] |
g ( $ | [^o] |
o ( $ | [^r] |
r ( $ | [^i] |
i ( $ | [^e] |
e ( $ | [^s] )))))))) |
u ( $ | [^s] |
s ( $ | [^t] |
t ( $ | [^o] |
o ( $ | [^m] |
m ( $ | [^e] |
e ( $ | [^r] |
r ( $ | [^s] ))))))))))
) .* ) $
|
{
"pile_set_name": "StackExchange"
}
|
Q:
maximizing inner product
Given two lists $L,L'\subseteq\mathbb{R}^d$ of $n$ vectors each,
how fast can we compute for all $p\in L$ the vector of $L'$ that maximizes the inner product with $p$, i.e., $\arg\max_{p'\in L'} \langle p, p'\rangle$.
I am only interested in $d=3$ (and possibly $d=4$).
A:
For three-dimensional vectors, construct the three-dimensional convex hull of the vectors in $L'$ in time $O(n\log n)$. The maximizer for a vector $v$ in $L$ is the point of the convex hull that is most extreme in the direction of $v$, and extreme-vertex queries may be answered in logarithmic time by using a Dobkin-Kirkpatrick hierarchy for the convex hull. For this part see e.g. O'Rourke's Computational Geometry in C, pp. 272ff. So the 3d problem can be solved in total time $O(n\log n)$.
For 4-dimensional vectors, the same thing would work, but you don't want to construct the convex hull because it's too expensive. Instead, it is possible to process a set of $n$ points in time and space $\tilde O(m)$ (for any $m$ between $n$ and $n^2$) so that you can answer extreme-point queries in time $\tilde O(n/\sqrt{m})$; see Corollary 8(iii) of Agarwal and Erickson's range query survey. Choosing $m=n^{4/3}$ gives total time $\tilde O(n^{4/3})$ to set up a data structure for $L'$ and query all vectors in $L$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Powershell : Query Document Exclude Document Set
I have a Document Library contains multiple Document Sets, each of the Document Sets contains Files.
Document Library ----> Document Set ----> Files
My objective is to query all File Name only across Document Sets.
here are my code:
function Get-SPItem{
$web = Get-SPWeb $webUrl
$documentsLib = $web.Lists[$libraryName]
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$query = New-Object Microsoft.SharePoint.SPQuery
#$viewFields = "<FieldRef Name='Title'/><FieldRef Name='Name'/>"
$query.Query = $camlQuery
$query.ViewAttributes = "Scope='Recursive'"
$queryResults = $documentsLib.GetItems($query)
foreach($item in $queryResults){
$filename = [io.path]::GetFileNameWithoutExtension($item.Name)
Write-Host $filename
}
}
Get-SPItem
The code above return both Document Set Name and Files Name, which going to be extra row and how can I eliminate Document Set Name?
Thank you in advanced :)
A:
Use the <BeginsWith> element in your query to select items that inherit from Document (0x0101...). Document Sets inherit from folder (0x0120...)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get confidence bands of parameters from a fitting procedure?
I have done fitting of data points with a given model that has two parameters (A and B), using NonlinearModelFit. The result of the fit is the maximum of the likelihood function, aka the best fit, and the best values for parameters A and B, say (A0, B0). On the A-B plot this would be a single point. There is also a standard deviation given for both parameters separately σA and σB. However, the likelihood function should also give a region on A-B diagram, therefore possible values for A and B that give a good fit - the one that is under a certain confidence level, like 68%. This region is not exactly {A-σA, A+σA} × {B-σB, B+σB}. Instead, {A-σA, A+σA} is probably projection of this region on A-axis.
How to get the region of A-B dependence with a specified confidence level (.68, .95, .99) coming from the fit?
A:
The output of the "ParameterConfidenceRegion" can in fact be directly fed into Graphics[], like so:
data = {{0., 1.}, {1., 0.}, {3., 2.}, {5., 4.}, {6., 4.}, {7., 5.}};
nlm = NonlinearModelFit[data, Log[a + b x^2], {a, b}, x];
Graphics[nlm["ParameterConfidenceRegion", ConfidenceLevel -> 0.95], Frame -> True]
You can grab confidence ellipses for multiple confidence levels:
ells = Table[nlm["ParameterConfidenceRegion", ConfidenceLevel -> c], {c, {.68, .95, .99}}];
Graphics[{{Directive[AbsolutePointSize[4], Red],
Point[{a, b} /. nlm["BestFitParameters"]]},
Dashed, MapThread[Tooltip[{#1, #2}, StringForm["α = `1`", InputForm[#3]]] &,
{ColorData[1] /@ Range[3], ells, {.68, .95, .99}}]}, Frame -> True]
(You won't see it in the picture here, but if you execute the last graphic in Mathematica, each confidence ellipse will have an associated tooltip corresponding to its confidence level.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using a SimpleCursorAdapter + Sqlite doesn't seem to work on a ListActivity
I've just started out building a very simple score screen for my app but nothing seems to be happening and I can't figure out why.
The ListActivity:
public class HighScoresActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.high_scores);
ScoresDatabase db = new ScoresDatabase(this);
Cursor data = db.getHighScores();
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, data, new String[] { "level" }, new int[] { R.id.level_text });
setListAdapter(adapter);
data.close();
db.close();
}
}
high_scores.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="Text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/level_text"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
There are no error messages whatsoever, simply nothing happens.
Its not that the cursor is blank either, when I test the adapter.getCount() method, it returns ~30, which is exactly as expected.
I think all the function names are pretty much intuitive but if you need any clarification, just ask.
Any help is greatly apprechiated
A:
There was 2 problems with my first code.
The first is as MisterSquonk pointed out, prematurely close the cursor and the database.
The second was in correctly binding the data to the views.
Here is the code of my now working solution
HighScoresActivity:
public class HighScoresActivity extends ListActivity {
private Cursor data;
private ScoresDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.high_scores);
db = new ScoresDatabase(this);
data = db.getHighScores();
ListAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.high_scores_entry, data,
new String[] { "level", "moves" },
new int[] { R.id.level_entry,
R.id.moves_entry });
setListAdapter(adapter);
}
@Override
protected void onDestroy() {
super.onDestroy();
data.close();
db.close();
}
}
high_scores.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="@android:id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
high_scores_entry.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/level_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/moves_entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
The way I had the data originally bound made no sense.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to check whether an integer has occurred or a character has occurred while reading input file in C++
Hie, I have a problem separating characters from integers within an input file in C++.An example of the file contents is given below:
D 5 C 7 C 9 H 4 S 8 D 11 H 13
I want to read and store characters in an array and integers their own array as well, I know how to use fstream but I am stuck on separating the items. I will greatly appreciate any help offered, thank you in advance.
I solved a similar problem last week but there were no characters in that assignment, code is given below for that:
#include <iostream>
#include <fstream>
using namespace std;
int frequencyCal(unsigned short int[][5], unsigned short int, ofstream&);
unsigned short int ScoreForRow(unsigned short int[][5], unsigned short int, ofstream&);
int main() {
unsigned short int iArray[50][5];
unsigned short int rows = 0;
ifstream fin("YahtzeIn.txt");
ofstream fout("YahtzeOut.txt");
for(unsigned short int i = 0; i < 50; i++) {
rows += 1;
for(unsigned short int j = 0; j < 5; j++) {
fin >> iArray[i][j];
cout << iArray[i][j] << " ";
fout << iArray[i][j] << " ";
}
cout << " ==> " << ScoreForRow(iArray,i,fout) << endl;
fout << " ==> " << ScoreForRow(iArray,i,fout) << endl;
if(fin.eof())
break;
}
cout << endl;
fout << endl;
frequencyCal(iArray, rows, fout);
return 0;
}
int frequencyCal(unsigned short int in_array[][5], unsigned short int filerows, ofstream& outfile) {
unsigned short int num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, num6 = 0;
// Count the numbers in each row;
for(unsigned short int i = 0; i < filerows; i++)
{
for(unsigned short int j = 0; j < 5; j++ )
{
// Identify the number and add one to a counter variable
if(in_array[i][j] == 1) {
num1+=1;
}
else if(in_array[i][j] == 2) {
num2+=1;
}
else if(in_array[i][j] == 3) {
num3+=1;
}
else if(in_array[i][j] == 4) {
num4+=1;
}
else if(in_array[i][j] == 5) {
num5+=1;
}
else if(in_array[i][j] == 6) {
num6+=1;
}
}
}
cout << "Dice frequency" << endl;
cout << "==============" << endl;
cout << "1's 2's 3's 4's 5's 6's" << endl;
outfile << "Dice frequency" << endl;
outfile << "==============" << endl;
outfile << "1's 2's 3's 4's 5's 6's" << endl;
// Print and display the values of the variables;
cout << num1 << " " << num2 << " " << num3 << " " << num4 << " " << num5 << " " << num6;
outfile << num1 << " " << num2 << " " << num3 << " " << num4 << " " << num5 << " " << num6;
return 0;
}
unsigned short int ScoreForRow(unsigned short int in_array[][5], unsigned short int i, ofstream& outfile) {
unsigned short int numb1 = 0, numb2 = 0, numb3 = 0, numb4 = 0, numb5 = 0, numb6 = 0, score = 0;
bool four = false, five = false;
for(unsigned short int j = 0; j < 5; j++ )
{
// Sum up all numbers in a row
score += in_array[i][j];
// check if number occurs twice, three times or five times
if(in_array[i][j] == 1) {
numb1+=1;
if(numb1 == 4) {
four = true;
}
else if(numb1 == 5) {
four = false;
five = true;
}
}
else if(in_array[i][j] == 2) {
numb2+=1;
if(numb2 == 4) {
four = true;
}
else if(numb2 == 5) {
four = false;
five = true;
}
}
else if(in_array[i][j] == 3) {
numb3+=1;
if(numb3 == 4) {
four = true;
}
else if(numb3 == 5) {
four = false;
five = true;
}
}
else if(in_array[i][j] == 4) {
numb4+=1;
if(numb4 == 4) {
four = true;
}
else if(numb4 == 5) {
four = false;
five = true;
}
}
else if(in_array[i][j] == 5) {
numb5+=1;
if(numb5 == 4) {
four = true;
}
else if(numb5 == 5) {
four = false;
five = true;
}
}
else if(in_array[i][j] == 6) {
numb6+=1;
if(numb6 == 4) {
four = true;
}
else if(numb6 == 5) {
four = false;
five = true;
}
}
}
// Check if a number appears twice and another occurs 3 times, if so, update score to 25;
if(((numb1 == 2) || (numb2 == 2) || (numb3 == 2) || (numb4 == 2) || (numb5 == 2) || (numb6 == 2))
&& ((numb1 == 3) || (numb2 == 3) || (numb3 == 3) || (numb4 == 3) || (numb5 == 3) || (numb6 == 3))) {
score = 25;
}
// Check if a number appears four times
else if(four == true) {
score = 30;
}
// Check if a number appears five times
else if(five == true) {
score = 50;
}
// the value returned is either sum or number generated by the conditions
return score;
}
A:
From the code above you could change iArray in a character array, after this you can use casting to read the integers. Hope this helps
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get single product from category id in magento?
<?php
$categoryid = 64;
$category = new Mage_Catalog_Model_Category();
$category->load($categoryid);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
foreach ($collection as $_product) { ?>
<a href="<?php echo $_product->getProductUrl() ?>"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(200); ?>" width="200" height="200" alt="" /></a> <a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $_product->getName(); ?></a>
<?php } ?>
A:
<?php
foreach($this->getStoreCategories() as $_category)
{
$cur_category=Mage::getModel('catalog/category')->load($_category->getId());
$collectionnn = Mage::getModel('catalog/product')
->getCollection()
->joinField('category_id','catalog/category_product', 'category_id', 'product_id = entity_id',null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('category_id',array('in' => $cur_category->getId()));
foreach($collectionnn as $product)
{
echo "<a href=".$product->getProductUrl().">".$product->getName()."</a><br>";
break;
}
}
?>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to prevent document.forms[0].submit() from submitting a form?
This is basically my form:
<form method="post" action="" onsubmit="checkallfields(); event.preventDefault();">
<!-- My Stuff -->
</form>
And it is the first form on my page. I have client-side field validation, which obviously is stored in the function checkallfields(). But the problem is, that the user can be very naughty and open up the console and type document.forms[0].submit(), and then the form will still submit.
How do I prevent this?
A:
I thought about the problem, and got my own answer. Tested it in Google Chrome.
var i = document.forms.length;
while (i--) {
document.forms[i].submit = function () {
return false;
}
}
Does it work for you guys? You can check here: http://jsfiddle.net/think123/ZRuYw/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Continuity of $\frac{x^5-4x^3y^2-xy^4}{(x^2+y^2)^2}$ at (0, 0)
I am having trouble proving that $\frac{x^5-4x^3y^2-xy^4}{(x^2+y^2)^2}$ is continuous at (0, 0) if we set the value at $(0, 0)$ to be 0.
I don't see a way to prove this as I cannot factor this into partial fractions.
A:
Hint. By considering polar coordinates,
$$
x:=r\cos\theta,\quad y:=r\sin\theta,
$$ you get
$$
\begin{align}
f(r\cos\theta,r\sin\theta)&=\frac{r^5(\cos^5\theta-4\cos^3\theta \sin^2\theta-\cos\theta\sin^4\theta)}{r^4}\\\\
&=r(\cos^5\theta-4\cos^3\theta \sin^2\theta-\cos\theta\sin^4\theta)
\end{align}
$$ then observe that
$$
\left|\cos^5\theta-4\cos^3\theta \sin^2\theta-\cos\theta\sin^4\theta\right|\leq7
$$ gives
$$
\left|f(r\cos\theta,r\sin\theta)\right|\leq7r
$$
for all $r>0$ and $\theta$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pyside setStyleSheet() and long lines?
I haven't found a way to cut the long code lines on these parts. No matter from what point I cut the line to the next, it breaks the string.
Is there a way to cut these in to shorter lines somehow?
self.setStyleSheet('ApplicationWindow { background-color: rgba(10, 10, 10, 10); } ButtonDefault { background-color: rgb(255, 10, 10); color: rgb(255, 255, 255); }')
My own solution was to move stylesheets in to seperate .css file and pare the whole thing from there as a simple string. It's nicer to develop that way too, but does this method sound reasonable?
stylesheet_string = ''
# Opens external stylesheet file
with open('stylesheet.css', 'r') as stylesheet:
for line in stylesheet:
line.replace('\n', ' ')
line.replace('\t', ' ')
stylesheet_string = stylesheet_string+line
self.setStyleSheet(stylesheet_string)
A:
For having shorter code lines in general see How can I break up this long line in Python?.
For stylesheets in particular and if you want them to load from file just load them and do not replace anything. It works!
with open('path', 'r', encoding='utf-8') as file:
style_sheet = file.read()
app.setStyleSheet(style_sheet)
An example that shows that it works:
from PySide import QtGui
app = QtGui.QApplication([])
window = QtGui.QMainWindow()
window.setStyleSheet('/*\n some comment */\n\nbackground-color:black;\n\r\t\n')
window.show()
app.exec_()
will show a black window despite the many newlines and comments in the stylesheet string.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spring pointcut XML expression on custom annotation
I have a custom annotation as follows:
@Inherited
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
}
In Spring XML configuration I have the following:
<aop:pointcut id="fooPointcut" expression="@annotation(com.foo.blah.MyCustomAnnotation)"/>
This will only match on method annotations. How do I tweak the spel to also capture type/class annotations?
A:
Use @within(com.foo.blah.MyCustomAnnotation) to
limit matching to join points within types that have the given annotation
A combined pointcut expression would become:
@annotation(com.foo.blah.MyCustomAnnotation) || @within(com.foo.blah.MyCustomAnnotation)
See Join Point Matching based on Annotations in the AspectJ 5 Developer's Notebook for further reference. Also note, that Spring's AOP doesn't support full AspectJ pointcuts, only a limited subset.
Also note that @annotation(com.foo.blah.MyCustomAnnotation) in AspectJ would match
all join points where the subject of the join point has the given annotation
meaning that it would match method-execution as well as method-call. In Spring AOP it only matches method-execution though, but it's better to write pointcut expressions that are valid in a broader scope as well, so don't forget to use an execution(...) pointcut too to restrict the pointcut.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Equivalent of "assert" in JPL7
I am currently creating a Java Swing GUI where the user can select what type of fruits they like. Depending on their choice, only certain fruit products will be shown. For instance, if the user selects "grape", then only grape products like grape jam or grape juice are displayed.
The issue is on how to assert some facts into Prolog. For instance, I am trying to assert that the user has selected "grape". TLDR; I am trying to find the JPL equivalent of the SWI-Prolog command of:
assert(selected_fruit(grape)).
Below are 2 of the attempts I have tried.
Query q2=new Query("assert selected_fruit(grape)");
System.out.println(q2.hasSolution());
And another one I tried is the following:
Query q2 = new Query("selected_fruit", new Term[] {new Atom("grape")});
System.out.println(q2.hasSolution());
The first attempt threw out a syntax_error, while the second one threw out an existence_error upon running. If anyone can shed some light, that would be greatly appreciated.
A:
Never mind, I found the answer after much experimentation. The correct way to assert in my case was the following:
Query q2 = new Query("assert(selected_fruit(grape))");
System.out.println(q2.hasSolution());
The console should then print out "true".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using enum in namespace
I'm using enumeration in namespace in my code
namespace Statusss
{
enum Statuss
{
Out = -1,
Ok = 0,
Busy = 1,
Error = 2,
Nor = 3
};
}
void tst()
{
int status =0;
Statusss::Statuss mystatus = static_cast<Statusss::Statuss>(status);
if (mystatus == (Statusss::Statuss::Ok))
{
std::cout << "Ok\n";
} else std::cout << "Other\n";
}
It works fine in simple console application. But if I place this code in GUI Qt widget application I have error:
'Statusss::Statuss' is not a class or namespace
if (mystatus == (Statusss::Statuss::Ok))
^
Why I'm getting this?
A:
The correct name for that symbol is
Statusss::Ok
In a traditional C-style enum, like the one you show here, the enum type is not part of the scope.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fitting a line curve to 3D data
I have a set of points in 3D which I need to fit a curve (not a plane) to. Essentially these points describe a string with a set order (i.e. point one connects to point two, etc.) and I need to fit a curve to follow these points and produce a smoothed, single-width string as a result.
Unfortunately all of the 3D fitting algorithms I've found so far (I'd probably go with polynomial fitting) result in a plane, not a line, and it's lead me to believe what I need is a 2D fitting algorithm which operates on three sets of coordinates.
I can work out how to do linear interpolation for these points, it's figuring out the polynomial that I'm struggling with. Does anybody have any helpful pointers for this?
A:
Since your points are already in a specified order, you could try fitting the $x$, $y$, and $z$ coordinates independently as functions of the index of the point in the ordering. That is, if you have points $(x_1,y_1,z_1)$, $(x_2,y_2,z_2)$, and so on, you fit $x_i$ as a function of $i$, then $y_i$ as a function of $i$, and $z_i$ as a function of $i$. Then your curve is given by $t\mapsto(x(t),y(t),z(t))$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
c# register form mysql insert
So im having problem gettin some data in to the database.. Im really stuck, im quite new to c# and have not learned all keywords yet, im not getting any errors just some nothing adds to my database.
textBox2.Text = myPWD;
MySqlConnection conn = new MySqlConnection("test")
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES ('values = @val')";
MySqlCommand data = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
SelectCommand.Parameters.AddWithValue("@val", this.textBox2.Text);
conn.Closed()
A:
Manipulate the concatenation of value in passing of parameters. Don't do it inside sql statement.
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES (@val)";
// other codes
SelectCommand.Parameters.AddWithValue("@val", "values = " + this.textBox2.Text);
the reason why the parameter is not working is because it was surrounded by single quotes. Parameters are identifiers and not string literals.
The next problem is you did not call ExecuteNonQuery() which will execute the command.
Before closing the connection, call ExecuteNonQuery()
// other codes
data.ExecuteNonQuery();
conn.Close();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rate of convergence of weakly null sequences
If $x_n$ is a normalized, weakly-null sequence in a Banach space, and $\epsilon_n\to 0$, does there exists a non-zero functional $f$ such that $|f(x_n)|<\epsilon_n$ for all $n$?
A:
No, in fact in the Banach space $c_0$, for any sequence $\epsilon_n$ of positive numbers decreasing to $0$, we can choose a normalized weakly-null sequence $x_n$ such that for every nonzero bounded linear functional $f$,
$\limsup_{n \to \infty} |f(x_n)|/\epsilon_n = \infty$.
Let $e_j$ be the $j$'th unit vector $(0,\ldots, 0, 1, 0, \ldots)$. Consider a sequence $x_n$ such that, for each positive integer $m$ such that $\epsilon_m < 1/2$, $x_{2^m+1}, \ldots, x_{2^{m+1}}$ consists of $\epsilon_m^{1/2}\left(\pm e_1 \pm e_2 \ldots \pm e_m\right) + e_{m+1}$
for all $2^m$ choices of signs. It is easy to see that this is normalized and converges weakly to $0$.
But for any nonzero $f \in c_0^* = \ell_1$, take $m$ large enough that $\sum_{j=1}^{m+1} |f_j| > \|f\|/2$. Then some $k$ with $2^m+1 \le k \le 2^{m+1}$ gives $f_j (x_k)_j$ all the same signs for $1 \le j \le m+1$, and thus for large enough $m$, $$\frac{|f(x_k)|}{\epsilon_k} \ge \frac{\epsilon_m^{1/2}}{\epsilon_k}\sum_{j=1}^{m+1} |f_j| > \frac{\epsilon_m^{1/2} \|f\|}{2 \epsilon_k}> \frac{\|f\|}{2 \epsilon_k^{1/2}} \to \infty$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How shall I say "star" and "unstar" (as in Github) in Russian?
Как сказать "star" и "unstar" (типа как отметить репозиторий звёздочной на GitHub'е или снять такую отметку) кратко и ясно? Желательно литературно, без "лайкнуть" и т.д.
How to say "star" and "unstar" (as if you marking a repository with star on Github or removing such mark) shortly and clearly? Advisably not slangish like "to put a like" and so on...
A:
In addition to previous answers:
star — "проголосовать", "проголосовать «за»", "отдать свой голос" (up-vote)
unstar — "проголосовать «против»", "снять свой голос" (down-vote)
or
star/unstar — "поставить(дать, отдать) звезду"/"снять(убрать, забрать) звезду"
or
star/unstar — "плюсануть"/"минусануть" (slang, to click on 'plus' or 'minus')
A:
Если брать в качестве примера тот же самый GitHub, то имеет смысл рассмотреть практическую значимость "проставления звезд": люди используют их для того, чтобы:
1. Выразить свое положительное отношение к проекту.
2. Иметь возможность быстрого доступа к проектам, интересующим пользователя.
Исходя из этих значений можно формулировать краткие аналоги для русского языка, при этом совершенно не обязательно использовать глаголы. Вот несколько подходящих вариантов:
Интересно / Не интересно
Поддержать / Не поддерживать
Отметить / Снять отметку (предложено ovgolovin)
В избранное / Удалить из избранного
Нравится / Не нравится
Важно / Не важно
Если немного отвлечься от концепции GitHub, в котором функция отслеживания является отдельной возможностью, то в каких-то случаях могут подойти слова Отслеживать/Не отслеживать. В любом случае, при переводе данной функциональности нужно рассматривать, в чем заключается смысл данной функции в конкретном сервисе/приложении/и т.д.
A:
star I would tranlate as Выделить или Отметить.
unstar I would translate as Снять выделение или Снять отметку.
I don't see any more eloquent variants as loquacious Снять выделение or Снять отметку.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to select all post's tags?
I have this table:
// QandA
+----+--------+----------------------------------------+------+---------+
| id | title | content | type | related |
+----+--------+----------------------------------------+------+---------+
| 1 | title1 | content of question1 | 0 | NULL |
| 2 | | content of first answer for question1 | 1 | 1 |
| 3 | title2 | content of question2 | 0 | NULL |
| 4 | title3 | content of question3 | 0 | NULL |
| 5 | | content of second answer for question1 | 1 | 1 |
| 6 | | content of first answer for question3 | 1 | 4 |
| 7 | title4 | content of question4 | 0 | NULL |
| 8 | | content of first answer for question2 | 1 | 3 |
+----+--------+----------------------------------------+------+---------+
-- type colum: it is 0 for questions and 1 for answers.
-- related column: it is NULL for questions and {the id of its own question} for answers.
Also I have these two other tables:
// interface_tags
+---------+--------+
| post_id | tag_id |
+---------+--------+
| 1 | 1 |
| 1 | 5 |
| 3 | 4 |
| 4 | 1 |
| 4 | 2 |
| 4 | 5 |
| 7 | 2 |
+---------+--------+
// tags
+----+----------+
| id | tag_name |
+----+----------+
| 1 | PHP |
| 2 | SQL |
| 3 | MySQL |
| 4 | CSS |
| 5 | Java |
| 6 | HTML |
| 7 | JQuery |
+----+----------+
And here is my query:
SELECT id,
title,
content
FROM QandA
WHERE id = :id1 OR related = :id2
-- Note: :id1, :id2 are identical
As you see it selects both the question (id = :id2) and all its own answers (related = :id3).
What's my question? I need to also select all question's tags. Here is expected output:
-- :id = 1
// QandA
+----+--------+----------------------------------------+------------+
| id | title | content | tag |
+----+--------+----------------------------------------+------------+
| 1 | title1 | content of question1 | PHP,JAVA |
| 2 | | content of first answer for question1 | |
| 5 | | content of second answer for question1 | |
+----+--------+----------------------------------------+------------+
How can I do that?
A:
You can try this
SELECT
q.id,
q.title,
q.content,
GROUP_CONCAT(t.tag_name) AS tag
FROM QandA q
LEFT JOIN interface_tags it ON it.post_id = q.id AND q.type = 0
LEFT JOIN tags t ON t.id = it.tag_id
WHERE q.id = :id1 OR related = :id2
GROUP BY q.id
View schema and script execution in SQLFiddle.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
awk: "not enough arguments to satisfy format string" error in script
I created a script to grab the data from our Unix server, however I am getting the below error:
awk: cmd. line:8: (FILENAME=- FNR=2) fatal: not enough arguments to satisfy format string
`|%-17s|%-16s|%-15s|'
^ ran out for this one
Below is the complete script:
#!/bin/sh
export TERM=xterm
ipath=/usr/local/nextone/bin
date=$(date +"%Y%m%d%H%M")
ifile="$(date '+/var/EndpointUsage_%I-%M-%p_%d-%m-%Y.csv')"
"$ipath"/cli iedge list | awk '
BEGIN { print "|-----------------|------------------|------------------|";
printf "|%-18s|%-17s|%-16s|\r\n","Registration ID", "Port", "Ongoing Calls"
}
/Registration ID/ { id = $3; next }
/Port/ { port = $3 ; next }
/Ongoing Calls/ {print "|-------------------|-----------------|------------- -----|";
printf "|%-18s|%-17s|%-16s|\r\n",id,port,$3 }
END{
print "|------------------|------------------|------------------|";
}'>> "$ifile"
Can anyone please help me on this, how can I resolve this error?
AFTER CHANGES the columns are showing correctly, but the Port column does not have any data. It should have 0 or if other endpoint have 1 o 2 Port number.
|-----------------|------------------|------------------|
|Registration ID |Port |Ongoing Calls |
|-------------------|-----------------|------------------|
|-------------------|-----------------|------------------
|CC_XXXXXX_01_0 | |174 |
|-------------------|-----------------|------------------|
A:
The offending printf is:
printf "|%-18s|%-17s|%-16s|\r\n",id,$3
^^^^ awk wants to see a third parameter here
You have three %s sequences in the format string, so awk expects ,<something else> after the $3. I think maybe it's a copy and paste error. Since you are only printing two column headers, try removing the %-16s| at the end and seeing if that gives you the output you expect.
Edit Without seeing your input file, I don't know for sure. Try this, though -
/Registration ID/ { id = $3; next }
/Port/ { port = $3 ; next }
/Ongoing Calls/ {print "|-------------------|-----------------|------------------|";
printf "|%-18s|%-17s|%-16s|\r\n",id,port,$3 }
I added {port=$3;next} to save the port number, and then when you print them out, I changed id,$3 to id,port,$3 to print the saved id, saved port, and ongoing-calls value ($3) in order.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Measuring lenght of time light levels peak using photoresistor
I'm trying to measure shutter speeds on old cameras. This essentially consists of:
Shining a torch at one end of the camera
putting the photoresistor at the other end
trigger the shutter which temporarily lets in the light from the torch (boosting the photoresistor values temporarily)
Recording the duration of the increased spike in light levels
What I have currently records light levels but the variation is massive and typically incorrect in that they change depending on how close the torch is to the shutter and typically records values between 400 and 900 ms which is far too long (should be about 50ms).
This is the key code I have so far:
if (shutterbot.opened())
{
/* Measure length of time it is opened until closure */
unsigned long previousMillis = millis();
while(true)
{
unsigned long currentMillis = millis();
unsigned long time_elapsed = currentMillis - previousMillis;
if (shutterbot.closed())
{
finished = true;
/* Report back to user */
Serial.println("Shutter speed is: ");
Serial.println(time_elapsed);
break;
}
}
}
The open and close methods in the shutterbot class are:
/* If light is 10% higher, set it to start recording */
int Shutterbot::opened()
{
if (light_level() > 400)
{
return true;
}
else
{
return false;
}
}
/*
If light drops to below 10% higher, set it to stop
recording
*/
int Shutterbot::closed()
{
if (light_level() < 400)
{
return true;
}
else
{
return false;
}
}
The full project code is here and just needs a photoresistor module and an arduino uno to test. I'm not sure I've provided enough information so if there are any questions, please let me know. Any help is greatly appreciated and thanks for reading.
A:
It is unlikely a photo resistor can be used to time an event with sub second granularity. This is because the electrons in such a device have many conductive states which they migrate into when exposed to light and out of when left in the dark. It takes time for the electrons to drift into and out of these conductive bands. In some cases it may take a good portion of a second. As described in the 2nd paragraph in the Design Considerations section of the above wikipedia page:
Photoresistors also exhibit a certain degree of latency between
exposure to light and the subsequent decrease in resistance, usually
around 10 milliseconds. The lag time when going from lit to dark
environments is even greater, often as long as one second. This
property makes them unsuitable for sensing rapidly flashing lights,
but is sometimes used to smooth the response of audio signal
compression.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to send mail from VB form using system.net.mail
Our company has a call centre which pc's are locked down (no access to internet, email, office applications) and there is a need for them to be able to log support tickets from their own machines.
I have created a VB Windows forms application which grabs some info from the user (name, email, extension, subject and description of the issue) as well as system information collected from WMI.
I intent to send all of this information to our helpdesk via email, the sys information would enable us to identify hardware problems and such.
However when trying to send a mail. it just doesnt work.
We have a smtp relay which allows for anonymous email relay and does not require user credentials.
Once i get the basic test mail to work i will start populating the mail with the information i get from the user. However the mail is currently throwing exceptions and not sending at all.
Note I am an absolute beginner when it comes to VB and .net as i come from a linux / php background
Below is my code:
Imports System.Management
Imports System.Management.Instrumentation
Imports System.Net.Mail
Public Class Form1
Private Property strComputer As String
Private Property objWMIService As Object
Private Property colItems As Object
Private Property colComputers As Object
Private Property strComputerRole As String
Private Property colDisks As Object
Private Property colOperatingSystems As Object
Private Property IPConfigSet As Object
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim response As MsgBoxResult
response = MsgBox("Are you sure you want to exit?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm")
If response = MsgBoxResult.Yes Then
Me.Dispose()
ElseIf response = MsgBoxResult.No Then
Exit Sub
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strName As String
Dim strDept As String
Dim strEmail As String
Dim strExt As String
Dim strDesc As String
Dim strAffect As String
Dim strSubject As String
strName = TextBox1.Text
strDept = TextBox2.Text
strEmail = TextBox3.Text
strExt = TextBox4.Text
strSubject = TextBox6.Text
strDesc = RichTextBox1.Text
strAffect = TextBox5.Text
strComputer = "."
objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
colItems = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")
For Each objItem In colItems
TextBox7.Text = objItem.Name
TextBox8.Text = objItem.Manufacturer
TextBox9.Text = objItem.Model
TextBox11.Text = objItem.TotalPhysicalMemory
Next
colComputers = objWMIService.ExecQuery _
("Select DomainRole from Win32_ComputerSystem")
For Each objComputer In colComputers
Select Case objComputer.DomainRole
Case 0
strComputerRole = "Standalone Workstation"
Case 1
strComputerRole = "Member Workstation"
Case 2
strComputerRole = "Standalone Server"
Case 3
strComputerRole = "Member Server"
Case 4
strComputerRole = "Backup Domain Controller"
Case 5
strComputerRole = "Primary Domain Controller"
End Select
TextBox10.Text = strComputerRole
Next
colItems = objWMIService.ExecQuery("Select * from Win32_Processor")
For Each objItem In colItems
TextBox12.Text = objItem.Manufacturer
TextBox13.Text = objItem.Name
TextBox14.Text = objItem.MaxClockSpeed & " MHz"
Next
colItems = objWMIService.ExecQuery("Select * from Win32_BIOS")
For Each objItem In colItems
TextBox15.Text = objItem.Version
TextBox16.Text = objItem.SerialNumber
Next
colItems = objWMIService.ExecQuery("Select * from Win32_VideoController")
For Each objItem In colItems
TextBox17.Text = objItem.Name
Next
colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk where DeviceID = ""C:""")
For Each objDisk In colDisks
TextBox18.Text = Math.Round(objDisk.Size / 1073741824) & " GB"
TextBox19.Text = Math.Round(objDisk.Freespace / 1073741824) & " GB"
Next
colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
For Each objOperatingSystem In colOperatingSystems
TextBox20.Text = objOperatingSystem.Caption & " " & objOperatingSystem.Version
TextBox21.Text = objOperatingSystem.ServicePackMajorVersion & "." & objOperatingSystem.ServicePackMinorVersion
Next
Dim moIP As ManagementObject
Dim myNet = New ManagementObjectSearcher _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each moIP In myNet.Get
' Eg: Display IP address in Message Box
TextBox22.Text = moIP("IPAddress")(0)
Next
Dim mail As New MailMessage()
mail.To.Add("[email protected]")
mail.From = New MailAddress(strEmail)
Dim smtp As New SmtpClient()
smtp.Host = "relay.company.local"
smtp.EnableSsl = False
mail.Subject = strSubject
mail.Body = strDesc
smtp.Send(mail)
End Sub
Private Function Wscript() As Object
Throw New NotImplementedException
End Function
Private Function IsNull(p1 As Object) As Boolean
Throw New NotImplementedException
End Function
End Class
UPDATE:
Below is an exception
An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll
Additional information: Service not available, closing transmission channel. The server response was: 4.3.2 Service not available, closing transmission channel
A:
You might be missing a few details. Here is a snippet to help:
'...
'for when not using default credentials
Dim SMTP_Credentials As System.Net.NetworkCredential = New System.Net.NetworkCredential
SMTP_Credentials.UserName = "UserName"
SMTP_Credentials.Password = "Password"
Using SMTP_Mail As New Net.Mail.SmtpClient
With SMTP_Mail
.EnableSsl = False
.Host = "IP" 'ip address of smtp client
.Port = 25 'by default SSL does not use port 25 (use port 587 for SSL)
.UseDefaultCredentials = True
If Not .UseDefaultCredentials Then .Credentials = SMTP_Credentials
.Send(mailMsg) 'send email.
End With
End Using
'...
I am going to suggest you play with the default credential settings first. I have found this to be almost never set as expected... Don't rely on the default settings being what is standard unless you are the on in control of the server...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to compare primary keys two tables, which is combination of five columns?
I have two tables, and I want to update one table from another. Primary key defined for both is combination of five columns which I addded like below
alter table custompricingnew
add primary key (partNumberSKU(100), customerClass(100), customerName(100), svcType(100), svcDuration(100), durationPeriod(100))
How to write the where clause of the update statment ? Do I need to specify those five columns separately ?
UPDATE customPricingTest t1, customPricingTesttemp t2
SET t1.customerId= t2.customerId, t1.customerNumber= t2.customerNumber, t1.custPartNumber=t2.custPartNumber
WHERE t1.primaryKey = t2.primaryKey
Nitesh
A:
You can also use a join with the USING syntax:
UPDATE customPricingTest t1 INNER JOIN customPricingTesttemp t2
USING (partNumberSKU, customerClass, customerName, svcType, svcDuration, durationPeriod)
SET t1.customerId = t2.customerId,
t1.customerNumber = t2.customerNumber,
t1.custPartNumber = t2.custPartNumber;
This is a shortcut syntax that assumes that the columns exist with the same names in both tables, and your join should use equality comparison for all of them.
Also note the parentheses are required.
See also: JOIN syntax
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convert DateTime Time from 00:00:00 to 23:59:59
In my database table fields are saved as 2013-02-15 00:00:00.000. I want they should be 2013-02-15 23:59:59.999. So how to convert 2013-02-15 00:00:00.000 to 02-15 23:59:59.999. In other words only change minimum to maximum time.
A:
DECLARE @Time TIME = '23:59:59.999'
SELECT dateColumn + @Time
FROM tableName
SQL Fiddle Demo
Edit
Cast @time to datetime before (+)
DECLARE @Time TIME = '23:59:59.999'
SELECT dateColumn + CAST(@Time as DATETIME)
FROM tableName
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to execute lightning component functions (apex or javascript controller) from a Visualforce page that includes the component?
I created a lightning component that will house a drag and drop file uploader and handle all of its goings ons.
Then I bring it into my Visualforce page like so:
$Lightning.use('c:DropZoneComponentApp', function(){
$Lightning.createComponent('c:DropZoneComponent', {eventId: currentEvent.taskId}, 'eventDropzone', function(cmp){
console.log('Component Created!', cmp);
console.log(cmp.get('v.fileInfo'));
//console.log(cmp.testingFunction()); <--Doesn't work
});
});
I now want to be able to call functions of the lightning component when a button is pressed on my Visualforce page. just doing cmp.functionName() does not seem to work.
How do you accomplish this? I am OK triggering the AuraEnabled controller methods for the component, or the javascript controller methods.
A:
You can use aura:method to invoke lightning controller methods as follows. Store the generated component to a global variable and invoke the aura:method to call your controller action. You can either call lightning controller methods which could, in turn, call the @AuraEnabled Methods or use RemoteActions to call your apex class methods, it really depends on your use case.
Component:
<aura:component access="global">
<aura:method name="sampleMethod" action="{!c.doAction}" description="Sample method with parameters" access="global">
<aura:attribute name="foo" type="String" default="parameter 1"/>
<aura:attribute name="bar" type="Object" />
</aura:method>
Inside Component
</aura:component>
Controller:
({
doAction : function(component, event, helper) {
var params = event.getParam('arguments');
if (params) {
console.log(params.foo);
console.log(JSON.stringify(params.bar));
}
}
})
Visualforce Page:
<apex:page >
<apex:includeLightning />
<div id="lightning" />
<script type="text/javascript">
var cmp;
$Lightning.use("c:TestApplication2", function() {
$Lightning.createComponent("c:Component1",{},"lightning",
function(component) {
cmp = component;
});
});
var invoke_aura_method = function(){
cmp.sampleMethod("Hello World ! ", {message : "I'm Jack Sparrow"});
}
</script>
<apex:form >
<apex:commandButton value="Call Aura Method" onclick="invoke_aura_method();return false;"/>
</apex:form>
</apex:page>
Example:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Apply endDate to table
I want to provide an EndDate when the MainAccountNum already exist. The endDate should be applied to the MainAccountNumb with the earliest startDate.
So If I have a create table statement like this:
Create Table ods.CustomerId(
ScreenDate INT NOT NULL,
CustomerNum nvarchar(40) NOT NULL,
MainAccountNum nvarchar(40) not null,
ServiceNum nvarchar(40) not null,
StartDate datetime not null,
EndDate datetime not null,
UpdatedBy nvarchar(50) not null);
and say I encounter something in the CustomerNum, MainAccountNum, StartDate, and EndDate like below:
1467823,47382906,2019-08-26 00:00:00.000, Null
1467833,47382906,2019-09-06 00:00:00.000, null
When the second record is inserted with that same MainAccountNum the first record should get the startDate of the New Record. The startDate has a default constraint as GetDat() so in the end it should look like:
1467823,47382906,2019-08-26 00:00:00.000,2019-09-06 00:00:00.000
1467833,47382906,2019-09-06 00:00:00.000, null
Please Provide code examples of how this can be accomplished
I would like to apply an update to the current records in my table that do not have an endDate but have this same situation. How would I apply that update to where I give the previous record an endDate please provide me with code to solve this issue. Thanks so much
A:
Your CustomerId table has EndDate as not null, how did they end up being null. Anyway try this:
update CustomerId
set EndDate = (select min(t2.StartDate) from CustomerId t2
where t2.MainAccountNum = t1.MainAccountNum and t2.StartDate > t1.StartDate)
from CustomerId t1
where t1.EndDate is null
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spring autowire a stubbed service - duplicate bean
Ok. We have the need to @Autowire a different webservice on-the-fly (preferably by toggling a JNDI setting on the webserver) and I'm at a loss on how to do this. This is the way I was approaching the problems..
Two packages:
com.mycomp.service.stub
com.mycomp.service.impl
One package contains MyServiceStub.java while implement MyService
The other package contains MyServiceImpl.java, which implements same
My controller, which requires MyService, has the bean defined as such
@Autowire
private MyService communicator;
My spring-context.xml has the following:
<context:component-scan base-package="com.mycomp" />
At this point I get a DuplicateBean exception during autowiring. Now, I can statically define which bean to autowire in spring-context.xml:
<bean id="communicator" class="com.mycomp.service.impl.MyServiceImpl" />
and everything works fine... But then, how to 'flip' the switch and change over to the Stub method on our QA server? It has no connection to that service, so we need to run with stubs enabled. A JNDI property would be best for this.. but I just can't get my head around how to toggle what bean spring autowires at runtime.
Any help??
Cheers,
Chris
A:
@Profile solution
You definitely have to try Spring 3.1 @Profile:
@Autowire
private MyService communicator;
//...
@Service
@Profile("prd")
class MyServiceImpl //...
@Service
@Profile("qa")
class MyServiceStub //...
Now depending on which profile is enabled, either DefaultMyService will be initialized or MyServiceStub.
You can choose between profile in various ways:
How to set active spring 3.1 environment profile via a properites file and not via an env variable or system property
using system property
programmatically
...
Spring AOP (explicit around every method)
In this example the aspect wraps around every single MyService method separately and returns stubbed value:
@Aspect
@Service
public class StubAspect {
@Around("execution(public * com.blogspot.nurkiewicz.MyService.foo(..))")
public Object aroundFoo(ProceedingJoinPoint pjp) throws Throwable {
if (stubMode()) {
return //stub foo() result
}
return pjp.proceed();
}
@Around("execution(public * com.blogspot.nurkiewicz.MyService.bar(..))")
public Object aroundBar(ProceedingJoinPoint pjp) throws Throwable {
if (stubMode()) {
return //stub bar() result
}
return pjp.proceed();
}
private boolean stubMode() {
//whatever condition you want here
return true;
}
}
The code is pretty straightforward, unfortunately the return values are buried inside the aspect and you need a separate @Around for every target method. Finally, there is no place for MyServiceStub.
Spring AOP (automatically around all methods)
@Aspect
@Service
public class StubAspect {
private MyServiceStub stub = //obtain stub somehow
@Around("execution(public * com.blogspot.nurkiewicz.MyService.*(..))")
public Object aroundFoo(ProceedingJoinPoint pjp) throws Throwable {
if (stubMode()) {
MethodSignature signature = (MethodSignature)pjp.getSignature();
Method method = signature.getMethod();
return method.invoke(stub, pjp.getArgs());
}
return pjp.proceed();
}
private boolean stubMode() {
//whatever condition you want here
return true;
}
}
This approach is more implicit as it automatically wraps every target method, including new methods added in the future. The idea is simple: if stubMode() is off, run the standard method (pjp.proceed()). If it is on - run the exact same method with exact same parameters - but on a different object (stub in this case).
This solution is much better as it involves less manual work (at the price of using raw reflection).
Note that if both MyService implementations are Spring beans (even when one is annotated with @Primary), you might run into weird troubles. But it should be a good start.
See also:
Spring 3.1 M1: Introducing @Profile
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change table value based on value of previous element
How would use greasemonkey to change the value of the 3rd row on the condition that the first row has the value "China"? All the other answers I found involves looking at the element id, but my code doesnt have any.
<td class="listRow listHighlight" align="center">101</td>
<tr id="country3" class="listRow">
<td class="listRow listHighlight" align="center">China</td>
<td class="listRow listHighlight" align="center">Asia</td>
<td class="listRow listHighlight" align="center">31</td>
</tr>
A:
Use jQuery :contains() selector and next():
var third = $('.listRow td:contains("China")').next().next();
if (third.text() === '31') {
third.text('32');
}
In case the first cell may have words except China like China something the selector approach won't work, you'll need an exact comparison. Use filter():
var third = $('.listRow td:first').filter(function() {
return $(this).text() === 'China';
}).next().next().filter(function() {
return $(this).text() === '31';
}).text('32');
Or a combined version:
var third = $('.listRow td:first').each(function() {
if ($(this).text() === 'China') {
var third = $(this).next().next();
if (third.text() === '31') {
third.text('32');
}
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
List Ethereum transactions to: and from: in one const
I would like to list all the transactions to and from my ERC-20 Ethereum address, i can only seem to list to or from, but not both at the same time. Is there another filter I could use or way to re-structure the statement to obtain both values in one const? Thanks
const transactions = await Token123.getPastEvents('Transfer', { fromBlock: 0, toBlock: 'latest', filter: { to: this.state.account } })
and
const transactions = await Token123.getPastEvents('Transfer', { fromBlock: 0, toBlock: 'latest', filter: { from: this.state.account } })
Here is how I am viewing the results:
<tbody>
{ this.state.transactions.slice().reverse().map((tx, key) => {
return (
<tr key={key} >
<td>{tx.returnValues.to}</td>
<td>{window.web3.utils.fromWei(tx.returnValues.value.toString(), 'Ether')}</td>
</tr>
)
}) }
</tbody>
Using: "web3": "1.0.0-beta.55"
A:
You cannot do this in one call with Web3, it is not supported yet. Using
const transactions = await Token123.getPastEvents('Transfer', { fromBlock: 0, toBlock: 'latest', filter: { from: this.state.account, to: this.state.account } })
will result in an empty list, unless the account happened to have send some money to himself. Your only option with Web3 are doing two calls. If you care about performance, you could use something like https://quickblocks.io/. But mostly just looking in the last X blocks will be good enough.
Command to get all transactions in one variable in one line:
const transactions = (await Promise.all([Token123.getPastEvents('Transfer', { fromBlock: 0, toBlock: 'latest', filter: { from: this.state.account } }), Token123.getPastEvents('Transfer', { fromBlock: 0, toBlock: 'latest', filter: { to: this.state.account } })])).flat()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do people I randomly run into keep living after I've left them?
When I wander around Skyrim I'll often run into high elves with prisoners, rich lords on horses and sometimes named NPCs that I can interact with.
Unfortunately for them, the dragon born of their world loves stabbing and robbing in that order.
If the dragon born let them be, would they still wander from town to town or would they simply despawn at some point in time?
Edit
I've encountered a hunter and his horse on the road and held my blade. I followed him for some time and it appears that his entire existence consists of patrolling up and down the same 100 meters of trail. I was disappointed to say the least. Sfter some time has passed I shall return to the place whence I saw him last and see if he continues his drudgery.
A:
All NPCs in the game follow a schedule, regardless of whether the player character is near their vicinity.
So they are technically still 'going on about their lives', even if you leave them alone.
However, some game locations will reset or respawn after some time (depending on their schedule and 'flag'). This will reset all NPCs that are based on that location.
From the UESP article, "Respawning":
Most locations in the game are respawning. This happens, depending on the location, at scheduled times. When a game location respawns, its enemies and loot are reset. This allows revisiting previously visited locations, which will have their contents reset.
In conclusion, I believe NPCs will not despawn until something causes them to die, or the location they're based in resets or respawns.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where does a Server trigger save in SQL Server?
A couple of days ago , I was practicing and I wrote some triggers like these :
create trigger trg_preventionDrop
on all server
for drop_database
as
print 'Can not Drop Database'
rollback tran
go
create trigger trg_preventDeleteTable
on database
for drop_table
as
print 'you can not delete any table'
rollback tran
But the problem is I don't know where it has saved and How can I delete or edit those.
Thank you
A:
Server Trigger
You can see them here
select * from sys.server_triggers
To drop use this syntax
drop trigger trg_preventionDrop on all server
In Management Studio they are under the "Server Objects" -> "Triggers" node
Database Trigger
You can see them here
select * from yourdb.sys.triggers
To drop use this syntax
drop trigger trg_preventDeleteTable on database
In Management Studio they are under the "Databases" -> "yourdb" -> "Programmability" -> "Database Triggers" node
A:
trigger on a particular table resides in "DataBase" -> "YourDb" -> "YourTable" -> "Trigger" folder in Management Studio
also one can find the trigger on a particular table by execution the following sql:
EXEC sp_helptrigger yourtablename
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flickering - Change CSS Background Position on Window Scroll
I'm going to rephrase my question due to lack of views. Does anyone know why modifying background-position on window scroll for Chrome and IE causes flickering sometimes?
Basically something like this will always cause flickering in Chrome and IE:
$(window).scroll(function(){$(divwithbg).css('background-position','center '+positiveinteger+px')});
Something like this never seems to flicker in any major browser:
$(window).scroll(function(){$(divwithbg).css('background-position','center '+negativeinteger+px')});
If you want to see this problem, try my sample code below, along with attached image. If you set data-parallaxdirection="0", that will be jitter free. If you set data-parallaxdirection="1", that will have jittering. I've attached the image I was using to this post.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.parallax-container {width:100%; position:relative; display:block; overflow:hidden; background-color:black; background-position:center center; background-repeat:no-repeat;}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var CONTAINER = window;
var AVAILHEIGHT;
$(document).ready(function(){
$(window).scroll(ParallaxScrollEvent);
AVAILHEIGHT = $(window).height();
$('.parallax-container').height(AVAILHEIGHT/1.1);
});
function ParallaxScroll(obj)
{
var containerTop = $(obj).position().top;
var containerHeight = $(obj).height();
var parallaxspace = parseInt($(obj).attr('data-parallaxspace'));
var goforward = parseInt($(obj).attr('data-parallaxdirection'));
var scrollTop = $(window).scrollTop() + AVAILHEIGHT;
// var links = $('.location-links'); //on contact page
if( scrollTop > containerTop)
{
var pos = 0;
if(goforward)
{
// why does this cause flickering?
var scrolled = $(window).scrollTop() - containerTop;
pos = 1.2*scrolled;
}
else
{
// why is this flicker free?
pos = -1*(scrollTop-containerTop)*parallaxspace/(2*containerHeight);
}
$(obj).css('background-position', 'center '+pos+'px');
}
}
function ParallaxScrollEvent()
{
var parallaxcontainer = $('.parallax-container');
for(var c=0; c< parallaxcontainer.length; c++)
ParallaxScroll(parallaxcontainer[c]);
}
</script>
</head>
<body>
<div class="parallax-container" style="background-image:url(images/location/2.jpg);" data-parallaxdirection="1" data-parallaxspace="800">
</div>
<div class="parallax-container" style="background-image:url(images/location/2.jpg);" data-parallaxdirection="1" data-parallaxspace="800">
</div>
<div class="parallax-container" style="background-image:url(images/location/2.jpg);" data-parallaxdirection="1" data-parallaxspace="800">
</div>
</body>
</html>
A:
I fixed the problem.
I added a background-attachment:fixed to my .parallax-container .
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scheme null? statement
Im quite new to the Scheme programming language and I just can't figure out the difference between these two pieces of code, particularly the lines I have indicated.
;program that returns the Nth element in a list where N is an integer argument
(define getElement
(lambda (N L)
(cond
((null? L) '() )
((= N 1) (car L))
(#t(getElement (- N 1) (cdr L)));this line
)
)
)
;takes a list L and a number N and returns the list L but with the first N elements removed
(define remove
(lambda (N L)
(cond
((null? L) '() )
((= N 0) L)
(#t(remove (- N 1) (cdr L)));and this line
)
)
)
Why is the output of these programs so different? I can't see what impact the 2 lines after the condition statement has on the output of the programs other than checking if the list is empty and if the integer N is a certain value, do this.
This is my first post so any advice is welcome
A:
As you say,
if the integer N is a certain value, do this
and the difference is in the "do this".
The first one,
((= N 1) (car L))
says "to get the first element of a list, take the car of the list".
The second one,
((= N 0) L)
says "to remove no elements from a list, return the entire list".
The recursions look exactly the same, but the first one reads "get element N - 1 from the cdr of the list", while the second reads "remove N - 1 elements from the cdr of the list".
(It looks like the first function has been translated from Lisp, where nil is "false-y". A more Scheme-y function would return #f.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Importing local package in another folder
I keep getting the following error and I have been trying out some of the other suggestions in other Stack Overflow threads.
./main.go:15:13: undefined: checkEnv
Folder Structure:
├── README.md
├── main.go
└── validate
└── args.go
$GOPATH
/Users/myusername/go
main.go
package main
import (
"fmt"
"log"
"os"
"projectName/validate"
"gopkg.in/urfave/cli.v1"
)
func main() {
app := cli.NewApp()
app.Name = "thirsty"
app.Action = func(c *cli.Context) error {
result := checkEnv(c.Args().Get(0))
fmt.Println(result)
return nil
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
validate/args.go
package validate
import "strings"
func checkEnv(environment string) bool {
env := strings.ToLower(environment)
return env != "qa" && env != "dev"
}
My project is in the src directory of my $GOPATH. If this is not the proper way to do code splitting, is there a generally used convention to follow?
Any feedback appreciated.
A:
There are two problems here.
The checkEnv method is not exported [in validate/args.go]. ie it is usable only inside the same package and not other packages To export just capitalize the first letter of the method CheckEnv. Now CheckEnv can be used from other packages
While calling a method from other package, the syntax should be packagename.ExportedMethod(params...). so in your code [in main.go] it should be result := validate.CheckEnv(c.Args().Get(0))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to implement a HTTPS login page in a web application?
I want to create a secure login/logout mechanism. I started reading the following articles to get an idea of things to take into account:
Solving the Logout Problem Properly and Elegantly
Revisiting the logout problem
These articles make some good points, but I was thinking in using HTTPS in a similar way as the Yahoo mail login page. You know... you type http://mail.yahoo.com and you are redirected to a HTTPS page like **https://**login.yahoo.com/config/login where you insert your username and password and after your credentials are verified you are redirected back to a HTTP page with a generated session_id cookie and all communications from there on are on HTTP using the cookie.
What do I need to implement this behavior?
I want to do this for two Java web apps (one with Spring framework and one with Struts 1) but don’t know exactly how to integrate that HTTPS part into the application (I have never worked with HTTPS before).
A:
First of all you need to enable SSL for your server. For Tomcat you need to generate an openSSL keystore and add the following connector to server.xml:
<Connector port="8443" scheme="https" secure="true" SSLEnabled="true"
keystoreFile="mykeystore" sslProtocol="TLS"
keystorePass="keystore password" />
To integrate SSL into your application I recommend Spring Security. It offers exactly what you want (login over HTTPS, then redirected to HTTP). All you have to do to implement it, is to set forceHTTPS to true:
<bean id="authenticationProcessingFilterEntryPoint"
class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint">
<property name="loginFormUrl" value="/pages/login.jsp" />
<property name="forceHttps" value="true"/>
</bean>
Of course Spring and Spring security do have a rather steep learning curve, but it is totally worth it. Do it once and then you can apply it to new apps in less than an hour. You can use Spring Security in both the Spring and Struts application.
Spring security used to be Acegi security. This is an article that will get you started.
A:
Not sure about any Java or spring specifics, but in general:
1) Set up an SSL cert on your server.
2) Forward or Link to an absolute URL (with https:// at the beginning) when going to login page
3) Forward to an absolute URL (with http://) after successful authentication.
4) Include a check in the login page code to only accept https connections.
Of course there may be framework specific ways of doing the http/https redirect without resorting to explicitly specifying the full URL.
A:
@see Acegi (spring security)
I think it provides all required components. For example it supports login via https. There is a good reference. How to get https login you can read here. I think you should read all.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
string.match() returns a String instead of an Array
I've been using Javascript string.match(*regex*) function to parse the navigator.userAgent string.
FYI, According to MDN & W3schools:
"The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object."
I first parse once to get the wanted strings for the base string:
var userAgent = navigator.userAgent;
var splitted = userAgent.match(/[(][^)]+[)]|\w+\/\S+/ig);
Which gives me the following Output (Which is an Array)
Mozilla/5.0
(Macintosh; Intel Mac OS X 10_10_3)
AppleWebKit/537.36
(KHTML, like Gecko)
Chrome/41.0.2272.76
Safari/537.36
Then i parse the Navigator/Version type strings in a for loop
for (var i = 0; i < splitted.length; i++ ) {
var str = splitted[i];
if (str[0] == '(') {
} else {
var name = str.match(/[^\/]+/i);
var version = str.match(/[0-9|\.]+/i);
}
But, very surprisingly and even though I get the desired result, I get a String Object for the name and an Array Object for the version
How is it even possible ?
Here's the snippet of the code (fiddle):
var userAgent = navigator.userAgent;
var splitted = userAgent.match(/[(][^)]+[)]|\w+\/\S+/ig);
var outputDiv = document.getElementById("log");
for (var i = 0; i < splitted.length; i++ ) {
var str = splitted[i];
if (str[0] == '(') {
} else {
var name = str.match(/[^\/]+/i);
var version = str.match(/[0-9|\.]+/i);
outputDiv.innerHTML += name.toString() + " is a " + typeof(name) + "<br>";
outputDiv.innerHTML += version.toString() + " is a " + typeof(version) + "<br>";
}
};
<div id="log"></div>
--- UPDATE ---
Thanks FactoryAidan for the answer, it was a scope problem.
Conclusion: be careful when naming global variables :)
A:
Global Variable Scope
It is because you are using name as your variable. This is a global browser window variable that is inherently a string and cannot be stored as an Array
Even if you redeclare it with var name =, you are still in the global scope. And thus name (aka window.name) simply retains the last value you assign to it.
You can test this with the following on an empty page without defining any variables at all:
console.log(name===window.name) // Returns true
console.log(name,window.name) // Returns 'Safari Safari' for my browser
Change name to something else
If you change your name variable to simply have a different name, like my_name, it stores the result of .match() as an Array.
var my_name = str.match(/[^\/]+/i);
var version = str.match(/[0-9|\.]+/i);
console.log(typeof my_name, my_name instanceof Array) // Returns object, true
Change Scope by wrapping in a function
This is your exact code wrapped inside a function and returns the correct variable types:
function getBrowserStuff(){
var userAgent = navigator.userAgent;
var splitted = userAgent.match(/[(][^)]+[)]|\w+\/\S+/ig);
for (var i = 0; i < splitted.length; i++ ) {
var str = splitted[i];
if (str[0] == '(') {
} else {
var name = str.match(/[^\/]+/i);
var version = str.match(/[0-9|\.]+/i);
console.log('Name','Typeof '+(typeof name), 'IsArray '+(name instanceof Array),name)
console.log('Version','Typeof '+(typeof version),'IsArray '+(version instanceof Array),version)
}
}
return 'whatever'
}
getBrowserStuff()
Changing the variable name to my_name OR wrapping code like the above function returns this:
Name Typeof object IsArray true ["Mozilla"]
Version Typeof object IsArray true ["5.0"]
Name Typeof object IsArray true ["AppleWebKit"]
Version Typeof object IsArray true ["600.3.18"]
Name Typeof object IsArray true ["Version"]
Version Typeof object IsArray true ["8.0.3"]
Name Typeof object IsArray true ["Safari"]
Version Typeof object IsArray true ["600.3.18"]
Where before it returned this:
Name Typeof string IsArray false Mozilla
Version Typeof object IsArray true ["5.0"]
Name Typeof string IsArray false AppleWebKit
Version Typeof object IsArray true ["600.3.18"]
Name Typeof string IsArray false Version
Version Typeof object IsArray true ["8.0.3"]
Name Typeof string IsArray false Safari
Version Typeof object IsArray true ["600.3.18"]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Given $\gamma(t)$ a $\mathcal{C}^1$ path on $\mathbb{C}^{\times}$, why is it true that $|\gamma(t)|$ is also $\mathcal{C}^1$?
Suppose $\gamma:[0,1]\to\mathbb{C}^{\times}$ is continuously differentiable, there is a proof I saw involved using the fact that $s(t)=|\gamma(t)|$ must also continuously differentiable but I cannot quite convince myself why this is the case. (Of course, the differentiability of $s(t)$ is in the sense of real-variables.)
So we want to show that $\lim_{h\to 0}\frac{|\gamma(t+h)|-|\gamma(t)|}{h}$ exist given $\gamma(t)$ is continuously complex differentiable. I have thought about using a bit of triangle inequality and manipulation, one can obtain $$\lim_{h\to 0}\frac{|\gamma(t+h)|-|\gamma(t)|}{h}\leq \lim_{h\to 0}\frac{|\gamma(t+h)-\gamma(t)|}{h}$$
Now I am a bit stuck, I think we can say since $\gamma(t)\in \mathcal{C}^1$ then $\lim_{h\to 0}\frac{|\gamma(t+h)-\gamma(t)|}{h}$ must exist, but what is next?
I can see the statement to be true but I wanted to construct something that is more concrete.
Many thanks in advance!
A:
The absolute value function from $\Bbb C\setminus\{0\}$ into $\Bbb R$ is real-differentiable everywhere, and its derivative is continuous; in other words, it's a class $C^1$ function. So, $t\mapsto|\gamma(t)|$ is the composition of two class $C^1$ functions, and thereforeit is a class $C^1$ function too..
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sinatra Rspec - testing that a view has rendered
I am writing tests for a Sinatra app that takes input from an API via a gem. Once I have the API response I need to test that the template has correctly rendered. The response of the API will be the HTML of the page that I am loading.
My first instinct was to write a test that looks like this:
describe 'the root path'
it 'should render the index view' do
get '/'
expect(last_response).to render_template(:index)
end
end
Unfortunately when I try this I get the following error: undefined method `render_template'
I was wondering if anyone has encountered this problem - it seems like it should be an easy fix, but I can't seem to find any documentation to help with it.
A:
I'm currently not testing views at all because of time constraints, but I did have some limited successs with Rack::Test.
In theory you can say:
require 'rack/test'
include Rack::Test::Methods
def app
Sinatra::Application
end
describe 'it should render the index view' do
get '/'
expect(last_response).to be_ok
expect(last_response.body).to eq(a_bunch_of_html_somehow)
end
If I were to go this road again, since my views are haml, I could implement the a_bunch_of_html_somehow method using a call to Haml::Engine -- but I'm not sure whether that helps you.
I'm lifting this wholesale from the Sinatra site here -- the page is well worth a read.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Grails compilation error: unable to resolve class JSON
I have the following setup, grails 2.0.3, STS, and I'm doing this in one of my controllers:
render(['car': contactL] as JSON)
When I run the application I get the following error:
I have read about the error, but none of the solutions have worked for me, I have tried cleaning, upgrading, using the Grails Tools -> Refresh dependencies but it gave me:
grails> | Error Error running script null: Cannot invoke method trim() on null object (Use --stacktrace to see the full trace)
I'm also getting this error in my project:
The project was not built since its build path is incomplete. Cannot find the class file for groovy.lang.GroovyObject. Fix the build path then try building this project Ristretto Unknown Java Problem
What's you diagnose?
A:
To fix the "unable to resolve class JSON" error, you should just have to import it:
import grails.converters.JSON
...
class MyController {
...
render [car: contactL] as JSON
A:
I finally managed to get it working, I switched workspace, and added my project - problem solved.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to load any attributes without using the Mapping ' lazy: false' in Grails
Constantly faced with a problem when I need to compare and manipulate objects that reference other objects. For example:
Class Student {
...
String Name
Integer Age
...
}
Class Stuff {
...
Student student
...
}
When I invoke an instance of Stuff (Stuff.get (id)/load(id)) and will access the Name, Age and other attribute I see in debug mode (stuff .name = null, they're like 'null' although they are not null. It
command when analyzing values of these attributes (stuff
.name == "pen") error occurs.
I need to invoke the instances and compare their values to execute business rules, but do not know how to resolve this issue.
I read something about the inclusion in the configuration Stuff Mapping 'student lazy: false' for all the time you need to load the instance ofstuff , also charge the Student, but that in addition to overload the memory (since stuff is a Domain Great) would solve this case being the only solution to put all references as 'lazy: false' which would slow the application just to make a simple comparison.
Does anyone know how to invoke instances (Stuff), automatically invoking the attribute to be working (student) just to make the comparison of data, without using the 'student lazy: false' that invokes the data at all times?...
Using Grails 2.2.0 e o Groovy 2
A:
Stuff don't have a property called name so you should get MissingPropertyException calling stuff.name. This has nothing to do with the lazy or eager relationship.
You can check the definition of a lazy relationship in the documentation and also the difference between the types of fetch.
To access the name property you need to access the student property before:
Stuff instance = Stuff.get(id)
println instance.student.name //this, if lazy, will trigger a new database query.
If you know that your code will access the Student instance by the relation with Stuff you could fetch both in one database access (eager and not lazy):
Stuff instance = Stuff.withCriteria {
eq('id', id)
fetchMode("student", FetchMode.JOIN)
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why the kernel is a normal subgroup?
Let $G$ be a group acting on a nonempty set $A$. Why the kernel of the action is a normal subgroup of $G$?
A:
Let $\;\phi:G\to H\;$ be a group homomorphism, and let $\;x\in\ker\phi\;,\;\;g\in G\;$ , then
$$\phi(g^{-1}xg)=\phi(g^{-1})\phi(x)\phi(g)=\phi(g)^{-1}\cdot1\cdot\phi(g)=\phi(g)^{-1}\phi(g)=1\implies$$
$g^{-1}xg\in \ker\phi\;$ whenever $\;x\in\ker\phi\;,\;\;g\in G\;\iff\;\ker\phi\lhd G$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
403 Forbidden Error for Joomla administrator
Let me preface this with, only one user is having this issue. Everyone else can log-in to the Joomla administration just fine.
Originally when I found that the single user was receiving a 403 when landing on the administrator page, I checked to make sure all directories were writable as per the directories listed under Site Information. I've also confirmed that the administrator directory has 755 permissions, and that the user has cleared her cache.
Also, the site was recently moved from one server to another. Changed the A record on the old server to the IP of the new server.
Thoughts as to why a single user would receive a 403 error only in the Joomla administration page?
A:
After chat discussion, it turns out that the server has been moved recently and since then the problem started.
The problem seems to be cached dns on the user's side, so the user has to clear dns cache, or wait for the provider to clear dns cache
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make interactive legends label using shiny?
So, i'm starting to use shiny and making interactive plots.
So far, i've made my first and it looks like this:
The code that i used for this plot was
ui <- fluidPage(titlePanel("Suicide Numbers Per 100k"),
sidebarLayout(sidebarPanel(selectInput("region","Region",choices = unique(df$Country))),
mainPanel(plotOutput("country100kplot"))))
server <- function(input,output){
output$country100kplot <- renderPlot(df%>% filter(Country == input$region) %>% ggplot(aes(x=Year,y=Suicides_per_100k,colour=Generation))+geom_line()+labs(x="",y="Suicides",title = "")+theme(plot.title = element_text(hjust = 0.5)))
}
shinyApp(ui,server)
Here, im only using dpyr,ggplot2 and shiny packages. We have a line plot for each generation ( and the user can select the country ), but the plot can be very noisy as you can see.
Say i only want to see the "Boomer" generation line; i would unmark all the other generation to see only this line plot. How can i do that?
EDIT: I tried to use ggplotly. It worked well for general plots. But i don't know why, it doesn't appear on the Shiny. The ggplotly only appears in my R Viewer, and on the shiny, it shows the original ggplot2 plot:
A:
The reason why this won't appear in Shiny with your current code is that you need to use a separate wrapper for plotly objects. I do not have access to the data you used but here is how I would adjust your code in order for this to work.
Main thing to note is the use of plotlyOutput() in the UI and renderPlotly in the Server section.
library(shiny)
library(tidyverse)
library(plotly)
ui <- fluidPage(titlePanel("Suicide Numbers Per 100k"),
sidebarLayout(sidebarPanel(selectInput("region","Region",choices = unique(df$Country))),
mainPanel(plotlyOutput("country100kplot"))))
server <- function(input,output){
output$country100kplot <- renderPlotly({
g <- df%>%
filter(Country == input$region) %>%
ggplot(aes(x=Year,y=Suicides_per_100k,colour=Generation))+
geom_line()+
labs(x="",y="Suicides",title = "")+
theme(plot.title = element_text(hjust = 0.5))
g <- ggplotly(g)
})
}
shinyApp(ui,server)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL : Retrieve inserted row IDs array / table
i have the following statement:
INSERT INTO table1 (field1, FIELD2)
SELECT f1, f2 FROM table2 -- returns 20 rows
after insert i need to know the array/table of IDs generated in table1.ID which is INT IDENTITY
thanx in advance.
A:
Use the OUTPUT clause (SQL2005 and up):
DECLARE @IDs TABLE(ID int)
INSERT INTO table1(Field1, Field2)
OUTPUT inserted.ID into @IDs(ID)
SELECT Field1, Field2 FROM table2
If you want to know exactly which rows from table2 generated which ID in table1 (and Field1 and Field2 aren't enough to identify that), you'll need to use MERGE:
DECLARE @IDs TABLE(Table1ID int, Table2ID int)
MERGE table1 AS T
USING table2 AS S
ON 1=0
WHEN NOT MATCHED THEN
INSERT (Field1, Field2) VALUES(S.Field1, S.Field2)
OUTPUT inserted.ID, S.ID INTO @IDs(Table1ID, Table2ID)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Google maps API map - initialise script in body not head, map not appearing
I am trying to add a google map to a page which is pre-defined and protected, so I can only add code to the body section. I've put the script at the bottom of the page and used the code for asynchronous loading from google's tutorial but, well, my div remains sadly empty. I suspect the API is not loading but have no clue how to check that. Any ideas please?
Thanks!
<div id="map_canvas" style="width: 650px; height: 350px;">
</div>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyDOtp_8dtVzG4kEJEzLw7E5bC187DagTRg&sensor=FALSE&callback=initialize";
}
window.onload = function(){loadScript();};
</script>
A:
1. you must insert the script-element into the document, otherwise the script will not execute:
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
2.the sensor-parameter(true or false) must be lowercase
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need a really simple navigation controller with a table view inside a tab bar controller
I have an app with a tab bar controller (2 tabs). In one tab view controller, a button leads to an alert window. I want one button of the alert window to call a table view containing possible answers. I want that table view to have a done button and a title. I think that means a navigation controller has to be used. But most everything I can find on navigation controllers assumes a much more complicated situation. Here's part of the alert window logic:
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 2) {
AnswersViewController *aVC = [[AnswersViewController alloc] init];
[self presentViewController:aVC
animated:YES
completion:NULL];
}
}
And AnswersViewController looks like this:
@interface AnswersViewController : UITableViewController
@end
@implementation AnswersViewController
- (id) init
{
self = [super initWithStyle:UITableViewStylePlain];
return self;
}
- (id) initWithStyle:(UITableViewStyle)style
{
return [self init];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[self view] setBackgroundColor:[UIColor redColor]];
}
@end
This code all works as expected (an empty red UITableView appears).
Two questions I guess: 1. Is there a simple modification to what I have that can give me a done button and title in my table view? 2. If I have to go to a navigation controller (probably), how can I make a bare-bones navigation controller with a done button and title and embed the table view within it? Oh, and I want to do this programatically. And I think I prefer the done button and title to be in the navigation bar, no tool bar desired. Thanks!
A:
To get what you are looking for, you do need to use a UINavigationController. That will provide the UINavigationBar where you can display a title and also buttons.
To implement this with a UINavigationController, you want to do smoothing like this (assuming you are using ARC, so you don't need to worry about memory management):
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 2) {
AnswersViewController *aVC = [[AnswersViewController alloc] init];
//Make our done button
//Target is this same class, tapping the button will call dismissAnswersViewController:
aVC.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissAnswersViewController:)];
//Set the title of the view controller
aVC.title = @"Answers";
UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:aVC];
[self presentViewController:aNavigationController
animated:YES
completion:NULL];
}
}
Then you would also implement - (void)dismissAnswersViewController:(id)sender in the same class as the UIAlertView delegate method (based on the implementation I have here).
Hope this helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Check existence of duplicated items with XQuery
I'm doing some exercises on XQuery and I can't figure out how to deal with this problem.
Let's say I have a FileSystem structured like this DTD: (Unspecified elements only contain PCData)
<!ELEMENT RootFolder ( File | Folder )* >
<!ELEMENT File ( Name, Type, Size, CreationDate, OwnerId )>
<!ELEMENT Folder ( Name, CreationDate (File | Folder)* ) >
How can I write a function that returns true/false checking whether the names of every resource (files and folders) are such that all of them have a distinct pathname?
A:
Instead of checking for uniqueness, you could check for duplicates by checking to see if a Folder or File has a sibling with the same Name...
declare variable $in :=
<RootFolder>
<Folder>
<Name>user</Name>
<File>
<Name>Fred</Name>
</File>
<File>
<Name>Bill</Name>
</File>
<File>
<Name>Fred</Name>
</File>
</Folder>
<Folder>
<Name>manager</Name>
<File>
<Name>Jane</Name>
</File>
<File>
<Name>Mary</Name>
</File>
<File>
<Name>Jane</Name>
</File>
</Folder>
</RootFolder>;
declare function local:hasDupe($ctx as element()) as xs:boolean {
boolean($ctx//(File|Folder)[Name=following-sibling::*/Name])
};
local:hasDupe($in)
This would return true.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
pgadmin 4 3.1 retiling data output panel
In the Query Tool, when trying to raise or lower the border between Query Sql Editor and Data Output Panel it is very common that when you move the mouse over the Data Output panel's header it changes the vertical - horizontal arrow icon to a cross arrow changing Data Output panel from its default tiling to floating
What should I do to return the Data Output panel to its initial tiling mode?
In addition, Data Output panel once in floating window stops showing queries's results, it only shows the messages, I suppose it's 3.1's bug.
My solution so far is to save the query, close it and reopen it to recover its tiling mode
Cursor's disappearance problems have not been corrected in full
What is the best free competitor of pgadmin 4?
A:
In the pgadmin browser, click on the File menu and select reset layout.
Yes, will get all kinds of warnings, but the query tool returns to being useful.
A:
I don't know in PgAdmin 4.3, but in 4.6 I found that way to re-arrange it.
First, right-click on somewhere to Add Panel -> Scratch Pad first to get a panel holder first (when clicking, notice the highlighted light blue space),
then right-click the lower half space to add another panel -> Scratch Pad at the lower half space (when clicking, notice the highlighted light blue space),.
After that, click on the tab and hold to drag and drop to where you want (when clicking, notice the highlighted light blue space).
A:
No this is not a bug, those panels are meant to be floatable so that user can arrange the view as per their convince.
But yes user should have the option to lock the layout, and I see feature request for locking the layout is already in the pgadmin4 list.
Hopefully, we will get it in the next future release.
Ref: https://redmine.postgresql.org/issues/3155
------ UPDATE -----
Now you can lock the layout in pgAdmin4 (File menu -> Lock layout) option
To reset the panels to default position (File manu -> Reset Layout) option
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex to work on XML tags - Help needed
I have some pseudo-XML which I'm trying to clean up, and I'm most of the way there, but there's a problem with casing in tags.
My source looks like this...
<?xml version="1.0" encoding="UTF-8"?>
<root>
<float_node>1.0</float_node>
<text_node>Pack My Box</text_node>
<UPPER_NODE>With Five Dozen</UPPER_NODE>
<MiXeD_NoDe>SCSG1</MiXeD_NoDe>
<!-- Comment should not be changed -->
<GRANDPARENT>
<PARENT>
<Child1>Liquor Jugs</Child1>
<Child2 with-attribute="Pangrams">Jackdaws Love</Child2>
</PARENT>
<PARENT>
<Child1>My Big Sphinx</Child1>
<Child2 with-attribute="Are Great">Of Gold</Child2>
</PARENT>
</GRANDPARENT>
</root>
but what I want is this...
<?xml version="1.0" encoding="UTF-8"?>
<root>
<float_node>1.0</float_node>
<text_node>Pack My Box</text_node>
<upper_node>With Five Dozen</upper_node>
<mixed_node>SCSG1</mixed_node>
<!-- Comment should not be changed -->
<grandparent>
<parent>
<child1>Liquor Jugs</child1>
<child2 with-attribute="Pangrams">Jackdaws Love</child2>
</parent>
<parent>
<child1>My Big Sphinx</child1>
<child2 with-attribute="Are Great">Of Gold</child2>
</parent>
</grandparent>
</root>
So far I have this pattern...
<(.+)( .+)?>(.*)<\/\1>
and this substitution...
<\L$1$2>$3</\L$1>
but the output is wrong...
<?xml version="1.0" encoding="UTF-8"?>
<root>
<float_node>1.0</float_node>
<text_node>pack my box</text_node>
<upper_node>with five dozen</upper_node>
<mixed_node>scsg1</mixed_node>
<data_format>excel</data_format>
<!-- Comment should not be changed -->
<GRANDPARENT>
<PARENT>
<child1>liquor jugs</child1>
<child2 with-attribute="pangrams">jackdaws love</child2>
</PARENT>
<PARENT>
<child1>my big sphinx</child1>
<child2 with-attribute="are great">of gold</child2>
</PARENT>
</GRANDPARENT>
</root>
The \L lowercasing is being applied to the tag content and attribute as well as the tags, even though the substitution string has $2 and $3 distinct and unaltered.
Nested nodes are overlooked. Only the innermost node is altered. How should I manage the hierarchy?
Can anyone tell me where my pattern or substitution is failing?
I'm using Regex101 for help with building the regex pattern and testing... https://regex101.com/r/Oeshto/3
(I'm using Notepad++ to do the actual work since my preferred editor (VSCode) doesn't handle the required \L conversion.)
A:
Here are the regular expressions to suit your needs. I'm sure some reg-ex wizard could optimise or make these better but they seem to get the job done. (Edited, I have removed my suggestion on the PEAR package as it was utterly nonsense when you asked for a regular-expression only)
Regular Expression.: /(<\/?[^!][^>]+)/g ( Change all tags+attributes )
Regular Expression.: /(<\w+|<\/\w+)/g ( Change only tags )
Substitution.......: \L$1
Don't forget the Global flag so it won't return after first result.
This should match all tags.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way to use C++/CLI managed Enums as array subscripts?
i have an enum declared as
enum class AccessLevel : int
{
ReadOnly = 0,
Excluded = 1,
ReadWrite = 2,
};
and an Array declared as
static array<String^>^ _accessMap = gcnew array<String^> { "R", "X", "W" };
I want to do something like this:
AccessLevel^ access = access::ReadOnly;
String^ foo = _accessMap[access];
A:
public enum struct AccessLevel
{
ReadOnly = 0,
Excluded = 1,
ReadWrite = 2,
};
AccessLevel access = access::ReadOnly;
you might need to cast to an int
String^ foo = _accessMap[(int)access];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do I need a mutex when replacing the value of a string in different goroutines?
Do I need a mutex in this case? I am refreshing the token with a goroutine, the token is used in another goroutine. In other words, will my token be empty at some point so that the response will be a 401?
If yes, is it part of the structure c *threatq or is it a simple variable, I mean, a "standalone" one inside my code.
// IndicatorChannelIterator returns indicators from ThreatQ into a channel.
func (c *threatq) IndicatorChannelIterator() (<-chan *models.Indicator, error) {
// Authenticate
token, err := c.authenticate(c.clientID, c.email, c.password)
if err != nil {
return nil, fmt.Errorf("Error while authenticating to TQ : %s", err)
}
// Periodically refresh the token
ticker := time.NewTicker(30 * time.Minute)
go func() {
for range ticker.C {
token, err = c.authenticate(c.clientID, c.email, c.password)
if err != nil {
logrus.Errorf("Error while authenticating to TQ : %s", err)
}
}
}()
// Prepare the query
query := &Query{}
// Get the first page
firstTQResponse, err := c.advancedSearch(query, token, 0)
if err != nil {
return nil, fmt.Errorf("Error while getting the first page from TQ : %s", err)
}
// Create the channel
indicators := make(chan *models.Indicator)
// Request the others
go func() {
req := 1
total := firstTQResponse.Total
for offset := 0; offset < total; offset += c.perPage {
// Search the indicators
tqResponse, err := c.advancedSearch(query, token, offset)
if err != nil {
logrus.Errorf("Error while getting the indicators from TQ : %s", err)
continue
}
...
A:
The rule is simple: if a variable is accessed from multiple goroutines and at least one of them is a write, explicit synchronization is needed.
This is true in your case: one of your goroutine writes the token variable (and also the err variable!), and another reads it, so you must synchronize access.
Since token is not a field of the threatq structure, putting the mutex that protects it would not be wise. Always put the mutex close to the data it ought to protect.
Some notes: as mentioned earlier, you also write and read the local err variable from multiple goroutines. You should not do this, instead create another local variable to hold the error from other goroutines (unless you want to "translfer" the error between goroutines, but this is not the case here).
See related questions:
Immutability of string and concurrency
Should we synchronize variable assignment in goroutine?
golang struct concurrent read and write without Lock is also running ok?
Reading values from a different thread
Why does this code cause data race?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Extend a Swagger Response Type at Swagger UI
I have the following like this below format for Example Value at Swagger UI:
{
"Username": "string",
"Interest": "string",
"Position": "string"
}
And here is the following for the Response Body at Swagger UI:
{
"ErrorCode": "0",
"ErrorMessage": "Success.",
"Result": [
{
"Username": "Test",
"Interest": "Test",
"Position": "Test"
}
]
}
My question is, how can I make the Example Value at Swagger UI to be like the Response Body at Swagger UI?
Here is the code that I am using:
Model class:
public class ActionResultExtended
{
public string ErrorCode { get; set; }
public string ErrorMessage { get; set; }
public object Result { get; set; }
}
public class User
{
public string Username { get; set; }
public string Interest { get; set; }
public string Position { get; set; }
}
Controller class:
[ResponseType(typeof(User))] // This is where the Example Value comes from
public HttpResponseMessage GetUser()
{
var userModel = new User
{
Username = "Test",
Interest = "Test",
Position = "Test"
};
var response = new ActionResultExtended()
{
ErrorCode = "0",
ErrorMessage = "Success.",
Result = userModel
};
return Request.CreateResponse(HttpStatusCode.OK, response);
}
I have tried the following, but it couldn't work as expected.
[ResponseType(typeof(ActionResultExtended))]
How can I extend the ResponseType attribute from Web API? So that I can make it like the Response Body instead of the Example Value at Swagger UI.
Any help would be appreciated. Thanks
A:
I have solved it by modifying my model class like this:
Model class:
public class ActionResultExtended
{
public string ErrorCode { get; set; }
public string ErrorMessage { get; set; }
public User Result { get; set; }
}
public class User
{
public string Username { get; set; }
public string Interest { get; set; }
public string Position { get; set; }
}
And from the ResponseType attribute set it like this:
[ResponseType(typeof(ActionResultExtended))]
This way, the Example Value in Swagger UI will be same like Response Body in Swagger UI:
{
"ErrorCode": "0",
"ErrorMessage": "Success.",
"Result": [
{
"Username": "Test",
"Interest": "Test",
"Position": "Test"
}
]
}
Thank you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
sort sorted list as data table order
i fill sorted list from ordered datatable but after fill sorted list my order changing
for (int i = 0; i < d.Rows.Count; i++)
{
int EmpID = Convert.ToInt32(d.Rows[i]["Fd_Emp"].ToString().Trim());
string type=d.Rows[i]["Fd_Type"].ToString().Trim();
emp.Add(EmpID, type);
}
my datatable order is 31e,32e,33e,7i
my sortedlist order become 7i,31e,32e,33e
how to keep my datatable order in my sorted list
A:
The idea of using a sorted list is that it keeps the added elements in a sorted order. This means that if the elements in the database are not sorted (or not sorted the same way as the sorted list sorts) the elements in the sorted list will have a different order
If the values in the DB are sorted and you want to get the same ordering from your sorted list, you can provide a custom sorting method for your elements, in which you duplicate the comparison logic that the DB uses for its values.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linear transformation of an infinitesimal rectangle
Consider the linear transformation of two random variables
$V=aX+bY$
$W=cX+eY$
or
$\begin{bmatrix}V\\W \end{bmatrix} $$=\begin{bmatrix}a &b \\ c& e\end{bmatrix}$$\begin{bmatrix}X\\Y \end{bmatrix} $
Consider the infinitesimal rectangle shown in the figure below. The points in this rectangle are mapped into the parallelogram.
I don't understand how the point $(x+dx,y)$ from the rectangle becomes $(v+a dx,w+c dx)$in the parallelogram.
A:
Your transformation is
$$(v;w)=T(x;y)=(ax+by; cx+ey)$$
i.e, $\mathbf v=\mathbf{ax+by}$ and $\mathbf w=\mathbf{cx+ey}$.
Then, applying the transformation in the vector $(x+dx,y)$:
$$T(x+dx;y)=(a(x+dx)+by;\ c(x+dx)+ey)$$
$$ = (\mathbf{(ax+by)}+adx;\ \mathbf{(cx+ey)}+cdx)=(\mathbf v+adx;\ \mathbf w+cdx) $$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iOS:Switching between views using UINavigationBarController
First of all, I am using XCode 4.2 and I am not using storyboards. I need to make an application with 2 views.
First view will contain a button and a navigation bar, the button's IBAction should only go to the second view, and from the secondview you should be able to go back to the first view via the Navigationbar.
My problem is the navigation controller / navigation bar, how do I set that up ?
I know that it would be smart using the singleView app and then add a navigation controller, the problem is that I dont know how to set it up in the code.
I have searched for similar problems on the internet, and I keep getting into posts where they use another SDK or using an older xcode etc.
What I do know is how to make the button, actions and delegation.
Anyone out there who is sitting with the one and only tutorial I am missing or can tell me how to do it ?
Thank you
A:
Use the Master-Detail Application template. Ignore the stuff for tables, it has navigation stack implemented in it. By deleting the tables, you should be pretty much left with what you are after.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A file reading-writing exception handling by adding a log record to a file
I'd like to write a log record in case of a failed attempt of a file reading(writing) operation, something like:
try
{
//some file operation, for example:
TextReader tr2 = new StreamReader(nfilepath);
resultN = tr2.ReadLine();
tr2.Close();
}
catch (Exception ex)
{
string recfilepath = "...
string rectoadd = "RecDateTime=" + DateTime.Now.ToString()+ ...+ex.Message.ToString();
File.AppendAllText(recfilepath, rectoadd);
}
Is this a correct way of doing that? What if in the above example the attempt of writing a log record (File.AppendAllText(recfilepath, rectoadd);) fail as well?
A:
Never catch Exception type - by this way you hide program bugs. Catch only expected exception types - in this case, it can be IOException.
Inside catch block, you can add another try-catch block, and report logging error by some another way: Trace, message box etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
abort currently running job in Salesforce
Is there a way to abort currently running batch job in Salesforce? I tried to run the query below and all it did was remove all jobs from Scheduled Jobs section without stopping the one that is currently running in the background. Please help. I would like to do it without contacting Salesforce support
List<CronTrigger> jobsToAbort = [select Id from CronTrigger where CronJobDetail.JobType = '7'];
for (CronTrigger job : jobsToAbort) { System.abortJob(job.Id); }
A:
Please run a SOQL query on AsyncApexJob with Status filter. CronTrigger is used to retrive Scheduled jobs wherein AsyncApexJob returns Apex Jobs (Running, Aborted, Pending, Completed etc.)
SOLUTION:
Use Below Code:-
for ( AsyncApexJob aJob : [ Select id ,Status, ApexClass.Name
from AsyncApexJob where Status!='Aborted'
and Status!='Completed' ] ){
System.AbortJob(aJob.Id);
}
A:
Went to SetUp --> Monitoring --> Apex Jobs. There was Abort option :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find Solutions To Some Diophantine Equations
I would like to find the solutions to
$$i)\qquad a(a+b+c)=bc \\ii)\qquad a(a+b+c)=2bc \\iii)\qquad a(a+b+c)=3bc$$
for $0< a \le b \le c$ and of course: $\textrm{gcd}(a,b,c) = 1$ (since those are the interesting cases).
To be honest, Diophantine equations seem like a black art. Guess and check has always been the only sure method that I can understand.
At least the last case ($iii$) seems to be "easy" as the only solution is apparently $ a = b= c=1$. I don't see how to prove this though.
For $i$, I've found solutions such as: $\{\{1,2,3\}, \{2,3,10\}, \{3,4,21\}, \{3,5,12\}, \ldots\}$
And For $ii$, I've found solutions such as: $\{\{1,1,2\}, \{4,5,6\}, \{15,20,21\}, \{20,22,35\}, \ldots\}$
Notwithstanding my ability to exhaust over integers, I don't have any deeper understanding of what is going on here mathematically. I would really like to understand these better and would appreciate some help! Thanks in advance!
A:
One can give a parameterization to,
$$a(a+b+c) = nbc\tag{1}$$
However, since you want $0<a<b<c$, this makes it trickier.
For $n=1$: A look at your solutions and one can see that $a,b$ are in arithmetic progression. Hence,
$$a,\;b,\;c = n,\;n+1,\;2n^2+n$$
For $n=2$: Most of your $b,c$ differ by one. Hence,
$$a,\;b,\;c = 2pq,\;p^2+pq-1,\;p^2+pq$$
where $p,q$ solve the Pell equation $p^2-3q^2=1$. Since $pq<p^2$, this guarantees that $a<b$.
For $n\ge3$: I checked this with Mathematica and, curiously, there doesn't seem to be any.
P.S. Without the inequalities, then $(1)$ has a two-parameter solution,
$$a,\;b,\;c = (-u + n v)u, \; (u + v)u, \; (-u + n v)v$$
Edit: This answers the comment below. First, we do the substitution $b,\;c = x+y,\;x-y\,$, on $(1)$ then solve for $a$,
$$a =-x\pm\sqrt{(n+1)x^2-ny^2}$$
Thus we have to solve, as W. Jagy pointed out, a ternary quadratic form,
$$(n+1)x^2-ny^2=z^2$$
and initial solution of which is $x,y,z =1,1,1$. Given an initial solution, we generally can find an infinite more. Two methods are described here in Form 2b.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
displaying a generic list two list items per row when using a foreach loop
I have a generic list of objects that's passed to a view. Currently, each list item is displayed to the user row-by-row:
@foreach (var result in Model.SearchResults)
{
result.Address.TownCity
// ...
}
So each list item is displayed in its own row. Aesthetically this doesn't look the best, as there's quite a lot of white space left over.
What I want to do is something like this:
row 1 | list item 1 | list item 2
row 2 | list item 3 | list item 4
and so on.....
Is this something I have to do server-side i.e. put half of my list into another list and in the view have two foreach loops - each one filling a column, row-by-row? Or is there anyway this can be done in the view using razor?
A:
You can do this to group each set of rows into 'batches' and then loop through each item in the batch.
@{
var batches = Model.SearchResult
.Select((x, i) => new { x, i })
.GroupBy(p => (p.i / 2), p => p.x);
}
@foreach(var row in batches)
{
<span>Row @row.Key</span>
@foreach(var item in row)
{
<span>| @item.Address.TownCity</span>
}
}
Alternatively you can use this; it's simpler, though a bit less elegant
@{
var resultArray = Model.SearchResult.ToArray(); // only necessary if SearchResult is not a list or array
}
@for(var i = 0; i < resultArray.Length; i++)
{
var item = resultArray[i];
if (i % 2 == 0)
{
<span>Row @(i / 2)</span>
}
<span>| @item.Address.TownCity</span>
}
A:
This is very easy to do in CSS without adding additional load and complexity to your code
See this fiddle: http://jsfiddle.net/taBec/
@foreach (var result in Model.SearchResults)
{
<div class="box">@result.Address.TownCity</div>
}
Then in CSS:
.box { width: 150px; float: left; height:25px}
Your app runs faster and your design is responsive and fluid. I hope this helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to select from field name from nested arrays in mongodb?
I have a document with nested arrays and I can't work out how to select the from the a field.
I'd like to select all documents where "components" has a "mast".
I've tried.
db.sites.find({"components": "mast" } ).pretty();
db.sites.find({"components.$": "mast" } ).pretty();
db.sites.find({"components.$.$": "mast" } ).pretty();
db.sites.find({"components.$.$.mast": {$exists: true} } ).pretty();
db.sites.find({"components.$.mast": {$exists: true} } ).pretty();
db.sites.find({"components.mast": {$exists: true} } ).pretty();
and a bunch of other failed attempts.
{
"_id" : ObjectId("23456yujbvfdfg"),
"d": 1234567,
"components" : [
[
"mast",
{
"foo":"bar"
}
],
[
"commsbox",
{
"BLARN": "bAAA"
}
]
]
}
My attempts are only returning blank results.
A:
If you are maintaining components as array then you query should look like
db.test.find({ "components": { $elemMatch: { $elemMatch: {$eq:"mast"} } }})
I have posted the solution based on the schema you have shared but i am certain that schema needs to be changed
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NavigatorIOS - Is there a viewDidAppear or viewWillAppear equivalent?
I'm working on porting an app to React-Native to test it out. When I pop back to a previous view in the navigator stack (hit the back button) I'd like to run some code. Is there a viewWillAppear method? I see on the Navigator there is a "onDidFocus()" callback which sounds like it might be the right thing.. but there doesn't appear to be anything like that on NavigatorIOS
A:
I find a way to simulate viewDidAppear and viewDidDisappear in UIKit,
but i'm not sure if it's a "right" way.
componentDidMount: function() {
// your code here
var currentRoute = this.props.navigator.navigationContext.currentRoute;
this.props.navigator.navigationContext.addListener('didfocus', (event) => {
//didfocus emit in componentDidMount
if (currentRoute === event.data.route) {
console.log("me didAppear");
} else {
console.log("me didDisappear, other didAppear");
}
console.log(event.data.route);
});
},
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error displaying Records in my table: It shows one record less
I'm showing records in a table from my database.
BUT If I have 6 records, my .php file shows me 5... It shows me one record less:
I've looking in pages like this, but I still have the error...
Any idea?
This is my code:
<?php
include 'conexion.php';
$contabla=conexion();
$sqltabla="select * from precotizacion p, producto pro where p.idproducto=pro.id";
$resutadotabla=mysql_query($sqltabla,$contabla);
$dato=mysql_fetch_array($resutadotabla);
$contador=0;
while ($dato=mysql_fetch_array($resutadotabla))
{
$contador++;
echo "<td>".$contador."</td>";
echo "<td>".$dato['id']."</td>";
echo "<td>".$dato['parte']."</td>";
echo "<td>".$dato['descripcion']."</td>";
echo "<td><input size='3' name='pcanitdad' id='idcantidad' value ='1' onchange='editarproducto(this.value)'> </td>";
echo "<td>".$dato['pfinal']."</td>";
echo "<td>subtotal</td>";
echo "<td>Descuento aplicado</td>";
echo "<td>total";
echo "<td><select name='desc' id='desc' onchange='descuento(this.value)'>
<option >Aplicar</option>
<option >1</option>
<option >2</option>
<option >3</option>
<option >4</option>
<option >5</option>
</select></td>";
echo '<td><a href="abcs/eliminarprecotizacion.php?id='.$dato['id'].'"> Eliminar producto </a></td>';
echo "</tr>";
}
?>
A:
Before going into while, please delete this line:
$dato=mysql_fetch_array($resutadotabla);
That line will get the first records and then it will go into the while loop, and starting with the second one.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Array of sockets as a parameters in CreateThread
I have an exmaple wich describes how to send 1 socket as a parameter to the new thread.
SOCKET clientSocket;
...
CreateThread(NULL, NULL, SexToClient, &clientSocket, NULL, &thID);
...}
DWORD WINAPI SexToClient(LPVOID client) {
SOCKET clientSocket;
clientSocket = ((SOCKET*)client)[0];
... }
But now I want to make another thread with array of sockets. How can I send them and use in thread?
And what does mean [0] at the end of this line? In this particular example we're send only one socket and it's working fine.
((SOCKET*)client)[0];
A:
You can pass any arguments to the CreateThread method by wrapping all the arguments into simple structure. For example:
struct ThreadParams {
std::vector<SOCKET *> sockets;
std::string clientName;
// more params
};
All you need to do is to initialize this structure before calling CreateThread function, and then pass a pointer:
ThreadParams * params = new ThreadParams();
params.setParameters();
CreateThread(, , SexToClient, params, );
DWORD WINAPI SexToClient(LPVOID arg) {
ThreadParams * params = reinterpret_cast<ThreadParams *>(arg);
// delete after usage;
delete params;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I create a MySQL query using an array?
I need to take an array and use it for a MySQL query.
I tried looking for methods but all of them seem to be related to PHP arrays and not Ruby.
For example, I have terms = ['genetics', 'elderly', 'health'] and I want to use:
con.query "SELECT col1 FROM data1 WHERE MATCH (col2) AGAINST (terms)"
Is this possible?
A:
You can just join your terms in your against clause:
terms = ['genetics' , 'elderly', 'health']
con.query "SELECT col1 FROM data1 WHERE MATCH col2 AGAINST ('#{terms.join(' ')}')"
Note that using match/against will almost certainly be more performative than using a series of like clauses. See this StackOverflow answer for more information: Which SQL query is better, MATCH AGAINST or LIKE?.
Check out the MySQL documentation for more information on full text searching (including possible operators): http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Conflict between wxWidgets and boost::property_tree
I'd like to use boost::property_tree in a wxWidgets applications.
However when I add the line
#include <boost/property_tree/ptree.hpp>
to a simple wxWidgets I suddenly get compilation errors:
||=== Build: Release in pulley_client_gui (compiler: GNU GCC Compiler) ===|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h||In function 'HWND__* CreateDialog(HINSTANCE, LPCTSTR, HWND, DLGPROC)':|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h|38|error: cannot convert 'LPCTSTR {aka const char*}' to 'LPCWSTR {aka const wchar_t*}' for argument '2' to 'HWND__* CreateDialogParamW(HINSTANCE, LPCWSTR, HWND, DLGPROC, LPARAM)'|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h||In function 'HFONT__* CreateFont(int, int, int, int, int, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, LPCTSTR)':|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h|69|error: cannot convert 'LPCTSTR {aka const char*}' to 'LPCWSTR {aka const wchar_t*}' for argument '14' to 'HFONT__* CreateFontW(int, int, int, int, int, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, LPCWSTR)'|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h||In function 'HWND__* CreateWindow(LPCTSTR, LPCTSTR, DWORD, int, int, int, int, HWND, HMENU, HINSTANCE, LPVOID)':|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h|94|error: cannot convert 'LPCTSTR {aka const char*}' to 'LPCWSTR {aka const wchar_t*}' for argument '2' to 'HWND__* CreateWindowExW(DWORD, LPCWSTR, LPCWSTR, DWORD, int, int, int, int, HWND, HMENU, HINSTANCE, LPVOID)'|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h||In function 'HMENU__* LoadMenu(HINSTANCE, LPCTSTR)':|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h|111|error: cannot convert 'LPCTSTR {aka const char*}' to 'LPCWSTR {aka const wchar_t*}' for argument '2' to 'HMENU__* LoadMenuW(HINSTANCE, LPCWSTR)'|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h||In function 'HICON__* LoadIcon(HINSTANCE, LPCTSTR)':|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h|311|error: cannot convert 'LPCTSTR {aka const char*}' to 'LPCWSTR {aka const wchar_t*}' for argument '2' to 'HICON__* LoadIconW(HINSTANCE, LPCWSTR)'|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h||In function 'HBITMAP__* LoadBitmap(HINSTANCE, LPCTSTR)':|
C:\Users\James\code\wxWidgets-3.0.1\include\wx\msw\winundef.h|324|error: cannot convert 'LPCTSTR {aka const char*}' to 'LPCWSTR {aka const wchar_t*}' for argument '2' to 'HBITMAP__* LoadBitmapW(HINSTANCE, LPCWSTR)'|
||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 3 second(s)) ===|
This would seem to indicate that the wxWidgets methods can no longer handle UTF8 parameters, the ability to convert to UTF16 has been broken by the boost header file.
A:
It seems that UNICODE definition is inconsistent, i.e. it's defined (or not) when <windows.h> is included from Boost headers and not defined (or is) when wxWidgets headers are included.
To prevent this from ever happening, the recommended solution is to define UNICODE in your make or project file, so that it is defined on the command line. Chances are you already define _UNICODE there (if using MSVS projects), but this only affects the CRT headers and you need UNICODE as well for <windows.h>.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Esteblishing a remote desktop connection from Windows 10 Home to RPi
I found a bunch of tutorials on how to connect to Raspberry Pi desktop remotely. They are all together goes wth the same way:
installing XRDP on RPi
Just running Remote Desktop Connection app on Windows computer and connect to RPi with its IP address.
So it looks so simple. However, I don't have Remote Desktop Connection application on my PC and I can not find anything on the web. The only thing I was able to find was Remote Desktop Connection Manager 2.7 which is not the thing.
I suspect that I need to have a Pro version of Windows to use this app. Is this correct?
My Windows is Home. So is there any alternatives?
A:
Here is what appears to be the client app. Seems to be free.
Using a VNC viewer app such as this one rather than RDP is another alternative.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Monitoring system that scales to 1,000 hosts and 100,000 variables
Suppose I wanted to monitor 1,000 hosts. For each host, there is 100 or more variables I want to monitor: ping, disk IO/latency, RAM free/swap/etc, and so on. 100,000 data points every 5-10 minutes, stored for 5 years.
What system scales this large?
What if I had 10x the number of hosts? What would you select then?
A:
You'll need to answer a few more questions before we can really give you a suggestion. For starters, are you wanting to store raw data for 5 years? Or is rolled-up data good enough? This matters more than you might think, and this feature alone may determine what your options are.
When you're talking about a 5 year time span, you're almost always talking about trending information that's going to rolled up and you'll lose precision over time. If you don't roll up the data, you're dealing with a monstrous volume of data and very few systems (both software and hardware) will be able to handle it.
Luckily, that's why RRDtool and Round Robin Databases (RRD) was invented. If you don't recognize it, that's okay. You may not know the name, but if you're looking at open source tools, you'll see practically everything built on top of it. Almost any open source program that is trending data over time and giving you pretty graphs is probably using RRDtool under the hood. RRDtool creates fixed sized databases that automatically roll up data and stores fixed precision to specified limits. For example, you might have it store 30 days worth of data at 5 minute precision, 90 days worth of data at 30 minute precision, 180 days worth of data at 1 hour precision, 365 days of data at 1 day precision, 3 years of data at 1 week precision, and 10 years of data at 1 month precision. It's all configurable, and ever time you add a new data point, it calculates the roll up data.
Now, once you figure out for sure what your data retention requirements are, you need to figure out how you're planning to monitor the systems. If there's a wide variety of devices, especially if there's a lot of network devices, SNMP is the standard. Also, there's a lot of devices that can't be monitored by anything other than SNMP, so at least some level of SNMP support is important (examples are UPS's, generators, printers, etc). If you have a lot of servers, you may want to go with an agent based system where you install a monitoring agent on each device to be monitored. This will often give you more detailed information, but significantly increases the management overhead required.
Next, you need to know what your projected growth is beyond "what handles X and what handles 10 times X". Even at the listed 1k hosts, 1k is a hugely different beast than 10k hosts. Lots of systems will handle 1k, but when you approach 10k, many times you'll need a distributed system to share the load. Also, you mention 100 variables per system that you want to monitor. . . are you sure about that? There's not all that many monitoring systems that support monitoring that many variables. That's a lot of information to be pulling from each device.
Finally, you need to consider much more than the monitoring system when you start approaching large scales. Pulling back 100 variable data bits form 1k (or 10k) devices with a 5 minute resolution is going to require some pretty serious bandwidth. Be prepared for that, or you could find that your monitoring system is negatively impacting your network. This is particularly important if you have your systems spread across multiple sites and you're crossing WAN links.
There are a few Open Source systems that stake a claim to being competitive in this large network monitoring scale, but not many. Nagios has been around for a long time and has been known to monitor 1k+ systems. Zenoss offers both an open source core product and a commercially supported product, and is attempting to challenge some of the "big hitters". Zabbix is fully open source with the company backing it offering support.
When it comes to the large companies with thousands of devices/systems that need monitoring, though, the biggest players are CA's Spectrum/eHealth/Unicenter, IBM's Tivoli suite, HP's OpenView. Each of these can handle huge scales, but also come with huge price tags.
Note: My Day job is the implementation and maintenance of network monitoring tools, where we monitor over 5k network devices and 8k servers. Finding tools that work well at these scales is hard.
A:
Nagios seems this is the default answer to these type of questions but there are some installations on this scale using it.
On top of scaling well it's flexible and easy to customize.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
fontawesome and pdflatex
When using pdflatex and the fontawesome package the below error shows up.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Fatal fontspec error: "cannot-use-pdftex"
!
! The fontspec package requires either XeTeX or LuaTeX to function.
!
! You must change your typesetting engine to, e.g., "xelatex" or "lualatex"
! instead of plain "latex" or "pdflatex".
!
! See the fontspec documentation for further information.
!
! For immediate help type H <return>.
!...............................................
Wish to keep on using "pdflatex" instead of "xelatex" or "lualatex".
In fontawesome Version 4.4.0 manual it says "When using the (pdf)(LA)TEX
engine, the fontawesome package doesn’t require any external package".
Tried solutions proposed for this question (Fontawesome doesn't scale up) without success.
MWE:
\documentclass{article}
\usepackage{fontawesome}
\begin{document}
{\faAdjust}
\end{document}
A:
Thanks to @AkiraKakuto, the problem was that MikTex was still using old versions of the fontawesome package from the AppData/Roaming folder despite the package was updated using the package manager and the "update app" within MiKTex.
The problem is solved by deleting the fontawesome folder within AppData/Roaming/MiKTex/'version'.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cache directory structure
I'm in the process of implementing caching for my project. After looking at cache directory structures, I've seen many examples like:
cache
cache/a
cache/a/a/
cache/a/...
cache/a/z
cache/...
cache/z
...
You get the idea. Another example for storing files, let's say our file is named IMG_PARTY.JPG, a common way is to put it in a directory named:
files/i/m/IMG_PARTY.JPG
Some thoughts come to mind, but I'd like to know the real reasons for this.
Filesystems doing linear lookups find files faster when there's fewer of them in a directory. Such structure spreads files thin.
To not mess up *nix utilities like rm, which take a finite number of arguments and deleting large number of files at once tends to be hacky (having to pass it though find etc.)
What's the real reason? What is a "good" cache directory structure and why?
A:
Every time I've done it, it has been to avoid slow linear searches in filesystems. Luckily, at least on Linux, this is becoming a thing of the past.
However, even today, with b-tree based directories, a very large directory will be hard to deal with, since it will take forever and a day just to get a listing of all the files, never mind finding the right file.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IE9 and 10 doesn't reflect javascript cursor change
The following code sample adds a semi transparent 100% overlay when a button is clicked. The overlay remains until the mouse button is released. Here's what is supposed to happen:
Click on the button and hold the mouse down.
While the mouse is down press and release the shift key.
When it's pressed, a div area
indicates this with the text "horizontal" and the cursor changes to
e-resize. When shift is released, the div indicates "vertical" and
the cursor changes to n-resize.
In IE9/10, the text changes but the cursor remains the same. I've tried changing the key bind to the body level and to the overlay level but to no avail.
Here's the code: (I tried putting it into jsfiddle and jsbin but for some reason they ignore the key presses completely).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
.overlay {
background-color: rgba(0, 0, 0, 0.3);
top: 0; bottom: 0; left: 0; right: 0; position: fixed;
z-index: 999;
}
.vertical { cursor: n-resize !important; }
.horizontal { cursor: e-resize !important; }
</style>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#button1").mousedown(onButtonMouseDown);
function onButtonMouseDown(e) {
var overlay;
overlay = $("body").after("<div class=\"overlay\"></div>").next();
overlay.addClass((e.shiftKey) ? "horizontal" : "vertical");
$(document).bind("keydown.ntextbox", function (e) {
if (e.which === 16) {
overlay.removeClass("vertical").addClass("horizontal");
$("#div1").html("horizontal");
}
});
$(document).bind("keyup.ntextbox", function (e) {
if (e.which === 16) {
overlay.removeClass("horizontal").addClass("vertical");
$("#div1").html("vertical");
}
});
overlay.mouseup(function (e) {
overlay.remove();
$(document).unbind(".ntextbox");
return false;
});
return false;
}
});
</script>
</head>
<body>
<div id="div1">...</div>
<button id="button1">Click me</button>
</body>
</html>
A:
Adding the following jQuery statements seems to fix it.
$(".overlay").css("cursor", "e-resize");
$(".overlay").css("cursor", "n-resize");
So, maybe something like this?
$(document).bind("keydown.ntextbox", function (e) {
if (e.which === 16) {
overlay.removeClass("vertical").addClass("horizontal").css("cursor", "e-resize");
$("#div1").html("horizontal");
}
});
$(document).bind("keyup.ntextbox", function (e) {
if (e.which === 16) {
overlay.removeClass("horizontal").addClass("vertical").css("cursor", "n-resize");
$("#div1").html("vertical");
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to convert a List of duplicate values to a List of distinct values with respect to a field of T class
I have a List<String> which contains names I want to convert that list to an other list of unique names I found a way that works well which is:
public class Main {
public Main() {
List<String> nameList = new ArrayList<>();
nameList.add("Ali");
nameList.add("Al");
nameList.add("Ali");
nameList.add("Al");
nameList.add("Ai");
nameList.add("li");
nameList.add("li");
nameList.add("Ai");
System.out.print("All names are: ");
for (String string : nameList) {
System.out.print(string + ", ");
}
System.out.println("");
System.out.print("Unique names are: ");
for (String string : convertToUniqueList(nameList)) {
System.out.print(string + ", ");
}
}
public List<String> convertToUniqueList(List<String> listInts) {
List<String> listDistinctInts = new ArrayList<>(listInts.size());
for (String i : listInts) {
if (!listDistinctInts.contains(i)) {
listDistinctInts.add(i);
}
}
return listDistinctInts;
}
public static void main(String[] args) {
new Main();
}
}
all things are working very well and I'm getting desired results, but I want to implement the same logic as above to following scenario where I have:
@Data // lombok annotation
public class Foo {
String name;
int age;
List<Bar> barList = new ArrayList<>();
}
@Data // lombok annotation
public class Bar {
String bloodGroup;
String dayOfPassing;
}
I want to get a list with unique day names from misc list in Main.java I tried:
public class Main {
public Main() {
Foo foo1 = new Foo();
foo1.setName("Foo One");
foo1.setAge(21);
List<Bar> barList = new ArrayList<>();
Bar bar1 = new Bar();
bar1.setBloodGroup("O +ve");
bar1.setDayOfPassing("Wednesday");
Bar bar2 = new Bar();
bar2.setBloodGroup("O +ve");
bar2.setDayOfPassing("Wednesday");
Bar bar3 = new Bar();
bar3.setBloodGroup("O +ve");
bar3.setDayOfPassing("Thursday");
Bar bar4 = new Bar();
bar4.setBloodGroup("O -ve");
bar4.setDayOfPassing("Friday");
barList.add(bar1);
barList.add(bar2);
barList.add(bar3);
barList.add(bar4);
System.out.print("All Bars with all days are: ");
for (Bar bar : barList) {
System.out.print(bar.dayOfPassing + ", ");
}
System.out.println("");
System.out.print("Bars with Unique days are: ");
int count = 0;
for (Bar bar : getBarsWithUniqueDays(barList, count)) {
System.out.print(bar.dayOfPassing + ", ");
count++;
}
}
public List<Bar> getBarsWithUniqueDays(List<Bar> barList, int count) {
List<Bar> listDistinctBars = new ArrayList<>(barList.size());
for (Bar bar : barList) {
if (!listDistinctBars.get(count).getDayOfPassing().contains(bar.dayOfPassing)) {
listDistinctBars.add(bar);
}
count++;
}
return listDistinctBars;
}
public static void main(String[] args) {
new Main();
}
}
with that code above I'm getting Exception:
All Bars with all days are: Wednesday, Wednesday, Thursday, Friday,
Bars with Unique days are: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Main.getBarsWithUniqueDays(Main.java:124)
at Main.<init>(Main.java:113)
at Main.main(Main.java:133)
I have searched and tried a lot but in vain, any solutions to this problem...
A:
Map<String, Bar> map = new LinkedHashMap<>();
for (Bar ays : barList) {
map.put(ays.dayOfPassing, ays);
}
barList.clear();
barList.addAll(map.values());
for (Bar ays : barList) {
System.out.println("Unique names are: "+ays.dayOfPassing);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android - Creating an alert dialog in listview from selected item
Ive been struggling to get an alert dialog to pop up when the user clicks an item in the list view. I can do a toast message but cant seem to get an alert dialog to work. I then want to have a button in the alert dialog to allow me to take the item just selected and display it on the next screen where it will be show contact details etc for the one selected. If anyone can give me any insight into any good techniques or tips on how to do this it would be awesome! Im a very new programmer and ive tried everywhere.
Below is my code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_LONG).show();
}
});
}
}
The array is in the strings.xml file.
Any help would be very much appreciated.
A:
Your code in general is correct. I'd make sure your code for posting a dialog works correctly first. Try it out in a way outside of the list, and then see if it works in the onClick() statement itself.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it allowed to use Admob ads during alpha or beta testing in Google Play?
I am going to upload my app as alpha testing in google play, but I wonder...
Is it correct to enable real Admob ads (no test ads) now in my app during alpha testing? Or should I add them later, when I upload my apk for production in google play?
A:
Is it ok to add admob ads during alpha testing in google play?
Yes it is. There is nothing that says you cannot do it during alpha and beta. Meaning having ads in alpha/beta is fine, doing anything against the Admob policy(e.g. getting people to press your ads) is still against the policy
|
{
"pile_set_name": "StackExchange"
}
|
Q:
React onClick `this` binding
export default React.createClass({
displayName: 'Test',
onItemClick(item) {
console.log(item);
},
render() {
return <div onClick={() => this.onItemClick('apple')}>Fruit</div>
});
When clicking the div I get Uncaught TypeError: Cannot read property 'onItemClick' of undefined. Tried also using bind, but with same result.
Later edit:
The actual code is different. I'm populating the items arrays inside the circle object with div objects. Outside the loop, if I call the onItemClick() function it works fine, but inside the loop I get the error above.
export default React.createClass({
displayName: 'Test',
onItemClick (item) {
console.log(item);
},
render() {
var circle = {
'one': { items: [] },
'two': { items: [] },
'three': { items: [] },
'four': { items: [] }
};
['one', 'two', 'three', 'four'].forEach(function (k, i) {
for (var j = 1; j <= 10; j++) {
var itemNo = (i * 10 + j);
circle[k].items.push(<div className={"item item-"+itemNo} onClick={() => this.onItemClick(itemNo)}>{itemNo}</div>);
}
});
return (
<div>{circle.one.items}</div>
)};
How can I address this problem?
A:
The forEach handler is a standard function and has a different this. Replace it by an arrow function and you should be fine.
render() {
var circle = {
'one': { items: [] },
'two': { items: [] },
'three': { items: [] },
'four': { items: [] }
};
['one', 'two', 'three', 'four'].forEach((k, i) => {
// ^^^^^^^^^^
for (var j = 1; j <= 10; j++) {
var itemNo = (i * 10 + j);
circle[k].items.push(<div className={"item item-"+itemNo} onClick={() => this.onItemClick(itemNo)}>{itemNo}</div>);
}
});
return (
<div>{circle.one.items}</div>
)};
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I create 256 bit self-signed certificate key with OpenSSL?
Take a look at PayPal (https://www.paypal.com/) security certificate.
It says: Connection Encrypted: High-grade Encryption (TLS_RSA_WITH_AES_256_CBC_SHA, 256 bit keys).
Now, how can I create my self signed certificate to have the same encryption, AES256?
I tried the following code in Openssl:
openssl> req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
I ended up with 128 bit certificate. Then I tried:
openssl> genrsa -aes256 -out key.key 4096
openssl> req -new -key key.key -out cert.csr
openssl> x509 -req -days 365 -in cert.csr -signkey key.key -out cert.crt
openssl> rsa -in key.key -out key.key
Even if I specified '-aes256', I ended up again with a 128 bit certificate: Connection Encrypted: High-grade Encryption (TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 128 BIT KEYS).
So, what did I do wrong and can you tell me how to create that 256 certificate? Thanks for help!
A:
CodesInChaos was right. I should have edited the configuration of the server. I added the SSLCipherSuite line in Apache config and it worked:
SSLCipherSuite AES256-SHA
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select from a table and Insert new records into another table but change some values
I have a 1 to many relationship between two tables... say Organisation and Members
I want to create a new Organisation based on an existing one (ID 111) and copy all the members but associate them with the newly created organisation.
some pseudo code..
-- Just create a new organisation based on the new name and address
-- passed to the proc.
Insert into Organisation (newOrganisationName, newAddress)
returning Organisation_ID into v_orgID;
So now I have the new organisation id returned in v_orgID of say 999 and I want to copy the members from an existing Organisation with say an ID of 111 and associate these with the new OrgID.
What is the best way to achieve this... should I loop and insert or can I use the Insert Into - select from method
INSERT INTO Members (OrganisationID, Membername, MemberAddress)
(SELECT v_orgID, MemberName, MemberAddress FROM Member
WHERE OrganisationId = 111)
thanks Mick
A:
Just insert the v_orgID into the query as a number:
INSERT INTO ... (SELECT 999, MemberName, MemberAddress FROM Member WHERE OrganisationId = 111)
For 999 as the new OrganizationId.
A:
Use INSERT/SELECT, changing the value:
INSERT INTO Members (OrganisationID, Membername, MemberAddress)
SELECT 999, MemberName, MemberAddress FROM Member
WHERE OrganisationId = 111
|
{
"pile_set_name": "StackExchange"
}
|
Q:
sql merge two tables in which the common fields are not complete
In SQL server 2008, I have the following two tables
Table_1:
C1 C2
A TypeStringA-1
B TypeStringA-2
C TypeStringA-3
D TypeStringA-4
E TypeStringA-5
Table_2
C1 C2
A TypeStringB-1
B TypeStringB-2
D TypeStringB-3
E TypeStringB-4
And I want to show the following data:
Result
A TypeStringA-1 TypeStringB-1
B TypeStringA-2 TypeStringB-2
C TypeStringA-3 Null
D TypeStringA-4 TypeStringB-3
E TypeStringA-5 TypeStringB-4
Right now what I have is two sub-queries and a where:
select
query1.C1
query1.C2
query2.C2
(select C1, C2
from Table_1) as query1
(select C2
from table_2) as query2
where query1.C1 = query2.C1
order by query1.C1
However logically in my result I am not having the Null data that I need to show, this is what I am getting:
Result
A TypeStringA-1 TypeStringB-1
B TypeStringA-2 TypeStringB-2
D TypeStringA-4 TypeStringB-3
E TypeStringA-5 TypeStringB-4
The question is what should I use to shot the table as I want with a Null data?.
A:
select coalesce(t1.C1, t2.C1)
, t1.C2
, t2.C2
from Table_1 t1
full outer join
Table2 t2
on t1.C1 = t2.C1
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Populate 2 Grids with the same Store
I have 2 grids and both of these grids will populate it self from the same store Person.
The problem i have is, In the first grid i will load all the Sports and the number of players it has. In the 2nd grid, i will show only the number of medals and gold medals won by a Sport, where SportID = 3. How can i do this ? When i load the grid, it gets populated with all
{
xtype: 'gridpanel',
title: 'ALl Sports',
store: 'Person',
columns: [
{
xtype: 'gridcolumn',
dataIndex: 'SportID',
text: 'Sport ID'
},
{
xtype: 'gridcolumn',
dataIndex: 'SportName',
text: 'Sport Name'
},
{
xtype: 'gridcolumn',
dataIndex: 'NoOfPlayers',
text: 'No Of Players'
}
]
},
{
xtype: 'gridpanel',
title: 'Sport Medals for Sport ID 3',
store: 'Person',
columns: [
{
xtype: 'gridcolumn',
dataIndex: 'noOfMedals',
text: 'No Of Medals'
},
{
xtype: 'gridcolumn',
dataIndex: 'NoOfGold',
text: 'No Of Gold'
}
],
I have 2 grids and both of these grids will populate it self from the same store Person. These 2 grids are in a Window. When the window loads, i populate the grid as follows;
UPDATE 1 #############################3
var personStore = Ext.getStore('Person');
var r = personStore.getAt(0);
personStore.on('load', function() {
r = personStore.getAt(0);
st.filter({
filterFn: function(rec) {
return rec.get('PersonId') == r.get('PersonId');
}
});
personStore.load();
#######################3
But, both grid populates with the same set of data. What i want is to display all of the sports Information on Grid 1 (sportID,sportName,noOfPlayers), and Display Sport Information (noOfMedals,noOfGolds) WHERE sportId='3'. How can i do this ?
A:
Short answer - you can't. If you need to present two different grids at the same time with same store you need to clone store and have another copy of it.
If it's not at the same time - you can use filtering and filter one store before grid is shown.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
locationClient.requestLocationUpdates doesn't fires Pending Intent in Kitkat
I have a code that works fine in Android 4.3 and below. But the same code doesn't work in 4.4 android. Please help if anyone knows about the issue.
Below is the code,
@Override
public void onConnected(Bundle arg0) {
Log.i(TAG, "location client connected");
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(2 * 60 * 1000);
locationRequest.setFastestInterval(1 *60 * 1000);
mIntentService = new Intent(context, MyService.class);
mPendingIntent = PendingIntent.getService(context, 0, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
locationClient.requestLocationUpdates(locationRequest, mPendingIntent);
}
Below is my Service class,
public class MyService extends IntentService {
private String TAG = this.getClass().getSimpleName();
Context context;
public MyService () {
super("MyService ");
context = this;
}
public MyService (String name) {
super("MyService ");
}
@Override
protected void onHandleIntent(Intent intent) {
// my code
}
}
A:
Lately I updated the google-play-service_lib
and changed the locationClient.requestLocationUpdates method to LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, mPendingIntent);
Now everything seems working fine on all versions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CompactFlash driver for Sony Clié (Palm OS)
A Sony Clié (PEG-NX70V) has come into my possession. It runs Palm OS 5.0, and has both a MemoryStick slot and a CompactFlash slot. The latter is only designed for use with a WiFi card, as Sony expected people would use their proprietary MemorySticks for data storage instead.
A third party, EruWare, wrote a driver that added support for CF cards for the PEG-NX70V (and other models) in 2003. This company seemed to fragment in two later that year (according to this blog post), resulting in two companies which each sold a CF driver for the Clié range: Athena's CF Enabler and PDAscent's CF Magic. Both these websites have long since disappeared from the internet, leaving only a skeletal presence on archive.org as testament that they once existed.
There was also a free driver written by "Pelaca", which patched the relevant OS files to use the Cf slot. These were hosted at snow.prohosting.com/~cfutil/ (later snow.prohosting.com/cfutil/) which again only exist at archive.org now. Sadly, while some binary files were archived, the relevant one (CFUtility) wasn't.
(There's also a patching utility by "Mini" that was archived, but it is only designed for the NX80, so is of no use to me.)
Is there a copy of any of these drivers still in existence? Or is there an alternative driver that may work for my NX70?
A:
Archive.org has a copy of Clié files that Rich Legg mirrored on his website. These include a file by the name of CFUtilityPelaca0603.zip, which appears to be a June 2003 version of Pelaca's CFUtility (1.0.3). There are also a number of other Clié-related files there.
CFUtility is provided as a .exe file, and requires Palm Desktop to be installed on the system. It uses Palm Desktop's HotSync function to install itself to the Clié device. I found that installation worked fine using Palm Desktop 6.2 on Windows XP (32-bit).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pegar atributo id de objeto selecionado no JComboBox
Tenho uma tabela no BD com Colunas Id, Placa N° e Furação na placa.
Eu gostaria de mostrar no JComboBox a concatenação de "Placa N° + Furação".
Exemplo:
Placa 10 - 113,00 mm
Mas quando um item do combobox for selecionado pelo usuário, capturar o ID correspondente do objeto Placa. Estou fazendo no Netbeans e MySQL.
Segue o método que pesquisa no banco(DAO):
public ArrayList<Placa> ObterTabelaPlaca() {
conectar();
ArrayList<Placa> placa = new ArrayList<Placa>();
Statement stmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM cadastroplaca ORDER BY CAST(furoPL AS DECIMAL(5,2))";
try {
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
Placa pl = new Placa();
pl.setId(rs.getInt("id"));
pl.setCodPlaca(rs.getInt("codigoPL"));
pl.setFuracao(rs.getDouble("furoPL"));
placa.add(pl);
}
} catch (Exception e) {
System.out.println("Erro " + e.getMessage());
}
return placa;
}
A classe Placa(Modelo):
public class Placa {
int codPlaca, qtdMoldePlaca, id;
double furacao;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
String notaPlaca;
public int getCodPlaca() {
return codPlaca;
}
public void setCodPlaca(int codPlaca) {
this.codPlaca = codPlaca;
}
public int getQtdMoldePlaca() {
return qtdMoldePlaca;
}
public void setQtdMoldePlaca(int qtdMoldePlaca) {
this.qtdMoldePlaca = qtdMoldePlaca;
}
public double getFuracao() {
return furacao;
}
public void setFuracao(double furacao) {
this.furacao = furacao;
}
public String getNotaPlaca() {
return notaPlaca;
}
public void setNotaPlaca(String notaPlaca) {
this.notaPlaca = notaPlaca;
}
}
O método que preenche o componente(Do controller):
public void MostraComboPlaca() throws SQLException{
CadastroDAO dao = new CadastroDAO();
ArrayList<Placa> listaplaca = dao.ObterTabelaPlaca();
DecimalFormat formato = new DecimalFormat("#0.00");
placaCilindrico.setModel(new ComboModelTipo(listaplaca));
for(int i=0;i<listaplaca.size();i++){
placaCombo.addItem(String.valueOf(formato.format(listaplaca.get(i).getFuracao()).replace('.', ','))+" - PL "+listaplaca.get(i).getCodPlaca());
}
}
Não consigo concluir o raciocínio da parte do Controle, para pegar o id do item selecionado.
Eu armazeno os detalhes da tabela numa ArrayList com a DAO acima.
placa.add(pl);
E populo o ComboBox(Valores Furação) usando o Modelo abaixo:
public void MostraComboPlaca() throws SQLException{
CadastroDAO dao = new CadastroDAO();
ArrayList<Placa> listaplaca = dao.ObterTabelaPlaca();
placaCombo.setModel(new ComboModelTipo(listaplaca));
}
Uso esta classe como ComboBoxModel:
public class ComboModelTipo extends AbstractListModel implements ComboBoxModel {
private ArrayList<Placa> lista;
private Placa selected;
public ComboModelTipo(ArrayList<Placa> lista) {
this.lista = lista;
}
@Override
public int getSize() {
return this.lista.size();
}
@Override
public Object getElementAt(int index) {
return this.lista.get(index).getFuracao();
}
@Override
public void setSelectedItem(Object anItem) {
this.selected = (Placa) anItem;
}
@Override
public Object getSelectedItem() {
return this.selected;
}
public Integer getIdObjetoSelecionado() {
return selected.getId();
}
}
Após essas etapas meu ComboBox é populado, mas quando clico em algum valor, ocorre o erro abaixo:
A:
A causa da exceção
O método getElementAt() deve retornar o objeto selecionado na lista, não seu atributo, como você está fazendo. Altere o método abaixo da seguinte forma:
@Override
public Object getElementAt(int index) {
return this.lista.get(index);
}
Alterando a exibição dos itens no ComboModel
Para exibir a informação no combo sem afetar o tipo de objeto é utilizando um ListCellRenderer:
public class PlacaComboRenderer extends DefaultListCellRenderer{
@Override
public Component getListCellRendererComponent(
JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof Placa) {
Placa placa = (Placa) value;
DecimalFormat formato = new DecimalFormat("#0.00");
String text = String.valueOf(formato.format(placa.getFuracao()).replace('.', ','))+" - PL "+ placa.getCodPlaca();
setText(text);
} else if(value == null) {
setText("Selecione uma placa:");
}
return this;
}
}
Neste caso, eu optei por utilizar a classe DefaultListCellRenderer porque ela não só implementa a interface ListCellRenderer como também traz outras funcionalidades afim de evitar termos que implementar um ListCellRenderer completo do zero.
Para aplicar, basta fazer isso:
public void MostraComboPlaca() throws SQLException{
CadastroDAO dao = new CadastroDAO();
ArrayList<Placa> listaplaca = dao.ObterTabelaPlaca();
DecimalFormat formato = new DecimalFormat("#0.00");
placaCilindrico.setModel(new ComboModelTipo(listaplaca));
//precisa ser exatamente após o ComboBoxModel ser aplicado
placaCombo.setRenderer(new PlacaComboRenderer());
}
E para capturar itens deste JComboBox, basta pegar o item selecionado, fazer o casting para seu objeto Placa e chamar o método que retorna o ID:
Placa placaSelecionada = (Placa)seuCombo.getSelectedItem();
int id = placaSelecionada.getId();
Não precisa criar um método no ComboBoxModel(no caso o getIdObjetoSelecionado()) para resgatar o id do objeto selecionado, uma vez que você já sabe que o getSelectedItem retornará um objeto tipo Placa, a solução acima já cobre isso.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can we edit the endpoints.py and add new functions to it in airflow?
I have new functions and I want to call them through api/experimental/route_name
I have the below function and want to integrate it with the airflow so that whenever I call the api/experimental/api_userDetail the details show up.
I have included the function in the file [endpoints.py] . For some reason, it is not showing up in the server and says 404 error. Would be great if I get some method to do so.
def returnFromVariable(key_name):
return Variable.get(key_name,deserialize_json=True)
@api_experimental.route('/api_userDetail',methods=['GET'])
def userDetailApi():
get_element_config_name="user_credential"
return jsonify(returnFromVariable(get_element_config_name))```
The output is the data returned.
A:
Actually the stuff worked. I had two versions of airflow running one on python2 and another on python3 so I had to made changes in python3 and that worked for me. The above stuff which I wrote worked. To add the new functionalities simply go to www/api/experimental and then add the api to the file and restart the webserver it will work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is the exception stating "Run-Time Check Failure #2 - Stack around the variable 'f' was corrupted." thrown here?
I have written this code:
void f1(void)
{
sprintf("\nf1.");
}
void f2(void)
{
sprintf("\nf2.");
}
void f3(void)
{
sprintf("\nf3.");
}
void f4(void)
{
sprintf("\nf4.");
}
int main()
{
// int i;
void (*f[4])(void);
f[1]=f1;
f[2]=f2;
f[3]=f3;
f[4]=f4;
(*f[1])();
(*f[2])();
(*f[3])();
(*f[4])();
/*for(i=0;i<4;i++)
{
(*f[i])();
}*/
getch();
}
The program compiles, runs, and shows the output
f1.
f2.
f3.
f4.
but when I press enter, it throws the exception stating "Run-Time Check Failure #2 - Stack around the variable 'f' was corrupted."
Please explain to me the reason for this, and also when to use snprintf and sprintf.
Also, let me know why I cannot use
for(i=0;i<4;i++)
{
(*f[i])();
}
for function pointer. It's throwing an error for this as well.
A:
void (*f[4])(void);
f[4]=f4;
Arrays start from 0 in C. Accessing f[4] is illegal.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.