source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0010120689.txt"
] | Q:
Bold and underline dropdown list menu item asp.net
i got a questiong to ask. I got a dropdown list in my app.However the dropdown list is populate with hierarchy format. Please c the picture
As the picture above. How can i bold and underline the parent menu item such as Men , ladies and NA On the other hand , the parent item is not allow to select also.
Here is my coding
private void createDDLCategory()
{
ddlCategory.AppendDataBoundItems = true;
ddlCategory.Items.Insert(0, new ListItem("All","A"));
ddlCategory.SelectedIndex = 0;
var ddl1 = dropdownlist.ddlCategoryWithoutGroup();
foreach (var value in ddl1)
{
if (value.P_CATEGORY_ID == null)
{
this.ddlCategory.Items.Add(new ListItem(value.CATEGORY_NAME, value.CATEGORY_ID.ToString()));
this.ddlCategory.Items.FindByValue(value.CATEGORY_ID.ToString()).Selected = false;
this.ddlCategory.Items.FindByValue(value.CATEGORY_ID.ToString()).Attributes.Add("disabled", "true");
this.ddlCategory.Items.FindByValue(value.CATEGORY_ID.ToString()).Attributes.Add("style", "font-weight:bold;");
foreach (var valueChild in ddl1)
{
if (valueChild.P_CATEGORY_ID == value.CATEGORY_ID)
this.ddlCategory.Items.Add(new ListItem(" " + valueChild.CATEGORY_NAME, valueChild.CATEGORY_ID.ToString()));
}
}
}
foreach (ListItem item in ddlCategory.Items)
{
item.Text = HttpUtility.HtmlDecode(item.Text);
}
}
Ur help is appreciate.Thanks
A:
Have you tried this way:
ddlCategory.Items.FindByValue("0").Attributes.Add("style", "font-weight:bolder")
MSDN has mentioned that only few style attributes are applicable for IE.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/controlscrashcourse-deriving.asp
|
[
"stackoverflow",
"0009156618.txt"
] | Q:
how to tell if user granted your permissions or not with FB.login
I saw a similar question, and it mentions about the change in December 2011, and that part was right
http://facebook.stackoverflow.com/questions/8753085/in-facebook-login-how-do-you-see-the-permissions-that-the-user-granted
but the rest of the answer is wrong
I did notice this is part of the url though
https://s-static.ak.fbcdn.net/connect/xd_proxy.php?version=3&error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.#cb= ...
A:
You will not know which permissions the user granted to your application in FB.login callback. You should query permissions connection for user object:
FB.api('/me/permissions', function(response){
if (response && response.data && response.data.length){
var permissions = response.data.shift();
if (permissions.email) {
alert('User have granted `email` permission');
}
}
});
Update:.
While it's not stated by Facebook that callback for FB.login will not include perms or scope property which was used before switch to OAuth2 this is the case! There is nothing said in current documentation about permissions passed to callback for FB.login, FB.getLoginStatus or FB.getAuthResponse.
There is also bug report about this behavior which is marked as Won't Fix
|
[
"stackoverflow",
"0000426500.txt"
] | Q:
How do I mock the Python method OptionParser.error(), which does a sys.exit()?
I'm trying to unit test some code that looks like this:
def main():
parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool')
parser.add_option('--foo', action='store', help='The foo option is self-explanatory')
options, arguments = parser.parse_args()
if not options.foo:
parser.error('--foo option is required')
print "Your foo is %s." % options.foo
return 0
if __name__ == '__main__':
sys.exit(main())
With code that looks like this:
@patch('optparse.OptionParser')
def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):
#
# setup
#
optionparser_mock = Mock()
mock_optionparser.return_value = optionparser_mock
options_stub = Mock()
options_stub.foo = None
optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments)
def parser_error_mock(message):
self.assertEquals(message, '--foo option is required')
sys.exit(2)
optionparser_mock.error = parser_error_mock
#
# exercise & verify
#
self.assertEquals(sut.main(), 2)
I'm using Michael Foord's Mock, and nose to run the tests.
When I run the test, I get:
File "/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py", line 27, in parser_error_mock
sys.exit(2)
SystemExit: 2
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test.
I can make the test pass by adding "return 2" under the parser.error() call in main() and removing the sys.exit() call from parser_error_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution?
Update: df's answer works, although the correct call is "self.assertRaises(SystemExit, sut.main)".
Which means the test passes whatever the number is in the sys.exit() in parser_error_mock(). Is there any way to test for the exit code?
BTW, the test is more robust if I add:
self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})])
at the end.
Update 2: I can test for the exit code by replacing "self.assertRaises(SystemExit, sut.main)" with:
try:
sut.main()
except SystemExit, e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, 2)
except Exception, e:
self.fail('unexpected exception: %s' % e)
else:
self.fail('SystemExit exception expected')
A:
Will this work instead of assertEquals?
self.assertRaises(SystemExit, sut.main, 2)
This should catch the SystemExit exception and prevent the script from terminating.
A:
As noted in my updates to my question, I had to modify dF's answer to:
self.assertRaises(SystemExit, sut.main)
...and I came up with a few longer snippet to test for the exit code.
[Note: I accepted my own answer, but I will delete this answer and accept dF's if he updates his.]
|
[
"stackoverflow",
"0054882971.txt"
] | Q:
Change Component's content during rendering phase when loading its model fails
I have a widget components with simple markup inheritance like so
AbstractWidget
<wicket:panel>
<wicket:child />
<div wicket:enclosure="editButton" class="widget-edit-wrapper">
<button wicket:id="editButton" type="button" class="widget-edit">
<span class="glyphicon glyphicon-cog"></span>
</button>
<div style="display:none;">
<div wicket:id="editPanel" class="widget-settings"></div>
</div>
</div>
</wicket:panel>
LabelWidget
<wicket:extend>
<div wicket:id="container" class="label-widget flex-container">
<div wicket:id="label"></div>
</div>
</wicket:extend>
Now imagine the label content is taken from a loadable detachable model and loading the model throws an Exception.
I need to show some feedback to the user on this 'broken' widget component. Is there a way to replace the whole child's content when loading its model throws an Exception?
Note that LabelWidget is just one from many AbstractWidget childs so I need to solve this in the AbstractWidget and I also need to preserve all elements from the AbstractWidget component.
A:
You can accomplish this by using a smarter model - a model that delegates to the original one and try/catches if it throws an exception. In case of an exception you will need to return an "empty" model object, where "empty" would mean different things for your different use cases.
Your smart model could implement IComponentAssignedModel so that it knows the Component it is used in. This way in the catch clause you can do component.error("..."). In AbstractWidget you should add a FeedbackPanel that will render the error message. The specialization widget, like LabelWidget, will render as "empty" (whatever this means for it) by using the fallback model.
|
[
"stackoverflow",
"0049095869.txt"
] | Q:
How can I run a Python 3 script with imports from a subfolder?
Whatever I try, since I switched to Python 3 I can run scripts with imports only from the root folder of the project, but not from subfolders. I am aware that there are lots of questions here about the error messages I get, but the proposed solutions don't work for me. Could someone please provide a sample solution for this small sample project? I am sure it would be appreciated by many.
proj
├── foofolder
│ ├── __init__.py
│ └── foofile.py
├── subfolder
│ ├── __init__.py
│ └── run.py
└── __init__.py
I define the function foofun() in foofile.py, and want to call it in run.py.
If run.py is directly in proj it works. But (just to keep things organized) I want to have it in a subfolder - which surprisingly seems impossible.
The annoying thing is that autocomplete in my IDE (PyCharm) suggests that from foofolder.foofile import foofun should work. But it does not. Nor does any other import I could imagine:
from foofolder.foofile import foofun --> ImportError: No module named 'foofolder'
from .foofolder.foofile import foofun --> SystemError: Parent module '' not loaded, cannot perform relative import (Same with two dots at the beginning.)
from proj.foofolder.foofile import foofun --> ImportError: No module named 'proj'
Not even the absolute import works. Why does it not find proj?
sys.path is: ['/parent/proj/subfolder', '/parent/env/lib/python35.zip', '/parent/env/lib/python3.5', '/parent/env/lib/python3.5/plat-x86_64-linux-gnu', '/parent/env/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/parent/env/lib/python3.5/site-packages']
I use Python 3.5.2 in a virtualenv.
Edit: I was wrong when I suggested that this problem is specific to Python 3. Problem and solution were the same when I checked in Python 2.7.12.
The solutions given by Pevogam work. The first one literally adds just '..' to 'sys.path', which describes the parent folder of wherever run.py is executed. The second explicitly adds '/parent/proj'.
A:
The quickest way I can think about doing this from the top of my head would be:
# subfolder/run.py
import sys
sys.path.append("..")
from foofolder.foofile import foofun
foofun()
Notice however that this will only work if you run run.py from its folder. A more elaborate way that does not depend on this would be
# subfolder/run.py
import sys
import os.path as o
sys.path.append(o.abspath(o.join(o.dirname(sys.modules[__name__].__file__), "..")))
from foofolder.foofile import foofun
foofun()
where you could reach the function from any location. The easiest thing to do for all such modules is to use the same pointer to the root package which in your cases happens by adding "..". You can then perform any imports from the perspective of this root package.
I tend to avoid using relative imports since they are confusing and reduce readability but hopefully some of this helps.
[*] Some IDEs may perform their own project scanning which is the reason they might still find the import as long as you run the python code within the IDE.
|
[
"stackoverflow",
"0027048293.txt"
] | Q:
timer increase upto 3 after then set to 0 for always
var times = 0;
$(selector).on('click',function(){
times += 1;
if(times > 3){
times = 0
}
console.log(times);
});
This will log:
1,2,3,0,1,2,3,0,and so on ...
But I want to get the result like this:
1,2,3,0,0,0,0, ..... , 0
It means after the number 3 the times variable should always be 0.
How should I do that?
A:
Another one:
var times = 1;
$(function(){
$("#test").on('click',function(){
console.log(times);
if(times >= 3 || times == 0){
times = -1
}
times += 1;
});
});
Working fiddle: http://jsfiddle.net/robertrozas/q1ywowm1/1/
|
[
"ux.stackexchange",
"0000108920.txt"
] | Q:
Intranet static menu: Below or above page banner?
I am currently working on a project to redesign a large organisation's intranet site. At present the project team is debating whether the site's static menu should appear below or above the banner. Just to be clear, by 'static menu' I mean this menu will appear on every page throughout the entire intranet site. It is also a hover menu in that a sub-menu appears when hovering over some of the options. The banner, however, will most likely change depending on the content being viewed.
Below are some mockups for illustrative purposes.
Option 1: Static menu appears below banner
Option 2: Static menu appears above banner
Note: Above images are mockups only.
At this point, the general consensus (in a team of five) is that Option 1 (the design with the banner above the static menu) looks better, while the other option doesn't seem to look quite right.
However, there is disagreement on whether the first option is the overall better approach from a UX perspective. The thinking goes like this:
The site is being designed for an organisation of 1,500 staff. The organisation is broken up into branches and these are also divided into many teams. As a result, there will be branch pages, team pages, and many other pages (e.g. L&D pages, News pages, etc) that will have their own banner and menu structure.
Opting for Option 1 creates the following issues:
Level 2 and below pages will be restricted to only having the option of using side navigation bars for their own menu structures (as using a top navigation bar will look strange if it's immediately below the main static menu)
Changing the banner to suit the individual page may be counter-intuitive as staff would also expect the menu below it to change (which it won't because it's a static menu across the entire site)
On the other hand, if a decision was made to keep the main banner static as well, then this reduces screen real estate for lower level pages and/or increases the amount of vertical scrolling that may be required
As branch and team pages will be maintained by their own staff who have the necessary permissions to edit those pages, it's felt that this design would make their job (and therefore their user experience) not as pleasant as it restricts how they can layout their own content
Opting for Option 2 creates the following issues:
the fact that some feel it just doesn't look as good (and for some it looks strange)
as the static menu contains a hover 'sub-menu' for some options, it's felt that these sub-menus appearing over the banner when being utilised will look odd
In summary, Option 1 is seen as looking better and more natural, while Option 2 seems to be more functional and the one that provides more flexibility. The disagreement is over which option is better overall from a UX point of view, not just for end users, but also for those with the responsibility of editing content.
Questions:
Which option provides the best user experience overall, and why?
Are there any other approaches that may better suit this environment?
A:
As i see from your image there is ITX with home icon and there is link(text) home also, i think the both buttons/links serves same purpose(correct me if i'm wrong)
so if that is case then why should there be two buttons/links .
check my image make a logo which is clickable and which serves as home click.
So in this case. Let me know if this isn't solving your problem.
|
[
"stackoverflow",
"0001096387.txt"
] | Q:
How multiple SPListItem's can share 1 workflow history?
I`v come across a need where I want to create multiple list items from within a workflow and be able to view workflow history from any of that item.
The problem context: In a recurring meeting, Agenda items are added. Some items have "open" status and some "closed". Those who have open, have the ability (and probably will) continue to be on agenda list further ocurring meetings. If user chooses to continue the item, from within a workflow I create a new item.
The result is, we have an item sequence like
Day 1: "Discuss problem A" (Parent item field value: null)
Day 2: "Discuss problem A.1" (Parent item field value: ID of Discuss problem A)
Day 3: "Discuss problem A.2" (Parent item field value: ID of Discuss problem A.1)
The thing is I want to be able to track this stuff in workflow history and be able to view it from any item. So in a workflow they should be in same state as all other items.
Any ideas on how to assign the same workflow for all those items?
A:
To the best of my knowledge, you will not be able to run ONE workflow for multiple items. Each workflow always executes in the context of one item.
One idea I had would be to use another list (referred to below as AgendaHistory) to manage the history for all agenda items. Every time an agenda item is created, if it has no parent create a new ID. If the new agenda item has a parent, use the parent's ID. The ID would be used to lookup history for all agenda items.
Then, for all agenda items you just need to link to a page that would show the history for a given thread. This page could have a List View webpart that filters on Agenda ID using a Query String Filter webpart.
For example:
User creates Agenda Item "Problem A"
Workflow determines Agenda Item "Problem A" has no parent and logs to AgendaHistory list:
AgendaID: 1, Title: The agenda item "Problem A" has been created!
Workflow Updates Agenda Item "Problem A" with a link to Pages/MyHistoryPage.aspx?AgendaID=1
User creates Agenda Item "Problem A.1"
Workflow determines Agenda Item "Problem A.1" has a parent and logs to AgendaHistory list:
AgendaID: 1, Title: The agenda item "Problem A.1" has been created!
Workflow updates Agenda Item "Problem A.1" with a link to Pages/MyHistoryPage.aspx?AgendaID=1
User creates Agenda Item "Unrelated Problem"
Workflow determines Agenda Item "Unrelated Problem" has no parent and logs to AgendaHistory list:
AgendaID: 2, Title: The agenda item "Unrelated Problem" has been created!
Workflow updates Agenda Item "Unrelated Problem" with a link to Pages/MyHistoryPage.aspx?AgendaID=2
....
|
[
"stackoverflow",
"0030806283.txt"
] | Q:
Mandrill API shows 'sent' status wrongly
I've been trying to use the Mandrill API to send transactional emails. While testing, I tried to send to an invalid email '[email protected]' and got this response
{"list":[{"email":"[email protected]","status":"sent","_id":"dab5afcb3b2643aba6abad8cb2f72e09","reject_reason":null}]}
This response is obviously misleading. However, when I logged into the web interface, the status for the said message displays as 'Soft bounced' and also gave 'Invalid Domain' as the reason, rightly so.
Can anyone explain why there is inconsistency in the status messages?
Thanks
A:
The Mandrill "Sent"-status doesn't actually mean that it is sent, only that Mandrill have received the message for processing. Extremely confusing and not very well documented. I only understood this after several emails with Mandrill support.
The only way of seeing if an email is actually sent (i.e. successfully delivered to the receiving mail server) is to see if the message has an smtp_event with a diag starting with 250.
|
[
"askubuntu",
"0001053667.txt"
] | Q:
NGINX virtual subdirectory is serving PHP files as downloads
My server answers to the following virtual subdirectory paths:
www.domain.com/us
www.domain.com/ca
www.domain.com/fr-ca
www.domain.com/spa
Each of these is an alias for www.domain.com.
If I attempt to access www.domain.com/some/virtual/path, it is correctly handed off to my index.php and processed by PHP-FPM.
If I attempt to access www.domain.com/us/some/virtual/path, it is correctly handed off to my index.php and processed by PHP-FPM
However, if I try to call www.domain.com/us/file.php, NGINX attempts to serve the file as a download. But without the virtual path, it is handled appropriately by PHP-FOM.
My virtual subdirectory paths are managed by this section in my NGINX config:
####
# Catch virtual locations: /us, /ca, /fr-ca, /spa
####
location ~ ^\/(?:(?<currentSite>us|ca|fr-ca|spa)(?:\/|$))(?<realPath>.*) {
try_files /$realPath /$realPath/;
break;
}
.
server {
listen 443 ssl;
listen 80;
listen [::]:80 default ipv6only=on;
server_name localhost;
ssl_certificate /certs/cert.pem;
ssl_certificate_key /certs/cert.key;
root ${LANDO_WEBROOT};
index index.php index.html index.htm;
######
# CloudFlare limit for headers is 8K - development should simulate this
large_client_header_buffers 4 8k;
####
# Catch virtual locations: /us, /ca, /fr-ca, /spa
####
location ~ ^\/(?:(?<currentSite>us|ca|fr-ca|spa)(?:\/|$))(?<realPath>.*) {
try_files /$realPath /$realPath/;
break;
}
####
# Manage the REAL locations
####
location /js {
index index.html
expires 100d;
add_header Pragma public;
add_header Cache-Control "public";
try_files $uri $uri/ =404;
break;
}
location /media {
index index.html
expires 100d;
add_header Pragma public;
add_header Cache-Control "public";
try_files $uri $uri/ =404;
break;
}
location /skin {
index index.html
expires 100d;
add_header Pragma public;
add_header Cache-Control "public";
try_files $uri $uri/ =404;
break;
}
location @handler {
rewrite / /index.php;
}
location / {
try_files $uri $uri/ @handler;
}
location ~ \.php$ {
# Try to load the file if requested, if not found, rewrite to @missing
# This should pass all requests through index.php
try_files $uri =404;
fastcgi_param MAGE_IS_DEVELOPER_MODE true;
fastcgi_buffers 256 500k; #Allow a greater amount of data to be included in cookies
fastcgi_buffer_size 1000k; #Allow a greater amount of data to be included in cookies
fastcgi_pass fpm:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_connect_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;
include fastcgi_params;
}
}
A:
You can use a rewrite...last to remove the language prefix from the URI, so that it can be processed correctly by the remaining locations in your configuration. In particular, .php URIs need to be processed by the location ~ \.php$ block.
For example:
location ~ ^/(?:(?<currentSite>us|ca|fr-ca|spa)(?:/|$))(?<realPath>.*) {
rewrite ^ /$realPath last;
}
Or more simply:
rewrite ^/(us|ca|fr-ca|spa)(?:/(.*))? /$1 last;
See this document for details.
|
[
"stackoverflow",
"0050667979.txt"
] | Q:
Load Image in React native from props
I'm trying to render a list of images from a base component by sending down title and image URL.
Everything works fine if I'm rendering the images like this:
<Image source={require('../assets/images/myImage.png')} />
The issue is coming when I'm trying to render the image from props:
class ListItem extends Component {
render() {
return (
<View>
<Text>{this.props.title}<Text>
<Image source={require(this.props.imageUri)} />
</View>
);
}
};
ListItem.propTypes = {
title: PropTypes.string.isRequired,
imageUri: PropTypes.string.isRequired,
};
As a result, I'm getting the next error:
calls to require expect exactly 1 string literal argument, but this
was found: require(this.props.imageUri).
I've also tried to render the images using uri
<Image source={{uri: this.props.imageUri}} />
package.js
"react": "16.3.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-27.0.0.tar.gz",
A:
If you're using remote images with uri they can be dynamic but require for local images needs to resolve the paths at build time so they can't be. Create a hash of known paths:
const imageNames = {
apple: require('./images/apple.png'),
orange: require('./images/orange.png'),
};
And refer to them by their name:
class ListItem extends Component {
render() {
return (
<View>
<Text>{this.props.title}<Text>
<Image source={imageNames[this.props.imageName]} />
</View>
);
}
};
ListItem.propTypes = {
title: PropTypes.string.isRequired,
imageName: PropTypes.oneOf(Object.keys(imageNames)),
};
// e.g.
<ListItem imageName="orange" />
|
[
"stackoverflow",
"0004647810.txt"
] | Q:
jquery select specific child
What is wrong with the below code. I am trying to loop over children of a specific id, and assigning a css class only to specific children.
var firstRC = $("#id_1").children();
for(j=0;j<firstRC.length;j++) {
if(j>5) {
$("#id_1:eq(j)").addClass("cssClass");
}
}
A:
Because the j in the jQuery selector is just a part of the string and not a variable. You'll need to create the selector string by concatenation:
var firstRC = $("#id_1").children();
for(j=0;j<firstRC.length;j++) {
if(j>5) {
$("#id_1 :eq(" + j + ")").addClass("cssClass");
}
}
Also you need a space before :eq, or you'll select the j-th element with the id id_1 and not the j-th child inside an element with id_1.
However you are doing it far to complicated. jQuery has a gt selector allowing you to select all elements *g*reater *t*han a specific index:
$("#id_1 :gt(5)").addClass("cssClass");
If you do need to loop over several elements you should ccheck out jQuery's each method, that is much better easier to use than a for loop. Inside the each loop, this refers to the current element.
Example:
$("#id_1").children().each(function(index) {
if (index > 5)
$(this).addClass("cssClass");
});
|
[
"stackoverflow",
"0012508932.txt"
] | Q:
How to get exact number of array elements(members)in PHP?
Say I have an array like this:
array('a string', 23, array(array('key'=>'value'), 67, 'another string'), 'something else')
and I want to know how many values my array has, excluding arrays that are member of the main array. How? (The expected result is 6)
Foreach loop is not suitable because of the problem itself - unknown depth of array.
Does anyone know how to implement this?
A:
You could use array_walk_recursive.
$count = 0;
array_walk_recursive($arr, function($var) use (&$count) {
$count++;
});
echo $count;
The working demo.
|
[
"dba.stackexchange",
"0000004154.txt"
] | Q:
Will the transaction log shrink automagically in SQL Server?
When SQL Server database in a SIMPLE mode, you don't have to care about the transaction log bakcups. But in a SIMPLE mode, the transaction log seems to grow as it does in FULL mode. Does is truncate automagically at some time point? Or do I have to truncate/shrink it manually?
A:
It will truncate automatically but that is very different to shrink. Truncation reclaims log space for re-use, shrinking physically reduces the file size to release space back to the OS. If your log has grown to its current size its likely that it will grow again if you shrink it.
I'd suggest getting a handle on what typical and maximum log usage is for your system. The query below (not mine, boosted from Glen Berrys DMV scripts) could be run manually or you could capture the output to a table via an agent job. If you log it to a table for a week or so you'll get a picture of typical usage and more importantly, when a process is causing the log to grow beyond what you expect.
SELECT
db.[name] AS [Database Name]
, db.recovery_model_desc AS [Recovery Model]
, db.log_reuse_wait_desc AS [Log Reuse Wait Description]
, ls.cntr_value AS [Log Size (KB)]
, lu.cntr_value AS [Log Used (KB)]
, CAST(
CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)
AS DECIMAL(18,2)
) * 100 AS [Log Used %]
, db.[compatibility_level] AS [DB Compatibility Level]
, db.page_verify_option_desc AS [Page Verify Option]
, db.is_auto_create_stats_on, db.is_auto_update_stats_on
, db.is_auto_update_stats_async_on, db.is_parameterization_forced
, db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on
FROM sys.databases AS db
INNER JOIN sys.dm_os_performance_counters AS lu
ON db.name = lu.instance_name
INNER JOIN sys.dm_os_performance_counters AS ls
ON db.name = ls.instance_name
WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%'
AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
AND ls.cntr_value > 0
OPTION (RECOMPILE);
Transaction Log Truncation describes both the when and why log truncation occurs.
If log records were never deleted from the transaction log, it would
eventually fill all the disk space that is available to the physical
log files. Log truncation automatically frees space in the logical log
for reuse by the transaction log.
Factors That Can Delay Log Truncation is a useful reference for understanding why your log may fail to truncate and therefore grow larger than expected.
A:
No and no
it won't shrink or truncate (in the physical LDF sense, it will do logically)
it needs to be the size it is so you don't shrink it
If you shrink it, it will grow again and you'll have a fragmented file
|
[
"stackoverflow",
"0020452372.txt"
] | Q:
Set the default DateTimeOffset value?
I have the following model class for entity framework code-first. I want to set the default value current time for CreateTime when creating database table. However, the following code cannot be compiled because
The type 'System.DateTimeOffset' cannot be declared const
Is it a better way to set default value for DateTimeOffset?
public class MyClass
{
public int Id { get; set; }
public string Title { get; set; }
[DefaultValue(now)]
public DateTimeOffset CreateTime
{
get { return _createTime; }
set { _createTime = value; }
}
private const DateTimeOffset now = DateTimeOffset.Now;
private DateTimeOffset _createTime = now;
}
A:
I think the best way for doing what you need is to override SaveChanges method in your DbContext.
public class MyDbContext : DbContext
{
public override int SaveChanges()
{
foreach (var entry in this.ChangeTracker.Entries<MyClass>().Where(x => x.State == EntityState.Added))
{
entry.Entity.CreateTime = DateTimeOffset.Now;
}
return base.SaveChanges();
}
}
|
[
"workplace.stackexchange",
"0000036705.txt"
] | Q:
How to handle two job offers professionally
I have received two offers, both verbal awaiting specific details about pay etc. I have a clear preference for one of them but they have been quite slow in the process, both jobs are through headhunters. How do I inform the preferred headhunter of my other offer so they can tell the company speed up the process, I don't want to accept the other offer and then back out later, but I'm worried I may have to end up doing that. Any other suggestions how to handle the situation? The other headhunter is saying that if I accept their verbal offer, I need to withdraw all my other offers/interviews, but what happens if it falls through. How can I delay this or should I, awaiting for my preferred offer?
A:
Any other suggestions how to handle the situation?
I would immediately notify both headhunters that you have other offers, and would like their offers in writing as quickly as possible so you can make your final decision.
Prepare yourself to make a quick decision, once you have formal offers. Think through the both situations ahead of time, get whatever other information you need to make your decision (benefits information, etc as suggested by @David), as you may not have a chance to hold off one position in hopes the other comes through.
I would never advise someone to accept one position with the intent of quickly backing out if the preferred position comes through. I think that approach lacks professionalism, and can ruin a reputation.
A:
You are in an enviable position.
Since they haven't moved quickly, you are under no obligation to move quickly yourself. As such, you have time to "ponder" both offers, at least as far as they are concerned.
I would tell them both that you are waiting on another offer before making a decision. That typically motivates people to move faster because most people will take the first job that comes along of the two.
If the offer comes for the job you don't prefer first, tell the one you do get the offer from that you'll make the decision in 24 or 48 hours and then call the one you do want more and give them a chance to counter it and with a time limit.
|
[
"stackoverflow",
"0035040737.txt"
] | Q:
Parse json to listview in qml
I'm writing a small application in qml which shows weather details in listview. I can't get any information on how to parse this complex json. I'm trying to parse it in qml. This is my json:
{
"coord":{
"lon":-0.13,
"lat":51.51
},
"weather":[
{
"id":520,
"main":"Rain",
"description":"light intensity shower rain",
"icon":"09d"
},
{
"id":310,
"main":"Drizzle",
"description":"light intensity drizzle rain",
"icon":"09d"
}
],
"base":"cmc stations",
"main":{
"temp":285.33,
"pressure":1006,
"humidity":82,
"temp_min":284.15,
"temp_max":286.15
},
"wind":{
"speed":7.7,
"deg":210,
"gust":12.9
},
"rain":{
"1h":1.4
},
"clouds":{
"all":75
},
"dt":1453904502,
"sys":{
"type":1,
"id":5091,
"message":0.0047,
"country":"GB",
"sunrise":1453880766,
"sunset":1453912863
},
"id":2643743,
"name":"London",
"cod":200
}
I tried this code but it's not working. In this code I send http request, try to parse json and show it listview.
import QtQuick 2.0
Rectangle {
id: main
width: 320
height: 640
color: 'skyblue'
ListModel { id: listModelJson }
Rectangle {
height: parent.height
width: parent.width
ListView {
id: listViewJson
x: 0
y: 0
width: 600
height: 592
delegate: Rectangle {
width: parent.width
height: 70
}
model: listModelJson
}
}
function getCityName() {
var request = new XMLHttpRequest()
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=44db6a862fba0b067b1930da0d769e98', true);
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status && request.status === 200) {
console.log("response", request.responseText)
var result = JSON.parse(request.responseText)
for (var i in result) {
listModelJson.append({
"name" : result[i].name,
"cod" : result[i].cod
});
}
// main.cityName = result.response
} else {
console.log("HTTP:", request.status, request.statusText)
}
}
}
request.send()
}
Component.onCompleted: {
getCityName()
}
}
Can you show me the way we can parse this json?
A:
Found this question by google and get it done with the Documentation from ListModel QML Element.
Maybe somebody else finds this useful:
Code:
import QtQuick 2.0
Rectangle {
width: 400
height: 200
ListModel {
id: cityModel
ListElement {
name: "Static Sunny City"
temp: 31.95
attributes: [
ListElement { description: "Tropical" },
ListElement { description: "Cloudless" }
]
}
}
Component {
id: cityDelegate
Row {
spacing: 10
Text { text: name }
Text { text: temp + "°C" }
}
}
ListView {
anchors.fill: parent
model: cityModel
delegate: cityDelegate
}
Component.onCompleted: {
cityModel.append({"name": "Append Cold City", "temp": 5.95})
getCityJSON()
}
function getCityJSON() {
var request = new XMLHttpRequest()
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=44db6a862fba0b067b1930da0d769e98', true);
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status && request.status === 200) {
console.log("response", request.responseText)
var result = JSON.parse(request.responseText)
cityModel.append({
"name": result.name + " " + Date(result.dt * 1000),
"temp": result.main.temp
})
} else {
console.log("HTTP:", request.status, request.statusText)
}
}
}
request.send()
}
}
|
[
"stackoverflow",
"0048452161.txt"
] | Q:
JButtons cutoff on bottom of window
I've been learning how to make GUIs in Java, and as part of an assignment, we're required to have two rows of buttons, one above the other. I have all of the buttons, but the bottom ones are being cutoff about halfway. I cannot figure out how to get them to display fully. I've tried adjusting the Y-size of the window, but they still remain cutoff. Does anyone have any idea on how I can get the bottom three buttons to fully display?
Image of what's happening
The relevant code
JPanel rightA = new JPanel();
JPanel bottomB = new JPanel();
JPanel bottomB2 = new JPanel();
JLabel jlName = new JLabel("Item Name: ");
JLabel jlNum = new JLabel("Number of: ");
JLabel jlCost = new JLabel("Cost: ");
JLabel jlOwed = new JLabel("Amount Owed: ");
JButton jbCalculate = new JButton("Calculate");
JButton jbSave = new JButton("Save");
JButton jbClear = new JButton("Clear");
JButton jbExit = new JButton("Exit");
JButton jbLoad = new JButton("Load");
JButton jbPrev = new JButton("<Prev");
JButton jbNext = new JButton("Next>");
this.setTitle("Items Order Calculator");
this.setMinimumSize(new Dimension(400, 200));
rightA.add(jlName);
rightA.add(jtfName);
rightA.add(jlNum);
rightA.add(jtfNum);
rightA.add(jlCost);
rightA.add(jtfCost);
rightA.add(jlOwed);
rightA.add(jtfOwed);
bottomB.add(jbCalculate);
bottomB.add(jbSave);
bottomB.add(jbClear);
bottomB.add(jbExit);
bottomB2.add(jbLoad);
bottomB2.add(jbPrev);
bottomB2.add(jbNext);
jtfOwed.setEnabled(false);
rightA.setLayout(new GridLayout(4, 2));
this.add(rightA, BorderLayout.EAST);
bottomB.add(bottomB2);
this.add(bottomB, BorderLayout.SOUTH);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setVisible(true);
A:
I think the problem is that you are adding the bottomB2 panel into the bottomB panel and they are not communicating their preferred sizes properly.
Try instead creating another panel with border layout and add them into north and south areas of this panel. Then add this new bottom panel into your gui at south.
JPanel bottomAll = new JPanel(new BorderLayout());
bottomAll.add(bottomB, BorderLayout.NORTH);
bottomAll.add(bottomB2, BorderLayout.SOUTH);
this.add(bottomAll, BorderLayout.SOUTH);
|
[
"stackoverflow",
"0006902653.txt"
] | Q:
postsharp exception is null
I have a probleme with Postsharp.
i have this:
[Serializable]
public class MethodConnectionTracking: OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
base.OnException(args);
}
}
and i used like this. In assemblyInfo.cs:
[assembly: MethodConnectionTracking]
so, when an exception occurs in the assembly its executes OnException method. But, when i debug the method and i watch args (type: MethodExecutionArgs ) every property has a null value. args.Exception is null. And i need the exception type..
Anyone knows how can i fix this?
Thanks in advance
A:
The answer if because PostSharp sees that you are not using any of those properties so it implements optimizations to not do anything with those properties. that is why they are null when you debug. change your aspect to match the following ocde then try to debug again
[Serializable]
public class MethodConnectionTracking: OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
Exception e = args.Exception;
}
}
you can see exactly why here: http://programmersunlimited.wordpress.com/2011/08/01/postsharp-why-are-my-arguments-null/
|
[
"stackoverflow",
"0049402835.txt"
] | Q:
JodaTime allows invalid date
I expected this to throw an exception because the 1st of February 2016 is not a Friday:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("EEEE, d MMMM yyyy");
final DateTime date = formatter.parseDateTime("Friday, 1 February 2016");
System.out.println(formatter.print(date));
Instead, it printed out Friday, 5 February 2016. What am I missing here?
A:
It's explained in the doc (http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormatter.html)
Parsing builds up the resultant instant by 'setting' the value of each parsed field from largest to smallest onto an initial instant, typically 1970-01-01T00:00Z. This design means that day-of-month is set before day-of-week. As such, if both the day-of-month and day-of-week are parsed, and the day-of-week is incorrect, then the day-of-week overrides the day-of-month. This has a side effect if the input is not consistent.
|
[
"stackoverflow",
"0038856426.txt"
] | Q:
How to add a medication's therapeutic class in FHIR?
I wonder if there is a way to add a therapeutic class (see definition with code DC) to a medication?
Definition here as well:
Description: A categorization of medicinal products by their
therapeutic properties and/or main therapeutic use.
A:
There's no element for this, so you'll have to add an extension
|
[
"stackoverflow",
"0005552326.txt"
] | Q:
Spring 3 Custom Editor field replacement
Having my ValueObject
UserVO {
long id;
String username;
}
I created custom editor for parsing this object from string id#username
public class UserVOEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
Preconditions.checkArgument(text != null,"Null argument supplied when parsing UserVO");
String[] txtArray = text.split("\\#");
Preconditions.checkArgument(txtArray.length == 2, "Error parsing UserVO. Expected: id#username");
long parsedId = Long.valueOf(txtArray[0]);
String username = txtArray[1];
UserVO uvo = new UserVO();
uvo.setUsername(username);
uvo.setId(parsedId);
this.setValue(uvo);
}
@Override
public String getAsText() {
UserVO uvo = (UserVO) getValue();
return uvo.getId()+'#'+uvo.getUsername();
}
in my controller i register
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(UserVO.class, new UserVOEditor());
}
having in my model object ModelVO
ModelVO {
Set<UserVO> users = new HashSet<UserVO>();
}
after custom editor is invoked all you can see after form submission is
ModelVO {
Set<String> users (linkedHashSet)
}
so when trying to iterate
for(UserVO uvo : myModel.getUser()){ .. }
Im having classCastException .. cannot cast 1234#username (String) to UserVO ..
HOW THIS MAGIC IS POSSIBLE ?
A:
It is not magic, it is because of Generics will be only proved at compile time. So you can put every thing in a Set at runtime, no one will check if you put the correct type in the Set.
What you can try, to make spring a bit more clever, is to put the ModelVO in your command object.
<form:form action="whatEver" method="GET" modelAttribute="modelVO">
@RequestMapping(method = RequestMethod.GET)
public ModelAndView whatEver(@Valid ModelVO modelVO){
...
}
|
[
"es.stackoverflow",
"0000352722.txt"
] | Q:
Error en consumo de un Api REST en ANGULAR
Estoy comenzando en esto de implementar el backend con el frontend, tengo un error debe ser simple y no lo veo, este es mi código...
Este seria mi componente que quiero mostrar en mi servidor local: Ahi indico donde me subraya el error, y al pasar el mouse por encima, me dice: Identifier 'Reclamos' is not defined. The component declaration, template variable declarations, and element references do not contain such a member.
Y no me facilita el Quick fix.
<ul>
<li *ngFor="let r of Reclamos"> <--------(MI ERROR SE MUESTRA AHI EN LA PALABRA Reclamos)
<span>{{r.num_reclamo}}, {{r.tipo_problema}}, {{r.fecha}}</span>
</li>
</ul>
Este es mi models de los atributos:
export interface Reclamos {
num_reclamo: number;
rut_usuario: number;
tipo_problema: string;
fecha: string;
texto_reclamo: string;
estado: string;
SLA_reclamo: number;
fecha_tope: string;
}
Este es mi codigo en la parte del component.ts
import { Component, OnInit } from '@angular/core';
import { ReclamosService } from 'src/app/services/reclamos-service.service';
import { Reclamos } from 'src/models/Reclamos';
@Component({
selector: 'app-busqueda-reclamo',
templateUrl: './busqueda-reclamo.component.html',
styleUrls: ['./busqueda-reclamo.component.css']
})
export class BusquedaReclamoComponent implements OnInit {
reclamos: Reclamos[];
constructor(private reclamosService: ReclamosService) { }
ngOnInit(){
this.obtenerReclamos();
}
obtenerReclamos() {
this.reclamosService.obtenerReclamos().subscribe(reclamos => this.reclamos = reclamos);
}
}
Este seria mi servicio.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Reclamos } from 'src/models/Reclamos';
@Injectable({
providedIn: 'root'
})
export class ReclamosService {
private URL = 'localhost:8080/api'
constructor(private http: HttpClient) { }
obtenerReclamos(): Observable<Reclamos[]>{
const suffix = '/reclamos/usuario'
return this.http.get<Reclamos[]>(this.URL+suffix);
}
}
De ante mano agradezco por sus tiempo y respuestas, gracias ;).
A:
Creo que el problema puede estar en que tu variable reclamos la estas colocando con el 'r' mayuscula. Prueba colocarlo en minúscula.
<ul>
<li *ngFor="let r of reclamos">
<span>{{r.num_reclamo}}, {{r.tipo_problema}}, {{r.fecha}}</span>
</li>
</ul>
|
[
"stackoverflow",
"0035661807.txt"
] | Q:
document.getElementsByTagName not working
I would like to use document.getElementsByTagName('input')
to set as required (or unset it) for a list of inputs.
is it possible?
I've tried:
document.getElementsByTagName('input').required = false;
or (for a different purpose)
document.getElementsByTagName('input').value = ""
but it doesn't seem work.
Moreover: is it possible to catch a certain type of input (i.e. text or radio)?
Thank you!!!
ObOnKen
A:
getElementsByTagName() returns a collection of elements so you need to iterate over the collection...
var elements = document.getElementsByTagName('input');
for(var i = 0; i < elements.length; i++)
{
if(elements[i].type == "text")
{
elements[i].value = "";
}
}
|
[
"stackoverflow",
"0042290322.txt"
] | Q:
wizard using jquery eq() next and previous button
I have wizard like list with CURRENT item selected, including NEXT/PREVIOUS buttons,
On clicking buttons I am updating data attribute so I can track current.
On clicking next its working fine, looks issue with my eq() in back button
<h1 data-index="3"></h1>
<ul>
<li class="done">1</li>
<li class="done">2</li>
<li class="sel">3</li>
<li>4</li>
</ul>
<a href="javascript:;" id="back">back</a>
<a href="javascript:;" id="next">next</a>
jQuery :
let i = $('h1').data('index');
$('h1').html(i);
$('#next').on('click', function(e){
let i1 = $('h1').data('index');
if (i1 < 4) {
$('ul li').eq(i1).addClass('sel');
$('ul li').eq(i1).prevAll().addClass('done');
i1 ++;
$('h1').data('index', i1);
$('h1').html(i1);
}
});
$('#back').on('click', function(e){
let i2 = $('h1').data('index');
alert('i2 : ' + i2);
if (i2 > 1) {
i2--;
$('h1').data('index', i2);
$('h1').html(i2);
$('ul li').removeClass('sel');
$('ul li').eq(i2).addClass('sel');
$('ul li').eq(i2).nextAll().removeClass('done');
//$('ul li').eq(i2).nextAll().removeClass('done sel');
}
});
here is link for jsfiddle
https://jsfiddle.net/mawLnqq0/
A:
Your classes are conflicting in the back button,
You need to remove the done class when adding the sel class in the <li>.
Also eq() index starts from 0 , hence the (i2-1).
Try this code for the back button click
$('#back').on('click', function(e){
let i2 = $('h1').data('index');
alert('i2 : ' + i2);
if (i2 > 1) {
i2--;
$('h1').data('index', i2);
$('h1').html(i2);
$('ul li').removeClass('sel');
$('ul li').eq((i2-1)).removeClass('done').addClass('sel');
$('ul li').eq((i2-1)).nextAll().removeClass('done');
//$('ul li').eq(i2).nextAll().removeClass('done sel');
}
});
|
[
"stackoverflow",
"0009199362.txt"
] | Q:
SLF4J and logger factories
I thought SLF4J would load org.slf4j.impl.StaticLoggerBinder via reflection but looking at the code in org.slf4j.LoggerFactory, it is not the case:
StaticLoggerBinder.getSingleton().getLoggerFactory();
That might suggest that when they packaged the slf4j-api.jar, they had either slf4j-simple.jar (or slf4j-nop.jar) in the classpath, however that would result in a circular dependency as ILoggerFactory interface that the above method returns is defined in slf4j-api.jar.
So, I think when they packaged slf4j-api.jar, they had a stub implementation of StaicLoggerBinder (and other similar classes) which they would compile but then remove the .class files from the jar. Sounds a bit unkosher, doesn't it?
What kind of build tool would one use to achieve such a result? Specifically, if I am using Maven, how do I build such jars where classes produced during compile time are excluded from the artifact? There could be anonymous and other inner/nested classes being produced too, should they be removed too?
A:
Take a look at pom.xml and at the sources of slf4j-api.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
<configuration>
<tasks>
<echo>Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder</echo>
<delete dir="target/classes/org/slf4j/impl"/>
</tasks>
</configuration>
</plugin>
So, I think when they packaged slf4j-api.jar, they had a stub implementation of StaicLoggerBinder (and other similar classes) which they would compile but then remove the .class files from the jar.
That's right and it's necessary to implement static binding.
|
[
"stackoverflow",
"0019425096.txt"
] | Q:
Expandable list view setOnChildClickListener not working
I m using an expandable listview. i given setOnChildClickListener inside the onceate method,
but the setOnChildClickListener is not working, i was searching for the solution in SO but i cannot find any solution. here giving what i had done
public class MenuActivity extends Activity{
ArrayList<MyObject> CatList = new ArrayList<MyObject>();
ArrayList<Object> childItem = new ArrayList<Object>();
ExpandableListView ExList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuactivity);
ExList=(ExpandableListView) findViewById(R.id.lvMenu) ;
ExList.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
ShowItem(CatList.get(childPosition).getId());
Toast.makeText(context, ""+CatList.get(childPosition).getId(), 1).show();
// TODO Auto-generated method stub
return false;
}
});
}
public void ShowItem(int id)
{
// do something
}
public class ElistAdapt extends BaseExpandableListAdapter {
public ArrayList<MyObject> groupItem, tempGrpChild;
public ArrayList<Object> Childtem = new ArrayList<Object>();
public LayoutInflater minflater;
public Activity activity;
public ElistAdapt(ArrayList<MyObject> GroupList, ArrayList<Object> childItem) {
groupItem = GroupList;
this.Childtem = childItem;
}
public void setInflater(LayoutInflater mInflater, Activity act) {
this.minflater = mInflater;
activity = act;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
@Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
tempGrpChild = (ArrayList<MyObject>) Childtem.get(groupPosition);
TextView text = null;
TextView text2 = null;
if (convertView == null) {
convertView = minflater.inflate(R.layout.childrow, null);
}
text = (TextView) convertView.findViewById(R.id.textView1);
text2 = (TextView) convertView.findViewById(R.id.textView2);
text.setText(tempGrpChild.get(childPosition).getName());
text2.setText(tempGrpChild.get(childPosition).getPrice());
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return ((ArrayList<MyObject>) Childtem.get(groupPosition)).size();
}
@Override
public Object getGroup(int groupPosition) {
// return null;
return this.groupItem.get(groupPosition);
}
@Override
public int getGroupCount() {
return groupItem.size();
}
@Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
@Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
@Override
public long getGroupId(int groupPosition) {
return 0;
}
@Override
public View getGroupView(final int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grouprow, null);
}
TextView tvGroupName = (TextView) convertView.findViewById(R.id.textView1);
tvGroupName.setText(groupItem.get(groupPosition).getName());
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
please help me why setOnChildClickListener is not working
A:
In your adapter class return the true value in isChildSelectable() method.
A:
finally i made its working, i removed the clickable, focusable from the R.layout.childrow xml.
now its working fine
|
[
"stackoverflow",
"0048693986.txt"
] | Q:
Bootstrap radio buttons without plugins angular 2+
Is it possible to hide the round old school radio buttons from appearing on bootrap radio buttons? I am only using bootstrap css no jquery or other plugins.
Currently the buttons look like this
I want them to look like this
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary" [ngClass]="{'active': radioYes}">
<input type="radio" name="options" id="option1" autocomplete="off" (click)="radioYes=true" > Yes
</label>
<label class="btn btn-primary" [ngClass]="{'active': !radioYes}">
<input type="radio" name="options" id="option2" autocomplete="off"(click)="radioYes=false" > No
</label>
</div>
Using Bootstrap 4. No additional css
A:
I figured out my mistake.
In the latest version of Bootstrap (4.0.0). The div containing the buttons needs the class btn-group-toggle
Relevant discussion -- https://github.com/twbs/bootstrap/issues/25281
|
[
"stackoverflow",
"0028346928.txt"
] | Q:
Issue with a join on MySQL 5.5.32
Good morning everyone.
I am having some difficulties trying to get a query to work (to build a view on it afterwards)
My table structure is this (shortened for brevity)
SUBS: code, mag, start, end
USERS: code, email
ISSUES: mag, issue, pubdate
"subs" contains subscriptions to magazines: CODE is the company code, MAG is the identifier of the mag, START and END are the dates on which the subscription is valid.
"users" contains emails associated with the company codes (1/N)
"issues" is a list of each issue of each magazine, with its publication date
SAMPLE DATA
This Fiddle should provide you some sample data. Here's a pastebin with the create statements with sample data
WHAT I WANT TO ACHIEVE
For each user, all the subscription he/she is entitled to, with starting issue and ending issue. Speaking with column names:
USERS.email, ISSUES.mag, SUBS.start, ISSUES.issue, SUBS.end, ISSUES.issue
For the sample data I provided this should be:
[email protected],01ARS,2014-01-01,01ARS14000387,2014-03-01,01ARS14000389
WHAT I HAVE SO FAR
SELECT users.email, subs.mag, subs.start, subs.end
FROM users
LEFT JOIN subs ON users.code = subs.code
I can't get current values for the start_issue and end_issue
My, albeit limited, knowledge of sql I guess it's not enough to achieve this
Any help would be appreciated.
A:
EDITED
Try this:
SELECT t1.email, t3.mag, t2.start, t3.issue s, t2.end, t4.issue e
FROM users t1
JOIN subs t2 ON t1.code = t2.code
JOIN issues t3 ON t2.mag = t3.mag AND t2.start = t3.pubdate
JOIN issues t4 ON t2.mag = t4.mag AND t2.end = t4.pubdate;
SQL Fiddle
|
[
"stackoverflow",
"0049747771.txt"
] | Q:
jhipster --skip-server. Spring Security
I want to do front project of Jhipster.
As I see in the documentation I have to execute the command:
jhipster --skip-server
By itself it is not worth and you have to put options.
https://stackoverflow.com/questions/42720061/jhipster-generator-skip-auth-code-at-skip-server
I do not see the possible options for the "--auth" parameter, in my case for a back with Spring Security.(I only see examples for jwt)
A:
The available auth types in JHipster as of v4.14.2 and v5 are jwt, oauth2, session, and specifically for microservices, uaa. All of these use Spring Security on the backend.
jwt - JSON Web Tokens (JWT)
session - Session-based authentication
oauth2 - OAuth2 and OpenID Connect
uaa - JHipster User Account and Authentication (UAA)
See the JHipster Securing Your App documentation for a full explanation of each type.
|
[
"stackoverflow",
"0053341988.txt"
] | Q:
Proper way to state a condition trough functions
I've got a code with different functions. Inside one of them there is a condition. I have to check if this condition occur to execute another function.
What's the proper way to do that? I've tried something like this but it doesn't work
Example:
class MyClass:
def thisFunction(self):
try:
"I'm doing things"
except:
self.stop = print("That's already done!")
def thisOtherFunction(self):
"I'm doing things with things done in thisFunction"
s = MyClass()
s.thisFunction()
if self.stop == None:
s.thisOtherFunction()
else:
pass
Thanks a lot!
Update
Actually it's a lot simplier doing:
class MyClass:
def thisFunction(self):
try:
"I'm doing things"
except:
self.stop = print("That's already done!")
def thisOtherFunction(self):
try:
"I'm doing things with things done in thisFunction"
except:
pass
s = myClass()
s.thisFunction()
s.thisOtherFunction()
Thanks to Adam Smiths's example, I simply didn't think about that. Maybe it's not so much elegant, though.
Update2
Another way is to use def __init__ in this way:
class MyClass:
def __init__(self):
self.commandStop = False
def thisFunction(self):
try:
"I'm doing things"
except:
self.commandStop = True
def thisOtherFunction(self):
"I'm doing things with things done in thisFunction"
def conditionToGo(self):
if self.commandStop == False:
print("That's already done!")
else:
s.thisOtherFunction()
s = myClass()
s.thisFunction()
s.conditionToGo()
A:
I've made patterns before where I had to do a series of transforms to a value and it needs to pass a test each time. You could construct that with:
def pipeline(predicate, transformers):
def wrapped(value):
for transformer in transformers:
value = transformer(value)
if not predicate(value):
raise ValueError(f"{value} no longer satisfies the specified predicate.")
return value
return wrapped
Then, to construct an example, let's say I need to do some math on a number but ensure that the number never goes negative.
operations = [
lambda x: x+3,
lambda x: x-10,
lambda x: x+1000,
lambda x: x//2
]
job = pipeline(lambda x: x>0, operations)
job(3) # fails because the sequence goes 3 -> 6 -> (-4) -> ...
job(8) # is 500 because 8 -> 11 -> 1 -> 1001 -> 500
|
[
"stackoverflow",
"0018683361.txt"
] | Q:
play pause multiple vimeo videos
I have found a solution to starting/pausing multiple vimeo videos from seperate buttons, but I would like to use images for the play and pause buttons.
Can anyone help me ammend the code? I guess I need to replace the html button code with images and then reference them in the javascript, but I can't seem to get it to work.
Many thanks.
my html is:
<div>
<h1>Player 1</h1>
<div class="api_output"></div>
<iframe id="player_1" src="http://player.vimeo.com/video/7100569?js_api=1&js_swf_id=player_1" width="500" height="281" frameborder="0"></iframe>
<button class="simple" id="api_play">Play</button>
<button class="simple" id="api_pause">Pause</button>
</div>
</div>
<div>
<div>
<h1>Player 2</h1>
<div class="api_output"></div>
<iframe id="player_2" src="http://player.vimeo.com/video/3718294?js_api=1&js_swf_id=player_2" width="500" height="281" frameborder="0"></iframe>
<button class="simple" id="api_play">Play</button>
<button class="simple" id="api_pause">Pause</button>
</div>
</div>
The javascript is:
var VimeoEmbed = {};
VimeoEmbed.init = function(e)
{
//Listen to the load event for all the iframes on the page
$('iframe').each(function(index, iframe){
iframe.addEvent('onLoad', VimeoEmbed.vimeo_player_loaded);
});
};
VimeoEmbed.vimeo_player_loaded = function(player_id)
{
$('#'+player_id).prev('.api_output').append('VimeoEmbed.vimeo_player_loaded ' + player_id+'<br/>');
var loop = 0;
var volume = 100;
//Simple Buttons
$('#'+player_id).nextAll('button.simple').bind('click', {'player_id': player_id}, function(e){
var iframe = $('#'+e.data.player_id).get(0);
iframe.api( $(e.target).attr('id'), null );
});
//API EVENT LISTENERS
VimeoEmbed.setupAPIEventListeners($('#'+player_id).get(0));
};
//On document ready
$(document).ready(VimeoEmbed.init);
A:
I think it'll be something like this
<div>
<h1>Player 1</h1>
<div class="api_output"></div>
<iframe id="player_1" src="http://player.vimeo.com/video/7100569?js_api=1&js_swf_id=player_1" width="500" height="281" frameborder="0"></iframe>
<img class="simple" id="api_play" src="play.png">
<img class="simple" id="api_pause" src="pause.png">
<!-- ... same for player 2 -->
And in the js
VimeoEmbed.vimeo_player_loaded = function(player_id)
{
$('#'+player_id).prev('.api_output').append('VimeoEmbed.vimeo_player_loaded ' + player_id+'<br/>');
var loop = 0;
var volume = 100;
//Simple Buttons
$('#'+player_id).nextAll('img.simple').bind('click', {'player_id': player_id}, function(e){
var iframe = $('#'+e.data.player_id).get(0);
iframe.api( $(e.target).attr('id'), null );
});
//API EVENT LISTENERS
VimeoEmbed.setupAPIEventListeners($('#'+player_id).get(0));
};
|
[
"stackoverflow",
"0004225121.txt"
] | Q:
jquery validate: sum of multiple input values
I need help to create custom method to validate sum of multiple text input values.
In form I have variable number of text inputs and when submitting I need to validate that the sum of input values in same group is exactly 100.
example (second group should not validate):
<input type='text' name='g1_number1' class='group1' value='20' />
<input type='text' name='g1_number2' class='group1' value='40' />
<input type='text' name='g1_number3' class='group1' value='40' />
<input type='text' name='g2_number1' class='group2' value='20' />
<input type='text' name='g2_number2' class='group2' value='40' />
<input type='text' name='g2_number3' class='group2' value='10' />
A:
I got it working this way:
Custom validation rule:
$.validator.addMethod(
"sum",
function (value, element, params) {
var sumOfVals = 0;
var parent = $(element).parent(".parentDiv");
$(parent).find("input").each(function () {
sumOfVals = sumOfVals + parseInt($(this).val(), 10);
});
if (sumOfVals == params) return true;
return false;
},
jQuery.format("Sum must be {0}")
);
And using like this:
$(".group1").rules('add', {sum: 100});
$(".group2").rules('add', {sum: 100});
A:
var sumOfValues=0;
$(".group1").each(function(){
sumOfValues+=$(this).val();
});
if(sumOfValues==100){
}else{
}
or in plugin form
$.fn.validateValuesSum=function(value){
var sumOfValues=0;
this.each(function(){
sumOfValues+=$(this).val();
});
if(sumOfValues==value){
return true;
}
return false;
}
|
[
"mathoverflow",
"0000288514.txt"
] | Q:
Pulling Back Cohen-Macaulay Sheaves
Suppose $f:X\to Y$ is a finite morphism of varieties and $\mathcal{F}$ is a Cohen-Macaulay sheaf on $Y$. Under what conditions on $f$ is $f^*\mathcal{F}$ Cohen-Macaulay?
A:
As far as being true for the most general situation, you need: $X,Y$ to be Cohen-Macaulay, $\dim \mathcal F_x =\dim Y_x$ ($\mathcal F_x$ is maximal Cohen-Macaulay) for all $x$ in the support of $\mathcal F$, and $f$ to have finite flat dimension. (more is true with a little extra technical assumption, you need the ``Cohen-Macaulay defect" to be constant along $f$, see the last paragraph).
Then what you need follows from the two local statements about f.g modules over a local ring $R$.
1) If M is maximal CM, and N has finite projective dimension, then $Tor_i(M,N)=0$ for all $i>0$ (M, N are Tor-independent).
See: http://www.math.lsa.umich.edu/~hochster/711F06/L11.20.pdf
2) If $M,N$ are Tor-independent and $pd_RN<\infty$, we also have the depth formula:
$depth(M\otimes N) + depth(R) = depth(M)+depth(N)$
See: https://www.math.unl.edu/~siyengar2/Papers/Abform.pdf
In particular, if N is CM then $M\otimes N$ is also CM of same depth. (here we use that $R$ is CM, so $depth(R) =depth(M)$).
If you drop any condition, it is not hard to find examples to show that the statement is no longer true. On the other hand, for special $X,Y,\mathcal F$, sometimes one can say a bit more. For example, if $R$ is a complete intersection, Tor-independence forces the depth formula to hold, without knowing that $N$ has finite flat dimension.
Added in response to OP's request: By looking at the depth formula in 2), the following more technical, but general statement is true: suppose $f: R\to S$ is a finite, local map of finite flat dimension, and $dim(R)-depth(R)=dim(S)-depth(S)$. Then for a maximal CM module $M$ over $R$, $M\otimes_R S$ is (maximal) CM over $S$. This cover both cases when $R,S$ are CM ( both sides of the equality is $0$), or if $f$ is flat (both dim and depth are preserved).
|
[
"stackoverflow",
"0031993930.txt"
] | Q:
Upload Image in Database (MySql) using PHP
Kindly tell me what is the best method of storing images in database.
Storing Images into database
OR
Uploading images to a folder and save the image path into the database for extracting it for later use.
If some one provide me a demo also with a form having two input fields of text and option of attaching image also and providing sql queries for uploading the record into database will help me a lot in understanding. I have little knowledge in this field. I m in learning process. Kindly help me
A:
The most commonly used method is to save the image path to the database and the actual image to a directory. This is just a demo of what I currently use.
HTML:
<form enctype="multipart/form-data" method="post" action="">
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
PHP:
$target_dir = 'PATH/TO/SAVE/IT/TO/';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
// If Its Empty Throw Error
if (basename($_FILES["fileToUpload"]["name"]) == "") {
// Error Code Here
$uploadOk = 0;
}
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
}else{
// Throw Error Here
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
// Throw Error Here
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > $max_image_size) {
// Throw Error Here
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
// Throw Error Here
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// DB Insert HERE
}else{
// Throw Error Here
}
}
Outputting the image:
PHP:
function getUserImage() {
$uid = $_SESSION['user'];
$query = "SELECT `image` FROM `users` WHERE `id` = ?";
$params = array($uid);
$results = dataQuery($query,$params);
return $results[0]['image'];
}
HTML:
<img src="images/users/<?php echo getUserImage(); ?>" />
|
[
"stackoverflow",
"0024480092.txt"
] | Q:
Accessing Array of View Controllers on Stack in Swift
Basically I'm trying to do this in Swift
// get the Detail view controller in our UISplitViewController (nil if not in one)
id detail = self.splitViewController.viewControllers[1];
// if Detail is a UINavigationController, look at its root view controller to find it
if ([detail isKindOfClass:[UINavigationController class]]) {
detail = [((UINavigationController *)detail).viewControllers firstObject];
}
I've got as far as this;
var detail : AnyObject = self.splitViewController.viewControllers[1]
if detail.isKindOfClass(UINavigationController) {
detail = ((detail: UINavigationController).detail).
but I can't find what to do after this.
Another separate quick question. Is it considered good practice to have a lot of statements ending in as [type]. It's mainly resulting from the use of AnyObject's, like using valueForKeyPath for instance. It just seems a bit messy having it all over my code
A:
Here's a way to do that in Swift using Optional Binding:
// get the Detail view controller in our UISplitViewController (nil if not in one)
var detail = self.splitViewController.viewControllers[1];
// if Detail is a UINavigationController, look at its root view controller to find it
if let nav = detail as? UINavigationController {
detail = nav.viewControllers[0];
}
As for your question, yes its quite common to use as type all over the place in Swift when using ObjC APIs. That's a by-product of going from ObjC to the strongly-typed Swift language, it should get better when more libraries are written in Swift and less ObjC is used!
|
[
"stackoverflow",
"0004232409.txt"
] | Q:
How to solve Boost::BGL template<->class circular dependency?
I have a problem with using the adjacency-list of the Boost Graphics Library. It seems to be a circular dependency problem:
I have a typedef T of a template which uses some class A. Additionally A stores a pointer to an object of type T. Now the compiler tells me, that T does not name a type.
Here are excerptions of my more concrete files:
//graphdefinitions.hpp
#include "lane.hpp"
#include "tie.hpp"
typedef boost::adjacency_list<boost::listS, boost::listS,
boost::directedS, Tie, Lane> Map;
typedef boost::graph_traits<Map>::edge_descriptor edge_descriptor;
//lane.hpp
#include "graphdefinitions.hpp"
class Lane {
...
edge_descriptor *left, *right;
};
//tie.hpp
//no important includes here
class Tie {
...
};
How do I solve this dependency / inclusion-order problem?
ANOTHER EDIT:
I just had the idea that the type of an edge_descriptor might be a primitive one like int. That would have solved the problem because I would have been able to replace the edge_descriptors of Lane by plain int-variables and thus could have removed the inclusion of graphdefinitions.hpp inside tie.hpp. Unfortunately my idea was cra* and I have to find another solution. Edge_descriptor types seem to be there for a reason...
A:
There is a not-well-documented traits class in BGL that gives the vertex and edge descriptor types for an adjacency_list graph without needing to know the property types. It is designed for exactly the use case you have. Look in the "Associated Types" section of http://www.boost.org/doc/libs/1_45_0/libs/graph/doc/adjacency_list.html and notice that there are two definitions for vertex_descriptor and edge_descriptor; you can use the versions that come from adjacency_list_traits in the definitions of your property bundles without causing a circular definition.
A:
You have circularly included headers. Lane includes graphdefinitions, which includes lane, which includes graphdefinitions, etc. This is the cause of your problem.
Edit: I realized this was already mentioned in the OP. The solution to this problem is PIMPL.
Edit: What I would actually do is put the typedef inside the Lane class. That should solve the problem in the neatest way.
|
[
"stackoverflow",
"0048276616.txt"
] | Q:
auto correct misspelled words in a list of lists - python
I have a list of lists containing words/tokens.
Eg:- [[u'note', u'subject', u'mussage', u'aar', u'install'],[ u'accomplishment', u'survice', u'hte', u'skinn', u'damaged', u'location', u'shown']
Need a python script which auto corrects the misspelled words and provides the results as.
Eg:- [[u'note', u'subject', u'message', u'air', u'install'],[ u'accomplishment', u'service', u'the', u'skin', u'damaged', u'location', u'shown']
I have around 2 million lists each having more than 5000 words/tokens. How to do a script which completes the job in very short time
A:
You can use the autocorrect lib to accomplish your task.
from autocorrect import spell
k = [[u'note', u'subject', u'mussage', u'aar', u'install'],[ u'accomplishment', u'survice', u'hte', u'skinn', u'damaged', u'location', u'shown']]
res = [map(spell, l) for l in k]
print res
Result:
[[u'note', u'subject', u'message', u'Aar', u'install'], [u'accomplishment', u'service', u'the', u'skin', u'damaged', u'location', u'shown']]
|
[
"stackoverflow",
"0022972566.txt"
] | Q:
Git fix last commit: rebase it with previous one
I don't know exactly how to describe it in Git terms but what I do is:
I make some changes, commit it to a "Add a search box" commit
I realized I had a parenthesis missing in my code, change it, commit it as "fix"
Then git rebase -i HEAD~2:
pick 34ea25a Add a search box
f 9c4b283 fix
Save the file
And yeah, I have a nice history
But I would like to automate that, so how can I use git rebase without having to open an editor?
A:
First of all, if you know that you are going to squash your next commit when doing it, you can just use git commit --amend instead. Here's example workflow:
$ git commit -am "Add a search box"
$ vim file1.c # fix something
$ git commit --amend file1.c
Git interactive mode, as the name suggest, is designed for interactive use. You can, however, do this using GIT_SEQUENCE_EDITOR environment variable or sequence.editor config option. Both works the same - you can set them to some script that will get a standard interactive rebase file as an input. It's output will be used for actual rebase. You can see some suggestion on how to use it in this question.
|
[
"dba.stackexchange",
"0000161137.txt"
] | Q:
Group by with showing full rows in Postgresql
I have a table like below with two columns A, B:
CREATE TABLE foo AS
SELECT * FROM ( VALUES
(1,1),
(1,1),
(1,2),
(1,2)
) AS t(a,b);
I want the result like below:
A B
1 1
1 1
sum B = 2
1 2
1 2
sum B = 4
How I can do it in PostgresSQL. Thanks everyone a lot.
A:
You just want this
SELECT a,b,sum(b)
FROM foo
GROUP BY a,b;
a | b | sum
---+---+-----
1 | 2 | 4
1 | 1 | 2
If you don't want to reduce the row set, you can do this..
SELECT a,b,sum(b) OVER (PARTITION BY a,b)
FROM foo;
a | b | sum
---+---+-----
1 | 1 | 2
1 | 1 | 2
1 | 2 | 4
1 | 2 | 4
|
[
"stackoverflow",
"0053465236.txt"
] | Q:
Update Values in Database after getting success message using curl
i am getting below message after passing values in url with curl:
{"AddManifestDetails":[{"AuthKey":"Valid","ReturnMessage":"successful",}]
If ReturnMessage is successful , than i want to update values in database, i tried below code :
<?php
$data =
array (
'OrderNo' => $order_id,
'AirWayBillNO' => $resultc[0]['awb'],
);
$url = "http://114.143.206.69:803/StandardForwardStagingService.svc/AddManifestDetails";
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
$res=json_decode($curl_response);
foreach ($res->curl_response as $values)
{
if($values->ReturnMessage=='successful')
{
$usql="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress', where order_id='".$order_id."'";
$result=$db_handle->executeUpdate($usql);
echo "1";die;
}
else
{
echo $values->ReturnMessage;die;
}
}
Here is full code : https://pastebin.com/EvcEY0xp
Result :
Notice: Undefined property: stdClass::$curl_response
Warning: Invalid argument supplied for foreach()
A:
$res will already contain decoded response from curl request, which will have only 1 property - AddManifestDetails.
Try following:
<?php
$data =
array (
'OrderNo' => $order_id,
'AirWayBillNO' => $resultc[0]['awb'],
);
$url = "http://114.143.206.69:803/StandardForwardStagingService.svc/AddManifestDetails";
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
$res=json_decode($curl_response);
if($res->AddManifestDetails[0]->ReturnMessage=='successful')
{
$usql="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress' where order_id='".$order_id."'";
$result=$db_handle->executeUpdate($usql);
echo "1";
die;
}
else
{
echo $res->AddManifestDetails[0]->ReturnMessage;
die;
}
|
[
"stats.stackexchange",
"0000190548.txt"
] | Q:
Probabilities of betting odds not adding up to 1
I am currently studying logistic regression. So the Probability(p(x)) of assigning an outcome is calculated as :
$\frac{p}{1-p} = e^{\beta_0 +\beta_1X} $
Further, I read that the fraction on the left is also called odds, frequently used in betting references.
So I went to a betting website, here were the odds given by them for a football match.
Chelsea vs West Brom ( Win Draw Win : 1.5, 4, 7.5)
Now I understand that they would have used a program to come up the odds.
But I figured that using the odds, I should be able to calculate the probabilities, that their software is assigning to each of the outcome.
When doing the calculations : I got 0.4 prob of Chelseas win, 0.2 of Draw and 0.11 chance of West Brom Win.
Why is this not adding up to 1?
A:
Decimal odds can be turned into their implied probabilities via the formula: $P=1/odds$. If you do this and sum you get 1.05 so I am guessing there is a small rounding errors in the decimal odds reported.
In response to the comment below, yes I am sure since these are,decimal odds . What is missing in this formula is the overhead that a "bookie" often uses to make the odds lower.
This formula is: $odds = 1/(P + \sigma)$, If you assume that the $\sigma$ are the same you can calculate this bias, and the probability will sum to 1.
Also see this post: How to convert sport odds into percentage?
Asking essentially the same question.
|
[
"stackoverflow",
"0045543320.txt"
] | Q:
Angular2 pass html to component
I am trying to create a component which displays a code example for a given component. The component shall be passed as HTML to the code-example component and be rendered once normally but also have its code displayed below.
When trying to fetch the code from <ng-content> in ngOnInit, Angular already started rendering the component, which means that I do not get the original code between the tags.
Passing the code via input does not work out, as the components may use single and double quotes which will cause problems when binding the data.
What I also tried is passing the code escaped to the component like
<code-example>
<component></component>
</code-example>
To unescape it and render it afterwards, which did not work out for me as I had trouble adding this pre-defined element to the DOM in a way that Angular renders it as a component.
Are there any other methods of dealing with this problem that I might be missing?
A:
As @Timothy suggested you may try the <pre> tag.
If you also want to highlight the syntax of your code I can recommend a third party module called ng2-prism.
This is a library that supports multiple languages and is quite easy to use.
|
[
"workplace.stackexchange",
"0000032587.txt"
] | Q:
Is it professional to take a job offer with a competitor after receiving a promotion and a bonus?
I have been working at the same company for the last two years, and although I have generally enjoyed it, I feel that I need a new challenge. Since I was recently promoted and given a bonus for my performance, and as the company has been pivotal to my development, I still feel a strong sense of loyalty.
Today, I was offered a job at one of the company's competitors. The money is slightly better, but it would give me the opportunity to take my career further, as well as to apply my skills in a totally new environment.
I really want to take this offer, but I don't want to damage my relationship with my current employer. Is it professional to leave just after receiving more investment, or would I be burning bridges?
A:
Your company has an obligation to do what they can to retain their talent. It doesn't seem like your company really understands what you want (Maybe change for the sake of change?) or they're not capable of providing it. When things go bad for them and they have to let you go, they'll say, "It's just business: nothing personal." so you can take the same approach.
If they're going to hold bettering your career against you, you're better off taking another opportunity while you can. There's no relationship to maintain in this case.
A:
I really want to take this offer, but I don't want to damage my
relationship with my current employer. Is it professional to leave
just after receiving more investment, or would I be burning bridges?
If you hadn't yet received the promotion and bonus, would your current company feel any better about your leaving? Unless both you and they believed that this promotion+bonus was designed to keep you around for a long time, the answer is probably "No."
Things happen. Circumstances change. Opportunities for growth arise. Employers understand this.
While employers would like to keep most people around forever, most employers realize that this just doesn't happen in the real world.
If your leaving burns any bridges, it most likely won't be due solely to leaving soon after a promotion+bonus. And if you give your notice professionally, and work with them to help in the transition, they most likely won't view your leaving as less than professional.
A:
Depends on any agreements. Different companies approach maintaining their talent and intellectual property differently. Non-compete agreements and non-disclosure agreements are the territory of lawyers and outside our scope - if you have signed these, see a lawyer. Typically non-disclosure is far easier to work with as it is about sharing what you know... the only tricky area is if you are asked, after your job change, about intellectual property of your old company.
The more cogent question is the personal level. People take their work personally. Normally it's a good thing - it's what inspired dedication and camaraderie. But it can also inspire spite and vindictiveness. How it plays out in the mental processes of your bosses and colleagues is anyone's guess. Normally the amount of irritation is somewhat related to the elegance with which you leave - don't leave when it would kill a huge effort that comes due very soon, don't leave without doing appropriate closure activities with your boss, don't be so gleeful about leaving that you are hard to be around. All of that is true whether you leave for a competitor or for a new type of business. My thought is that leaving for a competitor tends to amplify negative emotions in some folks.
You didn't ask, but I'll point out, that my experience in different lines of business is that competitors in a locality often optimize for the same basic outcome, which makes the working environments more similar than different. This improves your ability to feel at home on day 1, but decreases the likelihood of a drastically new work experience.
If you are leaving because you know that you'll work on brand new technology --today-- then maybe you get the change you want... but if you are leaving because "the new company would never force me to let my skills deprecate the way my current company does" - think again, that kind of long term cultural value only exists when there's profit in the competitive space from having that value... if these two companies are competing they are optimizing for the same thing.
|
[
"stackoverflow",
"0018183191.txt"
] | Q:
iOS: Converting id to int
I have troubles converting id of an object to int (or NSINteger), so that I can use it in a loop later.
Here is the case:
// "tasks" is a mutable array
int taskNo = [[tasks indexOfObject:@"something"] integerValue];
But it results in:
Bad receiver type 'NSUInteger' (aka 'unsigned int')
I found a similar thread with code similar to what I have above, but unfortunately it didn't work for me. I guess I must be missing something simple.
Thanks a lot!
A:
int taskNo = (int)[tasks indexOfObject:@"something"];
|
[
"stackoverflow",
"0053758861.txt"
] | Q:
Generating a Fixed alpha + sequential numeric values in python
I am trying to workout a method where in my models would have a field that has a structure like: "ITEM1", where in the numeric part would increase sequentially and be unique eg: "ITEM2", "ITEM3", and so on. I am not sure how to achieve this. Please point me in the right direction.
Thanks in Advance.
A:
For default Django models use AutoField as id. It's autoincremented. And you can write a property for your model to return the result you are expecting:
class MyModel(models.Model):
@property
def item_name(self):
return f'ITEM{self.id}'
my_model_instance1 = Model.objects.create()
my_model_instalce1.id = 1
my_model_instance1.item_name = 'ITEM1'
my_model_instance2 = Model.objects.create()
my_model_instalce2.id = 2
my_model_instance2.item_name = 'ITEM2'
I think it's redundant to store it in DB, but if you want you can do it with:
class MyModel(models.Model):
item = models.CharField(max_length=255)
def item_name(self):
return f'ITEM{self.id}'
def save(self, *args, **kwargs):
if not self.item:
self.item = self.item_name()
super(MyModel, self).save(*args, **kwargs)
|
[
"stackoverflow",
"0034848535.txt"
] | Q:
how to add image in a static cell of a table view programmatically
I have added an image view in one of the image view.I could have use Attributes inspector and then change the image property but i want to do it programmatically.
So far this is what i have done and get the following error
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'unable to dequeue a cell
with identifier account_cell - must register a nib or a class for the
identifier or connect a prototype cell in a storyboard
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell! = UITableViewCell()
if indexPath.section == 0{
if indexPath.row == 0{
cell = tableView.dequeueReusableCellWithIdentifier("account_cell", forIndexPath: indexPath)
if let AccountImage = cell.viewWithTag(100) as? UIImageView{
AccountImage.image = UIImage(named: "Friend_g")?.imageWithRenderingMode(.AlwaysOriginal)
}
}
}
print("\(indexPath)")
return cell
}
Can someone give me a beginners guide how can i achieve it programmatically.Any help would be appreciated.Thanks in advance.
A:
You don't need to use cellForRowAtIndexPath for assign image in your cell because you cells are statics.
One easy way to assign image into static cell is just create IBOutlet of that imageView this way:
@IBOutlet weak var UserImage: UIImageView!
After that assign image to UserImage in your viewDidLoad method this way:
override func viewDidLoad() {
UserImage.image = UIImage(named: "Friends_g")
self.tableView.separatorColor = UIColor.clearColor()
}
And result will be:
|
[
"stackoverflow",
"0030233813.txt"
] | Q:
Partially hiding an email address with PHP regex
I have found two topics which at first appear to answer my query but they only seem to get me part-way to a solution. Using them I have got to where I am. So it's not a duplicate!
I want to replace all but the first character in the name part and domain part of an email address with an asterisk:
eg
g******@g****.com or g******@g****.co.uk
code:
$email2 = preg_replace('/(?<=.).(?=.*@)/', '*', $email);
$email3 = preg_replace('/(?<=@.)[a-zA-Z0-9-]*(?=(?:[.]|$))/', '*', $email2);
which is almost there but gives me g******@g*.com rather than g******@g*****.com
Can anyone help me with the regex please?
A:
You can use:
$email = preg_replace('/(?:^|@).\K|\.[^@]*$(*SKIP)(*F)|.(?=.*?\.)/', '*', $email);
RegEx Demo
This will turn [email protected] into g*****@g*****.com and
[email protected] will become m*******@g*****.co.uk
and [email protected] into t*********@g*****.com
|
[
"stackoverflow",
"0001387983.txt"
] | Q:
Not a valid Office Add In
I developed a new Office 2007 addin using VS 2008 and VSTO. after this I go to
Office->Excel Options->AddIns->COM AddIns and GO... If I select the .dll which I ve created I get the error
'<path>' is not a valid Office Add In.
If I run it using the Visual Studio 2008 at my development machine, it works fine and I see the add-in.
I searched so many posts but didn't get a solution.
A:
Excel kept rejecting the Add-In, so the solution for me was doing it directly via the registry.
Save the below text as a .reg file, replace the Manifest path and FriendlyName to suit your PROJECT and double click the reg file to add the key to the Registry.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Office\Excel\Addins\PROJECTExcelAddIn]
"Manifest"="file:///C:\\TFS\\Pg.PROJECT\\PROJECTExcelAddIn\\Src\\PROJECTExcelAddIn\\PROJECTExcelAddIn\\bin\\Debug\\PROJECTExcelAddIn.vsto"
"FriendlyName"="PROJECTExcelAddIn"
"LoadBehavior"=dword:00000003
"Description"="PROJECTExcelAddIn - Excel add-in for PROJECT."
A:
VSTO does not create COM Addins. You will need to install your add-in on non-development machines. The article Adding the Office Primary Interop Assemblies as a Prerequisite in your ClickOnce installer at http://blogs.msdn.com/vsto/archive/2008/05/08/adding-the-office-primary-interop-assemblies-as-a-prerequisite-in-your-clickonce-installer-mary-lee.aspx will get you started.
|
[
"stackoverflow",
"0000929996.txt"
] | Q:
Should PHP 'Notices' be reported and fixed?
I recently switched to a new setup that is reporting PHP Notices; my code has worked fine without these notices being fixed, but I am wondering if it makes sense to fix every one and leave them reported or just ignore them and turn notice reporting off.
What are some different opinions on this? Are there any best practices associated with notices?
A:
Errors are errors. They have to be fixed before your code works.
Warnings are warnings. They warn you that what you're doing is probably a bad idea, even if it works (or seems to work) for you at the moment. So they too should probably be fixed.
Notices are notices. They should be noticed. Hence the name. It may not be a problem that your code generates some, but it's something you should examine and judge on a case-by-case basis.
And of course, it is much easier to notice notices if you don't get 400 of them. So there's a big benefit to trying to eliminate them. It makes the ones you haven't yet noticed become more noticeable.
A:
Yes, I would eliminate notices from any PHP code I write, even if it's just turning off the specific notice ID once I've investigated all instances of it. Notices (i.e. undefined index, initialised variable) very often indicate a situation you've forgotten to anticipate. You should investigate each one, eliminate the real problems, then possibly suppress the others (with a comment stating why).
The PHP manual itself states "NOTICE messages will warn you about bad style", so I guess the official "best practice" would be pretty much what I outlined. Follow good style, unless you have a valid reason not to.
A:
It depends on which notices-- most notices are evidence of bad code smells-- undefined array indices etc. If you do suppress a notice, leave a comment next to it indicating why you think it should be suppressed.
PHP.net Says:
Note: Enabling E_NOTICE during
development has some benefits. For
debugging purposes: NOTICE messages
will warn you about possible bugs in
your code. For example, use of
unassigned values is warned. It is
extremely useful to find typos and to
save time for debugging. NOTICE
messages will warn you about bad
style. For example, $arr[item] is
better to be written as $arr['item']
since PHP tries to treat "item" as
constant. If it is not a constant, PHP
assumes it is a string index for the
array.
I would treat every notice as a free opportunity to improve your code. :)
|
[
"stackoverflow",
"0002174568.txt"
] | Q:
org.hibernate.MappingException using annotations
I am using JPA annotations for these two classes:
@Entity
@RooJavaBean
@RooToString
@RooEntity
@MappedSuperclass
public abstract class BaseEntity {
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = "S-")
private Calendar created;
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = "S-")
private Calendar updated;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Version
@Column(name = "version")
protected Integer version;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@PrePersist
protected void onCreate() {
created = Calendar.getInstance();
}
@PreUpdate
protected void onUpdate() {
updated = Calendar.getInstance();
}
}
@Entity
@RooJavaBean
@RooToString
@RooEntity
public class Event extends BaseEntity {
private Score challenger;
private Score defender;
...
}
@Entity
@RooJavaBean
@RooToString
@RooEntity
public class Score extends BaseEntity {
@ManyToOne
private Team team;
private Event event;
private Integer score;
private Boolean accepted;
}
I get an exception though:
Caused by: org.hibernate.MappingException: Could not determine type for: edu.unlv.cs.ladders.entities.Score, at table: event, for columns: [org.hibernate.mapping.Column(challenger)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:269)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253)
at org.hibernate.mapping.Property.isValid(Property.java:185)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:440)
at org.hibernate.mapping.RootClass.validate(RootClass.java:192)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1108)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1293)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
Does this have to do with having two separate fields that access the same class? Do I have to be more descriptive and specify column names or something?
A:
You need to annotate the Score properties with ManyToOneor OneToOne.
|
[
"stackoverflow",
"0017366886.txt"
] | Q:
Refreshing a drop-down list after adding a new item
I'm new to Vaadin and i want to implement this : a A drop-down list containing file names for single selection. and an upload file button , after uploading a file the file name is added to the drop-down list :
List <String> fileDirList = Utilities.getDirectoryList("/home/amira/runtime/uploads/report");
// Create a selection component
Select select = new Select ("Select file");
for (String fileName : fileDirList) {
select.addItem(fileName);
}
public void uploadSucceeded(SucceededEvent event) {
String userHome = System.getProperty( "user.home" );
String filename = event.getFilename();
// Open the file for writing.
file = new File(userHome+"/runtime/uploads/report/"+filename);
String fileName = filename.substring(0,filename.length()-4 );
fileDirList.add(fileName);
}
};
The problem that the drop-list is not updated after uploading the file and adding its name in the fileDirList .
So how to refresh it
A:
When you add an object to your fileDirList the select component doesn't recognize this, because there is no connection between them.
You could create a method which adds the filename to the select component and to the list:
private void addFilename(String sFilename) {
fileDirList.add(sFilename);
select.addItem(sFilename);
}
Invoke this method in your upload code.
|
[
"stackoverflow",
"0029429863.txt"
] | Q:
Why is createBackgroundSubtractorGMG considered obsolete, and how can I use it
I am rather new to OpenCV and image processing in general. I am looking into background subtraction to facilitate motion tracking (people counting). Looking at the openCV documentation on background subtracting, GMG gives rather nice results. Also when looking at a video comparing the methods, I feel that GMG gives the best results, at least for my purpose.
I installed the latest version of opencv to use with python3 thus:
git clone --depth=1 https://github.com/Itseez/opencv.git
cd opencv
mkdir build
cd build
cmake -DBUILD_opencv_python3=YES -DBUILD_opencv_python2=NO -DINSTALL_PYTHON_EXAMPLES=YES -DPYTHON3_EXECUTABLE=/usr/local/bin/python3 -DPYTHON3_INCLUDE_DIR=/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/include/python3.4m -DPYTHON3_LIBRARY=/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/libpython3.4.dylib -DPYTHON3_NUMPY_INCLUDE_DIRS=/usr/local/lib/python3.4/site-packages/numpy/core/include/ -DPYTHON3_PACKAGES_PATH=/usr/local/lib/python3.4/site-packages/ ..
make -j8
make install
python3 -c "import cv2; print(cv2.__version__)"
the last line tells me I'm now running 3.0.0-dev. According to this question, cv2.createBackgroundSubtractorGMG ought to be available in this version, however it's not; and indeed, it seems to have been moved to obsolete in opencv master.
Interestingly enough, in my own tests the current (3.0.0-dev) versions of createBackgroundSubtractorKNN and createBackgroundSubtractorMOG2 work much better than the ones I tested before (MOG and MOG2) in opencv2. So possibly the GMG algorithm got moved into those. Or, if not, why is the GMG version considered obsolete now? And how can I get the obsolete version to work (on python3), to compare the results?
A:
I don't think it is obsolete... it was just moved to the contrib repository. You have to install it with OpenCV and then it is available under cv2.bgsegm. Follow the link for build instructions.
|
[
"stackoverflow",
"0003191199.txt"
] | Q:
Are there any jquery features to query multi-dimensional arrays in a similar fashion to the DOM?
What the question says...
Does jQuery have any methods that will allow you to query a mult-dimensional array of objects in a similar fashion as it does with the DOM.
So for instance, get me a list of objects contained within a multi-dimensional array having some matching property value - for instance where StartOfPeriod greater than a specified date or where name == "Ben Alabaster"
I'd like to avoid re-inventing the wheel if there's something already out there.
A:
You can't use selector syntax, but jQuery comes with $.grep and $.inArray, which can be useful for this. grep returns a new array of elements that match a predicate. inArray returns the index of the first matching element, or -1. For instance:
var matches = $.grep(array, function(el){
return el.StartOfPeriod > 2000;
});
These are similar to the standard ECMAScript methods, Array.filter (simimlar to grep) and Array.indexOf (similar to inArray); jQuery actually uses Array.indexOf where available. There are also other useful ECMAScript methods, such as Array.every (all elements matching) and Array.some (at least one matching). MDC has code you can add to your project so these work in browsers that don't have native implementations.
|
[
"stackoverflow",
"0049138462.txt"
] | Q:
Calendar in python/django
I am working on a website with weekly votations, but only the first three weeks of the month, so in each instance I have a start_date and end_date field.
I'd like to know if there's a way to automitically create these instances based on the current date, for instance:
Today it is 6 of March, and votations end tomorrow, so a function should be run (tmrw) that, taking into account this month calendar, would fill in the appropiate dates for the next votations. What calendar do you recommend me, and how shoul I do it?
(Never mind the automatically run part, I'll go with celery).
Thanks!
A:
I am not sure what your problem is and I don't know what votations are. But as a general direction of thinking: there is timeboard library that can generate rule-based schedules (calendars) and do calculations over them (DISCLAIMER: I am the author).
The code below designates, for every month of 2018, the days of the first three weeks of the month as 'on-duty' (i.e. 'active', 'usable') and the rest as 'off-duty':
>>> import timeboard as tb
>>> weekly = tb.Organizer(marker='W', structure=[[1],[1],[1],[0],[0],[0]])
>>> monthly = tb.Organizer(marker='M', structure=[weekly])
>>> clnd = tb.Timeboard(base_unit_freq='D',
... start='01 Jan 2018', end='31 Dec 2018',
... layout=monthly)
For example, in March 2018, the days from Thursday, 1st, through Sunday, 18th, are marked 'on-duty', and the days 19-31 are marked 'off-duty'.
Now you can move along the calendar picking only on-duty days. For example, adding 1 to March, 17 gives you March 18:
>>> (clnd('17 Mar 2018') + 1).to_timestamp()
Timestamp('2018-03-18 00:00:00')
However, adding 2 carries you over to April 1, as March 19 is NOT within the first 3 weeks of March:
>>> (clnd('17 Mar 2018') + 2).to_timestamp()
Timestamp('2018-04-01 00:00:00')
|
[
"stackoverflow",
"0041417199.txt"
] | Q:
MySQL PHPMyAdmin - Routine error
Using PHPMyAdmin and MySQL.
I'm trying to add a routine.
BEGIN
DECLARE cursor_ID INT;
DECLARE cursor_VAL VARCHAR;
DECLARE done INT DEFAULT FALSE;
DECLARE cursor_i CURSOR FOR SELECT ca.apprentice_id, c.courseNumber, c.level FROM tblcourseassignments ca LEFT JOIN tblcourses c ON ca.course_id = c.id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE varc1 INT DEFAULT 0;
DECLARE varc2 INT DEFAULT 0;
DECLARE varc3 INT DEFAULT 0;
DECLARE gradeCount INT;
OPEN cursor_i;
read_loop: LOOP
FETCH cursor_i INTO varc1, varc2;
SELECT COUNT(id) INTO gradeCount FROM tblapprenticegrades WHERE apprentice_id = varc1 and course_id = varc2;
if gradeCount = 0 then
INSERT INTO tblapprenticegrades(apprentice_id, course_id, phase) VALUES (varc1, varc2, varc3);
end if
IF done THEN
LEAVE read_loop;
END IF;
--queries which couldnt be made into set based queries go here---
END LOOP;
CLOSE cursor_i;
END;
But I keep on getting this error:
MySQL said: #1064 - You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '; DECLARE done INT DEFAULT FALSE; DECLARE cursor_i
CURSOR FOR SELECT ca.ap' at line 3
A:
Please find the fixes done in your code.
Varchar needs length to be specified.
Cursor and handler declarations must at the end of the declarations
Small syntax errors.
BEGIN
DECLARE cursor_ID INT;
DECLARE cursor_VAL VARCHAR(100); /* Varchar length */
DECLARE done INT DEFAULT FALSE;
DECLARE varc1 INT DEFAULT 0;
DECLARE varc2 INT DEFAULT 0;
DECLARE varc3 INT DEFAULT 0;
DECLARE gradeCount INT;
/* cursor and handler declaration at the end of declarations */
DECLARE cursor_i CURSOR FOR SELECT ca.apprentice_id, c.courseNumber, c.`level` FROM tblcourseassignments ca LEFT JOIN tblcourses c ON ca.course_id = c.id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cursor_i;
read_loop: LOOP
FETCH cursor_i INTO varc1, varc2;
SELECT COUNT(id) INTO gradeCount FROM tblapprenticegrades WHERE apprentice_id = varc1 and course_id = varc2;
if gradeCount = 0 then
INSERT INTO tblapprenticegrades(apprentice_id, course_id, phase) VALUES (varc1, varc2, varc3);
end if; /* semicolon here */
IF done THEN
LEAVE read_loop;
END IF;
--queries which couldnt be made into set based queries go here---
END LOOP;
CLOSE cursor_i;
END
|
[
"mathoverflow",
"0000000013.txt"
] | Q:
Learning about Lie groups
Can someone suggest a good book for teaching myself about Lie groups? I study algebraic geometry and commutative algebra, and I like lots of examples. Thanks.
A:
For someone with algebraic geometry background, I would heartily recommend Procesi's Lie groups: An approach through invariants and representations. It is masterfully written, with a lot of explicit results, and covers a lot more ground than Fulton and Harris. If you like "theory through exercises" approach then Vinberg and Onishchik, Lie groups and algebraic groups is very good (the Russian title included the word "seminar" that disappeared in translation). However, if you want to learn about the "real" side of Lie groups, both in linear and abstract manifold setting, my favorite is Godement's "Introduction à la théorie des groupes de Lie".
Several of the books mentioned in other answers are devoted mostly or entirely to Lie algebras and their representations, rather than Lie groups. Here are more comments on the Lie group books that I am familiar with. If you aren't put off by a bit archaic notation and language, vol 1 of Chevalley's Lie groups is still good. I've taught a course using the 1st edition of Rossmann's book, and while I like his explicit approach, it was a real nightmare to use due to an unconscionable number of errors. In stark contrast with Complex semisimple Lie algebras by Serre, his Lie groups, just like Bourbaki's, is ultra dry. Knapp's Lie groups: beyond the introduction contains a wealth of material about semisimple groups, but it's definitely not a first course ("The main prerequisite is some degree of familiarity with elementary Lie theory", xvii), and unlike Procesi or Chevalley, the writing style is not crisp. An earlier and more focused book with similar goals is Goto and Grosshans, Semisimple Lie algebras (don't be fooled by the title, there are groups in there!).
A:
There's also Fulton & Harris "Representation Theory" (a Springer GTM), which largely focusses on the representation theory of Lie algebras. Everything is developed via examples, so it works carefully through $sl_2$, $sl_3$ and $sl_4$ before tackling $sl_n$. By the time you get to the end, you've covered a lot, but might want to look elsewhere to see the "uniform statements". An excellent book.
A:
Brian Hall's "Lie Groups, Lie Algebras and Representations: An Elementary Introduction" specializes to matrix Lie groups, so it makes for an accessible introduction. Like Fulton & Harris, it's got plenty of worked examples. It also has some stuff about Verma modules that's not in Fulton & Harris. I think it'd be a great book for a first course.
Knapp's "Lie Groups: Beyond an Introduction" might be good for a second course (it has more of the "uniform statements" Scott mentioned) and is handy to have around as a reference. It has an appendix with historical notes and a ton of suggestions for further reading. It also has a lot more on Lie groups themselves than most books do.
|
[
"stackoverflow",
"0009191450.txt"
] | Q:
Where to store DbContext in a asp.net application?
I think I'm facing an architecture problem I can solve:
I'm developing a web applicationusing entity framework code first (v4.3 beta1).
Also, there are a few web services published.
In a separate Class Library, I have the DbContext and al, the entities. This library is referenced by the web application, obviuously.
In the "Data" library, I have a static property to hold de context:
namespace MMOrpheus.Lib
{
public class Context
{
public static MMOrpheusDB MMO
{
get
{
if (HttpContext.Current != null && HttpContext.Current.Session["MMOEntities"] == null)
{
HttpContext.Current.Session["MMOEntities"] = new MMOrpheusDB();
}
return HttpContext.Current.Session["MMOEntities"] as MMOrpheusDB;
}
set
{
if (HttpContext.Current != null)
HttpContext.Current.Session["MMOEntities"] = value;
}
}
}
}
MMOrpheusDB inherit from DbContext.
So the problem is I someway feel this is not right. Among other things, I don't think this Context class should be using System.Web!
Any suggestions on how to organize this project?
A:
The answer to your question is not a simple one.
First of all I suggest, you use a dependency injection & inversion of control framework (StructureMap,Unity,...).
If you are going to store your DbContext, using an IOC will make it so easy. You can define lifetime of your context. I normally go with PerRequest life time. One instance of DbContext for each web request. DBContext starts with a request and ends with it.
But there is no need to go with this pattern. You can simply start you context when you need it and dispose it after using it.
If you prefer the first approach, search for Domain Driven Design, IOC, Unit Of Work, Repository Pattern & etc.
|
[
"magento.stackexchange",
"0000004273.txt"
] | Q:
Adminhtml grid filtering with mass actions
I'm having some problems when using a mass action when a filter is applied to a grid block...
After a user has tried the mass action with the filter applied (once or twice) the mass action begins to work?!
When no filter is applied to the grid the mass actions work as expected..
Mage v1.6.2, All Caches off with Dev mode on..
Any help or tips appreciated
Below is my grid block app/code/local/NS/Swatchrequest/Block/Adminhtml/Swatchrequest/Grid.php or Code Gist
further below are the controller actions updateMassAction + deleteMassAction
EDIT: see layout xml right at the bottom
Ben
/**
* Class Group path for Resource Collection
*/
const RESOURCE_COLLECTION = 'baddass_swatchrequest/swatchrequest_collection';
/**
* Prepare base grid
*/
protected function _construct()
{
parent::_construct();
$this->setId('baddass_swatchrequest_swatchrequest');
$this->setDefaultSort('created_at');
/**
* @TODO: Why??
*/
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);
}
/**
* Grid URL for AJAX request
*
* @return string
*/
public function getGridUrl()
{
return $this->getUrl('*/*/grid', array('_current' => true));
}
/**
* Assign Swatchrequest collection to grid block
*
* @return this
*/
protected function _prepareCollection()
{
/**
* @var Baddass_Swatchrequest_Model_Resource_Swatchrequest_Collection
*/
$collection = Mage::getResourceModel(self::RESOURCE_COLLECTION);
$this->setCollection($collection);
return parent::_prepareCollection();
}
/**
* Required to filter collection
*
* @TODO: really?
* @param $column
* @return $this
*/
protected function _addColumnFilterToCollection($column)
{
return parent::_addColumnFilterToCollection($column);
}
/**
* From Collection define columns and Export types
*
* @return $this
*/
protected function _prepareColumns()
{
$this->addColumn('id', array(
'header' => $this->__('ID'),
'index' => 'entity_id',
'sortable' => true,
'width' => '60px'
));
$this->addColumn('email', array(
'header' => $this->__('Customer Email'),
'index' => 'email',
));
$this->addColumn('created_at', array(
'header' => $this->__('Created'),
'type' =>'datetime',
'index' => 'created_at'
));
$this->addColumn('name', array(
'header' => $this->__('Customer Name'),
'index' => 'name',
));
$this->addColumn('product_name', array(
'header' => $this->__('Product Name'),
'index' => 'product_name',
));
$this->addColumn('address', array(
'header' => $this->__('Address Name'),
'index' => 'address',
));
$this->addColumn('status', array(
'header' => $this->__('Status'),
'width' => '120',
'align' => 'left',
'index' => 'delivered_status',
'type' => 'options',
'options' => array(
0 => $this->__('Not Delivered'),
1 => $this->__('Delivered')
),
'frame_callback' => array(
$this, 'decorateStatus'
)
));
$this->addExportType('*/*/exportCsv', $this->__('CSV'));
$this->addExportType('*/*/exportXml', $this->__('XML'));
return parent::_prepareColumns();
}
/**
* @return Mage_Adminhtml_Block_Widget_Grid
*/
protected function _prepareMassaction()
{
$this->setMassactionIdField('id');
$this->getMassactionBlock()->setFormFieldName('swatchrequests');
// delete en mass
$this->getMassactionBlock()->addItem('delete', array(
'label' => $this->__('Delete'),
'url' => $this->getUrl('*/*/deleteMass'),
'confirm' => $this->__('Are you sure?')
));
// update delivered status en mass
$this->getMassactionBlock()->addItem('status', array(
'label' => $this->__('Delivery Status'),
'url' => $this->getUrl('*/*/updateMass'),
'additional' => array(
'visibility' => array(
'name' => 'delivered_status',
'type' => 'select',
'class' => 'required-entry',
'label' => $this->__('Status'),
'values' => array(
array(
'label' => 'Not Delivered',
'value' => 0
),
array(
'label' => 'Delivered',
'value' => 1
)
)
)
)
));
return parent::_prepareMassaction();
}
/**
* Get editable URL
*
* @param $row Row in collection
* @return string
*/
public function getRowUrl($row)
{
return $this->getUrl('*/*/edit', array(
'id' => $row->getId()
));
}
/**
* Decorate Delivery Status column with a Badge
*
* @param $value Value for $row
* @param $row Row in collection
* @param $column
* @param $isExport
* @return string
*/
public function decorateStatus($value, $row, $column, $isExport)
{
$cell = '<span class="grid-severity-critical"><span>' . $value . '</span></span>';
if($row->getDeliveredStatus() == 1) {
$cell = '<span class="grid-severity-notice"><span>' . $value . '</span></span>';
}
return $cell;
}
controller actions...
public function deleteMassAction()
{
if($data = $this->getRequest()->getPost('swatchrequests')) {
$deleted = array();
$model = Mage::getModel('baddass_swatchrequest/swatchrequest');
foreach((array) $data as $id) {
$model->setId($id)->delete();
$deleted[] = $id;
}
$this
->_getSession()
->addSuccess($this->__("Deleted Swatch Requests with ID's %s", implode(',', $deleted)));
}
$this->_redirect('*/*/');
}
public function updateMassAction()
{
if($records = $this->getRequest()->getPost('swatchrequests')) {
$delivered_status = (int) $this->getRequest()->getPost('delivered_status');
$model = Mage::getModel('baddass_swatchrequest/swatchrequest');
try {
foreach((array) $records as $id) {
$model->load($id);
$model->setDeliveredStatus($delivered_status);
$model->save();
}
$this
->_getSession()
->addSuccess($this->__('%s Swatch Requests updated', count($records)));
}
catch(Mage_Core_Model_Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
catch(Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
catch(Exception $e) {
$this
->_getSession()
->addException($e, $this->__('An error occurred while updating the product(s) status.'));
}
}
$this->_redirect('*/*/');
}
Layout xml.
<?xml version="1.0" encoding="UTF-8"?>
<layout>
<adminhtml_swatchrequest_list>
<reference name="content">
<block type="baddass_swatchrequest/adminhtml_swatchrequest" name="swatchrequest"/>
</reference>
</adminhtml_swatchrequest_list>
<adminhtml_swatchrequest_grid>
<block type="baddass_swatchrequest/adminhtml_swatchrequest_grid" name="ajax_grid" output="toHtml"/>
</adminhtml_swatchrequest_grid>
<adminhtml_swatchrequest_edit>
<reference name="content">
<block type="baddass_swatchrequest/adminhtml_swatchrequest_edit" name="baddass_swatchrequest_edit" />
</reference>
</adminhtml_swatchrequest_edit>
</layout>
A:
I think the problem comes from the layout file (at least it was for me some time ago, that's why I asked for the layout code). Mainly this:
<adminhtml_swatchrequest_grid>
<block type="baddass_swatchrequest/adminhtml_swatchrequest_grid" name="ajax_grid" output="toHtml"/>
</adminhtml_swatchrequest_grid>
The block should have a wrapper around it.
<adminhtml_swatchrequest_grid>
<block type="core/text_list" name="root" output="toHtml">
<block type="baddass_swatchrequest/adminhtml_swatchrequest_grid" name="ajax_grid"/>
</block>
</adminhtml_swatchrequest_grid>
This allows Magento to add the block that contains the form_key to the response of the ajax request. The form_key is required for all POST requests. That's why the mass action didn't work after filtering, because you didn't have anymore the form_key.
You can also put back $this->setSaveParamatersInSession(true) (I realized is not relevant. I wanted to refer to $this->setUseAjax(true);. Stupid mistake. Sorry.)
|
[
"stackoverflow",
"0027176987.txt"
] | Q:
Javascript to Jquery convertion, removing first child every iteration
I'm rewriting some old projects with Jquery to learn it better, I managed to do everything except for this while loop. It should loop through a container of divs and remove the first child every time.
var calendarModel = {
siteContainer: $('#calendar-container')
}
while (calendarModel.siteContainer.firstChild) {
calendarModel.siteContainer.removeChild(calendarModel.siteContainer.firstChild);
}
My first (horrible) attempt yielded no result except for an infinite loop:
var firstDiv = $('div:first-child', calendarModel.siteContainer);
while (firstDiv) {
firstDiv.remove();
}
Then I tried this:
var firstDiv = $('div:first-child', calendarModel.siteContainer);
while (calendarModel.siteContainer.firstDiv) {
calendarModel.siteContainer.firstDiv.remove();
}
Which was even worse cuz then it doesn't even enter the loop.
I also tried without the loop to see if it removed anything at all:
var firstDiv = $('div:first-child', calendarModel.siteContainer);
firstDiv.remove();
However, it didn't. I'm really stuck so I'd appreciate some help on this one. Any ideas?
A:
It is dangerous with jQuery to remove nodes using the native api since it can cause memory leaks.
Instead use a jQuery method so that data is cleaned up.
calendarModel.siteContainer.children().remove();
|
[
"stackoverflow",
"0009198327.txt"
] | Q:
Apply CSS rules to a nested class inside a div
I don’t know exactly how to apply CSS to a nested element. Here is my example code, but I’m looking for a manual that explains all the rules:
<div id="content">
<div id="main_text">
<h2 class="title"></h2>
</div>
</div>
How can I apply CSS to only the class title, nested inside that particular div?
A:
You use
#main_text .title {
/* Properties */
}
If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text with the class name title. If you use > instead of a space, it will only select the direct child of the element, and not children of children, e.g.:
#main_text > .title {
/* Properties */
}
Either will work in this case, but the first is more typically used.
|
[
"stackoverflow",
"0037582600.txt"
] | Q:
CSS - Border bottom length fixed to 60%
I need help on border-bottom length. I want to set border-bottom length to 60%. I can do it using the inner div like:
#myDiv {
background: #FED;
_border-bottom: 5px solid red;
}
#myDiv div {
margin: 5px 0px;
width: 60%;
height: 5px;
background-color: red;
}
<div id="myDiv">
My div
<div></div>
</div>
But i don't want to use it with extra div, I want to achieve it using border-bottom, I search for this in google and stack but no luck.
Thanks in advance.
A:
You can use pseudo element like this:
#myDiv {
background: #FED;
position: relative;
}
#myDiv::after {
content: "";
width: 60%;
height: 5px;
background: red;
position: absolute;
bottom: -5px;
left: 0;
}
<div id="myDiv">
My div
</div>
|
[
"stackoverflow",
"0010150228.txt"
] | Q:
Is there a key command to open suggestion menu (see image) in ReSharper
This has always bugged me and this morning I decided to try and find out if there is a key command to open the resharper suggestion menu and quickly up/down select the appropriate option. It's annoying to have to grab the mouse every time.
I checked the Resharper key commands list but couldn't spot anything that sounded like it would be it (although I found a few cool key commands I never knew about, particularly the encapsulate field command!)
Anyone know it if it exists?
A:
Alt + Enter
This is unless you chose to keep the Visual Studio shortcuts instead of ReSharper ones.
|
[
"stackoverflow",
"0052653414.txt"
] | Q:
Need a way to shorten and make code more effective
I want to perform a bootstrap simulation 1000 times and compute percentile confidence intervals 1000 times for different samplesizes n = 10,20,...,100. I've solved this problem and I'm just asking, instead of doing this huge computations 10 times, covering 300 lines of code, is there a way to shorten this? Like, running this function over and over again 10 times? I tried a for-loop but it did not work. Here is the code that does work:
B = 1000 # number of replicates
kHat = Parameters[1] # approx = 2.06786
gammaHat = Parameters[2] # approx = 0.51144
TheoreticalMean = kHat/gammaHat
TheoreticalVariance = kHat/gammaHat^2
PercCoverage = vector("numeric", 10L)
n = 10 # sample size
getCI = function(B, k, gamma, n) {
getM = function(orgData, idx) {
bsM = mean(orgData[idx])
bsS2M = (((n-1) / n) * var(orgData[idx])) / n
c(bsM, bsS2M)
}
F = rgamma(n, kHat, gammaHat) # simulated data: original sample
M = mean(F) # M from original sample
S2M = (((n-1)/n)*var(F))/n # S^2(M) from original sample
# bootstrap
boots = t(replicate(B, getM(F, sample(seq(along=F), replace=TRUE))))
Mstar = boots[,1] # M* for each replicate
S2Mstar = boots[,2] # S^2*(M) for each replicate
biasM = mean(Mstar)-M # bias of estimator M
# indices for sorted vector of estimates
idx = trunc((B+1)*c(0.05/2,1-0.05/2))
ciPerc = sort(Mstar)[idx] # percentile CI
c(perc=ciPerc)
}
# 1000 bootstraps
Nrep <- 1000 # number of bootstraps
CIs <- t(replicate(Nrep, getCI(B, kHat, gammaHat, n)))
# coverage probabilities
PercCoverage[1] = sum((CIs[,"perc1"]<TheoreticalMean) & (CIs[,"perc2"]>TheoreticalMean)) / Nrep
However, here I need to script this for n=10, n=20 and so on to n=100, and each time I need to change PercCoverage[1] to PercCoverage[2]...PercCoverage[10] in order to store these values in an array for later plotting.
I tried setting n=c(10,20,30,40,50,60,70,80,90,100) and then placing all of the above in a for loop but the function getCI needed numerical value.
EDIT: For loop attempt:
n = c(10,20,30,40,50,60,70,80,90,100)
B = 1000 # number of replicates
kHat = Parameters[1] # approx = 2.06786
gammaHat = Parameters[2] # approx = 0.51144
TheoreticalMean = kHat/gammaHat
TheoreticalVariance = kHat/gammaHat^2
PercCoverage = vector("numeric", 10L)
for (i in length(n)){
getCI = function(B, k, gamma, n[i]) {
getM = function(orgData, idx) {
bsM = mean(orgData[idx])
bsS2M = (((n[i]-1) / n[i]) * var(orgData[idx])) / n[i]
c(bsM, bsS2M)
}
F = rgamma(n[i], kHat, gammaHat) # simulated data: original sample
M = mean(F) # M from original sample
S2M = (((n[i]-1)/n[i])*var(F))/n[i] # S^2(M) from original sample
# bootstrap
boots = t(replicate(B, getM(F, sample(seq(along=F), replace=TRUE))))
Mstar = boots[,1] # M* for each replicate
S2Mstar = boots[,2] # S^2*(M) for each replicate
biasM = mean(Mstar)-M # bias of estimator M
# indices for sorted vector of estimates
idx = trunc((B+1)*c(0.05/2,1-0.05/2))
ciPerc = sort(Mstar)[idx] # percentile CI
c(perc=ciPerc)
}
# 1000 bootstraps
Nrep <- 1000 # number of bootstraps
CIs <- t(replicate(Nrep, getCI(B, kHat, gammaHat, n[i])))
# coverage probabilities
PercCoverage[i] = sum((CIs[,"perc1"]<TheoreticalMean) & (CIs[,"perc2"]>TheoreticalMean)) / Nrep
}
A:
Consider defining multiple functions: a master one boostrap_proc, gCI, and getM. Then pass in your sequences of sample sizes in lapply for list return or sapply for numeric vector each calling the master function and returning a series of probabilities (last line of function). Be sure to remove the hard coded n = 10.
Define Functions
B = 1000 # number of replicates
kHat = Parameters[1] # approx = 2.06786
gammaHat = Parameters[2] # approx = 0.51144
TheoreticalMean = kHat/gammaHat
TheoreticalVariance = kHat/gammaHat^2
bootstrap_proc <- function(n) {
Nrep <- 1000 # 1000 bootstraps
CIs <- t(replicate(Nrep, getCI(B, kHat, gammaHat, n)))
# coverage probabilities
sum((CIs[,"perc1"]<TheoreticalMean) & (CIs[,"perc2"]>TheoreticalMean)) / Nrep
}
getCI <- function(B, k, gamma, n) {
F <- rgamma(n, kHat, gammaHat) # simulated data: original sample
M <- mean(F) # M from original sample
S2M <- (((n-1)/n)*var(F))/n # S^2(M) from original sample
# bootstrap
boots <- t(replicate(B, getM(F, sample(seq(along=F), replace=TRUE),n)))
Mstar <- boots[,1] # M* for each replicate
S2Mstar <- boots[,2] # S^2*(M) for each replicate
biasM <- mean(Mstar)-M # bias of estimator M
# indices for sorted vector of estimates
idx <- trunc((B+1)*c(0.05/2,1-0.05/2))
ciPerc <- sort(Mstar)[idx] # percentile CI
c(perc=ciPerc)
}
getM <- function(orgData, idx, n) {
bsM <- mean(orgData[idx])
bsS2M <- (((n-1) / n) * var(orgData[idx])) / n
c(bsM, bsS2M)
}
Call Function
sample_sizes <- c(10,20,30,40,50,60,70,80,90,100)
# LIST
PercCoverage <- lapply(sample_sizes, bootstrap_proc)
# VECTOR
PercCoverage <- sapply(sample_sizes, bootstrap_proc)
# VECTOR
PercCoverage <- vapply(sample_sizes, bootstrap_proc, numeric(1))
|
[
"stackoverflow",
"0021383897.txt"
] | Q:
Chef execute block
I am very new to Chef. I have a recipe that installs sendmail and it does my configurations. I have noticed that Chef restarts the service on every run. That is because I'm running an execute that calls the session restart.
It looks like this:
execute "hashAccess" do
command "makemap hash /etc/mail/access < /etc/mail/access"
notifies :restart, "service[sendmail]"
end
I need to call this only when the access file if updated.
template "/etc/mail/access" do
source "access.erb"
mode "0644"
notifies :run, "execute[hashAccess]"
end
When the file is updated, the execute is called twice.
Both of the resources are in the same recipe and when I try to define hashAccess I get an error
ERROR: Cannot find a resource for define on amazon version 2013.09
How do I make the execute resource to run only when called?
A:
You should add action :nothing to your execute resource.
execute "hashAccess" do
command "makemap hash /etc/mail/access < /etc/mail/access"
action :nothing
notifies :restart, "service[sendmail]"
end
This way it will not be executed, unless notified by other resource.
|
[
"es.stackoverflow",
"0000214119.txt"
] | Q:
¿ como crear un tooltip generico con jquery que para usarlo solo le pase los parametros?
Quiero crear un tooltip generico que solo se pueda usar pasansole parametros como es el texto y el estilo.
A:
Como han dicho bien en los comentarios hay muchas formas de hacer un tooltip. La mejor manera (si no quieres utilizar mucho codigo/boostrap) es con Jquery.
Planteamiento
Se utilizaría la función .attr(), que permite coger el valor de un atributo sin que este sea valido para html.
A continuación crearías un elemento con la función .prepend() que permite añadir texto dentro del elemento.
Luego de eso haces un evento de hover y luego utilizas la función de .find() que pemite buscar dentro un elemento.
Y le añadiriamos una clase con la función .css() que permite modificar el css
Y bueno, luego de plantear como sería el codigo básicamente solo hace falta añadir el css y html
JQUERY
$(document).ready(function(){
$(".tooltip").css("visibility","hidden");
var mensaje = $(".tooltip-element").attr("tooltip-info");
$(".tooltip-element").prepend(''+mensaje+'');
$(".tooltip-element").hover(function(){
$(this).find(".tooltip").css("visibility","visible");
},function(){
$(this).find(".tooltip").css("visibility","hidden");
});
});
CSS
El CSS permite posicionar al elemento donde toca
.tooltip-element{
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip-element .tooltip{
visibility:hidden;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
background-color: #555;
color: #fff;
margin-left: -60px;
text-align: center;
padding: 5px 0;
}
HTML
Un texto de ejemplo con 2 tooltips
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt.
Prueba
https://jsfiddle.net/matahombres/9edLpxq8/
|
[
"stackoverflow",
"0005921747.txt"
] | Q:
Format to POST data with HttpWebRequest
I have a web service with two operations. One operation uses GET and the other uses POST. Please note that I am not a web service expert, so please feel free to point out anything I am doing wrong. Regardless, I have the following operations in my WCF service:
[WebGet(UriTemplate = "/GetPropertyValue/{propertyID}", ResponseFormat = WebMessageFormat.Json)]
public string GetPropertyValue(string propertyID)
{
return RetrievePropertyValueFromDatabase(propertyID);
}
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public string SetPropertyValue(string propertyID, string propertyValue)
{
return SetPropertyValueInDatabase(propertyID, propertyValue);
}
These two operations are being called by my Silverlight Phone application. This call has to use HttpWebRequest for performance reasons. In an effort to make this call, here is what I'm doing:
// Getting Property Value
string url = GetUrl(propertyID);
// url looks something like http://mydomain.com/myservice.svc/GetPropertyValue/2
WebRequest request = HttpWebRequest.Create(url);
request.BeginGetResponse(new AsyncCallback(GetProperty_Completed), request);
// Elsewhere in my code
// Setting property value
string url = GetUrl(propertyID, propertyValue);
// url looks something like http://mydomain.com/myservice.svc/SetPropertyValue/2/newValue
WebRequest request = HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetResponse(new AsyncCallback(SetProperty_Completed), request);
My urls are being generated properly. However, only the GetProperty request works. When I copy and paste the GetProperty url in the browser it works. When I try to execute SetProperty, I receive a failure saying Endpoint not found. I understand that the browser always uses GET, so that would make sense. But, from the HttpWebRequest, I get an error that says "The remote server returned an error: NotFound". What am I doing wrong?
Thank you!
A:
You forgot to declare the UriTemplate in the [WebInvoke] attribute. According to the sample URL in your code snippet it would have to be "SetPropertyValue/{propertyID}/{propertyValue}". This is why it comes back with a 404.
Also, you certainly don't want to use "application/x-www-form-urlencoded" as the request content-type. WCF doesn't have a MessageFormatter for that one. Plus, you're not even sending any content for this request anyways (WCF will use the UriTemplateDispatchFormatter). Hence, you can also remote the RequestFormat and BodyStyle properties. Leave the ResponseFormat property in there only if you really expect Json to come back!
|
[
"stackoverflow",
"0063445075.txt"
] | Q:
Inconsistent "Required type: byte provided: int" in Java
I stored integers in byte arrays but suddenly i got a "Required type: byte provided: int" error and some lines above not. So i tried to find out what different was, tests below:
byte b;
int integer = 12;
final int finalInteger = 12;
final int finalIntegerLO = 128; // 1000 0000
b = integer; //Required type byte provided int
b = finalInteger; //OK
b = finalIntegerLO; //Required type byte provided int
I guess having a final int with no '1' in the 2^7 place is Ok? It gave me an idea what happens if you combine it with bitwise operators and now it makes much less sense to me..
b = finalIntegerLO & 0xf; //OK
Is now ok..
but
b = integer & 0xf; //Required type byte provided int
not??
Can someone explain me why it acts so different?
A:
Let's break every line
case 1:
b = integer
Here we can see we are trying to convert int into a byte, so compiler asks as to explicitly typecast like so. (value of integer may exceed byte range.)
b = (byte) integer;
case 2:
b = finalInteger;
This case is slightly different since finalInteger is a constant whose value is fixed and the compiler can tell beforehand whether it lies within the range of byte or not. If it lies within the range compiler is smart enough to convert int to byte without us to explicitly typecast it.
case 3:
b = finalIntegerLO;
Range of byte is -128 to 127 clearly we cannot convert int to a byte and compiler sees that finalIntegerLO is a constant so it is impossible to carry out this conversion and we see an error
To remove this error we can explicitly typecase (DONT DO IT THOUGH) which will give use as b = -128
b = (byte) finalIntegerLO;
case 4:
b = finalIntegerLO & 0xf;
Here finalIntegerLO and 0xf both are constants and compiler can determine what will be the result it's 0 which is within the range of byte.
case 5:
b = integer & 0xf;
Here integer value can be changed before the execution of this line so the compiler is not sure if the result is within the range of int or not, so it asks us to explicitly typecast like so.
b = (byte) (integer & 0xf);
Again like case 3 you may get an unexpected result.
|
[
"meta.superuser",
"0000005896.txt"
] | Q:
Why are edits sometimes declined by Community, yet a similar edit shows up as accepted?
I have edited questions a couple of times, and will get rejected by Community (user -1) and will look at the question and it will contain the edits that I suggested. Is it a race condition possibly based on someone else editing the file at the same time?
Once, I figured it out, it was someone rejecting it, but another person taking my edits and proposing the same edit. (I talked with the editor, and this is the case.)
I find it strange behavior. And it doesn't happen often, but when it happens, The times that I have noticed it, other than the one I talked to the editor) they have had a 3k+ reputation.
But it also counts as a 'reject' even though the changes were ultimately accepted due to the result, though not the mechanism.
A:
There are 2 cases where I've seen this happen -
A race condition when the edit suggested and a 2k+ user edited the post simultaneously. Since edits by 2k+ users don't have to be peer-reviewed, their edit gets priority & the system accepts the edit, rejecting other suggested edits
The person who reviewed the edit unticked "Suggested edit was useful". In this case, the system incorporates the edits into the current revision, but since the tickbox was unchecked, the edit credit gets rejected
|
[
"stackoverflow",
"0047718346.txt"
] | Q:
Connect a docker node running on a separate ec2 host to Jenkins
I have 2 aws ec2 instances. One instance is running Jenkins, the other is running Docker. I am trying to connect the container running on the Docker host to Jenkins as a node.
To start the container on the Docker host I ran the following:
sudo dockerd -H tcp://127.0.0.1:2376 -H unix:///var/run/docker.sock
In the cloud settings (under jenkins/configure)
Docker Host URI:
tcp://IP-ADDRESS-OF-EC2-DOCKER-HOST:2376
Docker Hostname or IP address: IP-ADDRESS-OF-EC2-DOCKER-HOST
Dockerfile:
FROM ubuntu:16.04
RUN apt-get update
RUN apt-get install openjdk-8-jdk -y
RUN mkdir -p /home/jenkins
EXPOSE 22
ec2 Docker host security open incoming ports: 2375, 2376, 4243, 22
When I hit the "Test Connection" button, I get:
Connection refused: /IP-ADDRESS-OF-EC2-DOCKER-HOST:2376
java.net.ConnectException: Connection refused
Caused: io.netty.channel.AbstractChannel$AnnotatedConnectException:
Connection refused: /IP-ADDRESS-OF-EC2-DOCKER-HOST:2376
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at
sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:352)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:632)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)
at java.lang.Thread.run(Thread.java:748)
On another stackoverflow post, someone recommended hitting the "Apply" button first, but that doesn't work because I get an error popup stactrace stating a java.lang.NullPointerException.
A:
Try giving IP-ADDRESS-OF-EC2-DOCKER-HOST instead of 127.0.0.1 in below CMD
sudo dockerd -H tcp://127.0.0.1:2376 -H unix:///var/run/docker.sock
Test port is open from docker to Jenkins host using
telnet docker_host_ ip 2376
|
[
"stackoverflow",
"0042489381.txt"
] | Q:
Remove Dotted Line
I follow this link How to get 'div' shaped as a flag with CSS but now I can't remove dotted line. The code:
div {
height: 100px;
width: 100px;
margin: 100px auto;
position: relative;
overflow: hidden;
border: solid 3px #000;
border-bottom: none;
text-align: center;
}
div:before,
div:after {
content: '';
display: block;
height: 100%;
width: 200%;
transform: rotate(20deg);
box-shadow: 46px 0 0 3px #000;
position: absolute;
top: 1px;
right: -120%;
}
div:after {
transform: rotate(-20deg);
left: -120%;
box-shadow: -46px 0 0 3px #000;
}
<div>Test</div>
A:
Setting background: #fff seems to fix the issue. Apply z-index: -1 too, so that the content isn't covered by the :before and :after now that they're not transparent.
div {
height: 100px;
width: 100px;
margin: 100px auto;
position: relative;
overflow: hidden;
border: solid 3px #000;
border-bottom: none;
text-align: center;
}
div:before,
div:after {
content: '';
display: block;
height: 100%;
width: 200%;
transform: rotate(20deg);
box-shadow: 46px 0 0 3px #000;
position: absolute;
top: 1px;
right: -120%;
/* Setting the background
covers the "dotted line" */
background: #fff;
/* It also covers the content
so we need to move it underneath
with z-index */
z-index: -1;
}
div:after {
transform: rotate(-20deg);
left: -120%;
box-shadow: -46px 0 0 3px #000;
}
<div>Test</div>
|
[
"stackoverflow",
"0003336102.txt"
] | Q:
Integrating plug-ins of different languages in a framework
I have a question to ask: suppose I create a extensible software application with a plug in architecture, so that new applications can be integrated in this tool. If a new application is written in a different language and needs to be integrated in this application of mine, do I need to use tools such as SWIG and the Java Native Interface (depending of the languages used of course)? If not, what do I need?
A:
suppose I create a extensible software application with a plug in architecture
Okay. You've written some code. I'll pretend it's in Java because you mention SWIG and JNI.
If a new application is written in a different language
How did this happen?
You planned for it. In which case, your application had an API that supported at least one additional language. "different language" doesn't mean much because you -- as developer -- need to decide what languages you'll tolerate. New languages aren't a random event. They're something you designed for.
You didn't plan for it. In which case, someone else -- contrary to your design -- is demanding another language. A language you did not design for.
Choice 1 is the most common. You planned for specific languages, and wrote specific API libraries for those languages. You wrote -- in those other languages -- the necessary API library that would make those languages work with your application.
You probably don't use tools such as SWIG and the Java Native Interface to create this API. If you want to support Python, you'd use a bunch of Python tools to permit Python programmers to use your application.
Choice 2 is less common. Either you didn't plan, or you have someone who insists on writing their own API library based on their choice of language.
You probably don't use tools such as SWIG and the Java Native Interface to create this API. If someone else wants to support Python, they'll use a bunch of Python tools to use your application.
The real question is not "do I need to use tools such as SWIG and the Java Native Interface (depending of the languages used of course)?" Or anything like it.
The real questions are
How do I choose an additional language to support above and beyond the implementation language? You appear to be using Java. You want to support more languages than Java. [Just guessing -- your question is incomplete.]
Answer: Toss a coin. Whatever languages you think the marketplace will demand. C is popular. So is C#. So is Python. Pascal not so popular.
How to I write my framework to permit "foreign" languages?
Answer: This is challenging.
To write application which allows multiple language interfaces you have to do a bunch of things.
Know a bunch of languages well enough to know their limitations.
Write your application so that the API can be successfully used by all your various languages.
Have very, very clear use cases and unit tests to prove that the application really works that way.
Avoid language-specific features. Avoid hardware-specific features. This means avoid all "native" or "primitive" data types in the API, and use real standard types. Often Unicode strings represented in UTF-8. The kind of thing that is universal and ubiquitous.
Avoid quirky non-standard protocols. HTTP, FTP and the like are so widely adopted that you can't go too far wrong with these as an interface. They can be slow. For better speed, you'll can create named pipes between the "foreign" code and your application. If you want the foreign code to have "direct" access to your framework, think twice.
Or, do what many API's do and embrace C as the "lingua franca" of interfaces. Design everything to be callable from C programs. Use C conventions and C-friendly data types. This has limitations, but many people do it.
|
[
"stackoverflow",
"0012548003.txt"
] | Q:
Phonegap 2.1 support for Iphone 5 display
I updated to phonegap 2.1 with the hope of being able to deal with 4 inch retina display of new Iphone 5. (I am not sure if they ever promised to support it anyway)
The problem is that (as you guessed), when I change the device to Iphone 4 inch display in IOS simulator, this is how it looks like. How to deal with the black stripes on top and bottom ?
A:
All you need to do is to add another splash image: Add a [email protected] image, at 640 x 1136 px and it will work.
For next time: Google is your friend ;)
|
[
"math.stackexchange",
"0001338692.txt"
] | Q:
Approximating $\frac{(kn)!}{(n!)^k}$
Is there any approximations for the form
$$\frac{(kn)!}{(n!)^k},$$
where $n$ and $k$ are positive integers? $n$ is not necessary much larger than $k$?
A:
The usual form of Stirling's Approximation is
$$m! \approx \sqrt{2 \pi m} \left(\frac{m}{e}\right)^m,$$
which is a very good approximation for even modest $m$. Substituting using this approximation gives
$$\frac{(kn)!}{n!^k} \approx \frac{\sqrt{2 \pi (kn)} \left(\frac{kn}{e}\right)^{kn}}{\left[\sqrt{2 \pi n} \left(\frac{n}{e}\right)^n\right]^k} = (2 \pi n)^{\frac{1 - k}{2}} k^{kn + \frac{1}{2}}.$$
This approximation should be quite good again for $n, k$ that are not too small, and one could produce rather tight error estimates using the estimates given in the linked article.
|
[
"stackoverflow",
"0004726899.txt"
] | Q:
While Loop to Iterate through Databases
I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns. this is was I have done so far. nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)
DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)
SET @Loop = 1
SET @DBName = ''
WHILE @Loop = 1
BEGIN
SELECT [name] FROM sys.databases
WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
ORDER BY [name]
SET @Loop = @@ROWCOUNT
IF @Loop = 0
BREAK
SET @SQL = ('USE ['+ @DBNAME +']')
IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
BEGIN
SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
END
ELSE
--BEGIN
PRINT 'ErrorLog'
END
A:
I would consider sp_MSForEachDB which is a lot easier...
Edit:
sp_MSForEachDB 'IF DB_NAME LIKE ''Z%%''
BEGIN
END
'
A:
CREATE TABLE #T
(dbname sysname NOT NULL PRIMARY KEY,
SumPGCOUNT INT,
CREATED DATETIME)
DECLARE @Script NVARCHAR(MAX) = ''
SELECT @Script = @Script + '
USE ' + QUOTENAME(name) + '
IF EXISTS(SELECT * FROM sys.tables WHERE OBJECT_ID=OBJECT_ID(''dbo.tbldoc''))
INSERT INTO #T
SELECT db_name() AS dbname, SUM(PGCOUNT) AS SumPGCOUNT, CREATED
FROM dbo.tbldoc
GROUP BY CREATED;
'
FROM sys.databases
WHERE state=0 AND user_access=0 and has_dbaccess(name) = 1
AND [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
ORDER BY [name]
IF (@@ROWCOUNT > 0)
BEGIN
--PRINT @Script
EXEC (@Script)
SELECT * FROM #T
END
DROP TABLE #T
A:
My code to search for data from more than one database would be:
use [master]
go
if object_id('tempdb.dbo.#database') is not null
drop TABLE #database
go
create TABLE #database(id INT identity primary key, name sysname)
go
set nocount on
insert into #database(name)
select name
from sys.databases
where name like '%tgsdb%' --CHANGE HERE THE FILTERING RULE FOR YOUR DATABASES!
and source_database_id is null
order by name
Select *
from #database
declare @id INT, @cnt INT, @sql NVARCHAR(max), @currentDb sysname;
select @id = 1, @cnt = max(id)
from #database
while @id <= @cnt
BEGIN
select @currentDb = name
from #database
where id = @id
set @sql = 'select Column1, Column2 from ' + @currentDb + '.dbo.Table1'
print @sql
exec (@sql);
print '--------------------------------------------------------------------------'
set @id = @id + 1;
END
go
|
[
"stackoverflow",
"0017834561.txt"
] | Q:
Duplicating identical BeagleBone Black setups
After having set-up and customized my "master" BeagleBone Black (BBB) with applications etc. on the on-board eMMC, I want to duplicate it on other BBB boards.
What is the best way to duplicate the BBB?
My understanding of options:
SD-Card: Programming each board by inserting a prepared SD card containing an image and pressing the "boot" switch while powering up.
How should I prepare that .img file or the SD card from my master BBB?
The image should copy to the on-board eMMC, so that the SD-card can be removed afterwards.
USB: Programming by connecting the board over USB to a (Win7) PC.
Is it possible to write the full on-board eMMC from the PC?
With which app to do the writing?
How to prepare the image which will be written, starting from the master BBB?
Ethernet: Programming over LAN after boot-up with default angstrom distro.
Is it even possible over LAN?
How to do the writing?
How to prepare the image which will be written, starting from the master BBB?
Which is possible/best?
Edit: My current solution is to flash with a standard image (from the BeagleBoe website) and then have a script do all modifications as expected. This includes disabling many services I don't need, installing applications and configuring stuff etc.
If there is an easier way for making a SD card with a full image on it, I'm still interested.
A:
As noted at the bottom of the eLinux article, there is a much easier way if you are running the Debian distribution:
Boot master BBB with no SD card in
Insert SD card
Log in (e.g. with serial terminal, SSH etc.) and run sudo /opt/scripts/tools/eMMC/beaglebone-black-make-microSD-flasher-from-eMMC.sh. LEDs will flash in sequence whilst SD card is being written.
When the LEDs stop and the script terminates, remove the SD card.
Insert SD card into new BBB then power on.
eMMC will be flashed; LEDs on new BBB will flash in sequence until complete.
A:
For anyone else that needs this, the best answer I've found to this is to do the following:
First setup your master Beaglebone Black the way you want it.
Backup the eMMC
FAT format a 4GB or larger SD card (must be a MBR/bootable formatted microSD card)
Download beagleboneblack-save-emmc.zip and extract the contents onto your SD card
Note: this is an image from Jason Krinder at his github https://github.com/jadonk/buildroot using the save-emmc-0.0.1 tag
Put the card into your powered off Beaglebone Black
Power on your Beaglebone Black while holding the S2 Button
The USR0 led will blink for about 10 minutes, when it's steady on you have an SD card with a copy of your eMMC in a .img file
Use the eMMC to flash a new Beaglebone Black
On the SD card edit autorun.sh
#!/bin/sh
echo timer > /sys/class/leds/beaglebone\:green\:usr0/trigger
dd if=/mnt/<image-file>.img of=/dev/mmcblk1 bs=10M
sync
echo default-on > /sys/class/leds/beaglebone\:green\:usr0/trigger
where <image-file> is the image file you got after copying backing up your eMMC
Insert the card into your powered off Beaglebone Black
Power on your Beaglebone Black while holding the S2 Button
The Beaglebone Black should go into rebuilding mode and within about 20 minutes you'll have a newly flashed Beaglebone Black (when all 4 USR LEDs are solid) with a copy of your original
eLinux reference used for this article - http://elinux.org/BeagleBone_Black_Extracting_eMMC_contents
A:
I have the same need and am using dd and nc (NetCat) to save directly on my desktop without having to use an intermediary SD Card. You can do this over the USB connection, or ethernet connection, by changing the IP address in the steps below.
After setting up your BBB with the applications you want, the basic steps are:
On the desktop, run this command in a terminal:
nc -l 19000|bzip2 -d|dd bs=16M of=BBB.img
On the BeagleBone Black, run this command in a terminal (you can SSH into it, or do it directly from the BBB):
dd bs=16M if=/dev/mmcblk0|bzip2 -c|nc 192.168.7.1 19000
The 192.168.7.1 address is for the USB connection. (BBB is 192.168.7.2) If you're doing this over an ethernet connection, you should use your desktop's IP address.
This is taken from instructions here.
Finally, follow any method to install onto the next BBB. Here's an example of how to flash the emmc.
|
[
"stackoverflow",
"0015031440.txt"
] | Q:
need help on regex with comparision
I have a small question in tcl regular expression,
my sample goes like this
"rollno" is a variable which is list of 10211 17311 15111 16111 10111
$rollno takes a value at a time. for example rollno = 10211
student_1_class_A_Teacher = 10211
student_1_class_B_Teacher = 17311
student_1_class_c_Teacher = 15111
student_2_class_A_Teacher = 16111
student_2_class_B_Teacher = 10111
i need a regular expression which substitutes the variable "$rollno" in regular expression, and should return the classID = A
A:
So, if you have the value '15111' and an input file:
student_1_class_A_Teacher = 10211
student_1_class_B_Teacher = 17311
student_1_class_c_Teacher = 15111
student_2_class_A_Teacher = 16111
student_2_class_B_Teacher = 10111
You want to return 'c'?
You could try something like this:
class_\w(?=_Teacher = 15111)
This will return 'class_c', then you can extract the last character to get 'c'.
|
[
"stackoverflow",
"0032239430.txt"
] | Q:
Rails when I wrap a table with a form the table disappears checkbox
I am not sure what is happening here. When I wrap the form around the table the table disappears. When I remove the form, the table reappears. Thanks in advance. Here is the code:
<% form_tag deposit_checks_path :method => :put do %>
<table>
<thead>
<tr>
<th>Checkbox</th>
<th>Date</th>
<th>Mailer ID</th>
<th>Payment amt</th>
<th>Transaction type</th>
<th>Transaction</th>
<th>Deposit</th>
<th>User</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @payments.each do |payment| %>
<tr>
<td><%= check_box_tag "payment_id[]", payment.id, checked = false %></td>
<td><%= payment.created_at %></td>
<td><%= payment.mailer_id %></td>
<td><%= number_to_currency(payment.payment_amt) %></td>
<td><%= payment.transaction_type %></td>
<td><%= payment.transaction_id %></td>
<td><%= payment.deposit_id %></td>
<td><%= payment.user_id %></td>
<td><%= link_to 'Show', payment %></td>
<td><%= link_to 'Edit', edit_payment_path(payment) %></td>
<td><%= link_to 'Destroy', payment, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<%= submit_tag "Edit Checked" %>
<% end %>
thanks for the help
A:
did you notice in your code?
<% form_tag deposit_checks_path :method => :put do %>
you forgot to add a comma. It should have been
<% form_tag deposit_checks_path, :method => :put do %>
otherwise the method: :put is appended to the action attribute
Main Point:
You forgot to put an equals sign before form_tag
Try this
<%= form_tag deposit_checks_path, :method => :put do %>
|
[
"stackoverflow",
"0030397886.txt"
] | Q:
Template class constructor with one argument in the second template throw error "constant"
I have a problem with my class templates.
template <class T>
class test {
private:
T a;
public:
test (T _a){
a = _a;
}
test (){}
};
template <class T>
class test2 {
public:
test<double> first(10.2);
// ^ error C2059: syntax error : 'constant'
test<T> second;
test<T> third;
test2(){}
};
main()
{
test2<int> object;
return 0;
}
Why do I get the compiler error shown in the comment above?
A:
Non-static data member initializers need to use braces or an equals sign. Parentheses are not an option, probably so that the whole Most Vexing Parse fiasco doesn't happen with data members. Change it to one of the following:
test<double> first = 10.2; //option 1 (doesn't work with explicit constructor)
test<double> first{10.2}; //option 2
|
[
"stackoverflow",
"0033951598.txt"
] | Q:
Requires files in one file - Angular | Node.js
I have question, can I have many requires js files in one file ? If yes, how can I create object from this ? Calling like new AllPages.OnePage() doesn't working. if it is not clear. I want it like headers in C++, many *.h in one header. Thank you very much!
testFlow.js
var AllPages = require("./../requires.js");
describe('Test1', function() {
beforeEach(function() {
new Login().login();
});
it('Can i do it', function() {
new AllPages.OnePage()
.goToHome(Address);
browser.sleep(10000);
});
requires.js
var Login = require("./login.js");
var LoginPage = require("./pages/loginPage.js");
var OnePage = require("./pages/onePage.js");
loginPage.js
var LoginPage = function() {
this.visit = function() {
browser.get(browser.params.context);
return this;
};
this.enterName = function(name) {
element(by.id("j_username")).sendKeys(name);
return this;
};
this.enterPswd = function(pswd) {
element(by.id("j_password")).sendKeys(pswd);
return this;
};
this.login = function() {
element(by.id("submit")).click();
};
};
module.exports = LoginPage;
A:
You should be using it like below -
requires.js
module.exports = {
Login : require('./login.js'),
Loginpage : require('./pages/loginPage.js') // and so on
};
You can then require this requires.js in the files you want. You can invoke required files as follows -
var ALL = require('./requires');
// calling Login page functions
// ALL.Login like this
|
[
"stackoverflow",
"0015057949.txt"
] | Q:
GraphViz doesn't make a png file when it is started from C# code
In my class describing graph I would like to make one method generating GraphViz code and save it to the .dot file, and other making png graphics file with that graph. I tried:
private void MakeDotFile()
{
FileStream fileStream =
new FileStream("tmp.dot", FileMode.Create, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.Write("graph { a -- b }");
streamWriter.Close();
fileStream.Close();
}
public void MakePngFile()
{
MakeDotFile();
Process process = new Process();
process.StartInfo =
new ProcessStartInfo("<< dot.exe location >>",
"-Tpng << .dot file location >> > << .png file location >>");
process.Start();
process.WaitForExit();
}
but unfortunately it is finishing making a terible sound like "beep" and doing nothing (not creating png file). When I debugged, I had found that process exit code is 3. I checked many times if paths are good. Interesting is that the same program with the same arguments in cmd.exe is running right.
What do you think? Where is the problem? What is the solution?
Thanks in advance
A:
Instead of redirecting the output, you should use the -o parameter of dot.
process.StartInfo =
new ProcessStartInfo(@"D:\graphviz\bin\dot.exe",
@"-Tpng D:\tmp.dot -o D:\tmp.png");
|
[
"stackoverflow",
"0020916555.txt"
] | Q:
for loop versus foreach
I am fairly new at programming still, and I'm having a hard time been wishing for different between for/foreach. In a more technical exclamation, the for each loop counts how many times it is needed-unlike the code below.
Let's say I have been a sample of a for loop like this:
var i = result = 0;
for (var i = 2; i < process.argv.length; i++) {
result = result + Number(process.argv[i]);
}
console.log(result);
How would this code change if it were a foreach statement? Is the explanation right? Or is there more to it?
Thank you in Advance.
A:
A foreach loop goes through all the elements in an array and gives them to you one by one without having to do any messing about with an iteration variable with 'i'. For example, you could do this:
var result = 0;
process.argv.forEach(function(element){
result = result + element;
});
There is a difference between your code and this code: your code skipped the first two elements because 'i' started at 2. This is harder to do in a foreach loop, and if you need that, you should stick to a for loop.
The foreach loop sets up the counters for you. Convenient, but less flexible. It always starts at the first element and ends at the last one. One cool thing to notice is that we also don't have to do anything like '[i]'. The element in the array is pulled out and passed to our function.
In conclusion, a foreach loop is simply a simplified for loop for cases when you need to look at every element in an array.
I personally think the foreach loop in node.js is ugly, since it isn't really a statement, just a function attached to arrays. I much prefer how they look in something like php where they are a part of the language:
$result = 0;
foreach ($process as $element) {
$result = $result + $element;
}
But that is just personal taste.
A:
for and forEach are not your only options. You can also use reduce
var result = process.argv.slice(2).reduce(function(sum, n) {
return sum + parseInt(n, 10);
}, 0);
console.log(result);
Try and see
$ node reduce.js 1 2 3
6
|
[
"datascience.stackexchange",
"0000069743.txt"
] | Q:
What is the best way to find minima in Logistic regression?
In the Andrew NG's tutorial on Machine Learning, he takes the first derivative of the error function then takes small steps in direction of the derivative to find minima. (Gradient Descent basically)
In the elements of statistical leaning book, it found the first derivative of the error function, equated it to zero then used numerical methods to find out the root (In this case Newton Raphson)
In paper both the methods should yield similar results. But numerically are they different or one method is better than the other ?
A:
Being a second-order method, Newton–Raphson algorithm is more efficient than the gradient descent if the inverse of the Hessian matrix of the cost function is known. However, inverting the Hessian, which is an $\mathcal O(n^3)$ operation, rapidly becomes impractical as the dimensionality of the problem grows. This issue is addressed in quasi-Newton methods, such as BFGS, but they don't handle mini-batch updates well and hence require the full dataset to be loaded in memory; see also this answer for a discussion. Later in his course Andrew Ng will discuss neural networks. They can easily contain millions of free parameters and be trained on huge datasets, and because of this variants of the gradient descent are usually used with them.
In short, the Newton–Raphson method can be faster for relatively small problems, but the gradient descent scales better with complexity of problem.
A:
SGD just requires the first derivative, but Newton-Raphson ends up requiring the second derivative, which might be hard or impossible to compute. It will also need more computation as a result.
For non-convex problems, note that the derivative is 0 at maxima as well as minima, and at saddle points, which (as I understand) takes a little more care to get right with numerical methods.
But yes for logistic regression, which is convex and for which second derivates are not complex, Newton's method would be fine too. I believe it's usually optimized with L-BFGS, not simply SGD, which is in a way more like Newton's method.
I think it was explained with SGD just to keep it simple.
|
[
"dba.stackexchange",
"0000231922.txt"
] | Q:
How can I override the default values for a parameter in a report?
I have a report with a parameter that usually gets its default values by running a query that takes another parameter as it's input. This works fine when the report is run interactively.
However, I have a requirement to call this report from code where all the filters are supplied by the code. The code I have for the other parameters works fine:
string report = "Analysis/Report.aspx?ReportPath=/MyReport";
string fullReportPath = string.Format("{0}&LocationId={1}&BatchNumber={2}&SearchReference={3}", report, locationId, batchNumber, reference);
RunReport(fullReportPath);
There is a drop down where the both the available values and default values are retrieved from the database via a query which has the locationId as a parameter. This is so all the values are selected by default.
What do I need to change in the report and/or the code so it works as it does now and I can supply the selected values for this drop down as a parameter?
I've found this blog post which uses the concept of internal or hidden control parameters to use when setting the values of other parameters, but the example given just sets the other parameter to a default value or leaves it blank. I need for the parameter to run the current query.
A:
It appears that SQL Reports actually does what I want automatically - but only if the parameter with the dependent query immediately follows the first query.
We were modifying the report for other reasons and moved the offending drop down higher up the parameter list so it was second (after the query that filled in the location drop down). Having done that, the drop down was populated automatically.
The blog post I linked to in the question mentions that parameter order is important and there's a separate post about that by the same author.
|
[
"stackoverflow",
"0036587177.txt"
] | Q:
How can I conditionally change css styles with js?
I'd like to implement some javascript that uses an if statement to change some css styles. Not sure how to do it, any help would be great!
A:
If you want to change a single style of an element using JavaScript, use
document.getElementById(id).style.property = new style
eg :
document.getElementById("myDiv").style.color= "red";
To add a new CSS class to an element, use
document.getElementById(id).classList.add("mystyle");
To remove
document.getElementById(id).classList.remove("mystyle");
Demo :
function changeSingleStyle() {
var color = document.getElementById("myDiv").style.color;
if (color === "red")
document.getElementById("myDiv").style.color = "yellow";
else
document.getElementById("myDiv").style.color = "red";
}
function addClass() {
document.getElementById("myDiv").classList.add("mystyle");
}
function removeClass() {
document.getElementById("myDiv").classList.remove("mystyle");
}
.mystyle {
color : red;
background: green;
font-size: 50px;
}
<div id="myDiv"> This is a div </div>
<button onclick="changeSingleStyle()">changeSingleStyle</button>
<button onclick="addClass()">addClass</button>
<button onclick="removeClass()">removeClass</button>
|
[
"stackoverflow",
"0031430752.txt"
] | Q:
OxyPlot:Cannot setting Axis values
I have been tying to set the min and max values of y axis by using properties like ActualMinimum and ActualMaximum,but i doesn't work even I set the MinimumPadding and MaximumPadding to 0. I also tried the Zoom method of axis, it did not work. Sorry that I cannot upload a pic...
Could someone please guide me in this regard ? Any help is very much appreciated. Thanks !
A:
Please use the properties AbsoluteMaximum and AbsoluteMinimum to limit the axes to a specific value:
plotModel.Axes.Add(new LinearAxis
{
Position = AxisPosition.Left,
AbsoluteMaximum = 5.5,
AbsoluteMinimum = 0,
});
In my opinion the properties ActualMinimum and ActualMaximum are used to limit the axes to an initial value but you are able to zoom out later.
|
[
"stackoverflow",
"0049225490.txt"
] | Q:
How to share in memory database using TestServer and data seeding class to run Integration Tests in memory
I recently started using TestServer class to self-host and bootstrap an Aspnet Core API to run Integration Tests without a dedicated running environment.
I love the way it works and using custom environment name, I decided to control the way the EF Context is created, switching from SQL Server to In-Memory database.
Problem is that in order to seed the data necessary to run the tests via API requests, would be very expensive for both coding and running time.
My idea is to create a class or a simple framework to seed the data necessary by each test, but to do so I need to use the same in-memory database which is initialized with the API stack by the TestServer.
How is it possible to do so?
A:
In the first place is important to understand that for better testing in replacement to a relational database such SQL Server, In Memory database is not ideal.
Among the various limitations, it does not support foreign key constraints.
A better way to use an in-memory database is to use SQLite In-Memory mode.
Here is the code I used to setup the TestServer, Seed the Data and register the DB Context for the Dependency Injection:
TestServer
public class ApiClient {
private HttpClient _client;
public ApiClient()
{
var webHostBuilder = new WebHostBuilder();
webHostBuilder.UseEnvironment("Test");
webHostBuilder.UseStartup<Startup>();
var server = new TestServer(webHostBuilder);
_client = server.CreateClient();
}
public async Task<HttpResponseMessage> PostAsync<T>(string url, T entity)
{
var content = new StringContent(JsonConvert.SerializeObject(entity), Encoding.UTF8, "application/json");
return await _client.PostAsync(url, content);
}
public async Task<T> GetAsync<T>(string url)
{
var response = await _client.GetAsync(url);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(responseString);
}
}
Data Seeding (Helper class)
public class TestDataConfiguration
{
public static IMyContext GetContex()
{
var serviceCollection = new ServiceCollection();
IocConfig.RegisterContext(serviceCollection, "", null);
var serviceProvider = serviceCollection.BuildServiceProvider();
return serviceProvider.GetService<IMyContext>();
}
}
Data Seeding (Test class)
[TestInitialize]
public void TestInitialize()
{
_client = new ApiClient();
var context = TestDataConfiguration.GetContex();
var category = new Category
{
Active = true,
Description = "D",
Name = "N"
};
context.Categories.Add(category);
context.SaveChanges();
var transaction = new Transaction
{
CategoryId = category.Id,
Credit = 1,
Description = "A",
Recorded = DateTime.Now
};
context.Transactions.Add(transaction);
context.SaveChanges();
}
DB Context registration (In IocConfig.cs)
public static void RegisterContext(IServiceCollection services, string connectionString, IHostingEnvironment hostingEnvironment)
{
if (connectionString == null)
throw new ArgumentNullException(nameof(connectionString));
if (services == null)
throw new ArgumentNullException(nameof(services));
services.AddDbContext<MyContext>(options =>
{
if (hostingEnvironment == null || hostingEnvironment.IsTesting())
{
var connection = new SqliteConnection("DataSource='file::memory:?cache=shared'");
connection.Open();
options.UseSqlite(connection);
options.UseLoggerFactory(MyLoggerFactory);
}
else
{
options.UseSqlServer(connectionString);
options.UseLoggerFactory(MyLoggerFactory);
}
});
if (hostingEnvironment == null || hostingEnvironment.IsTesting())
{
services.AddSingleton<IMyContext>(service =>
{
var context = service.GetService<MyContext>();
context.Database.EnsureCreated();
return context;
});
} else {
services.AddTransient<IMyContext>(service => service.GetService<MyContext>());
}
}
The key is the URI file string used to create the SQLite connection:
var connection = new SqliteConnection("DataSource='file::memory:?cache=shared'");
|
[
"stackoverflow",
"0025948562.txt"
] | Q:
Auto populate Map with subclasses using Spring Framework
I have an abstract class A with a few sub classes B, C, D and I would like to have a Map with Spring auto injecting all the sub classes into a Map.
I'm about to make many sub classes from A and I do not want to after creating them to also populate the XML so Spring can put them in a Map (Its double work and tedious). I want Spring to take all those sub classes and auto put them in the Map without the bulky XML.
I understand for the Map I need to give a key to each instance of the sub class bean.
So have this so far:
public abstract class A{}
@Bean(name = "Bbean")
public class B extends A{}
@Bean(name = "Cbean")
public class C extends A{}
@Bean(name = "Dbean")
public class D extends A{}
And finally I want this to work and not be null when I reference it:
@Autowired
private Map<String, A> map;
How do I set this up in Spring Framework?
A:
ok, you want your beans auto-detected and then to collect them automatically.
So annotate your B, C, D classes with @Component -like annotations (e.g. @Component, @Service, @Repository, @Controller etc.), and then use @ComponentScan to detect them. (@Bean is used for other purposes, you didn't use it properly in your example).
Then you collect all beans of type A with @Autowired annotation:
@Autowired List<A> allAs;
Now you want to make a map, so make all these beans bean name-aware:
class A implements BeanNameAware {...}
And finally you create a map from your @Autowired list:
class AsMapHolder implements InitializingBean {
@Autowired private List<A> allAs;
private Map<String, A> nameToA = new LinkedHashMap<String, A>();
@Override void afterPropertiesSet() {
for (A a: allAs) {
nameToA.put(a.getName(), a); //getName() is from BeanNameAware, populated automatically
}
}
}
It should work.
Update: Simply '@Autowired Map beanNameToA;' should work as well
|
[
"stackoverflow",
"0043595108.txt"
] | Q:
warning 1st argument found type MapActivity required android.support.v4.app.Fragment
Hi i am new here and hope to find help...
i found a message "warning 1st argument found type MapActivity required android.support.v4.app.Fragment" I want to MapActivity as a Fragment because i want to add Map in View Pager. I am using View Pager and also View Pager Adapter and in View Pager Adapter i am using two Array List for Fragments and TabTitles
Here is the code of ViewPagerAdapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragments, String titles)
{
this.fragments.add(fragments);
this.tabTitles.add(titles);
}
public ViewPagerAdapter(FragmentManager fm)
{
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return tabTitles.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
and here is code of MainActivity.java
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new HomeFragment(), "Home");
viewPagerAdapter.addFragments(new SearchFragment(), "Search");
// viewPagerAdapter.addFragments(new MapFragment(),"Map");
viewPagerAdapter.addFragments(new MapsActivity(), "Map");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
in activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lilla.tabdemo.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="@layout/toolbar_layout"
/>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tabLayout"
app:tabMode="fixed"
app:tabGravity="fill"
>
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewPager"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>
Please help me Thanks....
MapsActivity.java
package com.example.lilla.tabdemo;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
A:
Your MapsActivity class must extend Fragment class and the Fragment class must be imported from the
android.support.v4.app.Fragment package.
Try this class:
public class MapsActivity extends Fragment implements
OnMapReadyCallback {
private GoogleMap mMap;
private MapView mMapView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_maps, container, false);
getActivity().setTitle("Map");
mMapView = (MapView) v.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this); //this is important
return v;
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
|
[
"stackoverflow",
"0053620343.txt"
] | Q:
Django Check for user in list
I'm creating a django blog app where users can add comments to articles.
I want to remove the post button when the user has already commented.
I have a model named article and another one named comment (with ForeignKey to article)
I tried {% if any request.user in article.comment_set.all} but that doesn't work. I tried to loop over article.comment_set.all but that didn't work either.
Is there a method to do this in the template?
A:
Rather than doing that in template, why don't you do that in view and send it via context. For example:
def view(request):
...
user_exists = article.comment_set.filter(user=request.user).exists()
context = {}
context['user_exists'] = user_exists
return render(request, 'template.html', context)
in template:
{% if user_exists %}
// do something
{% else %}
// do something else
{% endif %}
|
[
"stackoverflow",
"0052158473.txt"
] | Q:
Restricting Page for Non-Logged In Users Without PHP
I am currently working on a project that allows users to authenicate their logins with our Microsoft work/school accounts. Currently, I have a page where the user calls the API to login, like this:
// Graph API endpoint to show user profile
var graphApiEndpoint = "https://graph.microsoft.com/v1.0/me";
// Graph API scope used to obtain the access token to read user profile
var graphAPIScopes = ["https://graph.microsoft.com/user.read"];
// Initialize application
var userAgentApplication = new Msal.UserAgentApplication(msalconfig.clientID, null, loginCallback, {
redirectUri: msalconfig.redirectUri
});
//Previous version of msal uses redirect url via a property
if (userAgentApplication.redirectUri) {
userAgentApplication.redirectUri = msalconfig.redirectUri;
}
window.onload = function () {
// If page is refreshed, continue to display user info
if (!userAgentApplication.isCallback(window.location.hash) && window.parent === window && !window.opener) {
var user = userAgentApplication.getUser();
if (user) {
callGraphApi();
}
}
}
/**
* Call the Microsoft Graph API and display the results on the page. Sign the user in if necessary
*/
function callGraphApi() {
var user = userAgentApplication.getUser();
if (!user) {
// If user is not signed in, then prompt user to sign in via loginRedirect.
// This will redirect user to the Azure Active Directory v2 Endpoint
userAgentApplication.loginRedirect(graphAPIScopes);
// The call to loginRedirect above frontloads the consent to query Graph API during the sign-in.
// If you want to use dynamic consent, just remove the graphAPIScopes from loginRedirect call.
// As such, user will be prompted to give consent when requested access to a resource that
// he/she hasn't consented before. In the case of this application -
// the first time the Graph API call to obtain user's profile is executed.
} else {
// If user is already signed in, display the user info
window.location = "calc.html"
}
}
/**
* Callback method from sign-in: if no errors, call callGraphApi() to show results.
* @param {string} errorDesc - If error occur, the error message
* @param {object} token - The token received from login
* @param {object} error - The error string
* @param {string} tokenType - The token type: For loginRedirect, tokenType = "id_token". For acquireTokenRedirect, tokenType:"access_token".
*/
function loginCallback(errorDesc, token, error, tokenType) {
if (errorDesc) {
showError(msal.authority, error, errorDesc);
} else {
callGraphApi();
}
}
/**
* Show an error message in the page
* @param {string} endpoint - the endpoint used for the error message
* @param {string} error - Error string
* @param {string} errorDesc - Error description
*/
function showError(endpoint, error, errorDesc) {
var formattedError = JSON.stringify(error, null, 4);
if (formattedError.length < 3) {
formattedError = error;
}
document.getElementById("errorMessage").innerHTML = "An error has occurred:<br/>Endpoint: " + endpoint + "<br/>Error: " + formattedError + "<br/>" + errorDesc;
console.error(error);
}
/**
* Call a Web API using an access token.
* @param {any} endpoint - Web API endpoint
* @param {any} token - Access token
* @param {object} responseElement - HTML element used to display the results
* @param {object} showTokenElement = HTML element used to display the RAW access token
*/
function callWebApiWithToken(endpoint, token, responseElement, showTokenElement) {
var headers = new Headers();
var bearer = "Bearer " + token;
headers.append("Authorization", bearer);
var options = {
method: "GET",
headers: headers
};
fetch(endpoint, options)
.then(function (response) {
var contentType = response.headers.get("content-type");
if (response.status === 200 && contentType && contentType.indexOf("application/json") !== -1) {
response.json()
.then(function (data) {
// Display response in the page
console.log(data);
responseElement.innerHTML = JSON.stringify(data, null, 4);
if (showTokenElement) {
showTokenElement.parentElement.classList.remove("hidden");
showTokenElement.innerHTML = token;
}
})
.catch(function (error) {
showError(endpoint, error);
});
} else {
response.json()
.then(function (data) {
// Display response as error in the page
showError(endpoint, data);
})
.catch(function (error) {
showError(endpoint, error);
});
}
})
.catch(function (error) {
showError(endpoint, error);
});
}
/**
* Sign-out the user
*/
function signOut() {
userAgentApplication.logout();
}
<!DOCTYPE html>
<html>
<head>
<!-- bootstrap reference used for styling the page -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<title>Home</title>
</head>
<body style="margin: 40px">
<button id="callGraphButton" type="button" class="btn btn-primary" onclick="callGraphApi()">Call Microsoft Graph API</button>
<div id="errorMessage" class="text-danger"></div>
<div class="hidden">
<h3>Graph API Call Response</h3>
<pre class="well" id="graphResponse"></pre>
</div>
<div class="hidden">
<h3>Access Token</h3>
<pre class="well" id="accessToken"></pre>
</div>
<div class="hidden">
<h3>ID Token Claims</h3>
<pre class="well" id="userInfo"></pre>
</div>
<button id="signOutButton" type="button" class="btn btn-primary hidden" onclick="signOut()">Sign out</button>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/0.1.3/js/msal.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script>
<script type="text/javascript" src="msalconfig.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
The page is also connected to an msalconfig file, but I will not include said file for security reasons, since it contains some tokens.
If the user is logged in successfully, he/she is routed to calc.html, a simple caluclator app I've designed for testing purposes only. However, at the moment, anyone could access the calc.html file if they went to the URL. I want a way to only allow signed in users to access the page, as in the end, the project will allow various professors and others at my institution to change the scheudles for their courses over a ten-year period. Is there a way to do this without PHP? If so, what do these ways look like? I would prefer to keep things web based and client side if possible, but am open to anything.
A:
This is quite an open-ended question, but I'll take a stab at it.
First, you state that you're not willing to share msaclconfig.js -- and I quite understand if you don't wish to share it to Stack Overflow. However, you are sharing that file to anyone who happens to load your login page. That could be completely anyone.
For the use case you stated -- multiple people editing and viewing a same set of data -- you will need a server-side component. However, you don't necessarily need to create or host that component yourself. As you're using Microsoft's services for authentication already, maybe you could use their services for data storage as well? For example, the Graph API prominently advertises that it can access Excel, and that might work as storage backend.
If you are using Microsoft's services for both authentication and data storage, non-authorized user loading the application page might not be an issue. They can see the page itself, but thay can't see or edit the schedule -- provided that the permissions to see and edit the backing data storage are suitably set up, of course. This is, of course, a security tradeoff. Seeing the app helps a potential attacker, but this can be acceptable if the server is secure enough.
Similar thing applies to any storage backend you might use. At authentication, some sort of authentication token is generated. This should be something such that only the server is able to generate valid tokens, and that the server can later check that the token it received from client is valid. At every request to data storage, that token is checked, and data is accessed only with a valid token. Seeing the static app page might not be an issue, as the actual sensitive contents are only delivered to authenticated and authorized users.
|
[
"rpg.stackexchange",
"0000050099.txt"
] | Q:
Does Brains over brawn Factotum skill apply for grapple and initiative?
Brains over Brawn states
Brains over Brawn (Ex): At 3rd level, you gain your Intelligence bonus
as a modifier on Strength checks, Dexterity checks, and checks
involving skills based on Strength or Dexterity, such as Hide, Climb,
and Jump.
My master states that maybe I'm over-reading, Rolling Grapple isn't a stregth check. So, community, help us out! =)
I'm almost certain that he's right, I think that for making this valid it should say
Brains over Brawn (Ex): At 3rd level, you gain your Intelligence bonus
as a modifier on Strength-based checks and Dexterity-based checks
So, reiteration here: Brains over brawn Factotum ability applies for grapple and initiative?
A:
Initiative
d20SRD > Combat > Initiative
At the start of a battle, each combatant makes an initiative check. An initiative check is a Dexterity check. Each character...
An initiative check is a Dexterity check, and therefore benefits from Brains Over Brawn. The factotum adds his Intelligence bonus to initiative checks (in addition to his Dexterity bonus and any other bonus that might apply, e.g. Improved Initiative).
Grappling
d20SRD > Combat > Special Attacks > Grapple
Repeatedly in a grapple, you need to make opposed grapple checks against an opponent. A grapple check is like a melee attack roll. Your attack bonus on a grapple check...
A grapple check is like a melee attack roll, which itself is not any kind of ability check but a different sort of roll entirely, so Brains Over Brawn does not apply. Cunning Insight does apply to attack rolls, but even so, a grapple check is only like a melee attack roll, not actually a melee attack roll, so Cunning Insight does not apply to that either. Factota do not gain any ability that adds Intelligence bonus to grapple checks.
|
[
"stackoverflow",
"0031512739.txt"
] | Q:
How to delete row from SQLiteDatabase?
I have a todo app which shows on the mainscreen a list of tasks with ListView. I'm trying to delete a task by clicking on the done button.
But the app is deleting it by the lowest id instead of deleting the task that i tried to delete.
public void onDoneButtonClick(View view) {
ListView listView = (ListView)findViewById(R.id.list);
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
int columnId = cursor.getColumnIndex(BaseColumns._ID);
int id = cursor.getInt(columnId);
Log.d("id", Float.toString(id));
String sql = String.format("DELETE FROM %s WHERE %s = %d",
TaskContract.TABLE,
TaskContract.Columns._ID,
id);
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
updateUI();
Log.d("delete", sql);
}
Can someone help me to solve this?
A:
You can use delete method in SQLiteDatabase:
http://tinyurl.com/ngv2v3n
Edit:
// you must do it after opening database
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.delete(
TaskContract.TABLE, // table
TaskContract.Columns._ID + "=?", // where clause
new String[]{Integer.toString(id)} // where args
);
|
[
"math.stackexchange",
"0002128752.txt"
] | Q:
Convergence of average probability in Markov chain
Let $P$ be a stochastic matrix, and let $v_0$ be a probability vector for the initial distribution. So $v_k=P^kv_0$ is the probability vector for the distribution at time $k$, and $v_{ki}$ is the probability of being in the $i$th state at time $k$.
Is it true that for any fixed $i$, the sequence $$\left(\frac{\sum_{j=1}^kv_{ji}}{k}\right)_{k=1}^\infty$$
converges? Is there a result that guarantees this? I've looked at the Perron-Frobenius theorem, but it doesn't seem to imply anything about this sequence.
Also, if we let $T_k(i,j)$ be the random variable giving the number of transitions from $i$ to $j$ between times $1$ and $k$, then does $T_k(i,j)/k$ converge as well?
A:
This is a consequence / special case of the ergodic theorem for Markov chains. If $N_k(i)$ is the random variable giving the number of visits to $i$ between times $1$ and $k$, the ergodic theorem asserts that $N_k(i)/k$ converges almost surely. Since this ratio is bounded by $1$, the dominated convergence theorem says that its expectation also converges, and that is precisely the quantity you desire. (Let $\chi_j(i) = 1_{\{X_i = j\}}$ be the indicator of the event that we are in state $i$ at time $j$, and note that $N_k(i) = \sum_{j=1}^k \chi_j(i)$; then use linearity of expectation.)
You can see Durrett's Essentials of Stochastic Processes, Theorem 1.9, for an elementary proof, or his Probability: Theory and Examples, Theorem 6.6.1, for a more measure-theoretic argument. These are under the assumption that the chain is irreducible, but you can reduce to that case by writing $v_0$ as a convex combination of vectors supported on irreducible sets, with a little extra work if there are transient states.
|
[
"superuser",
"0000932061.txt"
] | Q:
Nessus on Linux detected SSL version 2 and 3 because of Samba. How to fix it?
We are using Nessus to confirm that our server does not have SSL 2 and 3 supported via any of the ports. We came down to the last product - samba (3.6.25.)
This samba version does not support turning ssl off during Configure and build. It requires changes to smb.conf
The problem we have is that despite ldap ssl = off (and restarting smbd) Nessus keeps discovering SSL23.
We have current run out of ideas and any query to search for a solution fails so far.
Anyone has solved that problem?
A:
At the end, I have goofed. The problem was NOT in SAMBA.
Indeed, ldap ssl = off was doing was it was supposed to do, but an other tool of ours, which was starting and stopping with SAMBA, was using SSL3 as the primary protocol. That is why Nessus was finding it. When we forced using TLS1 the problem disappeared.
Thank you for all your help, and I'm sorry for anyone loosing his/her time reading it, and trying to solve.
Blessings,
Greg.
|
[
"stackoverflow",
"0021968655.txt"
] | Q:
drawing a line between feature points without using "drawmatches" function
I got the feature points from two consecutive by using different detectors in features2d framework:
In the first frame, the feature points are plotted in red
In the next frame, the feature points are plotted in blue
I want to draw a line between these red and blue (matched) points inside the first frame (the image with red dots). drawmatches function in opencv doesn't help as it shows a window with two consecutive frames next to each other for matching. Is it possible in OpenCV?
Thanks in advance
A:
I guess that you want to visualize how each keypoint moves between two frames. According to my knowledge, there is no built-in function in OpenCV meeting your requirement.
However, as you have called the drawMatches() function, you already have the two keypoint sets (take C++ code as example) vector<KeyPoint>& keypoints1, keypoints2 and the matches vector<DMatch>& matches1to2. Then you can get the pixel coordinate of each keypoint from Point keypoints1.pt and draw lines between keypoints by calling the line() function.
You should be careful that since you want to draw keypoints2 in the first frame, the pixel coordinate may exceed the size of img1.
There is a quick way to get a sense of the keypoints' motion. Below is the result shown by imshowpair() in Matlab:
|
[
"astronomy.stackexchange",
"0000030437.txt"
] | Q:
What does the Sun look like from the heliopause?
I calculated the angular diameter of the Sun at the heliopause to be 0.004°. If that is correct, would the Sun appear as a disk, or like the pinpoint of light from a star?
How bright would the light from the Sun appear? I understand at Pluto the Sun appears as bright as the full moon at night on Earth. Assuming the heliopause is 3x distant from the Sun as Pluto, does that mean there would be 1/9th as bright at the heliopause. What would that brightness translate to an everyday measure?
A:
0.004° converts to about 14.4 arc-seconds.
That's within the range typical for Mars; 5-25 arc-seconds.
You'll see the sun as a point with the naked eye.
Heliopause is about 14 billion miles out. Absolute magnitude of sun is 4.83.
14 billion miles = 0.0007297pc.
Apparent magnitude will be -15.8543. Magnitude of the full moon, from earth, is about −12.74
So you'll see a point source of light, brighter than the full moon.
|
[
"stackoverflow",
"0007959622.txt"
] | Q:
How would I add .delegate to this external .autocomplete function?
I just learned about .delegate today, and I know I can be used for what I want but I'm not sure how I would add it here.
Each line when added needs to me able to use .autocomplete they all use the same data.
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$('#field1').val("");
$('#field2').val("");
$('#field3').val("");
$('#field4').val("");
$("#field1").autocomplete({
source: "PRODUCT.ORDER.QUERY.php",
minLength: 2,
autoFocus: true,
select: function(event, ui) {
$('#field1').val(ui.item.field1);
$('#field2').val(ui.item.field2);
$('#field3').val(ui.item.field3);
$('#field4').val(ui.item.field4);
}
});
});
</script>
</head>
<body>
<button id="removeAll">Delete All</button>
<button id="addLine">New Line</button>
<hr>
<form action="<?php echo $PHP_SELF;?>" method="post" id="orderform">
<table width="90%" border="0" cellspacing="2" cellpadding="2">
<tr>
<td>FIELD 1</td>
<td>FIELD 2</td>
<td>FIELD 3</td>
<td>FIELD 4</td>
<td>QTY</td>
</tr>
</table> <hr>
<div id="orderForm">
<table class="orderLine" width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input name="field1" type="text" id="field1" size="15" tabindex="1"></td>
<td><input name="field2" type="text" id="field2" size="15"></td>
<td><input name="field3" type="text" id="field3" size="15"></td>
<td><input name="field4" type="text" id="field4" size="15"></td>
<td><input name="qty" type="text" id="qty" size="15" tabindex="2"></td>
<td><button class="removeLine">Delete</button></td>
</tr>
</table>
</div>
</form>
<!-- START OF THE JQUERY FUNCTION THAT ADDS THE NEW ORDER LINE -->
<script type="text/javascript">
$("#orderForm").delegate(".removeLine", "click", function () {
$(this).closest('.orderLine').remove();
});
<!-- This removes all newLine table rows -->
$("#removeAll").click(function () {
$('.orderLine').remove();
});
<!-- ADDS the 'newLine' table rows -->
$("#addLine").click(function () {
$('#orderForm').append('<table class="orderLine" width="90%" border="0" cellspacing="0" cellpadding="0"><tr><td><input name="field1" type="text" id="field1" size="15" tabindex="1"></td><td><input name="field2" type="text" id="field2" size="15"></td><td><input name="field3" type="text" id="field3" size="15"></td><td><input name="field4" type="text" id="field4" size="15"></td><td><input name="qty" type="text" id="qty" size="15" tabindex="2"></td><td><button class="removeLine">Delete</button></td></tr></table>');
});
</script>
</body>
</html>
Working 1/2 wayish. Not I can use the .autocomplete again but its not right. I populates all the fields again.
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$('.field1').val("");
$('.field2').val("");
$('.field3').val("");
$('.field4').val("");
$("body").delegate(".field1:not(:ui-autocomplete)","focus",function(){
$(this).autocomplete({
source: "PRODUCT.ORDER.QUERY.php",
minLength: 2,
autoFocus: true,
select: function(event, ui) {
$('.field1').val(ui.item.field1);
$('.field2').val(ui.item.field2);
$('.field3').val(ui.item.field3);
$('.field4').val(ui.item.field4);
}
});
});
});
</script>
</head>
<body>
<button id="removeAll">Delete All</button>
<button id="addLine">New Line</button>
<hr>
<form action="<?php echo $PHP_SELF;?>" method="post" id="orderform">
<table width="90%" border="0" cellspacing="2" cellpadding="2">
<tr>
<td>FIELD 1</td>
<td>FIELD 2</td>
<td>FIELD 3</td>
<td>FIELD 4</td>
<td>QTY</td>
</tr>
</table> <hr>
<div id="orderForm">
<table class="orderLine" width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input class="field1" type="text" size="15" tabindex="1"></td>
<td><input class="field2" type="text" size="15"></td>
<td><input class="field3" type="text" size="15"></td>
<td><input class="field4" type="text" size="15"></td>
<td><input class="qty" type="text" size="15" tabindex="2"></td>
<td><button class="removeLine">Delete</button></td>
</tr>
</table>
</div>
</form>
<!-- START OF THE JQUERY FUNCTION THAT ADDS THE NEW ORDER LINE -->
<script type="text/javascript">
$("#orderForm").delegate(".removeLine", "click", function () {
$(this).closest('.orderLine').remove();
});
<!-- This removes all newLine table rows -->
$("#removeAll").click(function () {
$('.orderLine').remove();
});
<!-- ADDS the 'newLine' table rows -->
$("#addLine").click(function () {
$('#orderForm').append('<table class="orderLine" width="90%" border="0" cellspacing="0" cellpadding="0"><tr><td><input class="field1" type="text" size="15" tabindex="1"></td><td><input class="field2" type="text" size="15"></td><td><input class="field3" type="text" size="15"></td><td><input class="field4" type="text" size="15"></td><td><input class="qty" type="text" size="15" tabindex="2"></td><td><button class="removeLine">Delete</button></td></tr></table>');
});
</script>
</body>
</html>
WORKING EXAMPLE!
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$('.field1').val("");
$('.field2').val("");
$('.field3').val("");
$('.field4').val("");
$("body").delegate(".field1:not(:ui-autocomplete)","focus",function(){
$(this).autocomplete({
source: "PRODUCT.ORDER.QUERY.php",
minLength: 2,
autoFocus: true,
select: function(event, ui) {
$(this).closest('tr').find('.field1').val(ui.item.field1);
$(this).closest('tr').find('.field2').val(ui.item.field2);
$(this).closest('tr').find('.field3').val(ui.item.field3);
$(this).closest('tr').find('.field4').val(ui.item.field4);
}
});
});
});
</script>
</head>
<body>
<button id="removeAll">Delete All</button>
<button id="addLine">New Line</button>
<hr>
<form action="<?php echo $PHP_SELF;?>" method="post" id="orderform">
<table width="90%" border="0" cellspacing="2" cellpadding="2">
<tr>
<td>FIELD 1</td>
<td>FIELD 2</td>
<td>FIELD 3</td>
<td>FIELD 4</td>
<td>QTY</td>
</tr>
</table> <hr>
<div id="orderForm">
<table class="orderLine" width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input class="field1" type="text" size="15" tabindex="1"></td>
<td><input class="field2" type="text" size="15"></td>
<td><input class="field3" type="text" size="15"></td>
<td><input class="field4" type="text" size="15"></td>
<td><input class="qty" type="text" size="15" tabindex="2"></td>
<td><button class="removeLine">Delete</button></td>
</tr>
</table>
</div>
</form>
<!-- START OF THE JQUERY FUNCTION THAT ADDS THE NEW ORDER LINE -->
<script type="text/javascript">
$("#orderForm").delegate(".removeLine", "click", function () {
$(this).closest('.orderLine').remove();
});
<!-- This removes all newLine table rows -->
$("#removeAll").click(function () {
$('.orderLine').remove();
});
<!-- ADDS the 'newLine' table rows -->
$("#addLine").click(function () {
$('#orderForm').append('<table class="orderLine" width="90%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><input class="field1" type="text" size="15" tabindex="1"></td> <td><input class="field2" type="text" size="15"></td> <td><input class="field3" type="text" size="15"></td> <td><input class="field4" type="text" size="15"></td> <td><input class="qty" type="text" size="15" tabindex="2"></td> <td><button class="removeLine">Delete</button></td> </tr></table>');
});
</script>
</body>
</html>
A:
Assuming the fields have a class of "field", something like this should work.
$("body").delegate(".field:not(:ui-autocomplete)","focus",function(){
$(this).autocomplete(options);
});
Edit: I didn't realize that there was more to the code, so i didn't see the html below. Thank roselan for pointing that out. The duplicate ID issue will definitly be a problem, but the delegate code I posted should be a good starting point to figure out how to dynamically apply a plugin to an element that gets added with ajax. After that you just have to overcome the duplicate id issue.
Edit in response to comment:
This line and similar lines
$('.field1').val(ui.item.field1);
needs to be
$(this).closest('tr').find('.field1').val(ui.item.field1);
$(this).closest('tr').find('.field2').val(ui.item.field2);
$(this).closest('tr').find('.field3').val(ui.item.field3);
$(this).closest('tr').find('.field4').val(ui.item.field4);
Edit: Adding some optimization:
var $tr = $(this).closest('tr');
$tr.find('.field1').val(ui.item.field1);
$tr.find('.field2').val(ui.item.field2);
$tr.find('.field3').val(ui.item.field3);
$tr.find('.field4').val(ui.item.field4);
|
[
"stackoverflow",
"0005908987.txt"
] | Q:
How to remove div tag content?
How can I remove the content of a div tag using JavaScript?
I have tried some code, but it only removes the level1 div (and of course all o it childern), but how can I remove only the content in level3 inside?
function destroyDiv() {
var div = document.getElementById("level1");
div.parentNode.removeChild(div);
}
<div id="level1">
<div id="level2">
<div id="level3">
<label> Test content </label>
</div>
</div </div>
<div id=blahDiv>Remove me</div>
<input type=button value='Remove the div' onclick='destroyDiv()'>
A:
This sould work document.getElementById("level3").innerHTML = ''; but try thinking about using jQuery, because .innerHTML implementation differs in some browsers. jQuery would look like $('#level3').html('');
A:
Why don't you access directly level3 ?
document.getElementById("level3").innerHTML = "";
|
[
"stackoverflow",
"0047921209.txt"
] | Q:
add date to the tablename on oracle using php
I'm trying to backup a table from oracle using php, and the table name should be new table_20171221. The date must insert current date when the table backup.
$date=date('Ymd');include("koneksi.php");
$query= 'CREATE TABLE new_table_`$date` AS SELECT * FROM old_table';
$statemen=oci_parse($c, $query);
oci_execute($statemen, OCI_DEFAULT);
oci_commit($c);
and the error messages :
Warning: oci_execute(): ORA-00911: invalid character in
C:\xampp\htdocs\import_excel_v\create_table.php on line 7
and is there any way that can insert a current date after new_table?
A:
Your problem is that the variable is not concatinated,
This should fix it
$query= 'CREATE TABLE new_table_'.$date.'AS SELECT * FROM old_table';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.