text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
google map in visualforce page
Hi i used this code but google map not showing in visualforce page in account record please any one help on this
<apex:page standardController="Account">
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var myOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var address = "{!Account.BillingStreet}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalCode}, " + "{!Account.BillingCountry}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Account.Name}</b><br>{!Account.BillingStreet}<br>{!Account.BillingCity}, {!Account.BillingPostalCode}<br>{!Account.BillingCountry}"
});
geocoder.geocode( { address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Account.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
}
} else {
$('#map').css({'height' : '15px'});
$('#map').html("Oops! {!Account.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
</script>
<style>
#map {
font-family: Arial;
font-size:12px;
line-height:normal !important;
height:250px;
background:transparent;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</apex:page>
A:
Summer 16 released a new feature to the force.com platform of automatic adding GeoCodes for addresses on existing and new accounts, contacts, and leads.
Using this new feature, I have updated the solution below. Now we don't have to use google geocoder as we have already latitude and longitude (Account.BillingLatitude,Account.BillingLongitude) from Salesforce. This is pretty neat solution.
<apex:page standardController="Account">
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
center: {lat: {!Account.BillingLatitude}, lng: {!Account.BillingLongitude}}
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var marker = new google.maps.Marker({
position: {lat: {!Account.BillingLatitude},lng: {!Account.BillingLongitude}},
map: map
});
var infowindowtext = "<b>{!JSENCODE(Account.Name)}</b><br>{!JSENCODE(Account.BillingStreet)}<br>{!JSENCODE(Account.BillingCity)}, {!JSENCODE(Account.BillingPostalCode)}<br>{!JSENCODE(Account.BillingCountry)}";
infowindowtext = infowindowtext.replace(/(\r\n|\n|\r)/gm,"");
var infowindow = new google.maps.InfoWindow({
content: infowindowtext
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
</script>
<style>
#map {
font-family: Arial;
font-size:12px;
line-height:normal !important;
height:250px;
background:transparent;
}
</style>
<div id="map">Hello</div>
</apex:page>
Previous Solution using Google Geocoder
There were couple of issues first you have used http:// to fetch the JS files inside salesforce https:// domain. Second if an address has line break then your entire JavaScript will break. You have to wrap the address component with JSENCODE like this {!JSENCODE(Account.BillingStreet)}. Here is the updated code and it is working fine.
<apex:page standardController="Account">
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var myOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var address = "{!JSENCODE(Account.BillingStreet)}, " + "{!JSENCODE(Account.BillingCity)}, " + "{!JSENCODE(Account.BillingPostalCode)}, " + "{!JSENCODE(Account.BillingCountry)}";
address = address.replace(/(\r\n|\n|\r)/gm,"");
var infowindowtext = "<b>{!JSENCODE(Account.Name)}</b><br>{!JSENCODE(Account.BillingStreet)}<br>{!JSENCODE(Account.BillingCity)}, {!JSENCODE(Account.BillingPostalCode)}<br>{!JSENCODE(Account.BillingCountry)}";
infowindowtext = infowindowtext.replace(/(\r\n|\n|\r)/gm,"");
var infowindow = new google.maps.InfoWindow({
content: infowindowtext
});
geocoder.geocode( { address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
console.log('map '+map);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Account.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
}
} else {
$('#map').css({'height' : '15px'});
$('#map').html("Oops! {!Account.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
</script>
<style>
#map {
font-family: Arial;
font-size:12px;
line-height:normal !important;
height:250px;
background:transparent;
}
<div id="map">Hello</div>
</apex:page>
Output
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert Audio data in IeeeFloat buffer to PCM in buffer
I use NAudio to capture sound input and the input appears as a buffer containing the sound information in IeeeFloat format.
Now that I have this data in the buffer, I want to translate it to PCM at a different sampling rate.
I have already figured out how to convert from IeeeFloat to PCM, and also convert between mono and stereo. Converting the sampling rate is the tough one.
Any solution, preferable using NAudio, that can convert the IeeeFLoat buffer to a buffer with PCM format of choice (including changing sampling rate)?
A:
If you want to resample while you receive data, then you need to perform input driven resampling. I wrote an article on this a while ago.
NAudio has some helper classes to go from mono to stereo, and float to PCM, but they tend to operate on IWaveProvider or ISampleProvider inputs. Typically if I just had the samples as a raw block of bytes I'd write by own simple code to go from float to PCM and double up the samples. It's not that hard to do and the WaveBuffer class will allow you to read float samples directly from a byte[].
| {
"pile_set_name": "StackExchange"
} |
Q:
querying a database based on a dynamic amount of conditions
I am building a 'tag' system. I quoted it because its not quite a tag system, but close enough.
Obviously, when dealing with tags, the user may very well use multiple tags and expect to filter the results to an even greater depth.
The problem I am coming across is how exactly to do this.
there are 2 ways I can think of doing it so far, but I would be greatly appreciative if someone out there can explain the correct way.
way 1) Do an individual query for each tag then sort/combine/play with the data afterward.
way 2)
SELECT i2t.item_id
FROM Item2Tag i2t
INNER JOIN Tag t
ON i2t.tag_id = t.tag_id
WHERE t.tag_text IN ('beach','cloud','waves')
GROUP BY i2t.item_id
The above is my query. This is based on a modified version of Toxi's solution. Hopefully you see whats going on...essentially there are 3 tables, 1 for info, 1 for tags, and another to connect them.
This is currently what I am doing: I substitute 'beach','cloud','waves' with a variable. Then, within the PHP code, I convert the array to a string with each word separated by comma's and simply insert it into the query. so something like :
foreach ($tagarray as $tag){
$string = .$tag1.", " }
That is of course a bit over simplified, since I would need to correctly end the last tag without a comma..but hopefully you get the point.
so, $string becomes equal to 'tag1, tag2, tag3'
SELECT i2t.item_id
FROM Item2Tag i2t
INNER JOIN Tag t
ON i2t.tag_id = t.tag_id
WHERE t.tag_text IN ('$string')
GROUP BY i2t.item_id
Is there a better way to do this?
A:
The database structure is good with those 3 tables. But there's a little problem with your query. Not a syntax one thou. Let's take an example. users search for content with tags 'a' and 'b'. If you have a content with only tag 'a' it will turn up as a result. Also contents with only 'b' tags. You should append to query something like:
HAVING COUNT(t.tag_id) = x
, where x is the length of the numbers of tags you are querying with (in my example 2, in yours 3). This way a content will be considered result if all items of the given set was matched. This only works if there are no duplicate entries in any of these tables.
Also, instead of the loop use implode.
$string = implode(",", $tagarray);
This way you don't need to bother removing the last comma.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get a stack trace on all running ruby threads on passenger
I have a production ruby sinatra app running on nginx/passenger, and I frequently see requests get inexplicably stalled. I wrote a script to call passenger-status on my cluster of machines every ten seconds and plot the results on a graph. This is what I see:
The blue line shows the global queue waiting spiking constantly to 60. This is an average across 4 machines, so when the blue line hits 60, it means every machine is maxed out. I have the current passenger_max_pool_size set to 20, so it's getting to 3x the max pool size, and then presumably dropping subsequent requests.
My app depends on two key external resources - an Amazon RDS mysql backend and a Redis instance. Perhaps one of these is periodically becoming slow or unresponsive and thereby causing this behavior?
Can anyone advise me on how to get a stack trace to see if the bottleneck here is Amazon RDS, Redis, or something else?
Thanks!
A:
I figured it out -- I had a SAVE config parameter in Redis that was firing once a minute. Evidently the forking/saving operations of redis are blocking for my app. I change the config param to be "3600 1", meaning I only save my database once an hour, which is OK because I am using it as a cache (data persisted in MYSQL).
| {
"pile_set_name": "StackExchange"
} |
Q:
Can we use subethasmtp with postfix?
is it possible to use postfix with subethasmtp
so that postfix can deliver emails to subethasmtp and it handle those emails ?
A:
Usually you would use transport_maps to route certain mails or whole domains to subethasmtp.
transport_maps = hash:etc/postfix/transport
containing stuff like:
mydomain.com smtp:[ipaddress]:port
where subethasmtp must be listening on ipaddress and port.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reading file into buffer
I have a little problem that i can't figure out.
I am trying to read a file into a buffer,
My problem is that sometimes it adds a random character at the end of the text. (sometimes ? and abs etc.). So i wonder why that is happening. I haven't found any solution yet. The problem happens randomly, not every time i read the file.
static char text[1024 * 16];
std::ifstream File(FilePath, std::ios::in | std::ios::out | std::ios::binary | std::ios::ate);
std::streamsize Size = File.tellg();
File.seekg(0, std::ios::beg);
char *string = new char[Size + 1];
if (File.is_open())
{
File.read(string, Size);
memset(text, 0, sizeof(text));
snprintf(text, sizeof(text), "%s", string);
}
File.close();
delete[] string;
A:
Note that read() does not append a null terminator, it's just a raw binary read. In other words, the data is not a string, it's an array of bytes. You are probably trying to print it out or something, and it just keeps going until it sees a null terminator, potentially into uninitialized memory. You should manually allocate size + 1 and add the null terminator at the end.
A couple style notes: its not recommended to use variable names such as "File" or "Size". Its legal but bad practice, you can check out some popular style guides for more information (Google, LLVM)
Secondly, I would try to get this working with std::string rather than allocating memory manually, even on the stack. Check out reserve() and data()
Here's a cleaner example using std::string. More readable, easier to write, and just as efficient.
const char *somefile = "main.cpp";
std::ifstream fh(somefile, std::ios::in | std::ios::out | std::ios::binary |
std::ios::ate);
const size_t sz = fh.tellg();
if (sz <= 0) {
// error handling here
}
fh.seekg(0, std::ios::beg);
// Initalizes a std::string with length sz, filled with null
std::string str = std::string(sz, '\0');
if (fh.is_open())
fh.read(&str[0], sz);
fh.close();
std::cout << str << "[EOF]\n";
| {
"pile_set_name": "StackExchange"
} |
Q:
at the rpcrt4!NdrClientCall2 function - how does it know which pipe to use in order to transfer data to another process?
Hey i have a very time consuming problem, and i thought i might find someone here with better experience than mine that could help me out.
I am reverse-engineering an application which at some point uses the NdrClientCall2 api to use a remote procedure of some other service (which i dont know which one that is)
Now before i hear comments about not trying anything my self
There are some really good applications to accomplish what i want like NtTrace, Strace and roughly oSpy can achieve the same result aswell eventually.
But my application has some really hard anti-debugging techniques which force me to do everything manually.
What eventually i want to achieve is know what procedure is being called and on what service \ process.
Here is the NdrClientCall2 Decleration by MSDN
CLIENT_CALL_RETURN RPC_VAR_ENTRY NdrClientCall2(
__in PMIDL_STUB_DESC pStubDescriptor,
__in PFORMAT_STRING pFormat,
__in_out ...
);
so it uses the PMIDL_STUB_DESC struct which its definition is as the following:
typedef struct _MIDL_STUB_DESC {
void *RpcInterfaceInformation;
void* (__RPC_API *pfnAllocate)(size_t);
void (__RPC_API *pfnFree)(void*);
union {
handle_t *pAutoHandle;
handle_t *pPrimitiveHandle;
PGENERIC_BINDING_INFO pGenericBindingInfo;
} IMPLICIT_HANDLE_INFO;
const NDR_RUNDOWN *apfnNdrRundownRoutines;
const GENERIC_BINDING_ROUTINE_PAIR *aGenericBindingRoutinePairs;
const EXPR_EVAL *apfnExprEval;
const XMIT_ROUTINE_QUINTUPLE *aXmitQuintuple;
const unsigned char *pFormatTypes;
int fCheckBounds;
unsigned long Version;
MALLOC_FREE_STRUCT *pMallocFreeStruct;
long MIDLVersion;
const COMM_FAULT_OFFSETS *CommFaultOffsets;
const USER_MARSHAL_ROUTINE_QUADRUPLE *aUserMarshalQuadruple;
const NDR_NOTIFY_ROUTINE *NotifyRoutineTable;
ULONG_PTR mFlags;
const NDR_CS_ROUTINES *CsRoutineTables;
void *Reserved4;
ULONG_PTR Reserved5;
} MIDL_STUB_DESC, *PMIDL_STUB_DESC;
And here is how it looks like in windbg, when i put a breakpoint in the NdrClientCall2 function
0:006> .echo "Arguments:"; dds esp+4 L5
Arguments:
06d9ece4 74cc2158 SspiCli!sspirpc_StubDesc
06d9ece8 74cc2322 SspiCli!sspirpc__MIDL_ProcFormatString+0x17a
06d9ecec 06d9ed00
06d9ecf0 91640000
06d9ecf4 91640000
0:006> .echo "PMIDL_STUB_DESC:"; dds poi(esp+4) L20
PMIDL_STUB_DESC:
74cc2158 74cc2690 SspiCli!sspirpc_ServerInfo+0x24
74cc215c 74cca1cd SspiCli!MIDL_user_allocate
74cc2160 74cca1e6 SspiCli!MIDL_user_free
74cc2164 74ce0590 SspiCli!SecpCheckSignatureRoutineRefCount+0x4
74cc2168 00000000
74cc216c 00000000
74cc2170 00000000
74cc2174 00000000
74cc2178 74cc1c52 SspiCli!sspirpc__MIDL_TypeFormatString+0x2
74cc217c 00000001
74cc2180 00060001
74cc2184 00000000
74cc2188 0700022b
74cc218c 00000000
74cc2190 00000000
74cc2194 00000000
74cc2198 00000001
74cc219c 00000000
74cc21a0 00000000
74cc21a4 00000000
74cc21a8 48000000
74cc21ac 00000000
74cc21b0 001c0000
74cc21b4 00000032
74cc21b8 00780008
74cc21bc 41080646
74cc21c0 00000000
74cc21c4 000b0000
74cc21c8 00020004
74cc21cc 00080048
74cc21d0 21500008
74cc21d4 0008000c
0:006> .echo "PFORMAT_STRING:"; db poi(esp+8)
PFORMAT_STRING:
74cc2322 00 48 00 00 00 00 06 00-4c 00 30 40 00 00 00 00 .H......L.0@....
74cc2332 ec 00 bc 00 47 13 08 47-01 00 01 00 00 00 08 00 ....G..G........
74cc2342 00 00 14 01 0a 01 04 00-6e 00 58 01 08 00 08 00 ........n.X.....
74cc2352 0b 00 0c 00 20 01 0a 01-10 00 f6 00 0a 01 14 00 .... ...........
74cc2362 f6 00 48 00 18 00 08 00-48 00 1c 00 08 00 0b 00 ..H.....H.......
74cc2372 20 00 2c 01 0b 01 24 00-a2 01 0b 00 28 00 b8 01 .,...$.....(...
74cc2382 13 41 2c 00 a2 01 13 20-30 00 f8 01 13 41 34 00 .A,.... 0....A4.
74cc2392 60 01 12 41 38 00 f6 00-50 21 3c 00 08 00 12 21 `..A8...P!<....!
So how exactly do i figure out what is the remote process it is going to communicate with, or what pipe it is using to communicate?
As far as i understand from the MSDN, it is supposed to call a remote procedure. if i understand that right, it means it should call a remote function as if its an exported dll function. How can i set a breakpoint there?
P.S:
The main reason im posing this function is because the NdrClientCall2 seems to be pretty huge.
A:
So how exactly do i figure out what is the remote process it is going
to communicate with, or what pipe it is using to communicate?
The first step is to find the RPC client interface. This can be found via the first argument to NdrClientCall2(), named pStubDescriptor. In your question, pStubDescriptor points to SspiCli!sspirpc_StubDesc:
And here is how it looks like in windbg, when i put a breakpoint in
the NdrClientCall2 function
0:006> .echo "Arguments:"; dds esp+4 L5
Arguments:
06d9ece4 74cc2158 SspiCli!sspirpc_StubDesc
SspiCli!sspirpc_StubDesc is a MIDL_STUB_DESC, and on my computer, here are its associated values (via IDA Pro):
struct _MIDL_STUB_DESC const sspirpc_StubDesc MIDL_STUB_DESC
<
offset dword_22229B8,
offset SecClientAllocate(x),
offset MIDL_user_free(x),
<offset unk_22383F4>,
0,
0,
0,
0,
offset word_22224B2,
1,
60001h,
0,
700022Bh,
0,
0,
0,
1,
0,
0,
0
>
As documented on MSDN, the first field in the structure above "points to an RPC client interface structure". Thus, we can parse the data at that address as an RPC_CLIENT_INTERFACE struct:
stru_22229B8 dd 44h ; Length
dd 4F32ADC8h ; InterfaceId.SyntaxGUID.Data1
dw 6052h ; InterfaceId.SyntaxGUID.Data2
dw 4A04h ; InterfaceId.SyntaxGUID.Data3
db 87h, 1, 29h, 3Ch, 0CFh, 20h, 96h, 0F0h; InterfaceId.SyntaxGUID.Data4
dw 1 ; InterfaceId.SyntaxVersion.MajorVersion
dw 0 ; InterfaceId.SyntaxVersion.MinorVersion
dd 8A885D04h ; TransferSyntax.SyntaxGUID.Data1
dw 1CEBh ; TransferSyntax.SyntaxGUID.Data2
dw 11C9h ; TransferSyntax.SyntaxGUID.Data3
db 9Fh, 0E8h, 8, 0, 2Bh, 10h, 48h, 60h; TransferSyntax.SyntaxGUID.Data4
dw 2 ; TransferSyntax.SyntaxVersion.MajorVersion
dw 0 ; TransferSyntax.SyntaxVersion.MinorVersion
dd offset RPC_DISPATCH_TABLE const sspirpc_DispatchTable; DispatchTable
dd 0 ; RpcProtseqEndpointCount
dd 0 ; RpcProtseqEndpoint
dd 0 ; Reserved
dd offset _MIDL_SERVER_INFO_ const sspirpc_ServerInfo; InterpreterInfo
dd 4000000h ; Flags
From the RPC_CLIENT_INTERFACE struct above, we can extract the InterfaceId GUID: 4F32ADC8-6052-4A04-8701-293CCF2096F0
We can now look up that interface GUID with RpcView to find the associated DLL, running process, and endpoints:
To find out which specific endpoint is being used by the SSPI RPC server in the LSASS process, we can reverse engineer sspisrv.dll. In the exported function SspiSrvInitialize(), we see the following call:
RpcServerUseProtseqEpW(L"ncalrpc", 0xAu, L"lsasspirpc", 0);
To figure out which specific function is being called in sspisrv.dll, we need to look at the pFormat data passed to NdrClientCall2. In your example code above, the pFormat data is:
00 48 00 00 00 00 06 00-4c 00 30 40 00 00 00 00 ...
If we parse the pFormat data as an NDR_PROC_HEADER_RPC structure, we get:
handle_type = 0x00
Oi_flags = 0x48
rpc_flags = 0x00000000
proc_num = 0x0006
stack_size = 0x004C
From proc_num, we can see that this RPC call is calling the 6th RPC function in sspisrv.dll. We can use RpcView again to get the address for the 6th RPC function:
And with IDA Pro, we can see the function in sspisrv.dll at address 0x7573159D:
.text:7573159D __stdcall SspirProcessSecurityContext(x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x) proc near
RpcView also shows us a decompilation of that function's prototype:
(Note that on your computer, the 6th function might not be at virtual address 0x7573159D, and furthermore, the 6th function might not be SspirProcessSecurityContext(), but this is the approach you would use nonetheless.)
As such, we can now say the following:
The RPC server code for your NdrClientCall2() call is in sspisrv.dll
The RPC server for your NdrClientCall2() call is running in LSASS's process
The endpoint for your NdrClientCall2() call is named lsasspirpc
The RPC server function called by your NdrClientCall2() call in sspisrv.dll is SspirProcessSecurityContext()
| {
"pile_set_name": "StackExchange"
} |
Q:
WPF Button Inner Border
I am new to WPF development, I am creating a button style as per my designer provided it.
While creating button, I am facing an weird problem. I am not finding way Remove button Radius. I tried "Round Corner = false", but it is removing only Right side round corners. Moreover I am not finding way how to remove Inner silver border in button. I think this issue is caused because there is a default style applied to button, (chrome style in my case).
Is there any way to can I remove all round corners and Inner Border.
Thanks in anticipation.
A:
see this link http://msdn.microsoft.com/en-us/library/cc278069%28v=vs.95%29.aspx
and the
<ControlTemplate TargetType="Button">
part and find this line
<Border x:Name="Background" CornerRadius="3" ...
and as you gussed this is why. To change, you should use your custom style.
this linke might help you too: http://msdn.microsoft.com/en-us/magazine/cc163421.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Not catching ajax request
I am having request like this:
$(function(){
$("#novaProfaktura").click(function(){
$.ajax({
type: "POST",
url: "../Pages/Program.php",
data: { action: "testing" },
success: function()
{
alert("Ajax done"); //Testing purpose
}
});
location.reload();
});
});
And then in my body I have php like this:
<div id="Content">
<?php
echo("Php running <br>");
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo("Post running <br>");
if($_POST['action'] = "testing")
{
echo("Action running <br>");
}
}
?>
</div>
What I am getting from this is alert message so I assume ajax is set up properly and getting Php running but it doesn't pass if($_SERVER['REQUEST_METHOD'] == 'POST'
As you can see jQuery code is running on div click.
What am I doing wrong?
EDIT: I have used function(data) and it seems to work BUT it doesn't return only echoed data but WHOLE page with echo. I used document.write() and it rewrite whole page but how to get particular echo value?
A:
Answer for this was to instead of this:
success: function()
{
alert("Ajax done"); //Testing purpose
}
use this:
success: function(data)
{
alert("Ajax done"); //Testing purpose
document.getDocumentById('emptyDiv').innerHTML = data;
}
Now as data you are getting all HTML text from document you are running function from so instead of url: "../Pages/Program.php" I used separated file url: "../Php/Testing.php" and inside that file I have
only this code:
<?php
echo("Testing");
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Access to all request from chrome extension level
It is possible to have access to all request on a page from chrome extension level.
To see a list like in network tab or to be able to manipulate/filter request.
A:
There is the chrome.webRequest API which allows you to register listeners for various events in a request's lifecycle:
onBeforeRequest
onBeforeSendHeaders
onSendHeaders
onHeadersReceived
onAuthRequired
onResponseStarted
onBeforeRedirect
onCompleted
onErrorOccurred
Some of the events are also subject to interception and even modification (e.g. modifying the request or response headers).
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple Factory Pattern in C#
I am trying to create a simple factory pattern. Below is my sample code:
IMobile:
namespace SimpleFactory
{
public interface IMobile
{
void Hello();
}
}
IPhone:
namespace SimpleFactory
{
public class Iphone : IMobile
{
public void Hello()
{
Console.WriteLine("Hello, I am Iphone!");
}
}
}
Nokia
namespace SimpleFactory
{
public class Nokia : IMobile
{
public void Hello()
{
Console.WriteLine("Hello, I am Nokia!");
}
}
public void NokiaClassOwnMethod()
{
Console.WriteLine("Hello, I am a Nokia class method. Can you use me
with Interface");
}
}
MobileFactory:
namespace SimpleFactory
{
public class MobileFactory
{
public IMobile GetMobile(string mobileType)
{
switch (mobileType)
{
case "Nokia":
return new Nokia();
case "iPhone":
return new Iphone();
default:
throw new NotImplementedException();
}
}
}
}
Program:
namespace SimpleFactory
{
class Program
{
static void Main(string[] args)
{
MobileFactory factory = new MobileFactory();
IMobile mobile = factory.GetMobile("Nokia");
mobile.Hello();
mobile.NokiaClassOwnMethod();
}
}
}
I would like to access NokiaClassOwnMethod method of the Nokia and Iphone. Can I access NokiaClassOwnMethod method of the Nokia or Iphone class. If not, why? (I can add this NokiaClassOwnMethod method to the Interface and able to access it. But my question is How I can access class own methods? )
A:
In order to do that you will need to add Hello method to your interface:
public interface IMobile
{
void Hello();
}
It was not accessible previously because your factory method returned an interface and interface did not contain Hello() method. So during the runtime different types can be returned and when you call Hello child specific class implementation will be called.
If you want to have access to method/property that doesn't exist in interface but in the concrete implementation, you will need to cast:
MobileFactory factory = new MobileFactory();
IMobile mobile = factory.GetMobile("Nokia");
var iPhone = mobile as Iphone;
if(iPhone != null) iPhone.Hello();
| {
"pile_set_name": "StackExchange"
} |
Q:
NSFileHandle and scanf not echoing input in Xcode 4.5
I successfully use NSFileHandle to read keyboard input:
NSFileHandle * keyboard = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [keyboard availableData];
NSString * input =[[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding];
As the user types, only the first character of input is echoed on the screen. For example, if I type hello, only h is echoed on the screen. However the full input is read into the string.
The proper echo behavior works in Xcode 4.2. I'm currently using Xcode 4.5.
UPDATE
Giving up on NSFileHandle for now, I tried to use scanf. However there's the same echoing issue. scanf code:
char word[4];
scanf("%s",word);
NSString * input = [[NSString alloc] initWithBytes:word length:4 encoding:NSUTF8StringEncoding];
A:
This is a bug in Xcode 4.5. When the console is refreshed all echoed input is revealed.
| {
"pile_set_name": "StackExchange"
} |
Q:
which one of the following phrase is correct?
Which phrase is correct?
The shipped order has been dropped
The shipped order have been dropped
A:
The correct answer is: The shipped order has been dropped. The other sentence is incorrect because the verb does not agree with the noun. If you wanted the second sentence to be correct, you would need to change the noun from singular to plural. Then the sentence would be: The shipped orders have been dropped.
| {
"pile_set_name": "StackExchange"
} |
Q:
what is the wrong with this script
def hotel_cost(nights):
cost = nights * 40
return cost
def plane_ride_cost(city):
if city == "charolette":
cost = 180
elif city == "los angeles":
cost = 480
elif city == "tampa":
cost = 200
elif city == "pittspurgh":
cost = 220
return cost
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def trip_cost(city, days, spending_money):
return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days)\ + spending_money
city_list = ("charolette", "los angeles", "tampa", "pittspurgh")
print "we only support one of those cities" + str(city_list)
city = raw_input (" please choose the city you want to go ")
days = 0
spending_money = 0
if city in city_list:
days = raw_input("how much days you wanna stay ")
spending_money = raw_input("how much money do you wanna spend there")
print trip_cost(city, days, spending_money)
else:
print 'error'
it always generate this error
rint trip_cost(city, days, spending_money)
File "/home/tito/test 3 .py", line 23, in trip_cost
return (hotel_cost(days)) + (plane_ride_cost(city)) + (rental_car_cost(days)) + (spending_money)
TypeError: cannot concatenate 'str' and 'int' objects
A:
Converting the user input to the appropriate data types should help:
if city in city_list:
days = int(raw_input("how many days you wanna stay "))
spending_money = float(raw_input("how much money do you wanna spend there"))
You always get a string back from raw_input. You can convert a string into an integer with int() or to a float with float(). You will get an ValueError exception, if the string cannot be converter into this data type.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i force Highcharts to use same symbols in Legend and Series?
i try to draw multiple series with specific symbols(Highcharts standard symbols). But the symbols in series and in legend dont match. In series they are displayed correctly, but in legends they are kind of random...
Example: http://jsfiddle.net/ogkh77r7/1/
$(function () {
var chart = new Highcharts.Chart({
"chart":{
"zoomType":"xy",
"renderTo":"container"
},
"title":{
"text":null
},
"subtitle":{
"text":"text"
},
"xAxis":{
"min": - 14,
"max":25,
"title":{
"text":"text"
},
"tickPositions":[ - 14, - 10, - 5, 0, 5, 10, 15, 20, 25],
"plotLines":[{
"color":"#C0D0E0",
"width":1,
"value": - 14}]
},
"yAxis":{
"title":{
"text":"text"
},
"min":0,
"max":967
},
"plotOptions":{
"series":{
"marker":{
"enabled":true
}
}
},
"tooltip":{
"shared":false,
"useHTML":true,
"formatter":null,
"style":{
"border":"none !important",
"padding":"0px",
"font-size":"1em"
}
},
"series":[{
"type":"line",
"name":"s1",
"zIndex":20,
"data":[
{"x": - 14, "y":560.944, "marker":{"symbol":"circle"}},
{"x":15.333, "y":0, "marker":{"symbol":"circle"}}
]
},{
"type":"line",
"name":"s2",
"zIndex":19,
"data":[
{"x": - 14, "y":5.848, "marker":{"symbol":"circle"}},
{"x":25, "y":5.848, "marker":{"symbol":"circle"}}
]
},{
"type":"scatter",
"name":"s3",
"zIndex":10,
"data":[
{"x":0.8, "y":266.667, "marker":{"symbol":"circle"}},
{"x":2.513, "y":242.857, "marker":{"symbol":"circle"}},
{"x":1.675, "y":253.571, "marker":{"symbol":"circle"}}
]
},{
"type":"scatter",
"name":"s4",
"zIndex":9,
"data":[
{"x":13.263, "y":35.119, "marker":{"symbol":"diamond"}},
{"x":16.989, "y":13.021, "marker":{"symbol":"diamond"}},
{"x":16.2, "y":9.375, "marker":{"symbol":"diamond"}}
]
}, {
"type":"scatter",
"name":"s5",
"zIndex":30,
"data":[
{"x": - 14, "y":650.19492, "marker":{"radius":6, "symbol":"triangle"}}
]
}, {
"type":"scatter",
"name":"s6",
"zIndex":30,
"data":[
{"x":15, "y":5.8, "marker":{"radius":6, "symbol":"triangle-down"}}
]
}
],
"colors":["#2f7ed8", "#2f7ed8", "#b2b2b2", "#c4c4c4", "#f15c80", "#f15c80"]
});
});
I use Highcharts and Highstock on the same page, so i need to use highstock.js. Using highcharts.js dont fix the problem anyway.
Would be amazing if someone could help me with this, but i guess its a bug in Highcharts?
So long,
RaTm7
A:
You have to set your marker definitions on the series, not the data.
{
"type":"scatter",
"name":"s4",
"zIndex":9,
"marker": {
"symbol": "diamond"
},
"data":[
{"x":13.263, "y":35.119},
{"x":16.989, "y":13.021},
{"x":16.2, "y":9.375}
]
}
http://jsfiddle.net/8ma4ts9s/
| {
"pile_set_name": "StackExchange"
} |
Q:
How to target this HTML in CSS?
I'm trying to style Vanilla Forums and I just can't seem to figure out to select this class <li class="Item Announcement"></li> so that I can style it.
I don't know why it's being so difficult. Why would this not work?
.Item Announcement {
background-color: #FFF;
{
A:
Try:
li.Item.Announcement {
background-color: #FFF;
}
That list item has two classes applied to it (Item and Announcement). So to target that with CSS, you need to prefix each class with a period and then remove the spaces. Leaving the spaces in the CSS selector would apply it to a descendant element that had the class.
Quick jsFiddle example.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to turn on/off the monitor(s)?
I wanted to be able to turn on/off my monitors from a Delphi script, from Windows XP to 7.
I have searched within the Delphi section on stackoverflow and didn't find the answer.
I also found many samples which doesn't work anymore on Windows 7 (only with XP).
A:
I have successfully tested this on Windows XP and Windows 7:
const
MONITOR_ON = -1;
MONITOR_OFF = 2;
MONITOR_STANDBY = 1;
To turn off the monitor:
SendMessage(Application.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);
To turn on the monitor:
SendMessage(Application.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_ON);
| {
"pile_set_name": "StackExchange"
} |
Q:
opera driver is not working with Selenium - Java
I'm writing cross browser test script using Selenium web driver - Java. My firefox, chrome and IE browsers are opening and successfully running the script. But, in opera, only the browser is opening. Even driver.manage().window().maximize(); also not working. Just open the browser and stay until I close it. When I close the browser manually, test suite fails.
Here is my java class.
package multiBrowser;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.testng.annotations.Parameters;
public class MultiBrowserClass {
WebDriver driver;
@Test
@Parameters("browser")
public void multiBrowsers(String browserName) throws InterruptedException{
if(browserName.equalsIgnoreCase("firefox")){
System.setProperty("webdriver.firefox.marionette","D:\\My Work\\Setup\\JAR\\geckodriver.exe");
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
driver = new FirefoxDriver(myprofile);
}
if(browserName.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", "D:\\My Work\\Setup\\JAR\\driver\\chromedriver.exe");
driver = new ChromeDriver();
}
else if(browserName.equalsIgnoreCase("IE")){
System.setProperty("webdriver.ie.driver", "D:\\My Work\\Setup\\JAR\\driver\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
else if(browserName.equalsIgnoreCase("opera")){
System.setProperty("webdriver.opera.driver", "D:\\My Work\\Setup\\JAR\\driver\\operadriver.exe");
driver = new OperaDriver();
}
driver.manage().window().maximize();
driver.navigate().to("https://");
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//div[@id='navbar-main']/ul/li[5]/a")).click();
driver.findElement(By.xpath("//div[@id='navbar-main']/ul/li[5]/ul/li/a")).click();
Thread.sleep(3000);
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("[email protected]");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("1qaz2wsx");
Thread.sleep(3000);
driver.findElement(By.xpath("//form[@id='loginform']/div[8]/button")).click();
Thread.sleep(5000);
if(driver.getPageSource().contains("Welcome [email protected]")){
System.out.println("User Successfully logged in");
}else{
System.out.println("Username or password you entered is incorrect");
}
driver.quit();
}
}
Here is the testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<!-- firefox -->
<test name="FirefoxTestCases">
<parameter name="browser" value="firefox"/>
<classes>
<class name="multiBrowser.MultiBrowserClass"/>
</classes>
</test>
<!-- chrome -->
<test name="ChromeTestCases">
<parameter name="browser" value="chrome"/>
<classes>
<class name="multiBrowser.MultiBrowserClass"/>
</classes>
</test>
<!-- internet explorer -->
<test name="IETestCases">
<parameter name="browser" value="IE"/>
<classes>
<class name="multiBrowser.MultiBrowserClass"/>
</classes>
</test>
<!-- Opera -->
<test name="OperaTestCases">
<parameter name="browser" value="opera"/>
<classes>
<class name="multiBrowser.MultiBrowserClass"/>
</classes>
</test>
</suite> <!-- Suite -->
I've downloaded operadriver from this page (operadriver_win64.zip).
Here is how Opera browser is opening.
Opera version is 41.0.2353.56.
Thanks in advance. :)
A:
Figured out the answer.
System.setProperty("webdriver.chrome.driver", "D:\\My Work\\Setup\\JAR\\driver\\operadriver.exe");
driver = new Chro,eDriver();
Then installed opera 38. Problem solved. :)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to hide a link from a screen-reader?
I have a link which I want to show to visitors with vision, but hide from visitors using screen-reader ATs.
This is the reverse of the usual problem (with known solution) of hiding content from vision visitors (e.g. a "skip to content" link)
An example:
Clicking the "read more" link expands the text inline.
and conversely, clicking the "read less" link collapses it again.
This collapsed/expanding text functionality is only of benefit to visitors with vision, whose field of view would take in the extra text before they get to it (and in this example displaces the next FAQ, pushing it off screen).
A visitor with a screen-reader should instead be presented with the full text as they can choose to skip ahead to the next block, and they shouldn't encounter a spurious "read more" link which (a) doesn't link to a page, and (b) simply gives them what they were about to hear from their screen reader anyway.
How would this be done in HTML5?
A:
Use aria-hidden this way for the content:
<p aria-hidden="true">Screen readers will not read this!</p>
| {
"pile_set_name": "StackExchange"
} |
Q:
XSLT 2.0 node variable select by attribute
The XML File:
<XML>
<Item ID = "test1"></Item>
<Item ID = "test2"></Item>
</XML>
Result:
<XML>
<Item ID = "TEST01"></Item>
<Item ID = "TEST02"></Item>
</XML>
In my XSLT 2.0 file I want to acess the NewID of the variable if the currentID is equal to the OldID in order to change the attributes value with the predefined NewID.
<xsl:variable name="Items">
<Item OldID="test1" NewID = "TEST01"></Item>
<Item OldID="test2" NewID = "TEST02"></Item>
</xsl:variable>
<xsl:template match="XML">
<xsl:copy>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="Item">
<xsl:copy-of select="@*[name()!='ID']" />
<xsl:attribute name="ID">
<xsl:value-of select="$Items/Item[@OldID = @ID]/@NewID"/>
</xsl:attribute>
</xsl:copy>
</xsl:template>
A:
Try:
<xsl:value-of select="$Items/Item[@OldID = current()/@ID]/@NewID"/>
--
P.S. Suggested reading: http://www.w3.org/TR/xslt20/#key
| {
"pile_set_name": "StackExchange"
} |
Q:
Measuring 0-250V and 10A (AC) with arduino
So,
I've decided to make a "homemade variac", but for simple things, such as lightbulbs, etc. Just to try things. So I'm going to use a voltage regulator to regulate AC voltage between 0 and 230V, where current can be up to 8A (according to voltage regulator's "max. power", but I think never will go higher than 3-5A).
Now, the question here is: How can I properly measure AC voltage and current, which I intend to show on LCD display? Which modules would be proper to use?
( I intended to use these voltmeters, but couldn't find one for AC current 0-10A, so I decided, to make it on a display and show also input voltage, input current, power and Wh.)
A:
By using that cheap SCR "chopper" you have created a measurement problem for yourself. Since you have a non-sinusoidal waveform, you need a "true RMS" measurement scheme for BOTH voltage and current.
You can certainly find RMS conversion chips that will allow you to construct a circuit that accurately reports equivalent RMS voltage and current. But that is not a trivial thing you can throw together with an Arduino. The measurement of your "dirty" power has now become the primary project vs. a simple measurement task.
It seems unlikely that you can find any of those inexpensive digital voltage/current meters on Ebay that will read true RMS. Even if you could find one that is powered separately (so that it will measure down to zero).
If you want to use a cheap, noisy chopper SCR controller like that, then you must pay at the other end with RMS metering. There are reviews on YouTube for popular-price, commodity DMMs which have true RMS, and they are relatively inexpensive. For example you could start here with Dave Jones' Digital Multimeter Buying Guide for Beginners: https://youtu.be/gh1n_ELmpFI
If you are going to be experimenting with SCR choppers and mains power, then you need a couple of decent DMMs with true RMS anyway. And you would need at least one anyway in order to calibrate your Arduino circuit with the RMS chips.
| {
"pile_set_name": "StackExchange"
} |
Q:
Почему marker-mid не отображается?
<svg version="1" xmlns="http://www.w3.org/2000/svg" width="200" height="200"
style="border:1px solid crimson" viewBox='0 0 200 200'>
<defs>
<marker id='MarkerArrow'refX='0' refY='10' markerUnits='userSpaceOnUse' orient='auto' markerWidth='20' markerHeight='20'>
<polyline id="markerPoly1" points="0,0 20,10 0,20 2,10" fill="crimson" />
</marker>
<marker id="MarkerCircle" refX="0" refY="5"
markerUnits="userSpaceOnUse"
markerWidth="10" markerHeight="10">
<circle cx="5" cy="5" r="5" fill="crimson" />
</marker>
<marker id='MarkerCircleMid' markerWidth='30' markerHeight='30' refX='10' refY='0' orient='auto' markerUnits='userSpaceOnUse' >
<circle r="5" cx="10" cy="10" fill="black" stroke="black" stroke-width="2"/>
</marker>
</defs>
</defs>
<line x1='0' y1='100' x2='100' y2='100' fill='none' stroke='blue' stroke-width='5' style="marker-start: url(#MarkerCircle); marker-mid: url(#MarkerCircleMid); marker-end: url(#MarkerArrow)"; />
</svg>
A:
marker-mid появляется только на изломах линии, а у вас была прямая линия
<svg version="1" xmlns="http://www.w3.org/2000/svg" width="200" height="200"
style="border:1px solid crimson" viewBox='0 0 200 200'>
<defs>
<marker id='MarkerArrow'refX='0' refY='10' markerUnits='userSpaceOnUse' orient='auto' markerWidth='20' markerHeight='20'>
<polyline id="markerPoly1" points="0,0 20,10 0,20 2,10" fill="crimson" />
</marker>
<marker id="MarkerCircle" refX="0" refY="5"
markerUnits="userSpaceOnUse"
markerWidth="10" markerHeight="10">
<circle cx="5" cy="5" r="5" fill="crimson" />
</marker>
<marker id='MarkerCircleMid' markerWidth='10' markerHeight='10' refX='2' refY='2' orient='auto' markerUnits='userSpaceOnUse' >
<circle r="4" cx="5" cy="5" fill="green" stroke="black" stroke-width="1"/>
</marker>
</defs>
<polyline points=" 50,80 140,80 80,100 180,100 160,85 160,150 " fill='none' stroke='blue' stroke-width='5' style="marker-start: url(#MarkerCircle); marker-mid: url(#MarkerCircleMid); marker-end: url(#MarkerArrow)"; />
</svg>
| {
"pile_set_name": "StackExchange"
} |
Q:
F# passing an operator with arguments to a function
Can you pass in an operation like "divide by 2" or "subtract 1" using just a partially applied operator, where "add 1" looks like this:
List.map ((+) 1) [1..5];; //equals [2..6]
// instead of having to write: List.map (fun x-> x+1) [1..5]
What's happening is 1 is being applied to (+) as it's first argument, and the list item is being applied as the second argument. For addition and multiplication, this argument ordering doesn't matter.
Suppose I want to subtract 1 from every element (this will probably be a common beginners mistake):
List.map ((-) 1) [1..5];; //equals [0 .. -4], the opposite of what we wanted
1 is applied to the (-) as its first argument, so instead of (list_item - 1), I get (1 - list_item). I can rewrite it as adding negative one instead of subtracting positive one:
List.map ((+) -1) [1..5];;
List.map (fun x -> x-1) [1..5];; // this works too
I'm looking for a more expressive way to write it, something like ((-) _ 1), where _ denotes a placeholder, like in the Arc language. This would cause 1 to be the second argument to -, so in List.map, it would evaluate to list_item - 1. So if you wanted to map divide by 2 to the list, you could write:
List.map ((/) _ 2) [2;4;6] //not real syntax, but would equal [1;2;3]
List.map (fun x -> x/2) [2;4;6] //real syntax equivalent of the above
Can this be done or do I have to use (fun x -> x/2)? It seems that the closest we can get to the placeholder syntax is to use a lambda with a named argument.
A:
You could write a flip function, something like:
let flip f x y = f y x
List.map (flip (-) 1) [2;4;6]
I may have the syntax wrong, I'm not terribly fluent in F#.
A:
There are no 'operation sections' in F#, a la Haskell, nor placeholder arguments (apparently a la Arc). You can use a 'flip' combinator as suggested in another answer to reverse the order of arguments and then partially apply the first (now second) argument.
But I would just use
fun x -> x / 2
Unless you're playing code-golf, I don't think trying to shave another few characters off here buys you anything.
A:
The flip-solution suggested by Logan Capaldo can also be written using a operator (here >.):
let (>.) x f = (fun y -> f y x)
List.map (1 >. (-)) [2;4;6]
Or if you prefer the operands the other way around:
let (>.) f x = (fun y -> f y x)
List.map ((-) >. 1) [2;4;6]
Edit: Using an operator that "looks more like a placeholder" (here >-<) gets you very close to your suggested syntax:
List.map ((-) >-< 1) [2;4;6]
'_' is unfortunatly(?) not a valid operator symbol in F#.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSScrollView and manually setting the content offset while scrolling
I am trying to build an endless NSScrollView, i.e. a scroll view that can scroll infinitely in either direction. This is achieved by having a scroll view with fixed dimension which is 'recentered' once it gets too close to either edge, and keeping track of an additional endless offset that is updated when recentering. Apple even demonstrated this approach in a WWDC video for iOS, if I recall correctly.
On iOS everything is working. I perform the recentering logic in -scrollViewDidScroll: and it even works when the scrolling motion is decelerating without breaking the deceleration.
Now for the Mac version. Let me tell you that I'm fairly new to Mac development, so I may simply not have performed these operations in the correct places. I currently have the recentering logic in -reflectScrolledClipView:. When I perform the move operation immediately, however, the scroll view jumps exactly twice as far as I want it to (in this case, to 4000). If I delay the method slightly, it works just as expected.
- (void)reflectScrolledClipView:(NSClipView *)cView
{
[self recenteringLogic];
[super reflectScrolledClipView:cView];
}
- (void)recenteringLogic
{
CGFloat offset = self.documentVisibleRect.origin.y;
if (offset > 6000) {
// This makes the scroll view jump to ~4000 instead of 5000.
[self performSelector:@selector(move) withObject:nil];
// This works, but seems wrong to me
// [self performSelector:@selector(move) withObject:nil afterDelay:0.0];
}
}
- (void)move
{
[self.documentView scrollPoint:NSMakePoint(0, 4000)];
}
Any ideas on how I could achieve the behavior I want?
A:
I ended up working with [self performSelector:@selector(move) withObject:nil afterDelay:0.0]; and haven't encountered any serious issues with it, despite it seeming a little wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change tomcat version in Tomcat maven plugin?
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
By default this plugin gives Tomcat version 7.0.37, how can we point to Tomcat version 7.0.91?
As our security team came up with some vulnerabilities for 7.0.37, we need to upgrade to 7.0.91.
Is there any way we can configure the dependencies for the plugin?
A:
there is a newer version of tomcat7-maven-plugin which uses the tomcat 7.0.47 version. Maybe you want to give it a try.
if you really want to update the version referenced by the plugin you can try to exclude the particular references in the plugin and add dependencies in the dependencies section for the ones you excluded.
<dependencies>
...
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-util</artifactId>
<version>7.0.91</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-util</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</plugin>
<plugins>
<build>
| {
"pile_set_name": "StackExchange"
} |
Q:
PhantomJS was placed in path and can execute in terminal, but PATH error in Python
note: PhantomJS runs in PyCharm environment, but not IDLE
I have successfully used PhantomJS in Python in the past, but I do not know what to do to revert to that set up.
I am receiving this error in Python (2.7.11): selenium.common.exceptions.WebDriverException: Message: 'phantomjs' executable needs to be in PATH.
I have tried to 'symlink' phantomjs to the path (usr/local/bin [which is also in the path]), and even manually locate /usr/local/bin to place phantomjs in the bin folder. However, there is still a path error in python.
What am I missing?
A:
I solved this by passing the executable_path keyword arg to the driver constructor. For example:
driver = webdriver.PhantomJS(executable_path="/Path/to/driver/phantomjs")
Note that this must be the driver file itself, not the folder which contains it.
Thanks to PhantomJS() not running in pyCharm for hinting at this solution.
A:
After placing phantomjs in the folder /usr/bin, the application ran successfully. To access the folder directly, open a finder window, click 'Go' menu at top of screen, click 'Go to folder...', enter '/usr/bin'. Note that if on Mac OS El Capitan or newer, there is a default restriction to this folder which can be disabled
| {
"pile_set_name": "StackExchange"
} |
Q:
What does mean in TypeScript generics?
We use express with TypeScript in our app. I came across their type definitions and was wondering what the following means:
export interface IRouter extends RequestHandler {
all: IRouterMatcher<this>;
}
In particular, the IRouterMatcher<this>.
I read the docs a few times and couldn't find anything mentioning this use case. And it's pretty hard to search for <this> in either SO or the web as the angle brackets usually get stripped.
A:
this refers to the current available type.
This might also be the subtype of the overridden class or interface.
See also Polymorphic this types in https://www.typescriptlang.org/docs/handbook/advanced-types.html
Example:
class Calculator {
a: number;
add(): this {
a++;
return this;
}
}
class AdvancedCalculator {
substract(): this {
a--;
return this;
}
}
new AdvancedCalculator()
.add() // returns AdvancedCalculator as "this"
.substact() // it compiles!
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing Installation Path as input to dll - basic MSI - InstallShield 2012
Passing installation path selected from Destination Folder Dialog as input to a DLL from a custom dialog.
I am designing a basic MSI installer project using InstallShield 2012. I have designed a custom dialog to get user login info etc. in a custom dialog and it passes the details to the DLL which then creates a database accordingly. However I need to know how to pass the installation path [chosen in Destination Folder Dialog] as input to the dll so my DB is created inside the proper folders. My DLL action is executed after Installfiles.
Thanks in advance !! I'd be happy to explain if you are unable to understand the above ..
A:
You can't pass the values to the DLL directly, like in a command line.
You would store the values entered by user in a property, then your DLL custom action uses MsiGetProperty to get these properties from MSI session.
If your custom action needs to be run elevated during the commit phase of the installer, you'll have to pack both values in CustomActionData property. See Obtaining Context Information for Deferred Execution Custom Actions for more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Создание приложения для сайта на Android
Для расширения своего кругозора, прошу совета и подсказок в создание приложения для Android.
Задача следующая:
Необходимо написать приложение, которое осуществляло те же функции, что и сайт. А именно:
Вывод новостей, статей и т.п.
Поиск по сайту
Добавление комментариев к статьям и новостям
Просмотр каталога с графической и текстовой информациии
Личный кабинет пользователя
и т.д.
По идеи тот же сайт, только работает как приложение.
Подскажите с чего начать?
Что почитать (желательно с хорошими примерами), что изучить и вообще что для этого нужно. Т.е. нужна инструкция молодого бойца:)
A:
Два способа. Дурной и правильный.
Ваше приложение лишь парсер обычного сайта. Скачиваете нужные страницы, парсите html, выводите в виде пригодном для мобильного клиента. Способ уродский и может подойти лишь для сайтов находящихся не в вашем управлении и достаточно простых (а-ля башорг и пр.). При минимальной смене дизайна сайта - переделываете приложение полностью.
Сайт имеет API для обращения. Т.е. наборы методов, которые получают строго формализованные запрос и возвращают лишь необходимые данные т.е. контент. Оформление делаете средствами мобильного приложения. Если API нет, делаете его или идете читать 1 пункт.
пример API
A:
Можно сделать приложение, основанное на WebWiew и взаимодействовать с ним с помощью JavaScript, почитайте здесь
| {
"pile_set_name": "StackExchange"
} |
Q:
How does galvanised steel culvert withstand abrasion from solid particles in the stream?
Zinc-coated roofing steel loses its zinc coat after about ten years because of being exposed to elements and it has to be painted. Zinc-coated powerline posts lose zinc too and experience corrosion, however they are built of thick parts which are "eaten up" slowly and once enough cross-section is lost they are replaced.
However I've recently seen a culvert assembled from pieces of corrugated steel with coating looking like zinc. Parts were something like 5 millimeters thick and connected with numerous bolts and the culvert diameter was about 1,5 meters.
The water passing through a culvert bring sand and other particles which surely grind the surface. I assume this should remove the coating from the submerged part of the culvert within several years and then corrosion will start and eat the not so thick steel rather quickly.
How is abrasion by solid particles addressed in culverts made of galvanized steel?
A:
The design and establishment of a culvert, or any structure, is influenced by the materials available, the environmental conditions that the culvert will withstand, water pH, soil type and the amount of money available for the project.
Nothing lasts for ever and all engineering structures have an anticipated/designed service life, after which, if possible the service life of the structure may be extended by some form of refurbishment or the structure is replaced.
By way of example, this manufacturer of steel pipes, makes pipes that can be used for culverts and the service life of each the product depends on the different type of coatings applied to the pipes:
Zinc – 25 years
Aluminium – 75 years
Asphalt & polymer laminate – 100 years
As the website state:
choice of coatings depends on the soil conditions and other site or application factors
If galvanised steel is being used in a culvert there is already an expectation that it's service life will be less than if it were constructed from something else such as aluminium or concrete.
This site has a design guideline for culvert design. Point 4 states:
Determine which abrasion level most accurately describes the typical storm event (2 year storm). The expected stream velocity and associated abrasion conditions should be based on a typical flow and not a 10 or 50-year design flood
and Point 5 states:
determine whether the structural gage for the selected material is sufficient for the design service
life
If galvanised steel has been used to construct a culvert it's design life has been determined and accepted and deemed suitable for the application based on factors such as these.
| {
"pile_set_name": "StackExchange"
} |
Q:
Confirm application closure when pressing back button
How can I make it so that pressing the back button does not close my application? I want to display a confirmation message.
Thank you.
A:
Source: Override back button to act like home button
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Display confirmation here, finish() activity.
return true;
}
return super.onKeyDown(keyCode, event);
}
That was a very quick search, try to look a little next time.
A:
Application close confirmation is here
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to close?")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do finish
ImageViewActivity.this.finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do nothing
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
return super.onKeyDown(keyCode, event);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this probability answer correct?
In Game 1 the chance of winning 1 dollar is 12/25 and the chance
of losing 1 dollar is 13/25. Let W1 be the total winnings after playing Game 1 100 times.
Let $X_i$ be the total winnings of a single game
Calculate $E(W1)$ and $V(W1)$
So E(W1) is easy to calculate but I'm suspicious about the solution given for V(W1)
The solutions gives the answer as $100V(X_i)$
Is that the right solution? I'm a bit suspicious of it and we have been warned that some of the solutions are wrong.
A:
The variance of the sum of independent variables is equal to the sum of the variances. In this case you have 100 independent, identically distributed (commonly known as i.i.d.) random variables, so the variance of their sum is 100 times the variance of any single one of them. So in this case the given solution is correct.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding NSData attachment to Twitter as an image post
Currently my app gives the option to save to device, or email, the latter attaching the image automatically to the mail, I am looking to add a post to twitter option, simply attaching the image and posting to Twitter, I have done this a few times with other apps, but cannot seem to get this one working.
Here is the process for email;
-(void)displayComposerSheet
{
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
[mail setSubject:@""];
NSString* path =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/email.png"];
[mSplashView SaveResultImage:path];
[mail addAttachmentData:[NSData dataWithContentsOfFile:path] mimeType:@"image/png" fileName:@"Attached image"];
NSString *msg = [NSString stringWithFormat:@"I made this image!", [UIDevice currentDevice].model];
NSString* mailcontent = [NSString stringWithFormat:@"<br> %@ <br>", msg];
[mail setMessageBody:mailcontent isHTML:YES];
[self presentModalViewController:mail animated:YES];
[mail release];
}
I am struggling to see how I can use similar to attach the image to Twitter, I currently use this code, but it crashes when attempting to post;
TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
[self presentViewController:twitter animated:YES completion:nil];
NSString* path =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/email.png"];
[mSplashView SaveResultImage:path];
[twitter setInitialText:@"I made this image!"];
[twitter addURL:[NSData dataWithContentsOfFile:path]];
twitter.completionHandler = ^(TWTweetComposeViewControllerResult res) {
if(res == TWTweetComposeViewControllerResultDone) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Thank you" message:@"Posted successfully to Twitter." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
}
if(res == TWTweetComposeViewControllerResultCancelled) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Cancelled" message:@"You Cancelled posting the Tweet." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
}
[self dismissViewControllerAnimated:YES completion:nil];
};
}
Normally I could simply call [twitter addImage:]; but unfortunately it seems the image is not grabbed correctly without going through the processes above in the mail sheet.
A:
You can't pass NSData for -addURL: method.
If your image store on disk, you can create image with [UIImage imageWithContentsOfFile:imagePath] method. Next add it with -addImage:
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional formatting
I can make this work:
I have two cells A1 and B1, and if B1 = A1 I would like the cell to turn green.
However, I cannot seem to figure out how to make it generic enough when I copy the formatting for the rest of the column (b2:b100) that it works. Currently it well check the current cell vs A1 all the way down the column.
Im sure this is possible, but google's help documents weren't helpful to me.
A:
Looks like this got it to work
Custom formula is:
=(B1=A1)*(B1<>"")
background color: Green
range ... B:B
| {
"pile_set_name": "StackExchange"
} |
Q:
How to include another website in another using PHP
the title says it all. I've tried using iFrames, but it's not what I need. I have a website where it's echoing data (users on the site, etc..) - but I want to be able to display this data being posted on another website, using PHP to grab the text from the website.
I don't want to use iFrames, since I don't want it in PHP & I don't want the actual link where it's coming from to be shown; so I want it to be all done backend.
Website 1 contains the information I want to be displayed on website 2. For website 2 to access the data; they need to load http://example.com/page.php - where it echo's all the information. And I just want website 2 to echo/display the data in text format. If that makes sense.
A:
$file = file_get_contents('http://www.address.com/something'); // Can be locally too, for example: something.php
echo $file;
Be carefull, this method is not 100% safe, until You are not 100% sure that the url you are echoing is safe.
Hope it helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
execute program in various folders sequentially
I have two folders named one and two, placed in /home/. There is an (identical) executable prog.x in each folder, which takes 1 hour to finish after begin executed. I would like to first execute /home/one/prog.x and then /home/two/prog.x (so not at the same time).
I would like to make a script that does this for me. Is there a smart way to achieve this? Note that prog.x works by loading in a data file, which is located in the same folder.
A:
Since your program (unwisely?) has an implicit dependence on its executing directory, you may want to consider using subshells, and a ; to separate sequential commands
in a bash style shell you could do something like:
(cd /home/one ; ./prog x) ; (cd /home/two ; ./prog.x)
If you want to make a more general solution, you could use a for loop over a list:
for d in one two ; do cd /home/$d ; ./prog.x ; done
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS : Updating scope in ng-repeat
I have an Angular app with several nested controllers and views. I implemented infinite scrolling in it closely based on this tutorial for ngInfiniteScrolling: http://binarymuse.github.io/ngInfiniteScroll/demo_async.html
So I have a service that loads items into an array at $scope.content.items. Then there's an ng-repeat element that shows each result.
$scope.content = new Content()
$scope.content.loadMore( $scope.currentStream, 2 ) // this part is actually called in the HTML, but while debugging I've just done it in the controller
Now I want to implement search, and instead of making another search page, just have the items load in place of the current list of items. Basically to take the place of $scope.content.items.
So I built an identical controller, but now calling my search API. I use ng-change to see if someone has typed in the search box, then within the function that calls, do
$scope.search = function() {
$scope.content = new Search()
$scope.content.load( $scope.query )
}
I can see that this works in the console, that it replaces $scope.content.items, by doing this in the browser console:
var scope = angular.element($('[ng-controller=HomeController]')).scope()
scope.content.items
That shows me the array of objects I expect in each case (either before triggering ng-change="search()" or after). But the page itself does not update. It just shows the stuff from the Content() service.
Likewise, if I replace the above two lines from my controller with these below, it shows the content from the Search() service:
$scope.content = new Search()
$scope.content.load( 'thom' )
Long story short, I feel like the services and API work, but the page is not updating when I change the $scope.content.items array used by ng-repeat.
Here is the HTML
<div class="panel panel-item" ng-repeat="item in content.items" ng-hide="hideItem">
<h2 ng-hide=" item.stream == 'read' " data-ng-bind="item.title"></h2>
<a ng-click="openReaderModal( item )" class="cursor-pointer" ng-show=" item.stream == 'read' ">
<h2 data-ng-bind="item.title"></h2>
</a>
// ...
<div class="clearfix"></div>
</div>
A:
Fixed it, somehow. Here is my routes from app.config() before:
$stateProvider
// ...
.state( 'app', {
url: '/app',
templateUrl: 'app/views/app.html',
controller: 'HomeController'
})
.state( 'app.home', {
url: '/main',
templateUrl: 'app/views/home.html',
controller: 'HomeController'
})
.state( 'app.profile', {
url: '/profile',
templateUrl: 'app/views/profile.html',
controller: 'ProfileController'
})
.state( 'app.read', {
url: '/read',
templateUrl: 'app/views/stream-content.html',
controller: 'HomeController'
})
.state( 'app.watch', {
url: '/watch',
templateUrl: 'app/views/stream-content.html',
controller: 'HomeController'
})
.state( 'app.listen', {
url: '/listen',
templateUrl: 'app/views/stream-content.html',
controller: 'HomeController'
})
And here's after:
$stateProvider
// ...
.state( 'app', {
url: '/app',
templateUrl: 'app/views/app.html',
controller: 'HomeController'
})
.state( 'app.home', {
url: '/main',
templateUrl: 'app/views/home.html'
})
.state( 'app.profile', {
url: '/profile',
templateUrl: 'app/views/profile.html',
controller: 'ProfileController'
})
.state( 'app.read', {
url: '/read',
templateUrl: 'app/views/stream-content.html'
})
.state( 'app.watch', {
url: '/watch',
templateUrl: 'app/views/stream-content.html'
})
.state( 'app.listen', {
url: '/listen',
templateUrl: 'app/views/stream-content.html'
})
And it works. If anyone can provide an explanation, I'll credit them the answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I replace a ScrollViewer with a ContentPresenter on a ListBox?
According to a post at the very end of this thread you can replace the ScrollViewer of a ListBox with a ContentPresenter to disable scrolling in a nested scenario.
However, I don't know how to replace the ScrollViewer. Do I have to re-create the template?
A:
Yes, you'll need to assign your own template but you'll be using an ItemsPresenter, not ContentPresenter. The default template for ListBox includes a ScrollViewer wrapped around its ItemsPresenter. By making a copy of the template you can just remove the ScrollViewer and leave the rest of the template (and behavior) intact. This is the default template without the ScrollViewer (you can also remove the IsGrouping Trigger if you want):
<ControlTemplate TargetType="{x:Type ListBox}">
<Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="true">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
</Trigger>
<Trigger Property="IsGrouping" Value="true">
<Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL nested queries
I'm working on a project using a MySQL database and we'd like to combine a query which was previously made in several steps into one step.
The queries are created in a Java-App using Hibernate.
Goal
The goal of the query (or queries up to now) is the following: Loading a subset of data from several different tables (according to some filters and sorted).
Database Structure
The structure of the database can not be changed. I'll show here the needed tables with some example entries.
Table t1
id class counts ... other parameters
------- ----- ------
1 B5.2 124831
2 A7.9 83482
3 M5.5 53124812
Table t2
event_id reconstruction_algorithm ... other parameters
-------- ------------------------
1 0
1 0
1 0
1 1
1 1
1 1
1 2
1 2
1 2
1 3
2 0
2 0
2 0
2 0
2 1
2 1
2 1
2 2
2 2
2 2
2 3
2 3
... ...
Desired Result
I'm trying to find a query which can (in one step) do the following:
Get selected entries of table t1 (e.g. id and class) for some rows which meet some filter criteria (e.g. counts between 100000 and 150000)
Get the maximum amount of entries withe the same reconstruction_algorithm which belong to a single entry in t1 (e.g for the entry with id 1 this would be 3)
The problem
Up to now we used two requests. The first was used to get the entries of t1 which meet the filter criteria:
SELECT class, counts FROM t1 WHERE parameterX <= 123 AND parameterY >= 20;
The second was used to get the according amount of entries from t2:
SELECT MAX(tm.tNum) FROM (SELECT COUNT(*) as tNum from t2 t, t1 q WHERE q.id = t.event_id GROUP BY t.reconstruction_algorithm) tm;
Now I'd like to combine those two queries into one query. I tried doing this the following way:
SELECT q.id, q.class, MAX(tm.tmNum) AS nmbr
FROM t1 q, (SELECT COUNT(*) as tmNum from t2 t, t1 q WHERE
q.id = t.event_id GROUP BY t.reconstruction_algorithm) tm
WHERE q.parameterX >= 123 ORDER BY q.counts DESC;
The problem is now, that this query (tried in different ways) does return only a single row, although the outer query returns several rows. So I'd like the inner query to be run for every result of the outer query.
Is there a way to achieve this?
I hope somebody knows the answer to this problem.
A:
I think this query does what you are asking. The sub select gets the counts for each id. I then joined it back to t1. The outer query gets the max for each id. I didn't put the WHERE clause since I don't know the criteria but you can easily add it.
Here's a link to SQL Fiddle
select id,
class,
counts,
max(numOcc) as Occ
from t1
left join
(SELECT event_id, reconstruction_algorithm, count(1) as numOcc from t2
group by event_id, reconstruction_algorithm) a
on t1.id = a.event_id
group by t1.id, t1.class, t1.counts
| {
"pile_set_name": "StackExchange"
} |
Q:
Locus of closing escalator plate hinge
Folded plates $OA,AB,BX$ with given dimensions in inches hinging about $A,B,X$ are straightened out while closing the door in an escalator. $X$ moves on $x$ axis, fulcrum $O$ is fixed.
Find locus traced by $B$ (per approximate sketch).
dxiv's answer: $B$ moves on the parabola below $x$ - axis, $A$ moves on a circle inside the parabola above $x$-axis.
EDIT1:
If the joints are so flexible to allow rotation beyond $ \pi, B$ gets into opposite quadrant tracing a full ellipse!
A:
Hint: let $OA=r$ and $OX=4d\,$, then the coordinates of $B$ are $x=3d$ and $y=-\sqrt{r^2 - d^2}\,$. Eliminating $d$ between the two gives the equation in $x,y$ which describes the locus as ellipse
$$ (x/3)^2 + y^2 = r^2 $$
| {
"pile_set_name": "StackExchange"
} |
Q:
JFile Chooser throwing errors before use, only sometimes?
I create a JFile Chooser, and use .setCurrentDirectory(); to set the Directory to the root of my java project folder by passing a newFile("."); This seems to work fine sometimes, but other times it throws an error. This all happens while the program is loading, before any user input, so as far as I can tell it's completely random whether it happens or not. Here's the File Chooser related bits of my code:
public class PnlHighScores extends JPanel {
JFileChooser fcScores = new JFileChooser();
PnlHighScores() {
fcScores.addChoosableFileFilter(new TxtFilter());
//***********This seems to cause a strange error only somethimes, Right as the program is run!***********
fcScores.setCurrentDirectory(new File("."));//http://www.rgagnon.com/javadetails/java-0370.html
}
class ActFileChooser implements ActionListener {
public void actionPerformed(ActionEvent e) {//http://download.oracle.com/javase/tutorial/uiswing/examples/components/FileChooserDemoProject/src/components/FileChooserDemo.java
int returnVal = fcScores.showOpenDialog(PnlHighScores.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
filScores = fcScores.getSelectedFile();
sFileLocation = filScores.getAbsolutePath();//.getParent();//http://www.java-forums.org/awt-swing/29485-how-retrieve-path-filechooser.html
//System.out.println(filScores);
pnlScoreText.updateScoreFile(sFileLocation);
}
}
}
class TxtFilter extends javax.swing.filechooser.FileFilter {//http://www.exampledepot.com/egs/javax.swing.filechooser/Filter.html
public boolean accept(File file) {
String filename = file.getName();
if (file.isDirectory()) {
return true;
} else {
return filename.endsWith(".txt");
}
}
public String getDescription() {
return "*.txt";
}
}
}
The exact error is:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Invalid index
at javax.swing.DefaultRowSorter.convertRowIndexToModel(DefaultRowSorter.java:497)
at sun.swing.FilePane$SortableListModel.getElementAt(FilePane.java:528)
at javax.swing.plaf.basic.BasicListUI.updateLayoutState(BasicListUI.java:1343)
at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(BasicListUI.java:1294)
at javax.swing.plaf.basic.BasicListUI.getCellBounds(BasicListUI.java:935)
at javax.swing.JList.getCellBounds(JList.java:1600)
at javax.swing.JList.ensureIndexIsVisible(JList.java:1116)
at sun.swing.FilePane.ensureIndexIsVisible(FilePane.java:1540)
at sun.swing.FilePane.doDirectoryChanged(FilePane.java:1466)
at sun.swing.FilePane.propertyChange(FilePane.java:1513)
at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:339)
at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:276)
at java.awt.Component.firePropertyChange(Component.java:8128)
at javax.swing.JFileChooser.setCurrentDirectory(JFileChooser.java:568)
at Cannon.PnlSettings.<init>(PnlSettings.java:45)
at Cannon.FraWindow.<init>(FraWindow.java:19)
at Cannon.Main.main(Main.java:7)
Java Result: 1
The Main class simply creates FraWindow, and FraWindow Creates PnlSetting through its constructor method. They should be irrelavent, but here's main just in case:
package Cannon;
//Creates the frame
public class Main {
public static void main(String[] args) {
FraWindow fraMain = new FraWindow();
}
}
A:
This all happens while the program is loading,
All code that affects the GUI should execute on the Event Dispatch Thread. The creation of the GUI should be wrapped in a SwingUtilities.invokeLater().
Read the section from the Swing tutorial on Concurrency for more information. And look at any of the examples that demonstrate the proper way to create the GUI.
| {
"pile_set_name": "StackExchange"
} |
Q:
Loading Addressables and using ContinueWith()
Is there a reason why Task.ContinueWith() never gets called when loading addressables?
Addressables.LoadAssetAsync<Sprite>(spriteName).Task.ContinueWith(task =>
{
spriteRenderer.sprite = task.Result; // never called
});
I realize you can use the Completed event.
Addressables.LoadAssetAsync<Sprite>(spriteName).Completed += (op =>
{
spriteRenderer.sprite = op.Result; // called
});
I'm just curious why this is.
A:
Most of the Unity Engine API is not thread-safe.
ContinueWith is running on a different thread, so assigning a sprite to a SpriteRenderer from a different thread is invalid.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does GAE/JDO convert Entities to domain objects?
In the App Engine's JDO implementation, object types are saved as a 'Kind' with the Entity that is persisted to the datastore. When these Entities are fetched back out of the datastore, they are automatically returned (in some layer of JDO) as the original object type. What confuses me is that only the simple name of the class is saved; not the full path. So how is the JVM loading the correct class?
For example, if I have com.project.domain.User and I save an instance of this class to the datastore, only 'User' is defined for the Entity kind. When I use JDO to select this data back out, I get a com.project.domain.User back. How did GAE/JDO know to load com.project.domain.User and not com.project.other.domain.User?
A:
Your JDO provider (GAE isn't actually involved in this equation) keeps an internal mapping from entities to tables. Sometimes it forms this from various xml files, sometimes it forms this through annotations (depends on your coding style). In this map table names are actually mapped to fully qualified classes.
If you were storing both kinds of User objects then JDO would give you an exception because they'd be using the same table. You'd fix this by specifying a different table (via annotation or xml configuration). This specification would go into JDO's internal mapping. Then JDO would know how to resolve the entity correctly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Defining a Bootstrap button on a separate php file
Working with two php files, index.php and search.php. index sends some parameters to search, which performs a few queries into a database, and then returns the information on a table, stored into $output.
I now want to add a bootstrap button to the output, that calls a simple show/hide jQuery function.
The button is created, but it doesn't work when I test it on index.php
<div class="col-sm-8">
<table class="table table-hover" id="output">
</table>
<div id="edit" >
<div class="page-header" id="editar" style="display: none;">
<h2 id="producto">Placeholder<button id="exit" type="button" class="btn pull-right"><span class="glyphicon glyphicon-remove"></button><!--Clicking this button hides the edit div and shows the output table--></h2>
</div>
</div>
</div>
The exit/editbtn button calls the following:
<script>
$(document).ready(function(){
$("#exit").click(function(){
$(document.getElementById("edit")).hide();
$(document.getElementById("output")).show();
});
});
$(document).ready(function(){
$("#editbtn").click(function(){
$(document.getElementById("edit")).show();
$(document.getElementById("output")).hide();
});
});
</script>
And the definition of the "editbtn" is made on the separate php file:
if($query->num_rows){
$rows = $query->fetch_all(MYSQLI_ASSOC);
forEach($rows as $row){
$output .= '<tr><td><button id="editbtn" type="button" class="btn btn-default"><span class="glyphicon glyphicon-pencil"></span></button></td><!--Clicking this button hides the output table and shows the edit div--></tr>';
}
$output .= '</tbody>';
So in the end, I have the table with the button created, but it does nothing when I click on it.
A:
Why dont you try the same in order?
Like:
<script>
$(document).ready(function(){
$("#exit").click(function(){
$("#edit").hide();
$("#output").show();
});
$("#editbtn").click(function(){
$("#edit")).show();
$("#output")).hide();
});
});
</script>
This should work, always that you dont insert the edit button with ajax AND by definition, if you are using IDs, you are supposed to have only one element, if you have it between a foreach, it could cause you a problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
OpenCV depth Map from Stereo Images with nonparallel epilines
I found a tutorial about getting a depth map from stereo images which contains this piece of code:
import numpy as np
import cv2
from matplotlib import pyplot as plt
imgL = cv2.imread('tsukuba_l.png',0)
imgR = cv2.imread('tsukuba_r.png',0)
stereo = cv2.createStereoBM(numDisparities=16, blockSize=15)
disparity = stereo.compute(imgL,imgR)
plt.imshow(disparity,'gray')
plt.show()
Short question:
Do epipolar lines have to be parallel for this algorithm to work? I have two cameras which act as a stereo system but there is a small rotation and translation between them since I just put them on a table. So my epilines are by far not parallel.
A:
Yes, epipolar lines need to be parallel for createStereoBM to work.
For that you need to estimate the extrinsic calibration between your two cameras (Rotation and translation). It works basically the same as mono camera calibration. There are a few stereo calibration tutorials out there but I haven't found a good python one just now. Take a look at ROS camera calibration tool.
Next you need to rectify your camera images. This means you use the mapping you get from stereo calibration and warp your images so the epipolar lines are parallel. Take a look at the stereoRectify documentation by OpenCV: here.
When you have called initUndistortRectifyMap with the calibration parameters as suggested in the documentation I linked, your images are warped so that the epipolar lines are parallel, now you should be able to use createStereoBM to create a disparity map.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I alias python2 to python3 in a docker container?
I am trying to set the default python in my docker container to be python3 and have set the aliases in the dockerfile. When I open the .bashrc file, they show up. As far as I can tell, it should work but the default python version is still 2.7. if I run which python, it will still point to usr/bin/python rather than python3. Same with pip. Can anyone tell me what the problem is? Here is the command I'm using to alias:
RUN \
echo 'alias python="/usr/bin/python3"' >> /root/.bashrc && \
echo 'alias pip="/usr/bin/pip3"' >> /root/.bashrc
Does this look right? I am using ubuntu 17.10
A:
You try to create a symlink for python bin
RUN ln -s /usr/bin/python3 /usr/bin/python & \
ln -s /usr/bin/pip3 /usr/bin/pip
other option is use update-alternatives for more visit this site
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3
and another option is trying source the bashrc file after updating
RUN \
echo 'alias python="/usr/bin/python3"' >> /root/.bashrc && \
echo 'alias pip="/usr/bin/pip3"' >> /root/.bashrc && \
source /root/.bashrc
I recommend seeing all options of python images on Docker Hub
Tip: use anaconda or conda for managing your python versions (conda site)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to send binary stream from string content to third party api using axios nodejs
I have an API that takes a binary file stream. I am able to hit the API using postman.
Now on the server-side, the content of XML is in string object, So I have created stream first then posted it using axios lib (to call third party API) with form data. This is how I am doing
const Readable = require("stream").Readable;
const stream = new Readable();
stream.push(myXmlContent);
stream.push(null); // the end of the stream
const formData = new FormData();
formData.append("file", stream);
const response = await axios({
method: "post",
url: `${this.BASE_URL}/myurl`,
data: formData
});
return response.data;
but this is not sending data properly as third party API throws Bad Request: 400.
How can I send XML string content to API as a stream?
A:
Used Buffer.from method to send the stream. This worked for me
const response = await axios({
method: "post",
url: `${this.BASE_URL}/myUrl`,
data: Buffer.from(myXmlContent),
headers: { "Content-Type": `application/xml`, }
});
return response.data;
| {
"pile_set_name": "StackExchange"
} |
Q:
No funciona código de javascript utilizando socket.io
Solo él código referente a socket.io se ejecuta, el chat funciona perfecto, pero el código que tengo en bootstrapPage.js no funciona, ¿por qué?. (ANTES LOS FORMULARIOS AL HACER CLICK EN SIGN IN Y LOGIN SE EJECUTABAN, AHORA YA NO)
index.html
<html>
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<style>
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">MyApp <span class="glyphicon glyphicon-heart" style="color:red;"></span>
</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="#">Chat</a></li>
<ul class="nav navbar-nav navbar-right">
<li><a href="#" id="signUp"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
<li><a href="#" id="logIn"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</div>
</div>
</nav>
<div class="container" id="wrap">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="bootstrapPage.js"></script>
<div class="container" id="contenido">
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</div>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
bootstrapPage.js ( NO FUNCIONA EL CÓDIGO DENTRO DE bootstrapPage.js )
$(document).ready(function() {
$( "#signUp" ).on( "click", function(e) {
e.preventDefault();
$("#wrap").load("bootstrapSignUp.html");
});
$( "#logIn" ).on( "click", function(e) {
e.preventDefault();
$("#wrap").load("bootStrapLogIn.html");
});
window.onload = function() {
alert("Welcome to myApp"); // ESTE CÓDIGO TAMPOCO SE EJECUTA !!!!!!!
};
});
bootStrapLogIn.html
<div class="container">
<div id="loginbox" style="margin-top:50px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info" >
<div class="panel-heading">
<div class="panel-title">Sign In</div>
<div style="float:right; font-size: 80%; position: relative; top:-10px"><a href="#">Forgot password?</a></div>
</div>
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
<form id="loginform" class="form-horizontal" role="form">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="login-username" type="text" class="form-control" name="username" value="" placeholder="username or email">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="login-password" type="password" class="form-control" name="password" placeholder="password">
</div>
<div class="input-group">
<div class="checkbox">
<label>
<input id="login-remember" type="checkbox" name="remember" value="1"> Remember me
</label>
</div>
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<a id="btn-login" href="#" class="btn btn-success">Login </a>
<a id="btn-fblogin" href="#" class="btn btn-primary">Login with Facebook</a>
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div style="border-top: 1px solid#888; padding-top:15px; font-size:85%" >
Don't have an account!
<a href="#" onClick="$('#loginbox').hide(); $('#signupbox').show()">
Sign Up Here
</a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div id="signupbox" style="display:none; margin-top:50px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
bootstrapSignUp.html
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="r" method="post" accept-charset="utf-8" class="form" role="form"> <legend>Sign Up</legend>
<h4>It's free and always will be.</h4>
<div class="row">
<div class="col-xs-6 col-md-6">
<input type="text" name="firstname" value="" class="form-control input-lg" placeholder="First Name" /> </div>
<div class="col-xs-6 col-md-6">
<input type="text" name="lastname" value="" class="form-control input-lg" placeholder="Last Name" /> </div>
</div>
<input type="text" name="email" value="" class="form-control input-lg" placeholder="Your Email" /><input type="password" name="password" value="" class="form-control input-lg" placeholder="Password" /><input type="password" name="confirm_password" value="" class="form-control input-lg" placeholder="Confirm Password" /> <label>Birth Date</label> <div class="row">
<div class="col-xs-4 col-md-4">
<select name="month" class = "form-control input-lg">
<option value="01">Jan</option>
<option value="02">Feb</option>
<option value="03">Mar</option>
<option value="04">Apr</option>
<option value="05">May</option>
<option value="06">Jun</option>
<option value="07">Jul</option>
<option value="08">Aug</option>
<option value="09">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select> </div>
<div class="col-xs-4 col-md-4">
<select name="day" class = "form-control input-lg">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select> </div>
<div class="col-xs-4 col-md-4">
<select name="year" class = "form-control input-lg">
<option value="1935">1935</option>
<option value="1936">1936</option>
<option value="1937">1937</option>
<option value="1938">1938</option>
<option value="1939">1939</option>
<option value="1940">1940</option>
<option value="1941">1941</option>
<option value="1942">1942</option>
<option value="1943">1943</option>
<option value="1944">1944</option>
<option value="1945">1945</option>
<option value="1946">1946</option>
<option value="1947">1947</option>
<option value="1948">1948</option>
<option value="1949">1949</option>
<option value="1950">1950</option>
<option value="1951">1951</option>
<option value="1952">1952</option>
<option value="1953">1953</option>
<option value="1954">1954</option>
<option value="1955">1955</option>
<option value="1956">1956</option>
<option value="1957">1957</option>
<option value="1958">1958</option>
<option value="1959">1959</option>
<option value="1960">1960</option>
<option value="1961">1961</option>
<option value="1962">1962</option>
<option value="1963">1963</option>
<option value="1964">1964</option>
<option value="1965">1965</option>
<option value="1966">1966</option>
<option value="1967">1967</option>
<option value="1968">1968</option>
<option value="1969">1969</option>
<option value="1970">1970</option>
<option value="1971">1971</option>
<option value="1972">1972</option>
<option value="1973">1973</option>
<option value="1974">1974</option>
<option value="1975">1975</option>
<option value="1976">1976</option>
<option value="1977">1977</option>
<option value="1978">1978</option>
<option value="1979">1979</option>
<option value="1980">1980</option>
<option value="1981">1981</option>
<option value="1982">1982</option>
<option value="1983">1983</option>
<option value="1984">1984</option>
<option value="1985">1985</option>
<option value="1986">1986</option>
<option value="1987">1987</option>
<option value="1988">1988</option>
<option value="1989">1989</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
<option value="1994">1994</option>
<option value="1995">1995</option>
<option value="1996">1996</option>
<option value="1997">1997</option>
<option value="1998">1998</option>
<option value="1999">1999</option>
<option value="2000">2000</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
</select> </div>
</div>
<label>Gender : </label> <label class="radio-inline">
<input type="radio" name="gender" value="M" id=male /> Male
</label>
<label class="radio-inline">
<input type="radio" name="gender" value="F" id=female /> Female
</label>
<br />
<span class="help-block">By clicking Create my account, you agree to our Terms and that you have read our Data Use Policy, including our Cookie Use.</span>
<button class="btn btn-lg btn-primary btn-block signup-btn" type="submit">
Create my account</button>
</form>
</div>
</div>
</div>
A:
Tu problema se debe a que NO estás sirviendo contenido estático. Para hacerlo con Express se agregan la siguiente línea:
app.use(express.static('./assets'));
Suponiendo que el directorio assets tiene dentro js y css, en tus vistas debes referenciarlas como relativas:
<script src="/js/bootstrapPage.js"></script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Decision trees / stumps with Adaboost
I just started learning about decision trees with Adaboost and am trying it out on OpenCV and have some questions.
Boosted Decision Trees
I understand that when I use Adaboost with Decision Trees, I continuously fit Decision Trees to reweighted version of the training data. Classification is done by a weighted majority vote
Can I instead use Bootstrapping when training Decision Trees with Adaboost ? i.e. we select subsets of our dataset and train a tree on each subset before feeding the classifiers into Adaboost.
Boosted Decision Stumps
Do I use the same technique for Decision Stumps ? Or can I instead create stumps equal to the number of features ? I.e. if I have 2 classes with 10 features, I create a total of of 10 Decision Stumps for each feature before feeding the classifiers into Adaboost.
A:
AdaBoost not only trains the classifier on different subsets, but also adjusts the weights of the dataset elements depending on the assemble performance reached. The detailed description may be found here.
Yes, you can use the same technique to train decision stumps. The algorithm is approximately the following:
Train the decision stump on the initial dataset with no weights (the same as each element having weight = 1).
Update weights of all elements, using the formula from AdaBoost algorithm. Weights of correctly classified elements should become less, weights of incorrectly classified - larger.
Train the decision stump using the current weights. That is, minimize not just the number of mistakes made by this decision stump, but sum of the weights of the mistakes.
If the desired quality was not achieved, go to pt. 2.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove small interstices on the edges of a polygone
How can I remove the white interstices on the edges (and interior) of a polygone or polyline, as represented in the first figure below? I want to get smooth and continuous edges, capturing the global external shape, as represented by the red line in the second figure below. Also, I want to keep the big white interiors.
I've tried the following methods, none of them being sucessful:
convex hull (vector, geoprocessing tools)
v.generalize.simplify (GRASS)
Simplipy plugin
I used different generalisation algorithms, such as Douglas-Peuker, which I think is not suitable for this problem.
I work with QGIS 2.18.4 runing on Windows 10.
A:
Buffer - Debuffer would fill the interstices, but it will partially fill the holes, too. To protect these holes, extract the holes first, then put them back after buffer-debuffer step.
Original feature
Create Convex hull which outlines the original feature
Symmetrical difference to extract interior parts
Break-up the interior parts into single parts. Then select holes and save them as a new layer.
Buffer (positive distance)
Debuffer (negative distance)
Difference between (6) De-buffered polygon and (4) holes polygon
| {
"pile_set_name": "StackExchange"
} |
Q:
What to do first: Feature Selection or Model Parameters Setting?
This is more of a "theoretical" question. I'm working with the scikit-learn package to perform some NLP task. Sklearn provides many methods to perform both feature selection and setting of a model parameters. I'm wondering what I should do first.
If I use univariate feature selection, it's pretty obvious that I should do feature selection first and, with the selected features, I then tunne the parameters of the estimator.
But what if I want to use recursive feature elimination? Should I first set the parameters with grid search using ALL the original features and just then perform feature selection? Or perhaps I should select the features first (with the estimator's default parameters) and then set the parameters with the selected features?
Thanks in advance for any help you could give me.
EDIT
I'm having pretty much the same problem stated here. By that time, there wasn't a solution to it. Does anyone know if it exists one now?
A:
Personally I think RFE is overkill and too expensive in most cases. If you want to do feature selection on linear models, use univariate feature selection, for instance with chi2 tests or L1 or L1 + L2 regularized models with grid searched regularization parameter (usually named C or alpha in sklearn models).
For highly non-linear problems with a lot of samples you should try RandomForestClassifier, ExtraTreesClassifier or GBRT models and grid searched parameters selection (possibly using OOB score estimates) and use the compute_importances switch to find a ranking of features by importance and use that for feature selection.
For highly non-linear problems with few samples I don't think there is a solution. You must be doing neurosciences :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does std::forward discard constexpr-ness?
Being not declared constexpr, std::forward will discard constexpr-ness for any function it forwards arguments to. Why is std::forward not declared constexpr itself so it can preserve constexpr-ness?
Example: (tested with g++ snapshot-2011-02-19)
#include <utility>
template <typename T> constexpr int f(T x) { return -13;}
template <typename T> constexpr int g(T&& x) { return f(std::forward<T>(x));}
int main() {
constexpr int j = f(3.5f);
// next line does not compile:
// error: ‘constexpr int g(T&&) [with T = float]’ is not a constexpr function
constexpr int j2 = g(3.5f);
}
Note: technically, it would be easy to make std::forward constexpr, e.g., like so (note that in g std::forward has been replaced by fix::forward):
#include <utility>
namespace fix {
/// constexpr variant of forward, adapted from <utility>:
template<typename Tp>
inline constexpr Tp&&
forward(typename std::remove_reference<Tp>::type& t)
{ return static_cast<Tp&&>(t); }
template<typename Tp>
inline constexpr Tp&&
forward(typename std::remove_reference<Tp>::type&& t)
{
static_assert(!std::is_lvalue_reference<Tp>::value, "template argument"
" substituting Tp is an lvalue reference type");
return static_cast<Tp&&>(t);
}
} // namespace fix
template <typename T> constexpr int f(T x) { return -13;}
template <typename T> constexpr int g(T&& x) { return f(fix::forward<T>(x));}
int main() {
constexpr int j = f(3.5f);
// now compiles fine:
constexpr int j2 = g(3.5f);
}
My question is: why is std::forward not defined like fix::forward ?
Note2: this question is somewhat related to my other question about constexpr std::tuple as std::forward not being constexpr is the technical reason why std::tuple cannot be created by calling its cstr with rvalues, but this question here obviously is (much) more general.
A:
The general answer is that the C++ committee's Library Working Group have not done an exhaustive trawl through the working draft looking for opportunities to use the new core facilities. These features have been used where people have had the time and inclination to look at possible uses, but there is not the time for exhaustive checking.
There are some papers regarding additional uses of constexpr in the works, such as those in the November 2010 mailing.
| {
"pile_set_name": "StackExchange"
} |
Q:
JSF / PrimeFaces compatibility with HTML5 Storage methods
Do JSF / PrimeFaces support well HTML5 Storage methods (sessionStorage / localStorage)?
A:
Not out the box. But you can just wrap the necessary HTML/JS code in custom JSF components. One of our previous interns have done that. You can find it in this Google Code repository. Check the POC-SessionStorage part for the source code. You can find a writeup in this thesis.
To the point, it's merely a matter of generating the right HTML/JS code and hooking on JSF ajax events.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android & OrmLite: OnUpgrade fails
I have a small problem with OrmLite on Android.
When I increment the database version, the onUpgrade method is called as expected in my OrmLite Helper. After the upgrade, the onCreate method is called and I get this exception:
11-24 10:09:45.720: ERROR/AndroidConnectionSource(390): connection saved
com.j256.ormlite.android.AndroidDatabaseConnection@44f0f478 is not the one
being cleared com.j256.ormlite.android.AndroidDatabaseConnection@44f5d310
I have no clue why the cleared connection is not the same as the saved one.
I've put also my database functions (insert...) into the OrmLite Helper class. Maybe this could be a problem?!?
A snippet from my helper class:
public class OrmLiteDBProvider extends OrmLiteSqliteOpenHelper
implements IEntityProvider, IDBProvider {
//snip
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(OrmLiteDBProvider.class.getName(), "Creating database and tables");
TableUtils.createTable(connectionSource, OrgManaged.class);
} catch (SQLException e) {
Log.e(OrmLiteDBProvider.class.getName(),
"Can't create database and tables", e);
throw new RuntimeException(e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
Log.i(OrmLiteDBProvider.class.getName(),
"Database version changed. Dropping database.");
TableUtils.dropTable(connectionSource, OrgManaged.class, true);
// after we drop the old databases, we create the new ones
onCreate(db);
} catch (SQLException e) {
Log.e(OrmLiteDBProvider.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}
I think it's something simple I'm missing.
Thanks in advance for your effort.
A:
Ok, I see the problem and it exists, unfortunately, in the sample program as well. In the ORMLite helper class, the onUpgrade method should use:
onCreate(db, connectionSource);
instead of the following which is calling the subclass:
onCreate(db);
I've reproduced this problem in the HelloAndroid example program which has been fixed. I've also fixed this properly in the OrmLiteSqliteOpenHelper base class in the Android side of the ORMLite code. Sorry for the problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
ggplot showing percent not count when stacking
I am trying make a stacked barplot of following data:
df_APP -> Date CBPP3 ABSPP PSPP CSPP
2018-06-01 254551 27413 1991168 157034
2018-05-25 253297 27241 1987753 155648
2018-05-18 253759 27428 1984125 154796
2018-05-11 253270 27149 1980743 153637
2018-05-04 252583 27135 1972850 152593
I use following code to melt the data and delete rows with NAs:
APP <- as.data.frame(df_APP)
new_APP <- melt(APP, id = "Date")
new_APP <- new_APP[-which(is.na(new_APP$value)),]
I plot the melted dataset using:
ggplot(new_APP, aes(x=Date, y=value, fill = variable)) +
geom_bar(position = "fill", stat = "identity")
My graph does not show count but percent instead as you can see below, and I cannot figure out why.
A:
Position fill will fill up the full chart across every point to show the ratio. Hence the "fill" that exists. That is a stacked bar chart that you have posted
ggplot(new_APP, aes(x=Date, y=value, fill = variable)) + geom_col()
can work, also
ggplot(new_APP, aes(x=Date, y=value, fill = variable)) +
geom_bar(position = "stack", stat = "identity")
can work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adobe Script to show active Word Count
I have a script that allows me to view the Character Count limit, and then it counts down. I would prefer to display a Word Count instead because the majority of people don't count characters. I've attached a link to the pdf I've created for that.
http://webfro.gs/south/Adobe/Character%20Countdown.pdf
In Properties > Actions > On Focus > Run a Javascript - I have the following script running...
var maxlim=event.target.charLimit;
if (event.target.value.length==0)
this.getField("cntdwn").value=maxlim;
Then, in Properties > Format > Custom Keystroke Script - I am running this Countdown script
var value = custmMergeChange(event);
var L = value.length;
this.getField("cntdwn").value=(maxlim-L);
Is there something out there that can display a Word Count and when the word count is reached (counting up) or it reaches zero (counting down), can the ability to type any further be stopped?
How's this possible?
A:
In answer to the comment:
Not a preset variable per se, but there is an answer here, that should help.
Try this, then. It's directely from the Adobe forums, and answers your question more directly.
for (var i = 0; i < input.length; i++) {
var ch = input.charAt(i);
var str = new String("" + ch);
if (i+1 != input.length && str === " " && "" + input.charAt(i+1) !== " "){
wordCount++;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert hexadecimal value to ip address of type string in C.
i have a hex value say for example 0x0a010203 and i want to convert it to a string such that after conversion it should be like "10.1.2.3",How to extract the individual fields from the hex value ?
A:
You can use bit masking and bit shifts, eg:
unsigned int val = 0x0a010203;
printf("%d.%d.%d.%d",
(val & 0xFF000000) >> 24,
(val & 0x00FF0000) >> 16,
(val & 0x0000FF00) >> 8,
val & 0x000000FF);
A:
Fill a struct in_addr and use inet_ntoa() ("Internet address to ASCII string"):
#include <arpa/inet.h>
struct in_addr addr;
addr.s_addr = htonl(0x0a010203); // s_addr must be in network byte order
char *s = inet_ntoa(addr); // --> "10.1.2.3"
Note that the string returned by inet_ntoa() may point to static data that may be overwritten by subsequent calls. That is no problem if it is just printed and then not
used anymore. Otherwise it would be necessary to duplicate the string.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is a list or tuple a function? (trying to use tuple as a key in a sorted() function.)
I a beginner learning python and doing some python exercises and I have a generic question about why one piece of code works and another does not.
This code I wrote below works just fine:
def sort_last(tuples):
def MyFn(tuples):
return tuples[-1]
a = sorted(tuples, key=MyFn)
return a
Intuitively I thought this might work and tried it. It does not:
def sort_last(tuples):
a = sorted(tuples, key=tuples[-1])
return a
Will someone explain why the second piece does not work?
I have looked it up: #sorted
Is it because a list or tuple is not a function? Is it because it is more than one argument?
Thanks in advance!
A:
From the Docs:
key specifies a function of one argument that is used to extract a
comparison key from each list element
So, you could pass a callable object with one argument. You could rewrite second example with lambda:
def sort_last(tuples):
return sorted(tuples, key=lambda t: t[-1])
Or, as suggested by @ersran9, you could use operator.itemgetter:
import operator
def sort_last(tuples):
return sorted(tuples, key=operator.itemgetter(-1))
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I register a generic decorator using Castle Windsor?
I need decorate all based onICommandHandler<T> types using a corresponding DeadlockRetryCommandHandlerDecorator<T> type
I tried this solution, but unfortunately it doesn't work.
container.Register(
Component.For(typeof(ICommandHandler<>))
.ImplementedBy(typeof(DeadlockRetryCommandHandlerDecorator<>)));
container.Register(
AllTypes.FromThisAssembly()
.BasedOn(typeof(ICommandHandler<>))
.WithService.Base());
How can i register a generic decorator (DeadlockRetryCommandHandlerDecorator<T>) to wrap all generic ICommandHandler<T> implementations?
A:
currently this is not supported OOTB due to the fact that Windsor always favours mode specific component over an open-generic.
You can get that working quite easily with an ISubDependencyResolver though. The code below assumes you name the component for your decorator "DeadlockRetryCommandHandlerDecorator"
public class CommandHandlerResolver : ISubDependencyResolver
{
private readonly IKernel kernel;
public FooResolver(IKernel kernel)
{
this.kernel = kernel;
}
public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
return (dependency.TargetType.IsGenericType &&
dependency.TargetType.GetGenericTypeDefinition() == typeof (ICommandHandler<>)) &&
(model.Implementation.IsGenericType == false ||
model.Implementation.GetGenericTypeDefinition() != typeof (DeadlockRetryCommandHandlerDecorator<>));
}
public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
return kernel.Resolve("DeadlockRetryCommandHandlerDecorator", dependency.TargetItemType);
}
}
The recommended way of achieving scenarios like that with Windsor however is by using interceptors.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery call to oodle API returns nothing?
My question is specific to oodle API.
I am trying to call oodle API to get the JSON result like this:
$.getJSON("http://api.oodle.com/api/v2/listings?key=TEST®ion=sf&category=sale&format=json&mappable=address&jsoncallback=none", function (data) {
alert(data);
}
A:
You cannot make cross domain request (XSS). You will need to use JSONP by changing the jsoncallback parameter from your request to jsoncallback=? instead of none. The latest version of jquery will then handle JSONP correctly.
The Oodle API specs mentions jsoncallback: http://developer.oodle.com/listings
| {
"pile_set_name": "StackExchange"
} |
Q:
Head over to=go to?
Let's say there is a field reporter, where he/she is asking you to follow him/her to a place.
"We are now walking around in this shopping mall looking for the department store section, oh there it is! Let's head over to that place."
And
"We are now walking around in this shopping mall looking for the department store section, oh there it is! Let's go to that place."
Is head over to correctly used here? And which of the two is better? Because I think ''go to'' is too common as for its usage.
A:
This usage of head is an informal extrapolation of the meaning "to set the course of" as in "head a ship northward" (see Webster). In formal usage, you can head in a direction or head toward a destination, but "head" refers just to setting a course (direction of movement).
In common usage, though, head to or head over to have come to mean "go to" (referring to the destination, itself, rather than the direction of the destination). Either will work in your sentence, and both can be intended to mean the same thing, but in some case, they can have slightly different nuances.
Head to can sometimes have a meaning closer to the formal definition. "Let's head to the mall" can sometimes mean "let's start going in the direction of the mall (potentially subject to change if we see something more interesting on the way or think of a better destination before we get there).
"Let's head over to the mall" typically means that the mall is the intended destination and let's go there. "Over" contributes the sense of going directly there, as in "jumping over" other potential destinations along the way.
There can also be a different nuance in comparison to go to. "Let's go to that place" is very goal directed. You've specified a destination and an action to get there. It implies that getting there is the immediate objective. Head to or head over to doesn't imply any sense of urgency (in fact, they are often used as "softer" instructions to imply a lack of urgency), analogous to, "Start going in that direction and keep going until you get there, but feel free to focus on other things in the process."
| {
"pile_set_name": "StackExchange"
} |
Q:
textContent.replace not working within my function
I dont know why this is the case but my replace does not work. It is somehow unusual considering my syntax is correct.
info.textContent.replace('Title', "replaced");
where info is the variable that stores an element. It should actually replace all instances of Title with "replaced". I prefer not using innerText due to compatibility issues and innerHTML due to security risks. textContent is supported by firefox and I have no idea what is going on.
I would appreciate some insight. I am learning javascript and tips for best practice are welcome.
Below the full code in Jsfiddle:
http://jsfiddle.net/r7bL6vLy/123/
A:
It works, it's just replace method returns new string you need to assign back:
info.textContent = info.textContent.replace('Title', "replaced");
| {
"pile_set_name": "StackExchange"
} |
Q:
Does it improve performance to store a value instead of accessing it in an array
For example is there a performance difference between these two snippets:
var my_array = [''];
for (var i = 0; i < 2000; i++) {
my_array[0] += i;
}
and
var my_array = [''];
var my_string = array[0];
for (var i = 0; i < 2000; i++) {
my_string += i;
}
Thanks !
A:
See for yourself (lower is better).
var suite = [
function test0() {
var t0, t1;
t0 = performance.now();
var my_array = [''];
for (var i = 0; i < 2000; i++) {
my_array[0] += i;
}
t1 = performance.now();
return t1 - t0;
},
function test1() {
var t0, t1;
t0 = performance.now();
var my_array = [''];
var string = my_array[0];
for (var i = 0; i < 2000; i++) {
string += i;
}
my_array[0] = string;
t1 = performance.now();
return t1 - t0;
}];
var tests = [0, 0];
var amount = [1000, 1000];
function run(test) {
if (amount[test]-- > 0 && test < 2) {
tests[test] += suite[test]();
setTimeout(function(){run(test)}, 0);
} else if (test < 1) {
document.write('<pre>Running test 1 in 1 second</pre>');
setTimeout(function(){
document.write('<pre>Running test 1</pre>');
run(test+1)
}, 1000);
} else {
document.write('<pre>1000 runs complete</pre>');
document.write('<pre>Test 0 total: ' + tests[0] + 'ms</pre>');
document.write('<pre>Test 1 total: ' + tests[1] + 'ms</pre>');
}
}
setTimeout(function(){
document.write('<pre>Running test 0</pre>');
run(0);
}, 1000);
| {
"pile_set_name": "StackExchange"
} |
Q:
On the existence of some kind of "universal fibre bundle"
While attending an introductory course on the theory of (smooth) fibre bundles, an example I was given of (principal) bundles was that of topological coverings of a space with structure group the galois group of the covering. In this case, when the base space is nice enough, we get an universal covering space in the sense that any other covering space is covered by this universal cover.
This motivated me to ask the following question: can this be generalized? I mean, given a base space, can I construct some kind of "universal fibre bundle" which is universal in the sense that it is a fibre bundle over the base space with morphisms to every other fibre bundle over the base?
Initially, I considered the set(?) of all fibre bundles $E$ over $B$ and tried to give it an order (I wanted to apply Zorn's lemma) $E'\geq E$ iff $E'\overset{\pi}{\rightarrow}E$ is a fibre bundle and $\pi$ is a morphism of fibre bundles over $B$ but I didn't manage to prove that $E'\geq E$ and $E\geq E'$ implies $E\cong E'$.
Then I tried to consider, given $E$ and $E'$ over $B$, $E\times_B E'$ over $B$ but this is not necessarily a fibre bundle over $E$ and $E'$ (am I wrong?), so I got stuck again.
Any suggestion on how (and if) this can be done? Thanks in advance.
A:
You can get close. I claim that there is a fibration over $B$ (somewhat weaker than a fiber bundle, but a very useful notion in homotopy theory) which maps to any other fibration over $B$ up to homotopy.
To make the statement cleaner let $B$ be a path-connected space and fix a basepoint $b$ of it. There is an extremely interesting distinguished fibration over $B$ called the path space fibration
$$\Omega B \to PB \to B$$
(here when I write $F \to E \to B$ I mean that $E$ is a fiber bundle over $B$ with fiber $F$). Here $PB$ is the space of paths $p : [0, 1] \to B$ such that $p(0) = b$, and the bundle map $\pi : PB \to B$ is the evaluation map $p \mapsto p(1)$. The fiber of the bundle map $\pi$ over $b$ is the based loop space of paths $p : [0, 1] \to B$ such that $p(0) = p(1) = b$.
If $B$ is the classifying space $BG \cong K(G, 1)$ of a discrete group $G$, then the path space fibration is more or less the universal cover of $B$. In general you can think of the process of taking the universal cover as killing $\pi_1$ but retaining all the higher homotopy groups; similarly there are higher analogues of the universal cover which kill the first $n$ homotopy groups but retain all of the higher homotopy groups. They organize themselves into a tower called the Whitehead tower, and at the very top of the Whitehead tower is the path space fibration, which has the effect of killing all of the homotopy groups of $B$. It is the "most universal cover" of $B$ in that sense.
In particular, $PB$ is contractible. That makes it very easy to construct maps from the path space fibration to any other fibration $F \to E \to B$, up to homotopy; if $\pi : E \to B$ is the bundle map, pick any point in the preimage $\pi^{-1}(b)$ and map $PB \cong \text{pt}$ into it. More explicitly, given a path $p : [0, 1] \to B$ in $PB$, lift it up to a path $\tilde{p}$ in $E$ starting at the point you picked in $\pi^{-1}(b)$ and send $p$ to $\tilde{p}(1)$. Since paths don't lift uniquely for fibrations this isn't well-defined, but it turns out to be well-defined up to homotopy. ($E$ might be empty, but that's fine too.)
| {
"pile_set_name": "StackExchange"
} |
Q:
The data is not inserted successfully into object
The data is not inserted successfully.
Output:
dataHolder.variableNames = []
when it should be :
dataHolder.variableNames = [{'area_12345[<>]6789'}, {'apollo123'}, {'guruX'}, {'ok'}];
% USAGE:
elementNames = {'area_12345[<>]6789', 'apollo123', 'guruX', 'ok'};
elementTypes = {'string', 'specialChar', 'int', 'float'};
elementValues = {'charlie', 'vvv', '09', '123.321'};
dataHolder = dynamicVariableNaming;
str = 'test';
result = dataHolder.ensureCellType(str);
for i = 1:3
dataHolder.addVariables(elementNames(i), elementTypes(i), elementValues(i));
end
dataHolder.variableNames
%%% CLASS
classdef dynamicVariableNaming
%HELLO Summary of this class goes here
% -
properties
variableNames = [];
variableValues = [];
variableTypes = [];
end
methods (Access = public) % (Access = private)
function obj = dynamicVariableNaming (variableName, variableValue, variableType)
% class constructor
if(nargin > 0)
obj.variableNames = variableName;
obj.variableValues = variableValue;
obj.variableTypes = variableType;
end
end
% end
%
% methods (Static = true)
function addVariables (obj, variableName, variableValue, variableType)
obj.variableNames = [obj.variableNames ensureCellType(obj, variableName)];
obj.variableValues = [obj.variableValues ensureCellType(obj, variableValue)];
obj.variableTypes = [obj.variableTypes ensureCellType(obj, variableType)];
end
function cellData = ensureCellType(obj, value)
if (~strcmp(class(value), 'cell'))
cellData = {value};
% cell2string(value);
else
cellData = value;
end
end
end
end
A:
You are not returning the changed opbject from the addVariables method as required when you are working with non-handle objects. Remember, matlab is different in comparison with other reference passing-based languages.
To fix it either make your class enherit from the handle class, or return obj from addVariables
Cant say if there are other problems in the code due to its poor formatting and inability to run in matlab (unbalanced ends, missing constructors, etc.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular md-virtual-repeat directive is messing up items order
I'm using Angular Material md-virtual-repeat directive to improve performance with thousands items within a md-list.
However, when I scroll down and then up, the ordering is not preserved at all. At the beginning, my items are sorted by date and it's fine. When I start scrolling, ordering gets completely messed up.
Here's my markup:
<md-virtual-repeat-container class="flex flex-layout md-list indigo" ng-if="tracking.loaded">
<div md-virtual-repeat="marker in tracking.mapMarkers | orderBy: 'timestamp':true" class="md-list-item inset" style="height: 72.6px;">
<div class="md-list-item-content">
<h3 class="text-md">{{ ::marker.timestamp | time }}</h3>
</div>
</div>
</md-virtual-repeat-container>
And my controller:
self.mapMarkers = [];
...
// In a function which is called within a promise
_.each(_.without(_.reject(data.Positions, function(position){ return position.Id === currentPosition.Id; })), function (pos) {
var location = new google.maps.LatLng(pos.Latitude, pos.Longitude);
self.mapMarkers.push(new google.maps.Marker({
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle_blue.png",
size: new google.maps.Size(12, 12),
anchor: new google.maps.Point(4, 4)
},
position: location,
address: pos.Address,
timestamp: pos.Timestamp,
map: self.map
}));
});
A:
I solved my problem. It appears md-virtual-repeat fails recycling items correctly if one-way binding is used (notice my :: syntax in my markup). Seems obvious after all.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to stop reloading the page when the user press F5 or CTRL+R in XBAP Application
I have an XBAP Application.
In XBAP Page, if the user presses F5 or CTRL+R then the confirmation message must be shown to the user.
If Yes then the page must be reloded.
If No then the current page must remain as it is.
Can any one help how to do this.
A:
You could call on NavigationMode of Navigating event parameter, like code below shows,
Application.Current.Navigating += new NavigatingCancelEventHandler(Current_Navigating);
void Current_Navigating(object sender, NavigatingCancelEventArgs e)
{
if (e.NavigationMode == NavigationMode.Refresh)
{
//put your logic here
}
}
If user trigger refresh operation either by F5 or Ctrl+R combination keys, you could catch this event and handle it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not allowed to start service Intent
I'm trying to call a service from a activity:
When I'm running the program the activity throws an error which says: Not allowed to start service Intent. What am I doing wrong? I'm sorry for possible stupid mistakes in the code, but I'm a newbie.
activity code:
public void startService() {
try {
startService (new Intent ( this , SmsReminderService.class)) ; }
catch (Exception e ) { Log.v("Error" , e.getMessage()) }
}
service code :
public class SmsReminderService extends Service {
@Override
public void onStart(Intent intent, int startid) {
Log.v("SSms", "Service started") ; }}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.sms.smsReminder"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<permission android:name="SEND_SMS"></permission>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".SmsReminderActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".SmsReminderService"
android:permission="android.permission.BIND_REMOTEVIEWS">
<intent-filter>
<action android:name = "android.intent.category.LAUNCHER" ></action>
</intent-filter>
</service>
</application>
</manifest>
Thanks in advance, Tom
A:
Why this in the service?
<intent-filter>
<action android:name = "android.intent.category.LAUNCHER" ></action>
</intent-filter>
Try to add this:
<uses-permission android:name="android.permission.BIND_REMOTEVIEWS" />
| {
"pile_set_name": "StackExchange"
} |
Q:
IPhone Custom UIButton Cannot DismissModalViewController
I have a custom UIButton class in my IPhone navigation application. When the user clicks the button I present a modal view which displays a tableview list of records that the user can select from.
On click of the button I create my viewController and show it using the following code:
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
dropDownPickerViewController = [[DropDownListingViewController alloc] initWithNibName:@"DropDownListingView" bundle:[NSBundle mainBundle]];
.....
.....
[[(AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate] navigationController] presentModalViewController:dropDownPickerViewController animated:NO];
[dropDownPickerViewController release];
[super touchesEnded:touches withEvent:event];
}
As you can see the button could be on any viewController so I grab the navigationController from the app delegate. Than in my DropDownPickerViewController code i have the following when a user selects a record:
[[(AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate] navigationController] dismissModalViewControllerAnimated:NO];
But nothing occurs. It seems to freeze and hang and not allow any interaction with the form. Any ideas on why my ModalViewController wouldnt be dismissing? Im thinking it is the way I use the app delegate to present the viewController. Is there a way to go self.ParentViewController in a UIButton class so I can get the ViewController of the view that the button is in (if this is the problem)?
Any ideas would be greatly appreciated.
Thanks
A:
I did recall that I did have to do something similar once, and by looking at this post:
Get to UIViewController from UIView?
I was able to create some categories:
//
// UIKitCategories.h
//
#import <Foundation/Foundation.h>
@interface UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController;
- (id) traverseResponderChainForUIViewController;
@end
@interface UIView (FindUINavigationController)
- (UINavigationController *) firstAvailableUINavigationController;
- (id) traverseResponderChainForUINavigationController;
@end
//
// UIKitCategories.m
//
#import "UIKitCategories.h"
@implementation UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController {
// convenience function for casting and to "mask" the recursive function
return (UIViewController *)[self traverseResponderChainForUIViewController];
}
- (id) traverseResponderChainForUIViewController {
id nextResponder = [self nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return nextResponder;
} else if ([nextResponder isKindOfClass:[UIView class]]) {
return [nextResponder traverseResponderChainForUIViewController];
} else {
return nil;
}
}
@end
@implementation UIView (FindUINavigationController)
- (UINavigationController *) firstAvailableUINavigationController {
// convenience function for casting and to "mask" the recursive function
return (UINavigationController *)[self traverseResponderChainForUINavigationController];
}
- (id) traverseResponderChainForUINavigationController {
id nextResponder = [self nextResponder];
if ([nextResponder isKindOfClass:[UINavigationController class]]) {
return nextResponder;
} else {
if ([nextResponder isKindOfClass:[UIViewController class]]) {
//NSLog(@" this is a UIViewController ");
return [nextResponder traverseResponderChainForUINavigationController];
} else {
if ([nextResponder isKindOfClass:[UIView class]]) {
return [nextResponder traverseResponderChainForUINavigationController];
} else {
return nil;
}
}
}
}
@end
you can then call them like so:
UINavigationController *myNavController = [self firstAvailableUINavigationController];
UIViewController *myViewController = [self firstAvailableUIViewController];
maybe they will help you, I hope so.
| {
"pile_set_name": "StackExchange"
} |
Q:
3DES/DES encryption using the JCE - generating an acceptable key
I'm working on a project that requires 3DES encryption in Java. The issue is that I've been (and will continue to be) supplied with a 128-bit hex key like "0123456789ABCDEF0123456789ABCDEF". Conversion to bytes is no issue. What is the issue, however, is that the Java Cryptographic Extensions API will choke on this key, saying it is invalid. I gather that the MSB of each byte is merely a parity bit, so the JCE expects me to remove those (or so I think). In .NET, however, I can specify the key as supplied, and it quietly handles the encryption/decryption with no complaints.
Is there any way I can generate the kind of key the JCE expects from the kind of key I'm supplied?
I've found that the JCE allows you specify an 8-byte key for DES encryption, so I tried implementing 3DES as DES EDE using half of the supplied key. However, I'm still getting inconsistent results with .NET.
Here's the Java code:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class Main{
public static void main(String[] args) throws Exception {
byte [] plain = "I eat fish every day".getBytes("utf-8");
byte [] keyBytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
};
byte [] key2Bytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0 }; // actual keys replaced with dummies.
SecretKey keySpec = new SecretKeySpec(keyBytes, "DES");
SecretKey keySpec2 = new SecretKeySpec(key2Bytes, "DES");
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
Cipher e_cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
e_cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
cipher.init(Cipher.DECRYPT_MODE, keySpec2, iv);
byte [] cipherText = e_cipher.doFinal(plain);
cipherText = cipher.doFinal(cipherText);
cipherText = e_cipher.doFinal(cipherText);
System.out.println("Ciphertext: " + new sun.misc.BASE64Encoder().encode(cipherText));
}
}
and here's the .NET code:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace EncryptionDemo
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
var plainBytes = Encoding.UTF8.GetBytes("I eat fish every day");
var keyBytes = new byte [] { 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00 };
var tripleDES = TripleDESCryptoServiceProvider.Create();
var transform = tripleDES.CreateEncryptor(keyBytes, new byte [8]);
var memStream = new MemoryStream();
var cStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
cStream.Write(plainBytes, 0, plainBytes.Length);
cStream.FlushFinalBlock();
//memStream.Position = 0;
var cipherBytes = memStream.ToArray();
Console.WriteLine("Ciphertext: " + Convert.ToBase64String(cipherBytes));
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
Both produce different outputs (some characters in the Base64 string are the same)
A:
3DES keys are 192 bits long.
How are you creating the SecretKey instance? What error message to you get?
The Java code in your question is using DES, not "Triple DES". The algorithm name should be "DESede/CBC/PKCS5Padding". The code in your answer probably works because you got the algorithm right, not because you switched providers. The SunJCE provider in Java 6 will accept 128-bit keys (and use keying option 2). I am not sure about older versions.
A:
the Sun provider doesn't accept 16-byte 3DES keys, but the BouncyCastle provider does. I just tried it out and it works like a charm - it produces the same output as the .NET code!
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Main{
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
byte [] plain = "I eat fish every day".getBytes("utf-8");
byte [] keyBytes = new byte [] { (byte) 0xC1, (byte) 0x57, (byte) 0x45, (byte) 0x08,
(byte) 0x85, (byte) 0x02, (byte) 0xB0, (byte) 0xD3,
(byte) 0xA2, (byte) 0xEF, (byte) 0x68, (byte) 0x43,
(byte) 0x5E, (byte) 0xE6, (byte) 0xD0, (byte) 0x75 };
SecretKey keySpec = new SecretKeySpec(keyBytes, "DESede");
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
Cipher e_cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "BC");
e_cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte [] cipherText = e_cipher.doFinal(plain);
System.out.println("Ciphertext: " + new sun.misc.BASE64Encoder().encode(cipherText));
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Which is queue in multithread java without blocking
Please help me resolve the problem.
I'm trying to send data from gui thread to another thread via a queue.
But I got a problem. While another thread is using queue, GUI thread add an object to the queue, the Gui thread will be blocked some minisecond. So GUI is not smooth.
My class is:
public enum AresManager {
MANAGER;
Queue<AresAction> actionsQueue = new LinkedList<AresAction>();
public synchronized void sendAction(Context context, AresAction action) {
actionsQueue.add(action);
Intent intent = new Intent(context, AresServiceSingleHandler.class);
context.startService(intent);
}
public synchronized AresAction getActionFromQueue() {
AresAction action = actionsQueue.poll();
AresLog.v("[Actions Queue] size = " + actionsQueue.size()
+ " (always should be 0)");
return action;
}
}
A:
The ConcurrentLinkedQueue is a wait-free algorithm that may achieve the results you desire:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Download a file and read from it in the same time
I download a file with this method:
WebClient WC = new WebClient();
WC.DownloadFile(url, filePath);
And i want that in the same time to read the file in the same time with:
var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
but i get allways :
The process cannot access the file 'filePath' because it is being used by another process.
It's possible to download and read in the same time?
Edit
I now download the file with:
var req = (HttpWebRequest)HttpWebRequest.Create(url);
var fileStream = new FileStream(filePath,
FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
using (var resp = req.GetResponse())
{
using (var stream = resp.GetResponseStream())
{
byte[] buffer = new byte[0x10000];
int len;
while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, len);
}
}
}
And still get the error....
A:
var req = (HttpWebRequest)HttpWebRequest.Create(url);
using (var resp = req.GetResponse())
{
using (var stream = resp.GetResponseStream())
{
byte[] buffer = new byte[0x10000];
int len;
while ((len = stream.Read(buffer, 0, buffer.Length))>0)
{
//Do with the content whatever you want
// ***YOUR CODE***
fileStream.Write(buffer, 0, len);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Which pairs of positive integers (,) satisfy $^2−2^=153$?
My attempt: Rearrange to $x^2=2^n + 153$ and with $2^n\geq 2\ $ it follows $x^2 \geq 155\ $.
The next square number is 169, so $x = 13$ and $n = 4$. A first solution. Since $2^n$ is even and 153 is odd, $x^2$ will be odd. So any candidate solution will have an even distance of $2m$ from a previous solution and the difference between these solutions is $(x+2m)^2 - x^2 = 4mx + 4m^2$. This difference can be expressed as a difference between two powers of 2, $4mx + 4m^2 = 2^p - 2^n$. My idea was to show that this doesn´t work so that the first solution is the only one.
A:
$n$ must be even.
$$ 153 = 3^2 \cdot 17 $$
If $$ x^2 - 2 y^2 $$
is divisible by $3,$ then both $x,y$ are divisible by $3.$ Since this $y$ would be a power of $2$ this is impossible.
So $n$ is even, $n=2k,$ and we actually have $$ x^2 - (2^k)^2 = 153 \; , $$
$$ (x+ 2^k) (x-2^k) = 153 $$
Umm. $$ (x+ 2^k) - (x-2^k) = 2^{k+1} $$
This leads to a finite set of possible $x,$ we can factor $153$ as (ordered pairs)
$$ 153 \cdot 1 $$
$$ 51 \cdot 3 $$
$$ 17 \cdot 9 $$
$$ 153 - 1 = 152 = 8 \cdot 19 $$
$$ 51 - 3 = 48 = 16 \cdot 3 $$
$$ 17 - 9 = 8 $$
| {
"pile_set_name": "StackExchange"
} |
Q:
Como usar o método title() no Python?
Como eu uso o title() no Python em uma list, tuple, set?
Exemplos que não executam:
lista = ['banana', 'mamão', 'maçã']
print (lista.title())
tupla = ('banana', 'mamão', 'maçã')
print (tupla.title())
seta = {'banana', 'mamão', 'maçã'}
print (seta.title())
A:
A função title() é uma função que está associada a str do Python, ou seja, você só consegue usá-la se for em uma string. Caso você tenha uma lista de strings e queira que cada um da lista seja capitalizada com a função title, você tem que percorre a lista e adicionar a função title para cada uma deles, isso serve para qualquer interável em Python, como list, set, tuple, etc. Uma maneira simples de se fazer isso sem ter que criar um bloco for para percorrer seu interável de strings é usando as comprehensions do Python, ficaria assim.
lista =['laranja', 'mamão', 'maçã']
nova_lista_captalizada = [ i.title() for i in lista]
tupla = ('banana', 'mamão', 'maçã')
nova_tupla = tuple( i.title() for i in tupla)
# O modo de cima é a mesma coisa que a debaixo
nova_lista_captalizada =[]
for i in lista:
nova_lista_captalizada.append(i.title())
Se você ainda não conhece as comprehensions em Python, não tem problema, você precisa entender aqui, que a função title(), está relacionada a str em Python.
| {
"pile_set_name": "StackExchange"
} |
Q:
Numpy: vectorizing a function that integrate 2D array
I need to perform this following integration for a 2D array:
That is, each point in the grid get the value RC, which is integration over 2D of the difference between the whole field and the value of the field U at certain point (x,y), multiplying the normalized kernel, that in 1D version is:
What I did so far is an inefficient iteration over indexes:
def normalized_bimodal_kernel_2D(x,y,a,x0=0.0,y0=0.0):
""" Gives a kernel that is zero in x=0, and its integral from -infty to
+infty is 1.0. The parameter a is a length scale where the peaks of the
function are."""
dist = (x-x0)**2 + (y-y0)**2
return (dist*np.exp(-(dist/a)))/(np.pi*a**2)
def RC_2D(U,a,dx):
nx,ny=U.shape
x,y = np.meshgrid(np.arange(0,nx, dx),np.arange(0,ny,dx), sparse=True)
UB = np.zeros_like(U)
for i in xrange(0,nx):
for j in xrange(0,ny):
field=(U-U[i,j])*normalized_bimodal_kernel_2D(x,y,a,x0=i*dx,y0=j*dx)
UB[i,j]=np.sum(field)*dx**2
return UB
def centerlizing_2D(U,a,dx):
nx,ny=U.shape
x,y = np.meshgrid(np.arange(0,nx, dx),np.arange(0,ny,dx), sparse=True)
UB = np.zeros((nx,ny,nx,ny))
for i in xrange(0,nx):
for j in xrange(0,ny):
UB[i,j]=normalized_bimodal_kernel_2D(x,y,a,x0=i*dx,y0=j*dx)
return UB
You can see the result of the centeralizing function here:
U=np.eye(20)
plt.imshow(centerlizing(U,10,1)[10,10])
I'm sure I have additional bugs, so any feedback will be warmly welcome, but what I am really interested is understanding how I can do this operation much faster in vectorized way.
A:
normalized_bimodal_kernel_2D is called in the two nested loops that each shift only it's offset by small steps. This duplicates many computations.
An optimization for centerlizing_2D is to compute the kernel once for a bigger range and then define UB to take shifted views into that. This is possible using stride_tricks, which unfortunately is rather advanced numpy.
def centerlizing_2D_opt(U,a,dx):
nx,ny=U.shape
x,y = np.meshgrid(np.arange(-nx//2, nx+nx//2, dx),
np.arange(-nx//2, ny+ny//2, dx), # note the increased range
sparse=True)
k = normalized_bimodal_kernel_2D(x, y, a, x0=nx//2, y0=ny//2)
sx, sy = k.strides
UB = as_strided(k, shape=(nx, ny, nx*2, ny*2), strides=(sy, sx, sx, sy))
return UB[:, :, nx:0:-1, ny:0:-1]
assert np.allclose(centerlizing_2D(U,10,1), centerlizing_2D_opt(U,10,1)) # verify it's correct
Yep, it's faster:
%timeit centerlizing_2D(U,10,1) # 100 loops, best of 3: 9.88 ms per loop
%timeit centerlizing_2D_opt(U,10,1) # 10000 loops, best of 3: 85.9 µs per loop
Next, we optimize RC_2D by expressing it with the optimized centerlizing_2D routine:
def RC_2D_opt(U,a,dx):
UB_tmp = centerlizing_2D_opt(U, a, dx)
U_tmp = U[:, :, None, None] - U[None, None, :, :]
UB = np.sum(U_tmp * UB_tmp, axis=(0, 1))
return UB
assert np.allclose(RC_2D(U,10,1), RC_2D_opt(U,10,1))
Performance of %timeit RC_2D(U,10, 1):
#original: 100 loops, best of 3: 13.8 ms per loop
#@DanielF's: 100 loops, best of 3: 6.98 ms per loop
#mine: 1000 loops, best of 3: 1.83 ms per loop
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is my not working?
I have the following code:
<a4j:commandButton value="Adicionar BOM"
onclick="#{rich:component('addBomModal')}.show()">
<a4j:ajax event="click" immediate="true"
oncomplete="Richfaces.showModalPanel('addBomModal')"
render="addBomModal" />
</a4j:commandButton>
and
<h:form>
<rich:popupPanel id="popup" modal="true" resizeable="true"
onmaskclick="#{rich:component('popup')}.hide()">
// rest of popupPanel
</rich:popupPanel>
</h:form>
The page is rendered but nothing happens when I click the button.
How can this be solved?
Thanks in advance,
gtludwig
A:
You have too many things going on. You first open the pop-up in onclick (button) and then open it again in oncomplete via older API (I'm not sure it was migrated to RichFaces 4). All you need is what you have in onclick, you don't need a4j:ajax.
| {
"pile_set_name": "StackExchange"
} |
Q:
ActiveJob uninitialized constant
I have a weird problem with ActiveJob.
From a controller I'm executing the following sentence:
ExportJob.set(wait: 5.seconds).perform([A series of parameters, basically strings and integers])
ExportJob.rb
require_relative 'blablabla/resource_manager'
class ExportJob < ActiveJob::Base
def perform
ResourceManager.export_process([A series of parameters, basically strings and integers])
end
end
When the controller/action is executed for the first time the process goes fine, but the second time an error is thrown:
uninitialized constant ExportJob::ResourceManager
The weird thing is that this is not the only job I have in my project, the other ones are being executed without any problem.
I'm Attaching some information of my project:
development/production.rb
config.active_job.queue_adapter = :delayed_job
Gemfile:
gem 'delayed_job'
gem 'delayed_job_active_record'
Any clue would be a help for me.
Thanks in advance!
A:
Constants don't have global scope in Ruby. Constants can be visible from any scope, but you must specify where the constant is to be found.
Without :: Ruby looks for the ResourceManager constant in lexical scope of the currently executing code (which is ExportJob class, so it looks for ExportJob::ResourceManager).
The following should work (assuming that ResourceManager is defined as a top level constant (eg not nested under any module/class):
class ExportJob < ActiveJob::Base
def perform
::ResourceManager.export_process(*args)
end
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Count Unique Combination of Values
Imagine the following scenario:
ColA | ColB
1 | 1
1 | 2
1 | 3
2 | 1
2 | 2
2 | 3
3 | 1
3 | 2
3 | 3
Using SQL Server 2008, how would I count an occurrence such that the combination (1,2) would be the same as (2,1) and therefore my results would be as follows:
ColA | ColB | Count
1 | 1 | 1
1 | 2 | 2
1 | 3 | 2
2 | 2 | 1
2 | 3 | 2
3 | 3 | 1
Thanks!
A:
Try this:
;with cte as
(select
ColA,
ColB,
case when ColA < ColB then ColA else ColB end as ColC,
case when ColA > ColB then ColA else ColB end as ColD
from yourtable)
select
ColC as ColA,
ColD as ColB,
count(1) as Count
from cte
group by ColC, ColD
order by ColC, ColD
| {
"pile_set_name": "StackExchange"
} |
Q:
Quaternions: Difference(s) between $\mathbb{H}$ and $Q_8$
What is the difference between $\mathbb{H}$ and $Q_8$? Both are called quaternions.
A:
A good analogy here is the difference between the complex numbers $\mathbb{C}$ and the cyclic group with 4 elements, which can be realized as the group $\{1, i, -1, -i\}\subset\mathbb{C}$ with complex multiplication.
$\mathbb{C}$ is a 2-dimensional vector space over $\mathbb{R}$, and there is a group inside it denoted $\mathbb{Z}/4\mathbb{Z}=\{\pm 1, \pm i\}$ with complex multiplication. This is the cyclic group with four elements.
Analogously, $\mathbb{H}$ is a 4-dimensional vector space over $\mathbb{R}$, and there is a group called $Q_8$ inside of it, namely the standard basis (with negatives) $\{\pm 1, \pm i, \pm j, \pm k\}\subset\mathbb{H}$ where the operation is quaternion multiplication.
tl;dr -- $Q_8$ sits inside $\mathbb{H}$. The first is known as the quaternion group, and the second thing is the quaternions.
A:
One is the Hamiltonian Quaternions and has many descriptions, perhaps the most important (for things that immediately interest me) is that it is the )up to equivalence) only non-trivial central simple algebra over $\mathbb{R}$--it is also an object of fundamental importance in geometry.
$Q_8$ is the quaternion group. It is of great importance for the many weird properties it has that cause it to be a counterexample to many simple group theoretic questions--it is a non-abelian group all of whose subgroups are normal.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a popular expression in english to say "pasadomañana" as in spanish?
There is in spanish a word "pasadomañana" to refer to the day after tomorrow, I wonder if maybe there is an popular/informal way to mean the same without say the day after tomorrow
A:
Yes absolutely! One of the most popular expressions to refer to the day after tomorrow is "in two days", an expression slightly shorter than "pasadomañana". Or something similar, depending on the context.
(In fact, it's so common that any answer that dares suggest it might seem condescending, but I'll try my best.)
This expression can be used in pretty much any type of writing: formal, informal, headlines, txtspk, spoken, written, period-specific, etc.
(This is not something true for "overmorrow", a now-obsolete word which appears neither in COCA nor Google N-Grams. It was never popular, since the OED marks it as "obsolete rare", so if you use this word you risk clarity.)
When used in informal writing, the number isn't always written out: "in 2 days". More rarely, in extremely informal writing, sometimes the space after 2 is removed. In places where hashtags are common, you can sometimes see things written as a hashtag, although this is also pretty rare: "in #2days".
Although there are many false positives, you can find more examples on Twitter (in two days, in 2 days, in 2days, in #2days).
There is also an adjective form, seen for example on Amazon:
FREE Two-Day Shipping through Amazon Prime
| {
"pile_set_name": "StackExchange"
} |
Q:
Boost converter simulation keeps getting fried
In my project I want to use a couple of old russian VFDs. To drive them, I need 28V from a 12V power supply. The plan is to use a DC-DC boost converter as calculated here and here.
I've ported the designs to Yenka, a circuit simulator, but for some reason the MOSFET and inductor keep burning up because of sudden peeks of current of hundreds of amperes.
That surely can't be caused by the lack of Schottky diodes in the software, a small difference in frequency of switching the diode and the voltage drop can't cause such immense currents - or can it?
A:
The basic topology looks OK, so the problems are most likely due to implementation details. Since you gave little detail, we can only make some guesses:
The FET isn't being driven too slowly. The total transition time should be a small fraction of the pulsing period. For example, if the oscillator is running at 100 kHz, then the pulse period is 10 µs, and the switching transition time should be small compared to that. If the gate voltage takes more than 1 µs (in this example) to get from high to low or low to high, that's not good.
FETs have significant gate capacitance, so it takes a significant pulse of current to switch the gate from one state to the other. The digital output can probably only source or sink a few 10s of mA.
Your are using too high a frequency. This works together with #1. The faster the oscillator, the faster the gate needs to transition to keep the FET fully on or fully off most of the time.
At this low voltage you really should be using a Schottky diode, not the ordinary silicon diode you show. There are two reasons for this. Schottky diodes have a lower forward drop and have very fast reverse recovery time. The lower forward drop helps with efficiency. The fast reverse recovery time is very important since the FET is shorting the output during the recovery time. That really beats on the FET and the diode.
2 mH seems very large. Again, we don't know your switching speed or output current requirement, but such large inductors will have significant series resistance.
The duty cycle is not optimized. For a ideal switch and diode, the forward voltage on the inductor will be 12 V, and the reverse voltage 16 V. The length of the on and off phases should be inversely proportional to those, respectively. Again, let's use 100 kHz switching frequency as example. That gives you 10 µs for the whole period. You want 16 parts of that to be on and 12 parts off, which means 5.7 µs on and 4.3 µs off. Since there will be some inefficiencies and losses, in practise the on time will be a little more relative to the off time than the purely theoretical 16/12 ratio.
| {
"pile_set_name": "StackExchange"
} |
Q:
CRM 2011 Multiple Instances on Same SQL Server
We need to install multiple deployments of CRM 2011 for different clients. Is it possible to have a single SQL Server with multiple named instances as the database server - or - do we need a single SQL Server per CRM installation?
Any guidance is greatly appreciated.
Jason
A:
Named instances are fine for Dynamics CRM. However, do you really need separate instances of SQL?
Are you aware of the multi-tenant capabilities of Dynamics CRM? You could create as many organizations on a single SQL-Server, as long your infrastructure has enough resources. Each of the organizations are completely isolated from each other.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unit Tests run too fast when run in groups caused by the 'System.DateTime' accuracy
I am running a nice big list of unit tests which are checking various different class gets and sets. I have come across a bit of a bug in that my tests run too fast?!?
As a quick example, the unit tests start by mocking a blog with a comment;
Blog b = new Blog("Comment");
This sets the DateTime added of the new comment in the blog. I am then testing the addition of a comment to the blog;
b.addComment(comment);
At the end of the test I am asserting the addition of the test using the following;
Assert.AreEqual(x, b.Comments.OrderByDescending(x => x.CreatedDate).First().Comment;
As it stands this passes when run in isolation. However when the test is run in a group of tests this will fail because both comments have the exact same DateTime. It's worth noting the the following will pass only because it will be ordered by the default ordering;
Assert.AreEqual(x, b.Comments.OrderBy(x => x.Created).Last().Comment;
My initial thought was how the hell can it fail? The DateTime.Utc has a ticks function which is accurate to like a millionth of a second. after some research I found out that the system date time is only precise to 10-15ms so this is my issue.
My question is, whats the best solution?
I could add Thread.Sleep(20); to every test but if I run 1000 tests that's now 20 seconds? How have other people got round this issue?
A:
Your class depends on external resource, which is current system time. Thus you are not testing class in isolation, which gives you problem you faced. You should mock DateTime.Now (some unit-testing frameworks allow mocking static members - e.g. JustMock), or create abstract dependency, which will provide time to your class:
public interface ITimeProvider
{
DateTime CurrentTime { get; }
}
As Mark Seemann suggests here, you can use static instance of this abstraction to avoid passing this dependency to each class which needs to get current time, but that will make dependency implicit (so its up to you to decide which way to go):
public class TimeProvider : ITimeProvider
{
private static ITimeProvider _instance = new TimeProvider();
private TimeProvider() { }
public static ITimeProvider Instance
{
get { return _instance; }
set { _instance = value; } // allows you to set mock
}
public DateTime CurrentTime
{
get { return DateTime.Now; }
}
}
Usage will be easy
var date = TimeProvider.Instance.CurrentTime;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to configure a dockerfile and docker-compose for Jenkins
Im absolutely new in Docker and Jenkins as well. I have a question about the configuration of Dockerfile and docker-compose.yml file. I tried to use the easiest configuration to be able to set-up these files correctly. Building and pushing is done correctly, but the jenkins application is not running on my localhost (127.0.0.1).
If I understand it correctly, now it should default running on port 50000 (ARG agent_port=50000 in jenkins "official" Dockerfile). I tried to use 50000, 8080 and 80 as well, nothing is working. Do you have any advice, please? Im using these files: https://github.com/fdolsky321/Jenkins_Docker
The second question is, whats the best way to handle the crashes of the container. Lets say, that if the container crashes, I want to recreate a new container with the same settings. Is the best way just to create a new shell file like "crash.sh" and provide there the information, that I want to create new container with the same settings? Like is mentioned in here: https://blog.codeship.com/ensuring-containers-are-always-running-with-dockers-restart-policy/
Thank you for any advice.
A:
docker-compose for Jenkins
docker-compose.yml
version: '2'
services:
jenkins:
image: jenkins:latest
ports:
- 8080:8080
- 50000:50000
# uncomment for docker in docker
privileged: true
volumes:
# enable persistent volume (warning: make sure that the local jenkins_home folder is created)
- /var/wisestep/data/jenkins_home:/var/jenkins_home
# mount docker sock and binary for docker in docker (only works on linux)
- /var/run/docker.sock:/var/run/docker.sock
- /usr/bin/docker:/usr/bin/docker
Replace the port 8080, 50000 as you need in your host.
To recreate a new container with the same settings
The volumne mounted jenkins_home, is the placewhere you store all your jobs and settings etc..
Take the backup of the mounted volume jenkins_home on creating every job or the way you want.
Whenever there is any crash, run the Jenkins with the same docker-compose file and replace the jenkins_home folder with the backup.
Rerun/restart jenkins again
List the container
docker ps -a
Restart container
docker restart <Required_Container_ID_To_Restart>
A:
I've been using a docker-compose.yml that looks like the following:
version: '3.2'
volumes:
jenkins-home:
services:
jenkins:
image: jenkins-docker
build: .
restart: unless-stopped
ports:
- target: 8080
published: 8080
protocol: tcp
mode: host
volumes:
- jenkins-home:/var/jenkins_home
- /var/run/docker.sock:/var/run/docker.sock
container_name: jenkins-docker
My image is a locally built Jenkins image, based off of jenkins/jenkins:lts, that adds in some other components like docker itself, and I'm mounting the docker socket to allow me to run commands on the docker host. This may not be needed for your use case. The important parts for you are the ports being published, which for me is only 8080, and the volume for /var/jenkins_home to preserve the Jenkins configuration between image updates.
To recover from errors, I have restart: unless-stopped inside the docker-compose.yml to configure the container to automatically restart. If you're running this in swarm mode, that would be automatic.
I typically avoid defining a container name, but in this scenario, there will only ever be one jenkins-docker container, and I like to be able to view the logs with docker logs jenkins-docker to gather things like the initial administrator login token.
My Dockerfile and other dependencies for this image are available at: https://github.com/bmitch3020/jenkins-docker
| {
"pile_set_name": "StackExchange"
} |
Q:
Get values of multiple select boxes in PHP and add them to an array
I have a button which allows an ingredient to be added to a database. When the button is clicked, the user can add the name, measurement and unit for the ingredient which is done using Javascript:
function addIngredient() {
var area = document.getElementById("addedIngredient");
var num = document.createElement("p");
numText = document.createTextNode(countIngredient + ". ");
num.appendChild(numText);
area.appendChild(num);
//Ingredient Name
var ingredientNameLabel = document.createElement("p");
ingredientNameLabelText = document.createTextNode("Name");
ingredientNameLabel.appendChild(ingredientNameLabelText);
area.appendChild(ingredientNameLabel);
countIngredient++;
var ingredientNameInput = document.createElement("INPUT");
ingredientNameInput.setAttribute("name", "ingredient_name[]");
ingredientNameInput.setAttribute("type", "text");
ingredientNameInput.setAttribute("class", "form-control");
ingredientNameInput.setAttribute("class", "ingName");
area.appendChild(ingredientNameInput);
//Ingredient Measure
var ingredientMeasureLabel = document.createElement("p");
ingredientMeasureLabelText = document.createTextNode("Measure");
ingredientMeasureLabel.appendChild(ingredientMeasureLabelText);
area.appendChild(ingredientMeasureLabel);
var ingredientMeasureInput = document.createElement("INPUT");
ingredientMeasureInput.setAttribute("name", "ingredient_measure[]");
ingredientMeasureInput.setAttribute("type", "text");
ingredientMeasureInput.setAttribute("class", "form-control");
ingredientMeasureInput.setAttribute("class", "ingMeasure");
area.appendChild(ingredientMeasureInput);
//Ingredient Unit
var ingredientUnitLabel = document.createElement("p");
ingredientUnitLabelText = document.createTextNode("Unit");
ingredientUnitLabel.appendChild(ingredientUnitLabelText);
area.appendChild(ingredientUnitLabel);
var select = document.createElement("SELECT");
select.setAttribute("name", "ingredient_unit[]");
area.appendChild(select);
var option = document.createElement("option");
option.setAttribute("value", "grams");
var value = document.createTextNode("g");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "milimeters");
var value = document.createTextNode("ml");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "kilograms");
var value = document.createTextNode("kg");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "litres");
var value = document.createTextNode("litre(s)");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "slice");
var value = document.createTextNode("slice");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "whole");
var value = document.createTextNode("whole");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "pinch");
var value = document.createTextNode("pinch");
option.appendChild(value);
select.appendChild(option);
}
I am looking to get the unit selected for every ingredient added.
Can anyone tell me how I could do this using PHP?
I am trying the following way:
$units = [];
foreach ($_POST["ingredient_unit[]"] as $key => $unit) {
array_push($units, $unit);
}
This does not work nor does it give an error.
Thanks.
A:
Change the following code:
foreach ($_POST["ingredient_unit[]"] as $key => $unit) {
array_push($units, $unit);
}
And use this instead:
foreach ($_POST["ingredient_unit"] as $key => $unit) {
array_push($units, $unit);
}
And you should be getting a notice when you try to access $_POST["ingredient_unit[]"] since its not defined. If you are not seeing a notice, maybe the error_reporting level is too low. You could use something like the following to active all errors except the deprecated ones:
error_reporting(E_ALL &~ E_DEPRECATED);
| {
"pile_set_name": "StackExchange"
} |
Q:
Refresh .bashrc with new env variables
I have a production server running our rails app, and we have ENV variables in there, formatted correctly. They show up in rails c but we have an issue getting them to be recognized in the instance of the app.
Running puma, nginx on an ubuntu box.
What needs to be restarted every time we change .bashrc? This is what we do:
1. Edit .bashrc
2. . .bashrc
3. Restart puma
4. Restart nginx
still not recognized..but in rails c, what are we missing?
edit:
Added env variables to /etc/environment based on suggestions from other posts saying that .bashrc is only for specific shell sessions, and this could have an effect. supposedly /etc/environment is available for all users, so this is mine. still having the same issues:
Show up fine in rails c
Show up fine when I echo them in shell
Do not show up in application
export G_DOMAIN=sandboxbaa3b9cca599ff0.mailgun.org
export [email protected]
export [email protected]
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
edit:
In the app i request G_DOMAIN and G_EMAIL in plain html (this works on development with dotenv, does not work once pushed to production server with ubuntu server) :
ENV TEST<BR>
G_DOMAIN: <%= ENV['G_DOMAIN'] %><br>
G_EMAIL:<%= ENV['G_EMAIL'] %>
However, the following env variables are available to use (in both .bashrc and /etc/environment, same as all variables we displayed above) because our images work fine and upload to s3 with no issue, on production.
production.rb
# Configuration for Amazon S3
:provider => 'AWS',
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
edit2: could this be anything with this puma issue?
https://github.com/puma/puma/commit/a0ba9f1c8342c9a66c36f39e99aeaabf830b741c
A:
I was having a problem like this, also. For me, this only happens when I add a new environment variable.
Through this post and after some more googling, I've come to understand that the restart command for Puma (via the gem capistrano-puma) might not see new environment variables because the process forks itself when restarting rather than killing itself and being started again (this is a part of keeping the servers responsive during a deploy).
The linked post suggests using a YAML file that's only stored on your production server (read: NOT in source control) rather than rely on your deploy user's environment variables. This is how you can achieve it:
Insert this code in your Rails app's config/application.rb file:
config.before_configuration do
env_file = File.join(Rails.root, 'config', 'local_env.yml')
YAML.load(File.open(env_file)).each do |key, value|
ENV[key.to_s] = value
end if File.exists?(env_file)
end
Add this code to your Capistrano deploy script (config/deploy.rb)
desc "Link shared files"
task :symlink_config_files do
on roles(:app) do
symlinks = {
"#{shared_path}/config/local_env.yml" => "#{release_path}/config/local_env.yml"
}
execute symlinks.map{|from, to| "ln -nfs #{from} #{to}"}.join(" && ")
end
end
before 'deploy:assets:precompile', :symlink_config_files
Profit! With the code from 1, your Rails application will load any keys you define in your server's Capistrano directory's ./shared/config/local_env.yml file into the ENV hash, and this will happen before the other config files like secrets.yml or database.yml are loaded. The code in 2 makes sure that the file in ./shared/config/ on your server is symlinked to current/config/ (where the code in 1 expects it to be) on every deploy.
Example local_env.yml:
SECRET_API_KEY_DONT_TELL: 12345abc6789
OTHER_SECRET_SHH: hello
Example secrets.yml:
production:
secret_api_key: <%= ENV["SECRET_API_KEY_DONT_TELL"] %>
other_secret: <%= ENV["OTHER_SECRET_SHH"] %>
This will guarantee that your environment variables are found, by not really using environment variables. Seems like a workaround, but basically we're just using the ENV object as a convenient global variable.
(the capistrano syntax might be a bit old, but what is here works for me in Rails 5... but I did have to update a couple things from the linked post to get it to work for me & I'm new to using capistrano. Edits welcome)
| {
"pile_set_name": "StackExchange"
} |
Q:
Find distance from point to line
I am asked to find the distance between a point ( 5,1,1 ) and a line
$\displaystyle \left\{\begin{matrix} x + y + z = 0\\ x - 2y + z = 0 \end{matrix}\right.$
What ive done so far is to simplify by gauss elimination and I get to:
$\displaystyle \begin{bmatrix} 1 &1 &1 &0 \\ 0 &1 &0 &0 \end{bmatrix}$
In turn I put this back in the form of an equation
$\left\{\begin{matrix} x + y + z = 0\\ y = 0 \end{matrix}\right.$
What I need to find the distance between the point and line is any point on the line and a directional vector, right?
Am i right in assuming that we have
$\begin{pmatrix} x,y,z \end{pmatrix} = \begin{pmatrix} t,0,-t \end{pmatrix}$
So a point on this line could be (1,0,-1) or (12,0,-12)? If this is correct, how would I go on about finding the directional vector so I can put this all on the form of
$\begin{Vmatrix} \overrightarrow{PQ} \times \overrightarrow{v} \end{Vmatrix} \div \begin{Vmatrix} \overrightarrow{v} \end{Vmatrix}$
So to sum up, Q is given, the line is given in a system of equations, how do I extract a point P on the line and the vector v?
A:
For $t=1$, a possible directional vector for your line is $(1,0,-1)$. The projection of $(5,1,1)$ onto $(1,0,-1)$ would be $(2,0,-2)$ and that is the closest point on the line, to $(5,1,1)$.
The distance would then be $|(5,1,1)-(2,0,-2)|$. The length of the rejection.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to add active class in xslt?
could you please tell me how to add active class in xslt using call-template?
here is my code
http://xsltransform.net/jxDigTt/1
Expected output :active class added in A because I pass 'A' as selected item
<ul>
<li class="active">A</li>
<li>B</li>
</ul>
Expected output :active class added in B because I pass 'B' as selected item
<ul>
<li >A</li>
<li class="active">B</li>
</ul>
full code
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
<hmtl>
<head>
<title>New Version!</title>
<style>
.active {
color:red
}
</style>
</head>
<xsl:call-template name="submenu_navigation">
<xsl:with-param name="selectedItem" select="'A'"/>
</xsl:call-template>
</hmtl>
</xsl:template>
<xsl:template name="submenu_navigation">
<xsl:param name="selectedItem"/>
<xsl:value-of select='$selectedItem'/>
<ul>
<li>A</li>
<li>B</li>
</ul>
</xsl:template>
</xsl:transform>
A:
You can adjust the submenu_navigation template like this:
<xsl:template name="submenu_navigation">
<xsl:param name="selectedItem"/>
<xsl:value-of select='$selectedItem'/>
<ul>
<li><xsl:if test="$selectedItem = 'A'">
<xsl:attribute name="class">active</xsl:attribute></xsl:if>A</li>
<li><xsl:if test="$selectedItem = 'B'">
<xsl:attribute name="class">active</xsl:attribute></xsl:if>B</li>
</ul>
</xsl:template>
The <xsl:if> makes the creation of the attribute conditional.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dropdown list of a custom post type
I have a custom post type, Doctors, that I need to create a dropdown nav for. I just want it to populate a select list with all the posts of that CPT and navigate to that post on selection.
I'm doing a couple other dropdowns with wp_dropdown_categories, but I guess there's no built in function for listing a post type?
A:
You'll need to use get_posts and roll your own drop down.
Something like this (somewhere in functions.php):
<?php
function wpse34320_type_dropdown( $post_type )
{
$posts = get_posts(
array(
'post_type' => $post_type,
'numberposts' => -1
)
);
if( ! $posts ) return;
$out = '<select id="wpse34320_select"><option>Select a Doctor</option>';
foreach( $posts as $p )
{
$out .= '<option value="' . get_permalink( $p ) . '">' . esc_html( $p->post_title ) . '</option>';
}
$out .= '</select>';
return $out;
}
Then in your template...
<?php echo wpse34320_type_dropdown( 'doctors' ); ?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Algebraic Geometry for Topologists
As someone who is
familiar with algebraic topology, say, at the level of Hatcher's book, and
familiar with homological algebra and categories and applications in topology
but has no idea what a variety is
what is a good place to start learning algebraic geometry?
A:
(I guess my opinion is no more worthy of being an answer than the opinions in the comments, but it's verbose, so let me put it in the answer box anyway.)
As a beginning PhD student I knew a reasonable amount of algebraic topology, similar to what you describe in the question. But I don't think it really gave me any extra or better choices in how to start learning algebraic geometry. As Steven Landsburg's comment suggests, the kind of objects one studies and the methods one uses in algebraic geometry are so much more specialised than arbitrary (even nice) topological spaces that you really need to start from scratch, with something like Shafarevich (as suggested by Mark Grant).
That isn't to say that having a good knowledge of algebraic topology won't be useful to you in learning algebraic geometry --- quite the opposite, in fact. (Example: characteristic classes.) And, as you progress in algebraic geometry, you will likely run into more and more topics where your topology knowledge gives you a great head-start on understanding. But it won't really help with those first steps.
On the other hand, if I had to nominate a beginning algebraic geometry textbook that is oriented towards the topological point of view, I guess it would be Principles of Algebraic Geometry by Griffiths and Harris. But, great resource though it is, I don't think I can recommend that book to anyone in good conscience as a first introduction to algebraic geometry.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is wrong with my constructor in java?
Is there a better way (probably..) to build a class in which i can use set/get method.
Notice thay all the data are stock in a ArrayList.
public class PorterList
{
public PorterList()
{
ArrayList<Porter> porList = new ArrayList<>();
}
public PorterList(ArrayList<Porter> p)
{
ArrayList<Porter> porList = p;
}
SimpleDateFormat porterDF = new SimpleDateFormat("HH:mm:ss");
private Porter p = new Porter();
private int _porterNo;
public String getStatus(int porterNo)
{
_porterNo = porterNo;
p = porList.get(_porterNo);
return p.p_state;
}
There's something wrong on that second last line p = porList.get(_porterNo);
I want to use something like this in my main:
p_L = PorterList(p)
porter_status = p_L.get(5)
Thank you very much
A:
As you declare ArrayList porList = p; inside the constructors , It will become local variable , so it will not be visible outside that constructor , If you want it to use at your class level declare it at globally liek below
public class PorterList
{
private ArrayList<Porter> porList;
public PorterList()
{
porList = new ArrayList<>();
}
public PorterList(ArrayList<Porter> p)
{
porList = p;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
CONV() function in snowflake
I'm trying to find equivalent of the CONV() MySQL function in Snowflake, but I can't seem find it.
I'm trying to do the following in Snowflake:
SELECT CONV('39ix75wf3aor7',36,10)
The result should be 15468921890196183763
A:
I wrote a UDF to do what CONV() does. It works, but unfortunately Javascript variables don't support numeric precision for as large as your sample.
This will work for smaller inputs, but for your large Base36 input the following happens:
15468921890196183763 --should be this result
15468921890196185000 --Javascript native variables do not have that level of precision
In case you find it useful for smaller values to covert from one base to another, here it is:
create or replace function CONV(VALUE_IN string, OLD_BASE float, NEW_BASE float)
returns string
language javascript
as
$$
// Usage note: Loses precision for very large inputs
return parseInt(VALUE_IN, Math.floor(OLD_BASE).toString(Math.floor(NEW_BASE)));
$$;
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I format a month in mmm format?
I am trying to format a date in Excel with VBA, the current month to be in mmm format. Somehow I am getting the previous month, instead of the current month. I have checked and my computer month is Feb, but I am getting Jan, instead.
This is my code:
Cells(1, 2) = Format(month(Date), "mmm")
A:
Just format the existing date directly, ie
Cells(1, 2) = Format(Date, "mmm")
A:
You are formating the date 1/1/1900
Let me explain:
Date is worth 21/02/2012
Month(Date) is worth 1
Format will consider this as a date so Month(Date) will be 1/1/1900
So Format(month(Date), "mmm") will return Jan as the month of 1/1/1900
To teach you fishing, when you face this kind of issue, you can try to find the value of each statement :
Debug.Print (Date) returns 21/02/2012 so this part is ok
Debug.Print (Format(Month(Date), "mmm")) returns jan so this is not a displaying cell issue
| {
"pile_set_name": "StackExchange"
} |
Q:
Making the WebView more little
I have a little app for the iPad that shows some things, and a little WebView. The problem is that I don't know how to make the webs that the WebView shows more little. Anyone knows something about it?
A:
You may want to tell the UIWebView to scale the page to its bounds and modify its frame to the size you want.
[webView setScalesPageToFit:YES];
[webView setFrame:yourFrame];
| {
"pile_set_name": "StackExchange"
} |
Q:
What difference does it make when match_max is specified after or before spawing ssh?
# match_max 1000000000
set timeout 60
spawn ssh -o "StrictHostKeyChecking no" "$username@$hostname"
match_max 1000000000
If match_max option is given before i use ssh i don't get the complete output into the expect_out(buffer) but if I give the same thing after SSH I get correct results.
Also, if i use -d option in the first case I get the complete output. Why?
Also, how can I check how much buffer is set for my Linux system? I looked for limit command but couldn't find it.
A:
The man page for expect regarding the match_max command reads
match_max [-d] [-i spawn_id] [size]
defines the size of the buffer (in bytes) used internally by expect. With no size argument, the current size is returned. With the -d flag, the default size is set. (The initial default is 2000.) With the -i flag, the size is set for the named spawn id, otherwise it is set for the current process.
This is exactly what you're observing (since -i isn't specified).
| {
"pile_set_name": "StackExchange"
} |
Q:
to access a specific key-value pair in hash
I want to print only the specific key:pair from the following hash in perl:
1: one
2: two
3: three
and I am using the following statement to print my hash:
foreach (sort keys %hash) {
print "$_ : $hash{$_}";
}
what should the code if I only want to print 1: one or 2: two from the hash.
A:
foreach (sort keys %hash) {
if ($_ eq 1 ) {
print "$_ : $hash{$_}";
last;
}
}
Using last will cause your loop to exit as soon as condition is met. I hope this will solve your problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to upgrade Android firmware programatically?
I need to write Android application which looks for firmware in internet and allows to automatically download selected firmware and perform update on device. Is it possible?
Thanks
A:
It should be possible. I am trying to do the same thing. I posted a question about this as another user. It almost works for me, but my device can't apply the new image on boot time.
Basically you use the RecoverySystem.installPackage(context, packageFile) method to do this. You will also need the following permissions:
<uses-permission android:name="android.permission.REBOOT" />
<uses-permission android:name="android.permission.ACCESS_CACHE_FILESYSTEM" />
<uses-permission android:name="android.permission.DELETE_CACHE_FILES" />
Also, your app must run as a system app. I don't know if you're using the whole Android SDK with Eclipse and the SDK tools, but what I did for that was basically connect my device to my machine and used it for debuggin, then ran the app through the IDE so it gets uploaded and run on the device. And finally use the adb shell command to open up a shell on my device and moved the apk package file from /data/app to /system/app and rebooted.
Check out my post here. It might help you out.
Android development RecoverySystem.installPackage() cannot write to /cache/recovery/command permission denied
| {
"pile_set_name": "StackExchange"
} |
Q:
sql to get tags in linking table
I have a query that I made to return all the tags in a set with the tags in a concatenated list, but I'm trying to determine how to write a query that will return the same results but only for those items with a specific tag.. list talks by tag, if you will. Logically, if I add a 'where tbl_tag.tag_id=3', it only lists that specific tag in the group.. I want it to be able to still list all of them. Possibly multiple queries are the answer but I'm curious if it can be done with one.
SELECT tbl_talks.*,
GROUP_CONCAT(tbl_tag.tag_name ORDER BY tbl_tag.tag_name) AS tags
FROM tbl_talks
LEFT JOIN tbl_linking_talk_tag
ON tbl_talks.talk_id = tbl_linking_talk_tag.talk_id
LEFT JOIN tbl_tag
ON tbl_linking_talk_tag.tag_id = tbl_tag.tag_id
GROUP BY tbl_talks.talk_id
A:
The quick, hackish solution would be to wrap your entire query in an outer query, and only return records containing the appropriate tag using WHERE tags LIKE '%....%. This is fragile, because there's always the chance that you'll have one tag (e.g. "berry") that is container within another (e.g. "strawberry"). There are ways around this, but they're not pretty and not very SQLish.
A slightly more correct (and equally untested!) solution would be to add the original query as a subquery in your WHERE clause:
WHERE EXISTS
(
SELECT
1
FROM
tbl_talks
LEFT JOIN tbl_linking_talk_tag
ON tbl_talks.talk_id = tbl_linking_talk_tag.talk_id
LEFT JOIN tbl_tag
ON tbl_linking_talk_tag.tag_id = tbl_tag.tag_id
WHERE
tbl_tag.tag_id IN (the, tag_ids, you, want)
)
There might be a simpler built-in way of doing this in MySQL, but I don't know it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing default JLabel font
How would I go about setting the default font for all JLabel instances. Instead of setting the font for each JLabel independently.
A:
Use UIManager to define JLabel's default font:
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
public class LabelFont {
public static void main(String[] args) {
Font oldLabelFont = UIManager.getFont("Label.font");
UIManager.put("Label.font", oldLabelFont.deriveFont(Font.PLAIN));
JFrame f = new JFrame("LabelFont Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new FlowLayout());
JLabel df = new JLabel("Default JLabel font");
f.getContentPane().add(df);
JLabel ef = new JLabel("Font explicitly set");
ef.setFont(oldLabelFont);
f.getContentPane().add(ef);
f.pack();
f.setVisible(true);
}
}
Via: http://coding.derkeiler.com/Archive/Java/comp.lang.java.help/2005-04/msg00395.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento 2 How to override banktransfer.html file in custom module
I am trying to add custom text box by custom module throw overriding this file
"vendor/magento/module-offline-payments/view/frontend/web/template/payment/banktransfer.html"
to my custom module. Please share your idea or suggestions to make this code working.
A:
Add requiredjs-config.js :
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
var config = {
map: {
'*': {
'module-offline-payments/template/payment/banktransfer.html':
'namespace/ModuleName/template/payment/banktransfer.html'
}
}
};
After override this html template remove pub/static and apply
php bin/magento setup:static-content:deploy
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.