text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Count number of rows with blank cells (Excel / VBA)
Hi i'm trying to count the number of rows which contain blank cells. (I know there are 963 blank cells, i just don't know how many rows they're spread across)
I've very limited knowledge of VBA and am finding it difficult to implement.
The way i'm thinking...
Two for loops.
Outer loop will cycle down the rows
Inner loop will cycle across each cell in the row
When a blank cell is encountered in a row a counter will increment by one and we'll move to the next row.
A:
Here's a fairly easy way to do it without VBA:
A:
You actually don't need any loops to do this.
This sample checks row A. Change "Const column_to_test" number to the column number you wish to check for blank cells.
Sub countblank()
'This will count the number of rows that have a blank cell in column "A"
Const column_to_test = 1 'first column (A)
Dim r As Range
Set r = Range(Cells(1, column_to_test), Cells(Rows.Count, column_to_test).End(xlUp))
MsgBox ("There are " & r.SpecialCells(xlCellTypeBlanks).Count & " Rows with blank cells")
'You may want to select those rows (for deletion?)
r.SpecialCells(xlCellTypeBlanks).EntireRow.Select 'change .Select to .Delete
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
setNames for rows and columns?
I'm trying to write a function that returns a matrix with named rows and columns, and I'm looking for a more succinct solution than:
m <- get_matrix()
rownames(m) <- c('the', 'row', 'names')
colnames(m) <- c('the', 'col', 'names')
return (m)
I recently learned about the setNames function, which creates a copy of a vector or list with its names set. This is exactly the sort of functionality I need, but it doesn't work for matrix. Is there a function like setNames that works for two-dimensional data types?
A:
Use the structure function to set the dimnames attribute:
return (structure(get_matrix(), dimnames=list(c('the', 'row', 'names'), c('the', 'col', 'names'))))
To set only row names:
return (structure(get_matrix(), dimnames=list(c('the', 'row', 'names'))))
To set only column names:
return (structure(get_matrix(), dimnames=list(NULL, c('the', 'col', 'names'))))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Django Admin - Don't show results where a status tables shows "resolved"
I have a model and an admin model with a form that allows someone to enter a comment on a host that has an outage status of "Active". The comment form (within Admin) works properly where it shows all the hosts that are in the outage table, however I want to hide all the host from the outage table that have a status of "Resolved". I'm not finding a way on the django doc to do this. Is this possible within the admin page? Filter out results from a table based on the value of a column?
A:
Sorry I misunderstood your post.
To filter the results set that is displayed in the admin you can override the queryset() method of the admin class.
Like so:
class ExampleAdmin(admin.ModelAdmin):
def queryset(self, request):
qs = super(ExampleAdmin, self).queryset(request)
return qs.exclude(status='Resolved')
This will exclude any rows where the status is "Resolved" from your admin page.
See also this SO post
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Time complexitiy: Which is slower? (O(N^3) or O(2^N))
I'm learning time complexity recently and just wondering which Big-O Complexity is slower O(N^3) or O(2^N)? And why would you say that?
I can find a lot of information compared to O(N^2), O(2^N) but not O(N^3). Thank you.
A:
Changes to the "power" has greater effect than changing the "base", unless base is close to one (floating point 1.00001f).
So slowness is wildly increasing when N>2 because of N being power in the O(2^N)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Best design practices for .NET architecture with LINQ to SQL (DAL necessary? Can we truly use POCOs? Design pattern to adopt?)
I was avoiding writing what may seem like another thread on .net arch/n-tier architecture, but bear with me.
I, hopefully like others still am not 100% satisfied or clear on the best approach to take given today's trends and new emerging technologies when it comes to selecting an architecture to use for enterprise applications.
I suppose I am seeking mass community opinion on the direction and architectural implementation you would chose when building an enterprise application utilising most facets of today's .NET technology and what direction you would take. I better make this about me and my question, in fear of this being too vague otherwise; I would like to improve my architecture to improve and would really like to hear what you guys think given the list of technologies I am about to write.
Any and all best practices and architectural patterns you would suggest are welcome and if you have created a solution before for a similar type setup, any pitfalls or caveats you may have hit or overcome.
Here is a list of technologies adopted in my latest project, yep pretty much everything except WPF :)
Smart Client (WinForms)
WCF
Used by Smart Client
ASP.NET MVC
Admin tool
Client tool
LINQ to SQL
Used by WCF
Used ASP.NET MVC
Microsoft SQL Server 2008
Utilities and additional components to consider:
Dependency Injection - StructureMap
Exception Management - Custom
Unit Testing - MBUnit
I currently have this running in an n-Tier arch. adopting a Service-based design pattern utilising Request/Response (Not sure of it's formal name) and the Repository pattern, most of my structure was adopted from Rob Conery's Storefront.
I suppose I am more or less happy with most of my tiers (It's really just the DAL which I am a bit uneasy on).
Before I finish, these are the real questions I have faced with my current architecture:
I have a big question mark on if I should have a custom data access layer given the use of LINQ to SQL. Should I perform LINQ to SQL directly in my service/business layer or in a DAL in a repository method? Should you create a new instance of your DB context in each repository method call (using using())? or one in the class constructor/through DI?
Do you believe we can truly use POCO (plain old CLR objects) when using LINQ to SQL? I would love to see some examples as I encountered problems and it would have been particularly handy with the WCF work as I can't obviously be carrying L2S objects across the wire.
Creating an ASP.NET MVC project by itself quite clearly displays the design pattern you should adopt, by keeping view logic in the view, controller calling service/business methods and of course your data access in the model, but would you drop the 'model' facet for larger projects, particularly where the data access is shared, what approach would you take to get your data?
Thanks for hearing me out and would love to see sample code-bases on architectures and how it is split. As said I have seen Storefront, I am yet to really go through Oxite but just thought it would benefit myself and everyone.
Added additional question in DAL bullet point. / 15:42 GMT+10
A:
To answer your questions:
Should I perform LINQ to SQL directly in my service/business layer or in a DAL in a repository method? LINQ to SQL specifically only makes sense if your database maps 1-to-1 with your business objects. In most enterprise situations that's not the case and Entities is more appropriate.
That having been said, LINQ in general is highly appropriate to use directly in your business layer, because the LINQ provider (whether that is LINQ to SQL or something else) is your DAL. The benefit of LINQ is that it allows you to be much more flexible and expressive in your business layer than DAL.GetBusinessEntityById(id), but the close-to-the-metal code which makes both LINQ and the traditional DAL code work are encapsulated away from you, having the same positive effect.
Do you believe we can truly use POCO (plain old CLR objects) when using LINQ to SQL? Without more specific info on your POCO problems regarding LINQ to SQL, it's difficult to say.
would you drop the 'model' facet for larger projects The MVC pattern in general is far more broad than a superficial look at ASP.NET MVC might imply. By definition, whatever you choose to use to connect to your data backing in your application becomes your model. If that is utilizing WCF or MQ to connect to an enterprise data cloud, so be it.
A:
When I looked at Rob Connery's Storefront, it looked like he is using POCOs and Linq to SQL; However, he is doing it by translating from the Linq to SQL created entities to POCO (and back), which seems a little silly to me - Essentially we have a DAL for a DAL.
However, this appears to be the only way to use POCOs with Linq to SQL.
I would say you should use a Repository pattern, let it hide your Linq to SQL layer(or whatever you end up using for data access). That doesn't mean you can't use Linq in the other tiers, just make sure your repository returns IQueryable<T>.
A:
Whether or not you use LINQ-to-SQL, it is often cmomon to use a separate DTO object for things like WCF. I have cited a few thoughts on this subject here: Pragmatic LINQ - but for me, the biggest is: don't expose IQueryable<T> / Expression<...> on the repository interface. If you do, your repository is no longer a black box, and cannot be tested in isolation, since it is at the whim of the caller. Likewise, you can't profile/optimise the DAL in isolation.
A bigger problem is the fact that IQueryable<T> leaks (LOLA). For example, Entity Framework doesn't like Single(), or Take() without an explicit OrderBy() - but L2S is fine with that. L2S should be an implementation detail of the DAL - it shouldn't define the repository.
For similar reasons, I mark the L2S association properties as internal - I can use them in the DAL to create interesting queries, but...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Showing random div with javascript
So I want to show random divs, and I found this stackoverflow solution here: Showing random divs using Jquery
And the correct answer uses this code: http://jsfiddle.net/nick_craver/RJMhT/
So I want to do the above, but for the life of me, I don't know how.
I thought it would be as simple as
<html>
<head>
<script type="text/javascript">
var divs = $("div.Image").get().sort(function() {
return Math.round(Math.random())-0.5; //random so we get the right +/- combo
}).slice(0,4)
$(divs).appendTo(divs[0].parentNode).show();
</script>
<style type="text/css">
div.Image {
display: none;
}
</style>
</head>
<body>
<div class="Image"><img src="/image1.jpg">1</div>
<div class="Image"><img src="/image2.jpg">2</div>
<div class="Image"><img src="/image3.jpg">3</div>
<div class="Image"><img src="/image4.jpg">4</div>
<div class="Image"><img src="/image5.jpg">5</div>
<div class="Image"><img src="/image6.jpg">6</div>
<div class="Image"><img src="/image7.jpg">7</div>
</body>
</html>
But apparently not, as nothing shows up on my screen. Can somebody help me? Should be really really easy for someone who knows the least bit about javascript I think.
Thank ya!
A:
You are running the script before the HTML code for the body of the page has been parsed, so the elements doesn't exist yet.
Put your code in the ready event of the page:
$(document).ready(function(){
// your Javascript code goes here
});
Also you are missing the include of the jQuery library, as Conner showed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A Lot of 90% Proportions
In the land of Puzzovania Sock Enrage:
More than 90% of the puzzles are tagged with both riddle and mathematics.
More than 90% of the puzzles are tagged with both riddle and logical-deduction.
Show that among the puzzles tagged with both mathematics and logical-deduction, more than 90% are also tagged riddle.
Notes:
This is harder than it looks!
Based on a puzzle from the Russian Tournament of the Towns.
A:
Let $A_{RM}$ be puzzles tagged riddle and math, but not logical-deduction, and define $A_{LM}$, $A_{RL}$ and $A_{RLM}$ similarly.
From 1: $A_{RM} + A_{RLM} > 9(A_{RL} + A_{LM})$ (a)
From 2: $A_{RL} + A_{RLM} > 9(A_{RM} + A_{LM})$ (b)
Adding (a) and (b):
$$2A_{RLM} > 8A_{RL} + 8A_{RM} + 18A_{LM}$$
$$A_{RLM} > 4A_{RL} + 4A_{RM} + 9A_{LM}$$
Since all $A$s are non-negative, this implies $A_{RLM} > 9A_{LM}$, as desired.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find limit of the function $f(x) = \frac{\ln(x)}{\ln(2x)}$
Find limit of the function: $f(x) = \frac{\ln(x)}{\ln(2x)}$
Solve:
$\lim\frac{\ln(x)}{\ln(2x)} =\lim\frac{(\ln(x))'}{(\ln((2x))'}=\frac{\frac{1}{x}}{\frac{1}{2x}} = 2 $
However, the answer is $1$. What did I do wrong?
A:
The derivative of $\ln(2x)$ is not $\frac{1}{2x}$ but $\frac{1}{x}.$
You might also explain what limit is in question. However, the answer will remain the same.
A:
Also, another way
$$
\frac{\ln x}{\ln (2x)}= \frac{\ln x}{\ln x + \ln 2}=\frac{1}{1+\ln(2)/\ln(x)}
$$
which tends to $1$ as $x\to\infty$, or as $x\to0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Validate checkbox - frontend MVC3
I have created the following custom attribute to assist me with validating a required checkbox field:
public class CheckboxRequired : ValidationAttribute, IClientValidatable
{
public CheckboxRequired()
: base("required") { }
public override bool IsValid(object value)
{
return (bool)value == true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "mandatory";
yield return rule;
}
}
However, I am trying to get it to trigger client side, and not when I call my ActionResult (if (ModelState.IsValid))
The validation does work when I call my ActionResult, but I'd prefer it to validate before getting that far.
What modifications do I need to make to make the validation kick in client side?
Thanks
A:
In order to implement the client side you can add for example a jQuery validator method and an unobtrusive adapter (simple example):
// Checkbox Validation
jQuery.validator.addMethod("checkrequired", function (value, element)
{
var checked = false;
checked = $(element).is(':checked');
return checked;
}, '');
jQuery.validator.unobtrusive.adapters.addBool("mandatory", "checkrequired");
I hope it helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci
I update the gradle plugin to the latest : com.android.tools.build:gradle:3.0.0-alpha1 and this error occured :
export TERM="dumb"
if [ -e ./gradlew ]; then ./gradlew test;else gradle test;fi
FAILURE: Build failed with an exception.
What went wrong:
A problem occurred configuring root project 'Android-app'. Could not
resolve all dependencies for configuration ':classpath'. Could not
find com.android.tools.build:gradle:3.0.0-alpha1. Searched in the
following locations:
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha1/gradle-3.0.0-alpha1.pom
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha1/gradle-3.0.0-alpha1.jar
Required by:
Current circle.yml
dependencies:
pre:
- mkdir -p $ANDROID_HOME"/licenses"
- echo $ANDROID_SDK_LICENSE > $ANDROID_HOME"/licenses/android-sdk-license"
- source environmentSetup.sh && get_android_sdk_25
cache_directories:
- /usr/local/android-sdk-linux
- ~/.android
- ~/.gradle
override:
- ./gradlew dependencies || true
test:
post:
- mkdir -p $CIRCLE_TEST_REPORTS/junit/
- find . -type f -regex ".*/target/surefire-reports/.*xml" -exec cp {} $CIRCLE_TEST_REPORTS/junit/ \;
machine:
java:
version: oraclejdk8
Edit:
My gradle file :
buildscript {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
classpath 'com.google.gms:google-services:3.0.0'
classpath "io.realm:realm-gradle-plugin:3.1.3"
}
}
allprojects {
repositories {
mavenCentral()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
A:
Google have new maven repo
https://android-developers.googleblog.com/2017/10/android-studio-30.html > section Google's Maven Repository
https://developer.android.com/studio/preview/features/new-android-plugin-migration.html
https://developer.android.com/studio/build/dependencies.html#google-maven
So add the dependency on maven repo:
buildscript {
repositories {
...
// You need to add the following repository to download the
// new plugin.
google() // new which replace https://maven.google.com
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.3' //Minimum supported Gradle version is 4.6.
}
}
A:
For things to compile via command line I needed to include the maven repo in BOTH buildscript and allprojects.
root build.gradle:
buildscript {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
...
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
}
It's needed in the buildscript block to find the AGP, and in allprojects block to find android.arch and com.android.databinding packages (and others)
UPDATE:
It looks like the new repo is just called google() but I still needed to declare it in both places.
A:
To synchronize all of the answers here and elsewhere:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
} }
Make your buildscript in build.gradle look like this. It finds all of them between google and jcenter. Only one of them will not find all of the dependencies as of this answer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is my code not breaking and why is my maths's quiz not working . I am using python 3.2
I have made a menu as well. the main problem is with while selection:
import random
points=0
score=0
math_score=0
correctage= False
print ('Please choose one of the following: \n 1.General Quiz \n 2.Maths quiz \n 3.Exit/Quit')
selection= input ('Choose what you want to do: ')
while selection:
menu = {}
menu['1']="General Quiz."
menu['2']="Maths Quiz."
menu['3']="Exit"
while not correctage:
if selection == '1':
print ('Hello I am a Super Computer Genius Ajin')
name= (input ( ' What is your Name?')).title()
print( ' So your name is ' + name)
try:
age= int(input( ' How old are you?'))
print( ' So your Age is ' +str( age))
if age==14 or age==15:
print('You can Enter')
points=points+10
print( name+ ', You got ' +str (points) + ' points')
q1=input('Who won the last world cup ').upper()
if q1=='GERMANY':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
q2=input('Who won the founder of apple ').upper()
if q2=='STEVE JOBS':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
q3=input('Which company jailbroke ios 9 ').upper()
if q3=='PANGU':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
q4=input('What is the name of the latest apple phone? ').upper()
if q4=='IPHONE 6S':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
q5=input('What is he capital of India? ').upper()
if q5=='NEW DELHI':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
q6=input('Who is the fastest man ? ').upper()
if q6=='USAIN BOLT'or q6=='MO FARAH':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
q7=input('What is Android? ').upper()
if q7=='OPERATING SYSTEM':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
q8=input('Who is Thomas Edison ? ').upper()
if q8=='INVENTOR OF THE LIGHT BULB' or q8=='INVENTOR OF LIGHT BULB':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
q9=input('What does WWW mean ? ').upper()
if q9=='WORLD WIDE WEB':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
q10=input('Latest windows operating system? ').upper()
if q10=='WINDOWS 10':
print('Well Done')
points=points+1
score=score+1
print( name+ ', You got ' +str (points) + ' points')
else:
print ('wrong')
points=points-0
print( name+ ', You got ' +str (points) + ' points')
print(" Thank you for playing ", name, "You have scored" , score, 'out of 10')
text_file= open ("general_quiz.txt", "a")
text_file.write (name )
text_file.write (" scored ")
text_file.write(str(score ))
text_file.write (' out of 10, ' )
text_file.close()
print ("previous people who have played and what they scored out of 10")
text_file = open("general_quiz.txt", "r")
print (text_file.read())
text_file.close()
break
else:
print (' you shall not pass')
correctage=False
break
except:
print('Not a Valid age')
break
elif selection =='2':
for i in range(10):
num1=random.randint(1,12)
num2=random.randint(1,12)
ops= ('+', '-', '*')
operation= random.choice(ops)
answer=1
if operation == '+':
answer == num1+num2
elif operation == '-':
answer == num1-num2
elif operation == '*':
answer == num1*num2
maths_name= (input ( ' What is your Name?')).title()
print( ' Hello ' + maths_name)
print ('What is ' + str(num1) + operation + str(num2))
user_answer= int(input('Enter answer: '))
if user_answer == answer:
print('correct')
math_score=math_score+1
else:
print ('Incorect')
math_score=math_score-0
print(" Thank you for playing ", maths_name, "You have scored" , math_score, 'out of 10')
text_file= open("maths_score.txt", "a")
text_file.write(maths_name )
text_file.write(' Scored ')
text_file.write (str(math_score ))
text_file.write(' Out of 10, ')
text_file.close()
print('Previous people who have played are:')
text_file= open("maths_score.txt", "r")
print(text_file.read())
text_file.close()
elif selection =='3':
break
else:
break
The problem with my code is the maths quiz isn't working properly and the general quiz does not break so please someone help me.
I have spent a day trying to solve the problem
A:
The error is here:
if operation == '+':
answer == num1+num2
elif operation == '-':
answer == num1-num2
elif operation == '*':
answer == num1*num2
The three lines of the form answer == num1+num2 compare whether answer (which you initially set to 1) is equal to num1+num2, and then doing nothing with the result of that comparison.
I imagine you want the following instead:
if operation == '+':
answer = num1+num2
elif operation == '-':
answer = num1-num2
elif operation == '*':
answer = num1*num2
You might also want to consider moving the part of your program that asks your name outside of the for loop - at the moment it's asking you your name before each question.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do you place HTML in a table cell while creating a new PDF with iText7?
I'm creating a PDF with a large table on it. In this table, there's a cell that can be filled in with HTML. If it is, the HTML must be interpreted as HTML and not be shown as regular text. However, when I do so, the layout/style gets scrambled and some pictures don't get shown. (In the example I give, the bullet dashes are replaced by 9's.)
I program in C# and am using iText7 to create the PDF.
In my project, I have the following HTML Code that I want to show. The reason the HTML code looks like this is because it's RTF converted to HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="generator" content="SautinSoft.RtfToHtml.dll">
<title>Untitled document</title>
<style type="text/css">
.st1{font-family:Arial;font-size:12pt;color:#000000;}
.list-marker1 li:before {
content: "\F02D\9";
width: 30px;
font-family: Symbol;
font-size: 11pt;
}
.st2{font-family:Calibri;font-size:11pt;color:#000000;}
</style>
</head>
<body>
<div>
<p style="margin:0pt 0pt 0pt 0pt;"><span class="st1"> </span></p>
<ul style="list-style-type:none; list-style-image:none; list-style- position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="1" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Dishwasher soap container consumption is adjusted</span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="2" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Power UP ballast water treatmant unit, adjusted what necessary. GPS signal error still pending</span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="3" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Installed new insect killer in galley</span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="4" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Adjust securing and highest ladder position after its tilted to low trunnion position</span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="5" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">SW spooling device test is done and no isses </span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="6" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Sewage unit dosage pump; make permanent installation + drawing update</span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="7" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Intervention on DN203: installed tracker box on ICT request</span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="8" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Installed tracker box on ICT request </span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="9" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Regular greasing emotors according ship specific grease list</span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="10" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Regular maintenance of portable tools</span></li></ul>
<ul style="list-style-type:none; list-style-image:none; list-style-position:outside; margin-left:0px; padding-left:0px; text-indent:0px; margin-top:0px; margin-bottom:0px;" class="list-marker1">
<li value="11" style="margin-left:36pt;text-indent:-18pt;"><span class="st2">Intervention on DN203 due to problem with SB M/E</span></li></ul>
<p style="margin:0pt 0pt 0pt 0pt;"><span class="st2"> </span></p>
<p style="margin:0pt 0pt 0pt 0pt;"><span class="st1"> </span></p>
</div>
</body>
</html>
When I save this file as a HTML file and open it in a browser, you get the following result (which is correct): Correct result (website)
However, when I add it to the PDF cell, I get the following result: Bad result (PDF)
As you can see, the dashes used for bulleting have turned into 9's.
The code I use to add the HTML code to the PDF File is the following:
private void AddCellToTable(table table, string HTMLContent) {
Cell newCell = new Cell();
foreach (var element in HtmlConverter.ConvertToElements(HTMLContent))
{
var test = (IBlockElement)element;
newCell.Add(test);
}
table.AddCell(newCell);
}
This code is similar to the code suggested by https://itextpdf.com/en/resources/books/itext-7-converting-html-pdf-pdfhtml/chapter-1-hello-html-pdf (They use java instead of C#).
I would like to show bullets as dashes, instead of these 9's. Any help or suggestions would be very much appreciated.
Thank you in advance.
A:
Firstly, the problem isn't related to layout (table/cell/etc processing) - it's only about fonts and how iText processes them.
Secondly, the problem is that PDF's standard Symbol font, which is used by iText, differs from the one used by browsers.
Thirdly, iText doesn't processes "\F02D\9" (and "\9" part in particular) correctly.
What can you do to improve the resultant pdf? Don't use the standard PDF's Symbol font - use your own Symbol font instead.
How to do it?
Let me introduce you the FontProvider class.
FontProvider is responsible to handle the fonts which may be used
while processing an html file. Its instance could be passed as a
parameter of ConverterProperties, otherwise it'd be created by
iText. By default iText adds to FontProvider all standard pdf fonts
(FontProvider#addStandardPdfFonts) and some free sans fonts
(DefaultFontProvider#SHIPPED_FONT_NAMES).
You want to use your own Symbol font: that means that you should prevent iText from considering standard Symbol font during convertion. To do so, please create a DefaultFontProvider instance with the first constructor's argument passed as false.
(!) In 99% of the cases you want some other standard fonts to be considerd during convertion. So please add them manually as follows:
provider.addFont(StandardFonts.TIMES_ROMAN);
// some other fonts to be added
Now add your own Symbol font to this FontProvider instance the same way as I did it for the Times above:
provider.addFont("C:\\Windows\\Fonts\\symbol.ttf", PdfEncodings.IDENTITY_H);
It's important to use IDENTITY_H there, because in the Symbol font "-" has "F02D" as its unicode value.
After all these changes, I've managed to get the following file:
Now comes the second problem: iText doesn't process "\9" by default correctly. As for this one, I don't know any straight-forward solution. Probably, removing it from your html is the best one.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How much time does the original Fullmetal Alchemist anime cover?
I was always confused with something in the original (2003) Fullmetal Alchemist anime.
When Elric brothers have helped the Hughes' when Alicia was born, that happened around the same time when Edward have become a State Alchemist. If I know well, he was 12 in that time. It was in episode 6.
Most of the following episodes (Barry incident, the Chimaera, etc.) seems to cover a relatively short time. However, later it was mentioned that Ed is 14-15 years old. And also, I'm absolutely sure that it was true at the time when Hughes was murdered.
Which is the exact timeline order of the event in the episodes? First episode is obviously an introducing one, and second is the beginning of everything, and then?
Also, how is it possible that Edward looks totally the same in Episode 6 (where he was 12) and in Episode 50, for example (where he was 15)?
A:
Please note: Much of this information does not apply to Brotherhood.
The order of episodes goes something like this:
Episode 1 flashback
Transmutation of Trisha
Episode 28 flashbacks
Initial alchemy training under Izumi
Pre-automail for Edward
Episodes 3 through 9
Barry the Chopper
Shou Tucker and Nina
Etc.
Episodes 1, 2, and 10 through 51 (not counting flashbacks)
Main story
The Conqueror of Shamballa
I have missed a few brief flashbacks here, but this is the general idea. You can use Edward's age, somewhat, as a marker of time passing. He is ~11 in the flashbacks of their mother, 12 during his State Alchemist qualification, and turns 15 prior to the main story (the incident in Lior, etc.). He is 18 during The Conqueror of Shamballa. (This is shown by 14-year-old Al reverting to being 10 years old, then aging to 13 when Eckhart starts breaking into Amestris. Since he is one year younger, and would be 17, Ed is about 18.)
Here is a handy chart for a full comprehensive view of the series (click to enlarge, or click here for the spreadsheet). Note that Edward does have a birthday in the main timeline, when he turns 16.
(Orange = pre-anime; yellow = flashbacks; green = anime series; blue = post-anime)
To address your point about Ed's appearance: Edward doesn't actually look the same at 12 as he does at 15. At 12, his eyes are slightly larger and his face is a bit rounder, save for his chin, giving him an overall slightly younger and more innocent look. It's not generally noticeable in the more zoomed-out shots, but it's there. (Also remember that, to perpetuate the "shorty"/"chibi" jokes, he couldn't grow much, so all the changes are facially.)
(Left: 12-year-old Ed, episode 4, 6:45; Right: 15-year-old Ed, episode 10, 13:50)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Plotting using ggplot
I use the following code:
library(ggplot2)
ggplot(data = mpg) +
geom_point(aes(x = displ^2, x = hwy)
mpgfil = fliter(mpg, cyl = 8)
mpg_manu= select(mpg, starts_with("man") & ends_with("rv")
And a lot of various errors occur.
Any advice is appreciated.
A:
As for ggplot part you made typo in a code: the second argument should be substituted from x to y, as the points you are plotting should have two coordinates.
As for filter and select helpers you have multiple typos, as well as you cannot use & operator to create conditions for column selection:
Please see the corrected code below
library(ggplot2)
library(dplyr)
ggplot(data = mpg) + geom_point(aes(x = displ^2, y = hwy))
mpgfil <- filter(mpg, cyl == 8)
head(mpgfil)
# # A tibble: 6 x 11
# manufacturer model displ year cyl trans drv cty hwy fl class
# <chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
# 1 audi a6 quattro 4.2 2008 8 auto(s6) 4 16 23 p midsize
# 2 chevrolet c1500 suburban 2wd 5.3 2008 8 auto(l4) r 14 20 r suv
# 3 chevrolet c1500 suburban 2wd 5.3 2008 8 auto(l4) r 11 15 e suv
# 4 chevrolet c1500 suburban 2wd 5.3 2008 8 auto(l4) r 14 20 r suv
# 5 chevrolet c1500 suburban 2wd 5.7 1999 8 auto(l4) r 13 17 r suv
# 6 chevrolet c1500 suburban 2wd 6 2008 8 auto(l4) r 12 17 r suv
mpg_manu <- select(mpg, starts_with("man")) %>% select(ends_with("rv"))
head(mpg_manu)
# A tibble: 6 x 0
Output:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does one recreate a custom application launcher that takes command line syntax and even perhaps parameters?
I had some custom scripts that I had custom launchers for on my desktop on 10.04. I would like to recreate that again after migration to 12.04, but unity seems quite foreign to me.
A:
I have answered a similar question here.
Briefly, copy the nearest script from /usr/share/applications/ to ~/.local/share/applications and then edit the xyz.desktop file. The line that starts Exec= is the line you need to edit, to put your own command in, along with whatever command line options you want. You will probably also want to edit the Name= line to describe your own script.
Once you've done that you'll need to restart your computer or log out/log in, then you can hit the Super key, start typing part of the name you set and your launcher should appear. Select it and hit Enter and it will run your command.
A:
Maybe you are looking for this command:
gnome-desktop-item-edit ~/Desktop/ --create-new
Good Luck!
A:
I made a simple python script with GUI for this!
It's on http://jurschreuder.nl/
It's called Unity Launcher Creator, and I even use it myself!
Super simple:
Unzip
Click on UnityLauncherCreator.py
Type in name
Select program
Select icon
A launcher is created that you can drag & drop to Unity
I've included some icon files created by a genetic algorithm (GenArt for Android). You can use it in case the program doesn't supply a png or when it's just your own simple bash script.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Join Without Temp Tables
Long-ish story short, I have two individual queries that I want to combine into one better looking one. I previously accomplished this with CTE's, but I need to use SSIS '05 and it does not support CTE's or temp tables - and I cannot for the life of me figure out how to do it without them.
Like I said I have two separate 'select' statements. One for first averages, another for subsequent averages. The first has an output similar to this:
Description First_Averages
a) xxx 4.533333
b) xxx 8.238095
c) xxx .5
I) xxx 2
j) xxx 2.25
and my second 'select' statement's output looks very similar:
Description Subsequent_Averages
a) xxx 4.225806
b) xxx 4.393939
c) xxx .1428571
d) xxx 0
f) xxx 0
j) xxx 1.666667
Using CTE's, I got it to show every description even if the values were null (replacing nulls with 0) and combine them into one (much better looking) output. The desired output that I was able to get with CTE's looks like this:
Description First_Averages Subsequent_Averages
a) xxx 4.533333 4.225806
b) xxx 8.238095 4.393939
c) xxx .5 .1428571
d) xxx 0 0
e) xxx 0 0
f) xxx 0 0
g) xxx 0 0
h) xxx 0 0
i) xxx 2 0
j) xxx 2.25 1.666667
Is there a way to do this without using CTE's or temp tables of any kind?
My code for those first two 'select' statements is as follows:
SELECT
description, avg(total_score)
FROM (a long select statement)
WHERE sequence_num = '1'
group by description
order by description;
The second 'select' statement's code is exactly the same except for "sequence_num = '1'" is "sequence_num <> '1'".
If you want to see the FROM code, I can update and include it. It was making this post longer than it already is though so I removed it.
I can't find a way to display all the descriptions including those that have null average values and join the averages to the descriptions like I did with the CTE.
Thanks in advance for the tips. Let me know if you need more information, I've been running in circles for a while now trying to do this.
A:
Try CASE expressions:
SELECT
description,
avg(total_score),
avg( CASE WHEN sequence_num = 1 THEN total_score END ),
avg( CASE WHEN sequence_num <> 1 THEN total_score END )
FROM (a long select statement)
group by description
order by description;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
When does $\wp$ take real values?
Whittaker and Watson mention that when the invariants $g_2, g_3$ of Weierstrass $\wp$ function are real and such that $g_2^3 - 27g_3^2 > 0$, and if $2\omega_1$ and $2\omega_2$ are its periods then the function takes real values on the perimeter of the parallelogram with vertices $0,\omega_1,-\omega_2,-\omega_1-\omega_2$.
I am not able to understand why $\wp$ takes real values. Can someone help?
A:
Late answer, but here it is why.
If $g_2, g_3 \in \mathbb{R}$ and $g_2^3-27g_3^2>0$ it can bee seen that the half periods are of the form $\omega_1=\alpha$ and $\omega_2=i \beta$ with $\alpha, \beta \in \mathbb{R}$.
This essentially does the trick since it is easily seen by a direct computation that if $\wp(z)=\wp(z|\alpha, i \beta)$ then
\begin{equation}
\overline{\wp(z)}=\wp\left(\overline{z}\right) \tag{1}
\end{equation}
Now take $z \in \{ iy, \ \alpha+iy, \ x, \ x+i \beta : x,y \in \mathbb{R}\}$.
i): If $z=iy$ with $y \in \mathbb{R}$, by (1) it follows that $\overline{\wp(z)}=\overline{\wp(iy)}=\wp\left(\overline{iy}\right)=\wp(-iy)$, but since $\wp$ is even then $\wp(-iy)= \wp(iy)$, thus indeed
$$
\overline{\wp(z)}=\wp(iy)=\wp(z), \ \text{hence} \ \wp(z) \in \mathbb{R}
$$
ii): If $z=\alpha + iy$ with $y \in \mathbb{R}$, again by (1), $\overline{\wp(z)}=\overline{\wp(\alpha+iy)}=\wp\left(\overline{\alpha + iy}\right)=\wp(\alpha-iy)$, but $2\alpha$ is a period of $\wp$, that gives $\wp(\alpha-iy)= \wp(\alpha-iy-2\alpha)=\wp(-(\alpha+iy))$, again being $\wp$ even we have $\wp(-(\alpha+iy))=\wp(\alpha+iy)$, therefore
$$
\overline{\wp(z)}=\wp(\alpha+iy)=\wp(z), \ \text{hence } \ \wp(z) \in \mathbb{R}
$$
iii): If $z=x$ with $x \in \mathbb{R}$, (1) gives that $\overline{\wp(z)}=\overline{\wp(x)}=\wp(\overline{x})=\wp(x)=\wp(z)$, then of course $\wp(z) \in \mathbb{R}$
iv): Finally when $z=x + i\beta$ with $x \in \mathbb{R}$, by (1), $\overline{\wp(z)}=\overline{\wp(x+i\beta)}=\wp\left(\overline{x + i\beta}\right)=\wp(x-i\beta)$, since $2i\beta$ is a period of $\wp$ then $\wp(x-i\beta)= \wp(x-i\beta+2i\beta)=\wp(x+i\beta)$, therefore again
$$
\overline{\wp(z)}=\wp(x+i\beta)=\wp(z), \ \text{hence } \ \wp(z) \in \mathbb{R}
$$
Thus indeed $\wp$ takes real values in all the parallelograms generated by the half periods $\omega_1$ and $\omega_2$, as wanted.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A problem when using PageTransitionForward and Backward
http://www.youtube.com/watch?v=DyssOSmwuoo
according to my video
when call animation PageTransitionForward it will have a triangle on the left
and that triangle can see through next layer
how can i fix it?
A:
It happens because of limitation of depth buffer (search about z-fighting for more info).
To fix it just find CCPageTurn3DAction.m file and in (void)update:(ccTime) method change z coordinate of all vertices of the animated grid to some higher value (e.g. 0.5).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sequalize filtering on sub sub models
I'm trying to filter on a sub sub model, for that I'm doing the following filter:
await models.Event.findAll({
include: [
{
model: models.SubEvent,
include: [
{
model: models.Game,
where: {
[models.Sequelize.Op.or]: {
player1Team1Id: args.playerId,
player2Team1Id: args.playerId,
player1Team2Id: args.playerId,
player2Team2Id: args.playerId
}
},
required: true
}
]
}
]
});
The model structure is as following: A Event.hasMany(SubEvent) and SubEvent.hasMany(Game)
but the following gives me all the events.
not the one where the player matches
Any suggestions on why this is happening?
A:
The where clause is malformed, so probably Sequelize is ignoring it (you could confirm by looking at the generate SQL). OR needs to be an array of objects as shown below.
where: {
[models.Sequelize.Op.or]:
[
{player1Team1Id: args.playerId},
{player2Team1Id: args.playerId},
{player1Team2Id: args.playerId},
{player2Team2Id: args.playerId}
]
},
Strange there was no exception.
hth
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Diferença de tamanho (Release/Debug)
No Delphi tem Build Configurations (Release e Debug), escolhendo o Release o tamanho do executável diminui, queria saber o que ele deixa de incluir no Release, pois o tamanho teve uma diminuição considerável em relação ao Debug.
A:
Debug
É a forma de compilação utilizada para depurar a aplicação.
Ela vai gerar um executável maior por causa disso, porque para debugar algumas coisas, é necessário ter os pontos de referencias do código.
Release
É a forma de compilação enxuta, onde é gerado a versão que será disponibilizada para o cliente. Ela é menor pois não precisamos das referencias.
--
Essa é a diferença básica entre as duas, mas você pode customizar individualmente cada uma delas:
Isso vai permitir você fazer validações diferente quando estiver em Release ou Debug utilizando diretivas.
--
Você ainda pode criar suas próprias formas, onde pode adicionar verificações de vazamentos de memória, Code Review, Cobertura e varias outras coisas:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
One Signal Phonegap não funciona
Eu estou fazendo uma atualização de um app phonegap, ele compila na nuvem sem problemas, porém ao tentar fazer o login que estou usando o One Signal para fazê-lo, ele não acessa, não é problema com o api pois declarei que enviasse uma mensagem de erro. A versão que está rodando não apresenta o erro, apenas quando compilo no zip no site do phonegap, tentei fazer a build das versões anteriores, e se a build for feita a versão antiga também apresenta o erro. Alguém pode me dizer se há algo de errado com o xml. Ou alguém que tenha uma maior experiência com o One Signal para me dizer o que pode ser, segue o xml e o controler js:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.vectra.odontomedica" version="1.0.6" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:gap="http://phonegap.com/ns/1.0">
<name>Vectra</name>
<description>
Desenvolvimento por Augusto Xavier
</description>
<author email="[email protected]" href="">
Augusto Xavier
</author>
<content src="index.html"/>
<access origin="*"/>
<preference name="android-windowSoftInputMode" value="adjustPan" />
<preference name="webviewbounce" value="false"/>
<preference name="UIWebViewBounce" value="false"/>
<preference name="DisallowOverscroll" value="true"/>
<preference name="android-minSdkVersion" value="16"/>
<preference name="android-targetSdkVersion" value="23"/>
<preference name="BackupWebStorage" value="none"/>
<preference name="SplashScreen" value="screen"/>
<preference name="SplashScreenDelay" value="3000"/>
<feature name="StatusBar">
<param name="ios-package" value="CDVStatusBar" onload="true"/>
</feature>
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<plugin name="cordova-plugin-splashscreen" spec="4.0.0" />
<plugin name="cordova-plugin-whitelist" spec="1.3.0" />
<plugin name="ionic-plugin-keyboard" spec="2.2.1" />
<plugin name="onesignal-cordova-plugin" spec="2.0.6" />
<preference name="phonegap-version" value="cli-6.3.0" />
<preference name="android-build-tool" value="gradle" />
<preference name="fullscreen" value="false" />
<platform name="android">
<preference name="SplashScreen" value="screen"/>
<preference name="SplashScreenDelay" value="3000"/>
<!-- you can use any density that exists in the Android project -->
<splash src="res/screen/android/splash-land-hdpi.png" density="land-hdpi"/>
<splash src="res/screen/android/splash-land-ldpi.png" density="land-ldpi"/>
<splash src="res/screen/android/splash-land-mdpi.png" density="land-mdpi"/>
<splash src="res/screen/android/splash-land-xhdpi.png" density="land-xhdpi"/>
<splash src="res/screen/android/splash-port-hdpi.png" density="port-hdpi"/>
<splash src="res/screen/android/splash-port-ldpi.png" density="port-ldpi"/>
<splash src="res/screen/android/splash-port-mdpi.png" density="port-mdpi"/>
<splash src="res/screen/android/splash-port-xhdpi.png" density="port-xhdpi"/>
</platform>
<platform name="ios">
<!-- images are determined by width and height. The following are supported -->
<splash src="res/screen/ios/Default~iphone.png" width="320" height="480"/>
<splash src="res/screen/ios/Default@2x~iphone.png" width="640" height="960"/>
<splash src="res/screen/ios/Default-Portrait~ipad.png" width="768" height="1024"/>
<splash src="res/screen/ios/Default-Portrait@2x~ipad.png" width="1536" height="2048"/>
<splash src="res/screen/ios/Default-Landscape~ipad.png" width="1024" height="768"/>
<splash src="res/screen/ios/Default-Landscape@2x~ipad.png" width="2048" height="1536"/>
<splash src="res/screen/ios/Default-568h@2x~iphone.png" width="640" height="1136"/>
<splash src="res/screen/ios/Default-667h.png" width="750" height="1334"/>
<splash src="res/screen/ios/Default-736h.png" width="1242" height="2208"/>
<splash src="res/screen/ios/Default-Landscape-736h.png" width="2208" height="1242"/>
</platform>
<icon gap:platform="ios" src="res/icons/ios/icon-small.png" width="29" height="29" />
<icon gap:platform="ios" src="res/icons/ios/icon-small-2x.png" width="58" height="58" />
<icon gap:platform="ios" src="res/icons/ios/icon-40.png" width="40" height="40" />
<icon gap:platform="ios" src="res/icons/ios/icon-40-2x.png" width="80" height="80" />
<icon gap:platform="ios" src="res/icons/ios/icon-50.png" width="50" height="50" />
<icon gap:platform="ios" src="res/icons/ios/icon-50-2x.png" width="100" height="100" />
<icon gap:platform="ios" src="res/icons/ios/icon.png" width="57" height="57" />
<icon gap:platform="ios" src="res/icons/ios/icon-2x.png" width="114" height="114" />
<icon gap:platform="ios" src="res/icons/ios/icon-60.png" width="60" height="60" />
<icon gap:platform="ios" src="res/icons/ios/icon-60-2x.png" width="120" height="120" />
<icon gap:platform="ios" src="res/icons/ios/icon-60-3x.png" width="180" height="180" />
<icon gap:platform="ios" src="res/icons/ios/icon-72.png" width="72" height="72" />
<icon gap:platform="ios" src="res/icons/ios/icon-72-2x.png" width="144" height="144" />
<icon gap:platform="ios" src="res/icons/ios/icon-76.png" width="76" height="76" />
<icon gap:platform="ios" src="res/icons/ios/icon-76-2x.png" width="152" height="152" />
<icon gap:platform="android" gap:qualifier="ldpi" src="res/icons/android/icon-36-ldpi.png"/>
<icon gap:platform="android" gap:qualifier="mdpi" src="res/icons/android/icon-48-mdpi.png"/>
<icon gap:platform="android" gap:qualifier="hdpi" src="res/icons/android/icon-72-hdpi.png"/>
<icon gap:platform="android" gap:qualifier="xhdpi" src="res/icons/android/icon-96-xhdpi.png"/>
<icon gap:platform="android" gap:qualifier="xxhdpi" src="res/icons/android/icon-144-xxhdpi.png"/>
<icon gap:platform="android" gap:qualifier="xxxhdpi" src="res/icons/android/icon-192-xxxhdpi.png"/>
</widget>
O Controlador js:
(function () {
'use strict';
angular
.module('LoginModule', ['CommonModule'])
.controller('LoginController', LoginController);
LoginController.$inject = ['$scope', 'CommonService', '$ionicPopup', '$ionicLoading', '$state'];
function LoginController($scope, CommonService, $ionicPopup, $ionicLoading, $state) {
//CommonService.sair();
//CommonService.verificaLogado();
$scope.popup = {};
$scope.gravarSenha = false;
$scope.esqueciData = {};
var isGravarSenha = localStorage.getItem("gravarSenha");
if (isGravarSenha != null && isGravarSenha != undefined && isGravarSenha != "") {
isGravarSenha = JSON.parse(isGravarSenha);
$scope.gravarSenha = true;
$state.go("app.home");
}
var dadosOdonto = JSON.parse(localStorage.getItem("dadosOdonto"));
if (dadosOdonto != undefined && dadosOdonto.Url != null) {
$scope.logotipo = dadosOdonto.Url + "/logotipo.png";
} else {
$scope.logotipo = "img/logotipo.png";
}
$scope.cadastroNovo = function () {
localStorage.setItem("configuracoes", "false");
$state.go('cadastro');
}
$scope.clicarSenha = function (gravar) {
$scope.gravarSenha = gravar;
}
$scope.logar = function (data) {
$ionicLoading.show({
template: 'Efetuando o login...'
});
window.plugins.OneSignal.getIds(function (ids) {
data.deviceId = ids.userId;
//data.deviceId = "";
var chamaApi = CommonService.api("http://api.agafcomunicacao.com.br/api/login/entrar", data);
chamaApi.get(data).$promise.then(function (retorno) {
$ionicLoading.hide();
if (retorno.Cro != undefined) {
if ($scope.gravarSenha == true) {
localStorage.setItem("gravarSenha", JSON.stringify(data));
} else {
localStorage.removeItem("gravarSenha");
}
localStorage.setItem("logado", JSON.stringify(retorno));
$state.go('app.home');
} else {
$ionicPopup.alert({
title: 'Mensagem',
template: retorno.Mensagem
});
}
}, function (error) {
$ionicLoading.hide();
$ionicPopup.alert({
title: 'Ocorreu um erro!',
template: 'Erro ao realizar integração com a Api! Tente novamente mais tarde!'
});
});
});
}
$scope.esqueciSenha = function () {
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="popup.croEsqueciSenha" placeholder="Cro: ">',
title: 'Recuperar senha pelo Cro',
subTitle: 'Digite seu Cro',
scope: $scope,
buttons: [
{ text: 'Cancelar' },
{
text: '<b>Solicitar</b>',
type: 'button-positive',
onTap: function (e) {
if (!$scope.popup.croEsqueciSenha) {
e.preventDefault();
} else {
return $scope.popup.croEsqueciSenha;
}
}
}
]
});
myPopup.then(function (res) {
if (res != undefined) {
$ionicLoading.show({
template: 'Aguarde...'
});
var data = {};
data.cro = res;
var chamaApi = CommonService.api("http://api.agafcomunicacao.com.br/api/login/esquecisenha", data);
chamaApi.get(data).$promise.then(function (retorno) {
$ionicLoading.hide();
$scope.popup = {};
$ionicPopup.alert({
title: 'Mensagem',
template: retorno.Mensagem
});
}, function (error) {
$ionicLoading.hide();
$ionicPopup.alert({
title: 'Ocorreu um erro!',
template: 'Erro ao realizar integração com a Api! Tente novamente mais tarde!'
});
});
}
});
}
$scope.recuperarSenha = function () {
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="esqueciData.cro" placeholder="Cro:"></br><input type="text" ng-model="esqueciData.codigo" placeholder="Código:"> </br><input type="password" ng-model="esqueciData.novaSenha" placeholder="Nova Senha:">',
title: 'Trocar Senha',
subTitle: 'Digite o código enviado por e-mail e a nova senha',
scope: $scope,
buttons: [
{ text: 'Cancelar' },
{
text: '<b>Recuperar</b>',
type: 'button-positive',
onTap: function (e) {
if (!$scope.esqueciData.cro || !$scope.esqueciData.codigo || !$scope.esqueciData.novaSenha) {
e.preventDefault();
} else {
var data = {};
data.codigo = $scope.esqueciData.codigo;
data.cro = $scope.esqueciData.cro;
data.novaSenha = $scope.esqueciData.novaSenha;
return data;
}
}
}
]
});
myPopup.then(function (res) {
if (res != undefined) {
$ionicLoading.show({
template: 'Aguarde...'
});
var chamaApi = CommonService.api("http://api.agafcomunicacao.com.br/api/login/alterarsenha", res);
chamaApi.get(res).$promise.then(function (retorno) {
$ionicLoading.hide();
$scope.esqueciData = {};
$ionicPopup.alert({
title: 'Mensagem',
template: retorno.Mensagem
});
}, function (error) {
$ionicLoading.hide();
$ionicPopup.alert({
title: 'Ocorreu um erro!',
template: 'Erro ao realizar integração com a Api! Tente novamente mais tarde!'
});
});
}
});
}
}
})();
A:
Descobri a solução o código estava descontinuado, ajustei sendo a documentação do OneSignal e instalei o plugin cordova-plugin-file que é responsável por gravar as informações do deviceid, assim consegui resolver o problema.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error in the return of the intersection points
My algorithm checks the relative position between two lines at this point I'm sure the lines are concurrents and want to return the point of intersection. I'm using this formula to not have linear systems:
My problem is when the input lines are as follows:
r: X= (8,1,9) + λ(2,-1,3) s: X (3,-4,4) + µ(1,-2,2) I hope the output is (-2, 6, -6) but is (7.6, 1.2, 8.4). Does anyone have any idea why this occurs?
My method
public Point3D intersectingLines(Line lineOne, Line lineTwo) {
double x = lineOne.getPoint().getX() - lineTwo.getPoint().getX();
double y = lineOne.getPoint().getY() - lineTwo.getPoint().getY();
double z = lineOne.getPoint().getZ() - lineTwo.getPoint().getZ();
Vector3D pointsDifference = new Vector3D(x, y, z);
Vector3D second = pointsDifference.crossProduct(lineTwo.getVector());
Vector3D first = lineOne.getVector().crossProduct(lineTwo.getVector());
double lambda = first.getNorm() / second.getNorm();
double xIntersectionOne = lineOne.getPoint().getX() + (lambda * lineOne.getVector().getX());
double yIntersectionOne = lineOne.getPoint().getY() + (lambda * lineOne.getVector().getY());
double zIntersectionOne = lineOne.getPoint().getZ() + (lambda * lineOne.getVector().getZ());
double xInLineTwo = (xIntersectionOne - lineTwo.getPoint().getX()) / lineTwo.getVector().getX();
double yInLineTwo = (yIntersectionOne - lineTwo.getPoint().getY()) / lineTwo.getVector().getY();
double zInLineTwo = (zIntersectionOne - lineTwo.getPoint().getZ()) / lineTwo.getVector().getZ();
//Here I check if the point is even correct or lambda must be negative to obtain the correct point
if (xInLineTwo == yInLineTwo && xInLineTwo == zInLineTwo) {
return new Point3D(xIntersectionOne, yIntersectionOne, zIntersectionOne);
} else {
xIntersectionOne = lineOne.getPoint().getX() + (-1 * lambda * lineOne.getVector().getX());
yIntersectionOne = lineOne.getPoint().getY() + (-1 * lambda * lineOne.getVector().getY());
zIntersectionOne = lineOne.getPoint().getZ() + (-1 * lambda * lineOne.getVector().getZ());
return new Point3D(xIntersectionOne, yIntersectionOne, zIntersectionOne);
}
}
A:
The main problem is in the equation the other tests had no difference but that particular equation yes. The equation is in "reverse" order so got lambda = |0,2| and not lambda = |5|.
And another problem was noted in the comment's David Wallace where the condition checks equality of doubles type.
See more
|
{
"pile_set_name": "StackExchange"
}
|
Q:
UnZip data in C#
I'm new at C#, I writing a simple web service. It takes the zip file and decompress it in file system. In C# code is:
[WebMethod]
public String SetZip(string device_id, string file)
{
if (device_id == null || device_id.Length == 0)
{
return "10;no auth data";
}
StringBuilder output = new StringBuilder();
if (direcory == null)
{
return output.ToString();
}
string dirname = "c:\\temp\\" + direcory + "\\";
if (!System.IO.Directory.Exists(dirname))
{
System.IO.Directory.CreateDirectory(dirname);
}
string filename = dirname + "file1.txt";
string text = UnZipStr(Convert.FromBase64String(file));
File.WriteAllText(filename, text);
output.AppendLine("0;done");
return output.ToString();
}
public static string UnZipStr(byte[] input)
{
using (MemoryStream memstream = new MemoryStream())
{
using (MemoryStream inputStream = new MemoryStream(input))
{
using (DeflateStream gzip =
new DeflateStream(inputStream, CompressionMode.Decompress))
{
using (StreamReader reader =
new StreamReader(gzip, System.Text.Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
}
And send zip data from java code:
void callService(byte[] xmlData) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("device_id", AGENT);
Deflater deflater = new Deflater();
deflater.setInput(xmlData);
deflater.finish();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
while (!deflater.finished()) {
int byteCount = deflater.deflate(buf);
baos.write(buf, 0, byteCount);
}
deflater.end();
byte[] compressedBytes = baos.toByteArray();
request.addPropertyIfValue("file", org.kobjects.base64.Base64.encode(compressedBytes));...}
At C# code I have Exception when read data from StreamReader
SoapFault - faultcode: 'soap:Server' faultstring: 'System.Web.Services.Protocols.SoapException: ---> InvalidDataException: Block length does not correspond to the complement.
System.IO.Compression.Inflater.DecodeUncompressedBlock(Boolean& end_of_block)
System.IO.Compression.Inflater.Decode()
System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length)
System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count)
System.IO.StreamReader.ReadBuffer()
System.IO.StreamReader.ReadToEnd()
Service.UnZipStr(Byte[] input) в c:\inetpub\wwwroot\WebSite\App_Code\Service.cs: at 94
Service.SetZip(String device_id, String file) в c:\inetpub\wwwroot\WebSite\App_Code \Service.cs: at 73
What I'm doing wrong?
A:
Edit: I've been digging around and there is a way to generate DEFLATE format data from Java that C# recognizes: you have to use the Deflater(int,boolean) constructor. So change your Java code to:
Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
deflater.setInput(xmlData);
deflater.finish();
The reason is that by default the deflater emits a ZLIB header and checksum, which the C# DeflateStream doesn't expect.
It seems that Java and C# don't agree on the exact variety of "deflate" compression algorithm, but by my tests "gzip" should work:
This compresses xmlData in Java:
ByteArrayOutputStream baos = new ByteArrayOutputStream()
OutputStream out = new GZIPOutputStream(baos);
out.write(xmlData);
out.close();
byte[] compressedBytes = baos.toByteArray();
This decompress input in C#:
using (MemoryStream inputStream = new MemoryStream(input))
{
using (GZipStream gzip = new GZipStream(inputStream, CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(gzip, System.Text.Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to draw dotted lines between geopoints in google map on android
I have displayed the locations on map with marker images, but now i want to connect the locations by dotted lines, in same line locations.
Please give any idea....
A:
Here is your answer,
drawing-dotted-trail-path-instead-of-a-line
Implementation for the same is here too
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Организация указателей элементов двумерного массива
Здравствуйте. Допустим у меня динамически выделенный двумерный массив 3*5 (пусть будет матрица):
int** mat = malloc(sizeof(int*)*3);
for(int i = 0; i < 3; i++)
mat[i] = malloc(sizeof(int)*5);
Я хочу пробежаться не по всей матрице, а только по всем элементам от начальной точки (1,2) (вверх и вправо соотвественно).
Верна ли подобная аритметика указателей в данном случае:
int** ptr = &(&mat[1][2]);
ptr[0][0] == mat[1][2]; /// верно ли равенство ?
ptr[0][1] == mat[1][3]; /// "
ptr[1][1] == mat[2][3]; /// "
со сдвигом вправо в целом проблем меньше, так как можно просто взять original_mat + i и тогда например mat[0][5] = original_mat[0+i][5] является верным использованием ариметики, как на счет сдвига вверх? То есть верно ли сказать что расстояние между адрессами 2 строки в ширь явяется расстоянием "одного передвижения" размером соответвующего указателя. Или это совсем не обязательно и они разбросаны.
Или же разбросаны только в случае динамического выделения, а например при стандарте с99 если определить матрицу mat[length][width], то выше изложенный метод доступа с определенной точки к суб-матрице будет работать ?
Или единственный способ это сделать, это создать новый двумерный массив с соответсвующими размерами и переместить указатели всей строки (каждый указатель является указателем на сплошной ряд элементов всего столбца или части его - зависит от второй координаты) вручную в массив указатель друг за другом ?
Насколько понятна задача (доступ к суб-матрице с определнной точки), насколько понятны предложения о решение ?
A:
Сейчас Вы выделяете память сначала на указатели строк, затем каждому такому указателю выделяете место для самой строки. Верно, что выделенные куски памяти под строки не обязаны располагаться друг за другом.
Не могу подсказать, как работает выделение памяти сразу под двумерный массив, но точно могу сказать, что подобный способ не единственный. Советую использовать линейный массив как двумерный — в нём легко будет перепрыгивать по указателям.
int h = 3;
int w = 5;
int* mat = malloc(sizeof(int) * h * w);
Тогда обращаться к элементу с индексами (1,2) можно будет как mat[1*w+2].
UPD. В целом, первые два Ваши равенства логически правильны. С третьим не согласен, думаю, при итерации первого индекса второй как бы переходит в ноль. То есть:
ptr[1][1] == mat[2][1];
Но стоит учесть нюанс, что адрес (&) мы можем брать у переменной в памяти. Брать указатель указателя не получится, ибо это не переменная, а значение. Не компилируется, в общем.
Дальше я сделал такую программку, чтобы проверить, как выделяется память при объявлении сразу двумерного массива:
int h = 3;
int w = 5;
int mat[h][w];
for (int i = 0; i < h * w; i++) {
mat[i / w][i % w] = i + 1;
}
int* ptr = mat[0];
for (int i = 0; i < h * w; i++) {
int val = ptr[i];
printf("%d ", val);
}
printf("\n");
Получаем красивый вывод:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Подтверждает предположение о монолитном выделении памяти под двумерный массив.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting all members of a group and its subgroups
I have groups as such:
GroupA
GroupB
Users
GroupG
Users
So the goal is to get all users that are members of parent group GroupA.
I have the following filter:
(&(objectCategory=Person)(objectClass=User)(mail=*MyEmailDomain.com)(memberOf=CN=GroupB,OU=MyOU3,OU=MyOU2,OU=MyOU1,DC=MyDomain,DC=LOCAL))
Which works for the lowest level groups.
From research, it seems that this should work, but doesn't:
(&(objectCategory=Person)(objectClass=User)(mail=*MyEmailDomain.com)(memberof:1.2.840.113556.1.4.1941:=(CN=GroupA,OU=MyOU3,OU=MyOU2,OU=MyOU1,DC=MyDomain,DC=LOCAL)))
If it matters, I'm using Active Directory Explorer to get the Distinguished Names, and the LDAP Input step in Pentaho's Data Integration tool (Kettle/PDI) to retrieve the data.
A:
I love the fact that I always find the answer to my questions as soon as I post them somewhere. I need to learn to post much earlier and maybe I will spend less time searching :)
Found a random stackoverflow post that indicated there's an error in the msdn article for this and it has too many parenthesis.
This won't work:
(&(objectCategory=Person)(objectClass=User)(mail=*MyEmailDomain.com)(memberof:1.2.840.113556.1.4.1941:=(CN=GroupA,OU=MyOU3,OU=MyOU2,OU=MyOU1,DC=MyDomain,DC=LOCAL)))
But this DOES work:
(&(objectCategory=Person)(objectClass=User)(mail=*MyEmailDomain.com)(memberof:1.2.840.113556.1.4.1941:=CN=GroupA,OU=MyOU3,OU=MyOU2,OU=MyOU1,DC=MyDomain,DC=LOCAL))
(no parenthesis around the Distinguished Name)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
error: expected unqualified-id before '<' token|
I'm getting the following errors:
preprocessor_directives.cpp|15|error: expected unqualified-id before '<' token|
preprocessor_directives.cpp|26|error: expected `;' before "int"|
||=== Build finished: 2 errors, 0 warnings ===|
#include <iostream>
using namespace std;
// Avoid. Using #define for constants
#define MY_CONST1 1000
// Use. Equivalent constant definition
const int MY_CONST2 = 2000;
// Avoid. Using #define for function like macros
#define SQR1(x) (x*x)
// Use. Equivalent function definition
inline template <typename T>
T SQR2 ( T a ) {
return a*a;
}
// Writing #define in multiple lines
#define MAX(a,b) \
((a) > (b) ? (a) : (b))
// Compile time flags
#define DEBUG
int main()
{
cout << "SQR1 = " << SQR1(10) << endl;
cout << "SQR2 = " << SQR2(10) << endl;
cout << "MAX = " << MAX(10,11) << endl;
cout << "MY_CONST1 = " << MY_CONST1 << endl;
cout << "MY_CONST2 = " << MY_CONST2 << endl;
return 0;
}
A:
Move the inline keyword after the template keyword.
template <typename T> inline
T SQR2 ( T a ) {
return a*a;
}
A:
template <typename T>
inline T SQR2 ( T a ) {
return a*a;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Difference between two times follow up (Convert to decimal)
I asked a question like this earlier and got a great answer but I made a mistake and wanted the output to be a decimal rather than a time. So here's the question.
I have two textboxes that allow a user to enter a start time and an end time in this format (h:mm). I want it to return the difference in a label. For example, if a user enters 1:35 in the first textbox and 3:30 in the second textbox and press the 'Calculate' button, it will return the decimal 1.92.
Any ideas or resources for this? I only want to calculate decimal difference of the time entered, date and seconds doesn't matter at all. Below is the code for getting an output in the format of (h:mm).
TimeSpan ts1 = TimeSpan.Parse(textBox1.Text); //"1:35"
TimeSpan ts2 = TimeSpan.Parse(textBox2.Text); //"3:30"
label.Text = (ts2 - ts1).ToString(); //"1:55:00"
A:
It sounds like you want the total number of hours, in that 1.92 hours is 115 minutes (ish).
In that case you want:
double hours = (ts2 - ts1).TotalHours;
... you can then format that how you wish (e.g. to 2 decimal places).
For example:
TimeSpan ts1 = TimeSpan.Parse("1:35");
TimeSpan ts2 = TimeSpan.Parse("3:30");
double hours = (ts2 - ts1).TotalHours;
Console.WriteLine(hours.ToString("f2")); // Prints 1.92
Of course I'd personally use Noda Time and parse the strings as LocalTime values instead of TimeSpan values, given that that's what they're meant to be (times of day), but that's a minor quibble ;)
A:
(ts2 - ts1).TotalHours.ToString();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
.gitignore from parentmodule does not apply to submodules?
SO advises against deleting answered question so I will leave this here but please see John's answer which explains that the explanation is already present in the text a quoted.
According to the manpage it seems git commands would go up the directory hierarchy up to the root directory:
Patterns read from a .gitignore file in the same directory as the
path, or in any parent directory, with patterns in the higher level
files (up to the toplevel of the work tree) being overridden by those
in lower level files down to the directory containing the file.
Our project has many git submodules and I was hoping to be able to use a single .gitignore in the parentmodules that can apply to all of them.
But that doesn't seem to work. Does the search for .gitignore stop at the repository root? I am hoping I am making a mistake.
$ git --version
git version 1.8.5.5
$ grep target ../.gitignore # the .gitignore in the parent module
target
**/target/
$ git status --porcelain # feature/target/ matches **/target but is not ignored
?? feature/target/
?? update-site/target/
$ echo '**/target/' >> .gitignore # add it to submodule repo root
$ git status --porcelain
M .gitignore
A:
The search for a .gitignore does stop at the repository root. The docs you posted say as much themselves ("up to the top level of the work tree"). This doesn't work any differently for submodules as for any other repositories.
If you want the same ignore rules across the repositories, you need to either check the same .gitignore into each repo, or use global ignore rules (but of course those would be specific to your local machine; you can't check them in).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to create 3 processes with fork that are running async
I have a problem,
I need to write a small c program that prints out a random numbers given by three processes that are printing only one number by themselfes 20 times.
output should be something like 0122102021012021120... and something finishing from the parent process.
I only get outputs like:
00000000000000000000ready11111111111111111111readyready22222222222222222222readyreadyready
and I don't know what to do - it seems that I didn't understand the ground logic behind that fork() system ;)
my code is:
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4
5 void printfXtimes(int a, int b){
6 int i;
7 for(i=0;i<b;i++){
8 printf("%i",a);
9 sleep(1);
10 }
11 }
12
13 void main(){
14 for(int kid = 0; kid < 3; ++kid) {
15 int pid = fork();
16 if(pid < 0){
17 exit(EXIT_FAILURE);
18 }else if (pid > 0){
19 /* Parent process */
20 printf("ready");
21 }else{
22 /* Child process */
23 printfXtimes(kid,20);
24 exit(EXIT_SUCCESS);
25 }
26 for (int kid = 0; kid < 3; ++kid) {
27 int status;
28 pid_t pid = wait(&status);
29 }
30
31 }
32 }
whats wrong here? :/
The task is considered "easy"... I don't get it...
A:
Moderately workable code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
static void printfXtimes(int a, int b)
{
for (int i = 0; i < b; i++)
{
printf("%i\n", a);
usleep(10000);
//sleep(1);
}
}
int main(void)
{
for (int kid = 0; kid < 3; ++kid)
{
int pid = fork();
if (pid < 0)
{
exit(EXIT_FAILURE);
}
else if (pid > 0)
{
/* Parent process */
printf("PID %d ready\n", pid);
}
else
{
/* Child process */
printfXtimes(kid, 10);
exit(EXIT_SUCCESS);
}
}
for (int kid = 0; kid < 3; ++kid)
{
int status;
int corpse = wait(&status);
printf("PID %d exited 0x%.4X\n", corpse, status);
}
}
Notes:
When using fork(), the correct return type for main() is int, not void. You can use void main() on Windows; everywhere else, it is wrong (almost everywhere else — specific systems could document it as OK, like Windows does). See What should main() return in C and C++?
One problem is that after you launch each child, you wait for three children to die. That loop should be after the launch loop. Otherwise, you're forcing sequential processing, not asynchronous processing.
Another problem is that you don't use newlines at the ends of messages; this causes confusion too (see printf() anomaly after fork()).
Example output (no piping):
PID 34795 ready
PID 34796 ready
0
1
2
PID 34797 ready
0
1
2
0
1
2
0
1
2
0
1
2
0
1
2
1
2
0
1
0
2
1
0
2
1
2
0
PID 34795 exited 0x0000
PID 34797 exited 0x0000
PID 34796 exited 0x0000
Example output (piped to sed):
0
0
0
0
0
0
0
0
0
0
PID 34789 ready
1
1
1
1
1
1
1
1
1
1
PID 34789 ready
PID 34790 ready
2
2
2
2
2
2
2
2
2
2
PID 34789 ready
PID 34790 ready
PID 34791 ready
PID 34789 exited 0x0000
PID 34791 exited 0x0000
PID 34790 exited 0x0000
If you've read and understood the "printf() anomaly after fork()" question, you should understand about line buffering and full buffering, and the output via sed should be explicable (in particular, why there are extra copies of the PID nnnnn ready messages).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to get jquery response when form is submited using submit button
I am sending state,city,zip code to ajax.php file. using jquery.
I am unable to get those values in response
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Jquery Ajax</title>
</head>
<body>
<!------------------------Jquery-------POST DATA----------------------------------------->
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
-->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#id-submit').click(function() {
var reg_state = $('#reg_state').val();
var reg_city = $('#reg_city').val();
var reg_zip = $('#reg_zip').val();
var dataString = 'reg_state='+ reg_state;
//alert(dataString);
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data)
{
//$("#state").html(data);
alert(data);
}
});
});
});
</script>
<!------------------------Jquery-----------POST DATA END------------------------------------->
<form id="registration_form" action="" method="post">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="submit" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
</body>
</html>
This is the ajax.php file , from where i need to send response, and make it visible in div id="state
<?php
if($_POST['reg_state'])
{
echo $_POST['reg_state'];
}
else{
echo 'nothing';
}
?>
A:
When ever we use input['type']="submit" in form
we have to use
$('#id-submit').click(function(e) {
e.preventDefault();
}
Here is the full working code
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Jquery Ajax</title>
</head>
<body>
<!------------------------Jquery-------POST DATA----------------------------------------->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#id-submit').click(function(e) {
e.preventDefault();
var reg_state = $('#reg_state').val();
var reg_city = $('#reg_city').val();
var reg_zip = $('#reg_zip').val();
var dataString = { reg_state: reg_state, reg_city: reg_city, reg_zip : reg_zip }
//alert(dataString);
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(data)
{
$("#state").html(data);
// alert('hi');
}
});
});
});
</script>
<!------------------------Jquery-----------POST DATA END------------------------------------->
<form id="registration_form" action="" method="post">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="Response" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
</body>
</html>
ajax_city.php
<?php
if($_POST['reg_state'])
{
echo 'STATE: '.$_POST['reg_state'].'<br/>';
echo 'CITY: '.$_POST['reg_city'].'<br/>';
echo 'ZIP: '.$_POST['reg_zip'].'<br/>';
}
else{
echo 'nothing to respond';
}
?>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find the value of the following $n \times n$ determinantes
Find the value of the following $n \times n$ determinantes
$$\begin{vmatrix}
a_1+x & x & x & \ldots & x \\
x & a_2+x & x & \ldots & x \\
x & x & a_3+x & \ldots & x \\
\vdots & \vdots& &\ddots& \vdots\\
x & x & x & \ldots & a_n+x \\
\end{vmatrix}$$
$$\begin{vmatrix}
a_1+x & a_2 & a_3 & \ldots & a_n \\
a_1 & a_2+x & a_3 & \ldots & a_n \\
a_1 & a_2 & a_3+x & \ldots & a_n \\
\vdots & \vdots& &\ddots& \vdots\\
a_1 & a_2 & a_3 & \ldots & a_n+x \\
\end{vmatrix}$$
Both seem to be equally complicated to solve, I reckon that it's needed to subtract the $x$ from the diagonal in each term. I tried by subtracting the $(k-1)$-th row from the $k$-th row, however that doesn't really lead me to anything more comfortable whatsoever. So help is greatly appreciated, also perhaps a link to some methods on solving these kind of problems, would also be helpful.
A:
For 2) Let $$A=\begin{bmatrix} a_1 & a_2 & .. &a_n \\
a_1 & a_2 & .. &a_n \\
a_1 & a_2 & .. &a_n \\
...&...&...&...\\
a_1 & a_2 & .. &a_n \\
\end{bmatrix}$$
Then $A$ has rank $1$ and hence $\lambda=0$ is an eigenvalue with geometric multiplicity $n-1$, and hence has algebraic multiplicity at least $n-1$.
As the trace is the sum of eigenvalues, the last eigenvalue is $a_1+a_2+..+a_n$.
Thus
$$
\det(\lambda I-A) =\lambda^n -(a_1+...+a_n) \lambda^{n-1}
$$
Now replace $\lambda$ by $-x$.
For 1) Subtract the last row from each of the previous $n-1$. You get
$$\begin{vmatrix}
a_1+x & x & x & \ldots & x \\
x & a_2+x & x & \ldots & x \\
x & x & a_3+x & \ldots & x \\
\vdots & \vdots& &\ddots& \vdots\\
x & x & x & \ldots & a_n+x \\
\end{vmatrix}=\begin{vmatrix}
a_1 & 0 & 0 & \ldots & -a_n \\
0 & a_2 & 0 & \ldots & -a_n \\
0 & 0 & a_3 & \ldots & -a_n \\
\vdots & \vdots& &\ddots& \vdots\\
x & x & x & \ldots & a_n+x \\
\end{vmatrix}$$
This determinant is a linear function in $x$. Therefore
$$\begin{vmatrix}
a_1+x & x & x & \ldots & x \\
x & a_2+x & x & \ldots & x \\
x & x & a_3+x & \ldots & x \\
\vdots & \vdots& &\ddots& \vdots\\
x & x & x & \ldots & a_n+x \\
\end{vmatrix}=ax+b$$
Now when $x=0$ we get
$$b=a_1 ... a_n$$
All you have to do next is do row expansion by the last row in
$$\begin{vmatrix}
a_1 & 0 & 0 & \ldots & -a_n \\
0 & a_2 & 0 & \ldots & -a_n \\
0 & 0 & a_3 & \ldots & -a_n \\
\vdots & \vdots& &\ddots& \vdots\\
x & x & x & \ldots & a_n+x \\
\end{vmatrix}$$
in order to find the coefficient of $x$.
For 2), without eigenvalues: Transpose the matrix, and then add all rows to the first. We get:
$$\begin{vmatrix}
a_1+x & a_2 & a_3 & \ldots & a_n \\
a_1 & a_2+x & a_3 & \ldots & a_n \\
a_1 & a_2 & a_3+x & \ldots & a_n \\
\vdots & \vdots& &\ddots& \vdots\\
a_1 & a_2 & a_3 & \ldots & a_n+x \\
\end{vmatrix}=\begin{vmatrix}
a_1+x & a_1 & a_1 & \ldots & a_1 \\
a_2 & a_2+x & a_2 & \ldots & a_2 \\
a_3 & a_3 & a_3+x & \ldots & a_3 \\
\vdots & \vdots& &\ddots& \vdots\\
a_n & a_n & a_n & \ldots & a_n+x \\
\end{vmatrix}=\begin{vmatrix}
a_1+a_2+..+a_n+x & a_1+a_2+..+a_n+x & a_1+a_2+..+a_n+x & \ldots &a_1+a_2+..+a_n+x\\
a_2 & a_2+x & a_2 & \ldots & a_2 \\
a_3 & a_3 & a_3+x & \ldots & a_3 \\
\vdots & \vdots& &\ddots& \vdots\\
a_n & a_n & a_n & \ldots & a_n+x \\
\end{vmatrix}=(a_1+a_2+..+a_n+x)\begin{vmatrix}
1 & 1 & 1 & \ldots &1\\
a_2 & a_2+x & a_2 & \ldots & a_2 \\
a_3 & a_3 & a_3+x & \ldots & a_3 \\
\vdots & \vdots& &\ddots& \vdots\\
a_n & a_n & a_n & \ldots & a_n+x \\
\end{vmatrix}$$
Now if you do each row minus $a_i$ row one you get
$$=(a_1+a_2+..+a_n+x)\begin{vmatrix}
1 & 1 & 1 & \ldots &1\\
0 & x & 0 & \ldots & 0 \\
0 & 0 & x & \ldots & 0 \\
\vdots & \vdots& &\ddots& \vdots\\
0& 0 & 0 & \ldots & x \\
\end{vmatrix}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Converting between GPT and MBR hard drive without losing data
NOTE: I don't know a lot about hard drives so you're going to have to work with me here.
My question: Can I change my hard drive from GPT to MBR without losing data on it?
NOTE: there isn't an operating system on the laptop which I'm going to do this on. I'm going to boot from a USB and try to convert it.
A:
You can convert from GPT to MBR and MBR to GPT without data loss (I have tried that) with gdisk in Linux.
Use at your own risk
Run command gdisk /dev/sdx with sdx as per your HDD partition
GPT fdisk (gdisk) version 1.0.1
Partition table scan:
MBR: MBR only
BSD: not present
APM: not present
GPT: not present
***************************************************************
Found invalid GPT and valid MBR; converting MBR to GPT format.
THIS OPERATION IS POTENTIALLY DESTRUCTIVE! Exit by typing 'q' if
you don't want to convert your MBR partitions to GPT format!
***************************************************************
Command (? for help):
MBR to GPT
Enter w to write GPT partition on disk.
Press y to confirm your choice.
GPT to MBR
Enter r to enter in recovery and transformation options.
Enter g to convert GPT to MBR partition.
For Information
You can check table by command p.
Warning: You will lose your boot loader (Ex. GRUB)
You can check if your partition is GPT or MBR now gdisk /dev/sdx with sdx as per your HDD partition in Partition table scan(p)
A:
Making your drive bootable
This is an enhancement to the information provided by Krunal and clarkttfu with more details on the steps to create a BIOS boot partition and install grub to it.
If you are changing the partition table on a a boot drive you will need to create a new "BIOS boot partition" for grub to store the bootloader in. These examples use the drive /dev/sda which will usually be the boot drive.
First, validate that there is space before the current first partition to support a boot partition, fisk -l should show that the first partition starts at sector 2048:
johnf@ubuntu:~$ sudo fdisk -l /dev/sda
[...]
Device Boot Start End Sectors Size Id Type
/dev/sda1 * 2048 499711 497664 243M 83 Linux
/dev/sda2 501758 125829119 125327362 59.8G 5 Extended
/dev/sda5 501760 125829119 125327360 59.8G 8e Linux LVM
If it does then you have the space required to create the partition. If it doesn't you cannot follow these instructions and have a bootable system.
Use gdisk to convert the partition to gpt, you can now create a new partition for your MBR, run sudo gdisk /dev/sd, enter n to create a new partition, accept the proposed partition number, you should be able to select a first sector of 34, set the partition type of ef02:
Command (? for help): n
Partition number (2-128, default 2):
First sector (34-4294967262, default = 4294922240) or {+-}size{KMGTP}: 34
Last sector (34-2047, default = 2047) or {+-}size{KMGTP}:
Current type is 'Linux filesystem'
Hex code or GUID (L to show codes, Enter = 8300): ef02
Changed type of partition to 'BIOS boot partition'
You can now write your partition table with w. Run partprobe again and then install grub:
johnf@ubuntu:~$ sudo partprobe
johnf@ubuntu:~$ sudo grub-install /dev/sda
Installing for i386-pc platform.
Installation finished. No error reported.
You should now be able to reboot your machine without issue.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fubini's Theorem Application
My problem:
I've been given the double integral:
$$\int_{0}^{+\infty}\int_{0}^{+\infty}\sin(bx)y^{p-1}e^{-xy}dxdy, \quad 0<p<2,b\in \mathbb{R}$$
I need to prove that the value of the integral is independent of the order of integration (i.e. I can either integrate first with respect to $x$ and then with respect to $y$ or first with respect to $y$ and then $x$).
My attempt to a solution:
According to Fubini’s Theorem (https://en.wikipedia.org/wiki/Fubini%27s_theorem#Tonelli.27s_theorem) a double integral may be evaluated as an iterated integral if $f(x,y)$ is integrable on the domain of integration, that is, if the following conditions are met:
$f(x,y)$ is measurable.
However, the function is not defined on $y=0$, so it’s not continuous on $[0, +\infty)\times[0,+\infty)$. It still is measurable?
$\int|f(x,y)|d(x,y)<+\infty$. I am not sure how to check this condition.
I know that $|f(x,y)|$ is a non-negative function, so I can evaluate the double integral as an iterated integral (by Tonelli's theorem for non-negative functions):
$$\int_{[0, +\infty)\times[0,+\infty)}|f(x,y)|d(x,y)=\int_0^{+\infty}\int_0^{+\infty}|f(x,y)|dxdy$$
If I integrate first with respect to $y$ and then with respect to $x$ I get the following:
$$\int_0^{+\infty}\bigg(\int_0^{+\infty}|\sin(bx)y^{p-1}e^{-xy}|dy\bigg)dx=\\\int_0^{+\infty}|\sin(bx)|\bigg(\int_0^{+\infty}y^{p-1}e^{-xy}dy\bigg)dx=\\\int_0^{+\infty}|\sin(bx)|\bigg(\frac{\Gamma(p)}{x^{p}}\bigg)dx=\Gamma(p)\int_0^{+\infty}\frac{|\sin(bx)|}{x^{p}}dx
$$
I know that $\Gamma(p)<+\infty$ for $0<p<1$, but what about $\int_0^{+\infty}\frac{|\sin(bx)|}{x^{p}}dx$?$\int_0^{+\infty}\frac{|\sin(bx)|}{x^{p}}dx\leq\int_0^{+\infty}\frac{1}{x^{p}}dx$ doesn’t help me considering that the second integral does not converge...
By integrating first with respect to $x$ and then with respect $y$ doesn’t seem to help either.
I really apologize if this is a banal question, but I am quite new to this topic.
Thanks!
A:
Quick answer:
1. Yes, you could work on $(0,\infty)^2$ or add the value infinity to your function.
From $\int_0^{+\infty}\frac{|\sin(bx)|}{x^{p}}dx$
you can check using l'Hopital the behaviour of $F(x):=\frac{|\sin(bx)|}{x^{p}}$ at $0$, ($F$ should be integrable at $0$ for every $p\in(0,2)$). Then deal with integrability at $\infty$ (which is easy for $p>1$).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Catalog Page - Replace Filter Dropdown by Simple Links
I wish to replace the drop-down (position, name, price) on the catalog page by simple links.
www\app\design\frontend\base\default\template\catalog\product\list\toolbar.html
A:
Just change
from
<div class="sort-by">
<label><?php echo $this->__('Sort By') ?></label>
<select onchange="setLocation(this.value)">
<?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
<option value="<?php echo $this->getOrderUrl($_key, 'asc') ?>"<?php if($this->isOrderCurrent($_key)): ?> selected="selected"<?php endif; ?>>
<?php echo $this->__($_order) ?>
</option>
<?php endforeach; ?>
</select>
<?php if($this->getCurrentDirection() == 'desc'): ?>
<a href="<?php echo $this->getOrderUrl(null, 'asc') ?>" title="<?php echo $this->__('Set Ascending Direction') ?>"><img src="<?php echo $this->getSkinUrl('images/i_desc_arrow.gif') ?>" alt="<?php echo $this->__('Set Ascending Direction') ?>" class="v-middle" /></a>
<?php else: ?>
<a href="<?php echo $this->getOrderUrl(null, 'desc') ?>" title="<?php echo $this->__('Set Descending Direction') ?>"><img src="<?php echo $this->getSkinUrl('images/i_asc_arrow.gif') ?>" alt="<?php echo $this->__('Set Descending Direction') ?>" class="v-middle" /></a>
<?php endif; ?>
</div>
to
<div class="sort-by">
<label><?php echo $this->__('Sort By') ?></label>
<?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
<a href="<?php echo $this->getOrderUrl($_key, 'asc') ?>" > <?php echo $this->__($_order) ?> ASC</a>
<a href="<?php echo $this->getOrderUrl($_key, 'desc') ?>" > <?php echo $this->__($_order) ?>DESC</a>
<?php endforeach; ?>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compiling Programs with arm-none-eabi
first timer here, just wanna ask what happens if you compile something designed for a specific board like say raspberry pi but instead of using those compiler targets you use arm-none-eabi? Will it break the software or what?
A:
If your intent is to build a user space program that will execute on a Raspberry Pi running Linux, then arm-none-eabi is not the right toolchain to use because it has no libc (and it lacks other libs as well). You will not be able to build your application.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Access variables in self.method in ruby script
I am very new to ruby. I am facing issue in getting the variable value in self.method
My ruby class/script look like this:
class A1
def initialize
@myUtil = MyUtil.new log
@test_hash = @myUtil.loadPropertiesFile(File.dirname(__FILE__) + '/my-tests.properties')
end
def self.testCases
tests = {}
@test_hash.each do |k, v|
puts "#{k}"
end
tests
end
def launch test, testbed, h = {}
@test_hash.each do |k, v|
puts "#{k}"
end
end
end
I am able to print value in @test_hash in launch method but not in self.testCases. Where I am making the mistake?
A:
I see a few errors in your code.
In your initialize method, you created a global variable $test_hash, anytime you put a $ in front of a variable, it becomes available everything. That is not something you want to do in this case. An instance variable would work best for you in this case.
Your testCases method is a class method, which means you can call it without creating a new instance of the class, ie A1.new. So you call the method like A1.testCases (Ruby uses snake case for method names, test_cases, just fyi). You initializes the test_hash variable in the initialize method, which does not automatically gets call until you create a new instance of the class. Therefore, test_hash does not exist when you simply run 'A1.testCases`.
for the line puts "#{k}" is not good practice. puts stands for put string, and it will automatically convert the variable into a string. You should use puts k. the #{} is meant for string interpolation. Such as "Hi, my name is #{name}, and I am #{age} years old."
Here's how I would do this. I replaced the test_hash with a simple hash for testing purposes.
class A1
def initialize
@test_hash = {a: 1, b: 2, c: 3, d: 4, e: 5}
end
def testCases
@test_hash.each do |k, v|
puts k
end
end
end
Now, you create a new instance of A1 and call the testCases method (now an instance method, instead of a class method)
A1.new.testCases
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can the spam flag description be reworded?
For flag > spam, the description is as follows:
This answer is effectively an advertisement with no disclosure. It is not useful or relevant, but promotional.
This is good for a post such as this...
Buy the jQuery basic arithmetic plugin NOW for $19.99!!!!!!!!!11
...which is obviously said advertisement. But what about this...
Me love lorem ipsum. lorem ipsum! lorem ipsum!
...which is also spam, but not a "promotional" "advertisement." I generally flag these as spam and they are handled appropriately. Which leads me to my question:
Should either...
The description of spam gets changed to follow the dictionary definition? For example,
This answer is effectively an advertisement with no disclosure, or it is otherwise neither useful nor relevant.
Use a different flag reason? (Offensive/abusive? Not an answer? Very low quality?)
A:
You should be using the offensive/abusive flag for these kinds of posts, Shog said so:
If someone is abusing the site by posting gibberish, flag it as such. Any combination of 6 spam or offensive flags will delete and lock the post along with imposing various penalties and restrictions.
I do agree that this could be improved by adding something explicitly saying that gibberish should be flagged with that reason:
(we'd probably need to find something more universally recognizable than 'gibberish', but you get the point)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Format a datetime string to time only
I'm retrieving a datetime from a SQLite DB which comes out in the format...
2011-01-24 02:45:00
In C# I can simply use DateTime.Parse("2011-01-24 02:45:00").ToString("HH:mm") in order to get the string 02:45
Is their a way I can I do this in Android/Java? My code in my Android app looks like this...
// dateStr below is logging as correctly being yyyy-MM-dd HH:mm:ss format
String dateStr = cursor.getString(cursor.getColumnIndex("start_time"));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String shortTimeStr = sdf.format(dateStr); // <-- throws IllegalArgumentException
EDIT: Thanks to both doc_180 and Konstantin Burov - the examples given have helped me sort out the problem. Part of the issue was that I was importing java.sql.Date instead of java.util.Date. I've changed things around and it's working perfectly for me now.
A:
You need to do the following.
try {
Date date = null;
date = df.parse("2011-01-24 02:45:00");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String shortTimeStr = sdf.format(date);
System.out.println(shortTimeStr);
} catch (ParseException e) {
// To change body of catch statement use File | Settings | File Templates.
e.printStackTrace();
}
As I mentioned in comment, you should store the time as milliseconds instead of string. Otherwise, I do not see any other way than creating a middleman object Date.
A:
SimpleDateFormat.format expects Date or Calendar as argument while you're passing a String. Convert the String into Date first.
String dateStr = cursor.getString(cursor.getColumnIndex("start_time"));
SimpleDateFormat toFullDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fullDate = toFullDate.parse(dateStr);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String shortTimeStr = sdf.format(fullDate);
And yeah, I'd rather stored date as long in the database, so getting a Date object then would be more trivial:
Long dateMilliseconds = cursor.getLong(cursor.getColumnIndex("start_time"));
Date fullDate = new Date(dateMilliseconds);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are the various components of Visual Studio Team System each designed for?
What are the various components of Visual Studio Team System each designed for?
Our company was recently accepted to Microsoft BizSpark and now I have a blizzard of options to choose from. Right now I'm just needing version control and a coding environment but I'm not sure what distinguishes each of the available downloads.
A:
At long last, the official MS marketing site for VSTS seems to not suck. As the definitive source I'll link it up front: http://www.microsoft.com/visualstudio/en-us/products/teamsystem/default.mspx
Still, let's summarize the 60 second elevator pitch. You've got four "role SKUs" that are each a superset of VS Professional + some additional set of features. You've got Team Suite, which is a superset of everything (like "Ultimate" editions in Windows/Office). And you've got Team Foundation Server which glues everything together with source control, defect tracking, build automation, project management, and deep reporting.
Role SKUs:
Team Developer - profiler, static code analysis, code coverage tools
Team Database - a full offline DB development environment, including DB designers, unit test tools, etc. Lets you program declaratively and let the Schema Compare engine do the dirty work. Hard to explain in a sentence -- go watch the Channel9 videos.
Team Test - capture, tweak, and playback http requests as automated unit tests. Load & scale testing tools. Test list management.
Team Architecture - SOA modeling tools. They roundtrip through the code editors by generating stub projects and validating final code on the backend to ensure it fits the defined architecture.
Note - Team Dev and Team DB have merged from a licensing POV. Buy one, get the other free.
All Team Editions get you an MSDN Premium subscription and a client access license for Team Foundation Server. Team Suite, as mentioned, gets you the kitchen sink.
TFS itself is a separate purchase, not available for download. (except in the form of a 180-day trial, or the 5-user-limited "workgroup edition" that comes with most MSDN subs) The TFS client is a Visual Studio plugin you can install into any edition of VS higher than Express, although using it with a non-Team edition requires purchasing a CAL.
VSTS also has some auxiliary downloads like the Build Agent (for spreading your build automation across multiple machines) and the Load Test Runner (does what you'd expect). See the licensing whitepaper for complete details on them.
Anyway, if all you want to do is set up a version control system and start coding, it doesn't really matter. The only TFS editions you'll find for download have hard limits, so choose your poison. And they will plug into pretty much any edition of VS once you install the client plugin (dubbed "Team Explorer"). Actually installing the server is not trivial, but that's another show....
|
{
"pile_set_name": "StackExchange"
}
|
Q:
javascript $.post pass parameter to external PHP file
I have
enter code here
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser is too old to run me!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
document.getElementById("myTable").style.display = "block";
var x=document.getElementById("myTable");
for (var i = 0; i < data.length; i++) {
var row=x.insertRow(-1);
var cell1=row.insertCell(-1);
var cell2=row.insertCell(-1);
...
...
and in php
enter code here
<?php
session_start();
$username = "XXXXXXXX";
$password = "XXXXXXXX";
$database = "XXXXXXXX";
$link = mysql_connect("localhost", "$username", "$password");
if(!$link) {echo("Failed to establish connection to mysql server");
exit();}
$status = mysql_select_db($database);
$oId = mysql_real_escape_string($_POST["order_IDsearch"]);
if (isset($order_IDsearch)){
$result = mysql_query ("SELECT * FROM personal_info WHERE order_id= '".$oId."' ");
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo json_encode($myjsons);
}
?>
the javascript will show the table if i remove the SQL condition, matrk if and mark $_post
and it wont show the table if i leave the php as you see above,
whats wrong with the php page help please
here is the whole javascript ajax function,
enter code here
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser is too old to run me!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$.post('userfind.php', {orderId:"order_IDsearch"}, function(data) {
var obj = $("#myTable").show();
var x = obj.get(0);
for (var i = 0; i < data.length; i++) {
var row=x.insertRow(-1);
var cell1=row.insertCell(-1);
...
...
cell1.innerHTML = "<b><input name='edit' type='button' onClick='editRow(this)' value='Edit' /> <input name='del' type='button' onClick='delRow(this)' value='Del' /></b>";
cell2.innerHTML = data[i].user_id;
cell3.innerHTML = data[i].first_name ;
....
....
}},'json');}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
It's so confusing me please help me to modify the code, should I write the code again? can this code be modified?
A:
You are not passing anything to your php file from $.post...
make it like
$.post('userfind.php', {order_IDsearch: "your data"}, function(data){
// your implementation
});
This should work...
If your order_IDsearch is dynamic then have it done like this
$.post('userfind.php', {yourData:order_IDsearch}, function(data){
// your implementation
});
And on PHP side you will have to access it in
$_POST['yourData'];
To send multiple values
$.post('userfind.php', {key1:value1,key2:value2,...}, function(data){
// your implementation
});
A:
Aditya Parab really answered your question, but I must interject some jQuery basics you need to understand.
You can (and should) simplify your function DRASTICALLY. All of that ajaxRequest stuff, the first 20 lines or so of the code, is for use when you are NOT using jQuery Ajax. That stuff is built into jQuery and you don't have to do it.
Also, in jQuery, you can get an object by its ID by stating var object = $('#objectId').get(0). You do not need document.getElementsById().
Simplified Function
function ajaxFunction(){
$.post('userfind.php', {var1: "value 1"}, function(data) {
var obj = $("#myTable").show();
var x = obj.get(0); //Get the JS object from the jQuery Object
for (var i = 0; i < data.length; i++) {
var row=x.insertRow(-1);
var cell1=row.insertCell(-1);
var cell2=row.insertCell(-1);
}
...
...
});
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP database connection inside if statement
I am trying to connect to a database if a condition inside an if statement is met:
if ($check == 1){
require_once('Connections/connect.php');
mysql_select_db($database_lg, $lg);
$query = "SELECT token FROM tbltokens WHERE name = '$name'";
$result = mysql_query($query, $lg) or die(mysql_error());
}
It works just fine if I put this same code outside the if statement. As soon as I wrap it in the if statement I get the error: "Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in..." The error applies to lines 2 and 4 in the code.
Notes:
I found a similar question where the solution was to require the database connection inside the if statement, which I have done.
I realize that mysql_* functions are deprecated. The are tons of mysql_* functions on this site which I have to live with for a while longer.
Thank you in advance.
Edit:
connect.php mentioned in the code above looks like this:
$hostname_lg = "xxx";
$database_lg = "xxx";
$username_lg = "xxx";
$password_lg = "xxx";
$lg = mysql_pconnect($hostname_lg, $username_lg, $password_lg)
or trigger_error(mysql_error(),E_USER_ERROR);
This may not be very relevant though as the connection succeeds when the if statement isn't there. It only fails when inside an if statement as in the example.
A:
Is your if statement inside a function? Each function has its own scope in php. The error you're receiving is making it seem as the parameters you pass in, $database_lg, $lg are not defined, meaning they're probably out of scope. You should make sure the variables $database_lg, $lg are visible by calling global:
if ($check == 1){
global $database_lg;
global $lg;
...
}
Also, put require_once at the top of your code(not in the if statement).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why was Hamilton's idea of women and children working in factories so controversial?
I've been reading through Hamilton's Report on Manufactures recently, and he suggests that women and children work in factories to help ease the labor competition between the North and South. However, this was highly controversial and people hated it. However, it was normal in Great Britain and it wasn't quite as contested. Why was Hamilton's idea so controversial and not Great Britain's?
A:
I don't see how "people hated" the idea of women and children working in the manufactures. The criticism came mainly from Jefferson and Madison. And they of course these proponents of a weak federal government mainly opposed the idea of more subsidies. But it's true that the idea of giving these subsidies to places where women and children work along men, was especially preposterous.
Jefferson privately strongly preferred a society where women had different employments from men. You could say "segregated" in some sense. It was just his opinion though, and he didn't try to force on others by making it a law. A striking example of his views is his rant against men in Europe working as "shoemakers, tailors, upholsterers, staymakers, mantua makers, cooks, doorkeepers, [...]". Yes, he really considered it "a great derangment in the order of things". Source: Thomas Jefferson and American Nationhood p. 74
I imagine many people white men holding the same views at the time, especially in the agriculture. Agriculture traditionally has a strong separation of gender roles; the idea of man making a direct monetary profit of a woman's work seemed surely weird; the idea of woman actually keeping her wage for herself even weirder.
A:
The fear was that women and children working alongside men in the factories would "corrupt" them, by leading to "dating" before marriage, etc.
Here is an example of contemporary thought.
"The factory] operatives are well dressed, and we are told, well paid... This is the fair side of the picture . . . There is a dark side, moral as well as physical. Of the common operatives, few, if any, by their wages, acquire a competence . . . the great mass wear out their health, spirits, and morals, without becoming one whit better off than when they commenced labor...
What becomes of them then? Few of them ever marry; fewer still ever return to their native places with reputations unimpaired. “She has worked in a Factory,” is almost enough to damn to infamy the most worthy and virtuous girl. (emphasis added).
Orestes Brownson, The Laboring Classes: An Article from the Boston Quarterly Review, Boston: Benjamin H. Greene, 1840.
America is was a Puritanical society that was more concerned with such issues than England or European countries.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
php Eclipse console output
I'm trying to get php debug output to the console window in Eclipse but everything I have tried (echo, print) gets output to the web page. Any ideas?
Thanks
David.
A:
Are you trying to write a command line program in PHP that will be running outside of a web context (e.g. not using Apache, run as a script from the command line)? If so, you could try debugging as a "PHP Script" (see http://www.jansch.nl/2009/05/03/debugging-parameters-for-cli-apps-using-eclipse-pdt/). Either way you will probably want to setup something like xdebug for debugging: http://www.eclipse.org/pdt/articles/debugger/os-php-eclipse-pdt-debug-pdf.pdf
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to display a PIL image object in Django view?
Im using a library on github to generate a qrcode myself rather than using an api but I'm having a hard tme understanding how to render a PIL image object (which is the default image renderer).
So far I have this:
import qrcode
from qrcode.image.pure import PymagingImage
img = qrcode.make('Some data here', image_factory=PymagingImage)
but I'm stuck when it comes to displaying it as an image on my main page view.
Thanks in advance for any help :)
EDIT:
Also would really appreciate some clarification on the html syntax if possible:
<div class="row">
<div class="col-xs-12">
<img src="{% static "some.jpg" %}" alt="somename" class="img-responsive"/>
</div>
</div>
Thanks :)
A:
After generating QR-code you need to return it as image in response.
In one of my projects I use this library.
Here I have:
def generate_qr_code(data, size=10, border=0):
qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=size, border=border)
qr.add_data(data)
qr.make(fit=True)
return qr.make_image()
And the view:
@render_to()
def return_qr(request):
text = request.GET.get('text')
qr = generate_qr_code(text, 10, 2)
response = HttpResponse(mimetype="image/png")
qr.save(response, "PNG")
return response
Then you can pass your text to view, and image returns as result.
UPD:
I have an templatetag to show qr in my template.
@register.inclusion_tag('qrcode/qr_tag.html', takes_context=True)
def get_qrcode_image(context, text, size):
url = reverse('generate_qr')
return {'url': url, 'text': text, 'size': size}
And the template 'qrcode/qr_tag.html':
<img src="{{url}}?size={{size}}&text={{text}}" />
So in result you can include your QR-code in this way:
<div class="row">
<div class="col-xs-12">
{% get_qrcode_image 'some text to decode' 320 %}
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
QML: unexpected AnchorAnimation behavior
Consider the following QML code:
import QtQuick 2.0
Item{
id:window
anchors.fill:parent
transitions:Transition{AnchorAnimation{duration:500}}
Rectangle{
id:topBar
anchors{left:parent.left;right:parent.right;bottom:parent.top}
height:100
color:'red'
border.width:1
}
Rectangle{
id:bottomBar
anchors{left:parent.left;right:parent.right;top:parent.bottom}
height:100
color:'blue'
border.width:1
}
states:State{
name:'on'
AnchorChanges{target:topBar;anchors.top:parent.top;anchors.bottom:undefined}
AnchorChanges{target:bottomBar;anchors.bottom: parent.bottom;anchors.top:undefined}
}
Component.onCompleted:{window.state='on'}
}
It's fairly straightforward: on window creation, the topBar slides into view from the top, and the bottomBar from the bottom.
The topBar does exactly what it's supposed to, but the bottomBar doesn't: the animation happens at the top (overlapping the topBar), and appears at the bottom of the window when the animation is finished.
What's going on?
A:
At the time you start the animation, the window's height is 0:
Component.onCompleted: {
print(window.height)
window.state='on'
}
You could start the animation when the window's height is larger than zero:
onHeightChanged: if (height > 0) window.state = 'on'
It appears that afterSynchronizing() also works, and feels less hackish:
onAfterSynchronizing: window.state = 'on'
But I'm not sure if it's safe to assume that the window has a height by then.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use AngularJs NgIf in front end html?
In my case ( item.senses["0"].definition) , sometimes the json file dont have this data back. So i want to set Ngif on this part.Can anyone help me how should i write my code ? If this div has this json data, then show the data, else print null not something in the div.
<ion-header>
<ion-navbar color="primary" >
<ion-title>
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<div class="headword">{{ item.headword }}
</div>
<div class="ipa"> {{ item.pronunciations["0"].ipa }}
<ion-icon name="volume-up" class="sound">British</ion-icon>
<ion-icon name="volume-up" class="sound">American</ion-icon>
</div>
<ion-item>
<ion-row>
<p class="type"> [ {{ item.part_of_speech }} ]
</ion-row>
</ion-item>
<div padding>
<div class="Title">Definition : </div>
<div class="Content">{{item.senses["0"].definition}} </div>
<div class="Title">Example : </div>
<!-- <button ion-button clear class="sound" (click)="playExample()">
<ion-icon name="volume-up"></ion-icon></button> -->
<div class="Content">{{item.senses["0"].examples["0"].text}} </div>
</div>
</ion-content>
A:
You could do with,
<div ng-if="item.senses[0].definition" class="Content">{{item.senses["0"].definition}} </div>
<div ng-if="!item.senses[0].definition" class="Content"> Nothing </div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
general expression substitution in sympy
I have two univariate functions, f(x) and g(x), and I'd like to substitute g(x) = y to rewrite f(x) as some f2(y).
Here is a simple example that works:
In [240]: x = Symbol('x')
In [241]: y = Symbol('y')
In [242]: f = abs(x)**2 + 6*abs(x) + 5
In [243]: g = abs(x)
In [244]: f.subs({g: y})
Out[244]: y**2 + 6*y + 5
But now, if I try a slightly more complex example, it fails:
In [245]: h = abs(x) + 1
In [246]: f.subs({h: y})
Out[246]: Abs(x)**2 + 6*Abs(x) + 5
Is there a general approach that works for this problem?
A:
The expression abs(x)**2 + 6*abs(x) + 5 does not actually contain abs(x) + 1 anywhere, so there is nothing to substitute for.
One can imagine changing it to abs(x)**2 + 5*(abs(x) + 1) + abs(x), with the substitution result being abs(x)**2 + 5*y + abs(x). Or maybe changing it to abs(x)**2 + 6*(abs(x) + 1) - 1, with the result being abs(x)**2 + 6*y - 1. There are other choices too. What should the result be?
There is no general approach to this task because it's not a well-defined task to begin with.
In contrast, the substitution f.subs(abs(x), y-1) is a clear instruction to replace all occurrences of abs(x) in the expression tree with y-1. It returns 6*y + (y - 1)**2 - 1
Aside: in addition to subs SymPy has a method .replace which supports wildcards, but I don't expect it to help here. In my experience, it is overeager to replace:
>>> a = Wild('a')
>>> b = Wild('b')
>>> f.replace(a*(abs(x) + 1) + b, a*y + b)
5*y/(Abs(x) + 1) + 6*y*Abs(x*y)/(Abs(x) + 1)**2 + (Abs(x*y)/(Abs(x) + 1))**(2*y/(Abs(x) + 1))
Eliminate a variable
There is no "eliminate" in SymPy. One can attempt to emulate it with solve by introducing another variable, e.g.,
fn = Symbol('fn')
solve([Eq(fn, f), Eq(abs(x) + 1, y)], [fn, x])
which attempts to solve for "fn" and "x", and therefore the solution for "fn" is an expression without x. If this works
In fact, it does not work with abs(); solving for something that sits inside an absolute value is not implemented in SymPy. Here is a workaround.
fn, ax = symbols('fn ax')
solve([Eq(fn, f.subs(abs(x), ax)), Eq(ax + 1, y)], [fn, ax])
This outputs [(y*(y + 4), y - 1)] where the first term is what you want; a solution for fn.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to download GridView data after data binding?
In the past, I have populated GridView's with 'manually created' data sources in the code behind, by doing this in the Page Load:
DataTable myData = SomeMethod(); //Returns a DataTable
myGrid.DataSource = myData;
myGrid.DataBind();
and whenever I wanted to download the data to a CSV file, I'd just add the following to the button's Click event:
DataTable csvData = new DataTable();
csvData = (DataTable)myGrid.DataSource;
//CSV construction, reponse send to browser, etc.
This works because the GridView is already databound during Page Load, so the data is available when the Click event is reached.
But now I can't get it to work using a SqlDataSource control that I added in design time (HTML). This SqlDataSource is bound to a DropDown control with auto-postback, so that data is retrieved when the selection is changed.
I run the website, with data already displayed in the GridView (EnableViewState=false to force query at each page load), and click the button, only to get an exception caused by the fact that myGrid.DataSource is null.
My question (finally):
I've noticed that the click event occurs before GridView_OnDataBound, but even OnDataBound the datasource is null. How can I get the data from the rendered GridView to allow the donload? Or from where should I attempt to retrieve it?
A:
When using design time data sources, the DataSource property is not used. Instead the DataSourceID property is used, but all it contains is the name of the data source control. You will have to go back to your SQLDataSource to get the information you need for exporting.
DataView dv = (DataView)sqlDataSource.Select(DataSourceSelectArguments.Empty);
DataTable dt = dv.ToTable();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java scanner test for empty line
I'm using Scanner to read 3 lines of input, the first two are strings and the last one is int.
I'm having an issue when the first line is empty and I don't know how to get around it. I have to do this:
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
encrypt(operation,line,index);
But when the first line is empty I get an error message.
I tried the following to force a loop until I get a non empty next line but it does not work either:
while(sc.nextLine().isEmpty){
operation = sc.nextLine();}
Anybody has a hint please ?
A:
A loop should work, though you must actually call the isEmpty method and scan only once per iteration
String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());
You could also use sc.hasNextLine() to check if anything is there
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I find an integral of the form $\int$ cos(nx)
I came across this problem
$$I_n = \int_0^{2\pi} \frac {\cos(nx)}{1-\cos(x)}dx$$
I've seen methods to solve integrals of the form $\int\cos^n(x)$ etc., but not of this form. What is the basic transformation to be done to start solving it?
A:
Concerning the definite integral $$I_n = \int_0^{2\pi} \frac {\cos(nx)}{1-\cos(x)}dx$$ there is major issue at the bounds.
To show it, consider Taylor series around $x=0$ $$\frac {\cos(nx)}{1-\cos(x)}=\frac{2}{x^2}+\left(\frac{1}{6}-n^2\right)+\frac{1}{120} \left(10 n^4-10 n^2+1\right)
x^2+O\left(x^4\right)$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Do secure phone lines exist?
I could be out of context here about security, but , I would like to know if phone lines or phone calls over VOIP could be made secure .
I know that Skype and other VOIP service providers have to give access to respective governments of countries who request authorization of phone calls from their country .
The normal phone lines themselves are unsecure.
I am talking from a perspective of a kid(in terms of security) who watches movies and thinks what does it mean and how do they do it ? I would really like to know the secret that if its actually possible.
"The phone line at our end is secure , is your connection secure ?"
"Are we on a secure phone line ?"
A:
A secure phone line is conceptually possible; this is not really different from, e.g., a secure communication between a Web browser and a HTTPS server (there are technical subtleties about lost packets and whether they should be tolerated, but that is not the issue here). However, the movie-secure phone is not secure, and that's a structural problem.
The problem lies in the question: "is your connection secure ?". If you need to ask to the other guy whether the line is secure, then the line is not secure. That's as simple as that. A "bad guy" could hijack the line and, when you ask whether the connection is secure, the bad guy could simply respond "yes it is !", counterfeiting the voice of the intended recipient (and, in the other direction, he could "replace" the question by an innocent sentence).
In a secure phone line, the caller and the receiver shall be authenticated to each other, which can be done with various cryptographic tools (e.g. digital signatures, or, more simply, a shared secret). Variants of the same tools also establish a session-specific shared secret which can be used to symmetrically encrypt the data. Bottom-line is that once people begin to actually talk, the line should already be secure and both participants shall have ways to know it (e.g. they are using special phones which refuse to communicate if security is not achieved). Otherwise, there is no security.
On a more practical point of view, if I were to implement a phone-like secure system between two entities, I would investigate using VoIP over a VPN. This would require some delving into the details of the VoIP protocol, so I would do that with an open protocol (i.e. Ekiga, not Skype).
A:
Or dedicated, isolated phone lines, such as the famous "red phone" between the US president's office and the USSR premier, back in the days of yore (Don't know if this is still around).
(or the batphone in Commisioner Gordon's office...)
A:
Yes they can be made secure by encrypting data or through mutual authentication of both parties.
for more information check http://en.wikipedia.org/wiki/Secure_telephone and http://www.helpturk.org/telephone-line-encryption.htm
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Set theoretic proof involving union and intersection identity
How to prove that $$A\cap(B\cup C)=(A\cap B)\cup C \implies C\subset A$$
without returning back to symbolic logic. I've tried expanding with the distributive identities but it's not very clear to me of how to proceed from that...
A:
Assume x in C. Then x in $(A\cap B)\cup C.$
Thus x in $A\cap(B\cup C)$, x in A.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
some questions regarding research plan for postdoc
I am going to apply for some postdoc positions which last more than one year. As usual, one of the main required documents is research plan. Having considered some good questions in academia.stackexchange such as Research plan without a specific goal?
, Research proposal for postdoc applications and Research Plan that works?, I have another question:
In the case of more than one year postdoc positions, how can I cover several years with one research plan? In other words, I am thinking on some different projects to conduct during these years. Can I mentioned in my research proposal (plan) all of them which are less related to each other? One of them is a kind of my research work in my Ph.D program and the others are further away from my thesis project. In fact, besides working on some aspects of my Ph.D thesis, I would like to work on other topics. As an example, let suppose I worked on pure math and for future I have some plans to work on some applied math. My reason is based on my interests on both of them. In addition, I think by conducting research on projects related to my thesis in first year of my postdoc , I will be able to obtain quick results to provide progress in my research work.
A:
You can cover several years with one research plan by putting the different projects on a fictive timeline.
You can mention multiple of them but they have to have a logical connection.
I don't have experience in mathematics (I did a PhD in Life Sciences), but one important point for postdoctoral application is to show that you can do research in an independent manner i.e. that you understand what topic of research is interesting/relevant, the hypothesis you develop regarding this topic, the approach you choose, and the key experiments which would lead to the results to answer your hypothesis.
An another point is that the research can be done during the timeline of the granted money, i.e. it is realistic and achievable. It is also hard at this stage because you might not know yet but you need to have an educated guess at it. That's why that in terms of number it is also up to you to decide if you should include all of them or not.
Regarding possible failure of the plans, try to include the ideas which are innovative and challenging enough but at the same time easy for you (because of your PhD experience) to do in realistic timeframe.
In your case, the hardest part of the grant proposal is to convince the reader that there is a logical approach between these different parts you want to study. If there are no connection at all then it will be difficult to do so and I would advise to not include all of them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP and proper way of using the strcmp function
I am working on the following snippet. What is the point of using !== 0 inside the first if condition while even the second condition is returning same result without using !== 0?
I was following some online tutorial and noticed that most developer are using the !== 0 but I accidentally noticed that I am also getting same result back , at least in this specific example without using !== 0
<?php
$name1 = "Geeks";
$name2 = "geeks";
if (strcmp($name1, $name2) !== 0) {
echo 'Strings are not equal';
}
else {
echo 'Strings are equal';
}
if (strcmp($name1, $name2)) {
echo 'Strings are not equal';
}
else {
echo 'Strings are equal';
}
?>
A:
The "===" and "!==" comparison operators assert two things:
The values are equal, and
The values are of the same type
The short answer to your question "what is the point of using !== with the strcmp function" is simply "it's good practice". That's really the only reason regarding strcmp specifically, and != would give you the exact same result when it comes to that function.
The long answer is as follows:
PHP is traditionally a loosely typed language. That is, datatypes were not all that important and PHP implicitly cast types for you automatically. It still does this by default (although lots of stuff has been added to improve the situation over recent years). For example, if you add the string "1" to the integer 1, PHP will cast the string to an integer automatically and return the integer value 2. Strongly typed languages would return an error if you tried to do that. Another example is that PHP will cast 0 to boolean false and any other non-zero value to boolean true.
It's that second example that causes problems with some of PHP's built-in functions. For example, the strpos() function. If you check the documentation page for strpos you'll see a big "Warning" in the "Return Values" section stating "This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE". For that reason it advises you to use the "===" operator to make sure you are getting the exact value and type that you expect. So "=== 0" means the string was found at the beginning of the input, and "=== false" means the string was not found. If you just used "== false" you won't be distinguishing between the string being found at the beginning of the input and the string not being found at all (because 0 will be implicitly cast to boolean false for the "if" statement).
So, developers got into the habit of testing for equality and type by using "===" and "!==". It's a good habit.
Since strcmp always return an integer, and you are always comparing it to an integer, there is no implicit casting and so comparing types as well as equality is not neccessary.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are Employers Obliged to let you Return to Work Early from Unpaid Leave?
I have been an employee at the company for over 5-year and I had requested time off work (4-months) to do sabbatical with some travelling. It was granted by my line manager. The request was made in person and then finalised in email.
However, fast-forward to now and due to the coronavirus pandemic, I have had to return home early from my travels, at great financial cost. As such, I am keen to start working again as soon as possible and can do so from home with ease. FYI, before leaving I was working from home once a week anyway!
I having had a call with my line manager, he says it won't be possible to return before the original return date, almost 2-months away. I am certain that in any normal situation (e.g. sans corona) they would be pleased to have me back early. After all, there was a reluctance to let me go in the first place. When I pressed him on why, I was told my pay wasn't in the budget for April and due to corona they were already down in their P&L.
However, the UK government is willing to reimburse companies pay 80% of people's wages if the coronavirus has stopped them from working, so this seems a weak reason.
Either way, this leaves me in a very strange situation: I am employee but I am not being payed.
Therefore my questions are as such:
Can my company legally stop me from returning to work, if it is not from something such as illness, etc? Alternatively, there is a mechanism in place that can allow me to return to work earlier?
If I am not allowed to return to work, what does this mean for my employment status? If I was unemployed I could claim certain benefits, however, I would consider myself employed so I feel rather in limbo right now!
Any advice on this would be REALLY appreciated.
TL;DR
I requested 4-months leave
I have asked to start again 2-months
early
I am being denied that
Do I have a right to start again early?/Are they obligated to allow me to return early?
Outcome
It seems that I am in a rather strange, but probably not entirely unique position, so I will detail some findings for those that might find them useful.
My employment status remains "Employed", as suggested in the answers. However, I wrongly assumed this excludes me from claiming Universal Credits. As I am not current earning I can still apply (in fact you can apply if you are earning, that just take this into accounts and give you less). Hopefully this is useful to someone else in my position.
A:
No, they are not obliged to take you back early
As you say in your TL;DR you arranged 4 months leave and your employer no doubt made arrangements to deal with your absence. Now, you want to return early; they are not obliged to allow you to do so just as you would not be obliged to do so if they wanted you to cut your leave short.
No doubt the current pandemic has changed the situation and in its absence, they might have been more willing to have you back early. But then, you wouldn't want to be coming back early.
Your employment status is that you are employed and on leave. Subject to the details of your employment contract; there is nothing stopping you taking another job - there is a huge demand for logistics workers particularly in the health sector at the moment; much of it unskilled work. dIf you want to be unemployed, you can always resign.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Disable formatting in ReSharper/Visual Studio
Is there a simple way to disable automatic formatting for a specific file in Visual Studio 2008 using ReSharper?
A:
AFAIK, there is no option to conditionally disable the Auto-Format by file type or specific file with ReSharper 4.5. The only option is to enable/disable for all files:
ReSharper > Options > Editor: Auto-format on semicolon/closing brace
A:
In ReSharper 7 (and few prior versions) you can specify generated files masks, those will not be formatted.
ReSharper->Options->Code Inspection->Generated Code->Generated file masks
For example if I have a file that contains reference data (as an array, for example), I call file for example States.data.cs and add *.data.cs to generated files masks list.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
parsing failed SyntaxError: Unexpected end of input
I am trying to retrieve the response from an API, but after using
fetch("url").then(res=>res.json()),
I am getting unexpected end of input error in my code at the following line:
res => res.json(),
Please find below code and help me locate exactly where am i going wrong:-
static fetchCurrentServices(){
return fetch("http://localhost:8080/portal-backend/services", {
mode: "no-cors",
method: "GET" ,
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
}
})
.then(
res => res.json()
).catch(function (ex) {
console.log('parsing failed', ex)
});
}
A:
Can you try below code i think you missed adding {} and added some more changes please look at it.
static fetchCurrentServices(){
return fetch("http://localhost:8080/portal-backend/services", {
mode: "no-cors",
method: "GET" ,
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
}
}).then(res =>{
return new Promise((resolve) => {
if (res) {
res.json().then(json => resolve(json)).catch(() => resolve(null))
} else {
resolve(null)
}
})
}).catch(function (ex) {
console.log('parsing failed', ex)
});
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gitlab runner failure, HTTP 500 curl 22
We had been having troubles with gitlab runner for couple of days now. Whenever we try to deploy a commit, we are getting the following error (it's the full log):
Running with gitlab-runner 10.8.0 (079aad9e) on LST GitLab Runner
9db4eb2c Using Docker executor with image alpine:3.7 ...
Pulling docker image alpine:3.7 ...
Using docker image
sha256:6d1ef012b5674ad8a127ecfa9b5e6f5178d171b90ee462846974177fd9bdd39f
for alpine:3.7 ...
Running on runner-9db4eb2c-project-2-concurrent-0
via a7dcae9d7882...
Fetching changes...
HEAD is now at 142ba7a
Merge
branch '3378-new-payroll-export-lexware' into test
error: RPC failed;
HTTP 500 curl 22
The requested URL returned error: 500 Internal Server Error
fatal: The remote end hung up unexpectedly
ERROR: Job failed:
exit code 1
It happens right after pulling docker image. We also tested it on different branches and different stages (we have test and deploy), all of them result with the same error.
Not sure if it's relevant, but we also cannot preform pull request from git repository. It fails with following error:
RPC failed; HTTP 500 curl 22 The requested URL returned error: 500
Internal Server Error
The remote end hung up unexpectedly
We tried switching to SSH instead of HTTP, but this also didn't work.
Could you please point us in right direction so we can solve it? What could be the problem here?
A:
The whole problem was connected to disk space. After logging in via SSH, we found out that docker container accumulated a huge log, that took all the space. We removed it and everything was fixed
I guess next step to avoid that problem in the future will be enabling docker to automaticly rotate the logs
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Repeating CSS background images without stretching
Is there a way create a tiled background using a repeating image without it stretching and changing size?
I have a pattern which I am using as a background. However I want this to display consistently throughout the site. Currently the pattern repeats correctly, but stretches depending on the size of the container.
A:
Just for reference to anyone else who might find themselves with this problem...
It was because I was using a SVG. Changed to a regular image file and now everything is fine.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I start a JVM with unlimited memory?
How do I start a JVM with no heap max memory restriction? So that it can take as much memory as it can ?
I searched if there is such an option, but I only seem to find the -Xmx and -Xms options.
EDIT:
Let's say I have a server with 4GB of RAM and it only runs my application. And, let's say I have another server with 32GB of RAM. I don't want to start my application with 4GB of memory limit because the second machine should be able to handle more objects
A:
-XX:MaxRAMFraction=1 will auto-configure the max heap size to 100% of your physical ram or the limits imposed by cgroups if UseCGroupMemoryLimitForHeap is set.
OpenJDK 10 will also support a percentage based option MaxRAMPercentage allowing more fine-grained selection JDK-8186248. This is important to leave some spare capacity for non-heap data structures to avoid swapping.
A:
You can't (or at least, I don't know a JVM implementation that supports it). The JVM needs to know at start up how much memory it can allocate, to ensure that it can reserve a contiguous range in virtual memory. This allows - among others - for simpler reasoning in memory management.
If virtual memory would be expanded at runtime, this could lead to fragmented virtual memory ranges, making tracking and referencing memory harder.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I apply events to dynamicly loaded DOM nodes with JQuery?
I'm using AHAH to load a piece of HTML after the document is ready. There's a button in that chunk of HTML I would like to apply a .click event to. I'm having trouble applying that event after the HTML is loaded. The call back is very generic and is used by other parts of the page so I would prefer not to fill it up with specific code. Any ideas?
A:
Look into using the .live() method: http://api.jquery.com/live/
A:
This is what the live method was built for.
Your best bet is to either use that, or add an event listener to your containing element (or even to body). Live is great for events that bubble. Event listeners are the solution to ones that do not.
A:
As others are pointing out, you want to consider using $.live(), which will handle events for all pre-existing DOM elements, as well as any added later down the road. For instance, suppose the block of HTML you're loading in has a set of links containing the classname "foo," all of which should respond in a specific way when clicked:
$(".foo").click(function(){
// I don't do anything to dynamicall-added elements
});
This example will only apply to pre-existing items containing the classname "foo." To handle current, and future elements, we should do the following:
$(".foo").live("click", function(){
// I handle both present, and future elements
});
Now anything added at any time will be handled by this if it contains the classname "foo". This works great for situations like yours where large blocks of html will be inserted into the DOM later in the page's lifecycle.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails 4 nested attribute in a form not saving
I am trying to build a nested form in rails 4. I've got the view up and running however when I submit the form the values do not save to my database. I read through the following answer and tried to replicate it in my code but I am still having the same issue:
Rails 4 nested attributes not saving
Here are what I think the relevant pieces of code:
View:
<div class="field">
<%= f.label :imagefile %><br>
<%= f.text_area :imagefile %>
</div>
<%= f.fields_for :amount_due do |ff| %>
<div class="field">
<%= ff.label :amount_due %><br>
<%= ff.text_field :amount_due %>
</div>
<div class="field">
<%= ff.label :invoice_id %><br>
<%= ff.text_field :invoice_id %>
</div>
<% end %>
invoices_controller:
def new
@invoice = Invoice.new
@invoice.amount_dues.build
end
def invoice_params
params.require(:invoice).permit(:imagefile, :user_id,
:amount_dues_attributes => [:id, :amount_due, :invoice_id])
end
amount_due Model:
class AmountDue < ActiveRecord::Base
belongs_to :invoice
belongs_to :user
end
invoice Model:
class Invoice < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
has_many :amount_dues
accepts_nested_attributes_for :amount_dues
end
A:
Figured it out. I did not make plural :amount_due in my view.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I set the swipe distance when using '-[XCUIElement swipeDown]' in UITest with Xcode7
The XCUIElement.h class file shows
- (void)scrollByDeltaX:(CGFloat)deltaX deltaY:(CGFloat)deltaY; and
- (XCUICoordinate *)coordinateWithNormalizedOffset:(CGVector)normalizedOffset; functions. But these can't use on iOS device. XCUIElement.h provides - (void)swipeDown to swipe the tableview. Because of the insufficient distance to swipe down, pull-to-refresh framework just like MJRefresh can't be responded.
So how do I custom the location or use exist function to edit the swipe down distance?
A:
You can drop down to the coordinate APIs to perform a pull-to-refresh.
let firstCell = app.staticTexts["Cell One"]
let start = firstCell.coordinateWithNormalizedOffset(CGVectorMake(0, 0))
let finish = firstCell.coordinateWithNormalizedOffset(CGVectorMake(0, 6))
start.pressForDuration(0, thenDragToCoordinate: finish)
I've put together more information along with a working sample app on my blog.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flatlist not showing items as intended
I want to display some items with a flatlist, when I tap on the item I want it to turn green. The issue I having is that I tap on a couple of the item and then I search for a device, for example: 112. When I remove the entry I see that the previous items are not in green anymore.
Snack: https://snack.expo.io/Skhaj78WU
<FlatList
data={this.state.data}
renderItem={({ item }) => <Item item={item}/>
keyExtractor={item => item[0]}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
extraData={this.state.data}
/>
This is the Item component:
class Item extends Component{
constructor(props) {
super(props)
this.state={
currentColor:'white'
}
this.onClick = this.onClick.bind(this)
}
onClick() {
console.log(this.props.item[1].isSelected)
console.log(this.props.item[0])
this.props.item[1].isSelected = !this.props.item[1].isSelected
var color = 'white'
if (this.props.item[1].isSelected){
color='green'
}
this.setState({currentColor:color})
}
render(){
return (
<TouchableHighlight onPress={this.onClick} key={this.props.item[0]}>
<View style={[styles.item, {backgroundColor: this.state.currentColor}]}>
<Text style={styles.title}>{this.props.item[1].name}</Text>
</View>
</TouchableHighlight>
);
}
}
A:
This line is causing your problems:
this.props.item[1].isSelected = !this.props.item[1].isSelected
Props should always be treated as read-only. The normal method of modifying a list from a list item is to pass a callback to each item and modify the list from the parent component, like this:
Snack
class Item extends Component {
constructor(props) {
super(props);
}
getColor = () => (this.props.item[1].isSelected ? 'green' : 'white');
render() {
return (
<TouchableHighlight onPress={this.props.onClick} key={this.props.item[0]}>
<View style={[styles.item, { backgroundColor: this.getColor() }]}>
<Text style={styles.title}>{this.props.item[1].name}</Text>
</View>
</TouchableHighlight>
);
}
}
toggleListItem = index => {
const { data } = this.state;
data[index][1].isSelected = !data[index][1].isSelected;
this.setState({ data });
};
render() {
return (
<SafeAreaView style={{ flex: 1 }}>
<FlatList
data={this.state.data}
renderItem={({ item, index }) => (
<Item item={item} onClick={() => this.toggleListItem(index)} />
)}
keyExtractor={item => item[0]}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
extraData={this.state.data}
/>
</SafeAreaView>
);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Put Button in the Right Center of layer?
i want the bottom button (button1) in the right center of relative layout
the layout exists under fragment
i used this attribute
android:layout_gravity="right|center_horizontal"
but no reaction as photo
http://imgur.com/mNTJnew
can u help me ?
the XML File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<LinearLayout
android:id="@+id/topLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/rounded_corner"
android:layout_centerHorizontal="true"
android:orientation="horizontal" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:ems="10"
android:layout_centerInParent="true"
android:ellipsize="start"
android:gravity="center_horizontal"
android:hint="@string/search"
android:singleLine="true"
android:textColorHint="#c7c7c7"
android:width="250dp" />
<Button
android:id="@+id/button1"
android:layout_width="38dp"
android:layout_height="30dp"
android:background="#359c5e"
android:onClick="geoLocate"
android:padding="0dp"
android:paddingBottom="0dp"
android:text="@string/go"
android:textColor="#ffffff" />
</LinearLayout>
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/belowlayout"
android:layout_below="@id/topLayout" />
<RelativeLayout
android:id="@+id/belowlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_gravity="right|center_horizontal"
android:background="@drawable/botton_corner"
android:text="Next"
android:textColor="#ffffff" />
</RelativeLayout>
</RelativeLayout>
A:
Instead of your RelativeLayout belowlayout try below
<RelativeLayout
android:id="@+id/belowlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_alignParentRight="true"
android:background="#359c5e"
android:layout_gravity="right|center_horizontal"
android:text="Next"
android:textColor="#ffffff" />
</RelativeLayout>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to keep the structure of the dictionary
Well i have the following dictionary:
{'3d1011c0bade5f0a064f7daeef09e7acf900cfe8af09e025859b3426': ['mils news 02122002_0005.txt', 1] }
Where
['mils news 02122002_0005.txt', 1]
is a list. And now i have the following:
result_array = {k: db_array.get(k, 0)[1] + db_array.get(k, 0)[1] for k in set(db_array) | set(db_array)}
with this i want to sum the number that is in the list with another dictionary. So my question is how to keep the dictionary unchanged, coz i get the following:
{'3d1011c0bade5f0a064f7daeef09e7acf900cfe8af09e025859b3426': 2}
as a result.
Expected output:
{'3d1011c0bade5f0a064f7daeef09e7acf900cfe8af09e025859b3426': ['mils news 02122002_0005.txt', 2] }
According to the first answer of the user, tnx for the solution but i get the following for different keys:
db_array = {'a': ['mils news 02122002_0005.txt', 3]}
>>> result_array = {'b': ['mils news 02122002_0005.txt', 3]}
>>> result_array = {k: [db_array[k][0],db_array[k][1] + result_array.get(k, ['', 0])[1]] for k in set(db_array) | set(result_array)}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <dictcomp>
KeyError: 'b'
A:
Include the db_array[k][0] value in your dict generator expression:
dv = ['', 0]
result_array = {k: [
db_array.get(k, result_array.get(k))[0],
db_array.get(k, dv)[1] + result_array.get(k, dv)[1]
] for k in set(db_array) | set(result_array)}
Note that I updated the default value to ['', 0] (and used a variable for that to increase readability) if the key is not already present in either dict. Note that for the first item in the list we fall back to result_array if the key was not present in db_array; the key is always present in at least one of the two dicts, this way you do not end up with empty string values.
If the key were not in the result_array dict, then your original default would cause problems, as you use an int 0 to then index as an array:
>>> result_array.get('foobar', 0)[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
(Updated to reflect your comment showing your original code).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Merging MultiLineStrings
I have few OL3 MultiLineString objects like
Object { type: "MultiLineString", coordinates: Array[2] }
Object { type: "MultiLineString", coordinates: Array[3] }
Object { type: "MultiLineString", coordinates: Array[4] }
Object { type: "MultiLineString", coordinates: Array[3] }
Now I want to merge all of them in a new big MultiLineString ( like PostGIS ST_Union function ). Is there some way to do this using OL3 or I must deal with JS arrays?
A:
Have you look at the library JSTS
Personnaly, I use this library to make an union on two geometry.
var parser = new jsts.io.OL3Parser();
var a = parser.read(first_OlFeature.getGeometry());
var b = parser.read(second_OlFeature.getGeometry());
var unionGeometry = a.union(b);
var featureFromUnion = new ol.Feature().setGeometry(parser.write(unionGeometry));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Broken markup on some questions (but the preview works)
In at least one questions ( How to compute molecular formula?) there is broken formatting, but only in the posted form. The preview view (if one were to try and edit it) shows what I believe is the correct output.
Text for the line in question:
WCl$_{6}$, WCl$_{14}$, WCl$_{18}$, and WCl$_{21}$.
How it is displayed on the site:
How it is previewed:
This appears to be a bug.
A:
MathJax developer Davide Cervone has created an improved parser for better separation of $\LaTeX$ and Markdown (thanks a lot!). We've tested it on math.se for a while, and since it has been working great, I have now enabled it everywhere. The bug you found is one of the issues that this new parser solves, so this shouldn't happen again.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Partial não renderiza
Estou com um problema em minha aplicação. O que acontece é que eu não estou conseguindo renderizar um partial em um outra view.
Aqui o código do partial:
@model CEF01.Models.Ocorrencia
@using (Html.BeginCollectionItem("Ocorrencia"))
{
@Html.HiddenFor(model => model.AlunoId)
<div class="form-horizontal">
<h4>Ocorrencia</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.Tipo, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Tipo)
@Html.ValidationMessageFor(model => model.Tipo)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Causa, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Causa)
@Html.ValidationMessageFor(model => model.Causa)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Observacao, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Observacao)
@Html.ValidationMessageFor(model => model.Observacao)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Salvar" class="btn btn-default" />
</div>
</div>
</div>
}
E aqui a parte em que eu tento renderizar esse partial em outra view:
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#ocorrencias">
Ocorrências do Aluno
</a>
</h4>
</div>
<div id="ocorrencias" class="panel-collapse collapse in">
<div class="panel-body">
@foreach (var ocorrencia in Model.Ocorrencias)
{
@Html.Partial("_AdicionaOcorrencia")
}
</div>
</div>
</div>
Diretórios e seus respectivos arquivos:
Alunos:
_AdicionaOcorrencia.cshtml
Adiciona.cshtml
Detalhes.cshtml
Edita.cshtml
Index.cshtml
Remove.cshtml
Ocorrencias:
- Adiciona.cshtml
- Detalhes.cshtml
- Edita.cshtml
- Index.cshtml
- Remove.cshtml
Shared:
Dentro de Shared tenho o diretório EditorTemplates e nele contém:
Collection.cshtml
Dentro de Shared:
_Layout.cshtml
_LoginPartial.cshtml
Error.cshtml
A:
Você esqueceu de passar o Model para dentro da Partial. Veja a linha @Html.Partial abaixo:
<div id="ocorrencias" class="panel-collapse collapse in">
<div class="panel-body">
@foreach (var ocorrencia in Model.Ocorrencias)
{
@Html.Partial("_AdicionaOcorrencia", ocorrencia)
}
</div>
</div>
Outra coisa é se Model.Ocorrencias estiver vazio. Aí não vai aparecer mesmo. O que você pode fazer é:
<div id="ocorrencias" class="panel-collapse collapse in">
<div class="panel-body">
@if (Model.Ocorrencias.Count > 0) {
foreach (var ocorrencia in Model.Ocorrencias)
{
@Html.Partial("_AdicionaOcorrencia", ocorrencia)
}
} else {
<div>Ainda não há ocorrências</div>
}
</div>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to import classes in other modules to Jersey?
I want to create a Java project with two modules. One is the module for data analysis and another one is the module for creating a restful server so that I can do data analysis remotely. The structure is as follows:
├── MyProject
| ├── Module 1: classA
| └── Module 2:
| └── HelloWorld (resource class)
| └── MyApplication (configuration class)
In module 2 I use Jersey.(I am a green hand on it) And I use glassfish and Jersey to build it. (I refer to this link).
I imported the classes in module 1 to the resources class in module two
import module1.classA
public class HelloWorld {
classA a;
public HelloWorld(){
classA a = new classA();
}
@GET
@Consumes({MediaType.TEXT_PLAIN})
@Produces(MediaType.TEXT_PLAIN)
public String getClichedMessage(@QueryParam("test") String test){
return a.data_analysis()
}
}
However I get a exception as follows:
java.lang.NoClassDefFoundError: module1.classA;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2583)
at java.lang.Class.getDeclaredFields(Class.java:1916)
at org.glassfish.jersey.internal.util.ReflectionHelper$4.run(ReflectionHelper.java:309)
at org.glassfish.jersey.internal.util.ReflectionHelper$4.run(ReflectionHelper.java:306)
at java.security.AccessController.doPrivileged(Native Method)
at org.glassfish.jersey.server.model.IntrospectionModeller.checkResourceClassFields(IntrospectionModeller.java:210)
at org.glassfish.jersey.server.model.IntrospectionModeller.doCreateResourceBuilder(IntrospectionModeller.java:137)
at org.glassfish.jersey.server.model.IntrospectionModeller.access$000(IntrospectionModeller.java:80)
at org.glassfish.jersey.server.model.IntrospectionModeller$1.call(IntrospectionModeller.java:111)
at org.glassfish.jersey.server.model.IntrospectionModeller$1.call(IntrospectionModeller.java:108)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255)
at org.glassfish.jersey.server.model.IntrospectionModeller.createResourceBuilder(IntrospectionModeller.java:108)
at org.glassfish.jersey.server.model.Resource.from(Resource.java:744)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:400)
at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:285)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:310)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
at javax.servlet.GenericServlet.init(GenericServlet.java:244)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1583)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1382)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5704)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5946)
at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2286)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1932)
at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255)
at org.glassfish.jersey.server.model.IntrospectionModeller.createResourceBuilder(IntrospectionModeller.java:108)
at org.glassfish.jersey.server.model.Resource.from(Resource.java:744)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:400)
at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:285)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:310)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:170)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:358)
at javax.servlet.GenericServlet.init(GenericServlet.java:244)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1583)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1382)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5704)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5946)
at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2286)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1932)
at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
Startup of context /test_gf_war_exploded failed due to previous errors]]
Which shows that the class in module1 is not found.
I am wondering how to deal with it. And if my framework for realizing it is wrong, what is the right method to import others modules to Jersey?
A:
In order to access Module 1 resources in Module 2 you need to add Module 1 to the Module Dependencies of Module 2. Select Open Module Settings in the context menu and add the module in the Dependencies tab.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
remove returned object's property in C#
I am calling a method to delete an object that contain a specific value. It looks like this:
static public void RemovePiece(string BoardId)
{
LumberPiece board = LocateBoard(BoardId);
board = null;
}
LumberPiece is a class that looks like this:
private class LumberPiece
{
public string boardID;
...
}
and LocateBoard is a function that returns the correctly identified LumberPiece Object:
static private LumberPiece LocateBoard(string BoardId)
{
if (SawyerArea.lumber.boardID == BoardId)
return SawyerArea.lumber;
else if (SpliceArea1.lumber.boardID == BoardId)
return SpliceArea1.lumber;
else if (SpliceArea2.lumber.boardID == BoardId)
return SpliceArea2.lumber;
else
throw new Exception("Your LumberID was not found in any activity area. Has it already been removed? or are you handling the integer-String Conversion Correctly");
}
The Area variables are instances of this class:
private class ActivityArea
{
public Sensor sensor;
public ClampSet clampSet;
public Servo servo;
public LumberPiece lumber;
public bool IsCurrentlyFilled()
{
if (lumber != null)
return true;
else
return false;
}
public ActivityArea(Sensor s, ClampSet cs, Servo srv)
{
sensor = s;
clampSet = cs;
servo = srv;
}
How can I remove the correctly identified LumberPiece Object?
A:
In garbage collected frameworks like .NET, you don't "delete" the object. You just stop caring about it. Once you have no references to it (via any route), the garbage collector will take care of it in due course.
This might involve removing the reference from a list, etc - which is usually as simple as:
list.Remove(theObject);
However, since we can't see where you stored the board, we can't tell you how to remove the references to it.
Actually, the work you need to do here is no different to non-GC platforms; you would still need to remove the pointer from those lists, to avoid a horrible error later when the now-deleted pointer gets accessed.
A:
You need to locate the ActivityArea that contains the Lumber object you want to delete.
so for Example you could use this method instead of LocateBoard:
static public ActivityArea LocateAreaByBoard(string BoardId)
{
if (SawyerArea.lumber.boardID == BoardId)
return SawyerArea;
else if (SpliceArea1.lumber.boardID == BoardId)
return SpliceArea1;
else if (SpliceArea2.lumber.boardID == BoardId)
return SpliceArea2;
else
throw new Exception("Your LumberID was not found in any activity area. Has it already been removed? or are you handling the integer-String Conversion Correctly");
}
and then you can change your remove code to look like this:
ActivityArea area = LocateAreaByBoard(BoardId);
area.lumber = null;
And it will give you the desired deletion effects
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pure CSS emulation of a frameset
I have been searching for more than 1 hour with no success. Is there a pure CSS way of emulating a frameset? I mean, really emulating it. I have found some interesting stuff where you will have fixed top and bottom blocks, but the scroll bar for the content is the regular browser body scrollbar. What I need is a scrollbar only for the content block, as a frameset would do.
I can make it work by assigning overflow: auto to my content area div and setting a fixed height. But the problem is I don't know the client browser window size without using javascript. And I don't want to use javascript for this. I also canot use percents for the heights as my top block has a fixed height. The lower block is the one that should expand or shrink depending on the browser window height. Any help appreciated. Thank you!
A:
How about something like this?
HTML
<div id="header">
<img src="logo.gif" alt="logo" />
<h1 class="tagline">Oh em gee</h1>
</div>
<div id="content">
<div id="content-offset">
<p>This will be 100% of the screen height, BUT the content offset will have a top pixel margin which allows for your header. Set this to the pixel value of your header height.</p>
</div>
</div>
CSS
body, html {
margin: 0; padding: 0;
height: 100%;
}
#header {
height: 120px;
position: fixed;
top: 0;
background: red;
width: 100%;
}
#content {
height: 100%;
position: absolute;
top: 0;
}
#content-offset {
margin-top: 120px;
background: aqua;
height: 100%;
width: 100%;
position: fixed;
overflow: auto;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I cope with extreme pain from running on hard surfaces?
For the last 1/2 of 2011 I was going to my gym and working out 5-6 times per week. It was amazing! I preferred running on the treadmill as it was predictable with less impact. I also was able to switch it up and hop on an elliptical to diversify.
However, I'm no longer able to afford a gym or treadmill, and I'm trying to stick with some ad-hoc routines at home and running outside. But when I run outside consistently, I have a lot of pain. Feet, ankles, calves, knees and hips. This never happened when running on the treadmill, so it seems to be due to the impact of running outside, on steep hills and on pavement. Once I stop running and stretch, the pain is gone as quick as 10 minutes after my run is complete. I am definitely stretching both before and after.
How can I cope? I'd love not to be able to be eating ibuprofen all day and I really want to continue running, it keeps me sane!
Ideas?
EDIT With More Information:
After reading some of these responses and thinking about it some more, I have some additional information that I think would be helpful. This run is the same every time and it includes some pretty steep hills down in the beginning. I can imagine that the impact of downhill running on steep hills just makes the impact much worse? This could set the stage for pain throughout my run if running on this hill downward and landing heavily.
My shoes are great, never had an issue before, but that was on a treadmill. I would bet that I am conditioned to run on a treadmill, but since that is not an option and there are very little other choices where I live, can I train my body to run better on hard surfaces?
I've always been intrigued by the Vibram Five-Finger shoes, but I've heard mixed results. I am sure it would take a while to train myself to run differently, as I don't run this way.
ONE LAST EDIT
I tried my runs recently by skipping the hill, which I know is very tough on my body. The effort it takes to just make sure I don't go rolling down the hill is one thing, let alone the impact of my weight + momentum all landing on my feet and move throughout my body.
The last few days while running the trail I tried to get on real ground when I can (1/3 of the time) as well as skipping the extremely steep hills - it was not any better or less painful.
EVERYONE had great feedback and worthwhile points, but I'm inclined to think that it's about getting used to it. I do think that I'll try learning to run with less impact as well.
A:
I would guess that by running exclusively on a tread mill you developed a stride that relied on the forgiving surface. I run exclusively in minimalist shoes (Vibram Fivefingers) on pavement with no complaints now but I ran in traditional running shoes for over a decade and had occasional knee or plantar fascia problems. I also spent about five years running almost exclusively on gravel and during that time I had pretty severe knee pain any time I ran on pavement. It is clear to me now that my old stride included very hard heel strikes while the stride that I learned running in minimalist shoes does not. I can take off my shoes and run the same way barefooted with no discomfort (until the abrasion gets to the soles of my feet :-)
Learning to run in minimalist shoes would probably require more of a commitment than you would want to take on, but I recommend visiting this Harvard web site on the biomechanics of foot strikes to get an idea of how to run with a forefoot strike, then practicing that with the shoes you wear now. If you can modify your stride you will likely relieve much of your pain.
UPDATE: I just noticed the additional info you added. Running down steep hills definitely generates the hardest impacts so you should avoid them as long as you are experiencing pain. You could also consider walking down steep hills. Also, take plenty of time to recover between runs, perhaps several days. If you do not want to skip exercise for that length of time substitute walking between your runs.
UPDATE 2: I should have linked to this video originally. It gives you a nice overview of the information you will find at the Harvard Barefoot Running website.
A:
The problem is that you're conditioned to run on a treadmill and are transitioning to a road down-hill too quickly.
Your heart and lungs are prepared but your legs aren't; so you need to train them.
I would do something a little like a beginner's training plan. You'll need to start by walking and then walk-running before you can actually run. Yes, it will be very frustrating because your heart and lungs can run the distance. At the moment, your legs can't and that's why you're getting pain.
@JimClark's comment about forefoot/minimalist running is useful. While I'm unconvinced by Vibrams per se learning to run on your forefoot is definitely an advantage.
(I think most people who move to Vibrams don't take the time to adapt to them properly and get problems.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I make a switch-like conditional environment?
I'm writing a running presentation for an entire semester's lecture (with beamer) and would like to make an environment such as
\begin{lecture}{3}
...
\end{lecture}
such that I can have at the top of my document a variable, \thelecture that I can set to a number to compile only the slides of that lecture. (Additionally I'd like to also be able to set it to zero or have some such flag to compile all lectures' slides.)
Usual conditionals don't seem to do the trick. As best as I can tell I will need to combine \ifthenelse with the comment environment.
Is there any elegant solution? Or ideally even already a package made to do this?
A:
Chapter 10.4, Splitting a Course Into Lectures, in the Beamer documentation might be worth checking out, providing the \includeonlylecture command:
Designate different lectures with the \lecture[<short lecture name>]{<lecture name>}{<lecture label>} command:
\begin{document}
\lecture{Vector Spaces}{week 1}
\section{Introduction}
...
\section{Summary}
\lecture{Scalar Products}{week 2}
\section{Introduction}
...
\section{Summary}
\end{document}
Then do
\includeonlylecture{week 1}
in the preamble of the document.
There's also \AtBeginLecture{<text>}, which will insert arbitrary text at the beginning of every lecture.
\AtBeginLecture{\frame{\Large Today's Lecture: \insertlecture}}
Where \insertlecture{} will provide the lecture name. There's also \insertshortlecture{}, which will do the same thing for the <short lecture name>.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
handle ajax error when a user clicks refresh
i apologise if this is something i should be able to look up. all of the terms i wanted were way overloaded..
here is my problem: when i open a page, it fires off a whole series of ajax calls. if i then press Shift+Refresh, all of those ajax calls are being considered errors, and showing their error message dialogs before the entire page itself reloads.
so the error is being triggered by the client - is there anyway i can find out if this is the case so i can ignore it? eg in the xmlhttprequest, or in the ajax function (i am using jquery btw)
A:
There are several suggested approaches for detecting this:
Several have suggested the use of a beforeunload handler to set a boolean flag so that the error handler can know that the page is being unloaded (See list of related/duplicated posts below). This is great, except that mobile Safari on iOS doesn't support the beforeunload event.
Sachindra suggested an approach where instead of firing the error function immediately, it got delayed a second in a setTimeout(..., 1000). That way, there is a good chance the page has actually disappeared by the time the error handler gets called. "Good chance" that is. I bet if I have a huge page with e.g. many <input>s, it could take more than 1 sec to unload, and then perhaps the error handler would fire anyway.
I therefore suggest a combination of reliably detecting beforeunload support and if beforeunload is not supported (cough iPad/iPhone cough) revert to Sachindra's delay trick.
See the full solution with beforeunload detection and all in this jsfiddle.
It looks like the situation is a little better for jQuery 2.x than for 1.x, but 2.x also seems a little flakey, and so I still find this suggestion prudent.
P.S: There were also suggestions involving testing some fields in the XHR / jqXHR object. (Here and here). I have not come accross a combination that could distinguish between user navigation and restarting the webserver during a long-running AJAX call, and I have therefore not found this approach useful to me.
This is really also an answer to these related/duplicated Stack Overflow questions:
jQuery AJAX fires error callback on window unload?
$.ajax calls success handler when request fails because of browser reloading
How best to handle errors during jquery ajax calls caused by user clicking on links
Detecting that a jQuery.ajax call failed because the page is reloading?
and these posts outside of Stack Overflow:
What's the proper way to deal with AJAX error because of page reload?
How to Distinguish a User-Aborted AJAX Call from an Error | I like stuff.
A:
[this is an edit from the previous answer, which had outstanding questions that I have since resolved]
jQuery throws the error event when the user navigates away from the page either by refreshing, clicking a link, or changing the URL in the browser. You can detect these types of errors by by implementing an error handler for the ajax call, and inspecting the xmlHttpRequest object:
$.ajax({
/* ajax options omitted */
error: function (xmlHttpRequest, textStatus, errorThrown) {
if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0)
return; // it's not really an error
else
// Do normal error handling
});
A:
var isPageBeingRefreshed = false;
window.onbeforeunload = function() {
isPageBeingRefreshed = true;
};
$.ajax({
error: function (xhr, type, errorThrown) {
if (!xhr.getAllResponseHeaders()) {
xhr.abort();
if (isPageBeingRefreshed) {
return; // not an error
}
}
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does my mobile carrier re-encode a file when I download it?
I have found a very strange occurrence in Android. I have found that when downloading an image over 3g the sha1 computed afterwards is different than what it should have been occording to the file that is on the server. Upon further investigation, I found that the image was actually down sized and re-encoded. It would appear that my mobile carrier (verizon) is trying to optimize files that I'm downloading.
My question is, can anyone else confirm that mobile networks might optimize your file before it lands on your device? And if so, is there a setting somewhere somehow so that I can disable this.
It's very important in my app to know that the file's sha1 of what I've downloaded equals what the server says it should be.
Here's an article found about verizon optimizing 3g transfers.
A:
You didn't say, but let's assume this is an HTTP connection.
In short, they are doing it to save bandwidth. 3G isn't Free!
If you are directly requesting resources (GET), then you are at the mercy of all intermediaries that process the HTTP response (i.e. proxies, gateways), and you can be sure they can see the MIME type in the headers, and behave accordingly.
You can try using the HTTP Accept header in your request, and use the q parameter to "hint" that you want maximum fidelity.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Accept: image/png;q=1
The q ranges from 0 to 1. You may be able to get away with a lower value (than 1). Please read the linked section for more details.
You can also inspect the incoming Content-Type header; it may reveal if there's a "declared" change in quality or even MIME type. It may be telling you what it did!
It would be excellent if the "standard" does its job for you!
If that doesn't work, and you are in control of the server end already, use an alternate text-based encoding for it, like Base64, that intermediaries cannot "compress" for you. SOAP has been doing that since ever!
If you really really need to bypass image compression, and Accept doesn't work, you must proxy those kinds of requests yourself, and re-encode them with a non-image MIME type in the response.
If you are going the self-proxy route, you could probably get away with calling your images application/octect-stream which is the MIME type for "uninterpreted bytes". This would allow for more-or-less pass-through of the data, and hopefully keep intermediaries "helping hands" off your stuff!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Call private class method not being initialized in constructor
I am writing a unit test and one of the issues that I encounter is null exception on a private class that is not part of DI or not being initialized on constructor parameters. Anyone can help me? Here's my code. My problem is that how to mock PPortalSessionVariables class.
Controller:
public class EducatorController : BaseController
{
//Note: PPortalSessionVariables class should NOT be part of IOC
private readonly IPPortalSessionVariables _ppsessionVariable = new PPortalSessionVariables();
private readonly IEducatorService _educatorService;
public EducatorController(IEducatorService educatorService)
{
_educatorService = educatorService;
}
public ActionResult Index()
{
//during test null exception occurs on _ppsessionVariable.CurrentChild.Id
var model = _educatorService.GetEducatorsForChild(Convert.ToInt64(_ppsessionVariable.CurrentChild.Id));
return View(model);
}
}
Test Class:
[TestClass]
public class EducatorControllerTests
{
public EducatorController CreateController(Mock<IEducatorService> educatorService = null)
{
educatorService = educatorService ?? new Mock<IEducatorService>();
HttpContext.Current = HttpMockHelpers.FakeHttpContextCurrent();
var controller = new EducatorController(educatorService.Object);
controller.SetFakeControllerContext("?site=2");
return controller;
}
[TestMethod]
public void Index_Get_ReturnIndexView()
{
var ppsessionVariable = new Mock<IPPortalSessionVariables>();
var controller = CreateController();
var child = new ChildModel();
child.Id = 0;
ppsessionVariable.Setup(x => x.CurrentChild).Returns(child);
var result = controller.Index() as ViewResult;
Assert.IsNotNull(result);
}
}
A:
Don't understand why you just don't use it as any other dependency injecting it via IoC. As far as Moq works you should mock that class but never will be able to set that object, maybe a workaround is create a setter for that property and call the property in your test passing the mock object.
EducatorController
public void SetPortalSession(IPPortalSessionVariables portal)
{
_ppsessionVariable = portal;
}
EducatorControllerTests
[TestMethod]
public void Index_Get_ReturnIndexView()
{
var ppsessionVariable = new Mock<IPPortalSessionVariables>();
var controller = CreateController();
controller.SetPortalSession(ppsessionVariable.object);
var child = new ChildModel();
child.Id = 0;
ppsessionVariable.Setup(x => x.CurrentChild).Returns(child);
var result = controller.Index() as ViewResult;
Assert.IsNotNull(result);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Server Concatenate using FOR XML dilemma
I come from an oracle background so in doing searches on this site I have found countless examples on how to use the FOR XML PATH to try to duplicate what LISTAGG() will do in oracle. However I don't know if what I am trying to do is outside of that scope or I am not figuring out what piece I am missing. Every example I have found just uses a single key id and in my case I have to use joins from multiple tables.
Here is the layout for how the tables look.
CREATE TABLE driven_product
([PRODUCT_ID] int, [DRIVER_ID] int, [DRIVER_PRODUCT_INPUT_NUM] int);
INSERT INTO driven_product
([PRODUCT_ID], [DRIVER_ID], [DRIVER_PRODUCT_INPUT_NUM])
VALUES (1, 2, 3);
CREATE TABLE product_input
([PRODUCT_ID] int, [PRODUCT_INPUT_NUM] int, [PRODUCT_VALUE_NUM] int, [COLOR] VARCHAR (50));
INSERT INTO product_input
([PRODUCT_ID], [PRODUCT_INPUT_NUM], [PRODUCT_VALUE_NUM], [COLOR])
VALUES
(1, 3, 1, 'White'),
(1, 3, 2, 'Blue'),
(1, 3, 3, 'Green'),
(1, 3, 4, 'Yellow'),
(1, 3, 5, 'Orange');
CREATE TABLE driven_price
[PRODUCT_ID] int, [DRIVER_ID] int, [PRODUCT_VALUE_NUM] int, [PRICE] int);
INSERT INTO driven_price
([PRODUCT_ID], [DRIVER_ID], [PRODUCT_VALUE_NUM], [PRICE])
VALUES
(1, 2, 1, 10),
(1, 2, 2, 10),
(1, 2, 3, 10),
(1, 2, 4, 20),
(1, 2, 5, 20);
The driven_product table joins to the product_input table using driven_product.product_id = product_input.product_id AND driven_product.driver_product_input_num = product_input.product_input_num. The driven_price table joins using the
driven_product.product_id = driven_price.product_id, driven_product.driver_id = driven_price.driver_id, and product_input.product_value_num = driven_product.product_value_num.
The closest I have gotten to is:
SELECT STUFF((SELECT '/' + color
FROM product_input pi
WHERE pi.product_id = dp.product_id
AND pi.product_input_num = dp.product_input_num
FOR XML PATH( '')), 1, 1, ''), dpr.price
FROM driven_product dp
INNER JOIN driven_price dpr ON dp.product_id = dpr.product_id
AND dp.driven_id = dpr.driven_id
This combines all the colors into each price.
Now the obvious thing is that I am not joining the product_input.product_value_num to the driven_price.product_value_num. When I do that it breaks each color out into its own row.
So this is where I am struggling is that I need to do it by price. So I need to have "White, Blue, Green" and "Yellow, Orange" to be separate.
I tried to set this up on SQLFiddle, but I kept getting errors. Any guidance that you can provide will be appreciated.
A:
you can use group by or distinct.. but your main problem is you were not filtering your FOR XML query by PRICE, so you're getting every color.
SELECT DISTINCT
Products = STUFF((
SELECT '/' + color
FROM driven_price dp2
JOIN product_input pi ON dp2.Product_Value_Num = PI.Product_Value_Num
WHERE dp2.driver_id = dpr.driver_id AND dp2.Price = dp.Price
FOR XML PATH('')), 1, 1, ''),
dp.[Price]
FROM driven_product dpr
JOIN product_input pri ON dpr.Driver_product_input_num = pri.PRODUCT_INPUT_NUM
JOIN driven_price dp ON pri.product_id = dp.product_id
AND pri.product_value_num = dp.product_value_num
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unpacking a numpy ndarray of tuples and add it in a new dimension
I have a numpy ndarray x of of shape (M,N) where each element in N is a 2 element tuple containing real and imaginary parts of a complex number.
I would like to unpack the tuple into another dimension such that my x would now have the shape (M,N,2)
My first idea is to seperate the real and imaginary parts into two numpy arrays of shape (M,N) and concatenate them over the second axis so that I can get the desired output. To do so, I tried to access only the real and imaginary parts as follows
x[:,:][0]
x[:,:][1]
However, it returns me the whole array instead of only the real/imaginary parts. Any pointers on how I can proceed?
An example array is as follows
array([[( 4.82641562, -1.84333128), (-1.29724314, 2.06545141),
( 0.02074953, -1.32518303)],
[(-0.81477981, -3.34148138), ( 0.231383 , 1.35495823),
( 1.66341462, -1.33603417)],
[( 2.2809137 , -1.17720382), (-1.05115026, -2.09556016),
( 1.57932884, -0.7438237 )],
[(-2.2170903 , 0.81147059), ( 0.17489367, 0.15123805),
(-1.95151614, -0.5669619 )],
[(-2.16413158, 0.44555251), ( 1.2545366 , -0.06933326),
( 1.08469658, 1.71108236)],
[(-0.99776606, -0.0607623 ), (-0.11785624, -1.90687216),
( 1.28964911, -1.03083365)],
[( 1.65550362, -1.26383881), ( 0.13404437, 1.4402823 ),
( 0.04223597, -1.00992713)],
[(-0.4696885 , 2.66014003), (-1.12157114, -1.03019938),
( 2.6312301 , 0.22770433)],
[( 1.74457246, -0.91478885), (-0.18861201, 0.75360561),
( 0.27141119, 0.71356903)],
[(-0.15940566, 1.26613812), ( 1.28238354, 1.31858431),
( 0.31217745, 0.13244299)]],
dtype=[('real', '<f8'), ('imag', '<f8')])
A:
You conveniently have your array setup as a structured array, which means you can just access the real and imaginary parts using each field's string name:
arr['real']
arr['imag']
For example:
>>> arr['real']
array([[ 4.82641562, -1.29724314, 0.02074953],
[-0.81477981, 0.231383 , 1.66341462],
[ 2.2809137 , -1.05115026, 1.57932884],
[-2.2170903 , 0.17489367, -1.95151614],
[-2.16413158, 1.2545366 , 1.08469658],
[-0.99776606, -0.11785624, 1.28964911],
[ 1.65550362, 0.13404437, 0.04223597],
[-0.4696885 , -1.12157114, 2.6312301 ],
[ 1.74457246, -0.18861201, 0.27141119],
[-0.15940566, 1.28238354, 0.31217745]])
>>> arr['imag']
array([[-1.84333128, 2.06545141, -1.32518303],
[-3.34148138, 1.35495823, -1.33603417],
[-1.17720382, -2.09556016, -0.7438237 ],
[ 0.81147059, 0.15123805, -0.5669619 ],
[ 0.44555251, -0.06933326, 1.71108236],
[-0.0607623 , -1.90687216, -1.03083365],
[-1.26383881, 1.4402823 , -1.00992713],
[ 2.66014003, -1.03019938, 0.22770433],
[-0.91478885, 0.75360561, 0.71356903],
[ 1.26613812, 1.31858431, 0.13244299]])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Negative margins: can they work in IE7 and IE8?
I'm trying to have a kind of dirty underline effect using a string of hyphens, but I want it slightly closer to the multi-line title than the line-height.
Negative margin works a treat in FF but no joy in IE?
<p>a multiline title here<p><p style="margin: -7px 0px 10px 0px;">-----------------------------------------------------------------------------</p>
A:
ok fixed it,
i reduced the line height on my ------'s tag,
the line height acts like a top margin...
thanks guys
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JAVA: Trouble putting values into a toString method
My method locateLargest() as show below is a method to find the coordinates of my largest value in my array. I'm having trouble putting the return values into a toString method. I have no idea how to format it into the toString method.
public Location locateLargest(int[][] x){
int maxValue = getMax(x);
for (int i = 0; i < x.length; i++){
for (int j = 0; j < x.length; j++)
if (x[i][j] == maxValue)
return new Location(i,j);
}
}
My toString attempt:
public String toString(){
return "[" + i + "][" + j + "]";
}
location class code:
class Location {
private int row;
private int column;
Location(){}//end constructor
Location(int row, int column){
this.row = row;
this.column = column;
}//end arg constructor
public int getRow(){
return this.row;
}
public int getColumn(){
return this.column;
}
Here is my full code for my program:
import java.util.Scanner;
public class LocationTest {
public static void main(String[] args) {
Scanner numberInput = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of the array: ");
int row = numberInput.nextInt();
int column = numberInput.nextInt();
Location l1 = new Location(row, column);
Location l2 = new Location();
row = l1.getRow();
column = l1.getColumn();
int[][] array = new int[l1.getRow()][l1.getColumn()];
System.out.println("Please enter the array elements: ");
for (int r = 0; r < array.length; r++){
for (int c = 0; c < array[r].length; c++){
array[r][c] = numberInput.nextInt();
}//end nested loop
}//end for loop
System.out.println(getMax(array));
System.out.println(l1.locateLargest(array).toString());
}
public static int getMax(int[][] x){
int max = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++){
for (int j = 0; j < x[i].length; j++){
if (x[i][j] > max)
max = x[i][j];
}
}
return max;
}
public Location locateLargest(int[][] x){
int maxValue = getMax(x);
for (int i = 0; i < x.length; i++){
for (int j = 0; j < x.length; j++)
if (x[i][j] == maxValue)
return new Location(i,j);
}
return null;
}
}
class Location {
private int row;
private int column;
Location(){}//end constructor
Location(int row, int column){
this.row = row;
this.column = column;
}//end arg constructor
public int getRow(){
return this.row;
}
public int getColumn(){
return this.column;
}
public String toString(){
return "[" + row + "][" + column + "]";
}
}
A:
If the Location is a class your defined yourself, you should implement function toString() as well
class Location{
int locationX,locationY;
public Location(int x,int y){
locationX = x;
locationY = y;
}
public String toString(){
return locationX+","+locationY;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need help integrating $\frac{(t-1)^2-2t(t-1)}{t^2+(a(t-1)^2)^2}$
I need to integrate $$a\int_1^2 \frac{(t-1)^2-2t(t-1)}{t^2+(a(t-1)^2)^2} dt$$ $$=a\int_1^2 \frac{-t^2+1}{t^2+(a(t-1)^2)^2} dt $$
$$=-a\int_1^2 \frac{t^2-1}{t^2+(a(t-1)^2)^2} dt $$ with the hint that two trigonomic substitutions would be necessary and to consider using arctan. I have tried to tackle this a few different ways and get stuck every time. Can anyone help me start off?
A:
Looks like we could make use of this
$$ a\int \frac{-t^2+1}{t^2+(a(t-1)^2)^2} \; dt =
-a \int \frac{1 - \frac{1}{t^2}}{1 + \left( a \left( \sqrt{t } - \frac{1}{\sqrt t } \right )^2 \right )^2 }dt =
-a \int \frac{1 - \frac{1}{t^2}}{1 + \left( a \left( t + \frac{1}{ t } - 2 \right ) \right )^2 }dt $$
Substitute $\displaystyle a\left( t + \frac{1}{ t } - 2 \right ) = u$, you get $\displaystyle - \int \frac{ 1}{1 + (u)^2} du $
|
{
"pile_set_name": "StackExchange"
}
|
Q:
X-Symfony-Cache always miss
I'm working Symfony 2.6 HTTP cache, I'm following all the instructions in Symfony cook book here
But, why the response always X-Symfony-Cache: MISS. I try to modification AppModification.php erase array on privates header. the response header is X-Symfony-Cache:GET /page: fresh.
After I modified array, I got new problem, while I'm trying to login to my web I got error or message the page isn't working.
here my code before erase array private header:
protected function getOptions()
{
return array(
'debug' => true,
'default_ttl' => 60,
'private_headers' => array('Authorization', 'Cookie'),
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
);
}
Response Headers:
Cache-Control:private
Connection:Keep-Alive
Content-Type:text/html; charset=UTF-8
Date:Wed, 29 Jun 2016 03:37:56 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.5.30
Transfer-Encoding:chunked
X-Powered-By:PHP/5.5.30
X-Symfony-Cache:GET /page: stale, invalid
I try to erase array private header
protected function getOptions()
{
return array(
'debug' => true,
'default_ttl' => 60,
'private_headers' => array(),
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
);
}
Response Headers:
Age:2
Cache-Control:public, s-maxage=62
Connection:Keep-Alive
Content-Length:366990
Content-Type:text/html; charset=UTF-8
Date:Wed, 29 Jun 2016 03:41:56 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.5.30
X-Content-Digest:en5ea0d5af1ee851007583987e8dfb3a8207874e303363f3d33c412b7f3fe6c12c
X-Powered-By:PHP/5.5.30
X-Symfony-Cache:GET /page: stale, invalid, store
anyone can help me, to suggest to solve this problem? I have no idea anymore, and can't find in any Symfony documentation.
Here my controller:
public function showDetailsAction( $pageSlug,request $request)
{
$productManager = $this->get('my.core.manager.product');
$product = $productManager->findOneProduct();
$options = $cmsManager->getSlugType($pageSlug);
$memcacheKey = 'prodrelated_'.$productNumber;
if($this->get('memcache.default')->get($memcacheKey)){
$result = $this->get('memcache.default')->get($memcacheKey);
}else{
$cloudSearchManager = $this->get('my.core.manager.cloudsearch');
$result = $cloudSearchManager->findRelatedProductBy($options);
$this->get('memcache.default')->set($memcacheKey, $result, 0, 300);
}
$view = $this
->view()
->setTemplate("MyBundle:Product:detail.html.twig")
->setData(array(
'product' => $product
));
return $this->handleView($view);
}
A:
The Symfony Cache layer acts like an intermediary HTTP cache, much like a reverse proxy like Varnish would.
This means that for a response to be cacheable, it needs to be public (any cache can store it) and not private (only the browser cache may store it). Additionally, an appropriate caching strategy must be used, like a max-age in the Cache-Control header or an Expires header.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Utilize Results from Synchronized Hashtable (Runspacepool 6000+ clients)
Adapting a script to do multiple functions, starting with test-connection to gather data, will be hitting 6000+ machines so I am using RunspacePools adapted from the below site;
http://learn-powershell.net/2013/04/19/sharing-variables-and-live-objects-between-powershell-runspaces/
The data comes out as below, I would like to get it sorted into an array (I think that's the terminology), so I can sort the data via results. This will be adapted to multiple other functions pulling anything from Serial Numbers to IAVM data.
Is there any way I can use the comma delimited data and have it spit the Values below into columns? IE
Name IPAddress ResponseTime Subnet
x qwe qweeqwe qweqwe
The added values aren't so important at the moment, just the ability to add the values and pull them.
Name Value
—- —–
x-410ZWG \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-410ZWG",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-47045Q \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-47045Q",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-440J26 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-440J26",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-410Y45 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-410Y45",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-DJKVV1 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-DJKVV1",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
nonexistant
x-DDMVV1 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-DDMVV1",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-470481 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-470481",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-DHKVV1 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-DHKVV1",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-430XXF \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-430XXF",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-DLKVV1 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-DLKVV1",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-410S86 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-410S86",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-SCH004 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-SCH004",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
x-431KMS
x-440J22 \\x-DHMVV1\root\cimv2:Win32_PingStatus.Address="x-440J22",BufferSize=32,NoFragmentation=false,RecordRoute=0,…
Thank for any help!
Code currently
Function Get-RunspaceData {
[cmdletbinding()]
param(
[switch]$Wait
)
Do {
$more = $false
Foreach($runspace in $runspaces) {
If ($runspace.Runspace.isCompleted) {
$runspace.powershell.EndInvoke($runspace.Runspace)
$runspace.powershell.dispose()
$runspace.Runspace = $null
$runspace.powershell = $null
} ElseIf ($runspace.Runspace -ne $null) {
$more = $true
}
}
If ($more -AND $PSBoundParameters['Wait']) {
Start-Sleep -Milliseconds 100
}
#Clean out unused runspace jobs
$temphash = $runspaces.clone()
$temphash | Where {
$_.runspace -eq $Null
} | ForEach {
Write-Verbose ("Removing {0}" -f $_.computer)
$Runspaces.remove($_)
}
Write-Host ("Remaining Runspace Jobs: {0}" -f ((@($runspaces | Where {$_.Runspace -ne $Null}).Count)))
} while ($more -AND $PSBoundParameters['Wait'])
}
#Begin
#What each runspace will do
$ScriptBlock = {
Param ($computer,$hash)
$Ping = test-connection $computer -count 1 -ea 0
$hash[$Computer]= $Ping
}
#Setup the runspace
$Script:runspaces = New-Object System.Collections.ArrayList
# Data table for all of the runspaces
$hash = [hashtable]::Synchronized(@{})
$sessionstate = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
$runspacepool = [runspacefactory]::CreateRunspacePool(1, 100, $sessionstate, $Host)
$runspacepool.Open()
#Process
ForEach ($Computer in $Computername) {
#Create the powershell instance and supply the scriptblock with the other parameters
$powershell = [powershell]::Create().AddScript($scriptBlock).AddArgument($computer).AddArgument($hash)
#Add the runspace into the powershell instance
$powershell.RunspacePool = $runspacepool
#Create a temporary collection for each runspace
$temp = "" | Select-Object PowerShell,Runspace,Computer
$Temp.Computer = $Computer
$temp.PowerShell = $powershell
#Save the handle output when calling BeginInvoke() that will be used later to end the runspace
$temp.Runspace = $powershell.BeginInvoke()
Write-Verbose ("Adding {0} collection" -f $temp.Computer)
$runspaces.Add($temp) | Out-Null
}
# Wait for all runspaces to finish
#End
Get-RunspaceData -Wait
$stoptimer = Get-Date
#Display info, and display in GridView
Write-Host
Write-Host "Availability check complete!" -ForegroundColor Cyan
"Execution Time: {0} Minutes" -f [math]::round(($stoptimer – $starttimer).TotalMinutes , 2)
$hash | ogv
A:
When you use runspaces, you write the scriptblock for the runspace pretty much the same way you would for a function. You write whatever you want the return to be to the pipeline, and then either assign it to a variable, pipe it to another cmdlet or function, or just let it output to the console. The difference is that while the function returns it's results automatically, with the runspace they collect in the runspace output buffer and aren't returned until you do the .EndInvoke() on the runspace handle.
As a general rule, the objective of a Powershell script is (or should be) to create objects, and the objective of using the runspaces is to speed up the process by multi-threading. You could return string data from the runspaces back to the main script and then use that to create objects there, but that's going to be a single threaded process. Do your object creation in the runspace, so that it's also multi-threaded.
Here's a sample script that uses a runspace pool to do a pingsweep of a class C subnet:
Param (
[int]$timeout = 200
)
$scriptPath = (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent)
While (
($network -notmatch "\d{1,3}\.\d{1,3}\.\d{1,3}\.0") -and -not
($network -as [ipaddress])
)
{ $network = read-host 'Enter network to scan (ex. 10.106.31.0)' }
$scriptblock =
{
Param (
[string]$network,
[int]$LastOctet,
[int]$timeout
)
$options = new-object system.net.networkinformation.pingoptions
$options.TTL = 128
$options.DontFragment = $false
$buffer=([system.text.encoding]::ASCII).getbytes('a'*32)
$Address = $($network.trim("0")) + $LastOctet
$ping = new-object system.net.networkinformation.ping
$reply = $ping.Send($Address,$timeout,$buffer,$options)
Try { $hostname = ([System.Net.Dns]::GetHostEntry($Address)).hostname }
Catch { $hostname = 'No RDNS' }
if ( $reply.status -eq 'Success' )
{ $ping_result = 'Yes' }
else { $ping_result = 'No' }
[PSCustomObject]@{
Address = $Address
Ping = $ping_result
DNS = $hostname
}
}
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(100,100)
$RunspacePool.Open()
$Jobs =
foreach ( $LastOctet in 1..254 )
{
$Job = [powershell]::Create().
AddScript($ScriptBlock).
AddArgument($Network).
AddArgument($LastOctet).
AddArgument($Timeout)
$Job.RunspacePool = $RunspacePool
[PSCustomObject]@{
Pipe = $Job
Result = $Job.BeginInvoke()
}
}
Write-Host 'Working..' -NoNewline
Do {
Write-Host '.' -NoNewline
Start-Sleep -Seconds 1
} While ( $Jobs.Result.IsCompleted -contains $false)
Write-Host ' Done! Writing output file.'
Write-host "Output file is $scriptPath\$network.Ping.csv"
$(ForEach ($Job in $Jobs)
{ $Job.Pipe.EndInvoke($Job.Result) }) |
Export-Csv $scriptPath\$network.ping.csv -NoTypeInformation
$RunspacePool.Close()
$RunspacePool.Dispose()
The runspace script does a ping on each address, and if it gets successful ping attempts to resolve the host name from DNS. Then it builds a custom object from that data, which is output to the pipeline. At the end, those objects are returned when the .EndInvoke() is done on the runspace jobs and piped directly into Export-CSV, but it could just as easily be output to the console, or saved into a variable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using PDO to echo display all rows from a table
I'm trying to echo out all the rows of a table using PDO but am running into trouble.
With the old way of doing I'd have done it like
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){
$title= $row['title'];
$body= $row['body'];
}
But with PDO I'm trying;
$result = $db->prepare("SELECT title, body FROM post");
$result->execute();
while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
echo $title;
echo $body;
Which keeps giving me Call to undefined method PDO::fetchAll()
Doing the example given in the manual
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
Works, but I don't think I have control over the individual colums like I would with a $row=['blah']; do I? It also prints out like this; rather ugly:
Array ( [0] => Array ( [title] => This is the test title entered in the database[0]
What needs to be done to properly use PDO to do this?
A:
change:
while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
to:
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ASP.Net MVC return xml result similar to 37Signals' Highrise API
I was wondering how would one go about returning XML as a result using ASP.Net MVC when the user enters the following url:
http://www.mysite.com/people.xml
If the user enters http://www.mysite.com/people the normal html view should be rendered showing all the people in the database whereas if they add .xml they will get xml containing all the people in the database.
The 37Signals' Highrise API works this way. I know I can use XmlResult but, how would I configure the action to return the normal view if the user does not specify .xml at the end of the url?
A:
If I understood your question right, I think you can solve your problem like this:
public class HomeController : Controller{
public ActionResult Index(string filename){
if(filename != null){
string ext = // parse the filename and get the extension
/*
can't test, but I think
System.IO.Path.GetExtension(filename);
should work
*/
if(ext == "xml"){
// do stuff
return new XmlResult(/* filepath or something */);
}
}
// do stuff
// return the view you want if no filename or not a xml extension
return View();
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Getting a value of a certain JSON object field
I have the following JSON object:
var definitionsObject = {"company" : "Some information about company"};
This object will actually contain a lot of definitions, not just one. And I also have the following event handler for a link click which has a custom "data-name" attribute containing the term "company":
$(".definitinOpener").click(function() {
$this = $(this);
var hintID = $this.attr("data-name");
var hintText = definitionsObject.hintID;
});
So, what I'm trying to do is get the value of "data-name" custom attribute of the clicked link, go to the definitionsObject object and get the value of the field which is equal to the "data-name" attribute value. However in this way I'm always getting "undefined".
Could anybody please help me to figure out what exactly I'm doing wrong?
Thank you beforehand.
A:
You can look up a value in an object in two ways.
var obj = { key : 'value' }
var lookup = 'key'
console.log( obj.lookup ) //undefined
console.log( obj.key ) //value
console.log( obj[lookup] ) //value
You probably want this:
var hintText = definitionsObject[hintID];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Waiting for a button press within a for loop?
I'm not sure how to get around this, but the purpose of my code is to iterate through a csv file and the user searches for a certain item. I have my items read through a string array of type list with CSVReader, so that's not a problem.
When a user searches for an item, I have created a for loop to iterate through the rows and columns of my csv file, and once found will output some code.
What I'm wanting to do, is once the item has been found, it will open up another frame and again the user will make an input through the use of a text field. Then another button is to be pressed and thus continues where we left off in our other for loop in order to execute some code that makes changes. I can only iterate through the for loop once, or else the row and column values will double upon doing so twice.
Here's my code:
editTigerFrame obj = new editTigerFrame();
String getLocation = obj.editLocationField.getText();
javax.swing.JButton saveButt = obj.saveEditButton;
try{
String strSearch = searchSerialField.getText();
CSVReader reader = new CSVReader(new FileReader("test.txt"), ',');
List<String[]> myEntries = reader.readAll();
reader.close();
for (int row = 0; row < myEntries.size(); row++)
{
for (int column = 0; column < myEntries.get(row).length; column++)
{
if (myEntries.get(row)[column].trim().equalsIgnoreCase(strSearch))
{
System.out.println("Found - Your item is on row: " + row + ", column: " + column);
//If serial is found, open the editTigerFrame to edit details
new editTigerFrame().setVisible(true);
//Replace with user input
//When button is pressed in other class, execute this code
System.out.println("Saved");
String newLocation = getLocation;
As you can see near the bottom of the code snippet, once the button is pressed on the other form, execute the code to change a string.
Is there a way to pause and continue within a for-loop?
Thank you for your help, and if you need anything else, please let me know and I will provide.
A:
Is there a way to pause and continue within a for-loop?
Maybe display a JOptionPane asking for using input?
Check out the section from the Swing tutorial on How to Make Dialogs for more information and examples.
If you have more complex data to gather then you would use a modal JDialog.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JPA Query returning nulls - Composite Key with null column
I have a legacy database (Cobol files actually) that I am accessing using a proprietary JDBC driver with Hibernate/JPA.
The Entity has a composite primary key with 2 columns: CODE and SITE.
In the legacy data there are records for the same CODE that can have either a specific value for SITE, or there can be a record with NULL in the SITE column which represents 'All Sites'. The theory of this file is, if you cannot find the CODE for your specific SITE then you lookup the record with NULL in the SITE (the 'catch-all').
I cannot change the structure of this 'table' as it would involve rewriting large parts of the legacy Cobol system which we don't want to do. I also cannot create views of the data.
Now when I do an em.find with the primary composite key class containing a specific code and a null for site, then Hibernate correctly finds the matching record with the NULL value in the column - All good!
But if I try to do a query using em.createQuery similar to the following:
SELECT x FROM TareWeight x WHERE x.pk.code = 'LC2'
for which there are 2 records, it returns a null object in the resulting list for the record with the NULL in the SITE column.
If I take the SQL that Hibernate uses for this query, then the 'database' returns two records, one with the NULL site and one with a specific site. It seems that when Hibernate loads the Entities from these results, it is mapping it to a null Entity object.
So either Hibernate supports it or it doesn't. Why would the em.find work but not the em.createQuery?
I know that this question is similar, but the answers seem to suggest that it is impossible. But clearly Hibernate can do the find correctly, so why does the query not work?
EDIT: OK, so I found a NullableStringType class definition on this Hibernate JIRA Issue and added it to my project.
If I add a @Type definition on the site column of the PK using this type class, then I can successfully get non-null Entities back from the SELECT query, with the site field containing whatever String text I define as the representation of null.
However, it is still behaving differently. The find returns an Entity with the site field containing null, but the query returns an Entity with the site field containing "NaN" (the default representation of null).
It still feels like these should behave the same.
UPDATE 2: Some of you want to know specifics about the 'database' in question.
It is the Genesis RDBMS engine, written by Trifox Inc.. The data is stored in AcuCobol (now Micro Focus) Vision indexed files.
We have the configuration set to translate blank (SPACES) alphanumeric fields to NULL, hence our file records which contain spaces for the PK field are being translated to NULL. I can specifically select the appropriate record by using WHERE site_id IS NULL, so the RDBMS is treating these blank fields as an SQL NULL.
Having said all that I do not believe that this issue has anything to do with the 'database', apart from the fact that it is unusual to have PK fields being null.
What's more, if I log the SQL that Hibernate is using for both the find and the query, they are almost identical.
Here's the SQL for the find:
select tareweight0_.CODE as CODE274_0_, tareweight0_.SITE as SITE274_0_,
tareweight0_.WEIGHT as WEIGHT274_0_ from TARE_WEIGHT tareweight0_
where tareweight0_.CODE=? and tareweight0_.SITE=?
And here's the SQL for the Query:
select tareweight0_.CODE as CODE274_, tareweight0_.SITE as SITE274_,
tareweight0_.WEIGHT as WEIGHT274_ from TARE_WEIGHT tareweight0_
where tareweight0_.CODE=? and tareweight0_.SITE=?
As you can see, the only difference is the column alias names.
UPDATE 3: Here's some example data:
select code, site, weight from tare_weight where code like 'LC%';
CODE SITE WEIGHT
------ ------ -------
LC1 .81
LC2 .83
LC2 BEENLH .81
LC3 1.07
LC3 BEENLH 1.05
LC4 1.05
LCH1 .91
LCH2 .93
LCH2 BEENLH .91
LCH6 1.13
LCH6 BEENLH 1.11
And searching specifically for NULL:
select code, site, weight from tare_weight where code like 'LC%' and site IS NULL;
CODE SITE WEIGHT
------ ------ -------
LC1 .81
LC2 .83
LC3 1.07
LC4 1.05
LCH1 .91
LCH2 .93
LCH6 1.13
A:
"So either they support it or they don't"
TL;DR That expectation/feeling is unjustified. The unsupported functionality in your link (& mine below) is exactly yours. "Not supporting" it means that if you do it then Hibernate can do anything they want. You are lucky that they (seem to) return reasonable values. (Although it's just a guess how they are acting. You don't have a specification.) There is no reason to expect anything, let alone consistency. When behaviour is just a consequence of some unsupported case arising, any "why" is most likely just an artifact of how the code was written with other cases in mind.
Here is a(n old) support thread answered by the Hibernate Team:
Post subject: Composite key with null value for one column
PostPosted: Mon Jul 03, 2006 2:21 am
I have table with composite primary key and I created following
mapping for the table.As it is possible to insert a null value for any
column in composite key as long as the combination of all columns is
Unique, I have record in teh table which has null value for V_CHAR2
column ( which is part of composite key ) . when I execute a query on
this entity I get null values for the records which are having null
value of V_CHAR2 column. What's wrong in my mapping and
implementation..
Posted: Tue Jul 11, 2006 9:09 am
Hibernate Team
a primary key cannot be null (neither fully or partial)
Posted: Sat Jan 06, 2007 5:35 am
Hibernate Team
sorry to disapoint you but null in primary key is not supported -
primarily because doing join's and comparisons will require alot of
painfullly stupid code that is just not needed anywhere else.....think
about it and you will see (e.g. how do you do a correct join with
such a table)
This is not surprising, because NULL is not allowed in a PK column in SQL. A PRIMARY KEY declaration is a synonym for UNIQUE NOT NULL. NULL is not equal to anything with the (misguided) intent that some unrecorded value is not known to be equal. (Your expectations of some kind of exception for at least some occasions of NULL in a PK equaling a NULL in a condition is contrary to SQL.) Given that NULL is not allowed in PK values, we can expect PK optimizations related to 1:1 mappings and to sets rather than bags of rows to assume there are no NULLs when it's convenient. One can expect that Hibernate decided to not worry about what their implementation did with cases that shouldn't arise in the SQL. Too bad they don't tell you that on compilation or execution. Hopefully it is in documentation.)
Even find differing from createQueryre NULL is not surprising. The former involves one value while the latter involves what are expected to be sets (not bags) of rows without NULLs (but aren't).
A workaround may be to not treat any column of a primary key as NULL but as the actual string of spaces in storage. (Whatever this means given your storage/DBMS/hibernate/JPA/Java stack. You haven't given us enough information to know whether your Cobol view of the database would be impeded by not mapping spaces to NULL for your JPA). With your data you can still declare a UNIQUE index on the columns.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use webpack with typescript?
I'm using the example from cycle.js
MyScript.ts
import { run } from '@cycle/run';
import {makeDOMDriver, div, button} from '@cycle/dom';
import _ from 'lodash';
import xs from 'xstream';
function main (sources) {
console.log('Hello World');
const add$ = sources.DOM
.select('.add')
.events('click')
.map(ev => 1);
const count$ = add$.fold((total, change) => total + change, 0);
return {
DOM: count$.map(count =>
div('.counter', [
'Count: ' + count,
button('.add', 'Add')
])
)
};
}
const drivers = {
DOM: makeDOMDriver('.app')
}
run(main, drivers);
When I compile my project, it creates MyScripts.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var run_1 = require("@cycle/run");
var dom_1 = require("@cycle/dom");
function main(sources) {
console.log('Hello World');
var add$ = sources.DOM
.select('.add')
.events('click')
.map(function (ev) { return 1; });
var count$ = add$.fold(function (total, change) { return total + change; }, 0);
return {
DOM: count$.map(function (count) {
return dom_1.div('.counter', [
'Count: ' + count,
dom_1.button('.add', 'Add')
]);
})
};
}
var drivers = {
DOM: dom_1.makeDOMDriver('.app')
};
run_1.run(main, drivers);
//# sourceMappingURL=MyScript.js.map
When I inspect the page in chrome I get
Uncaught ReferenceError: exports is not defined
MyScript.js line 2
This answer says I probably need webpack.
gulp babel, exports is not defined
How do I load webpack? Is it like <script type='javascript' src='webpack' >
A:
I ended up using systemjs as my module loader which requires the correct tson.config as well as the correct mappings in the system.configjs.js file
WebPack is an alternative module loader
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get button that launched the flyout
I have a GridView and in that I have a button with a flyout. I have two methods on the MenuFlyoutItems in which I need to know the buttons properties that invoked the flyout. Is there a way to do it?
My code:
<Button Content="{x:Bind Text}" Name="{x:Bind Id}">
<Button.Flyout>
<MenuFlyout Placement="Bottom">
<MenuFlyoutItem Text="Remove" Click="Remove_Click" />
<MenuFlyoutSeparator/>
<MenuFlyoutItem Text="Select" Click="Select_Click"/>
</MenuFlyout>
</Button.Flyout>
</Button>
A:
ContainerFromItem return GridViewItem. You can get button element using VisualTreeHelper
private void Remove_Click(object sender, RoutedEventArgs e)
{
MenuFlyoutItem mfi = (MenuFlyoutItem)sender;
var datacontext = mfi.DataContext;
GridViewItem item = grd.ContainerFromItem(datacontext) as GridViewItem ;
Button button = FindElementInVisualTree<Button>(item);
}
private T FindElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0) return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
return (T)child;
else
{
var result = FindElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Import failed - Uncaught ReferenceError: function is not defined
I have two JavaScript files, and I'm trying to import and use the first one in the second file. The code I'm trying to import is the following:
let someFunction = function ( elem ) {
// some function stuff
};
And I'm trying to import it and use it in another file like this:
import '../utilities/functions';
const App = App || {};
App.someComponent = () => {
// call the someFunction function here
}
App.someComponent();
However, I get an error in console.log which says Uncaught ReferenceError: someFunction is not defined. The path to the file is correct, but I still can't use the function. Any advice on what am I doing wrong?
A:
Do it like this, in first file:
const someFunction = function ( elem ) {
// some function stuff
};
export default someFunction ;
second file:
import someFunction from '../utilities/functions';
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove elements by their attributes using JQuery
I hope I'm not wasting anyone's time by reproducing a question. I am having difficulty relating my issue with the existing answers.
I am dealing with an xml file containing information relating to films.
I am attempting to use xslt to produce an html file with a button that will eliminate tuples from the table on press. This is a building block that I will then use to construct a more complex web site once I have understood this problem.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<script src="jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function() {
$("button".click(function() {
$("ryear[!='1997']").hide();
});
</script>
<button>Click me to eliminate non-1997 films</button>
</head>
<body>
<h2>A Table of Remade Movies</h2>
<table border="1">
<tr>
<th>Title</th>
<th>Year</th>
<th>Original Title</th>
<th>Original Year</th>
<th>Fraction</th>
</tr>
<xsl:for-each select="remakes/remake">
<tr>
<td><rtitle><xsl:value-of select="rtitle"/></rtitle></td>
<td><ryear><xsl:value-of select="ryear"/></ryear></td>
<td><stitle><xsl:value-of select="stitle"/></stitle></td>
<td><syear><xsl:value-of select="syear"/></syear></td>
<td><fraction><xsl:value-of select="fraction"/></fraction></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Could someone point me in the direction of correcting this code? This solution will allow me to move on to the rest of my problems!
Thanks.
A:
After a conversation with the original poster, we came up with a better way of getting the same functionality:
function loadData(rocol) {
var data = [];
$(rocol).find('remake').each(function(){
data.push([
$(this).find("rtitle").text(),
$(this).find("ryear").text(),
$(this).find("fraction").text(),
$(this).find("stitle").text(),
$(this).find("syear").text()
])
});
return data;
}
$.get("http://neil.computer/stack/movie.xml", function (data) {
$('#example').dataTable( {
data : loadData(data)
} );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" /><script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<table id="example">
<thead>
<tr>
<th>Movie Title</th>
<th>rYear</th>
<th>Fraction</th>
<th>sTitle</th>
<th>sYear</th>
</tr>
</thead>
</table>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
On the probability of no. of radiating particles
Consider an experiment that consists of counting the number of $\beta $ particles
given of in one second time interval by one gram of a radio active material.
It is known that, on the average, 3.2 $\beta$-particles are given off .
What is
a good approximation to the probability that no more than 2 such $\beta$-
particles appear?
I don't know where to start with this problem. How does one calculate the probability that between $x$ particles are given off ? (I hope this makes sense )
Please help . thanks in advance
A:
Because of the nature of radioactive decays, in which the probability for an atom to decay in a short time interval is constant, and that there are an enormous number of atoms to decay (1 gram), the random variable that represents the total number of atoms that decay in a fixed time interval follows the Poisson distribution. Use that distribution to work out the probability that 0, 1, or 2 decays occur in one second, given that the expectation value is 3.2.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pickling object instance gives TypeError: __new__() missing required positional arguments
I am creating a board game in python that requires me to send objects created by a custom Hex() class that is a subclass of tuple. The problem I face is that when the server receives the pickled message (a tuple containing a string and the Hex object), it throws the following Error:
TypeError: __new__() missing 2 required positional arguments: 'r' and 's'
I'm relatively new to OOP but I believe that the server is attempting to create the Hex object when it unpacks the tuple message, however it obviously doesn't have the required information to recreate the original object as it is all packaged up in the object itself.
If anyone could suggest a way I can successfully send my Hex object from client to server and back that would be appreciated.
Code below:
server.py
import socket
import pickle
HOST = '127.0.0.1'
PORT = 57343
SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
SOCK.bind((HOST, PORT))
SOCK.listen()
print('Server active, waiting for connections...')
conn, addr = SOCK.accept()
print('Connected to:', addr)
conn.send(pickle.dumps('conn test'))
print('test message sent to', conn)
while True:
try:
print('waiting for data')
data = pickle.loads(conn.recv(2048))
command, info = data
if command == 'move':
print('Received message', data)
elif command == 'get':
pass
conn.sendall(pickle.dumps('game'))
except (EOFError, ConnectionResetError) as err:
print(err)
break
print('Lost connection')
conn.close()
client.py
import tmp_hex_lib as hl
from network import Network
def main():
game_over = False
moves = []
attack_switch = False
net = Network()
net.get_player()
while not game_over: # main game loop
try:
net.send(('get', None))
except:
game_over = True
print("Couldn't find game")
break
selected_hex = hl.Hex(-13, 10, 3)
print('selected_hex has type:', type(selected_hex))
moves.append(selected_hex)
if attack_switch:
net.send(('attack', None))
else:
net.send(('move', 'this message works'))
net.send(('move', selected_hex)) # if any other type is sent, game runs fine
attack_switch = False
if __name__ == '__main__':
main()
network.py
import socket
import pickle
class Network:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "127.0.0.1"
self.port = 57343
self.addr = (self.server, self.port)
self.player = self.connect()
def get_player(self):
return self.player
def connect(self):
try:
self.client.connect(self.addr)
print('connecting to server')
data = pickle.loads(self.client.recv(2048))
print('Received data:', data)
return data
except EOFError as err:
print(err)
def send(self, data):
try:
self.client.send(pickle.dumps(data))
return pickle.loads(self.client.recv(2048))
except socket.error as err:
print(err)
tmp_hex_lib.py
class Hex(tuple):
def __new__(self, q, r, s):
return tuple.__new__(self, (q, r, s))
def __init__(self, q, r, s):
self.q = q
self.r = r
self.s = s
assert not (round(q + r + s) != 0), "q + r + s must be 0"
A:
So after consulting the pickle documentation, I found a passage about pickling class instances. It seems that if you are defining your own __new__() method, you must also define a method __getnewargs__(self) that returns all the variables required by __new__() as a tuple. For instance (no pun intended) my case would be:
tmp_hex_lib.py
class Hex(tuple):
def __new__(self, q, r, s):
return tuple.__new__(self, (q, r, s))
def __getnewargs__(self):
return self.q self.r, self.s
def __init__(self, q, r, s):
self.q = q
self.r = r
self.s = s
assert not (round(q + r + s) != 0), "q + r + s must be 0"
Hope this helps others!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Definition of Gauge group
I have a problem with an example of Gauge group. I'm reading ""Yang-Mills equations over Riemann surfaces"" (Atiyah, Bott). Let $P$ be a principal $G$-bundle over $X$. We define the adjoint bundle
$AdP:= P \times_G G$. For example we can consider
$$ S^1 \to S^3 \to \mathbb{C}P^1 ,$$
so $AdS^3=S^3 \times_{S^1} S^1$. Then
$$ pt \to S^3 \times_{S^1} S^1 \to S^3 .$$
But in this way the fibre of $AdP$ is always a point. Is it true?
How can I describe the sections of $AdS^3$?
A:
You're not applying the definition of $\mathrm{Ad}(P)$ correctly.
Recall the associated bundle construction: If $\pi: P \rightarrow X$ is a principal $G$-bundle over $X$, $F$ is a topological space, and we have a homomorphism $\rho: G \longrightarrow \mathrm{Homeo}(F)$, we can form a new fiber bundle $F \hookrightarrow P \times_\rho F \xrightarrow{~\pi_\rho~} X$ where
$$E \times_\rho F = P \times F/\langle(p.g, f) \sim (p,\rho(g)(f))\rangle,$$
and the projection $\pi_\rho: P \times_\rho F \longrightarrow X$ is defined by
$$\pi_\rho([p, f]) = \pi(p).$$
Note that $P \times_\rho F$ is a fiber bundle with structure group $G$ and fiber $F$.
For the construction of $\mathrm{Ad}(P)$, one takes $F = G$ and $\rho$ is defined by
$$\rho(g)(h) = ghg^{-1}.$$
Then $\mathrm{Ad}(P) = P \times_\mathrm{Ad} G$ is a fiber bundle with fiber $G$ and structure group $G$.
In particular, for your example $P$ is the Hopf fibration $S^1 \hookrightarrow S^3 \to S^2$, and $\mathrm{Ad}(P)$ is a circle bundle over $S^2 = \Bbb C P^1$. Note that the fiber is a circle, not a point!
In general, sections of $\mathrm{Ad}(P)$ can be identified with $\mathrm{Ad}$-equivariant maps $f: P \longrightarrow G$, i.e. maps $f$ satisfying
$$f(p.g) = gf(p)g^{-1}.$$
Write $\Gamma(\mathrm{Ad}(P))$ for the space of sections of $\mathrm{Ad}(P)$. Then $\Gamma(\mathrm{Ad}(P))$ has the structure of a group if we define the product of $f, g: P \longrightarrow G$ pointwise:
$$(fg)(p) = f(p)g(p),$$
where the product on the right-hand side is the multiplication in $G$. Clearly $fg$ still satisfies the $\mathrm{Ad}$-equivariance property. We call this group $\Gamma(\mathrm{Ad}(P))$ the gauge group of $P$ and denote it by $\mathscr{G}(P)$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
When the CPU is in kernel mode, can it read and write to any register?
When the CPU is in kernel mode, can it read and write to any register, or are there some registers that are inaccessible even in kernel mode?
A:
On x86, there aren't banked registers so all the registers are architecturally visible at the same time.
And yes, in kernel mode (ring 0) x86 can write any register. (As long as the kernel is running in 64-bit mode, otherwise it can't access x/ymm8..16 or zmm8..31, or r8..r15).
And yes, a kernel that switches to 32-bit mode after entering the kernel from 64-bit userspace is possible; Solaris x86-64 apparently did this, and MacOS X used to do this for compatibility with 32-bit kernel drivers. On machines with less than 4GB of RAM and smaller caches, using smaller pointers in the kernel has some benefits and the downsides maybe aren't as huge.
wrmsr (Write Model-Specific Register) requires kernel mode. So does rdmsr to read MSRs. So unlike the integer and vector regs (rax..rsi/r8..r15 and xmm0..15), which user-space can freely use, there are registers that only the kernel can modify.
There might possibly be some model-specific regs that are only accessible in system-management mode. (sometimes called ring -1) I don't know, I haven't read much about SMM. And/or registers associated with SGX (used for "enclaves), which again I haven't looked into.
There might also be some read-only MSRs that you can never write with wrmsr. IDK if that's what you mean, or if you're only counting registers that are normally considered part of the architectural state that's saved/restored on context switches, like the general-purpose integer registers. All of those regs are writeable in any mode, even segment regs.
The internal segment base/limit registers are not directly readable, but in 64-bit long mode they're fixed at base=0 / limit=-1 except for FS and GS. But those bases are accessible with rdmsr/wrmsr on MSR_GS_BASE / MSR_FS_BASE.
The FSGSBASE ISA extension added wrfsbase etc. which does let you more directly read/write the FS and GS bases, more efficiently than the MSR. (Either way, the kernel doesn't have to actually modify a GDT or LDT entry and reload fs to update the fs base for thread-local storage). Detail about MSR_GS_BASE in linux x86 64
But I don't think the cs/ds/es/ss base/limit are exposed via MSRs, and those are relevant for 32-bit protected mode. (Or for switching back to real mode to create "unreal" mode.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use Frama-Clang to parse C++ programs
I have installed the plugin Frama-Clang of Frama-c to parse C++ programs. However, I don't know how to correctly use it. I tried it with a very simple c++ program but failed.
Here is the code of test.cpp:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
I used the command frama-c test.cpp and got the following error:
[kernel] Parsing test.cpp (external front-end)
In file included from test.cpp:1:
In file included from /home/server3/.opam/system/share/frama-c/frama-clang/libc++/iostream:29:
/home/server3/.opam/system/share/frama-c/frama-clang/libc++/ostream:31:40: error: implicit instantiation of undefined template 'std::basic_ios<char, std::char_traits<char> >'
class basic_ostream : virtual public basic_ios<charT,traits> {
^
test.cpp:5:10: note: in instantiation of template class 'std::basic_ostream<char, std::char_traits<char> >' requested here
cout << "Hello, world!" << endl;
^
/home/server3/.opam/system/share/frama-c/frama-clang/libc++/iosfwd:37:68: note: template is declared here
template <class charT, class traits = char_traits<charT> > class basic_ios;
^
code generation aborted due to one compilation error
[kernel] User Error: Failed to parse C++ file. See Clang messages for more information
[kernel] User Error: stopping on file "test.cpp" that has errors.
[kernel] Frama-C aborted: invalid user input.
Can someone tell me how to successfully parse it?
A:
Your usage is correct: simply give it a .cpp file and it will try to parse it.
However, Hello World using <iostream> is not the best example due to the size and complexity of the STL: your program, after preprocessing, contains between 18k and 28k lines (depending on whether I use g++ or clang).
As indicated in the Frama-Clang webpage,
Frama-Clang is currently in an early stage of development. It is known to be incomplete (...)
Handling the STL is indeed one of the major difficulties in supporting C++, and currently under development.
If you try with a non-STL file, you should have better results. Part of the STL is supported, but there is no comprehensive list of which classes are and which aren't (as this is continually evolving).
For instance, the toy example below, which uses std::exception, templates and classes, is successfully parsed by Frama-Clang (despite a few warnings), simply by running frama-c test.cpp.
#include <exception>
class empty_stack: public std::exception {
virtual const char* what() const throw() {
return "stack is empty!";
}
};
class full_stack: public std::exception {
virtual const char* what() const throw() {
return "stack is full!";
}
};
template <class T>
class Stack {
private:
T elems[10];
unsigned index;
public:
Stack() {
index = 0;
}
void push(T const&);
T pop();
T top() const;
bool empty() const {
return index == 0;
}
};
template <class T>
void Stack<T>::push (T const& elem) {
if (index >= 10) throw new full_stack();
elems[index++] = elem;
}
template <class T>
T Stack<T>::pop () {
if (index == 0) throw new empty_stack;
return elems[--index];
}
template <class T>
T Stack<T>::top () const {
if (index == 0) throw new empty_stack;
return elems[index-1];
}
int main() {
try {
Stack<int> intStack;
intStack.push(7);
intStack.push(42);
return intStack.pop();
} catch (char* ex) {
return -1;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Proof of existence of subspaces that sum up to the vector space
How to go about proving this statement?
Suppose V is finite dimensional and U is a subspace of V . Prove that there exists a subspace W of V such that V = U + W and U ∩ W = {0}, where 0 is the additive identity of V .
A:
Take a basis $B$ of $U$, and complete this basis $B\cup B_c$ into a basis of $V$
$W = \text{Span}(B_c)$ is a possible answer
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.