text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
JTable + MySQL "Realtime Feeling"
I have a JTable that get's populated with data from a MySQL Table, but there are multiple Clients updating and inserting to the Database at once. My Goal is to provide some kind of near realtime experience for the Table. I thought of just updating the TableModel every let's say 5 seconds, but with over 1000 rows that doesn't really make sense. Could someone explain me how the general approach to something like this looks or which techniques i should be using,
Thanks in advance,
Stefan
A:
You'd need to go for a 3 tier architecture:
Between swing clients and MySql database put an application server.
The clients will not connect directly to the database, instead they'll connect to the application server which will provide higher level APIs (e.g. business logic methods) to get the data from the DB.
As for data refresh in clients, you could use something like JMS to push events to the clients when data changes.
If you don't have control of the other clients that change the data you'll have to use some kind of polling.
| {
"pile_set_name": "StackExchange"
} |
Q:
explain this javascript construct please
I am not too familiar with javascript. Can someone please explain this construct to me?
[{a:"asdfas"},{a:"ghdfh",i:54},{i:76,j:578}]
What does this construct declare? I can see that this is an array that consists of 3 elements, right? And every element in this array is a class, which is declared in JSON format, isn't it? And I do not need to use any scripts to use JSON, do I?
A:
This declares an array of 3 objects. The first object of this array contains one string property a = "asdfas". The second object in the array contains two properties a = "ghdfh" and i = 54. And the last object contains two numeric properties a = 76 and j = 578. So this represents a javascript object and you don't need to declare any scripts to use it:
var array = [ { a: "asdfas" },
{ a: "ghdfh", i: 54 },
{ i: 76, j: 578 }
];
alert(array[1].i); // prints the i property of the second item in the array: 54
A:
It's simply an array composed of 3 elements. Each element is an object. The first one has the a key with associated 'asdfas' value. The second one i key with 54 value etc etc
it could be built in this way :
var arr = []; //[] <= array
var first = {}; // {} <= object
first.a = "asdfas"; // object.key = value, same by doing var first = {a:"asdfas"}
arr.push(first); //pushing an object inside the array
//arr status: [{a:"asdfas"}]
var second = {};
second.a = "ghdfh";
second.i = 54;
arr.push(second);
//arr status: [{a:"asdfas"},{a:"ghdfh",i:54}]
var third = {};
third.i = 76;
third.j = 578;
arr.push(third);
//arr status: [{a:"asdfas"},{a:"ghdfh",i:54},{i:76,j:578}]
alert(arr[2].j) //third element of the array => object => key j => alerts j value 578
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I have separate application pools for Service Applications?
So I've looked high and low for a best-practice, and a practical practice to this: Should I separate each of my service applications in a SharePoint 2010 installation into different application pools?
In my particular instance, we'll be starting off with only a 2 server installation (1 SQL server, all SP services running on a second server), and will only be deploying Excel, PerformancePoint, User Profiles, Search, BDC, and maybe Visio. However, additional service apps and additional servers (and possibly farms for geography) may be added later as our deployment & usage of SharePoint expands.
I feel that having separate AppPools & AppPools accounts would be overkill, even if it follows least privileged principals. Maybe separate pools for each Application Proxy Group?
What are your guys thoughts on the topic?
(NB. I will be separating each of my web applications into their own application pool.)
A:
The generally held view is that Service Applications can happily co-exist in a single Application Pool for a small server farm like you have suggested. As you scale out your farm you should carefully consider the app pool architecture.
If you try to put all your service applications into seperate application pools as well as all your web applications and consider the other app pools that are configured by the install then you will need som beefed up RAM on that box which is definitely overkill.
Scale approriately is the key.
Any 'Best Practice' for SharePoint 2010 should be taken with a large pinch of the white stuff for at least the next 6 months (if you know what I mean.)
| {
"pile_set_name": "StackExchange"
} |
Q:
multiple bar charts with dual y axis in objective c
I want to generate bar chart with dual y axis. I tried like this
-(void)loadGraph
{
_barColors = @[[UIColor cyanColor]];
_currentBarColor = 0;
// CGRect chartFrame = CGRectMake(0.0,
// 0.0,
// 300,
// 300.0);
CGRect chartFrame = CGRectMake(60,128-20,self.view.frame.size.width-40-40,180);//728//1024
_chart = [[SimpleBarChart alloc] initWithFrame:chartFrame];
//_chart.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
_chart.delegate = self;
_chart.dataSource = self;
_chart.barShadowOffset = CGSizeMake(2.0, 1.0);
_chart.animationDuration = 1.0;
_chart.barShadowColor = [UIColor clearColor];
_chart.barShadowAlpha = 0.5;
_chart.barShadowRadius = 1.0;
_chart.barWidth = 30.0;
_chart.xLabelType = SimpleBarChartXLabelTypeHorizontal;//SimpleBarChartXLabelTypeVerticle;
_chart.incrementValue = 10;
_chart.barTextType = SimpleBarChartBarTextTypeTop;
_chart.barTextColor = [UIColor blackColor];
//
_chart.gridColor = [UIColor clearColor];
//
[scroll addSubview:_chart];
[_chart reloadData];
I'm getting only one single axis without y axis values. Can any one help? I want to draw bar graph with dual y axis with values.
Thanks in advance.
A:
Try this graph if your value is negative it will show you dual y axis.
https://github.com/chasseurmic/TWRCharts
| {
"pile_set_name": "StackExchange"
} |
Q:
Could not convert javascript argument
After trying to append some code to a div layer I received the following error and don't know why.
uncaught exception: [Exception... "Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://code.jquery.com/jquery-latest.min.js :: anonymous :: line 113" data: no]
Below is the code that is causing the error. I understand there is some excessive code but I made it that way so it would be easy to build on for future features. Just looking for any suggestions for the error? Thank You! :)
function catSelect(itm){
//params for query
var params = {
category: itm
};
var cmd = jQuery.param(params);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "views/gallery.php",
data: cmd,
dataType: "json",
success: function(resp){
if(resp.status == "ok") {
$('#project').empty();
//alert(resp.projects[0]);alert(resp.files[0]); alert(resp.titles[0]);
var check = 0;
var projGallery = new Array();
for(var i in resp.projects){
if(check!=resp.projects[i] || check == 0){
projGallery[i] ='<a class="group" title="'+resp.titles[i]+'" href="images/gallery/"'+resp.files[i]+'" rel="'+resp.projects[i]+'" ><img class="group" alt="" src="../images/gallery/thumbs/"'+resp.files[i]+'"/></a>';
} else {
projGallery[i] ='<a class="group" rel="'+resp.projects[i]+'" href="images/gallery/"'+resp.files[i]+'" title="'+resp.titles[i]+'"></a>';
}
check = resp.projects[i];
}
//alert(projGallery[0]);
alert(projGallery);
$('#project').append(projGallery);
} else {
alert("Failed to select projects");
}
}
});
}
A:
I don't think you can append an array.
Change:
$('#project').append(projGallery);
To:
$.each(projGallery, function(idx, val) {
$('#project').append(val);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
What do people mean when they say "ancestor" with regards to git?
I've seen it talked about a lot but when I google'd for the meaning I could not find it. What's an ancestor?
I'm guessing an ancestor of branch x is any parent, grand parent, grand grand parent etc of the branch?
So if branch x branched from master, and branch y branched from x, and branch z branched from y, then z's ancestors are y, x and master? Just taking a guess.
A:
The term ancestor was first introduced in April 2005 for merge-base (replacing "parent"), explained one month later:
merge-base finds as good a common ancestor as possible.
Given a selection of equally good common ancestors it should not be relied on
to decide in any particular way.
"parent" was seen as an immediate ancestor, while a merge-base algorithm needed to go back further than that.
As mentioned in commit f76412e:
Parent is the first parent of the commit.
We may name it as (n+1)th generation ancestor of the same head_rev as commit is nth generation ancestor of, if that generation number is better than the name it already has.
In August 2005, the first ancestor notation was introduced:
[PATCH] Add a new extended SHA1 syntax ~
The new notation is a short-hand for <name> followed by <num> caret ('^') characters.
E.g. "master~4" is the fourth generation ancestor of the current "master" branch head, following the first parents; same as "master^^^^" but a bit more readable.
z's ancestors are any commit reachable from z HEAD.
The term "reachable" was clarified in 2007:
reachable:
All of the ancestors of a given commit are said to be reachable from that commit.
More generally, one object is reachable from another if we can reach the one from the other by a chain that follows tags to whatever they tag, commits to their parents or trees, and trees to the trees or blobs that they contain.
That lead to revise the notion of distance between two commits:
When a commit has only one relevant parent commit, the number of commits the commit can reach is exactly the number of commits that the parent can reach plus one; instead of running count_distance() on commits that are on straight single strand of pearls, we can just add one to the parents' count.
On the other hand, for a merge commit, because the commits reachable from one parent can be reachable from another parent, you cannot just add the parents' counts up plus one for the commit itself; that would overcount ancestors that are reachable from more than one parents.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pass arguments to already running nsis java launcher
Am using nsis for launching my java application. I wanted to show a window once the application is launched. I can pass a command line argument while launching the java application like this.
OutFile "Test.exe"
....
ExecWait javaw.exe -jar myapp.jar
SectionEnd
Now I would like to show the default window of the already running java application if another instance of the nsis launcher is invoked. In order to do this I need to pass an argument to my java application. For this to happen I have to pass the argument to the cmd window(internally used by NSIS) of the already running instance.
How would I accomplish this?
A:
I'm not sure I understand you correctly but you can use this example to create a mutex for the nsis installer. The example there will bring to front the already running installer, you can change it a bit to bring to front the running java window, if you know its handle or title.
System::Call "kernel32::CreateMutexA(i 0, i 0, t 'my_mutex') i .r0 ?e"
Pop $0
StrCmp $0 0 launch
FindWindow $1 "my window class" "my window title"
IntCmp $1 0 bring_front end
bring_front:
System::Call "user32::SetForegroundWindow(i r1) i."
end:
Abort
launch:
If you have Spy++ (which comes with Microsoft Visual Studio) you can find the window class of your java app.
| {
"pile_set_name": "StackExchange"
} |
Q:
evaluate series and express sum with harmonic numbers
I've computed the series but have had trouble expressing the sum in harmonic numbers
For $M\geq1$ compute the sum of the series below at $x=\dfrac{1}{\sqrt{M}}$ and express the sum in harmonic numbers. e.g $3H + H $ where
$3H=3\sum_{k=1}^{n}\dfrac{1}{k}$
$$ \sum_{n=1}^\infty \dfrac{x}{n(1+x^2n)}$$
A:
Substitute $x=\frac{1}{\sqrt{m}}$ into the sum & do partial fractions
\begin{eqnarray*}
\sum_{n=1}^{\infty} \frac{\frac{1}{\sqrt{M}}}{n(1+\frac{n}{M})}=\sqrt{M} \sum_{n=1}^{\infty} \frac{1}{n(n+M)} = \frac{1}{\sqrt{M}}\sum_{n=1}^{\infty} \left( \frac{1}{n} -\frac{1}{n+M} \right) =\color{red}{ \frac{H_M}{\sqrt{M}}}.
\end{eqnarray*}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to move all images into one group in xcode
All images and header files are looking very confusing. So i want to separate all images and other files into different groups. Anyone please help me
A:
To organize your files on disk, simply make the folders you want to make in the Finder and drag the files to them. To do this, open the folder containing your .xcodeproj file in the Finder. Use Cmd-Shift-N to create a new folder or choose "New Folder" from the "File" menu. You'll be prompted to give the folder a name. You'll probably want to name it something like "Images" or "Headers". Once the folder is created, you can simply click on an image file and drag it to the "Images" folder (or whatever you named it). Repeat the process for any files you want to move.
Once you've done the above, the files may display as red in Xcode's Project Navigator. If that's the case, you need to select the file in Xcode's Project Navigator and show the "Utilities" pane (the right-most button in the toolbar opens and closes the Utilities pane). There are 2 tabs in the Utilities pane - the File Inspector and Quick Help. Click on the File Inspector. It should display the name of your file, the type, and the location. Next to the "Location" is an icon of a folder. Click on the folder and you'll be presented with a file navigation dialog. Navigate to the new location of the file and select it. Click the "Choose" button and the file will be re-connected in Xcode.
You may need to repeat the process for any files you moved into new folders.
| {
"pile_set_name": "StackExchange"
} |
Q:
iPhone base64 corrupted when posted to php script
In my app the user crops there picture i encode it to a base64 string and send it to my php script.I am using the NSData+base64 class However, when the app goes to retrieve the string again to convert back into a picture I get this error:
Jan 8 14:21:33 Vessel.local Topic[11039] <Error>: ImageIO: JPEG Corrupt JPEG data:214 extraneous bytes before marker 0x68 Jan 8 14:21:33 Vessel.local Topic[11039] <Error>: ImageIO: JPEG Unsupported marker type 0x68
Here is the code in which i send off the data:
NSString *urlString = [NSString stringWithFormat:@"http://myurl.php"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];
NSString *param = [NSString stringWithFormat:@"username=%@&password=%@&email=%@"e=%@&pic=%@",user,password,email,quote,pic];
[request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
Here is when i get it back in another view controller and attempt to turn it back into a image
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
homeData = [NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];
NSString *decodeString = [[homeData objectAtIndex:0]objectForKey:@"profile_pic" ];
decodeString = [decodeString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
int returnNUM = [decodeString length];
NSLog(@"RETURN STRING=%d",returnNUM);
NSData *data = [[NSData alloc] initWithData:[NSData dataFromBase64String:decodeString]];
profilepic = [[UIImageView alloc]initWithFrame:CGRectMake(5, 4, 120, 120)];
profilepic.image = [UIImage imageWithData:data];
UIGraphicsBeginImageContextWithOptions(profilepic.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:profilepic.bounds cornerRadius:80.0] addClip];
[pic drawInRect:profilepic.bounds];
profilepic.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.view addSubview:profilepic];
}
How can i prevent the image from being corrupted once i post it..or once i get it back how can i clean it or prevent the corruption thats happening! This is driving me nuts..a clear answer with some code would be highly appreciated.Thanks
This is the code that I use to convert the image into base64 before i send it.
NSData *imageData = UIImageJPEGRepresentation(crop, 1.0);
NSString *baseString = [imageData base64EncodedString];
int original =[baseString length];
NSLog(@"orignal String=%d",original);
[self register:username.text withPass:password.text withEmail:email.text withQuote:quote.text withPic:baseString];
A:
Why are you doing the "stringByTrimmingCharactersInSet" call? That would seem to me to remove characters that the encoded image probably needs...
Edit to include example from some code I'm using which correctly embeds a couple images into a http form to be submitted to a php page.
I use the following Category on NSMutableData...
The following goes inside NSMutableData+HTTP.h
@interface NSMutableData (HTTP)
-(void)appendFileAtPath:(NSString*)fullFilePath withFormKey:(NSString*)formKey withSuggestedFileName:(NSString*)suggestedFileName boundary:(NSData*)boundary;
-(void)appendKey:(NSString*)key value:(NSString*)value boundary:(NSData*)boundary;
@end
The following goes inside NSMutableData+HTTP.m
#import "NSMutableData+HTTP.h"
@implementation NSMutableData (HTTP)
//use for attaching a file to the http data to be posted
-(void)appendFileAtPath:(NSString*)fullFilePath withFormKey:(NSString*)formKey withSuggestedFileName:(NSString*)suggestedFileName boundary:(NSData*)boundary{
[self appendData:boundary];
[self appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", formKey, suggestedFileName] dataUsingEncoding:NSUTF8StringEncoding]];
[self appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[self appendData:[NSData dataWithContentsOfFile:fullFilePath]];
[self appendData:[@"Content-Encoding: gzip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[self appendData:boundary];
}
//use for attaching a key value pair to the http data to be posted
-(void)appendKey:(NSString*)key value:(NSString*)value boundary:(NSData*)boundary{
[self appendData:boundary];
[self appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[self appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
[self appendData:boundary];
}
@end
Then in my code that creates an http form submission I do the following to attach a couple images and key-value pairs (via the category methods above) to the form... (Note: I have not included the NSURLConnectionDelegate methods that you'll need to implement if you want to track the progress of the form submission.)
NSString *boundaryString = @"0xKhTmLbOuNdArY";
NSData *boundaryData = [[NSString stringWithFormat:@"\r\n--%@\r\n", boundaryString] dataUsingEncoding:NSUTF8StringEncoding];
NSString *phpReceiverURL = @"http://www.someurl.com/somephppage.php";
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setTimeoutInterval:30];
[theRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[theRequest setHTTPShouldHandleCookies:NO];
[theRequest setURL:[NSURL URLWithString:phpReceiverURL]];
[theRequest setHTTPMethod:@"POST"];
[theRequest addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundaryString] forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
//add some image files to the form
[body appendFileAtPath:[imagePath stringByAppendingPathComponent:@"cat.jpg"]
withFormKey:@"cat"
withSuggestedFileName:@"received-cat.jpg"
boundary:boundaryData
];
[body appendFileAtPath:[imagePath stringByAppendingPathComponent:@"dog.jpg"]
withFormKey:@"dog"
withSuggestedFileName:@"received-dog.jpg"
boundary:boundaryData
];
//add some key value pairs to the form
[body appendKey:@"testkeyone" value:@"testvalueone" boundary:boundaryData];
[body appendKey:@"testkeytwo" value:@"testvaluetwo" boundary:boundaryData];
// setting the body of the post to the reqeust
[theRequest setHTTPBody:body];
//create the connection
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
Also note I haven't tested this outside of my app so I may have forgotten something (such as "imagePath" which I haven't defined in the example above - you'll have to specify a path for your images), but it should give you a good idea of how to attach some images to a form to be submitted to a php page.
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
cmake clang-tidy (or other script) as custom target
I am trying to create a custom cmake target for clang-tidy, to lint my project. The source folder looks something like this:
src/scripts/run-clang-tidy.py
src/.clang-tidy
src/...
So far my plan was to copy both these files to the build directory with a custom command:
add_custom_command(
OUTPUT run-clang-tidy.py .clang-tidy
COMMAND cp ${CMAKE_SOURCE_DIR}/scripts/run-clang-tidy.py ${CMAKE_SOURCE_DIR}/.clang-tidy ${CMAKE_CURRENT_BINARY_DIR})
I now want to call run-clang-tidy.py in the build directory (which should be the working directory), with a custom target, so that I can just call:
make lint
Which should run the checks specified in .clang-tidy.
For this script to work, it also needs the CMAKE_EXPORT_COMPILE_COMMANDS option. I try to set it with the following command, but it does not recognize it:
add_definitions(-DCMAKE_EXPORT_COMPILE_COMMANDS=ON)
How would the call to add_custom_target look like?
A:
Since CMake 3.6, native integration of clang-tidy is implemented [1, 2]. Mechanics are similar to include-what-you-use integration that was there since CMake 3.3 [3].
A:
I can suggest another way to do, which do not require an extra Python script.
First of all, I wanted to integrate clang-tidy and clang-format in custom CMake rules, so I first generated .clang-tidy and .clang-format files which were located at the root directory of the project.
Generating the configuration files
To generate .clang-tidy, first find the suitable options for your project and then, just do:
$> clang-tidy <source-files> -dump-config <tidy-options> -- <compile-options> > .clang-tidy
Similarly for clang-format you may start with a default style using the -style=xxx option, and dump it. For example, starting with the LLVM style:
$> clang-format -style=LLVM -dump-config > .clang-format
Then, edit it and configure it properly as you wish. It should looks like that:
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: true
AlignEscapedNewlinesLeft: false
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AlwaysBreakAfterDefinitionReturnType: false
AlwaysBreakTemplateDeclarations: false
AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BinPackParameters: true
BinPackArguments: true
ColumnLimit: 80
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
DerivePointerAlignment: false
ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: false
IndentWrappedFunctionNames: false
IndentFunctionDeclarationAfterType: false
MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: true
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakString: 1000
PenaltyBreakFirstLessLess: 120
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
SpacesBeforeTrailingComments: 1
Cpp11BracedListStyle: true
Standard: Cpp11
IndentWidth: 2
TabWidth: 8
UseTab: Never
BreakBeforeBraces: Attach
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpacesInAngles: false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
SpaceAfterCStyleCast: false
SpacesInContainerLiterals: true
SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4
CommentPragmas: '^ IWYU pragma:'
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
SpaceBeforeParens: ControlStatements
DisableFormat: false
...
Creating the custom CMake rule
CMake allow to define custom rules in a very simple way, you just have to write a set of CMake commands in a file with a call to the add_custom_target() procedure and, then, include it in your CMakeList.txt file. This is what we will do, we first create a cmake/clang-dev-tools.cmake file at the root of your project:
# Additional target to perform clang-format/clang-tidy run
# Requires clang-format and clang-tidy
# Get all project files
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.hpp)
add_custom_target(
clang-format
COMMAND /usr/bin/clang-format
-style=file
-i
${ALL_SOURCE_FILES}
)
add_custom_target(
clang-tidy
COMMAND /usr/bin/clang-tidy
${ALL_SOURCE_FILES}
-config=''
--
-std=c++11
${INCLUDE_DIRECTORIES}
)
Then, edit you CMakeLists.txt and add:
# Including extra cmake rules
include(cmake/clang-dev-tools.cmake)
Then, once the build-system regenerated, you should be able to run make clang-tidy and make clang-format.
A:
The documentation mentioned by Alexander Shukaev is a bit short on details, so I'm adding an example. The formatting of the warning strings makes IDEs think the clang-tidy results are compiler warnings and will mark the source code. Also, it runs each file in parallel after its object file has been created.
if ( CMAKE_VERSION GREATER "3.5" )
set(ENABLE_CLANG_TIDY OFF CACHE BOOL "Add clang-tidy automatically to builds")
if (ENABLE_CLANG_TIDY)
find_program (CLANG_TIDY_EXE NAMES "clang-tidy" PATHS /usr/local/opt/llvm/bin )
if (CLANG_TIDY_EXE)
message(STATUS "clang-tidy found: ${CLANG_TIDY_EXE}")
set(CLANG_TIDY_CHECKS "-*,modernize-*")
set(CMAKE_CXX_CLANG_TIDY "${CLANG_TIDY_EXE};-checks=${CLANG_TIDY_CHECKS};-header-filter='${CMAKE_SOURCE_DIR}/*'"
CACHE STRING "" FORCE)
else()
message(AUTHOR_WARNING "clang-tidy not found!")
set(CMAKE_CXX_CLANG_TIDY "" CACHE STRING "" FORCE) # delete it
endif()
endif()
endif()
The only problems I've had with this is that it still checks automatically generated moc_*.cxx files and the usual annoyances of warnings from code in an ExternalProject.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to call different associated resource variables in their controllers?
I am a beginner learning Ruby on Rails. Apologies if this question is very obvious...
I have two resources:
books and book_pages
A book has several pages and I have set up the belongs_to and has_many associations within the models. In the controller for book pages, how do I create a new book_page under this association? I currently have:
class BookPagesController < ApplicationController
...
def new
@book_page = BookPage.new
end
end
...
Also, how would I need to set up the corresponding view to create a new page?
A:
Generally speaking, you would need to use a code like this:
book = Book.find(book_id)
book.book_pages.create(page_number: 1, footnote: "yey")
But note that you need to have the book id somehow in your request.
I strongly advise you to stop muddling through and read the rails guides, because rails uses convention over configuration which can be very confusing if you are not up to read the documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I use Target-specific Variable Values and call other rules whilst using parallel execution?
I have a makefile with the following lines:
debug: CFLAGS += $(DEBUGFLAGS)
debug: clean all
What I want to do is run 'clean' and 'all' with the Target Specific Variable values. This works fine and as expected.
But if I ran this with parallel execution 'clean' might destroy the files being create by 'all'.
So if I do something like the following:
debug: CFLAGS += $(DEBUGFLAGS)
debug:
$(MAKE) clean
$(MAKE) all
This will ensure that the order of the rules is respected. But the Target Specific Variables will not be taken into the new invocations of make.
So I was wondering how I can use both Target Specific Variables and parallel execution.
A:
Why not just pass through the values as well?
debug: CFLAGS += $(DEBUGFLAGS)
debug:
$(MAKE) clean CFLAGS='$(CFLAGS)'
$(MAKE) all CFLAGS='$(CFLAGS)'
| {
"pile_set_name": "StackExchange"
} |
Q:
Shoot bullet from player
So I wanted to add a shoot option to my game but at the moment when I press the spacebar, the bullet spawns in where the player is, and that's about it, it doesn't move, it just sits there, I'm new to pygame in particular so I'm not quite sure.
Please say if you need any more context than this
Heres The code:
import pygame
import random
from pygame.locals import(
RLEACCEL,
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
K_w,
K_a,
K_s,
K_d,
K_0,
K_9,
K_SPACE,
KEYDOWN,
QUIT
)
pygame.init()
pygame.joystick.init()
pygame.mixer.init()
pygame.display.set_caption("Dodge The Missile (ALPHA 0.11)")
SCREEN_WIDTH = 1600
SCREEN_HEIGHT = 1000
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super(Enemy, self).__init__()
self.surf = pygame.image.load("Missiles.png").convert()
self.surf.set_colorkey((255,255,255), RLEACCEL)
self.rect = self.surf.get_rect(
center=(
random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
random.randint(0, SCREEN_HEIGHT),
)
)
self.speed = random.randint(Enemy_SPEED_Min, Enemy_SPEED_Max)
def update(self):
self.rect.move_ip(-self.speed, 0)
if self.rect.right < 0:
self.kill()
class Player(pygame.sprite.Sprite):
def __init__(self):
super(Player, self).__init__()
self.surf = pygame.image.load("Spaceship.png").convert()
self.surf.set_colorkey((255,255,255), RLEACCEL)
self.rect = self.surf.get_rect()
self.layers = 1
def update(self, pressed_keys):
if pressed_keys[K_UP] or pressed_keys[K_w]:
self.rect.move_ip(0, -5)
if pressed_keys[K_DOWN] or pressed_keys[K_s]:
self.rect.move_ip(0, 5)
if pressed_keys[K_LEFT] or pressed_keys[K_a]:
self.rect.move_ip(-5, 0)
if pressed_keys[K_RIGHT] or pressed_keys[K_d]:
self.rect.move_ip(5, 0)
if self.rect.left < 0:
self.rect.left = 0
if self.rect.right > SCREEN_WIDTH:
self.rect.right = SCREEN_WIDTH
if self.rect.top <= 0:
self.rect.top = 0
if self.rect.bottom >= SCREEN_HEIGHT:
self.rect.bottom = SCREEN_HEIGHT
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
class Cloud(pygame.sprite.Sprite):
def __init__(self):
super(Cloud, self).__init__()
self.surf = pygame.image.load("Cloud.png").convert()
self.surf.set_colorkey((255,255,255), RLEACCEL)
self.layers = 3
self.rect = self.surf.get_rect(
center=(
random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
random.randint(0, SCREEN_HEIGHT)
)
)
def update(self):
self.rect.move_ip(-5, 0)
if self.rect.right < 0:
self.kill()
class Bullet (pygame.sprite.Sprite):
def __init__ (self, x, y):
super (Bullet, self).__init__()
self.surf = pygame.image.load("Bullet.png").convert()
self.surf.set_colorkey((255,255,255), RLEACCEL)
self.rect = self.surf.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedx = 5
def update(self):
self.rect.x += self.speedx
if self.rect.left > SCREEN_WIDTH:
self.kill()
class AddEnemyTimer():
def __init__(self, Generate_Enemy_Timer, Generate_Cloud_Timer):
self.Generate_Enemy_Timer = Generate_Enemy_Timer
self.Generate_Cloud_Timer = Generate_Cloud_Timer
class Game_Speed_Class():
def __init__(self, Game_Speed):
self.Game_Speed = Game_Speed
class Enemy_Speed_Class():
def __init__(self, First_NEW_ENEMY_SPEED, Second_NEW_ENEMY_SPEED):
self.First_NEW_ENEMY_SPEED = First_NEW_ENEMY_SPEED
self.Second_NEW_ENEMY_SPEED = Second_NEW_ENEMY_SPEED
Enemy_SPEED = Enemy_Speed_Class(20, 50)
Enemy_SPEED_Min = Enemy_SPEED.First_NEW_ENEMY_SPEED
Enemy_SPEED_Max = Enemy_SPEED.Second_NEW_ENEMY_SPEED
count = 0
green = (0, 255, 0)
Lives = 99999999999999
Primary_Music = pygame.mixer.music.load("Game.ogg")
pygame.mixer.music.play(loops=-1)
Milestone_Delay = 50
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
First_NEW_ENEMY_Timer = 175
Second_NEW_ENEMY_Timer = 250
First_NEW_CLOUD_Timer = 300
Second_NEW_CLOUD_Timer = 600
Generate_Timer= AddEnemyTimer(random.randint(First_NEW_ENEMY_Timer, Second_NEW_ENEMY_Timer), random.randint(First_NEW_CLOUD_Timer, Second_NEW_CLOUD_Timer))
ADDENEMY = pygame.USEREVENT + 1
pygame.time.set_timer(ADDENEMY, Generate_Timer.Generate_Enemy_Timer)
More_Enemies = pygame.USEREVENT +2
pygame.time.set_timer(More_Enemies, 3000)
ADDCLOUD = pygame.USEREVENT + 3
pygame.time.set_timer(ADDCLOUD, Generate_Timer.Generate_Cloud_Timer)
New_Progress = pygame.USEREVENT + 4
pygame.time.set_timer(New_Progress, Milestone_Delay)
Game_Framerate = Game_Speed_Class(59.94)
Set_Game_Speed = pygame.USEREVENT + 5
pygame.time.set_timer(Set_Game_Speed, 10000)
player = Player()
health = 0
green = (0, 255, 0)
enemies = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
clouds = pygame.sprite.Group()
clock = pygame.time.Clock()
running = True
Large_Font = 60
Medium_Font = 40
Small_Font = 20
Small_Size = pygame.font.Font("Airstrip Four.ttf", Small_Font)
Medium_Size = pygame.font.Font("Airstrip Four.ttf", Medium_Font)
Large_Size = pygame.font.Font("Airstrip Four.ttf", Large_Font)
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.key == K_SPACE:
player.shoot()
if event.key == K_0:
pygame.mixer.music.set_volume(0)
if event.key == K_9:
pygame.mixer.music.set_volume(1)
elif event.type == QUIT:
running = False
elif event.type == ADDENEMY:
new_enemy = Enemy()
enemies.add(new_enemy)
all_sprites.add(new_enemy)
elif event.type == ADDCLOUD:
new_cloud = Cloud()
clouds.add(new_cloud)
all_sprites.add(new_cloud)
elif event.type == New_Progress:
count+= 1
elif event.type == Set_Game_Speed:
Enemy_SPEED_Min += 10
Enemy_SPEED_Max += 10
elif event.type == More_Enemies:
First_NEW_ENEMY_Timer += 50
Second_NEW_ENEMY_Timer += 50
First_NEW_CLOUD_Timer += 50
Second_NEW_CLOUD_Timer += 50
if Lives == 0:
running = False
screen.fill((135,206,250))
for entity in all_sprites:
screen.blit(entity.surf, entity.rect)
if pygame.sprite.spritecollide(player, enemies, True):
print("Hit!")
Lives -= 1
screen.blit(Medium_Size.render(str(count), True, (0, 0, 0)), (SCREEN_WIDTH // 2, 48))
screen.blit(Medium_Size.render(("Lives: ") + str(Lives), True, (0,0,0)), (20, 40))
fps = str(int(clock.get_fps()))
screen.blit(Small_Size.render(("FPS: ") + str(fps), True, (0,0,0)), (10, 0))
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
enemies.update()
clouds.update()
pygame.display.flip()
clock.tick(62)
A:
Create a pygame.sprite.Group for the bullets:
bullets = pygame.sprite.Group()
Add the bullets to the group:
class Player(pygame.sprite.Sprite):
# [...]
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
Update the bullets Group in the main application loop:
while running:
# [...]
player.update(pressed_keys)
enemies.update()
clouds.update()
bullets.update() # <-----
pygame.display.flip()
| {
"pile_set_name": "StackExchange"
} |
Q:
Binning a list of numbers to a given window
I have the following list example:
[-8,-7,-6,-5,-3,-2,-1,0,0,1,2,3,4,5,6,7]
I need to bin it in the following way:
e.g. given window=2, we always start binning from 0 to left for negative numbers, and from 0 to right for positive numbers:
[-4,-3,-3,-2,-2,-1,-1,0,0,1,1,2,2,3,3,4]
e.g. given window=3:
[-3,-2,-2,-2,-1,-1,-1,0,0,1,1,1,2,2,2,3]
The bins are computed starting from the 0s. So I need to bin everything left and right to zero. Say, in [-5,-4,-3,-2,-1,0] with window=2, I would bin the negative numbers in a step of 2. Let's reverse the list to start with 0 to help understand it better [0, -1, -2, -3, -4, -5], the result would be:
[-1, -2] turns into a bin -> [-1,-1]
[-3, -4] -> [-2, -2]
[-5, ] -> [-5, ]]
If I have both positive and negative numbers, I would first bin either the ones left to the most left 0 or right to the most right 0. Another example:
list = [-2,-1,0,0,0,1,2,3,4]
window=2
So I need to bin [-2,-1] and [1,2,3,4]. They would turn into: [-1,-1] and [1,1,2,2]. The final list will be: [-1,-1,0,0,0,1,1,2,2]
I am on Python 3. My attempt at it, mostly pseudo-code:
def bin_positions(self, positions_list, bin_window):
""" put relative positions into bins """
binned_list = list()
for index, element in enumerate(positions_list):
if element == 0:
# leave 0s untouched
binned_list.append(element)
elif element < 0:
if index % bin_window == 0:
# bin negative numbers
pass
elif element > 0:
if index % bin_window == 0:
# bin positive numbers
pass
# print(element, index)
return binned_list
Explanation on why I need this, as requested:
I am working on an NLP task where I need to encode positional embeddings relative to a given word span of the main word or phrase in the sentence. In my example, word span of the main phrase is denoted by 0s. And a word to the left of it, is indexed as -1, to the right, as index 1 and so on. I need to bin those positions since I don't care how precisely far the words are from the main word, but only relatively. So, all 3 words to the left of the main word can be indexed as -1,-1,-1 if window=3.
A:
Assuming that I understand your question correctly, and all the indices are always ordered, I would use numpy for this:
import numpy as np
def bin_list(l, width):
a = np.array(l)
a[a>0] = (a[a>0]+(width-1))//width
a[a<0] = (a[a<0])//width
return list(a)
l = [i for i in range(-9,0)] + [0,0] + [i for i in range(1,10)]
print(l)
print(bin_list(l,2))
print(bin_list(l,3))
print(bin_list(l,4))
This gives:
[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[-5, -4, -4, -3, -3, -2, -2, -1, -1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5]
[-3, -3, -3, -2, -2, -2, -1, -1, -1, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]
[-3, -2, -2, -2, -2, -1, -1, -1, -1, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3]
If getting a list as result is an unnecessary constraint, you can change return list(a) to return a.
| {
"pile_set_name": "StackExchange"
} |
Q:
Comment traduire l'expression « get on your tits » ?
Je cherche à traduire la phrase :
that must really get on your tits!
Je pense comprendre le sens général : quelque chose d'ennuyeux, dans le sens de légèrement dérangeant...
Mais je ne trouve pas d'équivalent en Français, dans un langage familier.
D'avance merci si vous avez des pistes !
A:
Si tu n'as pas peur d'avoir l'air un peu ringard tu peux utiliser l'expression "courir sur le haricot" (lit: to run on the bean). Le "haricot" en question représente une partie du corps sur laquelle serait en train de courir une petite bête, et ça commence à gratter. Pour l'instant c'est encore supportable, mais la si ça ne s'arrête pas on risque d'atteindre un stade de colère supérieur. Cas d'usage commun:
Tes mensonges commencent à me courir sur le haricot, dis-moi la vérité maintenant ou je vais m'énerver !
Moins ringard mais très similaire: "taper sur les nerfs". En général c'est un désagrément plus fort que "courir sur le haricot".
Sinon il y a l'éternel "faire chier" qui est vulgaire et peu précis. Cela peut désigner l'ennui, le désagrément léger, le désagrément lourd, la catastrophe imprévue...
A:
Comme relevé dans d'autres réponses, la phrase d'origine est elle-même une variation d'un idiome plus courant, to get on one's nerves, qui a une traduction littérale en français : taper sur les nerfs. La variation indique d'une part que le locuteur est une femme en mentionnant les seins et d'autre part utilise un registre de langage plus familier en se référant aux seins par le terme tits.
En recherchant les équivalents familiers de taper sur les nerfs, on trouve courir sur le haricot et casser / briser les couilles, ce dernier terme étant parfois, en fonction de l'effet recherché, remplacé par un euphémisme comme les noix ou les bonbons, voire simplement sous-entendu comme dans me les briser.
Mais toutes ces expressions ci-dessus sous-entendent, pour ma part, un locuteur mâle.
Je suggérerais donc la variation suivante :
Ça a dû te briser les miches
Miche étant un mot d'argot pouvant designer à la fois les seins de la femme ou les fesses.
Une autre possibilité moins imagée est
Ça a dû te saouler
Ça a dû te gonfler
A:
Cette expression ressemble énormément à une autre : getting on one's nerves,
qui indique l'agacement. On peut donc traduire ta phrase par
Ça a vraiment dû t'agacer/t'énerver/t'irriter
ou toute autre expression exprimant cette idée.
Getting on one's tits est une variante féminine de cette expression (tits désignant les seins). La traduction reste donc la même.
Edit important : J'ai sauté la phrase où tu demandes un langage familier on dirait, au temps pour moi.
Mais si tu prends en compte le reste de ma réponse, tu pourras en conclure que l'expression taper sur les nerfs proposée par AnneAunyme est la meilleure et plus proche traduction possible
| {
"pile_set_name": "StackExchange"
} |
Q:
lambda expression meaning
I have created an htmlhelper which has signature like this:
public static MvcHtmlString PageLinks(this HtmlHelper html,
PagingInfo pagingInfo,Func<int, string> pageUrl)
and I see that It is passed like this:
@Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
but I dont know what is it meaning ?
x => Url.Action("List", new {page = x})
Please suggest meaning of this lambda expression
A:
Well, it's a lambda expression which takes a single parameter called x and is implicitly typed to be a int, and which calls Url.Action with one argument of the string "List" another argument of an anonymous type which has a single property page with the value of the parameter x.
The value returned from Url.Action is used as the return value for the lambda expression.
That's how the lambda expression itself is broken down, in terms of language constructs. If you're asking what it means in terms of behaviour, that's a different matter - you'd need to look at your own PageLinks method, as well as the documentation for Url.Action.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wait for VPN connection to be established loop
I was looking for a way in PHP to check and wait for vpn connection (tun0 interface) to come up before continuing with the code
here is what I come up with but it's not seeing any change after interface tun0 is up
$val = exec("/bin/netstat -i | grep tun0 | wc -l");
while($val == "0")
{
echo "Still Not Connected\n";
sleep(2);
}
echo "VPN Connected";
A:
Your command is just not in the loop :p
do
{
$val = exec("/bin/netstat -i | grep tun0 | wc -l");
if( $val == "0" ){ echo "Still Not Connected\n"; sleep(2); }
} while($val == "0")
echo "VPN Connected";
I'm using do-while structure because you will do at least one time the loop.
| {
"pile_set_name": "StackExchange"
} |
Q:
bash testing to see if a script is being run in a certain directory with aliases and not using string matching
I have a bash script I am writing for a public code and I want to ensure that the user is not running the script directly in the git repository (or sub-directory thereof). I have an environmental variable CODELIB that points to the repository location and I was testing for string matching in the following way, with wildcards to catch subdirectories:
if [[ `pwd` == *${CODELIB}* ]]; then
echo "error: do not run in your git repository " $CODELIB
exit 1
fi
This works fine in most circumstances, but is sometimes caught out if the user has their code in a subdirectory of $HOME, as my employer using AFS, and there seems to be use of aliases such that for some users the home is mounted such that
cd $HOME
pwd
gives this
/afs/xyz.it/home/t/user/
instead of this
/afs/xyz/home/t/user/
As the variable CODELIB points to
/afs/xyz/home/t/user/code_location
my test fails in this case. I was therefore wondering if there were an inbuilt function in bash that could more robustly test if a directory is a subdirectory of another without resorting to string matching.
The solutions I found here: https://unix.stackexchange.com/questions/6435/how-to-check-if-pwd-is-a-subdirectory-of-a-given-path were all based on string matching
A:
You can use realpath on both directories.
if [[ "$(realpath "$(pwd)")"/ == "$(realpath "${CODELIB}")"/* ]]; then
If realpath is not available but perl is:
realpath(){
perl -MCwd -e 'print Cwd::realpath($ARGV[0])' "$1"
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Removing deny everyone permissions from GPO
As part of the workaround for CVE-2014-1776 I created a group policy object that applied Deny permissions to everyone on VGX.DLL. I am now trying to undo this group policy and having a lot of trouble. I first attempted to unlink the group policy and then force a group policy update, when that didn't work I also attempted to explicitly add read permissions for Everyone again, this also did not work.
If you've added Deny Everyone permissions to a file via group policy, how do you remove those to return things to the status quo?
A:
It turned out that the problem had to do with the ownership of the file. By default the file is owned by TrustedInstaller. Because I had set all permissions to Deny to Everyone the only person who could change the permissions on the file was TrustedInstaller.
The solution in the end was to modify the Group Policy object to also change the owner of the file to Domain Administrators AND also remove the Deny permission from the GPO. It is not necessary to explicitly add an allow permission to the GPO.
| {
"pile_set_name": "StackExchange"
} |
Q:
Django objects.filter in template
I have django project with three below models:
models.py
from django.db import models
from django.contrib.auth.models import User
class Album(models.Model):
owner = models.ForeignKey(User)
title = models.CharField(max_length=127)
artist = models.CharField(max_length=63)
release_date = models.DateField()
logo = models.ImageField(blank=True, upload_to='album_logos', default='album_logos/no-image.jpeg')
t_added = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(null=True, blank=True, max_length=63)
class Meta:
ordering = ['-release_date']
def __str__(self):
return self.title
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
# is_favorite = models.BooleanField(default=False)
favorites = models.IntegerField(default=0)
song_file = models.FileField(blank=True, null=True, upload_to='song_files', default='song_files/mektub.mp3')
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Favorite(models.Model):
user = models.ForeignKey(User)
song = models.ForeignKey(Song)
created = models.DateTimeField(auto_now_add=True)
As you can see from these models many users can favorite many songs. In template, I want to add class to songs which are favorited by authenticated user:
template
<span {% if authenticated user favorited this song %}class="favorited" {% endif %}></span>
My problem is, I don't know how to write "if authenticated user favorited this song" in template. In terminal, I can get this information by this code:
user_favorited_this = song.favorite_set.filter(user=sample_user) and True or False
I couldn't do the same thing in template, since it doesn't support passing argument to filter method. How can I overcome this problem?
A:
A tag filter can do what you want:
If the User.favorite_set.all has something in common with Song.favorite_set.all this means the current user has favorited that song
from django import template
register = template.Library()
# Method 1 for django queryset (Better)
@register.filter
def intersection(queryset1,queryset2):
return queryset1 & queryset2
# Method 2 for queryset or python List
@register.filter
def intersection(queryset1,queryset2):
return list(set.intersection(set(queryset1),set(queryset2)))
html:
{% if request.user.favorite_set.all|intersection:song.favorite_set.all %} class="favorited" {% endif %}
| {
"pile_set_name": "StackExchange"
} |
Q:
Mandarin Equivalent of 啥子树子招啥虫?
Heard 啥子树子招啥虫 used in the same sense as "不是一家人,不进一家门" - I was wondering if there is a similar phrased expression in Mandarin for the first, mentioned, expression.
A:
Note that 啥子树子招啥虫 emphasizes more on similarity of couples of marriage.
龙生龙,凤生凤,老鼠儿子会打洞。
Dragon's son must be a dragon, phoenix's son must be a phoenix, and that of a mouse must can dig holes.
Meaning:
A great man teaches out great sons, a noble man cultivates noble sons. Normal people have only normal posterities.
Sometimes we neglect the second half of the phrase, i.e. just 龙生龙,凤生凤.
| {
"pile_set_name": "StackExchange"
} |
Q:
nodeJS when and how is the heap memory freed?
In order to understand the memory usage pattern of NodeJS's V8 engine, I wrote a simple web program as shown below:
contents of server.js:
var http = require("http");
var server = http.createServer(function(req, res) {
res.write("Hello World");
res.end();
});
server.listen(3000);
When the program is launched using node server.js, the initial memory snapshot is as below:
After I kept making multiple URL hits to this server, I could see a pattern of increased heap usage. To be more precise, for every 6 or 7 hits, there is an increase of 4K. I kept repeating the hits continuously for about 2 minutes, then this is the snapshot.
I didn't see any eventual decrease in heap usage, even if I kept it idle without load.
My question is:
Is this a normal behavior, or there is a memory leak in nodeJS?
Or, am I understanding or interpreting it incorrectly?
A:
Node uses V8 under the hood, so the answer to this question most likely applies:
How does V8 manage its heap?
The code appears to be valid, so to test you could write a small application to repeatedly call your api and then examine Node's memory while running. Use this to help detect possible leakage (if there is any over 5 consecutive runs of the garbage collector): http://www.nearform.com/nodecrunch/self-detect-memory-leak-node/
| {
"pile_set_name": "StackExchange"
} |
Q:
Access all views in ViewNavigatorApplication ( Flex Mobile Application )
My goal
I'd like to make an application for PlayBook (using Flex) that has the UI similar to the PlayBook web browser. By similar I mean I want to implement a menu that is shown when the user swipes down from the top bezel of the tablet. I like this feature because I can draw on it, place tons of other objects and handle all kind of events without using screen space when not needed. Plus the PlayBook does not have a "Menu" button like some phones have.
Depending on configurations chosen from the first view a number of other views will be pushed onto the the stack view. When the user will access the pull down menu I'd like to show in form of thumbnail snapshot my main (configuration view) and the rest of the views that are on the view stack. This will basically show the user what is going on in different view and let him choose to which one to switch.
Achieved so far
The menu is accessible from any view, but the code for event handler is in my main MXML file (project.MXML), I found this to be the only way of having one menu for all the views.
I managed to pull down the menu from any view and displaying a thumbnail of the current view.
My problem
How to get access to all the views. I've been trying all day and all my trials give me access to the active view and my menu object. Here is some code to show what is going on:
// This is in my default view MXML
navigator.pushView(MainView);
navigator.pushView(SecondView);
navigator.pushView(ThirdView);
navigator.pushView(FourthView);
.......
// And this is where I try to gain access to my Views (in the Project.MXML)
var totalViews:int = navigator.length;//Length is 5 (4 Views plus menu which is wright)
var obj:Object;
for(var i:int = 0; i < totalViews; ++i)
{
obj = navigator.getElementAt(i);// Tried child here, it's not working either
var currentThumbnail:Preview = new Preview();
var bmData:BitmapData = new BitmapData( obj.stage.width, obj.stage.height );
bmData.draw(obj.stage);
currentThumbnail.setSize( m_previewH, m_previewW );
currentThumbnail.setBitmap( bmData );
currentThumbnail.setLayoutBoundsPosition(i * m_previewW + PREVIEW_GAP * i, 10);
slideMenu.addChild( currentThumbnail );
trace(i.toString() + " " + obj.toString());
}
As I mentioned above this for loop will successfully do the job for the current view then it will crash.Does anyone know how to loop through all the views?
This is my first application with flex so if there are any alternatives to my approach I'll be glad to try them. Although I'd like to stick with a single ViewNavigator as opposed to tabbed navigator and multiple views instead of states, I don't mind suggestions from that side.
TIA.
A:
I'm pretty sure that for memory consumpation reasons Flex will not keep more than one instance of the view in memory at a time. So, looping over the number of views and trying to access the instance of that view will cause issues; because the view is essentially created every time it is displayed and destroyed every time it is hidden.
To do what you want to do, I think you're going to have to create the view snapshots on your own. Perhaps as in memory bitmaps that will exist even if the view isn't on screen. Or perhaps you'll want to save them temporarily to disk for memory purposes. Or even better, you could provide "pre-rendered" images.
Anyway, then keep a list of the images as they relate to the views and display them in your "Display Shelf" style menu.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add space between elements
I have a nav-menu on which it seems that I can't add a space (margin: 3px;) between the <li> elements.
You can see the HTML and CSS code on this jsfiddle or below.
You will see that I've added a border-bottom: 2px solid #fff; to the #access li to simulate the space between elements, but that is not going to work because under the nav-menu I will have a bunch of different colors. If I add margin-button: 2px it doesn't work.
This is the HTML:
<nav id="access" role="navigation">
<div class="menu-header-menu-container">
<ul id="menu-header-menu" class="menu">
<li id="menu-item-41" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-41">
<a href="http://localhost:8888/fullstream/?page_id=5">About Us</a>
</li>
<li id="menu-item-35" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-35">
<a href="http://localhost:8888/fullstream/?page_id=7">Services</a>
</li>
<li id="menu-item-34" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-34">
<a href="http://localhost:8888/fullstream/?page_id=9">Environmental Surface Cleaning</a>
</li>
<li id="menu-item-33" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-33">
<a href="http://localhost:8888/fullstream/?page_id=11">Regulations</a>
</li>
<li id="menu-item-32" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-32">
<a href="http://localhost:8888/fullstream/?page_id=13">Contact Us</a>
</li>
</ul>
</div>
This is the CSS:
#access {
background: #0f84e8; /* Show a solid color for older browsers */
display: block;
margin: 0 auto 6px 55px;
position: absolute;
top: 100px;
z-index: 9999;
}
#access ul {
font-size: 13px;
list-style: none;
margin: 0 0 0 -0.8125em;
padding-left: 0;
}
#access li {
position: relative;
padding-left: 11px;
}
#access a {
border-bottom: 2px solid #fff;
color: #eee;
display: block;
line-height: 3.333em;
padding: 0 10px 0 20px;
text-decoration: none;
}
#access li:hover > a,
#access ul ul :hover > a,
#access a:focus {
background: #efefef;
}
#access li:hover > a,
#access a:focus {
background: #f9f9f9; /* Show a solid color for older browsers */
background: -moz-linear-gradient(#f9f9f9, #e5e5e5);
background: -o-linear-gradient(#f9f9f9, #e5e5e5);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#f9f9f9), to(#e5e5e5)); /* Older webkit syntax */
background: -webkit-linear-gradient(#f9f9f9, #e5e5e5);
color: #373737;
}
#access ul li:hover > ul {
display: block;
}
A:
add:
margin: 0 0 3px 0;
to your #access li and move
background: #0f84e8; /* Show a solid color for older browsers */
to the #access a and take out the border-bottom. Then it will work
Here: http://jsfiddle.net/bpmKW/4/
A:
You can use the margin property:
li.menu-item {
margin:0 0 10px 0;
}
Demo: http://jsfiddle.net/UAXyd/
A:
Since you are asking for space between , I would add an override to the last item to get rid of the extra margin there:
li {
background: red;
margin-bottom: 40px;
}
li:last-child {
margin-bottom: 0px;
}
ul {
background: silver;
padding: 1px;
padding-left: 40px;
}
<ul>
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
<li>Item 1</li>
</ul>
The result of it might not be visual at all times, because of margin-collapsing and stuff... in the example snippets I've included, I've added a small 1px padding to the ul-element to prevent the collapsing. Try removing the li:last-child-rule, and you'll see that the last item now extends the size of the ul-element.
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular: How to get content from a custom div
I want to get a the content from a custom div tag, I tried various ways to do it, not working well. Here is an example. The general item is to retrieve the content in the custom directive tags. and then bind them into the template. I hope some one can give me a suggestion or solution that does it, or does similar things
The html
<questions>
<qTitle> this is title</q-title>
<qContent> this is content <q-content>
</questions>
The angular js
var app = angular.module('app'[]);
app.directive('questions', function () {
return {
transclude: true;
template: "<div class='someCSSForTitle'>{{qTitle}}</div>"+
"<div class='someCSSForContent'>{{qContent}}</div>"
link:(scope, element, attrs)
scope.qTitle = element.find(qTitle).innerHTML
scope.qContent = element.find(qContent).innerHTML
}
}
});
A:
First I'd advise you to read the AngularJS Guide. You didn't even copy-paste the structure correctly and you have javascript and even html errors.
Basic fixes:
HTML
<questions>
<q-title>this is title</q-title>
<q-content>this is content</q-content>
</questions>
Why do you mix qTitle and q-title?
As regarding JS:
app.directive('questions', function () {
return {
restrict: 'E',
replace: true,
template: "<div class='question'>{{title}}</div>", /* simplified */
link: function(scope, element, attrs) {
scope.title = "hallo";
console.log(element.html());
}
};
});
by default, restrict is set to 'A'. That means attributes. Your syntax is for elements.
replace set to true is not compulsory. However, because the browser doesn't understand your elements but does understand the content ("this is title"), it will print it.
the link function has to be a function. you had syntax errors there (same for transclude: you had something that you were not using followed by ";")
You can print the element to know the contents. If you do, you'll see that element in link is not question.
Now if you want to read the content, you can use a transclude function or create directives for each part and create the template separately. This seems simpler. Live example:
app.directive('questions', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
template: "<div class='question' ng-transclude></div>",
};
});
app.directive('qTitle', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
template: "<div class='title' ng-transclude></div>",
};
});
In this case you translude the contents to an inner div.
You can also define custom complex transclude functions in the compile phase but this doesn't seem necessary here.
| {
"pile_set_name": "StackExchange"
} |
Q:
String formatting - combine multiple forms
I've read the docs about string formatting mini language, and found out about few cool features:
integer representations:
'{0:X}'.format(16) # output is '10'
padding with zeros:
'{0:03X}'.format(16) # output is '010'
and alternate forms:
'{0:#X}'.format(16) # output is '0X10'
My question - is there a way combining all 3 in single command?
For instance:
'{0:#03X}'.format(16) # output is '0x10', desired output is '0x010'
Thanks in advance!
A:
You need to specify some more digits:
print('{0:#05x}'.format(16))
Output:
0x010
You need 5 and not 3 because 0x are also considered when padding the output.
Beside that, you can always hack your output usign string concattenation or zfill():
print('0x'+'{0:03x}'.format(16) )
print('0x'+ '{:x}'.format(16).zfill(3))
| {
"pile_set_name": "StackExchange"
} |
Q:
pd.read_html for several pages
I have a few pages to crawl. On each page there is a table. That's what I exactly want to get. And the urls of the pages are only different by the last number. Is there anyway that I could use pd.read_html to get all the tables and merge the tables into one table?
import pandas as pd
url_head = 'http://www.kmzyw.com.cn/jiage/today_price.html?pageNum=1'
data =pd.read_html(url)[0]
A:
You can add each url output to a list in a loop, and then use pd.concat at the end to combine the list into one large dataframe.
import pandas as pd
df_list = []
for i in range(1, N):
url_head = 'http://www.kmzyw.com.cn/jiage/today_price.html?pageNum=%d' %i
df_list.append(pd.read_html(url)[0])
df = pd.concat(df_list)
Replace N with the number of web pages you have plus one.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the Japanese term for putting an arm around another's shoulder?
What is the Japanese term for putting an arm around another's shoulder? it is kind of hard, at first I am thinking of 抱きしめる but I think it is more about embracing someone (tightly).
Thank you for the responds
A:
Most commonly, we would say:
「(Person)の肩{かた}に腕{うで}をかける」 or
「(Person)の肩に腕を回{まわ}す」
I actually could not think of another phrase.
A:
In addition to @l'électeur's answer, we also commonly say 肩【かた】を組【く】む when two or more people put their arms on one another's shoulders.
| {
"pile_set_name": "StackExchange"
} |
Q:
android make links in a TextView clickable
First, I'll start by saying I've visited this two:
question 1 about this subject, question 2 about this subject
and both have failed me.
Second, my app is based on a single map fragment, i don't know if that's an issue, but the TextView is part of an info window which is displayed over the map.
I have the following TextView in xml:
<TextView
android:id="@+id/tv_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:linksClickable="true"
android:autoLink="web" />
which I want to make into a link, I'm feeding the text programatically, and can see the text as it is, but it is not clickable, or "hyper-link"ed.
The following is the part where I set up the TextView in my activity:
TextView tvLink = (TextView) v.findViewById(R.id.tv_link);
// make the link clickable
tvLink.setClickable(true);
tvLink.setMovementMethod(LinkMovementMethod.getInstance());
String text = (String) urls.get(arg0.getTitle());
// Setting the link url
tvLink.setText(Html.fromHtml(text));
I have also tried making the TextView have attribute of android:onClick="openBrowser" and have this class openBroweser:
public void openBrowser(View view){
//Get url from tag
String url = (String)view.getTag();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
//pass the url to intent data
intent.setData(Uri.parse(url));
startActivity(intent);
}
but it also didn't work. I might have made a mess while trying the different approached, but I did try to separate each try. and am confused and in need of an outside look.
EDIT 1 :
added the following:
My string in the res file (inside a string-array)
Click here for more info about this location
(which works here, so I assume it should be a legal link as needed)
My whole XML file as requested in comment
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="@+id/tv_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/tv_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp" />
</LinearLayout>
<ImageView
android:id="@+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
/>
A:
What you are trying to do will not work because a Google Maps InfoWindow is not a live view.
In the documentation for Custom Info Windows it states:
The info window that is drawn is not a live view. The view is rendered
as an image (using View.draw(Canvas)) at the time it is returned. This
means that any subsequent changes to the view will not be reflected by
the info window on the map. To update the info window later (for
example, after an image has loaded), call showInfoWindow().
Furthermore, the info window will not respect any of the interactivity
typical for a normal view such as touch or gesture events. However you
can listen to a generic click event on the whole info window as
described in the section below.
and
As a result, any listeners you set on the view are disregarded and you
cannot distinguish between click events on various parts of the view.
So the clicks on the individual tv_link TextView within the overall InfoWindow layout will not be processed.
You need to use the OnInfoWindowClickListener to listen for clicks on an InfoWindow
| {
"pile_set_name": "StackExchange"
} |
Q:
Mailgun for receiving emails (rackspace)
Disclaimer: I am a total server noob so this might be a very stupid question.
If I am using Mailgun as my email service for my domain, where do I setup mailboxes for the domain? ie. [email protected]
According to Mailgun, mailboxes are a legacy feature no longer supported. So, what am I missing here?
A:
You're missing the point of Mailgun. It is not intended to replace a normal e-mail infrastructure. If you want that, you need something like Google Apps for Business.
Mailgun is intended for sending and receiving automated e-mails. For example, you might set up e-mails to [email protected] to be processed by a script to add them to your ticket system.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como criar um emulador sem utilizar a ide?
Eu preciso emular o android na minha máquina, mas não queria utilizar uma máquina virtual porque utilizaria muitos recursos, queria usar o sdk tools do android studio, mas também não queria instalar o android studio para isso.
Então eu baixei o sdk tools no site do android studio e tentei rodar, nas versões antigas tinha uma gui e era bem simples para criar e rodar, mas na versão atual não tem, é tudo via comando, tentei ate executar alguns mas nenhum foi bem sucedido.
Executei isso:
C:\Users\Futurotec\Downloads\sdk-tools-windows-3859397\tools>android
**************************************************************************
The "android" command is deprecated.
For manual SDK, AVD, and project management, please use Android Studio.
For command-line tools, use tools\bin\sdkmanager.bat
and tools\bin\avdmanager.bat
**************************************************************************
Invalid or unsupported command ""
Supported commands are:
android list target
android list avd
android list device
android create avd
android move avd
android delete avd
android list sdk
android update sdk
Então tentei rodar o comando android create avd:
C:\Users\Futurotec\Downloads\sdk-tools-windows-3859397\tools>android create avd
**************************************************************************
The "android" command is deprecated.
For manual SDK, AVD, and project management, please use Android Studio.
For command-line tools, use tools\bin\sdkmanager.bat
and tools\bin\avdmanager.bat
**************************************************************************
Invoking "C:\Users\Futurotec\Downloads\sdk-tools-windows-3859397\tools\bin\avdmanager" create avd
Error: The parameters --package, --name must be defined for action 'create avd'
Usage:
avdmanager [global options] create avd [action options]
Global options:
-s --silent : Silent mode, shows errors only.
-v --verbose : Verbose mode, shows errors, warnings and all messages.
--clear-cache: Clear the SDK Manager repository manifest cache.
-h --help : Help on a specific command.
Action "create avd":
Creates a new Android Virtual Device.
Options:
-a --snapshot: Place a snapshots file in the AVD, to enable persistence.
-c --sdcard : Path to a shared SD card image, or size of a new sdcard for
the new AVD.
-g --tag : The sys-img tag to use for the AVD. The default is to
auto-select if the platform has only one tag for its system
images.
-p --path : Directory where the new AVD will be created.
-k --package : Package path of the system image for this AVD (e.g.
'system-images;android-19;google_apis;x86'). [required]
-n --name : Name of the new AVD. [required]
-f --force : Forces creation (overwrites an existing AVD)
-b --abi : The ABI to use for the AVD. The default is to auto-select the
ABI if the platform has only one ABI for its system images.
-d --device : The optional device definition to use. Can be a device index
or id.
Tentei varias parâmetros, mas nenhum criava o emulador.
Tentei utilizar também o comando avdmanager direto, mas apresentou as mesmas mensagens.
Em todas as minhas pesquisas só encontrava soluções que era necessário abrir o android studio ou que os comandos eram das versões antiga.
A:
TL;DR
Um exemplo de comando válido para criar um avd:
avdmanager create avd -n "Meu-Emulador" -k "system-images;android-26;google_apis_playstore;x86"
avdmanager
O programa utilizado para criar AVDs é o avdmanager. Ele está localizado em sdk/tools/bin/avdmanager. O android também funcionaria, mas ele acaba utilizando o avdmanager por baixo.
Para a criação de um AVD dois parâmetros são obrigatórios:
-n ou --name para nomear o AVD
-k ou --package para indicar qual imagem de sistema será utilizada
Imagens de sistema
Para a criação de AVDs é obrigatório indicar uma imagem de sistema. Para listar as imagens instaladas, utilize o mesmo comando sem o parâmetro -k:
avdmanager create avd -n "Meu-Emulador"
Se nenhuma imagem for listada, significa que nenhuma foi instalada. A instalação de novas imagens pode ser feita através da utilização do sdkmanager.
Para listar os pacotes disponíveis:
sdkmanager --list --verbose
Nota: o --verbose foi utilizado para não truncar os nomes dos pacotes.
Para instalar uma imagem:
sdkmanager "system-images;android-26;google_apis;x86"
Executando o avd no emulador
Para iniciar o emulador, utilize o programa emulator, localizado em sdk/tools/emulator, informando o nome do AVD a ser executado:
emulator -avd "Meu-Emulador"
| {
"pile_set_name": "StackExchange"
} |
Q:
Resonant vs. Non-resonant Raman
What does it mean to say that the conventional Raman effect is non-resonant? And, how/why does resonant Raman give a stronger signal than the non-resonant type?
A:
The normal nonresonant Raman scattering happens when a photon interacts with a molecule; the molecule absorbs the photon momentarily and re-emits it with slightly less energy.
In an energy diagram, that looks like this.
The frequency of the incoming photon is $\omega_i$, and the frequency of the scattered photon is $\omega_s$. The thick lined level is the ground state of the molecule, and the thin solid lined levels are vibrational states that are only slightly above the energy of the ground state.
The dotted line is a virtual energy state, which doesn't actually exist; but since the photon is re-emitted such a short time later, that's OK.
Most of the time, this doesn't happen; it's very uncommon compared to Rayleigh scattering, where $\omega_s=\omega_i$. That's why the signal from nonresonant Raman scattering is so low. Only a tiny, tiny fraction of scattered photons have their energy changed due to Raman scattering.
Now, resonant Raman scattering is exactly the same thing as nonresonant Raman scattering, except that $\omega_i$ is such that the virtual state's energy level is very close to one of the molecule's excited states (which are not virtual, but very real indeed.)
Being so close to an excited state makes the Raman process much more likely to occur. That's why the signal is so much stronger and can be used to detect much lower concentrations of a substance than conventional Raman can.
For more information, read the Wikipedia page.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: Select the first file in a directory
I'm trying to process some files in a directory without knowing their name, and one by one.
So I've used os.listdir(path) to list files.
So I have to list files at each call of my function. The problem is when there is a lot of files (like 2000), it takes a loooooong time to list each file and I just want the first one.
Is there any solution to get the first name without listing each files ?
Thank you :)
A:
os.listdir(path)[0]
It would be faster than 'listing' (printing?) each filename, but it still has to load all of the filenames into memory. Also, which file is the first file, do you only want whichever one comes first or is there a specific one you want, because that is different.
A:
If your goal is to process each file name, use os.walk() generator:
Help on function walk in module os:
walk(top, topdown=True, onerror=None, followlinks=False)
Directory tree generator.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get matrix $A$ from $A^\top A=B$ with given symmetric matrix $b$?
Given a symmetric matrix $B \in \mathbb{C}^{n\times n}$.
How many coefficients of $A \in \mathbb{C}^{n\times n}$ can you obtain from the following equation?
$$A^\top A=B$$
I think this problem is under determined? Isn't it? Sure $B$ must be symmetric. Thus only $\frac{n(n+1)}{2}$ complex equations remain for $n\times n$ coefficients.
A:
Not completely sure about complex numbers, but... If $A^\top A=B$ then, $B$ is symmetric positive semi-definite. So you can take the eigenvalue/vector decomposition of $B$, such that $B=U\Lambda U^\top$.
Then $A=(U\Lambda^{1/2})^\top$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do multiple branches from one node occur with the Monte Carlo Tree Search?
I think I understand the Monte Carlo Tree search. It goes through the tree until it reaches a leaf node, where it branches (creates a child node). However, the branching only occurs at the leaf nodes (right?). So, a branch never comes out from a non-leaf node. So how could one node have multiple branches (multiple child nodes) coming out of it? Here's a picture, for clarity:
So wouldn't that process just keep getting repeated? It's not a leaf node, so the algorithm won't branch (create another child node)... so it has to pick the next node. And since it only has one option, it must pick that one. It just continues down, until it reaches the end. What's the point of that?
I'm probably missing something big here, but all the pages I've look at don't really explain this. It just magically repeats selection, expansion, simulation, and back-propagation, until it constructs a nice tree at the end. How?
EDIT:
I figured it usually creates only one child node because of this taken of this source:
In its simplest and most memory efficient implementation, MCTS will add one child node per iteration.
Also, even if you create just two or three, would that really be enough to cover all the possible moves, especially if the branching factor is large? How would one determine how many child nodes to create?
A:
It sounds like you're reading a summary/overview. You might be reading too much into one sentence there. The sentence says "MCTS will add one child node per iteration". That doesn't mean each node will have only one child after the process finishes. You might have one iteration that adds one child of X, and a later iteration that adds another child of X, and an even later iteration that adds yet another child of X, and so on.
Similarly, nothing says that MCTS is limited to adding only two or three children per node.
| {
"pile_set_name": "StackExchange"
} |
Q:
What am i doing wrong in this attempt at an infinite loop?
I'm trying to make a code for my python class and i'm making a wallet management system basic. but i cant get this infinite loop to work. What am i doing wrong?
def main():
# Initial balance
balance = input ('Wallet balance: ')
# This constructs the infinite loop
while true:
# Initial balance
balance = input ('Wallet balance: ')
# Withdraw amount from wallet balance
withdraw= input ('Withdraw amount: ')
#If there is no balance to withdraw from
if balance < 1:
print ('You have no funds to withdraw.')
# Withdraw process and new balance display
if balance > 0:
new = balance - withdraw
print ('Your new balance: '), new
main()
A:
Fixed it for you, it had a few errors
True must be capitalized in Python
If you are passing an int into a str you need to cast the int as a str
Also, I'm not sure why what you're using the main function for? It doesn't pass the initial value into the infinite loop and seems redundant.
def main():
# Initial balance
balance = input ('Wallet balance: ')
# This constructs the infinite loop
while True:
# Initial balance
balance = input('Wallet balance: ')
# Withdraw amount from wallet balance
withdraw= input('Withdraw amount: ')
#If there is no balance to withdraw from
if balance < 1:
print('You have no funds to withdraw.')
# Withdraw process and new balance display
if balance > 0:
new = balance - withdraw
print('Your new balance: ' + str(new))
main()
However, I'm assuming you're trying to build a functional wallet that can withdraw and deposit. I'm not sure how comfortable you are with python and class construction, but I built a fully functional wallet for you to check out and learn from.
class Wallet:
#Grab the initial balance in the account
def __init__(self, initial_balance):
self.balance = initial_balance
#method that deposits funds to the balance
def deposit(self, deposit_amount):
self.balance += deposit_amount
#method that attempts to withdraw from the balance
def withdraw(self, withdraw_amount):
if withdraw_amount <= self.balance:
self.balance -= withdraw_amount
else:
print("Insufficient funds. You have " + str(self.balance) + " in your account. Please deposit more or withdraw less.")
#display the balance
def display_balance(self):
print("The current balance in the account is " + str(self.balance))
print("-----")
#Check if this module is the one currently being run
if __name__ == "__main__":
#Ask user for initial balance
initial_balance = int(input("Initial balance in account: "))
#initiate the class, passing the initial balance
wallet = Wallet(initial_balance)
wallet.display_balance()
while True:
#Pick an option to withdraw, deposit or exit
print("1: Deposit funds")
print("2: Withdraw funds")
print("3: Exit")
type = int(input("Please select an option (1, 2 or 3): "))
if type == 1:
deposit_amount = int(input("Please specify amount to deposit: "))
wallet.deposit(deposit_amount)
wallet.display_balance()
elif type == 2:
withdraw_amount = int(input("Please specify amount to withdraw: "))
wallet.withdraw(withdraw_amount)
wallet.display_balance()
elif type == 3:
break
else:
print("Invalid selection, please type either 1, 2 or 3")
| {
"pile_set_name": "StackExchange"
} |
Q:
Can you boil/decontaminate water with heat from a magnifying glass?
A bit hypothetical, but ruling out being able to use a solar still, or the SODIS method, could you make water drinkable by using the suns heat through a magnifying glass?
Paper self ignites at 451° F , water boils at 212° F, but that is at one concentrated point when paper burns using a magnifying glass. Would it be possible to boil a small about of water using the same method? For sake of it lets say you have a magnifying glass that is 3.5" across, and a plethora of different small containers available glass or metal.
I realize you could then start a fire, and boil water in a metal container but i am just curious if it is possible to heat the water enough to be drinkable without placing it on a fire using this method. As fires cause smoke lets say you are in a less than desirable place where the smoke from a fire could give away your location when you didn't want it to.
A:
Let's do some back-of-the-envelope calculations.
The specific heat of water is the amount of energy needed to raise the temperature of a particular amount of water by 1 degree C. This is 4.186 joules/gram °C (reference).
To raise the temperature of 1 L of water (1000 g) by 80 degrees C (to boiling from room temperature), would be 4.186 * 1000 * 80 = 334,800 joules.
The amount of sunlight falling on a square metre of the earth's surface is at maximum about 300 watts/m² (reference). A watt is a joule per second, so this means you could get 334,800 joules from a square metre of sunlight in 334,800 / 300 = 1116 seconds, or about 19 minutes.
Of course, a magnifying glass with an area of a square metre would be rather heavy and unwieldy to carry. A largeish one of 9 cm (3.54 inch) diameter would be about 64 cm², or 0.0064 square metres. Using this magnifying glass would boil our 1 litre of water in about 157 times as much time, or about 175,000 seconds, or just over 48 hours.
As you can see, the amount of energy you can collect directly from the sun is insufficient to boil any useful amount of water in a reasonable time. Even if you only wanted a small drink of 100 mL, it would still take all afternoon.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java methods and classes, how do they fit together?
Currently I am writing a program for an introductory Java class. I have two pieces to my puzzle. Hopefully this is a relatively simple to answer question.
Firstly, here is what I am trying to use as my main program:
import java.util.Scanner;
public class TheATMGame
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double newBalance = 0;
double monthlyInterest = 0;
int answer = 0;
int i=1;
while (i < 100) {
System.out.print ("Please enter your ID: ");
answer = input.nextInt();
System.out.println(" ");
if (answer >=0 && answer<10)
TheATMGame.runGame (answer);
else
System.out.println("Sorry, this ID is invalid.");
}
}
public static void runGame(int id) {
double amount = 0;
int continueOn = 0;
while (continueOn < 4) {
ATMGame myATM = new ATMGame();
Scanner input = new Scanner(System.in);
System.out.println ("---Main menu--- ");
System.out.println ("1: Check balance ");
System.out.println ("2: Withdraw ");
System.out.println ("3: Deposit ");
System.out.println ("4: exit ");
int answer = input.nextInt();
if (answer == 1)
System.out.println("your balance is: " + myATM.getBalance (id));
else if (answer == 2){
System.out.println("Enter an amount to withdraw: ");
amount = input.nextInt();
myATM.withdraw(amount, id);
}
else if (answer == 3)
{
System.out.println("Enter an amount to deposit: ");
amount = input.nextInt();
myATM.deposit(amount, id);
}
else if (answer == 4)
continueOn = 4;
else if (answer > 4)
System.out.println ("Please review the main menu. " +
"Your selection must be between 1-4.");
}
}
//ATM class (balance, annualInterestRate2, id2)
//ATM myATM = new ATM (20000, 4.5, 1122 );
//newBalance = myATM.withdraw(2500);
//newBalance = myATM.deposit(3000);
//monthlyInterest = myATM.getMonthlyInterestRate();
//System.out.println("Your current balance is: " + newBalance);
//System.out.println ("Your monthly interest rate is: " + monthlyInterest);
}
Now here are all of the classes I want to impliment into that program:
import java.util.Date;
public class ATMGame {
private double annualInterestRate = 0;
private double balance = 0;
private int id = 11;
private int[] ids = {0,1,2,3,4,5,6,7,8,9};
private int[] balances = {100,100,100,100,100,100,100,100,100,100};
public Date dateCreated;
public ATMGame() {
}
public ATMGame (double balance2, double annualInterestRate2, int id2) {
balance = balance2;
annualInterestRate = annualInterestRate2;
id = id2;
dateCreated.getTime();
}
public double getMonthlyInterestRate() {
double monthlyInterest = annualInterestRate/12;
return monthlyInterest;
}
public double withdraw(double amountWithdrawn, int id) { //This method withdraws money from the account
double newBalance = balances[id] - amountWithdrawn;
System.out.println("Your withdrawel has processed. New balance: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double deposit(double amountDeposited, int id) { //This method deposits money in the account
double newBalance = balances[id] + amountDeposited;
System.out.println("Your deposit has processed. New Balance is: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double getBalance(int id) {
double myBalance = balances[id];
balance = myBalance;
return myBalance ;
}
}
When I try to run the first program it says "No Main classes found."
As you can see I have written the line " public void Main() ..." to take care of this, but eveidently it does not work. What am I doing wrong?
Replacing "public void Main() {" with "public static void main(String[] args) {" still returns the error: "No Main classes found." :/
http://img21.imageshack.us/img21/9016/asdfsdfasdfg.jpg
I was able to fix it by changing Main.java to TheATMGame.java and then running from ATMGame.java.
A:
You should use:
public static void main(String[] args)
Instead of Main because the JVM calls this method first. It is a convention.
A:
You've just misdefined main. Should be:
public static void main(String[] args) {
....
}
You're going to run into some other problems with your code, though. From a quick glance...
Your main() is a function, as well as runGame() - one shouldn't be defined within the other.
You cannot name your two classes the same thing - call the main() class something different than ATMGame.
Not sure where you're going with ATM class (balance, annualInterestRate2, id2), but it's not valid Java.
A:
Your method signature must be:
public static void main(String[] args) {
...
}
That's the convention you have to follow. Anything else won't work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Validar si existe un registro en una tabla DB y almacenar en una variable
Estoy realizando una consulta para validar si existe un registro en la base de datos, para esto empleó lo siguiente
declaro variable
decimal serie= 10002;//este valor corresponde a un ejemplo, la variable puede tomar cualquier valor
realizo la query
string sql2 = "SELECT codigo from tabla2 WHERE codigo=@serie";
mi intencion es capturar ese valor del campo codigo en la siguiente variable
var camp = db.Database.SqlQuery<decimal>(sql2);
lo intente de esa forma, que debo modificar para que me capture ese valor en esa variable
A:
El problema imagino que es que SqlQuery normalmente devuelve una lista, pero en tu caso solo quieres un resultado.En ese caso, debes especificarlo. Hay varias maneras de indicar que solo quieres un resultado:
Single()
SingleOrDefault()
First()
FirstOrDefault()
Last()
LastOrDefault()
Cada uno de ellos tiene su funcionamiento. Los que contienen OrDefault te van a devolver el valor por defecto del tipo del IEnumerable en caso de que no encuentren ningún elemento. En tu caso, al ser decimal el valor por defecto será 0.
Resumiendo, tu código debe ser algo como:
var camp = db.Database.SqlQuery<decimal>(sql2).SingleOrDefault();
if (camp==0)
{
//El registro no se ha encontrado en la base de datos
}
else
{
//El registro ya existe en la base de datos
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Tomcat uses a Java 8 SDK but won't compile JSP with Java 8 language feature. How to fix it?
I think I'm looking at a Tomcat configuration issue with my current problem. I'm developing a Java Servlet and JSP application for Tomcat 8.5.8, and have begun to use Java 8 language features (specifically method references and streams). On my local machine running jdk1.8.0_211 the new code works, compiling JSP at runtime as it is meant to do.
On our testing server (RH Linux) the new JSP fails to compile (but the rest of the app works). The error is
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 135 in the jsp file: /jsp/directory/page.jsp
Method references are allowed only at source level 1.8 or above
I didn't set up the server myself, but it runs some build of Java 8, and has the same Tomcat version (8.5.8), so I suspect there's a configuration file somewhere that's telling it to compile the JSP at an older language level. (The evidence is that it knows what a Method reference is but refuses to compile it; an exception rather than an error.)
Where might a configuration be hiding that tells Tomcat to compile JSP at an older language level?
A:
Per https://tomcat.apache.org/tomcat-8.0-doc/jasper-howto.html,
The servlet which implements Jasper is configured using init parameters in your global $CATALINA_BASE/conf/web.xml.
compilerSourceVM - What JDK version are the source files compatible with? (Default value: 1.7)
compilerTargetVM - What JDK version are the generated files compatible with? (Default value: 1.7)
To give an example, if your web.xml file contains the following code, it will compile JSP to the 1.8 language level:
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>compilerSourceVM</param-name>
<param-value>1.8</param-value>
</init-param>
<init-param>
<param-name>compilerTargetVM</param-name>
<param-value>1.8</param-value>
</init-param>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
| {
"pile_set_name": "StackExchange"
} |
Q:
Нужна ли запятая? 4
Или новая модель развития, — или всё поглощающий кризис.
A:
Нужна ли запятая?
Не нужна.
Или новая модель развития — или всё поглощающий кризис.
Возможен и другой вариант:
Или новая модель развития, или — всё поглощающий кризис.
| {
"pile_set_name": "StackExchange"
} |
Q:
hibernate not creating table but no error messages
I am doing a spring-boot project and trying to create a table with hibernate, I get no errors when I run the app and the server starts normally, but the table does not get created.
StatusUpdate.java
package model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.PrePersist;
@Entity
@Table(name="status_update")
public class StatusUpdate {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name="text")
private String text;
@Column(name="added")
@Temporal(TemporalType.TIMESTAMP)
private Date added;
@PrePersist
protected void onCreate() {
if (added == null) {
added = new Date();
}
}
public StatusUpdate(String text) {
this.text = text;
}
public StatusUpdate(String text, Date added) {
this.text = text;
this.added = added;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getAdded() {
return added;
}
public void setAdded(Date added) {
this.added = added;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((added == null) ? 0 : added.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((text == null) ? 0 : text.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StatusUpdate other = (StatusUpdate) obj;
if (added == null) {
if (other.added != null)
return false;
} else if (!added.equals(other.added))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (text == null) {
if (other.text != null)
return false;
} else if (!text.equals(other.text))
return false;
return true;
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
<tiles.version>3.0.7</tiles.version>
</properties>
<groupId>com.voja</groupId>
<artifactId>spring-boot-tutorial</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-core</artifactId>
<version>${tiles.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>${tiles.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
</dependencies>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties
debug=true
spring.datasource.url=jdbc:mysql://localhost:3306/springboottutorial
spring.datasource.username=springboot
spring.datasource.password=hello
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUG
I also get a yellow line under dialect in this line spring.jpa.hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialectwhich says `spring.jpa.hibernate.dialect' is an unknown property. Did you mean 'spring.jpa.hibernate.ddl-auto' in case that might be a problem.
A:
Found the problem by reading another post, actually there was a problem with packages and classes within them, they couldn't find one another and so the table wasn't created.
I made a new project and put all classes inside the same package and it worked, so I will fix my existing project based on that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a new project from a project skeleton using git
In order to get a new django project up and running faster, I'd like to maintain a separate "project skeleton" on which I base all my new projects. It would be great if, as I improved the skeleton, I could bring those improvements into my active projects. How can I accomplish this with git?
So, maybe in my remote git repository machine I would have 1 repo for each project and one for the skeleton?
proj-A-repo
proj-B-repo
skeleton-repo
If I want to create a new proj-C locally based on the skeleton, then push my local changes up to the remote server in a new repo called proj-C-repo, how might I do this?
I've read through quite a bit of git documentation, but I'm confused about how to go about this. Do I need to clone the skeleton, or create an empty repo and then track a remote branch, or something else?
A:
This is exactly what git (or any DVCS) is good at. Give the skeleton its own repo; to create a new project you'd typically clone the skeleton onto your workstation, work away, then push to a different location (e.g. myserver:repo-C). If you later improve the skeleton and push changes to it, you can work them into an existing project with git pull myserver:skeleton and then merging.
| {
"pile_set_name": "StackExchange"
} |
Q:
Datastax Opscenter Restore Fails with TLS enabled (node-to-node encryption)?
I am using DSE version 5.09 and Opscenter version 6.08.
Opscenter restore process seems to be failing when node-to-node encryption is enabled on C* nodes. It works successfully when I disable TLS on all nodes and carry out restore process.
Has anyone faced similar issue or Is there a way around to get the restore successfully done without disabling TLS?
Also SSTableloader seems to be failing with node-to-node encryption enabled.
Is DSE restore process using SSTableloader/Opscenter isn't feasible with TLS enabled? Any opinions/comments would be appreciated. Thanks in advance
A:
DataStax OpsCenter engineer here.
This is a known issue and is tracked internally via the ticket id's DSP-14202 and OPSC-12334, if you have support or access to a sales engineer they can check the status of these tickets for you. I'm not on the DSE team, but my sense is that progress has been made on this issue and that it should be addressed in the next round of patch-releases for DSE.
In the meantime, I think you simply won't be able to use OpsCenter to perform your restores with this configuration. You'd have either disable node-to-node encryption or do restores outside of OpsCenter and pass in extra TLS options like:
JVM_OPTS="$JVM_OPTS -Dssl.keystore=$2 -Dssl.enabled=true";
JVM_OPTS="$JVM_OPTS -Dssl.keystore.password=$2";
JVM_OPTS="$JVM_OPTS -Dssl.truststore=$2 -Dssl.enabled=true";
JVM_OPTS="$JVM_OPTS -Dssl.truststore.password=$2";
| {
"pile_set_name": "StackExchange"
} |
Q:
Mathjax templates dont work on local computer
I have started to use Mathjax to develop a desktop app. I have found a very nice collection of examples and templates at: https://www.tuhh.de/MathJax/test/examples.html
However, whenever I download the HTML code of these files (with Ctrl+U) and copy it into a Notepad++ file (with .html suffix), they don't work on any local computer i have tried so far.
A:
Just replace the relative path :
<script type="text/javascript" src="../MathJax.js?config=MML_HTMLorMML-full"></script>
to
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=MML_HTMLorMML-full"></script>
(see here to choose a cdn : http://docs.mathjax.org/en/latest/start.html)
or download the js files to embed them localy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding object to list
I have a Building class with a rooms property of type List:
private List<Room> rooms;
I wrote the following method to add an room to the list:
public void addRoom(Room room) {
this.rooms.add(room);
}
This code is not raising an exception immediately, but the room is not added to list. Also, the method is called in an iteration, after returning from addRoom method to this iteration, the next iterations are skipped and then an NullPointerException is raised.
I'm creating Room objects from a file. Here's how I call the method:
Room newRoom = new Room();
newRoom.setName(meetingRoom[0]);
newRoom.setCode(meetingRoom[1]);
few more setters ...
home.addRoom(newRoom);
home is an instance of Building found by another method earlier, its value is ok according to the debugger.
A:
Is your List ever instantiated?
Try with
private List<Room> rooms = new LinkedList<>();
| {
"pile_set_name": "StackExchange"
} |
Q:
C26486 with string_view
Compilling the code below in MSVS with c++ core guidlines enabled produces warning:
C26486 LIFETIMES_FUNCTION_PRECONDITION_VIOLATION - Link to relevant Microsoft Docs
using vec_pair = std::vector<std::pair<const std::string_view, const std::string_view>>;
void foo(const vec_pair& vec_pair) noexcept
{
for (auto [first, second] : vec_pair) //<---- Warning here
{
// do stuff
}
}
int main()
{
const vec_pair my_vec_pair { {
{"yes", "no"},
{"what", "why"},
{"salt", "pepper"},
} };
foo(my_vec_pair);
return 0;
}
Description is:
Don't pass a pointer that may be invalid to a function. Parameter 0 '$S1' in call to '<move><std::pair<std::basic_string_view<char,std::char_traits<char> > const ,std::basic_string_view<char,std::char_traits<char> > const > & __ptr64>' may be invalid (lifetime.3).
Changing std::string_view to std::string does not help. Nor does checking for nullptr both before and after the for loop.
How should I deal with this?
A:
This is a bug in the Core Guidelines checker. The bug is actually in its understanding of structured bindings to tuple-like types (such as std::pair); a minimal example is:
#include <utility>
void foo(std::pair<int, int> p) noexcept {
auto const [x, y] = p;
}
It appears that the checker is being confused by the treatment of the invented variable as an xvalue; see Case 2: binding a tuple-like type at Structured binding declaration and dcl.struct.bind. A workaround is to use a ref-qualifier of & so that the invented variable is treated as an lvalue:
#include <utility>
void foo(std::pair<int, int> p) noexcept {
auto const& [x, y] = p;
// ^
}
Live example.
Note: admittedly, that workaround won't work in this case, since it falls foul of C26445: A reference to gsl::span or std::string_view may be an indication of a lifetime issue (gsl.view). If you can't suppress or ignore the warning, you'll have to use first and second like in the old days.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I define the response to a missing claim in NancyFX?
I have a module meant to enable administrators to manage users. Of course, this module requires not only authentication but also a specific claim. I have discovered that, if you are missing the claim in question, you actually get only a blank page as a response to your request. This isn't ideal.
How can I change that?
Module code below (if anyone needs to look)...
public class UserModule : NancyModule
{
public UserModule()
: base("/users")
{
this.RequiresAnyClaim(new[] { "evil-dictator" });
Get["/"] = _ =>
{
ViewBag.UserName = Context.CurrentUser.UserName;
return Negotiate.WithView("Index");
};
// Generate an invitation for a pre-approved user
Get["/invite"] = _ =>
{
throw new NotImplementedException();
};
}
}
A:
You can use an After hook to alter the response in case the claim is missing. Note that the response you get when you do not have the required claim has HTTP status code 403 Forbidden. Check for that in the After hook and alter the response as needed.
E.g. the following will redirect to the root - "/" - of the application, when the user does have the evil dictator claim:
public class UserModule : NancyModule
{
public UserModule()
: base("/users")
{
After += context =>
{
if (ctx.Response.StatusCode == HttpStatusCode.Forbidden)
ctx.Response = this.Response.AsRedirect("/");
}
this.RequiresAnyClaim(new[] { "evil-dictator" });
Get["/"] = _ =>
{
ViewBag.UserName = Context.CurrentUser.UserName;
return Negotiate.WithView("Index");
};
// Generate an invitation for a pre-approved user
Get["/invite"] = _ =>
{
throw new NotImplementedException();
};
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
LIKE clause is not working in SQL server
I have a table which have the following columns in SQL Server 2005:
DocID NSN QTY
-----------------
DHA12 32 5
DSRB23 22 45
TF22 70 23
Whenever I perform the following query to get all the NSN which have a DocId that starts with either DSRB or DHA, it gives me empty set:
SELECT DocId, NSN, Qty, RequestDate, ReceiveDate
FROM Orders
WHERE (DocID LIKE '%DSRB%')
AND (DocID LIKE '%DHA%')
I guess the problem with having two LIKE clauses because when I delete the last LIKE clause, the query works fine.
A:
You get an empty result because there is no row in your table where DocID is like both %DSRB% and %DHA% at the same time. You don't say in your question, but I guess you are expecting to receive the two rows with DocIds DHA12 and DSRB23.
To do this, you need to select rows where DocID is like either %DSRB% or %DHA%. Try changing the AND in your WHERE clause to an OR:
SELECT DocId, NSN, Qty, RequestDate, ReceiveDate
FROM Orders
WHERE (DocID LIKE '%DSRB%') OR (DocID LIKE '%DHA%')
See this introduction to SQL Logical Operators if you want more examples.
A:
If you want to find rows that contain either XX or YY, you need to use OR:
SELECT DocId, NSN, Qty, RequestDate, ReceiveDate
FROM Orders
WHERE (DocID LIKE '%DSRB%')
OR (DocID LIKE '%DHA%')
A:
Don't you want an OR in there instead of an AND?
| {
"pile_set_name": "StackExchange"
} |
Q:
Exception in loading Skin
I'm using SkinLookAndFeel and want to use aquathemepacke of SkinLookAndFeel. I've downloaded sklf.jar and aquathemepack.zip. Here is my code:
Skin skin = SkinLookAndFeel.loadSkin("aquathemepack.zip");
SkinLookAndFeel.setSkin(skin);
UIManager.setLookAndFeel(new SkinLookAndFeel());
and the exception is:
java.lang.Exception: Unable to load this skin file:/C:/Workspaces/Demo_Swing/Demo/aquathemepack.zip (by using filename matching), try an explicit constructor
at com.l2fprod.gui.plaf.skin.SkinLookAndFeel.loadSkin(SkinLookAndFeel.java:902)
at com.l2fprod.gui.plaf.skin.SkinLookAndFeel.loadSkin(SkinLookAndFeel.java:883)
at com.talk.Atalk.<init>(Atalk.java:139)
at com.talk.Atalk.main(Atalk.java:1214)
Why I'm getting this error? How can I solve this?
A:
Ok I have solved it.
Instead of using loadSkin() I use loadThemePack() and all works fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
New Tag request #Midori
I would like to have the #Midori Tag. Since this browser comes with the common Raspian OS for Raspberry-Pi and there are many tutorials using #Midori . I think it makes sense to create the tag.
A:
Ok, I created it, midori, and a tag wiki for it, and added it to a few relevant questions. It was logical since internet-explorer, firefox and opera and others already exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
Set field values in 1 place and apply those values on all other pages
I am using ACF for an ad. There are 2 fields, an image for the ad and the link where the image will lead to if clicked on. I have set them up and they are working correctly. They are required to show on the home page, and on post pages.
Now what this question is about: I would like to be able to set the ad only on the home page (or somewhere else if you have a better idea), and to apply those field values on the post pages.
Currently I set it for the home page, its ok and it works. But if I create a new blog post, I need to select the ad for every new blog post. I believe this is bad UX, because if there is only 1 ad, it would be nicer to set it once and apply it everywhere else.
What would be the best approach to implement this?
A:
The true way to do this with ACF is using the $post->ID parameter.
Say you set the value of the field on the homepage, now you wan't to bring it in on other pages the following simply wont work:
the_field('homepage_field');
You need to tell ACF what page ID to check the value for:
the_field('homepage_field', $pageID);
If you're trying to get your homepage which is set to front page in the wordpress options use the following:
$frontpage_id = (int)get_option( 'page_on_front' );
the_field('homepage_field', $frontpage_id);
This will also work with:
get_field('field_name', $pageID)
get_sub_field('field_name', $pageID)
the_sub_field('field_name', $pageID)
have_rows('field_name', $pageID)
With regards to a potential different option as you mentioned if there is one we would suggest. Try the Premium ACF Options Page plugin, this will allow you to get fields using:
the_field('field_name', 'options')
get_field('field_name', 'options')
get_sub_field('field_name', 'options')
the_sub_field('field_name', 'options')
have_rows('field_name', 'options')
| {
"pile_set_name": "StackExchange"
} |
Q:
How to administer medication to feisty cats
I wonder what other people do to get their cats to allow them to do flea treatments (advantage) or ANY other kind of medication. I have 4 cats, two older females at the age of 11 and 12 years and two tomcats who are at the age of 7 years and 4 years. None of them will tolerate us giving them any kind of treatment at all, they go wild at even the sight of the flea treatment package!
There is zero chance of "wrapping" them as they know what we intend to do and run if I even pick up a towel! Yet, we have had them all since they were kittens and handled and socialized them as you should. They are all bad but the elder tomcat is a nightmare as he is a very big cat, he weighs nearly 25 lbs (11 kg) and is long and tall. He will scratch, bite and struggle so hard to get away that he hurts us regardless of what we wear.
The same problem applies to trimming nails, so they have very sharp claws, somebody suggested a restraint for them but we know they would not allow us to even get them into one!
A:
I think the main focus here is that your cat needs to trust you. You can't just expect it to do so immediately, but I suggest you work at building a rapport with him. I'll focus my answer on the flea treatment, but the principle is the same for all the other things he does not want you to do.
This answer is based on my experience with housebreaking our two incredibly shy cats, who had lived in the wild for their first 6 months. We've had to teach them everything (other than using a litter box), starting from a position where they didn't trust any human. When out in the wild, they lived in a prison, where they survived by avoiding all humans.
Needless to say, they were apprehensive of everything we did (including feeding them, as the prison guards had tried to give them poisoned food). However, over the last 6 months we've managed to gain their trust and turn them into actual pets, so I'm confident that this method works.
Cats don't listen to people like dogs do. They are incredibly independent, and tend to always do what they think is best. Since you can't command a cat to come to you, you should try to incentivize it so that it will want to come to you.
If you want your cat to make a certain choice, then make that choice the best possible choice.
Don't expect a cat to obey you.
Not one of them will tolerate us giving them any kind of treatment at all
they would not allow us to even get them into [a harness]!
as they know what we intend to do and run if I even pick up a towel!
They are all bad but the elder tom is a nightmare
He will scratch, bite and struggle so hard to get away that he hurts us regardless of what we wear.
From these quotes, I'm starting to infer that you're expecting your cat to listen to what you want it to do. It might not like the flea treatment, but it should allow it because you're clearly indicating to them that they should allow you.
Cats are not really known for their obedience. It is possible to get them to listen, but this completely hinges on one thing: trust.
Playing the advocate for your cats: what have you done to show your cats that they can trust you?
This isn't a personal attack on you, I hope you don't read it that way. I'm trying to show you what the cats' point of view is. What do they stand to gain from allowing you to do something to them that they don't like? Because if there's no benefit to doing so, why would they want to endure it?
The wrong way
Do not overpower your cat and force him to do something against his will. This may be a quick win for you now, but it will be detrimental in the long run.
If you betray his trust by grabbing him and forcing him, then you're teaching him that it's unsafe to be around you. Over time, he will keep you at a distance, or even hide instead of come to you when you call for him.
Don't try to lure the cat in with treats and then trap him. It may work a few times, but over time he will learn to see it coming, and will refuse to come close to you. He might even end up disliking his treats (or distrusting you when you're giving him treats).
Our cat did this to us. Whenever she saw us handle the cat carrier, even if it was in a different room than me and her were currently in, she would refuse to go near any humans. After a few trips to the vet, she got wise to our tricks to get her into the carrier.
they go wild at even the sight of the flea treatment package!
as they know what we intend to do and run if I even pick up a towel!
This suggests that the cat has bad memories connected to the flea treatment package (the same goes for the towel). Whenever he's seen such a package, he ended up in an uncomfortable situation (wrestling with whoever is trying to apply the treatment).
This is essentially a Pavlovian response. The cat has identified that the uncomfortable moments are always preceded by seeing the flea treatment package, and therefore knows that it's going to be uncomfortable soon (and will avoid it al all costs).
The severity of their wild behavior directly corresponds to the severity of their (bad) experiences.
Caveat
If your cat requires urgent medical attention, then this does not apply. Medical emergencies are more important than the cat's personal comfort, or your personal relationship with him.
The right way
Doctors give lollipops to children at the end of a doctor's visit. Since this is the last interaction with the doctor, the child will remember the lollipop more than what came before it. The lollipop subconsciously teaches the child to be less afraid of having to go the the doctor.
Essentially, that's what you have to do with your cat. Make the experience (in hindsight) a positive memory, not a negative one.
Every cat, no matter how wild, will always want food when hungry. It's the most basic form of incentivization. Take away his food options except for one food bowl, and sit next to it.
Caveat
From your description, I gather that he has no problems approaching you (e.g. when you're sitting next to his food), but he puts up a fight once you interact with him in a way that he doesn't like. If your cat is fearful enough that it would rather starve than come near you (we've had a cat like that), then this approach obviously will not work.
When he starts eating, calmly start applying the flea treatment. Act as if this is the most normal thing in the world, don't act like you're pulling off a heist (cats sense the difference, at least ours do)
Given your description of your cat, I expect that he'll stop you (pull away his head). Calmly look at him, and let him continue eating. The moment he continues eating, you continue applying the treatment.
This will repeat several times, and that's okay. Most animals (and children) need repetition in order to learn something. You're teaching him that the food and the flea treatment are a package deal. He gets to make the choice: food and treatment, or no food and no treatment. (Do not starve your cat, see the next chapter)
After a few times, if he's had some food (enough to not starve, but not enough to be full) and still puts up a fight, simply take away the rest of the food and walk away. Ignore him for a minute or two. He will ask for more food at some point (whether it's 2 minutes or a few hours, depends on the cat) When he wants more food, bring the food bowl back and repeat the process.
This may take a while, you might not be able to actually apply the treatment for the first meal or two (where he ends up eating enough in small chunks that he's had his fill).
Eventually though, he should realize that putting up a fight costs him more effort than letting you do your thing.
edit: If you feel like he's not improving, and simply coasting on what little food he can scavenge before you take it away again, then wait longer before giving him more food. Again, do not starve him, but make him wait for food a bit longer. This incentivizes him to behave during feeding time.
Do not starve your cat!
I cannot stress this enough. The point of the exercise is not to punish your cat for not listening to you, you're simply trying to teach your cat to take the bad with the good (food + flea treatment).
If you treat him unfairly (forcing him, starving him, berating him for not wanting the treatment), then he will hold you responsible. This is the opposite of what you want, you're trying to get him to trust you. If your cat trusts you, then he will also trust your judgment.
If your cat is stubborn enough that he would rather starve than let you apply the flea treatment, then you should switch tactics instead of trying to outstubborn the cat.
Give him free access to (a small amount of) cat food that he doesn't really like (but will eat if hungry). However, put his favorite food in the bowl next to you.
This is the same principle as before: the choice is his, does he want the lousy free food, or the good food that comes with the flea treatment?
This is not a quick solution. But it is the best solution in the long run.
Quick fixes often end up making a dent in the cat's trust of you, which will only make future treatments more difficult.
Tangential
(Unrelated to the problem at hand, but it might help you in the long run.)
You've mentioned that none of the cats allow you to apply the flea treatment. They're probably learning from each other.
For our two cats, if the smarter one gets scared or runs away (e.g. something makes a loud bang), the other will immediately follow suit. The smarter one usually gets over it rather quickly, but the other one can take days before she forgets it. She heavily relies on the judgment of the smarter one (we see that in everything they do, especially when investigating new things)
This can have negative consequences (as you are experiencing now), but you can also turn it to your advantage: if one of the cats allows you to do something that the others don't, immediately reward it. Even petting them for a few minutes (directly after) can signal to the other cats that they are missing out on bonuses.
Edit
One more tip: You've mentioned that the cats already turn wild when they see the flea treatment box.
You're going to have to start from a disadvantaged position, as your cat already has bad memories attached to the box/syringe.
If I were you, I would first try to get the cats to forget their earlier memories. Put one of those strips in plain sight, somewhere near their food bowls (or somewhere they often have to pass by), but never use it.
Your cats will be very apprehensive in the beginning (somewhat obviously). But if they see this object every day, and it has never harmed them or been used in any way, and you don't even acknowledge that it exists, then they should stop being afraid of it after a while.
| {
"pile_set_name": "StackExchange"
} |
Q:
Attempting to Databind an ObservableCollection to a ListView the MVVM Way
I'm new to WPF/MVVM and have been attempting to bind an observable collection class to a list view, no code behind, just MVVM.
The XAML:
<Window.DataContext>
<local:acLengthCalcVM/>
</Window.DataContext>
<StackPanel>
<GroupBox Header="Section(s) Selected" Margin="3,10,3,10">
<ListView x:Name="lvSections" Margin="0,6,0,2" Height="150" ItemsSource="{Binding SectionsSelected}">
<ListView.View>
<GridView>
<GridViewColumn Header="#" Width="30"/>
<GridViewColumn Header="Reference Tag #" Width="100"/>
<GridViewColumn Header="Section Type" Width="150"/>
<GridViewColumn Header="Section Length" Width="100"/>
</GridView>
</ListView.View>
</ListView>
</GroupBox>
</StackPanel>
The View Model:
Public Class acLengthCalcVM
Implements INotifyPropertyChanged
Dim _sectionsSelected As ObservableCollection(Of acLengthCalcModel) = New ObservableCollection(Of acLengthCalcModel)
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Public Property SectionsSelected As ObservableCollection(Of acLengthCalcModel)
Get
Return _sectionsSelected
End Get
Set(value As ObservableCollection(Of acLengthCalcModel))
_sectionsSelected = value
NotifyPropertyChanged("SectionsSelected")
End Set
End Property
Private Sub NotifyPropertyChanged(Optional propertyName As String = "")
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
The Model:
Public Class acLengthCalcModel
Inherits ObservableCollection(Of acLengthCalcData)
Public Sub New()
Add(New acLengthCalcData(1, "n/a", "VTU Frame", 8))
Add(New acLengthCalcData(2, "1.1.01", "Air Conveyor Straight", 118))
End Sub
End Class
Public Class acLengthCalcData
' Constructor for this Class
Public Sub New(serialNum As Integer, refTagNum As String, sectionType As String, sectionLength As Double)
_refTagNum = refTagNum
_sectionLength = sectionLength
_sectionType = sectionType
_serialNum = serialNum
End Sub
' Reference Tag #
Private _refTagNum As String
Public Property RefTagNum As String
Get
Return _refTagNum
End Get
Set(value As String)
_refTagNum = value
End Set
End Property
' Section Length
Private _sectionLength As Double
Public Property SectionLength As Double
Get
Return _sectionLength
End Get
Set(value As Double)
_sectionLength = value
End Set
End Property
' Section Type
Private _sectionType As String
Public Property SectionType As String
Get
Return _sectionType
End Get
Set(value As String)
_sectionType = value
End Set
End Property
' Serial #
Private _serialNum As Integer
Public Property SerialNum As Integer
Get
Return _serialNum
End Get
Set(value As Integer)
_serialNum = value
End Set
End Property
End Class
When I run the code, the list view is created with only its headers, none of the data I initialized in the model constructor shows up.
Any pointers? Thanks.
A:
You should create and return an instance of a acLengthCalcModel in your view model class:
Public Class acLengthCalcVM
Implements INotifyPropertyChanged
Dim _sectionsSelected = New acLengthCalcModel
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Public Property SectionsSelected As acLengthCalcModel
Get
Return _sectionsSelected
End Get
Set(value As acLengthCalcModel)
_sectionsSelected = value
NotifyPropertyChanged("SectionsSelected")
End Set
End Property
Private Sub NotifyPropertyChanged(Optional propertyName As String = "")
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
You also need to bind each of the columns to a property of the acLengthCalcData class using the DisplayMemberBinding property:
<ListView x:Name="lvSections" Margin="0,6,0,2" Height="150" ItemsSource="{Binding SectionsSelected}">
<ListView.View>
<GridView>
<GridViewColumn Header="#" DisplayMemberBinding="{Binding SerialNum}" Width="30"/>
<GridViewColumn Header="Reference Tag #" DisplayMemberBinding="{Binding RefTagNum}" Width="100"/>
<GridViewColumn Header="Section Type" DisplayMemberBinding="{Binding SectionType}" Width="150"/>
<GridViewColumn Header="Section Length" DisplayMemberBinding="{Binding SectionLength}" Width="100"/>
</GridView>
</ListView.View>
</ListView>
| {
"pile_set_name": "StackExchange"
} |
Q:
Jewish Life vs. Opinion-based
This is not to rehash the Jewish life parameters. Go take that over there.
My question is where we draw the line between that and off-topic as opinion based. Jewish life questions seem to be of the form "Judaism causes problem X. Any tips on how to solve that?"
For instance: Exercises to prevent eyes tiring
Advice for Lighting in a Sukkah
How can I make a long summer shabbat a delight?
How do you deal with huge numbers of calls from tzedaka organizations?)
These two actually did get closed as opinion-based:
What bar/bat mitzva present did you actually want/like/use?
What would you really, actually like to receive (give?) for Mishloach Manot on Purim?
A:
From our (and every Stack Exchange site's) FAQ page on "What types of questions should I avoid asking?":
To prevent your question from being flagged and possibly removed, avoid asking subjective questions where …
every answer is equally valid: “What’s your favorite ______?”
your answer is provided along with the question, and you expect more answers: “I use ______ for ______, what do you use?”
...
Some subjective questions are allowed, but “subjective” does not mean “anything goes”. All subjective questions are expected to be constructive. What does that mean? Constructive subjective questions:
inspire answers that explain “why” and “how”
tend to have long, not short, answers
have a constructive, fair, and impartial tone
invite sharing experiences over opinions
insist that opinion be backed up with facts and references
are more than just mindless social fun
For more detail, read about our guidelines for great subjective questions and blog post about how real questions have answers.
I encourage you to read the full "Good Subjective, Bad Subjective" blog post linked above. The list of qualities of "constructive subjective questions" above is a summary of that post's guidelines for "great subjective questions." Note that this is not the same thing as hard rules for acceptable subjective questions, which that post says are difficult to draw.
In general, I think it's wise, with respect to any question that has subjective aspects, to apply the overall advice in the blog post:
Apply the six subjective question guidelines and see how it scores. If the score is low, close it. If the score is high, vote it up.
More particularly, this meta question concerns mainly questions that fall into two main categories: product-recommendation and how-to.
With respect to product recommendations, we've written what has emerged as a primary consideration into the product-recommendation tag wiki:
Questions in this tag should give explicit, specific guidelines describing the sought after qualities in the product. "A really good Fizzboop" is not sufficiently explicit and should be closed as primarily opinion based.
I'd say that a similar standard ought to apply to how-to questions: It should be clear from the question what criteria would make one answer better than another. In many cases, simply stating a particular problem to solve clearly is probably sufficient, since the implied overall criterion is how well answers solve that problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multi-dimensional array for values in a selectbox
public function getCategories()
{
$categories = array(
array('is-yemekleri', 'İş yemeklerine uygun.'),
array('bekarliga-veda', 'Bekarlığa veda partileri için uygun.'),
array('dogum-gunleri', 'Doğum günleri için uygun.'),
array('mac-yayinlari', 'Maç yayınları mevcut.'),
array('akdeniz-yunan-mutfagi', 'Akdeniz ve Yunan mutfağı mevcut.'),
array('turk-osmanli-mutfagi', 'Türk ve Osmanlı mutfağı mevcut.'),
array('italyan-mutfagi', 'İtalyan mutfağı mevcut.'),
array('fransiz-mutfagi', 'Fransız mutfağı mevcut.'),
array('uzakdogu-mutfagi', 'Uzakdoğu mutfağı mevcut.'),
array('bar-pub', 'Bar-pub mevcut.'),
array('brunch-kahvalti ', 'Brunch Kahvaltı mevcut.'),
array('partiler', 'Partiler için uygun.'),
array('cafe', 'Cafe mevcut.'),
array('club', 'Club mevcut.'),
array('dugun-mekanlari', 'Düğünler için uygun.'),
array('fasil-mekanlari', 'Fasıl için uygun.'),
array('et-restoranlari', 'Et restoranı bulunuyor.'),
array('balik-restoranlari', 'Balık restoranı bulunuyor.'),
array('meyhaneler', 'Meyhane bulunuyor.'),
array('kina-geceleri', 'Kına geceleri için uygun.'),
);
return $categories;
}
I need to output this in my view file.
There is a checkbox and it should look like this:
foreach($categories as $k => $v)
{
İş yemeklerine uygun: (second value of array)
<input type="checkbox" id="{ $k }" name="{ $k }" value="(first value of array)">
}
Output should be like this;
İş yemeklerine uygun:
<input type="checkbox" id="0" name="0" value="is-yemekleri">
Bekarlığa veda partileri için uygun.
<input type="checkbox" id="1" name="1" value="bekarliga-veda">
...
Kına geceleri için uygun.
<input type="checkbox" id="18" name="18" value="kina-geceleri">
How can I do this?
A:
Each $v in your foreach-loop is an array.
First $v:
array('is-yemekleri','İş yemeklerine uygun.') //$v[0] and $v[1]
Second $v:
array('bekarliga-veda','Bekarlığa veda partileri için uygun.') //$v[0] and $v[1]
Third $v:
array('dogum-gunleri','Doğum günleri için uygun.') //$v[0] and $v[1]
etc...
I think you're looking for something like this:
foreach($categories as $k => $v)
{
echo $v[1]; //second value of array
echo '<input type="checkbox" id="' . $k .'" name="'.$k.'" value="' . $v[0] . '" />';
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is Window.ShowDialog not blocking in TaskScheduler Task?
I'm using a custom TaskScheduler to execute a task queue in serial. The task is supposed to display a window and then block until the window closes itself. Unfortunately calling Window.ShowDialog() doesn't seem to block so the task completes and the window never displays.
If I put a breakpoint after the call to ShowDialog I can see the form has opened but under normal execution the Task seems to end so quickly you cant see it.
My TaskScheduler implementation taken from a previous question:
public sealed class StaTaskScheduler : TaskScheduler, IDisposable
{
private readonly List<Thread> threads;
private BlockingCollection<Task> tasks;
public override int MaximumConcurrencyLevel
{
get { return threads.Count; }
}
public StaTaskScheduler(int concurrencyLevel)
{
if (concurrencyLevel < 1) throw new ArgumentOutOfRangeException("concurrencyLevel");
this.tasks = new BlockingCollection<Task>();
this.threads = Enumerable.Range(0, concurrencyLevel).Select(i =>
{
var thread = new Thread(() =>
{
foreach (var t in this.tasks.GetConsumingEnumerable())
{
this.TryExecuteTask(t);
}
});
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
return thread;
}).ToList();
this.threads.ForEach(t => t.Start());
}
protected override void QueueTask(Task task)
{
tasks.Add(task);
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return tasks.ToArray();
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return Thread.CurrentThread.GetApartmentState() == ApartmentState.STA && TryExecuteTask(task);
}
public void Dispose()
{
if (tasks != null)
{
tasks.CompleteAdding();
foreach (var thread in threads) thread.Join();
tasks.Dispose();
tasks = null;
}
}
}
My Application Code:
private StaTaskScheduler taskScheduler;
...
this.taskScheduler = new StaTaskScheduler(1);
Task.Factory.StartNew(() =>
{
WarningWindow window = new WarningWindow(
ProcessControl.Properties.Settings.Default.WarningHeader,
ProcessControl.Properties.Settings.Default.WarningMessage,
processName,
ProcessControl.Properties.Settings.Default.WarningFooter,
ProcessControl.Properties.Settings.Default.WarningTimeout * 1000);
window.ShowDialog();
}, CancellationToken.None, TaskCreationOptions.None, this.taskScheduler);
A:
Nothing obviously wrong. Except what is missing, you are not doing anything to ensure that an exception that's raised in the task is reported. The way you wrote it, such an exception will never be reported and you'll just see code failing to run. Like a dialog that just disappears. You'll need to write something like this:
Task.Factory.StartNew(() => {
// Your code here
//...
}, CancellationToken.None, TaskCreationOptions.None, taskScheduler)
.ContinueWith((t) => {
MessageBox.Show(t.Exception.ToString());
}, TaskContinuationOptions.OnlyOnFaulted);
With good odds that you'll now see an InvalidOperationException reported. Further diagnose it with Debug + Exceptions, tick the Thrown checkbox for CLR exceptions.
Do beware that this task scheduler doesn't magically makes your code thread-safe or fit to run another UI thread. It wasn't made for that, it should only be used to keep single-threaded COM components happy. You must honor the sometimes draconian consequences of running UI on another thread. In other words, don't touch properties of UI on the main thread. And the dialog not acting like a dialog at all since it doesn't have an owner. And it thus randomly disappearing behind another window or accidentally getting closed by the user because he was clicking away and never counted on a window appearing from no-where.
And last but not least the long-lasting misery caused by the SystemEvents class. Which needs to guess which thread is the UI thread, it will pick the first STA thread. If that's your dialog then you'll have very hard to diagnose threading problems later.
Don't do it.
| {
"pile_set_name": "StackExchange"
} |
Q:
XML Schemas (XSD> - Can a non-empty element have a type and an attribute?
i'm relatively new to XML Schemas and i've encountered a problem. I know that for an element to have an attribute assocaited with it, it must be a complex type. However I can only figure out how to associate an attribute with an empty element (See Example 1)...is it possible to assocaite an attribute with a non-empty elemnet and have a type declared for that element (See Example 2)? I'm using Visual Studio 2008 to write the schemas...when i declare the element as a complex type it tells me that I have to remove the type declaration from the element - see below.
Example 1:
<phone units = "grams" />
Example 2:
<phone units = "grams">92</phone>
Phone.XML
<?xml version="1.0" encoding="utf-8"?>
<phone xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="XSD.xsd">
<make>Nokia</make>
<model>N700</model>
<code>532/4329</code>
<weight units ="grams">92</weight>
<price>49.99</price>
</phone>
XSD.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:attribute name ="units" type ="xs:string" />
<xs:element name ="phone">
<xs:complexType>
<xs:sequence>
<xs:element name ="make" type="xs:string" />
<xs:element name ="model" type="xs:string" />
<xs:element name ="code" type="xs:string" />
<xs:element name ="weight" type="xs:string">
<xs:complexType>
<xs:attribute name="units" type="xs:string" />
</xs:complexType>
</xs:element>
<xs:element name ="price" type="xs:double" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
I have yet to find an example on the net demonstrating this. Is it possible or do I have to sacrifice the type associated with the weigh element in order to insert the attribute?
Any help would be much appreciated....Thanks....
A:
Do something like this:
<xs:element name="weight" type="weightType">
</xs:element>
<xs:complexType name="weightType">
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="units" type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
| {
"pile_set_name": "StackExchange"
} |
Q:
Assign an identity key to non-identity key
I have a table table1, the primary key is Pkey. It is an identity column. I have another table table2 that has no primary key and identity column.
I want to insert the value of Pkey of table1 into id column of table2.
obj2.id = obj1.Pkey;
I get an exception:
Cannot insert the value NULL into column 'id', table 'table2'; column does not allow nulls. INSERT fails.
Thanks for hint. Does the system want to assign the identity property to id?
UPDATE:
Origninally table2 is empty, I created new record from entity framework.
BDetail obj2= iContext.DetailsRecords.Create();
obj2.id = obj1.Pkey;
iContext.BDetail.Add(obj2);
iContext.SaveChanges(); // exception here
A:
Is it possible that obj1 hasn't been created yet? Hence the NULL value from a primary key (which, if the row exists, can never be NULL).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use Attributes for authentications on ASP.NET Webpage?
I have a Website which has several aspx pages that derives from a PageBase class. For example one of that is below:
public partial class Pages_Home_Default : PageBase
{
}
In some of these pages, I would like to prevent access UNLESS logged in. I can get whether client is logged in or not in my PageBase with a IsMember property.
I would like to use attibutes to achive that. For example:
[AuthenticationRequired(true)]
public partial class Pages_Home_Default : PageBaseList
{
}
[AttributeUsage(AttributeTargets.Class)]
public class AuthenticationRequired : Attribute
{
public AuthenticationRequired(bool isMemberRequired)
{
Value = isMemberRequired;
}
public bool Value { get; private set; }
}
and in the PageBase for example:
protected override void OnPreInit(EventArgs e)
{
//Retrieve the AuthenticationRequired attribue value and if not authenticated Redirect client to a login page if logged in, continue displaying the page
}
I also found this to get and read the attribute
System.Reflection.MemberInfo info = typeof(Pages_Home_Default);
object[] attributes = info.GetCustomAttributes(true);
But this is not practical when you want to do it on the BASE class instead of the DERIVED one.
Can this be done?
Thank you very much
A:
Ok. I combined the code I have given earlier with a simple line from other sources and here is the code I came up with:
[AttributeUsage(AttributeTargets.Class)]
public class AuthenticationRequired : Attribute
{
public AuthenticationRequired(bool isMemberRequired)
{
Value = isMemberRequired;
}
public bool Value { get; private set; }
}
public class Utility
{
public static T GetCustomAttribute<T>(Type classType) where T : Attribute
{
object Result = null;
System.Reflection.MemberInfo Info = classType;
foreach (var Attr in Info.GetCustomAttributes(true))
{
if (Attr.GetType() == typeof(T))
{
Result = Attr;
break;
}
}
return (T)Result;
}
}
public class PageBase : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
AuthenticationRequired AttrAuth = Utility.GetCustomAttribute<AuthenticationRequired>(this.GetType());
if (AttrAuth != null && AttrAuth.Value)
{
if(!IsMember)
HttpContext.Current.Response.Redirect("Membership.aspx");
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript function is not working?
I am using javascript to match two text box values but my function is not working.
Here is my code:
<script>
function validatePassword() {
var newPassword = document.getElementById('newPasswordTB').value;
var confirmPassword =document.getElementById('confirmPasswordTB').value;
if(newPassword != confirmPassword) {
newPassword.value="";
confirmPassword.value="";
document.getElementById('newPasswordTB').focus();
document.getElementById("confirmPasswordTB").innerHTML = "not same";
}
}
</script>
<label>New Password</label>
<input type="password" name="newPassword" id="newPasswordTB" class="txtField"/><span id="newPassword" class="required"></span>
<label>Confirm Password</label>
<input type="password" name="confirmPassword" id="confirmPasswordTB" class="txtField"/><span id="confirmPassword" class="required"></span>
<input type="submit" name="submit" value="Submit" class="btnSubmit" onclick="validatePassword()">
I want to display a message if newpassword and confirmpassword is not the same.
Where i am wrong in this code?
Any help will be appreciated.
A:
You can't use innerHTML to alter the content of a textbox, because it doesn't contain any HTML, like a DIV, a SPAN or similar. It is called a "void" element. Also it is a password, so if you put a value in it, the user will not be able to see it. You should put your message in any other place. For example, in the SPAN element next to the confirmPasswordTB input:
function validatePassword() {
var newPassword = document.getElementById('newPasswordTB').value;
var confirmPassword =document.getElementById('confirmPasswordTB').value;
if(newPassword != confirmPassword) {
newPassword.value="";
confirmPassword.value="";
document.getElementById('newPasswordTB').focus();
document.getElementById("confirmPassword").innerHTML = "not same"; //Setting message in the SPAN tag
}
}
You can check it working in this fiddle: http://jsfiddle.net/w8dt0dnr/1/
| {
"pile_set_name": "StackExchange"
} |
Q:
Unexpected indent Python
I keep getting the error "unexpected indent" for the line "lijst2 = lijst + [cat]" in the following code. I have no idea why, because as far as I can see indentation seems to be correct? Please keep in mind I am a beginner. Thank you! This is my code:
for fileid in corpus.fileids():
tekst1 = corpus.words(fileid)
instantie = defaultdict(float)
cat = mijn_corpus.fileids()
for word in tekst1:
if word in freq:
instantie[word] +=1
for word in freq:
if word not in tekst1:
instantie[word] +=0
lijst1 = []
for key, value in instantie.iteritems():
lijst1.append(value)
lijst2 = lijst + [cat] # Here I get the error message: unexpected indent
resultaten.writerrow(lijst2)
A:
You mixed spaces and tabs.
The line resultaten.writerrow(lijst2) for example starts with a tab, while all your other lines starts with spaces (you even copied it into your question).
Better use a editor that shows such characters:
| {
"pile_set_name": "StackExchange"
} |
Q:
Loop outputs [object, object, object object]
I have been taking some online courses recently to try and understand the basics of programming, Gradually trying to increase the complexity of what I am learning. However I cannot seem to be able to control the output of my loop, I either get the last value or [object,object object,object object, object,object]
Any help would be greatly appreciated, I am sure this is quite simple but I have tried for in's for's and for each's and no luck so far.
{
"years": [
{
"id": "1",
"year": "2015",
"total": "55045",
"points": [
{
"id": "2",
"points": "600",
"total": "215",
"percent": "0.4"
},
{
"id": "3",
"points": "500-599",
"total": "5431",
"percent": "9.9"
},
{
"id": "4",
"points": "400-499",
"total": "14097",
"percent": "25.6"
},
{
"id": "5",
"points": "300-399",
"total": "14446",
"percent": "26.2"
},
{
"id": "6",
"points": "200-299",
"total": "9768",
"percent": "17.7"
},
{
"id": "7",
"points": "100-199",
"total": "6562",
"percent": "11.9"
},
{
"id": "8",
"points": " >100",
"total": "4526",
"percent": "8.2"
}
]
},
{
"id": "9",
"year": "2014",
"total": "54025",
"points": [
{
"id": "10",
"points": "600",
"total": "162",
"percent": "0.3"
},
{
"id": "11",
"points": "500-599",
"total": "5088",
"percent": "9.4"
},
{
"id": "12",
"points": "400-499",
"total": "13447",
"percent": "24.9"
},
{
"id": "13",
"points": "300-399",
"total": "14047",
"percent": "26"
},
{
"id": "14",
"points": "200-299",
"total": "9584",
"percent": "17.7"
},
{
"id": "15",
"points": "100-199",
"total": "6926",
"percent": "12.8"
},
{
"id": "16",
"points": " >100",
"total": "4771",
"percent": "8.8"
}
]
},
{
"id": "17",
"year": "2013",
"total": "52767",
"points": [
{
"id": "18",
"points": "600",
"total": "152",
"percent": "0.3"
},
{
"id": "19",
"points": "500-599",
"total": "4813",
"percent": "9.1"
},
{
"id": "20",
"points": "400-499",
"total": "12803",
"percent": "24.3"
},
{
"id": "21",
"points": "300-399",
"total": "13381",
"percent": "25.4"
},
{
"id": "22",
"points": "200-299",
"total": "9566",
"percent": "18.1"
},
{
"id": "23",
"points": "100-199",
"total": "6914",
"percent": "13.1"
},
{
"id": "24",
"points": " >100",
"total": "5138",
"percent": "9.7"
}
]
},
{
"id": "25",
"year": "2012",
"total": "52589",
"points": [
{
"id": "26",
"points": "600",
"total": "165",
"percent": "0.2"
},
{
"id": "27",
"points": "500-599",
"total": "5026",
"percent": "9.6"
},
{
"id": "28",
"points": "400-499",
"total": "12395",
"percent": "23.6"
},
{
"id": "29",
"points": "300-399",
"total": "13170",
"percent": "25"
},
{
"id": "30",
"points": "200-299",
"total": "9588",
"percent": "18.2"
},
{
"id": "31",
"points": "100-199",
"total": "6999",
"percent": "13.3"
},
{
"id": "32",
"points": " >100",
"total": "5276",
"percent": "10"
}
]
},
{
"id": "33",
"year": "2011",
"total": "54341",
"points": [
{
"id": "34",
"points": "600",
"total": "162",
"percent": "0.3"
},
{
"id": "35",
"points": "500-599",
"total": "4863",
"percent": "8.6"
},
{
"id": "36",
"points": "400-499",
"total": "12235",
"percent": "22.5"
},
{
"id": "37",
"points": "300-399",
"total": "13860",
"percent": "18.4"
},
{
"id": "38",
"points": "200-299",
"total": "9966",
"percent": "18.4"
},
{
"id": "39",
"points": "100-199",
"total": "7477",
"percent": "13.8"
},
{
"id": "40",
"points": " >100",
"total": "5928",
"percent": "10.9"
}
]
},
{
"id": "34",
"year": "2010",
"total": "54480",
"points": [
{
"id": "35",
"points": "600",
"total": "136",
"percent": "0.2"
},
{
"id": "36",
"points": "500-599",
"total": "4564",
"percent": "8.4"
},
{
"id": "37",
"points": "400-499",
"total": "11973",
"percent": "22"
},
{
"id": "38",
"points": "300-399",
"total": "13878",
"percent": "25.5"
},
{
"id": "39",
"points": "200-299",
"total": "10391",
"percent": "19.1"
},
{
"id": "40",
"points": "100-199",
"total": "7294",
"percent": "13.4"
},
{
"id": "41",
"points": " >100",
"total": "6244",
"percent": "11.5"
}
]
}
]
}
I am hoping someone can maybe help with controlling the output of the loop.
A:
You haven't showed any code, but I can guess that your problem is something typical in JavaScript:
JavaScript closure inside loops – simple practical example
Check out neurosnap's answer.
http://coffeescript.org/#loops
In CoffeeScript it's even simpler:
for filename in list
do (filename) ->
fs.readFile filename, (err, contents) ->
compile filename, contents.toString()
Basically, you need a lambda/IIFE inside the for loop in JavaScript to loop to avoid your problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why aren't file uploads binding to my viewmodel?
I'm trying to bind file uploads to a ViewModel (as demonstrated in this post).
But I can't get the files to bind to the Files property on the ViewModel.
Please see the code below. What am I doing wrong?
(Edit for clarity - I'd like the uploads to bind to the VM, not have them as an Action parameter.)
ViewModel
public class PrimaryImageUploadViewModel
{
public PrimaryImageUploadViewModel()
{
}
public HttpPostedFileBase[] Files { get; set; }
public string Title { get; set; }
}
Action
[HttpPost]
public async Task<ActionResult> Upload(PrimaryImageUploadViewModel postedModel)
{
var requestFiles = postedModel.Files; // THIS VALUE IS NULL - WHY?
foreach (var f in requestFiles)
{
if (f.ContentLength == 0)
{
// do stuff
}
}
}
Request Headers
Accept:*/*
Content-Disposition:attachment; filename="MyImage.png"
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEj8zSF9hwGU3ZQA9
Origin:http://localhost:52588
Referer:http://localhost:52588/example/edit/1
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
------WebKitFormBoundaryEj8zSF9hwGU3ZQA9
Content-Disposition: form-data; name="Title"
Some Test Title
------WebKitFormBoundaryEj8zSF9hwGU3ZQA9
Content-Disposition: form-data; name="files[]"; filename="MyImage.png"
Content-Type: image/png
------WebKitFormBoundaryEj8zSF9hwGU3ZQA9--
A:
public class Model1
{
public HttpPostedFileBase[] Files { get; set; }
public string Title { get; set; }
}
Hope this helps...
| {
"pile_set_name": "StackExchange"
} |
Q:
ViewState handler updateLayout method never get hit when handled within default.js
I am starting with a blank template where I get a default.htm and default.js. I want to handle the event when app goes from full to snap or filled mode etc. I have added updateLayout method but when I add a breakpoint here, its never get hit. The break point on ready method is getting hit. What am I doing wrong here?
// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
"use strict";
WinJS.UI.Pages.define("default.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
},
unload: function () {
// TODO: Respond to navigations away from this page.
},
updateLayout: function (element, viewState, lastViewState) {
}
});
})();
A:
It's a bit confusing, but updateLayout isn't actually an event handler.
The navigation framework, which is included when starting from other templates, handles a different event (window.onresize), and calls the updateLayout function if it exists. If you create a new project using the Navigation template, for example, and inspect navigator.js, you will see where the onresize event is handled, and the updateLayout function is called.
If you start from the Blank template, this functionality is not in place, so you would either need to (a) handle the onresize event, (b) add navigator.js to your project, or (c) use a different project template.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ingreso de datos arroja datatype mismatch (code 20)
El problema sucede al iniciar la app con SQlite se cae por el tema que dice que datos datos que no coinciden si alguien tiene alguna idea sobre este error seria de gran ayuda cualquier aporte para solucionarlo
Helper
public class ConexionHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "DAATAA";
private static final int VERSION = 2;
public static final String TABLE = "pizza";
public static final String ID = "id";
public static final String NOMBRE = "nombre";
public static final String FOTO = "foto1";
public static final String INGREDIENTE1 = "igrediente1";
public static final String INGREDIENTE2 = "igrediente2";
public static final String INGREDIENTE3 = "igrediente3";
public static final String INGREDIENTE4 = "igrediente4";
public static final String CALIFICACION = "calificacion";
public static final String DESCRIPCION = "descripcion";
public static final String PRECIO = "precio";
public ConexionHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String script = "";
script += "create table " + TABLE + "(";
script += ID + " integer primary key autoincrement,";
script += NOMBRE + " text,";
script += FOTO + " text,";
script += INGREDIENTE1 + " text,";
script += INGREDIENTE2 + " text,";
script += INGREDIENTE3 + " text,";
script += INGREDIENTE4 + " text,";
script += CALIFICACION + " integer";
script += DESCRIPCION + " text,";
script += PRECIO + " integer";
script += ");";
db.execSQL(script);
db.execSQL("insert into " + TABLE + " values( 'Española',"+ R.drawable.pizza_espanola+" , "+R.drawable.espa_ola1+" , "+R.drawable.espa_ola2+" , "+R.drawable.espa_ola3+" , "+R.drawable.espa_ola4+" ,5, 'ÑAMI ÑAMI',7500);");
db.execSQL("insert into " + TABLE + " values( 'Todas Las Carnes'," + R.drawable.todascarne + "," + R.drawable.todas1 + "," + R.drawable.todas2 + " ," + R.drawable.todas3 + " ," + R.drawable.todas4 + " ,4, 'DELICHIUSS',5500);");
db.execSQL("insert into " + TABLE + " values( 'Vegetariana'," + R.drawable.vegetariana + "," + R.drawable.veg1 + "," + R.drawable.veg2 + " ," + R.drawable.veg3 + " ," + R.drawable.veg4 + " ,3, 'KAKAKAK',1500);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table " + TABLE);
onCreate(db);
}
}
CRUD
public class CRUD {
private ConexionHelper helper;
private ContentValues values;
private SQLiteDatabase db;
public CRUD(Context context) {
helper = new ConexionHelper(context);
values = new ContentValues();
}
public void insert(Pizza p) {
db = helper.getWritableDatabase();
values.clear();
values.put(ConexionHelper.NOMBRE, p.nombre);
values.put(ConexionHelper.FOTO, p.foto1);
values.put(ConexionHelper.INGREDIENTE1, p.igrediente1);
values.put(ConexionHelper.INGREDIENTE2, p.igrediente2);
values.put(ConexionHelper.INGREDIENTE3, p.igrediente3);
values.put(ConexionHelper.INGREDIENTE4, p.igrediente4);
values.put(ConexionHelper.CALIFICACION, p.calificacion);
values.put(ConexionHelper.DESCRIPCION, p.descripcion);
values.put(ConexionHelper.PRECIO, p.precio);
db.insert(ConexionHelper.TABLE, null, values);
db.close();
}
public void delete(String id) {
String pk = id + "";
db = helper.getWritableDatabase();
db.delete(ConexionHelper.TABLE,
ConexionHelper.ID + "=?",
new String[]{pk});
db.close();
}
public void update(Pizza p) {
db = helper.getWritableDatabase();
values.clear();
values.put(ConexionHelper.NOMBRE, p.nombre);
values.put(ConexionHelper.FOTO, p.foto1);
values.put(ConexionHelper.INGREDIENTE1, p.igrediente1);
values.put(ConexionHelper.INGREDIENTE2, p.igrediente2);
values.put(ConexionHelper.INGREDIENTE3, p.igrediente3);
values.put(ConexionHelper.INGREDIENTE4, p.igrediente4);
values.put(ConexionHelper.CALIFICACION, p.calificacion);
values.put(ConexionHelper.DESCRIPCION, p.descripcion);
values.put(ConexionHelper.PRECIO, p.precio);
String pk = p.id + "";//String.valueOf(m.id);
db.update(ConexionHelper.TABLE,
values,
ConexionHelper.ID + "=?",
new String[]{pk});
db.close();
}
public Pizza find(String id) {
Pizza p = new Pizza();
db = helper.getReadableDatabase();
String sql = "select * from " + ConexionHelper.TABLE + " where " + ConexionHelper.ID + "=?";
String pk = id + "";
Cursor cursor = db.rawQuery(sql, new String[]{pk});
if (cursor.moveToNext()) {
p.id = cursor.getString(0);
p.nombre = cursor.getString(1);
p.foto1 = cursor.getInt(2);
p.igrediente1 = cursor.getInt(3);
p.igrediente2 = cursor.getInt(4);
p.igrediente3 = cursor.getInt(5);
p.igrediente4 = cursor.getInt(6);
p.calificacion = cursor.getInt(7);
p.descripcion = cursor.getString(8);
p.precio = cursor.getInt(9);
}
db.close();
return p;
}
public List<Pizza> pizzaList() {
List<Pizza> list = new ArrayList<>();
db = helper.getReadableDatabase();
String sql = "select * from " + ConexionHelper.TABLE;
Cursor cursor = db.rawQuery(sql, null);
while (cursor.moveToNext()) {
Pizza p = new Pizza();
p.id = cursor.getString(0);
p.nombre = cursor.getString(1);
p.foto1 = cursor.getInt(2);
p.igrediente1 = cursor.getInt(3);
p.igrediente2 = cursor.getInt(4);
p.igrediente3 = cursor.getInt(5);
p.igrediente4 = cursor.getInt(6);
p.calificacion = cursor.getInt(7);
p.descripcion = cursor.getString(8);
p.precio = cursor.getInt(9);
list.add(p);
}
db.close();
return list;
}
}
Logcat
2018-11-12 00:14:19.311 11014-11014/? E/SQLiteLog: (20) statement aborts at 5: [insert into pizza values( 'Española',2131165324 , 2131165287 , 2131165288 , 2131165289 , 2131165290 ,5, 'ÑAMI ÑAMI',7500);] datatype mismatch
2018-11-12 00:14:19.312 11014-11014/? D/AndroidRuntime: Shutting down VM
2018-11-12 00:14:19.313 11014-11014/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.proyecto.pizzaappproyect, PID: 11014
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.proyecto.pizzaappproyect/com.example.proyecto.pizzaappproyect.MainActivity}: android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2668)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2729)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6169)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
Caused by: android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20)
at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:734)
at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1679)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
at com.example.proyecto.pizzaappproyect.DB.ConexionHelper.onCreate(ConexionHelper.java:47)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
at com.example.proyecto.pizzaappproyect.DB.CRUD.pizzaList(CRUD.java:97)
at com.example.proyecto.pizzaappproyect.MainActivity.onCreate(MainActivity.java:59)
at android.app.Activity.performCreate(Activity.java:6692)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2621)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2729)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6169)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
FOTO
A:
De acuerdo a el error mostrado en el LogCat:
SQLiteLog: (20) statement aborts at 5: [insert into pizza values(
'Española',2131165324 , 2131165287 , 2131165288 , 2131165289 ,
2131165290 ,5, 'ÑAMI ÑAMI',7500);] datatype mismatch
El problema es que alguno o varios valores que tratas de insertar en la tabla son del tipo incorrecto, esta es la estructura de tu tabla y los tipos de los campos:
script += "create table " + TABLE + "(";
script += ID + " integer primary key autoincrement,";
script += NOMBRE + " text,";
script += FOTO + " text,";
script += INGREDIENTE1 + " text,";
script += INGREDIENTE2 + " text,";
script += INGREDIENTE3 + " text,";
script += INGREDIENTE4 + " text,";
script += CALIFICACION + " integer";
script += DESCRIPCION + " text,";
script += PRECIO + " integer";
script += ");";
Estas tratando de insertar valores tipo INTEGER en donde tienes definidos campos TEXT lo cual es incorrecto:
db.execSQL("insert into " + TABLE + " values( 'Española',"+ R.drawable.pizza_espanola+" , "+R.drawable.espa_ola1+" , "+R.drawable.espa_ola2+" , "+R.drawable.espa_ola3+" , "+R.drawable.espa_ola4+" ,5, 'ÑAMI ÑAMI',7500);");
Puedes realizar este cambio:
db.execSQL("insert into " + TABLE + " values( 'Española', '"+ R.drawable.pizza_espanola+"' , '"+R.drawable.espa_ola1+"' , '"+R.drawable.espa_ola2+"' , '"+R.drawable.espa_ola3+"' , '"+R.drawable.espa_ola4+"' ,5, 'ÑAMI ÑAMI',7500);");
En tu método find() estas obteniendo valores tipo INTEGER de campos que previamente definiste como TEXT, lo cual también es incorrecto:
public Pizza find(String id) {
Pizza p = new Pizza();
db = helper.getReadableDatabase();
String sql = "select * from " + ConexionHelper.TABLE + " where " + ConexionHelper.ID + "=?";
String pk = id + "";
Cursor cursor = db.rawQuery(sql, new String[]{pk});
if (cursor.moveToNext()) {
p.id = cursor.getString(0);
p.nombre = cursor.getString(1);
p.foto1 = cursor.getInt(2);
p.igrediente1 = cursor.getInt(3);
p.igrediente2 = cursor.getInt(4);
p.igrediente3 = cursor.getInt(5);
p.igrediente4 = cursor.getInt(6);
p.calificacion = cursor.getInt(7);
p.descripcion = cursor.getString(8);
p.precio = cursor.getInt(9);
}
db.close();
return p;
}
Es importante saber que si deseas guardar los id´s de imágenes que se encuentran en tu proyecto como son:
R.drawable.pizza_espanola
R.drawable.espa_ola1
R.drawable.espa_ola2
R.drawable.espa_ola3
R.drawable.espa_ola4
lo recomendable sería guardarlos en campos tipo INTEGER.
| {
"pile_set_name": "StackExchange"
} |
Q:
MSDeploy runCommand using relative path
I am trying to run a command as a part of my packaging/deployment process via MSDeploy. In particular, I am trying to create a custom event log by running installutil against one of my DLLs, but I am having trouble with specifying a relative path to the DLL from the deployment directory. To get started, I added the below config to my csproj in order to generate the runCommand provider inside of my Manifest file. Please note the absolute path to the DLL.
<PropertyGroup>
<!-- Extends the AfterAddIisSettingAndFileContentsToSourceManifest action to create Custom Event Log -->
<IncludeEventLogCreation>TRUE</IncludeEventLogCreation>
<AfterAddIisSettingAndFileContentsToSourceManifest Condition="'$(AfterAddIisSettingAndFileContentsToSourceManifest)'==''">
$(AfterAddIisSettingAndFileContentsToSourceManifest);
CreateEventLog;
</AfterAddIisSettingAndFileContentsToSourceManifest>
</PropertyGroup>
<Target Name="CreateEventLog" Condition="'$(IncludeEventLogCreation)'=='TRUE'">
<Message Text="Creating Event Log" />
<ItemGroup>
<MsDeploySourceManifest Include="runCommand">
<path>installutil C:\inetpub\wwwroot\MyTestApp\bin\BusinessLayer.dll</path>
</MsDeploySourceManifest>
</ItemGroup>
</Target>
<ItemGroup>
After calling msbuild, this generated my manifest correctly inside of my package.zip. When I ran MyTestApp.deploy.cmd /Y it correctly called msdeploy and deployed my files to inetpub\wwwroot\MyTestApp and ran my command from the manifest below:
<runCommand path="installutil C:\inetpub\wwwroot\MyTestApp\bin\BusinessLayer.dll ... etc
The problem I am having is I do not want to hardcode this DLL path to c:\inetpub\etc. How can I make the above call using the relative path from my deployment directory under Default Web Site? Ideally, I would like MSDeploy to take this path and pass it as a variable to the runCommand statement in order to find the DLL. Then I could write something like: <path>installutil $DeploymentDir\NewTestApp\bin\BusinessLayer.dll</path> without having to worry about hard-coding an absolute path in.
Is there any way to do this without using the absolute path to my DLL every time?
A:
You can add definition of DeploymentDir to the .csproj with the action you wrote above:
<PropertyGroup>
<DeploymentDir Condition="'$(Configuration)'=='Release' AND '$(DeploymentDir)'==''">Release Deployment Dir</DeploymentDir>
<DeploymentDir Condition="'$(Configuration)'=='Debug' AND '$(DeploymentDir)'==''">Debug Deployment Dir</DeploymentDir>
<DeploymentDir Condition="'$(DeploymentDir)'==''">C:\inetpub\wwwroot</DeploymentDir>
<AplicationName Condition="'$(Configuration)'=='Release' AND '$(AplicationName)'==''">NewTestApp</AplicationName>
<AplicationName Condition="'$(Configuration)'=='Debug' AND '$(AplicationName)'==''">MyTestApp</AplicationName>
<ApplicationDeploymentDir Condition="'$(ApplicationDeploymentDir)'==''">$(DeploymentDir)\$(ApplicationName)\bin</ApplicationDeploymentDir>
</PropertyGroup>
Theese conditions will allow to change everything from command line to take full control over the build process in your build system or script.
MSBuild.exe yourproj.proj /p:Configuration=Release /p:DeploymentDir=D:\package /p:ApplivationName=BestAppForever
And inside of your task you can use it
<ItemGroup>
<MsDeploySourceManifest Include="runCommand">
<path>installutil $(ApplicationDeploymentDir)\BusinessLayer.dll</path>
</MsDeploySourceManifest>
</ItemGroup>
A:
I realize this isn't the answer you probably wanted to hear but this is how I got around it.
We created a powershell script on the destination server. So instead of running your command:
installutil C:\inetpub\wwwroot\MyTestApp\bin\BusinessLayer.dll ... etc
We would run:
c:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe d:\powershell\installSites.ps1 siteName <NUL
The "sitename" is being passed in as a param into the powershell script. Inside the script it knows on that destination server which files to install, any commands that need to run, app pools to recycle, etc.
Again, not as easy as finding a relative path, but it does the job.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to send uri request via a GET from C# to PHP and get chars encoded as a browser does?
I am making a GET from C#.
var result = webClient.DownloadString(
Microsoft.JScript.GlobalObject.encodeURI(
"http://www.example.com?value=contacts[contact][0][name]=test man"
);
This results in the recieving PHP site:
"value=contacts%5Bcontact%5D%5B0%5D%5Bname%5D=test%20man"
After decoding in PHP
urldecode($value)
"value=contacts%5Bcontact%5D%5B0%5D%5Bname%5D=test man"
So error on the [
But when i paste the url in a browser (IE8 or Chrome) i get this results in the recieving PHP site:
"value=contacts[contact][0][name]=test%20man"
IE. The browser sends the request (url) in a workable encoding, my code does not.
How do I use the GET with the correct encoding, as the browsers do?
A:
It was a lot of chars that had higher Code Points, that needs a %25 infront to parse right in PHP.
Ex. å = %C3%E5 in encoding .NET
but shold be:
%25C3%25E5
So I made a function for correcting this, it is not complete for reuse, but will be if all other codes are added.
var urlCodes = new [] { "20", "C3", "84", "85", "96", "A4", "A5", "B6", "2C", "C2", "A0", "2F", "40", "3A" };
foreach (var stringsUrlCodes in urlCodes)
{
encodedUrl = encodedUrl.Replace("%" + stringsUrlCodes.ToString(), "%25" + stringsUrlCodes.ToString().Replace("%", string.Empty));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
sort a list of percentages
I have the following list:
l = ['50%','12.5%','6.25%','25%']
Which I would like to sort in the following order:
['6.25%','12.5%','25%','50%']
Using l.sort() yields:
['12.5%','25%','50%','6.25%']
Any cool tricks to sort these lists easily in Python?
A:
You can sort with a custom key
b =['52.5%', '62.4%', '91.8%', '21.5%']
b.sort(key = lambda a: float(a[:-1]))
This resorts the set, but uses the numerical value as the key (i.e. chops of the '%' in the string and converts to float.
| {
"pile_set_name": "StackExchange"
} |
Q:
Purpose of Cycle and Edge-Cut Vector Spaces?
I'm currently studying out of Dummit and Foote's Graph Theory and Its Applications (2nd ed.), and am having trouble understanding the significance of one of the sections. More specifically, section 4.6 defines a vector space of edge subsets of a graph over the scalar field $GF(2)$. They then consider the subspaces of cycles and edge-cuts in this vector spaces, and define a basis for each space in terms of the fundamental systems of cycles and edge-cuts of spanning trees. This allows them to find the dimension of the cycle and edge-cut spaces and prove that the two spaces are orthogonal to each other.
Establishing links between graph theory and linear algebra seems good and useful. However, the definition of the edge space of a graph fields rather forced, and the book doesn't provide any particularly deep results about it. My question is this: what makes the edge, cycle, and edge-cut vector spaces useful objects of study? Is there some important theorem that hinges on them somehow? Do they motivate an interesting area of study? Sorry if this question is too open-ended, but I've asked my professors and done some online research to no avail.
A:
The vector space of cycles of a graph is the simplest nontrivial case of the homology group of a simplicial complex, so in some sense this vector space motivates about half of algebraic topology.
Back in the realm of graph theory, a cycle basis is relevant to solving many problems whose constraints arise from the cycles of a graph, because a small basis stands in for exponentially many cycles. A simple example of this is the application of Kirchoff's law for the potential differences in an electric circuit.
The law states that around any cycle, the sum of the potential differences is $0$. This gives as many constraints as there are cycles, and in a dense graph, many of them are redundant and it's not clear what the relevant ones are. A cycle basis gives us a small list of sufficient constraints.
| {
"pile_set_name": "StackExchange"
} |
Q:
validation code not working in php
i am validate my textbox that only contain numbers and also it can be null or blank.but when i leave it blank or enter any number it always display error message "Passing Year Only Contain Numbers.".my code is
<?php
include "config.php";
function is_valid_fname($postg_year)
{
if ( !preg_match ("/^[0-9\s]+$/",$postg_year)) {
?>
<center><strong><font color="red">Passing Year Only Contain Numbers.</font></strong></center>
<?php
return false;
}
}
if (isset($_POST['submit'])) {
$postg_year=$_POST['postg_year'];
if(is_valid_fname($postg_year))
{
//my code
}
<form method="post">
<input type="text" name="postg_year" class="small_text" width="60">
<input type="submit" name="submit" value="submit">
</form>
}
A:
if I understand correctly...
change this:
if ( !preg_match ("/^[0-9\s]+$/",$postg_year)) {
into this:
if ( !preg_match ("/^[0-9\s]*$/",$postg_year)) {
the difference being that "+" requires at least one character, while "*" accepts even 0 characters.
| {
"pile_set_name": "StackExchange"
} |
Q:
which ide is use for create and debug a apache cordova PLUGIN
I'm going to develop an Apache Cordova Plugin.
Which IDE is the best,i need to develop a plugin for apache cordova but i do not if correct my source...
A:
To develop the javascript part of your plugin you can always use the IDE you usually use for cordova development (e.g. Visual Studio Code). Depending on which platforms you want to support with your plugin you will need one or more of the following IDEs:
Android Studio to develop/run the Android platform (Java)
XCode to develop/run the iOS platform (Objective-C)
To get started I suggest to clone a simple existing plugin and rename it, remove all code you don't need, etc. so it fits your needs. Then you can add the local plugin to your project:
cordova plugin add <path to your local plugin>
Then you open the native IDE (e.g. Android Studio) and import the native project located in platfroms/android. Then you can start to edit the .java files of your plugin and run it on a device via the IDE. When you're done don't forget to copy back your changes to your plugin folder otherwise the changes will be lost if you remove the platform.
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert seconds since 01-01-1900 to timestamp in Brazil
I'm managing devices that report their system clock as seconds since midnight 01-01-1900.
I need to convert this into a timestamp.
So far, I'm doing this as follows:
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TestTime
{
// Pass seconds since 01-01-1900 00:00:00 on the command line
public static void main(String[] args)
{
// ---------------------
// Create time formatter
// ---------------------
SimpleDateFormat format;
format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// ---------------------------
// Compose 01-01-1900 00:00:00
// ---------------------------
Calendar cal;
cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1900);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// -------------------
// Show what we've got
// -------------------
System.out.println(format.format(cal.getTime()));
// ---------------------------------------------
// Add the seconds as passed on the command line
// ---------------------------------------------
long secs = Long.parseLong(args[0]);
while (secs > Integer.MAX_VALUE)
{
cal.add(Calendar.SECOND, Integer.MAX_VALUE);
secs -= Integer.MAX_VALUE;
}
cal.add(Calendar.SECOND, (int)secs);
// -------------------
// Show what we've got
// -------------------
System.out.println(args[0] + " corresponds to " + format.format(cal.getTime()));
} // main
} // class TestTime
When running this on my local PC (Italy, Windows 7), I get the following:
java -cp . TestTime 3752388800
1900-01-01 00:00:00
3752388800 corresponds to 2018-11-28 10:13:20
This is perfectly correct.
I get the same results when running this on a Linux machine (still in Italy).
However, running the very same program on a Linux machine in Brazil, I get different results:
java -cp . TestTime 3752388800
1900-01-01 00:00:00
3752388800 corresponds to 2018-11-28 11:19:48
Whatever value I pass on the commandline, the difference is always 01:06:28.
Any idea where this difference is coming from?
BTW, I'm not concerned about the timezone. I just need a timestamp
Update 1:
The very same thing happens also when using Java 6 (which is the actual version used within our production environment in Brazil).
So, the problem does not depend on the java version
Update 2:
The problem does not occur when entering a number of seconds below 441763200 (which corresponds to 01-01-1914 00:00:00)
The question remains why we get a difference for Brazil?
A:
java.time
A solution is to make sure you do your conversion in UTC:
Instant base = LocalDate.of(1900, Month.JANUARY, 1)
.atStartOfDay(ZoneOffset.UTC)
.toInstant();
String secsSince1900String = "3752388800";
long secsSince1900 = Long.parseLong(secsSince1900String);
Instant target = base.plusSeconds(secsSince1900);
System.out.println(target);
Output (independent of JVM time zone):
2018-11-28T10:13:20Z
The trailing Z in the output means UTC. I have tested while setting my JVM’s default time zone to America/Sao_Paulo, it made no difference. If you want, you can formate the date and time to your liking, for example:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = target.atOffset(ZoneOffset.UTC).format(formatter);
System.out.println(formattedDateTime);
2018-11-28 10:13:20
What went wrong when running in Brazil?
There are a number of time zones across Brazil. I took São Paulo as an example and reproduced your output readily. At the turn of the century in 1900, São Paulo was at offset -03:06:28 from GMT. Your Calendar uses the JVM’s default time zone, so you really set its time of day to 03:06:28 GMT, which explains the difference.
That said, the date-time classes you were using — SimpleDateFormat and Calendar — have design problems and have fortunately been replaced by java.time, the modern Java date and time API, with Java 8 nearly 5 years ago. One trait of the modern API is we more naturally make time zone explicit, which makes it easier to avoid issues like yours, and also to fix them if we run into them anyway.
Question: Our production Java version is Java 6. Can I use java.time?
Yes, java.time works nicely on Java 6. It has been backported.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
A:
On Jan 1st, 1914 Brazil changed the time and added 6 minutes and 28 seconds to their time moving from LMT to BRT (see Time Changes in São Paulo Over the Years, 1900-1924).
The additional one hour of difference is probably that Brazil spans 3 time zones (UTC-4, UTC-3, UTC-2) and you didn't set the time zone in your code, depending on the JVM system time zone.
A:
Have a look at this site: https://www.timeanddate.com/time/zone/brazil/sao-paulo and navigate to Time zone changes for: 1900-1924. There you can see an offset of -03:06:28 to UTC before 01-01-1914. It is exactly the same reason as in Why is subtracting these two times (in 1927) giving a strange result?
| {
"pile_set_name": "StackExchange"
} |
Q:
Firebase Cloud Function error: Some values show as undefined?
I am designing a game experience for students. The game is like jeopardy and it writes data to the real time database as students progress through the game. At the end of the game I would like to send students an email confirming that they have finished with their score and finish time/date.
I have set up the following code in cloud functions to do so. However, when I run the code off of the trigger, some of the values I read from the database show as undefined - this means that some of the data is not present in the email. What is going on here???
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'https://[MY DATABASE URL]/'
});
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: gmailEmail,
pass: gmailPassword,
},
});
var email;
var exitTime;
var name;
var userScore;
exports.gameDoneNotice=functions.database.ref("USERS/{termDate}/GameData/{myUID}/ExitDateTime")
.onCreate(async (snapshot, context) => {
const myNumber = context.params.myUID;
const myRotation = context.params.termDate;
var adminDB = admin.database();
exitTime = snapshot.val();
var aRef = adminDB.ref("USERS/" + myRotation + "/GameData/" + myNumber + "/");
aRef.on("value", (snapshot) => {
email = snapshot.child("eMail").val();
name = snapshot.child("Name").val();
userScore = snapshot.child("User Score").val();
});
var emailsaad = "[email protected]";
console.log(myNumber);
console.log(myRotation);
console.log(userScore);
console.log(name);
const APP_NAME = 'WCM-Q DeLib eLearning';
const mailOptions = {
from: `${APP_NAME} <[email protected]>`,
to: email,
bcc: emailsaad,
};
mailOptions.subject = `Welcome to ${APP_NAME}!`;
mailOptions.html = `<h3>Dear, ${name}</h3><p>Thank you for completing the Medicine Clerkship EBM game.</p><hr><h4>Your Score: <font color="red">${userScore}</font></h4><h4>Game Completion Time/Date: <font color="green">${exitTime}</font></h4><hr><p>If you have any questions about the game or your EBM project in this clerkship, don’t hesitate to ask for clarification. Otherwise, your next step is to begin to prepare with your group for your presentation.</p>`;
try {
await mailTransport.sendMail(mailOptions);
console.log("eMail was a success");
} catch(error) {
console.error('Something has gone horribly wrong, bro!', error);
}
return null;
});
I expect that I should be able to read the values I need for email, userScore, etc. from the database and include them in the mailOptions before it is send. However, when I receive the email after the trigger, all of the values from the database read are "undefined."
A:
Instead of using the on() method, which sets a listener "for data changes at a particular location", you need to use the once() method, which "listens for exactly one event of the specified event type" and returns a Promise. You will then be able to use await to make the Cloud Function waiting until the promise returned by once() resolves and returns its result.
You should therefore modify your code as follows:
exports.gameDoneNotice = functions.database
.ref('USERS/{termDate}/GameData/{myUID}/ExitDateTime')
.onCreate(async (snapshot, context) => {
const myNumber = context.params.myUID;
const myRotation = context.params.termDate;
var adminDB = admin.database();
exitTime = snapshot.val();
var aRef = adminDB.ref(
'USERS/' + myRotation + '/GameData/' + myNumber + '/'
);
try {
const snapshot = await aRef.once('value');
const email = snapshot.child('eMail').val();
const name = snapshot.child('Name').val();
const userScore = snapshot.child('User Score').val();
const emailsaad = '[email protected]';
console.log(myNumber);
console.log(myRotation);
console.log(userScore);
console.log(name);
const APP_NAME = 'WCM-Q DeLib eLearning';
const mailOptions = {
from: `${APP_NAME} <[email protected]>`,
to: email,
bcc: emailsaad
};
mailOptions.subject = `Welcome to ${APP_NAME}!`;
mailOptions.html = `<h3>Dear, ${name}</h3><p>Thank you for completing the Medicine Clerkship EBM game.</p><hr><h4>Your Score: <font color="red">${userScore}</font></h4><h4>Game Completion Time/Date: <font color="green">${exitTime}</font></h4><hr><p>If you have any questions about the game or your EBM project in this clerkship, don’t hesitate to ask for clarification. Otherwise, your next step is to begin to prepare with your group for your presentation.</p>`;
await mailTransport.sendMail(mailOptions);
//Here, actually you could also do return mailTransport.sendMail(mailOptions); , see the video mentioned below
} catch (error) {
console.error('Something has gone horribly wrong, bro!', error);
}
});
You may watch the official Firebase video series by Doug Stevenson which explains all these points. In particular the 3 videos about "JavaScript Promises" and the video about async/await: https://www.youtube.com/watch?v=Jr7pDZ1RAUg
| {
"pile_set_name": "StackExchange"
} |
Q:
ast.literal_eval power support
How to evaluate user input mathematical expressions such as power safely?
Tried using ast.literal_eval but it raises an exception.
>>> import ast
>>> ast.literal_eval('2**2')
ValueError: malformed node or string: <_ast.BinOp object at ...>
A:
You can use seval package for arithmetic operations and literals safe evaluation.
>>> import seval
>>> seval.safe_import('2 ** 2')
4
| {
"pile_set_name": "StackExchange"
} |
Q:
Letter-only collation (was: Weird file ordering in Emacs dired with my locale)
I just noticed. And this is creepy. But here's my screenshot. So help me, maybe!
TL;DR
The question's at the bottom.
Symptom
-rw-r--r-- 1 jb jb 24287 mars 21 2012 array.c
-rw-r--r-- 1 jb jb 28767 oct. 1 2014 arrayfunc.c
-rw-r--r-- 1 jb jb 2895 mai 11 2012 arrayfunc.h
-rw-rw-r-- 1 jb jb 4030 mars 29 2009 array.h
-UUU:%%--F1 bash-4.3.30 6% L9 (Dired by name)---------------------
(This is an emacs -nw screenshot. Yes, my terminal is 6 lines tall. It makes the screenshots more to-the-point. The locale is French, and that's expected. It's not that different to English, just imagine there's a “may” instead of « mai » and the months are Capitalized and truncated to three characters)
In case you missed it, it's dired mode, the files are supposed to be sorted by name (says so in the modeline) yet array.c and array.h aren't together!
Panic
I was looking for array.c, had the cursor beneath so whoa dude where is it it was there a minute ago. Then I actually find it. Then I check the modeline. Then I go WTF I'm asking SO. Then I notice it's in French they'll never understand better take a new screenshot with LC_ALL=C.
But that fixed the problem.
(Yes, it really happened.)
So it's a locale thing
My locale is fr_FR.UTF-8
$ ls ar* | $ LC_ALL=C ls ar*
array.c | array.c
arrayfunc.c | array.h
arrayfunc.h | arrayfunc.c
array.h | arrayfunc.h
(That's when I remove the emacs tag and start wondering if anyone actually follows collation seriously)
Seems it's the norm
I'll spare you the arcane shell invocations, but the gist of it: of the 29 locales I've got installed here, all but three use the “weird” ordering. Those three are: C, C.UTF-8 and POSIX.
It goes without saying, but there's no harm in mentioning it anyway: the “weird” ordering disturbs me, but it makes sense in its own way: on this small sample set it orders lexicographically as usual, only ignoring the period. So arrayc < arrayf < arrayh.
Question
Why? WHY? WHY??? It's in every locale but C, so it's deliberate. What rule is this based on? Did someone in some committee erect and convict: “thou shalt not observe thy punctuation whilst collating”? There's probably some legitimate serious document where they say it's perfectly normal, here's why, right?
It's the first time in oh so many years that I notice.
It also ignores spaces, of course.
Bonus: It's the bash-4.3.30 tarball from gnu.org. Why are some files 0664 and others 0644? Keep answers to that in the comments.
Also: I'm not asking how to fix it. In case you hadn't noticed, I already fixed don't really need to fix it. Plus, this has dupes everywhere. What I'm asking is why.
A:
ANSWER: The Unicode Consortium came to the conclusion that having a guaranteed sort order, regardless of 'variable' characters, was more important than including every character in the string.
DETAILS: I believe the answer you're looking for resides in:
Unicode Technical Standard #10: Unicode Collation Algorithm
If I'm understanding it correctly, punctuation (among other things, like whitespace) is 'variable' among languages, and therefore to ensure an identical sort order across languages, 'variable' characters are given a very low 'weight' in sorting; frequently resolving to a weight of zero, and therefore having no effect on sorting at all.
The UTS does indicate that the sorting can be customized per user.
Unfortunately, most systems just go with the defaults, which leads to only a few collation definitions that give 'variable' characters equal weight; and no real support for users to tune the defaults so that they get UTF-8 sorting with punctuation and whitespace INCLUDED instead of EXCLUDED.
If I follow the rational correctly, consider sorting names. In many cultures and languages, firstname is always given before lastname, and when reversed, the lastname is separated by punctuation from the firstname. In other cultures, the reverse is true.
lastname, firstname
lastname firstname
and
firstname lastname
firstname, lastname
To ensure that each list is always sorted in the same order, the punctuation is ignored.
| {
"pile_set_name": "StackExchange"
} |
Q:
node js (-bash: syntax error near unexpected token `"Hello World"')
I just started to learn node.js and I use macbook pro. In its terminal when I write any node.js command like console.log("Hello World"); its shows -bash: syntax error near unexpected token `"Hello World"'. How can I solve this?
A:
Type node then press Enter and THEN type console.log("Hello World")
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to install Rails on mac os x El Capitan
I cannot figure out how to install rails on my computer.
I have MacOS X El Capitan. I have been looking around for answers and trying different things and can't get it to work:
Miguels-MacBook-Pro-3:~ Miguel$ sudo gem install rails
Password:
Building native extensions. This could take a while...
ERROR: Error installing rails:
ERROR: Failed to build gem native extension.
/Users/Miguel/.rbenv/versions/2.2.3/bin/ruby -r ./siteconf20160109-19466-eulg4w.rb extconf.rb
checking if the C compiler accepts ... yes
checking if the C compiler accepts -Wno-error=unused-command-line-argument-hard-error-in-future... no
Building nokogiri using packaged libraries.
Using mini_portile version 2.0.0
checking for iconv.h... yes
checking for gzdopen() in -lz... yes
checking for iconv... yes
************************************************************************
IMPORTANT NOTICE:
Building Nokogiri with a packaged version of libxml2-2.9.2
with the following patches applied:
- 0001-Revert-Missing-initialization-for-the-catalog-module.patch
- 0002-Fix-missing-entities-after-CVE-2014-3660-fix.patch
- 0003-Stop-parsing-on-entities-boundaries-errors.patch
- 0004-Cleanup-conditional-section-error-handling.patch
- 0005-CVE-2015-1819-Enforce-the-reader-to-run-in-constant-.patch
- 0006-Another-variation-of-overflow-in-Conditional-section.patch
- 0007-Fix-an-error-in-previous-Conditional-section-patch.patch
- 0008-CVE-2015-8035-Fix-XZ-compression-support-loop.patch
- 0009-Updated-config.guess.patch
- 0010-Fix-parsering-short-unclosed-comment-uninitialized-access.patch
- 0011-Avoid-extra-processing-of-MarkupDecl-when-EOF.patch
- 0012-Avoid-processing-entities-after-encoding-conversion-.patch
- 0013-CVE-2015-7497-Avoid-an-heap-buffer-overflow-in-xmlDi.patch
- 0014-CVE-2015-5312-Another-entity-expansion-issue.patch
- 0015-Add-xmlHaltParser-to-stop-the-parser.patch
- 0016-Detect-incoherency-on-GROW.patch
- 0017-CVE-2015-7500-Fix-memory-access-error-due-to-incorre.patch
- 0018-CVE-2015-8242-Buffer-overead-with-HTML-parser-in-pus.patch
Team Nokogiri will keep on doing their best to provide security
updates in a timely manner, but if this is a concern for you and want
to use the system library instead; abort this installation process and
reinstall nokogiri as follows:
gem install nokogiri -- --use-system-libraries
[--with-xml2-config=/path/to/xml2-config]
[--with-xslt-config=/path/to/xslt-config]
If you are using Bundler, tell it to use the option:
bundle config build.nokogiri --use-system-libraries
bundle install
Note, however, that nokogiri is not fully compatible with arbitrary
versions of libxml2 provided by OS/package vendors.
************************************************************************
Extracting libxml2-2.9.2.tar.gz into tmp/x86_64-apple-darwin15.0.0/ports/libxml2/2.9.2... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0001-Revert-Missing-initialization-for-the-catalog-module.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0002-Fix-missing-entities-after-CVE-2014-3660-fix.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0003-Stop-parsing-on-entities-boundaries-errors.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0004-Cleanup-conditional-section-error-handling.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0005-CVE-2015-1819-Enforce-the-reader-to-run-in-constant-.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0006-Another-variation-of-overflow-in-Conditional-section.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0007-Fix-an-error-in-previous-Conditional-section-patch.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0008-CVE-2015-8035-Fix-XZ-compression-support-loop.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0009-Updated-config.guess.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0010-Fix-parsering-short-unclosed-comment-uninitialized-access.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0011-Avoid-extra-processing-of-MarkupDecl-when-EOF.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0012-Avoid-processing-entities-after-encoding-conversion-.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0013-CVE-2015-7497-Avoid-an-heap-buffer-overflow-in-xmlDi.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0014-CVE-2015-5312-Another-entity-expansion-issue.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0015-Add-xmlHaltParser-to-stop-the-parser.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0016-Detect-incoherency-on-GROW.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0017-CVE-2015-7500-Fix-memory-access-error-due-to-incorre.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxml2/0018-CVE-2015-8242-Buffer-overead-with-HTML-parser-in-pus.patch... OK
Running 'configure' for libxml2 2.9.2... OK
Running 'compile' for libxml2 2.9.2... OK
Running 'install' for libxml2 2.9.2... OK
Activating libxml2 2.9.2 (from /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/ports/x86_64-apple-darwin15.0.0/libxml2/2.9.2)...
************************************************************************
IMPORTANT NOTICE:
Building Nokogiri with a packaged version of libxslt-1.1.28
with the following patches applied:
- 0001-Adding-doc-update-related-to-1.1.28.patch
- 0002-Fix-a-couple-of-places-where-f-printf-parameters-wer.patch
- 0003-Initialize-pseudo-random-number-generator-with-curre.patch
- 0004-EXSLT-function-str-replace-is-broken-as-is.patch
- 0006-Fix-str-padding-to-work-with-UTF-8-strings.patch
- 0007-Separate-function-for-predicate-matching-in-patterns.patch
- 0008-Fix-direct-pattern-matching.patch
- 0009-Fix-certain-patterns-with-predicates.patch
- 0010-Fix-handling-of-UTF-8-strings-in-EXSLT-crypto-module.patch
- 0013-Memory-leak-in-xsltCompileIdKeyPattern-error-path.patch
- 0014-Fix-for-bug-436589.patch
- 0015-Fix-mkdir-for-mingw.patch
- 0016-Fix-for-type-confusion-in-preprocessing-attributes.patch
- 0017-Updated-config.guess.patch
Team Nokogiri will keep on doing their best to provide security
updates in a timely manner, but if this is a concern for you and want
to use the system library instead; abort this installation process and
reinstall nokogiri as follows:
gem install nokogiri -- --use-system-libraries
[--with-xml2-config=/path/to/xml2-config]
[--with-xslt-config=/path/to/xslt-config]
If you are using Bundler, tell it to use the option:
bundle config build.nokogiri --use-system-libraries
bundle install
************************************************************************
Extracting libxslt-1.1.28.tar.gz into tmp/x86_64-apple-darwin15.0.0/ports/libxslt/1.1.28... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0001-Adding-doc-update-related-to-1.1.28.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0002-Fix-a-couple-of-places-where-f-printf-parameters-wer.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0003-Initialize-pseudo-random-number-generator-with-curre.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0004-EXSLT-function-str-replace-is-broken-as-is.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0006-Fix-str-padding-to-work-with-UTF-8-strings.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0007-Separate-function-for-predicate-matching-in-patterns.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0008-Fix-direct-pattern-matching.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0009-Fix-certain-patterns-with-predicates.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0010-Fix-handling-of-UTF-8-strings-in-EXSLT-crypto-module.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0013-Memory-leak-in-xsltCompileIdKeyPattern-error-path.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0014-Fix-for-bug-436589.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0015-Fix-mkdir-for-mingw.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0016-Fix-for-type-confusion-in-preprocessing-attributes.patch... OK
Running git apply with /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/patches/libxslt/0017-Updated-config.guess.patch... OK
Running 'configure' for libxslt 1.1.28... OK
Running 'compile' for libxslt 1.1.28... OK
Running 'install' for libxslt 1.1.28... OK
Activating libxslt 1.1.28 (from /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1/ports/x86_64-apple-darwin15.0.0/libxslt/1.1.28)...
checking for main() in -llzma... yes
checking for xmlParseDoc() in libxml/parser.h... no
checking for xmlParseDoc() in -lxml2... no
checking for xmlParseDoc() in -llibxml2... no
-----
libxml2 is missing. Please locate mkmf.log to investigate how it is failing.
-----
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers. Check the mkmf.log file for more details. You may
need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/Users/Miguel/.rbenv/versions/2.2.3/bin/$(RUBY_BASE_NAME)
--help
--clean
--use-system-libraries
--enable-static
--disable-static
--with-zlib-dir
--without-zlib-dir
--with-zlib-include
--without-zlib-include=${zlib-dir}/include
--with-zlib-lib
--without-zlib-lib=${zlib-dir}/lib
--enable-cross-build
--disable-cross-build
--with-xml2lib
--without-xml2lib
--with-libxml2lib
--without-libxml2lib
extconf failed, exit code 1
Gem files will remain installed in /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.7.1 for inspection.
Results logged to /Users/Miguel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-15/2.2.0-static/nokogiri-1.6.7.1/gem_make.out
A:
First install necessary libraries:
$ brew install libxml2 libxslt libiconv
Second, install nokogiri:
$ sudo gem install nokogiri -- --use-system-libraries --with-xml2-include=/usr/include/libxml2 --with-xml2-lib=/usr/lib
| {
"pile_set_name": "StackExchange"
} |
Q:
What should our domain be?
Possible Duplicate:
Write and Elevator Pitch / Tagline
Note:
We are closing this domain naming thread. It is asking the entirely wrong question. See this blog post for details: Domain Names: Wrong Question
We're going to keep the name android.stackexchange.com. But we WILL be setting up redirects from the more "popular" domains names. (e.g. seasonedadvice.com to cooking.stackexchange.com, basicallymoney.com to money.stackexchange.com, and others as we go through the list).
New question: "Write and Elevator Pitch / Tagline!"
Click here to contribute ideas and vote.
[original message text below]
Post your ideas for a dot-com domain name for this website, which captures the spirit and intent of the site, namely:
{name} is intended for enthusiasts,
power users, and regular people using
the Android operating system.
Please follow these guidelines:
Check to see if the domain is taken before making the name suggestion. Taken names, however clever, are not helpful. You can use whois.net to check availability. (Read this post regarding squatted names).
Post one domain per answer. This makes the voting process much easier. If domains are very similar (e.g. "dev" and "devs"), they can be in the same answer.
Make sure the domain wasn't already suggested. To search within this question, use a search query such as: inquestion:1 "example.com" replacing example.com with the domain to search for.
When coming back to this question, make sure to sort the answers "newest first", as to not miss new proposals.
A:
AndroidExchange.org
Edit: .com and .net was taken.
A:
droid.io for "Android Input/Output"
"I/O, refers to the communication between an information processing system, and the outside world possibly a human."
This fits in two ways:
In a way our community is an android related information processing system based on Inputs (Questions) and Outputs (Answers).
Android is itself a system of I/O
I know the .io is a little unconventional but I think the name flows nicely and it's short.
A:
RoboticOverlords.[com/org]
| {
"pile_set_name": "StackExchange"
} |
Q:
Pandas How to hide the header when the output need header as a condition to filter the result?
Solution
If you hide the header of the output. use the header = None option. And notice that just use it when you are going to print it. For the reason that if you set the header = None when you load the data, the name of the column is unusable to you, so you can't use it to filter the data or do something else.
For example :
print(ResDf.to_string(header = None))
Update
The output I want has no header.
For example the output is
0 1 2 3 4 5 6 7 8 9 10 11 <------------------column name
3 b 7 a 4 b 2 b 6 b NaN 10 b
8 a 8 a 6 b 2 c 4 a NaN 10 c
The output I want is
------------without column name -------------------
3 b 7 a 4 b 2 b 6 b NaN 10 b
8 a 8 a 6 b 2 c 4 a NaN 10 c
But it can't be done by using header = none, so I wonder how to make it?
Thing is that if you set the header = None option, the column name can't be used as a condition to filter the data. Cuz there is no column name already.
For example I set the filter ( or called mask) as mask = df[u'客户'].str.contains(Client, na=False) & df[u'型号'].str.contains(GoodsType, na=False). If you set the header = None I think that there is no 型号 or 客户 in the dataframe, so It can't be used. So how to hide header when you still want to use the header to filter the output data?
I want the pandas output without the header, but the output needs the header to filtered.
Here is my code, I knew the trick to set the header=None, but I can't do that because the header still is used as a condition to filter the output. For example here I want the output with the '客户'(which is a column name) contain the certain word 'Tom'(For example). If I use the header = None option, the '客户' will not be recognized. So how to get the output without the header, in my condition?
# -*- coding: utf-8 -*-
# -*- coding: gbk -*-
import pandas as pd
import numpy as np
import sys
import re
import os
import sys
Client = sys.argv[1]
GoodsType = sys.argv[2]
Weight = sys.argv[3]
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir ) # change to the path that you already know
pd.set_option('display.max_columns', 1000)
# df = pd.read_excel("packagesum.xlsx", header = None) # '客户' will not be recognized when set the header to None
df = pd.read_excel("packagesum.xlsx")
# print(str(df.ix[:,u'客户经理':u'内袋标贴'][df[u'客户'].str.contains(Client, na = False)][df[u'型号'].str.contains(GoodsType, na = False)]))
ResDf = df.ix[:,u'客户经理':u'留样'][df[u'客户'].str.contains(Client, na = False)][df[u'型号'].str.contains(GoodsType, na = False)]
ResDf[u'重量'] = Weight
print(str(ResDf))
with open('GoodsTypeRes.txt', 'w') as the_file:
the_file.write(str(ResDf))
This is the header of my excel file.
A:
I think you need parameter names for set column names if does not exist, also header = None can be omit:
#change column names by your data
df = pd.read_excel("packagesum.xlsx", names=['col1','col2','col3', ...])
And then code can be simplify by boolean indexing with DataFrame.to_csv:
mask = df[u'客户'].str.contains(Client, na=False) & df[u'型号'].str.contains(GoodsType, na=False)
ResDf = df.loc[mask,u'客户经理':u'留样']
ResDf[u'重量'] = Weight
ResDf.to_csv('GoodsTypeRes.tx', header=False)
Another solution is select columns by position with iloc.
df = pd.read_excel("packagesum.xlsx", header=None)
#check positions if corrects, python starts from 0 for first position
mask = df.iloc[:, 2].str.contains(Client, na=False) & df.iloc[:, 4].str.contains(GoodsType, na=False)
#all columns
ResDf = df[mask].copy()
#add new column to position 10 what is same as column name
ResDf[10] = Weight
ResDf.to_csv('GoodsTypeRes.tx', header=False)
Sample:
np.random.seed(345)
N = 10
df = pd.DataFrame({0:np.random.choice(list('abc'), size=N),
1:np.random.choice([8,7,0], size=N),
2:np.random.choice(list('abc'), size=N),
3:np.random.randint(10, size=N),
4:np.random.choice(list('abc'), size=N),
5:np.random.choice([2,0], size=N),
6:np.random.choice(list('abc'), size=N),
7:np.random.randint(10, size=N),
8:np.random.choice(list('abc'), size=N),
9:np.random.choice([np.nan,0], size=N),
10:np.random.choice([1,0], size=N),
11:np.random.choice(list('abc'), size=N)})
print (df)
0 1 2 3 4 5 6 7 8 9 10 11
0 a 7 b 6 a 2 a 7 c 0.0 1 b
1 a 8 b 3 b 0 a 7 a NaN 0 b
2 b 8 b 3 b 2 a 8 c NaN 1 b
3 b 7 a 4 b 2 b 6 b NaN 0 b
4 c 0 b 2 c 2 c 7 a NaN 1 b
5 a 0 a 8 c 2 b 1 c NaN 1 b
6 a 8 b 5 c 2 a 5 a 0.0 0 a
7 b 8 a 2 c 0 a 1 a NaN 1 c
8 a 8 a 6 b 2 c 4 a NaN 0 c
9 c 0 b 2 a 0 b 2 c 0.0 0 b
Client = 'a'
GoodsType = 'b'
Weight = 10
mask = df.iloc[:, 2].str.contains(Client, na=False) & df.iloc[:, 4].str.contains(GoodsType, na=False)
ResDf = df[mask].copy()
ResDf[10] = Weight
print (ResDf)
0 1 2 3 4 5 6 7 8 9 10 11
3 b 7 a 4 b 2 b 6 b NaN 10 b
8 a 8 a 6 b 2 c 4 a NaN 10 c
| {
"pile_set_name": "StackExchange"
} |
Q:
Bootstrap .affix - jQuery hasClass not working
I'm using the Bootstrap .affix plugin and I'm trying to do something that the navbar when the affix class is added, but for some reason I can't seem to access the class once it is added to the navbar.
Keep in mind navbar is just a variable I created.
navbar.affix({
offset: {
top: header.height()
}
});
The above code adds .affix class to my navbar after scrolling the height of the header, and when I look in Chrome developer tools I see the class is added for sure, but when I try to do something like this:
navbar.hasClass('affix', function() { // Do something });
The code above never get's called.. it's as if .affix is never added to the navbar.
Am I missing something here? Is it doing something I'm not aware of that is somehow blocking me from being able to access the .affix class?
A:
You cannot assign a function to hasClass method. Instead use a true/false condition based on hasClass result to call your function.
The .hasClass() method will return true if the class is assigned to an element ...
https://api.jquery.com/hasclass/
EDIT: I have checked which class gets added to the element using navbar.attr('class') and the result is main-menu affix-top. So if you check hasClass('affix-top') it should work. https://jsfiddle.net/yqy7gah6/14/
EDIT 2: You should better check for the presence of any one of these three classes to ascertain that affix has been applied: Here's how the affix plugin works: affix-top, affix and affix-bottom.
You could use hasClass with OR or you could better use jQuery is like this:
if (navbar.is('.affix, .affix-top, .affix-bottom')) {
// Do you stuff here
}
From Bootstrap's description of Affix:
To start, the plugin adds .affix-top to indicate the element is in its
top-most position. At this point no CSS positioning is required.
Scrolling past the element you want affixed should trigger the actual
affixing. This is where .affix replaces .affix-top and sets position:
fixed; (provided by Bootstrap's CSS).
If a bottom offset is defined,
scrolling past it should replace .affix with .affix-bottom. Since
offsets are optional, setting one requires you to set the appropriate
CSS. In this case, add position: absolute; when necessary. The plugin
uses the data attribute or JavaScript option to determine where to
position the element from there.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the coin that Booker can't pick up?
I got this question from a gaming test in a local weekly magazine. And I've done a lot of searching on Google, reading wiki and different sites, but I can't find any information about this "coin" (not sure if it's a coin).
The only thing I know is it's is a kind of coin or maybe Silver Eagle, but Booker can't pick it up. Where is that coin and which chapter does it appear?
A:
This should probably be in the comments but...
I'm going to say "Baptism".
From reading the Bioshock Wikia Article about Booker, it seems that Booker is repeatedly given the option to be Baptized into the Christian religion and, in his version of reality, opts out on various occasions and, apparently almost does get Baptized but is knocked out cold.
Towards the end of the Wikia article, in the last paragraph before the Epilogue section it reads:
Booker then realizes that the only way to erase the atrocities committed by Comstock (himself), and the harm visited upon Elizabeth, is for him to die before he can accept or reject his baptism. Thus cancelling out either outcome.
This sounds to me like a two sided coin... one that he can't pick up because doing so creates two flawed people who can't exist without destroying Elizabeth, his daughter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error at building model of new Gradle project for libgdx
I installed Gradle in eclipse and want to import a libgdx Gradle project. But when i click on "Build Model" button, i have an error at about 50% of the loading bar. Here is the problem :
> Plug-in: org.springsource.ide.eclipse.gradle.core Severity : error
> Message : org.eclipse.osgi.internal.framework.EquinoxConfiguration$1
> Exception Stack trace : java.lang.reflect.InvocationTargetException
> at
> org.springsource.ide.eclipse.gradle.core.util.GradleRunnable.run(GradleRunnable.java:92)
> at
> org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
> Caused by: org.eclipse.core.runtime.CoreException:
> org.eclipse.osgi.internal.framework.EquinoxConfiguration$1 at
> org.springsource.ide.eclipse.gradle.core.GradleModelProvider$GroupedModelProvider.ensureModels(GradleModelProvider.java:284)
> at
> org.springsource.ide.eclipse.gradle.core.GradleProject.getGradleModel(GradleProject.java:633)
> at
> org.springsource.ide.eclipse.gradle.core.GradleProject.getSkeletalGradleModel(GradleProject.java:654)
> at
> org.springsource.ide.eclipse.gradle.ui.wizards.GradleImportWizardPageOne$11.doit(GradleImportWizardPageOne.java:516)
> at
> org.springsource.ide.eclipse.gradle.core.util.GradleRunnable.run(GradleRunnable.java:84)
> ... 1 more Caused by: org.gradle.tooling.GradleConnectionException:
> Could not fetch model of type 'HierarchicalEclipseProject' using
> Gradle distribution
> 'http://services.gradle.org/distributions/gradle-1.11-all.zip'. at
> org.gradle.tooling.internal.consumer.ResultHandlerAdapter.onFailure(ResultHandlerAdapter.java:55)
> at
> org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:57)
> at
> org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
> at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
> at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
> at java.lang.Thread.run(Unknown Source) at
> org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
> at
> org.gradle.tooling.internal.consumer.DefaultModelBuilder.get(DefaultModelBuilder.java:48)
> at
> org.springsource.ide.eclipse.gradle.core.GradleModelProvider.buildModel(GradleModelProvider.java:385)
> at
> org.springsource.ide.eclipse.gradle.core.GradleModelProvider$GroupedModelProvider.ensureModels(GradleModelProvider.java:290)
> ... 5 more Caused by:
> org.gradle.launcher.daemon.client.DaemonConnectionException: Could not
> dispatch a message to the daemon. at
> org.gradle.launcher.daemon.client.DaemonClientConnection.dispatch(DaemonClientConnection.java:57)
> at
> org.gradle.launcher.daemon.client.DaemonClient.executeBuild(DaemonClient.java:168)
> at
> org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:151)
> at
> org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:74)
> at
> org.gradle.tooling.internal.provider.DaemonBuildActionExecuter.execute(DaemonBuildActionExecuter.java:42)
> at
> org.gradle.tooling.internal.provider.DaemonBuildActionExecuter.execute(DaemonBuildActionExecuter.java:29)
> at
> org.gradle.tooling.internal.provider.LoggingBridgingBuildActionExecuter.execute(LoggingBridgingBuildActionExecuter.java:53)
> at
> org.gradle.tooling.internal.provider.LoggingBridgingBuildActionExecuter.execute(LoggingBridgingBuildActionExecuter.java:30)
> at
> org.gradle.tooling.internal.provider.ProviderConnection.run(ProviderConnection.java:106)
> at
> org.gradle.tooling.internal.provider.ProviderConnection.run(ProviderConnection.java:93)
> at
> org.gradle.tooling.internal.provider.DefaultConnection.getModel(DefaultConnection.java:133)
> at
> org.gradle.tooling.internal.consumer.connection.ModelBuilderBackedModelProducer.produceModel(ModelBuilderBackedModelProducer.java:49)
> at
> org.gradle.tooling.internal.consumer.connection.GradleBuildAdapterProducer.produceModel(GradleBuildAdapterProducer.java:42)
> at
> org.gradle.tooling.internal.consumer.connection.BuildInvocationsAdapterProducer.produceModel(BuildInvocationsAdapterProducer.java:47)
> at
> org.gradle.tooling.internal.consumer.connection.ModelBuilderBackedConsumerConnection.run(ModelBuilderBackedConsumerConnection.java:55)
> at
> org.gradle.tooling.internal.consumer.DefaultModelBuilder$1.run(DefaultModelBuilder.java:59)
> at
> org.gradle.tooling.internal.consumer.connection.LazyConsumerActionExecutor.run(LazyConsumerActionExecutor.java:82)
> at
> org.gradle.tooling.internal.consumer.connection.ProgressLoggingConsumerActionExecutor.run(ProgressLoggingConsumerActionExecutor.java:58)
> at
> org.gradle.tooling.internal.consumer.connection.LoggingInitializerConsumerActionExecutor.run(LoggingInitializerConsumerActionExecutor.java:44)
> at
> org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:55)
> at
> org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
> at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
> at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
> at java.lang.Thread.run(Unknown Source) Caused by:
> org.gradle.messaging.remote.internal.MessageIOException: Could not
> write message Build{id=67f4f73f-8d68-4e23-87c2-648a4fec30c8.1,
> currentDir=C:\applications\Eclipse} to '/127.0.0.1:1598'. at
> org.gradle.messaging.remote.internal.inet.SocketConnection.dispatch(SocketConnection.java:115)
> at
> org.gradle.launcher.daemon.client.DaemonClientConnection.dispatch(DaemonClientConnection.java:51)
> ... 23 more Caused by: java.io.NotSerializableException:
> org.eclipse.osgi.internal.framework.EquinoxConfiguration$1 at
> java.io.ObjectOutputStream.writeObject0(Unknown Source) at
> java.io.ObjectOutputStream.writeObject(Unknown Source) at
> java.util.HashMap.internalWriteEntries(Unknown Source) at
> java.util.HashMap.writeObject(Unknown Source) at
> sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
> sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
> sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
> java.lang.reflect.Method.invoke(Unknown Source) at
> java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) at
> java.io.ObjectOutputStream.writeSerialData(Unknown Source) at
> java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at
> java.io.ObjectOutputStream.writeObject0(Unknown Source) at
> java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at
> java.io.ObjectOutputStream.writeSerialData(Unknown Source) at
> java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at
> java.io.ObjectOutputStream.writeObject0(Unknown Source) at
> java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at
> java.io.ObjectOutputStream.writeSerialData(Unknown Source) at
> java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at
> java.io.ObjectOutputStream.writeObject0(Unknown Source) at
> java.io.ObjectOutputStream.writeObject(Unknown Source) at
> org.gradle.messaging.remote.internal.Message.send(Message.java:40) at
> org.gradle.messaging.remote.internal.DefaultMessageSerializer$MessageWriter.write(DefaultMessageSerializer.java:62)
> at
> org.gradle.messaging.remote.internal.inet.SocketConnection.dispatch(SocketConnection.java:112)
> ... 24 more Root exception: org.eclipse.core.runtime.CoreException:
> org.eclipse.osgi.internal.framework.EquinoxConfiguration$1 at
> org.springsource.ide.eclipse.gradle.core.GradleModelProvider$GroupedModelProvider.ensureModels(GradleModelProvider.java:284)
> at
> org.springsource.ide.eclipse.gradle.core.GradleProject.getGradleModel(GradleProject.java:633)
> at
> org.springsource.ide.eclipse.gradle.core.GradleProject.getSkeletalGradleModel(GradleProject.java:654)
> at
> org.springsource.ide.eclipse.gradle.ui.wizards.GradleImportWizardPageOne$11.doit(GradleImportWizardPageOne.java:516)
> at
> org.springsource.ide.eclipse.gradle.core.util.GradleRunnable.run(GradleRunnable.java:84)
> at
> org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
> Caused by: org.gradle.tooling.GradleConnectionException: Could not
> fetch model of type 'HierarchicalEclipseProject' using Gradle
> distribution
> 'http://services.gradle.org/distributions/gradle-1.11-all.zip'. at
> org.gradle.tooling.internal.consumer.ResultHandlerAdapter.onFailure(ResultHandlerAdapter.java:55)
> at
> org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:57)
> at
> org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
> at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
> at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
> at java.lang.Thread.run(Unknown Source) at
> org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
> at
> org.gradle.tooling.internal.consumer.DefaultModelBuilder.get(DefaultModelBuilder.java:48)
> at
> org.springsource.ide.eclipse.gradle.core.GradleModelProvider.buildModel(GradleModelProvider.java:385)
> at
> org.springsource.ide.eclipse.gradle.core.GradleModelProvider$GroupedModelProvider.ensureModels(GradleModelProvider.java:290)
> ... 5 more Caused by:
> org.gradle.launcher.daemon.client.DaemonConnectionException: Could not
> dispatch a message to the daemon. at
> org.gradle.launcher.daemon.client.DaemonClientConnection.dispatch(DaemonClientConnection.java:57)
> at
> org.gradle.launcher.daemon.client.DaemonClient.executeBuild(DaemonClient.java:168)
> at
> org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:151)
> at
> org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:74)
> at
> org.gradle.tooling.internal.provider.DaemonBuildActionExecuter.execute(DaemonBuildActionExecuter.java:42)
> at
> org.gradle.tooling.internal.provider.DaemonBuildActionExecuter.execute(DaemonBuildActionExecuter.java:29)
> at
> org.gradle.tooling.internal.provider.LoggingBridgingBuildActionExecuter.execute(LoggingBridgingBuildActionExecuter.java:53)
> at
> org.gradle.tooling.internal.provider.LoggingBridgingBuildActionExecuter.execute(LoggingBridgingBuildActionExecuter.java:30)
> at
> org.gradle.tooling.internal.provider.ProviderConnection.run(ProviderConnection.java:106)
> at
> org.gradle.tooling.internal.provider.ProviderConnection.run(ProviderConnection.java:93)
> at
> org.gradle.tooling.internal.provider.DefaultConnection.getModel(DefaultConnection.java:133)
> at
> org.gradle.tooling.internal.consumer.connection.ModelBuilderBackedModelProducer.produceModel(ModelBuilderBackedModelProducer.java:49)
> at
> org.gradle.tooling.internal.consumer.connection.GradleBuildAdapterProducer.produceModel(GradleBuildAdapterProducer.java:42)
> at
> org.gradle.tooling.internal.consumer.connection.BuildInvocationsAdapterProducer.produceModel(BuildInvocationsAdapterProducer.java:47)
> at
> org.gradle.tooling.internal.consumer.connection.ModelBuilderBackedConsumerConnection.run(ModelBuilderBackedConsumerConnection.java:55)
> at
> org.gradle.tooling.internal.consumer.DefaultModelBuilder$1.run(DefaultModelBuilder.java:59)
> at
> org.gradle.tooling.internal.consumer.connection.LazyConsumerActionExecutor.run(LazyConsumerActionExecutor.java:82)
> at
> org.gradle.tooling.internal.consumer.connection.ProgressLoggingConsumerActionExecutor.run(ProgressLoggingConsumerActionExecutor.java:58)
> at
> org.gradle.tooling.internal.consumer.connection.LoggingInitializerConsumerActionExecutor.run(LoggingInitializerConsumerActionExecutor.java:44)
> at
> org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:55)
> at
> org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
> at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
> at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
> at java.lang.Thread.run(Unknown Source) Caused by:
> org.gradle.messaging.remote.internal.MessageIOException: Could not
> write message Build{id=67f4f73f-8d68-4e23-87c2-648a4fec30c8.1,
> currentDir=C:\applications\Eclipse} to '/127.0.0.1:1598'. at
> org.gradle.messaging.remote.internal.inet.SocketConnection.dispatch(SocketConnection.java:115)
> at
> org.gradle.launcher.daemon.client.DaemonClientConnection.dispatch(DaemonClientConnection.java:51)
> ... 23 more Caused by: java.io.NotSerializableException:
> org.eclipse.osgi.internal.framework.EquinoxConfiguration$1 at
> java.io.ObjectOutputStream.writeObject0(Unknown Source) at
> java.io.ObjectOutputStream.writeObject(Unknown Source) at
> java.util.HashMap.internalWriteEntries(Unknown Source) at
> java.util.HashMap.writeObject(Unknown Source) at
> sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
> sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
> sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
> java.lang.reflect.Method.invoke(Unknown Source) at
> java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) at
> java.io.ObjectOutputStream.writeSerialData(Unknown Source) at
> java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at
> java.io.ObjectOutputStream.writeObject0(Unknown Source) at
> java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at
> java.io.ObjectOutputStream.writeSerialData(Unknown Source) at
> java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at
> java.io.ObjectOutputStream.writeObject0(Unknown Source) at
> java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at
> java.io.ObjectOutputStream.writeSerialData(Unknown Source) at
> java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at
> java.io.ObjectOutputStream.writeObject0(Unknown Source) at
> java.io.ObjectOutputStream.writeObject(Unknown Source) at
> org.gradle.messaging.remote.internal.Message.send(Message.java:40) at
> org.gradle.messaging.remote.internal.DefaultMessageSerializer$MessageWriter.write(DefaultMessageSerializer.java:62)
> at
> org.gradle.messaging.remote.internal.inet.SocketConnection.dispatch(SocketConnection.java:112)
> ... 24 more
Session data :
eclipse.buildId=4.4.1.M20140925-0400
java.version=1.8.0_20
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments: -product org.eclipse.epp.package.java.product
Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product
Any help will be appreciated
A:
Credit to Kris De Volder and 'Alex' for the following explanation and work around, as commented on the issue I opened at this address https://issuetracker.springsource.com/browse/STS-3922 and mostly just directly quoted here to provide a complete answer for this question:
"The problem is coming from the following system properties [... as they contain] values that are not serializible. The properties are:
osgi.configuration.area.default
osgi.user.area.default
osgi.user.area
"As a workaround people can add -D properties to their STS.ini, eclipse.ini or GGTS.ini to set these properties to the values they used to have in Eclipse 4.4.1
-Dosgi.configuration.area.default=null
-Dosgi.user.area.default=null
[email protected]
"We are also adding this workaround to Gradle tooling in upcoming 3.6.2 release so that when the gradle plugins are installed these props will be added to the .ini file automatically.
"Also worth mentioning that Gradle seems to have patched this problem on their end as well so another workaround is using Gradle 2.2.BUILD-SNAPSHOT. Set it via Gradle Preference page in the tooling or by setting in the gradle.wrapper in your gradle project(s)."
So there you have it! A simple fix which you can either apply manually yourself, or through an update. And I can confirm that it works.
A:
I thought it' easier to edit the current answer specially when STS installation has /sts_installation_dir/configuration/config.ini instead off sts.ini.
The correct format to edit config.ini is little different since you do NOT prefix properties with -D.
It would be:
osgi.configuration.area.default=null
osgi.user.area.default=null
[email protected]
| {
"pile_set_name": "StackExchange"
} |
Q:
fat-free SELECT is not returning any data
i am using Fat-Free Framework to do rapid prototyping of my application. Now, whenever I try to load some data from database, i can use the load() function within the SQL\Mapper but it returned all of the column.
I found SELECT() function but it does not returning any data.
$this->load(['myId=?',$id]) will return the data along with the other columns
$this->select('name',['myId=?',$id]) should return the data from name column but i got nothing.
$this->db->exec('SELECT name FROM persons WHERE myId=?',$id) will return the the data from name column.
what is the proper way of using SELECT() from Fat-Free framework? my goal is to only retrieve single data from name column only.
A:
The right way to do it is like this:
$table = new DB\SQL\Mapper($db, 'persons');
// assign to $results
$results = $table->load(array('myId=?', $id));
foreach($results => $row){
echo $row->name;
}
As described here: https://fatfreeframework.com/3.6/databases#SeekandYouShallFind
| {
"pile_set_name": "StackExchange"
} |
Q:
SPARQL QuadPattern
In SPARQL a QuadPattern is defined as
QuadPattern ::= '{' Quads '}'
Quads ::= TriplesTemplate? ( QuadsNotTriples '.'? TriplesTemplate? )*
From this I understand that a QuadPattern can be empty. But I can not understand the reason. Whats the purpose of an empty QuadPattern?
A:
As @Antoine Zimmermann points out just because the syntax allows it doesn't mean it is meaningful.
In this case I believe it was done to keep the grammar within a certain constraint and to simplify it. If you don't allows Quads to be empty then you'd have to redefine the QuadPattern rule as so:
QuadPattern ::= '{' '}' | '{' Quads '}'
Which just adds unnecessary complication particularly when you are using a parser generator
| {
"pile_set_name": "StackExchange"
} |
Q:
Swap Selected and available columns of columnchooser dialogue + jqgrid
Current in columnchooser popup, selected columns come on the left side and available on right side, is there a way i can swap the columns to make available on left and selected on right ?
A:
I prepared the demo for you, which demonstrates what you can do. It displays columnChooser dialog like
The demo uses the following code inside of onClickButton callback:
$(this).jqGrid("columnChooser");
var $available = $("#colchooser_list .ui-multiselect > .available");
$available.prependTo($available.parent())
.css({
"border-left": "0 none",
"border-right": "1px solid"
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it a kind of deadlock in the code?
Definitely, second loop will never be executed, but still curious to know whether the following example could be classified as a deadlock or not.
public class Test {
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <= 10; i++)
System.out.print(i + " ");
Thread.currentThread().join();
for (int i = 11; i <= 20; i++)
System.out.print(i + " ");
}
}
A:
No, this is not a deadlock. But you did block your main thread indefinitely. The join method blocks until the Thread on which it is called dies.
Waits for this thread to die.
Calling Thread.currentThread().join(); means that the main thread is waiting for itself to die, which won't happen.
This differs from a deadlock, where two threads each own the lock on separate resources, but each needs the other's locked resource to continue. That is not the case here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I configure gitosis to ask for passwords and check against an Active Directory
I have successfully installed and configured gitosis on an Ubuntu server. We're currently just a few developers creating a development platform for a large organization (more than 2000 employees.)
Currently they use subversion for version control. The departments can modify their users permissions by editing and commit a single file, much like gitosis.conf. However the difference is they don't need to push public keys for their users, but use the user's domain login, since subversion is configured to check users against our AD.
Is there's a way gitosis can behave similarly:
They edit gitosis.conf, but they don't need to add the public keys.
How do I configure git/gitosis to ask for users password and check them agains the AD.
A:
I have been reading some post in order to achieve this. I've been able to setup the smart git http backend, and using Apache's LDAP Auth module I've have achieve the AD integration.
Now I'm hacking gitosis hooks to generate the "Require users" for Apache and reloading the apache configuration.
Another possible way is to setup Gitorious and subscribe the ActiveMQ the use for messaging between subsystems.
Here's the list of post I've been reading:
http://www.toofishes.net/blog/git-smart-http-transport-lighttpd/
http://progit.org/2010/03/04/smart-http.html
http://www.openg.info/tag/steps-setup-git-http-backend-apache-windows
http://www.openg.info/entry/authentication-git-push-http
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql: unknown variable 'login-path=develop' via ssh
I'm trying to execute below mysql command via ssh, of course this command works fine on server A, and I'm trying to execute it from server B via ssh.
ssh accountId@serverA "(cd dir1/dir2/; mysql --login-path=develop)"
but it fails with
mysql: unknown variable 'login-path=develop
does anyone know the reason?
A:
I found the root cause and fixed!!! I'm posting it for someone who might suffer from similar problem.
My problem was several mysql binaries on serverA. The 'mysql' binary, one that I executed on serverA and from serverB via ssh were different. So I modified the command to use absolute path for mysql and it works fine now.
ssh accountId@serverA "(cd dir1/dir2/; /user/bin/mysql --login-path=develop)"
| {
"pile_set_name": "StackExchange"
} |
Q:
Get subfolder svn revision in TeamCity
We have a strange way of using repos here (and I have little control over it I'm afraid), where a root repo holds multiple projects... no fancy stuff like trunk/tags/branches folder either... (I'm so sad).
So for example the structure looks like this:
http://my.svn.root/main
|-- /Project1
|-- /Project2
...
and so on...
Now, doing svn log on the folders will give me the latest revision number in that folder. Problem is that TeamCity seems to be doing svn info on the root, so even if I specify a VCS root like this:
http://my.svn.root/main/Project1
the %build.vcs.number% property seems to be picked from the main root of the repo, so a commit in Project2 will actually advance that number (which is not what I would like).
Is there a way to tell TeamCity to use the subfolder latest commit number rather than the root revision? or a different property that does just that?
Thanks!
A:
Hmmm, apparently it's all due to the VCS root settings. Basically the best option would be to have a root set up to the main and then edit the checkout rules:
VCS root: http://my.svn.root/main
checkout rules: +:Project1=>.
This seems to be a lot more stable and also more responsive in terms of Build triggering.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculating the sun’s position in ECI
I’m trying to calculate visible ISS passes and I need to calculate if the ISS is behind the earth by “drawing” a line between the ISS and the sun and seeing if it crosses earth. I have the ECI position of the ISS, but I don’t have the position of the sun. How do I calculate the suns ECI position given a date and time?
Edit: I need to use c# for this so I can’t use python libraries
A:
public static Vector3 GetSunDirection(DateTime time)
{
time = time.ToUniversalTime();
double JD = 367*time.Year-Math.Floor(7.0*(time.Year+Math.Floor((time.Month+9.0)/12.0))/4.0)+Math.Floor(275.0*time.Month/9.0)+time.Day+1721013.5+time.Hour/24.0+time.Minute/1440.0+time.Second/86400.0;
double pi = 3.14159265359;
double UT1 = (JD-2451545)/36525;
double longMSUN = 280.4606184+36000.77005361*UT1;
double mSUN = 357.5277233+35999.05034*UT1;
double ecliptic = longMSUN+1.914666471*Math.Sin(mSUN*pi/180)+0.918994643*Math.Sin(2*mSUN*pi/180);
double eccen = 23.439291-0.0130042*UT1;
double x = Math.Cos(ecliptic*pi/180);
double y = Math.Cos(eccen*pi/180)*Math.Sin(ecliptic*pi/180);
double z = Math.Sin(eccen*pi/180)*Math.Sin(ecliptic*pi/180);
return new Vector3(x, y, z);
}
public static Vector3 GetSun(DateTime time)
{
double sunDistance = 0.989 * 1.496E+8;
var sunPosition = GetSunDirection(time.ToUniversalTime());
sunPosition = sunPosition * sunDistance;
return sunPosition;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Display randomly goes into wrong position
Running Xubuntu 14.04 on a Mac Mini, using open source ATI driver (more info below).
After some time running in Xorg, the display 'rearranges' itself so the beginning and the end of the screen (at least, horizontally) are in the wrong place.
Restarting the X server does not appear to do anything (if I kill X entirely, the terminal has the same display issue ... it starts at the wrong place).
Rebooting the system fixes up the problem.
Not sure what to call this issue - where should I start looking?
lshw -c video reports:
*-display UNCLAIMED
description: VGA compatible controller
product: Whistler [Radeon HD 6630M/6650M/6750M/7670M/7690M]
vendor: Advanced Micro Devices, Inc. [AMD/ATI]
physical id: 0
bus info: pci@0000:01:00.0
version: 00
width: 64 bits
clock: 33MHz
capabilities: pm pciexpress msi vga_controller bus_master cap_list
configuration: latency=0
resources: memory:90000000-9fffffff memory:a8800000-a881ffff ioport:2000(size=256) memory:a8820000-a883ffff
*-display UNCLAIMED
description: Display controller
product: 2nd Generation Core Processor Family Integrated Graphics Controller
vendor: Intel Corporation
physical id: 2
bus info: pci@0000:00:02.0
version: 09
width: 64 bits
clock: 33MHz
capabilities: msi pm cap_list
configuration: latency=0
resources: memory:a8000000-a83fffff memory:a0000000-a7ffffff ioport:3000(size=64)
A:
Because Ubuntu 14.04 open source drivers come together with a peculiar video patch, the chances to install official drivers for ATI cards are slim sometimes and not so slim other times. I was under the impression that this patch error affects only NVIDIA video cards but it seems that ATI video cards can have the same issues.
Sometimes open source drivers work like a charm with ATI cards, and sometimes you get funny results like in your case. To fix the problem you are supposed to remove your ATI drivers from your system, remove xorg.conf, and after that reinstall xorg completely and finally reconfigure Xorg.
All this operations are better performed in the console terminal, and to get to the console you have to press Ctrl+Alt+F1 at login prompt, and login with your username and password. So it would be better to write down these commands on some piece of paper before actually running them.
sudo apt-get purge fglrx*
sudo rm /etc/X11/xorg.conf
And to reinstall xorg completely:
sudo apt-get install --reinstall xserver-xorg-core libgl1-mesa-glx:i386 libgl1-mesa-dri:i386 libgl1-mesa-glx:amd64 libgl1-mesa-dri:amd64
immediately followed by:
sudo dpkg-reconfigure xserver-xorg
and finally
sudo reboot
The following is a well documented guide addressed to fixing the proprietary ATI drivers, the one I used to address your problem. I have no idea whether it will work for you, I never used ATI video cards but I think you should also read the comments to this guide because there are a few interesting suggestions in there too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Move zip file between servers using C#
I want to move the zip file from one server to another server.
What is the best way to do that using C#?
If i am on my local machine running my C# application.
And I want to access two servers server A and serverB using File.COpy() to transfer the file from A to B then it is giving me credential issue.
I don't know whether I have UNC share for both the servers.
I want to use webrequest to transfer the zip file from Server A to Server B from my machine.
A:
If you have a UNC share on the destination server, you can just use
System.IO.File.Copy(String sourceFileLocation,
String destinationFileLocation)
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I detect if some file in a subdir changed?
Basically I have a big directory (>10GB)(each subdir only has a few other subdirs) and want to do sth to any files that changes. I can't just go through all the files and check, because it takes to long and uses about 90% of my CPU :(.
This is how it looks basically:
dir
dir/subA
dir/subA/subAsubA
dir/subA/subAsubB
...
dir/subB
dir/subB/subBsubA
dir/subB/subBsubB
...
dir/SubC
dir/SubD
...
My thought was like this(file "test" in subBsubA chaged):
Check dir
-> dir changed
-->Check subA
-> subA didn't change
-->Check subB
-> subB changed
--> Check subBsubA
-> subBsubA changed
--> Check all files
But sadly the change of a file only effects the modification date of the direct parent directory :(
A:
As @Aereaux pointed out you probably need inotify, available in Linux since 2.6.13. See http://en.wikipedia.org/wiki/Inotify
There are inotify-tools available for command line usage as well.
http://techarena51.com/index.php/inotify-tools-example/
| {
"pile_set_name": "StackExchange"
} |
Q:
Apscheduler cron to start on the half hour
I’m looking to have a cron job that runs based on the stock market open and close times (8:30-3 CST). I want it to run every 15 minutes, starting at 8:30.
What I currently have is
sched.add_job(scheduled_task,'cron',
day_of_week='mon-fri', hour='8-15',
minute=enter code here'0-59/15',
timezone='America/Chicago')
This allows me to run 8am-3pm every 15 minutes which isn’t exactly what I want. I have also tried the following:
sched.add_job(scheduled_task,'cron',
day_of_week='mon-fri', hour='12-20',
minute='30/15',
timezone='America/Chicago')
This gets me closer but only runs on the 30 and 45 minutes.
A:
The solution is to use OrTrigger:
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.combining import OrTrigger
cron1 = CronTrigger(day_of_week='mon-fri', hour='8', minute='30,45', timezone='America/Chicago')
cron2 = CronTrigger(day_of_week='mon-fri', hour='9-15', minute='*/15', timezone='America/Chicago')
trigger = OrTrigger([cron1, cron2])
sched.add_job(scheduled_task, trigger)
| {
"pile_set_name": "StackExchange"
} |
Q:
Cx framework: How to set align:right and decimal precision on NumberField
I am working on a project where IU is done in Cx, new React based Framework for FrontEnd. https://cxjs.io/
I have a Grid with filter Fields on top of each Column.
For example this is Number Column and Field:
{
field: 'score', sortable: true,
header: {
style: 'width: 150px',
items: <cx>
<div>
Score
<br />
<NumberField style="width:100%;margin-top:5px" value:bind="$page.filter.score"
reactOn="enter blur"/>
</div>
</cx>
},
},
But value is on the left side, and I need it on the right.
I want both grid and filter field value to be on the right but keeping column name on the left. Like it is usually in Excel.
Also how to set custom number of decimal, 2 for example?
A:
NumberField widgets allow setting additional styles on the input element through inputStyle. Formatting is done using format. Grid column headers can set its own styles using just style.
With all that in mind, it should be something like this:
{
field: "score",
sortable: true,
header: {
style: "width: 150px; text-align: left",
items: (
<cx>
<div>
Score
<br />
<NumberField
value:bind="$page.filter.score"
format="n;2"
style="width:100%;margin-top:5px"
inputStyle="text-align: right"
reactOn="enter blur"
/>
</div>
</cx>
)
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing credentials from ASP.NET C# to another web service
I have a one page ASP.NET 4.0 C# script running. In debug mode my script works just fine but when I publish it, it seems like it is not sending the credentials when making the WebRequest.
The following is the code I am using, I have tried a bunch of things but I keep getting a 401 Unauthorized when I am using my published version of the script. BTW I am using IIS 7
WebRequest fwRequest = HttpWebRequest.Create(fwURL);
fwRequest.UseDefaultCredentials = true;
//fwRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse myHttpWebResponse = (HttpWebResponse)fwRequest.GetResponse();
A:
While debugging, your project use your credentials, but when you publish it it will use the credentials of ASP.NET user, or the credentials set in IIS configuration.
So no, you can not pass credentials of your client to another web service/appliaction unless you convince him/her to pass username-password to your application (Except that both web apps are on the same machine).
| {
"pile_set_name": "StackExchange"
} |
Q:
What "religions" did previous Buddhas practice?
I recently found a book called "A Buddhist Bible".
In it, Buddha refers to that there have been many Buddhas before him.
If Buddha was the one to put the foundations of Buddhism, what "religions" did the previous Buddhas practice?
Does this question even make any sense?
A:
According to tradition, as in the Nagara Sutta, Buddhas all discover the path to enlightenment and teach that same path to their followers:
"It is just as if a man, traveling along a wilderness track, were to
see an ancient path, an ancient road, traveled by people of former
times. He would follow it. Following it, he would see an ancient city,
an ancient capital inhabited by people of former times, complete with
parks, groves, & ponds, walled, delightful. He would go to address the
king or the king's minister, saying, 'Sire, you should know that while
traveling along a wilderness track I saw an ancient path... I followed
it... I saw an ancient city, an ancient capital... complete with
parks, groves, & ponds, walled, delightful. Sire, rebuild that city!'
The king or king's minister would rebuild the city, so that at a later
date the city would become powerful, rich, & well-populated, fully
grown & prosperous.
"In the same way I saw an ancient path, an ancient road, traveled by
the Rightly Self-awakened Ones of former times. And what is that
ancient path, that ancient road, traveled by the Rightly Self-awakened
Ones of former times? Just this noble eightfold path: right view,
right aspiration, right speech, right action, right livelihood, right
effort, right mindfulness, right concentration. That is the ancient
path, the ancient road, traveled by the Rightly Self-awakened Ones of
former times. I followed that path. Following it, I came to direct
knowledge of aging & death, direct knowledge of the origination of
aging & death, direct knowledge of the cessation of aging & death,
direct knowledge of the path leading to the cessation of aging &
death. I followed that path. Following it, I came to direct knowledge
of birth... becoming... clinging... craving... feeling... contact...
the six sense media... name-&-form... consciousness, direct knowledge
of the origination of consciousness, direct knowledge of the cessation
of consciousness, direct knowledge of the path leading to the
cessation of consciousness. I followed that path.
"Following it, I came to direct knowledge of fabrications, direct
knowledge of the origination of fabrications, direct knowledge of the
cessation of fabrications, direct knowledge of the path leading to the
cessation of fabrications. Knowing that directly, I have revealed it
to monks, nuns, male lay followers & female lay followers, so that
this holy life has become powerful, rich, detailed, well-populated,
wide-spread, proclaimed among celestial & human beings."
So, all Buddhas essentially practice and preach the same religion.
| {
"pile_set_name": "StackExchange"
} |
Q:
My .bashrc file not executed on Git Bash startup (Windows 7)
This is what I did:
cd ~
touch .bashrc
notepad .bashrc
and the content of my .bashrc is (found on the web somewhere):
SSH_ENV="$HOME/.ssh/environment"
# start the ssh-agent
function start_agent {
echo "Initializing new SSH agent..."
# spawn ssh-agent
ssh-agent | sed 's/^echo/#echo/' > "$SSH_ENV"
echo succeeded
chmod 600 "$SSH_ENV"
. "$SSH_ENV" > /dev/null
ssh-add
}
# test for identities
function test_identities {
# test whether standard identities have been added to the agent already
ssh-add -l | grep "The agent has no identities" > /dev/null
if [ $? -eq 0 ]; then
ssh-add
# $SSH_AUTH_SOCK broken so we start a new proper agent
if [ $? -eq 2 ];then
start_agent
fi
fi
}
# check for running ssh-agent with proper $SSH_AGENT_PID
if [ -n "$SSH_AGENT_PID" ]; then
ps -ef | grep "$SSH_AGENT_PID" | grep ssh-agent > /dev/null
if [ $? -eq 0 ]; then
test_identities
fi
# if $SSH_AGENT_PID is not properly set, we might be able to load one from
# $SSH_ENV
else
if [ -f "$SSH_ENV" ]; then
. "$SSH_ENV" > /dev/null
fi
ps -ef | grep "$SSH_AGENT_PID" | grep -v grep | grep ssh-agent > /dev/null
if [ $? -eq 0 ]; then
test_identities
else
start_agent
fi
fi
Somehow that script is not executed at all. I don't see any of the strings that should be echoed. I am familiar with Unix commandline in Linux and Mac OS X, but I have no idea how it works under Windows. Any suggestions please?
EDIT: Okay, my mistake... this script is executed, but I don't fully understand what it does. I was hoping to prevent being asked for passphrase every time I push to remote repo. As it stands now I'm still asked every time.
A:
Bingo! Something was obviously wrong with the way the ssh-agent is run in that .bashrc. I copied the one from here and it works a treat! Now I only have to enter my passphrase once when git bash starts up, and any subsequent push no longer need it.
Here's the actual content of the script now:
SSH_ENV=$HOME/.ssh/environment
function start_agent {
echo "Initialising new SSH agent..."
/usr/bin/ssh-agent | sed 's/^echo/#echo/' > ${SSH_ENV}
echo succeeded
chmod 600 ${SSH_ENV}
. ${SSH_ENV} > /dev/null
/usr/bin/ssh-add;
}
# Source SSH settings, if applicable
if [ -f "${SSH_ENV}" ]; then
. ${SSH_ENV} > /dev/null
#ps ${SSH_AGENT_PID} doesn't work under cywgin
ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
start_agent;
}
else
start_agent;
fi
A:
The simplest mechanism on Windows is the one from here http://anterence.blogspot.co.uk/2012/01/ssh-agent-in-msysgit.html
Modified to show key names other than 'id_rsa', the .bashrc file looks like this:
#! /bin/bash
eval `ssh-agent -s`
ssh-add ~/.ssh/github_rsa
ssh-add ~/.ssh/otherkey_rsa
You are prompted for the passphrase for each key in turn, but only the first time after a machine start.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.