source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"softwareengineering.stackexchange",
"0000358924.txt"
] | Q:
Is it a bad idea to use getters/setters and/or properties at all?
I am perplexed by comments under this answer: https://softwareengineering.stackexchange.com/a/358851/212639
A user is arguing there against the use of getters/setters and properties. He maintains that most times using them is a sign of a bad design. His comments are gaining upvotes.
Well I'm a novice programmer, but to be honest, I find the concept of properties very appealing. Why shouldn't an array allow resizing by writing to its size or length property? Why shouldn't we get all elements in a binary tree by reading its size property? Why shouldn't a car model expose its maximum speed as a property? If we're making an RPG why shouldn't a monster have its Attack exposed as a getter? And why shouldn't it expose its current HP as a getter? Or if we're making a home design software why shouldn't we allow recoloring a wall by writing into its color setter?
It all sounds so natural, so obvious to me, I could never reach a conclusion that using properties or getters/setters might be a warning sign.
Is using properties and/or getters setters usually a bad idea and if so, why?
A:
Simply exposing fields – whether as public fields, properties, or accessor methods – can be an indicator of insufficient object modelling. The result is that we ask an object for various data and make decisions on that data. So these decisions will be made outside of the object. If this happens repeatedly, maybe that decision should be the responsibility of the object, and should be provided by a method of that object: We should tell the object what to do, and it should figure out how to do that on its own.
Of course this is not always appropriate. If you overdo this, your objects end up with a wild collection of many small unrelated methods that are only used once. Maybe, it is better to keep your behaviour separate from your data and choose a more procedural approach. That is sometimes called an “anemic domain model”. Your objects then carry very little behaviour, but expose their state through some mechanism.
If you expose any kind of properties, you should be consistent, both in naming and in technique used. How to do this depends mostly on the language. Either expose all as public fields, or all via properties, or all via accessor methods. E.g. don't combined a rectangle.x field with a rectange.y() method, or a user.name() method with a user.getEmail() getter.
One issue with properties and especially with writeable properties or setters is that you risk weakening the encapsulation of your object. Encapsulation is important because you can reason about correctness of your object in isolation. This modularization allows you to comprehend complex systems more easily. But if we access fields of an object instead of issuing high-level commands, we become increasingly coupled to that class. If arbitrary values may be written to a field from outside an object, it becomes very difficult to maintain a consistent state for the object. It is the responsibility of the object to keep itself consistent, and that means validating incoming data. E.g. an array object must not have its length set to a negative value. This kind of validation is impossible for a public field and easy to forget for an autogenerated setter. It is more obvious with a high-level operation like array.resize().
Suggested search terms for further info:
Tell, don't ask
Anemic Domain Model
Uniform Access Principle
A:
It is not an inherently bad design, but like any powerful feature it can be abused.
The point of properties (implicit getter and setter methods) is that they provide a powerful syntactic abstraction allowing consuming code to treat them logically as fields while retaining control for the object that defines them.
While this is often thought of in terms of encapsulation, it often has more to do with A controlling state, and B with syntactic convenience for the caller.
To get some context, we first have to consider the programming language itself.
While many languages have "Properties", both terminology and the capabilities vary dramatically.
The C# programming language has a very sophisticated notion of properties on both the semantic and a syntactic level. It allows either the getter or setter to be optional, and it critically allows them to have different visibility levels. This makes a big difference if you wish to expose a fine grained API.
Consider an assembly that defines a set of data structures that are by nature cyclic graphs. Here is a simple example:
public sealed class Document
{
public Document(IEnumerable<Word> words)
{
this.words = words.ToList();
foreach (var word in this.words)
{
word.Document = this;
}
}
private readonly IReadOnlyList<Word> words;
}
public sealed class Word
{
public Document Document
{
get => this.document;
internal set
{
this.document = value;
}
}
private Document document;
}
Ideally, Word.Document would not be mutable at all, but I cannot express that in the language. I could have created an IDictionary<Word, Document> that mapped Words to Documents but ultimately there will be mutability somewhere
The intent here is to create a cyclic graph such that any function that is given a word can query the Word as to its containing Document by way of the Word.Document property (getter). We also want to prevent mutation by consumers after the Document has been created. The only purpose of the setter is to establish the link. It is only meant to be written once. This is hard to do because we have to create the Word instances first. By using C#'s ability to ascribe different levels of accessibility to the getter and setter of the same property, we are able to encapsulate the mutability of the Word.Document property within the containing assembly.
Code consuming these classes from another assembly will see the property as read-only (as only having a get not a set).
This example leads me to my favorite thing about properties. They can have a getter only. Whether you simply want to return a computed value or whether you want to expose only the ability to read but not to write, the use of properties is actually intuitive and simple for both the implementation and the consuming code.
Consider the trivial example of
class Rectangle
{
public Rectangle(double width, double height) => (Width, Height) = (width, height);
public double Area { get => Width * Height; }
public double Width { get; private set; }
public double Height { get; private set; }
}
Now, as I said previously, some languages have different concepts of what a property is. JavaScript is one such example. The possibilities are complex. There are a multitude of ways in which a property can be defined by an object and their are very different ways in which visibility can be controlled.
However, in the trivial case, as in C#, JavaScript allows properties to be defined such that they expose only a getter. This is wonderful for controlling mutation.
Consider:
function createRectangle(width, height) {
return {
get width() {
return width;
},
get height() {
return height;
}
};
}
So when should properties be avoided? In general, avoid setters that have logic. Even simple validation is often better accomplished elsewhere.
Going back to C#, it is often tempting to write code such as
public sealed class Person
{
public Address Address
{
get => this.address;
set
{
if (value is null)
{
throw new ArgumentException($"{nameof(Address)} must have a value");
}
this.address = value;
}
}
private Address address;
}
public sealed class Address { }
The exception thrown is likely a surprise to consumers. After all, Person.Address is declared mutable and null is a perfectly valid value for a value of type Address. To make matters worse, an ArgumentException is being raised. The consumer may not be aware that they are calling a function and so the type of the exception adds even more to the surprising behavior. Arguably, a different exception type, such as InvalidOperationException would be more appropriate. However, this highlights where setters can get ugly. The consumer is thinking of things in different terms. There are times when this sort of design is useful.
Instead, however, it would be better to make Address a required constructor argument, or create a dedicated method for setting it if we must expose write access, and expose a property with only a getter.
I will add more to this answer.
A:
Adding getters and setters reflexively (that is, without thought, not to be confused with doing it reflectively as per the question you link) is a sign of problems. First of all, if you have passthrough getters and setters for fields, why not just makes the fields public? For example:
class Foo
{
private int _i;
public int getData() { return _i; }
public void setData(int i) { _i = i; };
}
What you have done above is just make it hard to use the data, and difficult to read using code. Rather than just doing foo.i += 1 you're forcing the user to do foo.setData(foo.getData() + 1), which is just obtuse. And for what benefit? Supposedly you're doing getters and setters for encapsultation and/or data control, but if you have a passthrough public getter AND setter you don't need either of those anyway. Some people argue that you might want to add data control later, but how often is that done in practice? If you have public getters and setters you're already working at a level of abstraction were you simply are not doing that. And on the off-chance that you will, you can just fix it at that point.
Public getters and setters are a sign of cargo-cult programming, where you are just following rote rules because you believe they make your code better, but haven't acctually thought about whether or not they do. If you're code base is filled with getters and setters consider why it is that you are simply not working with PODs, perhaps that is just a better way to work with data for your domain?
The criticism to the original question is not that getters or setters are a bad idea, it is that just adding public getters and setters for all fields as a matter of principle doesn't actually do anything good.
|
[
"stackoverflow",
"0000937573.txt"
] | Q:
Changing the user agent of the WebBrowser control
I am trying to change the UserAgent of the WebBrowser control in a Winforms application.
I have successfully achieved this by using the following code:
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(
int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
const int URLMON_OPTION_USERAGENT = 0x10000001;
public void ChangeUserAgent()
{
List<string> userAgent = new List<string>();
string ua = "Googlebot/2.1 (+http://www.google.com/bot.html)";
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, ua, ua.Length, 0);
}
The only problem is that this only works once. When I try to run the ChangeUserAgent() method for the second time it doesn't work. It stays set to the first changed value. This is quite annoying and I've tried everything but it just won't change more than once.
Does anyone know of a different, more flexible approach?
Thanks
A:
The easiest way:
webBrowser.Navigate("http://localhost/run.php", null, null,
"User-Agent: Here Put The User Agent");
A:
I'm not sure whether I should just copy/paste from a website, but I'd rather leave the answer here, instead of a link. If anyone can clarify in comments, I'll be much obliged.
Basically, you have to extend the WebBrowser class.
public class ExtendedWebBrowser : WebBrowser
{
bool renavigating = false;
public string UserAgent { get; set; }
public ExtendedWebBrowser()
{
DocumentCompleted += SetupBrowser;
//this will cause SetupBrowser to run (we need a document object)
Navigate("about:blank");
}
void SetupBrowser(object sender, WebBrowserDocumentCompletedEventArgs e)
{
DocumentCompleted -= SetupBrowser;
SHDocVw.WebBrowser xBrowser = (SHDocVw.WebBrowser)ActiveXInstance;
xBrowser.BeforeNavigate2 += BeforeNavigate;
DocumentCompleted += PageLoaded;
}
void PageLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
void BeforeNavigate(object pDisp, ref object url, ref object flags, ref object targetFrameName,
ref object postData, ref object headers, ref bool cancel)
{
if (!string.IsNullOrEmpty(UserAgent))
{
if (!renavigating)
{
headers += string.Format("User-Agent: {0}\r\n", UserAgent);
renavigating = true;
cancel = true;
Navigate((string)url, (string)targetFrameName, (byte[])postData, (string)headers);
}
else
{
renavigating = false;
}
}
}
}
Note: To use the method above you’ll need to add a COM reference to “Microsoft Internet Controls”.
He mentions your approach too, and states that the WebBrowser control seems to cache this user agent string, so it will not change the user agent without restarting the process.
A:
Also, there is a refresh option in the function (according to MSDN). It worked well for me (you should set it before any user agent change). Then the question code could be changed like this:
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(
int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
const int URLMON_OPTION_USERAGENT = 0x10000001;
const int URLMON_OPTION_USERAGENT_REFRESH = 0x10000002;
public void ChangeUserAgent()
{
string ua = "Googlebot/2.1 (+http://www.google.com/bot.html)";
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT_REFRESH, null, 0, 0);
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, ua, ua.Length, 0);
}
|
[
"stackoverflow",
"0046896986.txt"
] | Q:
Best way to access variable in a loop from a different file
I have a script that has 2 files, diff.py and login.py
Here is what I have in diff.py:
domains = ("rt", "tc", "mfg", "ltd")
i = 0
while i<len(domains):
# Opens a files containing different items
with open("Files/"+domains[i]+"-diff_list.txt", 'r') as f:
g = f.readlines()
newList = map(lambda s: s.strip(), g)
print "New " +domains[i]+" List: ", newList
f.close()
i += 1
Here is what I have in login.py:
import diff
host = diff.newList
hostDomain = diff.domains
while i < len(host):
print "\nLogging into", host[i], "\n"
login(user, password, host[i], timeout)
** Code omitted: Applying setting for that domains **
i += 1
As you can see the issue is I will always get only "ltd" domain hosts as each loop overwrites newList variable with new info and since "ltd" is the last item, it always returns only that.
What is the best way I can access all items for each domain separately? I do not want all items in one list and would like to keep them in separate variables.
I was leaning towards dynamic variables but heard its a bad idea .. ofcourse this doesn't work but I was thinking doing this:
newList+domain[i] = map(lambda s: s.strip(), g)
#I was hoping this would give me 4 variables ..
#newListrt, newListtc, newListmfg and newListltd
Thanks
A:
You do not need 2 files for the example you provided. If you need to split up large code then you should write functions. Without knowing what your entire code is doing below is an example re-written in the way I describe.
domains = ["rt", "tc", "mfg", "ltd"]
def get_diff_lists():
result = []
with open(filename, 'r') as f:
result = map(lambda s: s.strip(), f.readlines())
return result
for domain in domains:
hosts = get_diff_list("Files/" + domain + "-diff_list.txt")
for host in hosts:
login(user, password, host, timeout)
As you stated these need to be in seperate files then you can use functions and generators to acheive this.
File #1
domains = ["rt", "tc", "mfg", "ltd"]
def get_diff_list():
for domain in domains:
with open("Files/" + domain + "-diff_list.txt", 'r') as f:
yield map(lambda s: s.strip(), f.readlines())
File #2
from diff import get_diff_list
for diff_list in get_diff_list():
for host in diff_list:
login(user, password, host, timeout)
If you find an error I'm doing this off the top of my head.
I suggest reading some basic programming books as this isn't specific to Python.
|
[
"stackoverflow",
"0005310328.txt"
] | Q:
getting the object passed to the NSThread selector
When I'm creating an NSThread I pass it a number that I want the process to be aware of. I can understand how to set the number but I cannot figure out how to read the number from the thread selector method so that I can then pass it to a timer.
How do you do it?
-(void) setthread
{
//passing the number to the selector here fine
NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread) object:[NSNumber numberWithInt:index]];/
[timerThread setThreadPriority:0.5];
[timerThread start]; //start the thread
}
// don't get how to read the value passed to this selector
-(void) startTimerThread
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[[NSTimer scheduledTimerWithTimeInterval: 0.1
target: self
selector: @selector(timerTick:)
userInfo: thenumberhere
repeats: YES] retain];
[runLoop run];
[pool release];
}
- (void)timerTick:(NSTimer *)timer
{
//code
}
A:
You're specifying your selector wrong:
@selector(startTimerThread) // we are missing ':' at the end
It should have : at the end, like so:
@selector(startTimerThread:)
This indicates it's a selector which takes one parameter.
Then take in the parameter in your startTimerThread method:
-(void) startTimerThread:(NSNumber *)myNumber {
// ... etc
|
[
"scifi.stackexchange",
"0000091390.txt"
] | Q:
"Tea, Earl Grey, Hot" and archaeology
If I'm not mistaken two important parts of Picard's character were introduced in the same episode of TNG, "Contagion", in the space of three lines:
PICARD: Archaeology has been a hobby since my Academy days. But why don't we talk about what really brought you here?
WESLEY: It's the Yamato, Captain. I can't stop thinking about her. All those people dead. I don't know how you and Commander Riker and Geordi, how you handle it so easily.
PICARD: Easily? Oh no, not easily. We handle it because we're trained to, as you will be. Tea, Earl Grey, hot. But if the time ever comes when the death of a single individual fails to move us (a pot plant appears in the replicator)
WESLEY: Didn't you order tea, sir?
PICARD: Now that should not have happened.
(Source, emphasis mine)
Is this a coincidence, or was there some deliberate attempt to introduce more backstory and mannerisms around the same time?
A:
I believe the OP is correct that the sudden introduction of these two facets of Picard's character is no coincidence.
First of all, drastic changes in the writing personnel between Season 1 and Season 2 are what paved the way for new character developments:
There were significant changes backstage to the writing team. Maurice Hurley became head writer, and following extensive re-writes to "The Royale" and "Manhunt", Tracy Tormé left the writing team. Likewise, following the submission of a script for "Blood and Fire", David Gerrold allowed his contract to run out due to issues with Gene Roddenberry and Leonard Maizlish, Roddenberry's lawyer. Other departing writers included Leonard Mlodinow and Scott Rubenstein, while Melinda M. Snodgrass, Hans Beimler, and Richard Manning joined the team.
(Source)
The new staff made the decision to focus more on Picard, Riker, and Data, in order to foster a Kirk-McCoy-Spock triangle that was felt to be missing in TNG thus far:
A further change seen in Season 2, which increased later in the season, was an increasing focus on the trio of Captain Jean-Luc Picard, Commander William T. Riker and Lt Cmdr. Data, reminiscent of Captain James T. Kirk, Dr. Leonard McCoy and Commander Spock in Star Trek: The Original Series. This relegated the other cast members to background roles for the majority of episodes.
(Source)
As "Contagion", the episode the OP is referring to, was the 11th episode (exactly halfway through the season), it is likely that Picard's archaeology obsession and Earl Grey tea addiction were part of this "increasing focus".
A:
TL;DR: Yes, this was likely a deliberate attempt to give Picard more "character".
As others have stated, Season 2 saw a pointed effort to put more focus on Picard as a character. As a result, the producers decided that Picard would be a man with classic interests and that his favorite beverage would be tea.
Patrick Stewart discusses this briefly in an interview from 1998:
Q: In Star Trek you drink a lot of Earl Grey. Do you see that as a
man's tea?
A: When it first came up that Captain Picard was going to drink a lot
of tea I suggested lapsang souchong, but the producers thought that
nobody would know what it was. I must urge people not to send me any
more Earl Grey. I've got so much of it now I could open a tea shop.
Source: Neon Magazine, July 1998, interview by Ben Mitchell
As for the archaeology, Stewart has also mentioned on numerous occasions that - following the success of Season 1 - he had an increasing amount of input into Picard as a character. Since Stewart himself has interests in both history & theatre, it's not a huge assumption that this influenced Picard's interests as well.
|
[
"stackoverflow",
"0025207263.txt"
] | Q:
Button inside ListView item in Android - how to make it part of the onItemClickListener
I am building a ListView that includes a TextView and a button.
I simply put the button so the user will know he can press the list item.
But thie forces one to either define specific OnClick listener to the button and write a lot of code or make a TextView that looks like a button but this caused the text in the button to be gray when item inside is not clicked.
Here is the resource file for the list item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/channelListEntry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|left"
android:background="@color/white"
android:orientation="vertical"
>
<RelativeLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
>
<TextView
android:id="@+id/titleText"
android:layout_height="fill_parent"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="@+id/channelButton"
android:layout_height="fill_parent"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:background="@drawable/search_result_button"
android:layout_marginRight="10dp"
android:padding="2dp"
android:text=" Play "
/>
</RelativeLayout>
</LinearLayout>
A:
I found the solution.
Just add the following to the TextView named channelButton:
android:textColor="#000000"
And this made the text color of the TextView (that looks like button) always black (and not only when the item is clicked).
SoftCoder: In our app, we are afraid the user will just look at the list entries and would not know there is an action to be taken when clicking the item.
So what I did is used a TextView with the shape of a button.
|
[
"stackoverflow",
"0005540510.txt"
] | Q:
Ironpython query
I have a setup file ready with all the references I need to run the python classes. However, as I do not know much python, I would like to use C# to be able to improve this program as part of my thesis study. I was told IronPython is a wrapper class that can be used to invoke methods on behalf of python using .NET.
how exactly should I go about doing this? does anyone have any code examples? Also do I need to include the references in some path for ironpython to use?
A:
Maybe this will be useful: http://www.ironpython.net/documentation/dotnet/
|
[
"stackoverflow",
"0052957227.txt"
] | Q:
Kubectl command to list pods of a deployment in Kubernetes
Is there a way to use kubectl to list only the pods belonging to a deployment?
Currently, I do this to get pods:
kubectl get pods| grep hello
But it seems an overkill to get ALL the pods when I am interested to know only the pods for a given deployment. I use the output of this command to see the status of all pods, and then possibly exec into one of them.
I also tried kc get -o wide deployments hellodeployment, but it does not print the Pod names.
A:
There's a label in the pod for the selector in the deployment. That's how a deployment manages its pods. For example for the label or selector app=http-svc you can do something like that this and avoid using grep and listing all the pods (this becomes useful as your number of pods becomes very large):
$ kubectl get pods -l=app=http-svc
or
$ kubectl get pods --selector=app=http-svc
|
[
"puzzling.stackexchange",
"0000060546.txt"
] | Q:
Find the missing digits
How to solve these missing number questions, and what logic should be applied to solve these type of questions?
A:
First Answer :
8, 1 Logic: The phrasing of the question (number instead of numbers) provides the clue that each pair of digits in a row forms a two-digit number. So representing the grid as two-digit numbers we have: 73, 46, 19 (delta -27) 11, 9, 7 (delta -2) 52, 42, 32 (delta -10)99, 50, 1 (delta -49) 67, 82, 97 (delta 15) 15, 48, 81 (delta 33)
Second Answer may be :
Answer : 7 Logic : In each row of the diagram, the central value equals the sum of the differences between the left hand pair of numbers and the right hand pair of numbers.
|
[
"stackoverflow",
"0037744701.txt"
] | Q:
How to jump to the Android implementation source file in Android Studio
in Android Studio (2.2 Preview 2), I have the sdk sources attached and I can also jump to the interfaces of android sources: e.g. when I CTRL-click on SharedPreferences, the file ~/Android/Sdk/sources/android-23/android/content/SharedPreferences.java is opened.
But now I also want to jump to the implementation of this interface - or a member function e.g. getFloat()
How can this be done?
notes:
clicking CTRL-ALT-B only show the error no implementations found
the relevant file SharedPreferencesImpl.java exists in the location where I expect it: ~/Android/Sdk/sources/android-23/android/app
the compileSdkVersion is set to 23 in my build.gradle file
A:
I found a workaround to easily get me to the implementation file:
Set the cursor to the interface-name SharedPreferences
Open the Find Usages dialogue (e.g. press CTRLALTSHIFT7). In the Scope box select Project and Libraries.
Click the Find button and the SharedPreferencesImpl class will show up in Found usages (under the Android API 23 Platform node)
|
[
"ru.stackoverflow",
"0000174826.txt"
] | Q:
В чем заключается суть паттерна EAO?
Искал и читал на английском, но смысла так и не понял.
A:
Entity Access Object - это некая вариация на тему старого доброго DAO (Data Access Object), только уже применительно к ентити бинам (EJB) или говоря строго версия DAO с поддержкой операций CRUD (Create, Read, Update, Delete).
DAO, в свою очередь, это паттерн для разделения кода доступа к данным от бизнес-логики
|
[
"stackoverflow",
"0050920981.txt"
] | Q:
Fortran DO loop over generic set of indices?
I have an N-dimensional dataset (say real numbers) which is stored as a 1D array with an additional dimension array which specifies the original dimensions.
In addition, the functions to deduce the 1-D index from an N-D index and vice-versa are given.
I'm trying to figure out how do I make a do-loop (or equivalent) for the generic N-dimensional index (which will be transformed to 1D index of course) from some set of limiting lower indices to a set of upper indices.
So I need an "N-dimensional" loop which does not go over all of the values - only a portion of the array, therefore doing the linear index of an equivalent 1D array is not relevant (at least without modifications).
This is a schematic of my problem:
subroutine Test(Array,Dims,MinIndex,MaxIndex)
implicit none
real , dimension(1:), intent(inout) :: Array
integer, dimension(1:), intent(in) :: Dims,MinIndex,MaxIndex
integer, dimension(size(Dims)) :: CurrInd
integer :: 1Dindex
! size(Dims) can be 1, 2, 3 ,..., N
! size(MinIndex)==size(MaxIndex)==size(Dims)
! size(Array)==Product(Dims)
! 1Dindex=Get1dInd(NDindex,Dims)
! NDindex=GetNdInd(1Dindex,Dims)
! How do I actually preform this?
do CurrInd=MinIndex,MaxIndex
1Dindex=Get1dInd(CurrInd,Dims)
<Some operation>
enddo
end subroutine
I figured it is possible to loop over the Dims array and use an inner loop but I don't manage to write the procedure down properly.
Another option that didn't work for me (maybe because I use it incorrectly?) is FORALL, as that requires each index to be specified separately.
A:
If you knew the dimensions of your arrays at compilation time you could do a series of nested DO loops, each of them running between pairs of components of MinIndex and MaxIndex. Since you don't know the dimensions, that's not possible.
The easiest strategy I can think of is to loop with a single DO loop over all the 1D indices. For each of them, compute the N-dimensional index, and check if it is within the bounds provided by MinIndex and MaxIndex: if it is, continue doing what you need; if it is not, discard that 1D index and go to the next one. If the indices are sequential you may be able to do something smarter that skips blocks of indices that you know you will not be interested in.
do OneDindex = 1, size(Array)
CurrInd = GetNDInd(OneDindex, Dims)
if ((any(CurrInd<MinIndex)) .or. (any(CurrInd>MaxIndex))) cycle
! <Some operation>
end do
Note that, as far as the index manipulation is concerned, this strategy is compatible with parallelising the loop.
Also note that Fortran variables must start with a letter: 1Dindex is not a valid Fortran variable name.
|
[
"stackoverflow",
"0053655770.txt"
] | Q:
I want to change Vue components with media Queries
In my App.vue I've set my template like this
<app-header></app-header>
<router-view></router-view>
<app-footer ></app-footer>
app-header sets a header component to every other component of my project (so I don't have to repeat myself). app-footer does the same, but with a common footer for all of my components.
This works perfect with my Desktop web, but for Mobile I would like to change the header component to a new-header.vuecomponent, and I would like to get rid of the Footer when using a mobile device so it doesn't use screenspace.
How can I achieve this? I tried to use app-footer {display: none;} in a media query at App.Vue but its not working.
A:
You do not want to use CSS to hide. The beauty of Vue is that in the case of mobile, the code will not even be generated at all.
Use a v-if directive, and add an isMobile property to your data, computed, store, etc. Or call a method to get it.
<app-footer v-if='!isMobile'></app-footer>
For the header, there are 2 ways. Using a component element with v-bind:is to swap in the correct one, or using v-if and v-else
<app-header v-if='!isMobile'></app-header>
<app-header-mobile v-else></app-header-mobile>
Here is the official link to the Vue dynamic component approach.
https://vuejs.org/v2/guide/components-dynamic-async.html.
It would look like this:
<component v-bind:is="currentHeaderComponent"></component>
In this case, you would set currentHeaderComponent based on your conditions.
If you insist on CSS and media queries for the footer, set the component id or class, and that in your CSS
Component
<app-header id='app-header'></app-header>
<router-view></router-view>
<app-footer id='app-footer'></app-footer>
CSS
#app-footer {display: none;}
|
[
"math.stackexchange",
"0002807957.txt"
] | Q:
What means number on number?
What does the following notation mean?
$$k \choose n$$
If you didn't understand me see my question and the first answer that was accepted Permutation and combinations using chairs?
A:
$$\binom{n}{r}=nCr=\frac{n!}{r!(n-r)!}$$
$$\text{Where }x!=1\cdot2\cdot3\cdot\ldots\cdot x$$
E.g.
$$\binom{7}{5}=\frac{7!}{5!\cdot2!}=\frac{1\cdot2\cdot3\cdot4\cdot5\cdot6\cdot7}{(1\cdot2\cdot3\cdot4\cdot5)\cdot(1\cdot2)}=\frac{6\cdot7}{2}=21$$
|
[
"stackoverflow",
"0020624222.txt"
] | Q:
Toggle-switch library + Bootstrap submenu = how to stop propagation?
What I'm talking about - http://jsfiddle.net/NJc5b/ - I need the submenu to don't close when I change the switch value. As you see e.stopPropagation(); does not help.
A:
JSFiddle: http://jsfiddle.net/NJc5b/2/
$('.dropdown-menu').sortable();
$(document).on('click', '.switch-toggle *', function(e){
e.stopPropagation();
console.log('wtf');
});
Simply changing your label to a * does the job. You need to stop propagation from all child elements of the switch, without interfering with the propagation of other submenu items.
|
[
"stackoverflow",
"0003346249.txt"
] | Q:
Java combination algorithm
Given a collection of integers, what's a Java algorithm that will give combinations as follows..
Given the example collection: [1,3,5], we'd want the output:
[1-1]
[3-3]
[5-5]
[1-3]
[1-5]
[3-5]
Note that ordering is not important, so we want one of [1-3], [3-1] but not both.
This should work with a collection of n numbers, not just the the three numbers as in this example.
A:
Below function should do this
private void printPermutations(int[] numbers) {
for(int i=0;i<numbers.length; i++) {
for (int j=i; j<numbers.length; j++) {
System.out.println("[" + numbers[i] + "-"+ numbers[j] +"]");
}
}
}
Example call to this function
int[] numbers={1,2,3};
printPermutations(numbers);
|
[
"serverfault",
"0000903766.txt"
] | Q:
How to check if my machine is an amplifier for DRDoS?
My machine has been identified as amplifier for DRDoS attack. How can I trace how my machine has been used to do this and remove the software used?
I tried to check machine's system log but I can't find anything. They said there was a service on my machine active on port 17 udp, taking part to the attack, but I cannot find that, currently, using netstat.
A:
If the DDoS is over, then whatever was listening on Port 17 may not be running any more, as the C&C server may have told it to shut down. It may also be possible that your PC was not sending traffic on udp/17 but rather it was creating requests to a different QOTD server on udp/17.
If you were the one sending amplified traffic, udp/17 is traditionaly QOTD (Quote of the Day) which really has no business running on any modern server. QOTD can be used for DNS amplification, sending up to 512 bytes for a forged UDP request.
The way to defend against this is to have a firewall that doesn't permit any inbound requests from services you don't explicitly punch through
However, it may simply be that your machine is infected with malware and is not being used as an amplifier, but rather you were requesting the amplification (e.g. you were sending fake UDP packets to another machine which did the amplification).
If you are running your own edge network, implement BCP38 (or petition your upstream ISP to implement it). This essentially says "Don't let any traffic in or out of your network that is not designated for or has not come from your network". If every edge network and ISP implemented this, UDP amplification attacks would disappear overnight. What this essentially means is that when your computer started forging UDP requests, your edge device would say "Oh, this UDP request is designated for 203.0.113.77 but I only know of the network 198.51.100.0/24, therefor this traffic is junk and I should discard it before letting it leave my network. (BCP38 is for client networks, not transit networks. Obviously if ISPs implemented this on all their networks then the internet would grind to a halt)
More importantly though if your machine is infected with this malware you need to nuke the entire machine and start again.
|
[
"math.stackexchange",
"0000825566.txt"
] | Q:
Determining odd or even functions
I know that to determine wether or not a function is even, you sub in $(-x)$ for $x$, and see if it the same (even) or not (odd/neither). However, I get confused when you have to sub in $(-x)$ for multiple exponents of $x$ such as $x^9$ or higher.
I noticed that, as a general rule, if the exponent is even, such as $x^8$, the $-x$ will be $x$, and it will turn out to be $x^8$, however if the exponent is an odd number, such as $x^7$, the exponent will turn out to be $-x^7$, is this correct?
A:
Yes, because $$(-1)^n = \left\{\begin{array}{lr} 1 &\text{$n$ even} \\ -1 &\text{$n$ odd}\end{array}\right.$$
Combining this with the fact that
$$(-x)^n = ((-1) x)^n = (-1)^ n x^n$$
gives the desired result.
|
[
"salesforce.stackexchange",
"0000227692.txt"
] | Q:
External entry point Error in Trigger
In my Apex trigger I got an error:
Error:Apex trigger Remittance caused an unexpected exception, contact your administrator: Remittance: execution of AfterUpdate caused by: System.QueryException: List has more than 1 row for assignment to SObject: External entry point
and here is my code:
public class OutstandingFieldUpdateOnLegal {
public List<Legal__c> legalFieldUpdate(List<Remittance__c>newRemit){
Map<Id,String> remAccnt=new Map<Id,String>();
for(Remittance__c remit : newRemit){
if(remit.Status__c =='Manual Payment' && remit.Payment_Type__c =='Legal Settlement Payment')
remAccnt.put(remit.Id,remit.Customer__c);
}
List<Legal__c> legallist = new List<Legal__c>();
if(remAccnt.size() >0)
legallist.add([SELECT id,Outstanding_Final_Judgment_Amount__c,
Outstanding_Final_Settlement_Amount__c,
Final_Judgment_Date__c,Final_Settlement_Date__c,
Customer__c From Legal__c
WHERE Customer__c IN : remAccnt.Values()]);
return legallist;
}
public void legalFieldUpdating(List<Remittance__c>newRemit){
List<Legal__c> lgl =new List<Legal__c>();
List<Legal__c> legaldata = legalFieldUpdate(newRemit);
for(Remittance__c remit : newRemit){
if(legaldata.size() > 0){
for(Legal__c legals : legaldata){
if(legals.Final_Judgment_Date__c!=Null && remit.Date__c!=Null &&
legals.Final_Judgment_Date__c > remit.Date__c){
legals.Outstanding_Final_Judgment_Amount__c =
legals.Outstanding_Final_Judgment_Amount__c - remit.Payment_Amount__c;
lgl.add(legals);
}
else if(legals.Final_Settlement_Date__c !=Null && remit.Date__c !=Null &&
legals.Final_Settlement_Date__c > remit.Date__c){
legals.Outstanding_Final_Settlement_Amount__c =
legals.Outstanding_Final_Settlement_Amount__c - remit.Payment_Amount__c;
lgl.add(legals);
}
else if(legals.Final_Judgment_Date__c !=Null && remit.Date__c !=Null &&
legals.Final_Judgment_Date__c < remit.Date__c){
legals.Outstanding_Final_Judgment_Amount__c =
legals.Outstanding_Final_Judgment_Amount__c - remit.Payment_Amount__c;
legals.Outstanding_Final_Settlement_Amount__c =
legals.Outstanding_Final_Settlement_Amount__c - remit.Payment_Amount__c;
lgl.add(legals);
}
}
}
}
update lgl;
}
}
Can someone help me why is it so?
A:
You've only got one query here, so that gives us a pretty good bead on where the issue lies:
legallist.add([SELECT id,Outstanding_Final_Judgment_Amount__c,
Outstanding_Final_Settlement_Amount__c,
Final_Judgment_Date__c,Final_Settlement_Date__c,
Customer__c From Legal__c
WHERE Customer__c IN : remAccnt.Values()]);
List<Legal__c>.add() takes a single argument of type Legal__c. As a result, Salesforce is treating this query the same way it would if it were written out as a single sObject assignment:
Legal__c l = [SELECT .... FROM Legal__c ...];
so as to provide the right argument type to this method.
When the query returns 0 or more than 1 object in a single-sObject assignment, a QueryException results.
Fortunately, List also provides an addAll() method, which accepts a List of objects to add. Here, the type of that parameter would be List<Legal__c>, which is what a SOQL query against Legal__c would normally return.
Changing add() to addAll() will allow the query to complete in that "normal" List context, which doesn't throw QueryException when 0 or >1 result is returned. It's legal to call addAll() with an empty list, too.
|
[
"stackoverflow",
"0021896956.txt"
] | Q:
what is the correct way of using `include` to avoid recursive makefile?
I am not sure if i understand include statement in makefile well enough. I have recently started to use makefile for making my analysis reproducible, and thought i was in the right track until the complexity grew, and seems like include statement is the answer as I am also trying to avoid recursive makefile problem while trying to keep my makefile sane.
To test what include did i ran a dumb test basically created the following.
test_folder-|-makefile
|-test_folder2-|
|-test2.mk
In the makefile i added include test_folder2/test2.mk, which according to my understanding would add the code from the test2.mk, so when i run make, it will also run target:dependencies listed in test2.mk, but it only ran the target:dependencies from makefile.
It would be great if someone can explain or point me to another blog/stack answer that might explain the right way to avoid recursive makefiles by using include statement.
PS: My analysis mostly includes python and R scripts and some command line tools.
makefile
test.txt:
echo "test.txt" > test.txt
include test_folder2/test2.mk
test2.mk
test_folder2/test1.txt:
echo "this is a test" > test1.txt
A:
First, there is no directory called test1, so I will modify the makefiles accordingly.
Second, notice that the test_folder2/test1.txt rule builds test1.txt locally, despite its name. there is more than one way to so what I think you want; one way is to modify test_folder2/test2.mk:
test_folder2/test1.txt:
echo "this is a test" > test_folder2/test1.txt
In order to execute this rule by running make in test_folder/, you must modify makefile.
To execute only the test_folder2/test1.txt rule, do this:
test_folder2/test1.txt:
test.txt:
echo "test.txt" > test.txt
include test_folder2/test2.mk
To execute both rules, do this:
all: test.txt test_folder2/test1.txt
test.txt:
echo "test.txt" > test.txt
include test_folder2/test2.mk
(Note that "all" is the conventional name for a phony target that comes first in the makefile -- and is therefore the default -- and requires other rules to be executed. You can use another name if you like.)
To execute test_folder2/test1.txt dirst, then test.txt, do this:
test.txt: test_folder2/test1.txt
echo "test.txt" > test.txt
include test_folder2/test2.mk
(It is possible to execute them in the opposite order, but it gets ugly.)
Further refinements are possible, but this is a start.
|
[
"stackoverflow",
"0027677452.txt"
] | Q:
difference between pci_alloc_consistent and dma_alloc_coherent
I am working on pcie based network driver. Different examples use one of pci_alloc_consistent or dma_alloc_coherent to get memory for transmission and reception descriptors. Which one is better if any and what is the difference between the two?
A:
The difference is subtle but quite important.
pci_alloc_consistent() is the older function of the two and legacy drivers still use it.
Nowaways, pci_alloc_consistent() just calls dma_alloc_coherent().
The difference? The type of the allocated memory.
pci_alloc_consistent() - Allocates memory of type GFP_ATOMIC.
Allocation does not sleep, for use in e.g. interrupt handlers, bottom
halves.
dma_alloc_coherent()- You specify yourself what type of memory to
allocate. You should not use the high priority GFP_ATOMIC memory
unless you need it and in most cases, you will be fine with
GFP_KERNEL allocations.
Kernel 3.18 definition of pci_alloc_consistent() is very simple, namely:
static inline void *
pci_alloc_consistent(struct pci_dev *hwdev, size_t size,
dma_addr_t *dma_handle)
{
return dma_alloc_coherent(hwdev == NULL ? NULL : &hwdev->dev, size, dma_handle, GFP_ATOMIC);
}
In short, use dma_alloc_coherent().
|
[
"stackoverflow",
"0002633155.txt"
] | Q:
Are default _id fields for MongoDB documents always 24 hex characters?
As part of my application requirements, I have a limit of 30 characters for an ID field. This is out of my control and I am wondering if the MongoDB default _id fields will work for me. It appears as though the default _id field is 24 characters long. That works for me, but I am wondering if this is likely to change in the future. I am well aware that things can always change, but, for the next year or two, can I expect there to be 24 character default _id fields?
A:
They aren't actually 24 characters - they are 12 bytes (24 characters in hex representation). And yes, that will be the case for the foreseeable future.
|
[
"security.stackexchange",
"0000196618.txt"
] | Q:
Does full disk encryption offer mitigation in the case of the firmware of an SSD being compromised?
Suppose the firmware of an SSD or HDD has been compromised by rogue actors either through "interdiction" (interception) or via the internet. They are able to exfiltrate data and conduct surveillance at will without my knowledge.
Can I mitigate the effects of the compromise by having the entire disk encrypted using tools such as Linux's Luks or Microsoft Windows Bitlocker? Or would installing Qubes-Whonix be a better option than LUKS and Bitlocker?
A:
Partially. Full disk encryption, when done through software (e.g. LUKS), means that a compromised storage device will only ever see encrypted data, never decrypted data. It will never have access to the key. However, it would still be able to tamper with data by exploiting the malleability of non-authenticated modes which could potentially be abused to compromise the operating system (for example, the storage device could randomize any 16 byte block in XTS by toggling a single bit in the ciphertext, which can be very bad in some situations), or by exploiting weaknesses in XTS when snapshots are available to an attacker over time to leak information. Additionally, if you are booting from the drive, then a malicious MBR could be sent to the computer from the drive, loading a bootkit. Another issue is the capabilities of the storage device interface. SATA, for example, should not make a DMA attack possible, but a drive connected directly over PCIe might be able to write to system memory.
|
[
"stackoverflow",
"0001767588.txt"
] | Q:
PHP Accurate Font Width
I am trying to generate a text image.
So I create a new font:
$font = '../fonts/Arial.ttf';
Then I add some background for the text
imagefilledrectangle($image, 0, 0, ?, 12, $green);
And add text
imagettftext($image, 12, 0, 0, 12, $white, $font, $text);
The problem is right now I don't know how to get the width of my font with size 12.
Thanks.
A:
Using ImageTTFBBox()
|
[
"stackoverflow",
"0026292178.txt"
] | Q:
how to assign values to textbox inside html cell
i want to assign value to this textboxes using javascript
i'll try it usig this
(table.rows.item(i).cells[5]).find('input').val("45");
but it wouldn't happen
i'm append my table like this
success: function (data) {
$('#invoiceDetailTbl > tbody > tr:nth-child(n+1)').remove();
var date;
var invDate;
var invNo;
var netAmt;
var paidAmt;
var balance;
var totalAmt = 0;
var totalBalance = 0;
for (var i = 0; i < data.length; i++) {
date = data[i].inv_Date;
invDate = date.substring(0, 10);
invNo = data[i].inv_No;
netAmt = parseFloat(data[i].Net_Amt).toFixed(2);
paidAmt = parseFloat(data[i].Paid_Amt).toFixed(2);
balance = (parseFloat(netAmt) - parseFloat(paidAmt)).toFixed(2); //id = "damt['+i+']"
$("#invoiceDetailTbl tbody").append("<tr id=" + i + ">" + "<td>" + invDate + "</td>" + "<td>" + invNo + "</td>" + "<td>" + netAmt + "</td>" + "<td>" + paidAmt + "</td>" + "<td>" + '<input type="text" class="discountAmt form-control input-sm" style="width: 100px;" placeholder="Discount Amt" id="damt">' + "</td>" + "<td>" + '<input type="text" class="payingAmt form-control input-sm" style="width: 100px;" placeholder="Paying Amt" id="pamt">' + "</td>" + "<td>" + balance + "</td>" + "<td>" + '<span class="glyphicon glyphicon-file"></span>' + "</td>" + "</tr>");
totalAmt = totalAmt + parseFloat(netAmt);
totalBalance = totalBalance + parseFloat(balance);
}
}
A:
table.rows.item(i).cells[5]) is a DOM element, not a jQuery object. So you cannot invoke find on it.
try
$(table.rows.item(i).cells[5])).find('input').val("45");
|
[
"stackoverflow",
"0039969822.txt"
] | Q:
Should I override a property in child class form parent class (UIButton)
I want to create a custom button, that will help me change all button background color to default red color if I don't set any color for the button.
So I do like this and it working well
in .h file I have
@interface ITSButton : UIButton
@property(nonatomic, strong) UIColor *backgroundColor;
@property(nonatomic, strong) UIColor *onPressBackgroundColor;
@end
in .m fie
-(UIColor *)backgroundColor
{
if(!_backgroundColor){
_backgroundColor = [UIColor redColor];
}
return _backgroundColor;
}
But the problem here backgroundColor is already a property of UIButton class. Is it good and clear if I override it in ITSButton?
And if I don't override backgroundColor property, I can not use the function (UIColor *)backgroundColor, so I can not set the default background to red
A:
And if I don't override backgroundColor property, I can not use the function (UIColor*)backgroundColor, so I can not set the default background to red
Yes you can, and I think that realizing this is probably the key to your dilemma. Leave backgroundColor alone! It has an important job to do. Instead, implement the initializer of your subclass to set the background color of this button to red. You should do this for all possible initializers; the two most likely are initWithFrame: and initWithCoder:.
The result is that all buttons of this class, and all buttons of any subclass of this class, will be red by default, which is what you want. And to change that, you just set the background color of the button, just as you do now with any button.
Don't forget to read the docs on how to override an initializer in a subclass if you don't already know the rules on how to do it.
|
[
"stackoverflow",
"0013152055.txt"
] | Q:
Can I insert a domain when I applying a style in document?
I want to insert field code like {SEQ seq \h} when I apply "Heading 1" style to some text.
I think it is related to vba and can be divide into two parts.
1.find the event which would be triggered after Paragraph Style changed.
2.insert field code at head of the paragraph.
question 2 can be achieved by
.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:="SEQ SEQ_ID\* Arabic \* MERGEFORMAT", PreserveFormatting:=True
question 1 is hard to find. Any one have done that before?
A:
You may be able to capture the WindowSelectionChange event. However, you will have to write your own handler for it. Refer to this website to get you started:
Writing application event procedures
|
[
"puzzling.stackexchange",
"0000095232.txt"
] | Q:
Find the hidden word (Harry Potter theme)
Bouncing bulbs are jumping all around the greenhouse. Can you help sort them out and figure out the hidden word?
(Note: the answer is something from Harry Potter)
A:
Each rectangle of letters gives
the name of a Harry Potter character, ignoring repeated letters.
Top row:
ERNIE (Macmillan), VERNON (Dursley), AMOS (Diggory), (Madam) HOOCH, RUFUS (Scrimgeour), MARVOLO (Gaunt, or Tom ... Riddle).
Bottom row:
ALECTO (Carrow), ARGUS (Filch), REGULUS (Arcturus Black), ANTHONY (Goldstein), REMUS (Lupin).
At first I'd thought the dots in some rectangles would be
missing letters, and we'd need to figure out what to add and then make an anagram, but the REMUS in the bottom right was too good not to be true. Funnily enough the top left with an extra F would be FENRIR, and bottom left with an extra M would be CATTERMOLE, but just 1 extra letter wouldn't fit either of those anyway.
Now, what can we do with these words we've got?
Ernie, Vernon, Rufus, Hooch, Amos, Marvolo, Alecto, Argus, Regulus, Anthony, Remus: the letters EVRHAMAARAR don't spell anything. Could be this is another anagram to be solved though ...
Macmillan, Dursley, Scrimgeour, Rolanda, Diggory, Gaunt, Carrow, Filch, Black, Goldstein, Lupin: the letters MDSRDGCFBGL don't spell anything either, nor do they anagram to anything (no vowels).
Another idea is to
follow the order of letters within the configurations given, which in some cases could spell out letters:
We can clearly see some letters, especially on the bottom row which almost looks like SNAPE, but especially the third one on the top row seems to make no sense.
Thanks to Stiv, this does indeed make sense if we just simplify the tracks a bit:
and the answer is
DEVIL'S SNARE, another Harry Potter thing which would fit in the "greenhouse" as stated in the OP.
A:
Each box has the first names of Harry Potter characters scrambled: ERNIE, VERNON, RUFUS, CHO, AMOS, MARVOLO, ALECTO, ARGUS, REGULUS, ANTHONY, REMUS. Tracing the names from letter to letter reveals the letters DEVILS SNARE, a plant from Harry Potter.
|
[
"ux.stackexchange",
"0000122895.txt"
] | Q:
What is correct user expectation regarding drag and move?
I have the following note taking app - https://wenote.jstock.co
I have some question, regarding user expectation regarding drag and move.
Say, you have the following card position.
[1] [2]
[3] [4]
when you move card 1 to card 4 position
Should they become (Card 1 and card 4 are being swapped. Only position of card 1 and card 4 affected.)
[4] [2]
[3] [1]
Or, the entire cards position are being shuffled (The entire list of cards are being shifted forward, to give space to the moved card. All cards position are affected.)
[2] [3]
[4] [1]
So, I'm some how confused here. What is the correct behavior when coming to drag n move for the above case?
Card 1 and card 4 are being swapped. Only position of card 1 and card 4 affected.
The entire list of cards are being shifted forward, to give space to the moved card. All cards position are affected.
For me, the 1st approach has a more "Direct intuitive". But, I notice that some popular note taking app like Google Keep, Zoho Notebook are using 2nd approach.
A:
User expectation for drag and move can depend on the existing mental models and the kind of affordance provided in the UI. The correctness depends on how well the application interface solves the Use case --> UI pattern --> Affordance combination.
Pattern 1:
Commonly known as Swappable. In this pattern, when a card is dragged onto another card, the other card doesn't change its position until the user releases the drag. Usually the other card is highlighted visually to indicate that a change is going to happen. This pattern is more common in games.
Pattern 2:
Commonly known as Sortable. In this pattern, when a card is dragged onto another card, the other cards shift positions to give space for the change. Here the visual feedback to the user is immediate. This pattern is more common in apps where the cards arrangement can be customized.
Why Sorting is the more common approach for rearranging
Applications provide the feature to rearrange so that users can arrange content in a way more meaningful for them. If we take the following example of a list of cards:
[1] [2] [3] [4] [5] [6]
To get the result [2] [3] [4] [5] [6] [1] using 1) Swapping will take a lot of combinations whereas 2) Sorting happens in a single go.
To get the result [6] [2] [3] [4] [5] [1] using 1) Swapping will happen in a single attempt and 2) Sorting will happen in two attempts.
Using Sorting to swap items can always happen with no more than two attempts. That's why Sorting is the more efficient approach and found in most of the apps like the examples mentioned in the question.
|
[
"english.stackexchange",
"0000182915.txt"
] | Q:
Is this list punctuated correctly?
I am in the process of writing my CV/Resume and want to list my skills with a brief explanation of how I learnt them. So far I have been using:
Marketing Experience - Gained from owning a small online business.
Flexible Worker - A basic requirement of my previous role as a
general assistant.
IT Skills - Gained from 2 years of software development as a hobby.
etc...
Is this correct? I thought about using a colon instead of the dash but would that be grammatically incorrect?
A:
I think that's absolutely fine. You could alternatively put a line break in and make each skill/experience a subheading. Good luck with the job hunt!
|
[
"stackoverflow",
"0021796939.txt"
] | Q:
C++ Call an abstract method from a static method using *this
I am trying to make an abstract class which allows you to call the method Fun, which is static, which prints "Abstract Class", however, it is not working, as I am using *this in a static method. I am confused on how I can reslove this problem:
class A
{
private:
virtual void __Fun() = 0
{
std::cout << "Abstract Class";
}
static void _Fun(A &instance)
{
instance.__Fun();
}
public:
static void Fun()
{
_Fun(*this); // 'this' may only be used in nonstatic member functions
}
};
int main()
{
A a; // Throws - which is good: class is abstract
A::Fun(); // Desired result
}
A:
Myabe what you want is to create not an abstract class, but a class with a private constructor (like a singleton)?
class A
{
private:
A()
{
}
virtual void __Fun()
{
std::cout << "Abstract Class";
}
static void _Fun(A &instance)
{
instance.__Fun();
}
public:
static void Fun()
{
A a;
_Fun(a);
}
};
int main()
{
A a; // Throws - which is good: constructor is private
A::Fun(); // Desired result
}
But then, I'm not sure why do you need such a thing at all, and why do you need virtual functions in it?
|
[
"stackoverflow",
"0051140693.txt"
] | Q:
Wide to Long data with duplication
I am trying to convert a data set that contains a combination of both wide and long data. Currently it looks something like this:
(note: there are many other variables either side, this is just the segment I need to change)
Currently, WTP1 and 2 are in the same row as they are associated with the same participant (buyers). What I need is for there to be one column for WTP so each buyer has two rows which are identical other than the WTP value. Something like this:
WTP
15
5
I have nearly reached a solution using the unite function but the problem is here that the two values are in the same cell rather than in their own rows:
library(dplyr)
long_Data <- unite(mydata.sub1,WTP,player.WTP1:player.WTP2, sep = "_", remove= TRUE)
I'm sure there is an easy solution to this but I'm a beginner! any suggestions welcome. TIA
A:
Is this what you're looking for?
df1 <- data.frame(
player.WTA = c(NA,20,10,NA,10,5,NA),
player.WTP1 = c(15,NA,NA,15,NA,NA,15),
player.WTP2 = c(5,NA,NA,5,NA,NA,5)
)
require(reshape2)
melt(df1, id.var="player.WTA", value.name="WTP")
player.WTA variable WTP
1 NA player.WTP1 15
2 20 player.WTP1 NA
3 10 player.WTP1 NA
4 NA player.WTP1 15
5 10 player.WTP1 NA
6 5 player.WTP1 NA
7 NA player.WTP1 15
8 NA player.WTP2 5
9 20 player.WTP2 NA
10 10 player.WTP2 NA
11 NA player.WTP2 5
12 10 player.WTP2 NA
13 5 player.WTP2 NA
14 NA player.WTP2 5
And if you just want to see the non-NA values:
require(dplyr)
melt(df1, id.var="player.WTA", value.name="WTP") %>% filter(WTP != 'NA')
player.WTA variable WTP
1 NA player.WTP1 15
2 NA player.WTP1 15
3 NA player.WTP1 15
4 NA player.WTP2 5
5 NA player.WTP2 5
6 NA player.WTP2 5
|
[
"stackoverflow",
"0034474993.txt"
] | Q:
Prepend icon before td that will be changed with .html()
I have tds that need to have their values changed. Doing so with:
$(".class td:nth-child(2)").html("new value");
But I am trying to append font-awesome icons before this value with:
$(".class td:nth-child(2)").append("<i class=\"fa fa-arrow-up\"></i>");
which puts the icon after the html. I want it to be before the html. It looks like I need to append because html clears the class information. How do I put the icon before the html dynamically?
A:
You need to use .prepend():
$(".class td:nth-child(2)").prepend("<i class=\"fa fa-arrow-up\"></i>");
A:
Use prepend() to add content to the beginning of a parent element instead:
$(".class td:nth-child(2)").prepend("<i class=\"fa fa-arrow-up\"></i>");
http://api.jquery.com/prepend
|
[
"stackoverflow",
"0042283563.txt"
] | Q:
Shared element is visible both in calling and called activity
Here's a screencast from George Mount's transition demo app.
You can see that the shadow around the hero element is darker for a moment. This is because both the calling and the called activity displayed the text for a short duration.
I would like to know if there is a workaround for this.
A:
Unfortunately, there is no way to avoid the doubling of the shadow at the moment. There is no interlock with the shared element, so it is briefly drawn on both surfaces, and translucent elements (shadows included) are seen twice.
One way to ensure you don't see this is to drop the view (elevation -> 0) as a shared element exit transition, and then raise the view again as part of a shared element enter transition. The shadow will animate out and then animate back in again, but you won't see the double shadow.
|
[
"stackoverflow",
"0030728463.txt"
] | Q:
Windows server 2012 sign out or disconnect?
I am connected with RDP on a remote server.
I just want to leave and I have two options:
1) Sign out
2) Disconnect
What is the difference between these two?
A:
Sign Out - interrupt sessions and all active programs started by you in session. Same as 'Log Off' or 'Log Out'.
Disconnect - all programs started by you in session remain active in background. You can reconnect, and continue using the same session.
|
[
"stackoverflow",
"0010098186.txt"
] | Q:
Blank space with frames
So, I have created a page with 3 frames, top, left and right where left meant to be main and content frame where right frame meant to be index.
Here is how it looks on opera/nightly/even ie:
yet, this is how it looks on chrome:
see white space after blue, under green. it looks even uglier when you use black.
I wish i could give you jsfiddle or something but it doesnt work for frames, and problem only happens in chrome. the html code is located at http://pastebin.com/HxG4NUjb and cant paste here because alth. I use four spaces, this editor seems to think its just text.
A:
You are enclosing the frame id="ma" inside another extra frameset. Remove the extra frameset and that'll get rid of the extra white space.
Change this...
<frameset id="x" rows="50,*" border = "0" frameborder ="0">
<frame id="to" name="to" src="http://examancer.com/mobile/screen.html" style="frameborder:0" scrolling="no" noresize="noresize" />
<frameset cols="*,200" border="0">
<frame id="ri" name="ri" src="http://examancer.com/mobile/screen.html" frameborder="0" noresize="noresize" />
<frameset cols="200,*" style="border:0">
<frame id="ma" name="ma" src="http://examancer.com/mobile/screen.html" frameborder="0" noresize="noresize" />
</frameset>
</frameset>
</frameset>
to this...
<frameset id="x" rows="50,*" border = "0" frameborder ="0">
<frame id="to" name="to" src="http://examancer.com/mobile/screen.html" style="frameborder:0" scrolling="no" noresize="noresize" />
<frameset cols="*,200" border="0">
<frame id="ri" name="ri" src="http://examancer.com/mobile/screen.html" frameborder="0" noresize="noresize" />
<frame id="ma" name="ma" src="http://examancer.com/mobile/screen.html" frameborder="0" noresize="noresize" />
</frameset>
</frameset>
|
[
"stackoverflow",
"0031438649.txt"
] | Q:
App crashes when trying to create a SQLite table
My app keep crashing when I try to add a new row to a table (which then calls onCreate because it doesn't exist yet). Line 40 is db.execSQL(CREATE_SESSIONS_TABLE_QUERY);
My assumption so far is that there is something wrong with the query string, but I can't figure out what it is.
This is the class that manages the database:
public class PBMDatabaseOperations extends SQLiteOpenHelper{
private static final int database_version = 1;
private String CREATE_SESSIONS_TABLE_QUERY = "CREATE_TABLE " + PBMDatabaseContract.SessionTable.TABLE_NAME + "("
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_ID + " INT PRIMARY KEY AUTOINCREMENT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_SESSION_TYPE + " TEXT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_STAKE_LEVEL + " TEXT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_LIMIT_TYPE + " TEXT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_GAME_TYPE + " TEXT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_LOCATION + " TEXT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_START_TIME + " TEXT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_END_TIME + " TEXT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_BUY_IN + " INT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_CASH_OUT + " INT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_NUM_OF_PLAYERS + " INT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_POSITION_PLACED + " INT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_PLACES_PAID + " INT, "
+ PBMDatabaseContract.SessionTable.COLUMN_NAME_IS_COMPLETED + " INT"
+ ");";
public PBMDatabaseOperations(Context context) {
super(context, PBMDatabaseContract.DATABASE_NAME, null, database_version);
Log.d("Database operations", "Database created");
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SESSIONS_TABLE_QUERY);
Log.d("Database operations", "Table created");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putNewCashGame(PBMDatabaseOperations dbop, String stake, String limit, String gameType, String location, String startTime, int buyIn){
SQLiteDatabase sqdb = dbop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(PBMDatabaseContract.SessionTable.COLUMN_NAME_STAKE_LEVEL, stake);
cv.put(PBMDatabaseContract.SessionTable.COLUMN_NAME_LIMIT_TYPE, limit);
cv.put(PBMDatabaseContract.SessionTable.COLUMN_NAME_GAME_TYPE, gameType);
cv.put(PBMDatabaseContract.SessionTable.COLUMN_NAME_LOCATION, location);
cv.put(PBMDatabaseContract.SessionTable.COLUMN_NAME_START_TIME, startTime);
cv.put(PBMDatabaseContract.SessionTable.COLUMN_NAME_BUY_IN, buyIn);
cv.put(PBMDatabaseContract.SessionTable.COLUMN_NAME_CASH_OUT, 0);
cv.put(PBMDatabaseContract.SessionTable.COLUMN_NAME_IS_COMPLETED, 0);
long k = sqdb.insert(PBMDatabaseContract.SessionTable.TABLE_NAME, null, cv);
Log.d("Database operations", "new row inserted to table " + PBMDatabaseContract.SessionTable.TABLE_NAME);
}
}
This is the method that is calling the method to add a new row:
createSession.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (buyIn.getText().toString().equals("")) {
Toast.makeText(v.getContext(), "The Buy In Field Cannot Be Empty", Toast.LENGTH_LONG).show();
}
else {
Session cg = new Session();
cg.setStakeLevel(stakes.getSelectedItem().toString());
cg.setLimitType(limitTypes.getSelectedItem().toString());
cg.setGameType(gameTypes.getSelectedItem().toString());
//TODO Location is currently a string needs to be a Location Object
//cg.setLocationName(locations.getSelectedItem().toString());
cg.setStartTime(startDate.getText().toString());
cg.setBuyIn(Integer.parseInt(buyIn.getText().toString()));
//add to database
PBMDatabaseOperations db = new PBMDatabaseOperations(C);
db.putNewCashGame(db, cg.getStakeLevel(), cg.getLimitType(), cg.getGameType(),locations.getSelectedItem().toString(), cg.getStartTime(), cg.getBuyIn());
Toast.makeText(v.getContext(), "New Cash Game Session Created", Toast.LENGTH_LONG).show();
finish();
}
}
});
and this is the logcat when I try to run it:
07-15 14:45:19.531 7107-7107/pokerbankrollmanager.com.pokerbankrollmanager D/Database operations﹕ Database created
07-15 14:45:19.534 7107-7107/pokerbankrollmanager.com.pokerbankrollmanager E/SQLiteLog﹕ (1) near "CREATE_TABLE": syntax error
07-15 14:45:19.535 7107-7107/pokerbankrollmanager.com.pokerbankrollmanager D/AndroidRuntime﹕ Shutting down VM
07-15 14:45:19.535 7107-7107/pokerbankrollmanager.com.pokerbankrollmanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: pokerbankrollmanager.com.pokerbankrollmanager, PID: 7107
android.database.sqlite.SQLiteException: near "CREATE_TABLE": syntax error (code 1): , while compiling: CREATE_TABLE sessions(id INT PRIMARY KEY AUTOINCREMENT, session_type TEXT, stake_level TEXT, limit_type TEXT, game_type TEXT, location TEXT, start_time TEXT, end_time TEXT, buy_in INT, cash_out INT, num_of_players INT, position_placed INT, places_paid INT, is_completed INT);
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at pokerbankrollmanager.com.pokerbankrollmanager.PBMDatabaseOperations.onCreate(PBMDatabaseOperations.java:40)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at pokerbankrollmanager.com.pokerbankrollmanager.PBMDatabaseOperations.putNewCashGame(PBMDatabaseOperations.java:51)
at pokerbankrollmanager.com.pokerbankrollmanager.AddCashGame$2.onClick(AddCashGame.java:183)
at android.view.View.performClick(View.java:5199)
at android.view.View$PerformClick.run(View.java:21155)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5415)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:725)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615)
A:
You have the word CREATE_TABLE when it should be two words CREATE TABLE.
|
[
"superuser",
"0000145659.txt"
] | Q:
Emulate middle mouse click by pressing the two buttons at the same time
I upgraded the driver of my Synaptics Touchpad under XP and I can no longer press the left and right buttons simultaneously to simulate a middle click. How can I turn this back on?
A:
This forum post has a solution. I've also verified it works under Windows 7 Professional 64-bit on an HP ProBook 6550b.
Run the registry editor (regedit)
Go to key: HKEY_LOCAL_MACHINE\Software\Synaptics\SynTP\Defaults\
Create a new key as a DWORD and name it as HasBothButtonFeature and set the value to 1.
Log off and Log on again.
|
[
"stackoverflow",
"0011135133.txt"
] | Q:
A CREATE script exported by MySQL Workbench has syntax error on another computer
I created a database on my computer, with MySQL 5.5 and MySQL Workbench 5.2.34 CE installed.
Then i want to migrate the database to another computer, which has MySQL 5.0 installed. (I just need to migrate the schema, data are not needed)
I use the MySQL Workbench's File -> Export -> Forward Engineer SQL CREATE script to generate db.sql script and copy it to the other computer.
I type mysql < db.sql to create the database but only to receive an error.
Error occurs here:
DELIMITER $$
CREATE PROCEDURE `filedb`.`GetIncompleteFileId` (in latestFileId BIGINT UNSIGNED, in serverBits BIT(32), in fileCount SMALLINT UNSIGNED)
BEGIN
SELECT `id`, `key`, `length`, `path`
FROM
(
SELECT * FROM `filedb`.`fileInfo` WHERE `id` <= latestFileId
) AS TempTable
WHERE (serverBits & `serverownership` NOT IN (serverBits, 0))
ORDER BY `id` DESC
LIMIT fileCount;
END
$$
The error is near 'fileCount; END'.
If i remove the "LIMIT fileCount", the error disappears.
Anyone tells me what is the problem?
A:
In the MySQL 5.0 LIMIT arguments must be nonnegative integer constants, not a variables or procedure parameters. Use prepared statements to avoid this error.
From the MySQL 5.0 documentation -
The LIMIT clause can be used to constrain the number of rows returned
by the SELECT statement. LIMIT takes one or two numeric arguments,
which must both be non-negative integer constants (except when using
prepared statements).
From the MySQL 5.5 documentation -
The LIMIT clause can be used to constrain the number of rows returned
by the SELECT statement. LIMIT takes one or two numeric arguments,
which must both be nonnegative integer constants, with these
exceptions:
Within prepared statements, LIMIT parameters can be specified using ? placeholder markers.
Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables as of MySQL 5.5.6.
|
[
"math.stackexchange",
"0000755184.txt"
] | Q:
particular solutions is zero
We have some issues with particular solution.
Cannot solve A and B on the last line because it becomes zero all together.
So it becomes $2sin(2x) = 0$
What are we doing wrong?
Thanks for your time.
$$y''+4y=2\sin2x$$
$$r^2+4=0, r=\sqrt{-4}, r_1=2i, r_2=-2i$$
$$y=C_1\cos{2x}+C_2i\sin{2x}$$
$$Y=A\cos{2x}+B\sin{2x}$$
$$Y'=-2A\sin{2x}+2B\cos{2x}$$
$$Y''=-4A\cos{2x}-4B\sin{2x}$$
$$2\sin{2x}=-4A\cos{2x}-4B\sin{2x}+4(A\cos{2x}+B\sin{2x})$$
A:
Your particular solution should be $ Ax\cos 2x+Bx\sin 2x $
|
[
"stackoverflow",
"0058760033.txt"
] | Q:
Session Value always equals last instance
I have a page that is running an SQL query. I am displaying information for each row that the query results in. I am now trying to implement a way to update the information for the things being displayed.
My understanding is that in order to get information from one page to another you need to use sessions.
My code is displaying the information from the MySQL tables, then underneath it is giving the user the choice to edit the information in a form then send it to another file
A:
One way of easily doing this is to use <input type="hidden"> so that you can include $row['Toy_ID'] in your form.
Something like this:
$row = $result->fetch_assoc();
while ($row){
echo "Toy Name: " . $row['Toy_Name'] . "<br>" .
"Store Name: . $row['Store_Name'] . "<br>" .
"Cost: " . $row['Cost'] . "";
echo "<form action='update.php' method='post'>" .
"<input type='hidden' name='toyid' value='".$row['Toy_ID']."'>" . // here's the hidden input, which you can call by using `$_POST['toyid']`
"<label>Toy Name: </label><input name='tname'; value='" . $row['Toy_Name'] . "'><br>" .
"<label>Store Name: </label><input name='storename'; value='" . $row['Store_Name'] . "'><br>" .
"<label>Cost: </label><input name='cost'; value='" . $row['Cost'] . "'><br>" .
"<input type='submit' value='Submit'>" .
"</form></div><br><br>";
$row = $result->fetch_assoc();
}
Then change your query to make use of $_POST['toyid'] instead of $_SESSION['toyid']
|
[
"stackoverflow",
"0008188490.txt"
] | Q:
Using cURL to get google chart images through a proxy
I need to get images from Google Chart, but I'm behind a proxy.
With the code below (changing $url) I can get images from other sites, but not from google:
$url =
'http://chart.apis.google.com/chart?chs=450x270&chd=t:'.$values_list.'&cht=p&chl='.$labels_list.'&chco=80AF1B,FFFF8C&chf=bg,s,F8F8F8';
$img = '../uploads/tx_oriindicadores/triglo.png';
file_put_contents($img, t3lib_div::getURL($url));
The code of the getURL() method uses cURL functions to connect and retrieve data.
At this moment I only get an empty file.
Are there some parameters or configuraton that I care in order to get images from google?
Thanks.
The getURL() method is native of TYPO3 and you can see the code in this page:
http://doc-typo3.ameos.com/4.1.0/class_8t3lib__div_8php-source.html Line 2342
I pass the parameters through the backend of the site.
A:
The function above is right, the problem was that in the variable $labels_list there were spaces. So replacing the spaces with %20 solved the problem.
The spaces in the direct URL request are not a problem, but in cURL there are.
So as general rule don't use spaces when work with cURL, use instead %20.
|
[
"stackoverflow",
"0041821699.txt"
] | Q:
ToolbarAndroid is not displaying in react native
I am learning react-native programming, creating toolbar using this https://facebook.github.io/react-native/docs/toolbarandroid.html but in my case it is not being showed. I could not understand what exactly mistake I am doing.
Can anyone help me for this.
import React, { Component } from 'react';
import { AppRegistry, Text, View, TextInput, TouchableOpacity, ToolbarAndroid } from 'react-native';
import { ToolBar } from 'react-native-material-design';
class LoginComponent extends Component {
render() {
return (
<View style={{flex: 1, flexDirection: 'column', margin:10}}>
<ToolbarAndroid title="Login" titleColor="black"/>
<TextInput style={{height: 40, borderColor:'gray', borderWidth: .5}}
placeholder="Email address" underlineColorAndroid='transparent'/>
<TextInput style={{height: 40, borderColor:'gray', borderWidth: .5}}
placeholder="Password" secureTextEntry={true} underlineColorAndroid='transparent'/>
<TouchableOpacity style={{ height: 40, marginTop: 10 , backgroundColor: '#2E8B57'}}>
<Text style={{color: 'white', textAlign: 'center', marginTop: 10, fontWeight: 'bold'}}>LOG IN</Text>
</TouchableOpacity>
</View>
);
}
}
AppRegistry.registerComponent('Myntra', () => LoginComponent);
A:
This is a known issue. A workaround is set a height for your ToolbarAndroid.
|
[
"stackoverflow",
"0015917211.txt"
] | Q:
my Struts 2 didn't work at all
Helo All,
i'm very newb in Struts, in order to work as developer, i need to expert in Struts..
but, i should learn by my self and now, i got problem when i'm adding struts.xml
when i add struts.xml the result always shown The requested resource is not available.
when i remove it, it will come well wihtout Struts...
i've followed many simple tutorial using struts, but none of them worked on mine..
i think, there were no error in my console log...
Apr 10, 2013 10:17:39 AM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based
Apache Tomcat Native library which allows optimal performance in
production environments was not found on the java.library.path:
C:\Program
Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program
Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files
(x86)\NVIDIA
Corporation\PhysX\Common;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program
Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth
Software\syswow64;C:\Program Files (x86)\ATI
Technologies\ATI.ACE\Core-Static;c:\Program Files (x86)\Microsoft SQL
Server\90\Tools\binn\;C:\Program Files (x86)\Microsoft SQL
Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL
Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL
Server\100\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL
Server\100\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL
Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files
(x86)\Microsoft Visual Studio
9.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft
Shared\Windows Live;. Apr 10, 2013 10:17:40 AM
org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING:
[SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting
property 'source' to 'org.eclipse.jst.jee.server:TryAgain' did not
find a matching property. Apr 10, 2013 10:17:40 AM
org.apache.coyote.AbstractProtocol init INFO: Initializing
ProtocolHandler ["http-bio-8080"] Apr 10, 2013 10:17:40 AM
org.apache.coyote.AbstractProtocol init INFO: Initializing
ProtocolHandler ["ajp-bio-8009"] Apr 10, 2013 10:17:40 AM
org.apache.catalina.startup.Catalina load INFO: Initialization
processed in 893 ms Apr 10, 2013 10:17:40 AM
org.apache.catalina.core.StandardService startInternal INFO: Starting
service Catalina Apr 10, 2013 10:17:40 AM
org.apache.catalina.core.StandardEngine startInternal INFO: Starting
Servlet Engine: Apache Tomcat/7.0.39 Apr 10, 2013 10:17:41 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Parsing
configuration file [struts-default.xml] Apr 10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Unable
to locate configuration files of the name struts-plugin.xml, skipping
Apr 10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Parsing
configuration file [struts-plugin.xml] Apr 10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Parsing
configuration file [struts.xml] Apr 10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for (com.opensymphony.xwork2.ObjectFactory) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.FileManagerFactory) Apr 10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for
(com.opensymphony.xwork2.conversion.impl.XWorkConverter) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.conversion.impl.CollectionConverter) Apr 10,
2013 10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger
info INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.conversion.impl.ArrayConverter) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.conversion.impl.DateConverter) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.conversion.impl.NumberConverter) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.conversion.impl.StringConverter) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.conversion.ConversionPropertiesProcessor) Apr
10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for
(com.opensymphony.xwork2.conversion.ConversionFileProcessor) Apr 10,
2013 10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger
info INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.conversion.ConversionAnnotationProcessor) Apr
10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for
(com.opensymphony.xwork2.conversion.TypeConverterCreator) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.conversion.TypeConverterHolder) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.TextProvider) Apr 10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for (com.opensymphony.xwork2.LocaleProvider) Apr 10,
2013 10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger
info INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.ActionProxyFactory) Apr 10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for
(com.opensymphony.xwork2.conversion.ObjectTypeDeterminer) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(org.apache.struts2.dispatcher.mapper.ActionMapper) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (jakarta) for
(org.apache.struts2.dispatcher.multipart.MultiPartRequest) Apr 10,
2013 10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger
info INFO: Choosing bean (struts) for
(org.apache.struts2.views.freemarker.FreemarkerManager) Apr 10, 2013
10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Choosing bean (struts) for
(org.apache.struts2.components.UrlRenderer) Apr 10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for
(com.opensymphony.xwork2.validator.ActionValidatorManager) Apr 10,
2013 10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger
info INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.util.ValueStackFactory) Apr 10, 2013 10:17:42
AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO:
Choosing bean (struts) for
(com.opensymphony.xwork2.util.reflection.ReflectionProvider) Apr 10,
2013 10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger
info INFO: Choosing bean (struts) for
(com.opensymphony.xwork2.util.reflection.ReflectionContextFactory) Apr
10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for (com.opensymphony.xwork2.util.PatternMatcher) Apr
10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for (org.apache.struts2.dispatcher.StaticContentLoader)
Apr 10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for (com.opensymphony.xwork2.UnknownHandlerManager) Apr
10, 2013 10:17:42 AM
com.opensymphony.xwork2.util.logging.jdk.JdkLogger info INFO: Choosing
bean (struts) for (org.apache.struts2.views.util.UrlHelper) Apr 10,
2013 10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger
info INFO: Loading global messages from [ApplicationResources] Apr 10,
2013 10:17:42 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger
error SEVERE: Dispatcher initialization failed Unable to load
configuration. - action -
file:/C:/apache-tomcat-7.0.39/wtpwebapps/TryAgain/WEB-INF/classes/struts.xml:18:54
at
com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:70)
at
org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:429) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:473)
at
org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74)
at
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:51)
at
org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
at
org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
at
org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
at
org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4746)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5399)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at
java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at
java.lang.Thread.run(Unknown Source) Caused by: Action class
[HelloWorld] not found - action -
file:/C:/apache-tomcat-7.0.39/wtpwebapps/TryAgain/WEB-INF/classes/struts.xml:18:54
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:482)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:426)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:543)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:292)
at
org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:112)
at
com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:250)
at
com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
... 17 more
Apr 10, 2013 10:17:42 AM org.apache.catalina.core.StandardContext
filterStart SEVERE: Exception starting filter Struts2Filter Unable to
load configuration. - action -
file:/C:/apache-tomcat-7.0.39/wtpwebapps/TryAgain/WEB-INF/classes/struts.xml:18:54
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:485)
at
org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74)
at
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:51)
at
org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
at
org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
at
org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
at
org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4746)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5399)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at
org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at
java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at
java.lang.Thread.run(Unknown Source) Caused by: Unable to load
configuration. - action -
file:/C:/apache-tomcat-7.0.39/wtpwebapps/TryAgain/WEB-INF/classes/struts.xml:18:54
at
com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:70)
at
org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:429) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:473)
... 15 more Caused by: Action class [HelloWorld] not found - action -
file:/C:/apache-tomcat-7.0.39/wtpwebapps/TryAgain/WEB-INF/classes/struts.xml:18:54
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:482)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:426)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:543)
at
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:292)
at
org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:112)
at
com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:250)
at
com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
... 17 more
Apr 10, 2013 10:17:42 AM org.apache.catalina.core.StandardContext
startInternal SEVERE: Error filterStart Apr 10, 2013 10:17:42 AM
org.apache.catalina.core.StandardContext startInternal SEVERE: Context
[/TryAgain] startup failed due to previous errors Apr 10, 2013
10:17:42 AM org.apache.catalina.startup.HostConfig deployWAR INFO:
Deploying web application archive
C:\apache-tomcat-7.0.39\webapps\FirstStruts-Try2.war Apr 10, 2013
10:17:44 AM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter struts2
java.lang.ClassNotFoundException:
org.apache.struts2.dispatcher.StrutsPrepareAndExecuteFilter at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
at
org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:527)
at
org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:509)
at
org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:137)
at
org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
at
org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
at
org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4746)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5399)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at
org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at
org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at
org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
at
org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1655)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown
Source) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown
Source) at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at
java.lang.Thread.run(Unknown Source)
Apr 10, 2013 10:17:44 AM org.apache.catalina.core.StandardContext
startInternal SEVERE: Error filterStart Apr 10, 2013 10:17:44 AM
org.apache.catalina.core.StandardContext startInternal SEVERE: Context
[/FirstStruts-Try2] startup failed due to previous errors Apr 10, 2013
10:17:44 AM org.apache.catalina.startup.HostConfig deployWAR INFO:
Deploying web application archive
C:\apache-tomcat-7.0.39\webapps\StrutsHelloWorld.war Apr 10, 2013
10:17:44 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger
error SEVERE: Dispatcher initialization failed
java.lang.RuntimeException:
java.lang.reflect.InvocationTargetException at
com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:301)
at
com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:438)
at
com.opensymphony.xwork2.inject.ContainerBuilder$5.create(ContainerBuilder.java:207)
at com.opensymphony.xwork2.inject.Scope$2$1.create(Scope.java:51) at
com.opensymphony.xwork2.inject.ContainerBuilder$3.create(ContainerBuilder.java:93)
at
com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:487)
at
com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:484)
at
com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:584)
at
com.opensymphony.xwork2.inject.ContainerBuilder.create(ContainerBuilder.java:484)
at
com.opensymphony.xwork2.config.impl.DefaultConfiguration.createBootstrapContainer(DefaultConfiguration.java:323)
at
com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:221)
at
com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
at
org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:429) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:473)
at
org.apache.struts2.dispatcher.FilterDispatcher.init(FilterDispatcher.java:193)
at
org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
at
org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
at
org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
at
org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4746)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5399)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at
org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at
org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at
org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
at
org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1655)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown
Source) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown
Source) at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at
java.lang.Thread.run(Unknown Source) Caused by:
java.lang.reflect.InvocationTargetException at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:299)
... 31 more Caused by: java.lang.ExceptionInInitializerError at
com.opensymphony.xwork2.ognl.OgnlValueStackFactory.setContainer(OgnlValueStackFactory.java:84)
... 36 more Caused by: java.lang.IllegalArgumentException: Javassist
library is missing in classpath! Please add missed dependency! at
ognl.OgnlRuntime.<clinit>(OgnlRuntime.java:168) ... 37 more Caused
by: java.lang.ClassNotFoundException: javassist.ClassPool at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
at java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Unknown Source) at
ognl.OgnlRuntime.<clinit>(OgnlRuntime.java:165) ... 37 more
Apr 10, 2013 10:17:44 AM org.apache.catalina.core.StandardContext
filterStart SEVERE: Exception starting filter struts2
java.lang.reflect.InvocationTargetException - Class:
com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector File:
ContainerImpl.java Method: inject Line: 301 -
com/opensymphony/xwork2/inject/ContainerImpl.java:301:-1 at
org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:485) at
org.apache.struts2.dispatcher.FilterDispatcher.init(FilterDispatcher.java:193)
at
org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
at
org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
at
org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
at
org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4746)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5399)
at
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at
org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at
org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at
org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at
org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
at
org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1655)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown
Source) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown
Source) at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at
java.lang.Thread.run(Unknown Source) Caused by:
java.lang.RuntimeException:
java.lang.reflect.InvocationTargetException at
com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:301)
at
com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:438)
at
com.opensymphony.xwork2.inject.ContainerBuilder$5.create(ContainerBuilder.java:207)
at com.opensymphony.xwork2.inject.Scope$2$1.create(Scope.java:51) at
com.opensymphony.xwork2.inject.ContainerBuilder$3.create(ContainerBuilder.java:93)
at
com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:487)
at
com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:484)
at
com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:584)
at
com.opensymphony.xwork2.inject.ContainerBuilder.create(ContainerBuilder.java:484)
at
com.opensymphony.xwork2.config.impl.DefaultConfiguration.createBootstrapContainer(DefaultConfiguration.java:323)
at
com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:221)
at
com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
at
org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:429) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:473)
... 18 more Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:299)
... 31 more Caused by: java.lang.ExceptionInInitializerError at
com.opensymphony.xwork2.ognl.OgnlValueStackFactory.setContainer(OgnlValueStackFactory.java:84)
... 36 more Caused by: java.lang.IllegalArgumentException: Javassist
library is missing in classpath! Please add missed dependency! at
ognl.OgnlRuntime.<clinit>(OgnlRuntime.java:168) ... 37 more Caused
by: java.lang.ClassNotFoundException: javassist.ClassPool at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
at java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Unknown Source) at
ognl.OgnlRuntime.<clinit>(OgnlRuntime.java:165) ... 37 more
Apr 10, 2013 10:17:44 AM org.apache.catalina.core.StandardContext
startInternal SEVERE: Error filterStart Apr 10, 2013 10:17:44 AM
org.apache.catalina.core.StandardContext startInternal SEVERE: Context
[/StrutsHelloWorld] startup failed due to previous errors Apr 10, 2013
10:17:44 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory
C:\apache-tomcat-7.0.39\webapps\docs Apr 10, 2013 10:17:44 AM
org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying
web application directory C:\apache-tomcat-7.0.39\webapps\examples Apr
10, 2013 10:17:45 AM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized() Apr 10, 2013 10:17:45 AM
org.apache.catalina.core.ApplicationContext log INFO: SessionListener:
contextInitialized() Apr 10, 2013 10:17:45 AM
org.apache.catalina.core.ApplicationContext log INFO: ContextListener:
attributeAdded('org.apache.jasper.compiler.TldLocationsCache',
'org.apache.jasper.compiler.TldLocationsCache@634fbcac') Apr 10, 2013
10:17:45 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory
C:\apache-tomcat-7.0.39\webapps\host-manager Apr 10, 2013 10:17:45 AM
org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying
web application directory C:\apache-tomcat-7.0.39\webapps\manager Apr
10, 2013 10:17:45 AM org.apache.catalina.startup.HostConfig
deployDirectory INFO: Deploying web application directory
C:\apache-tomcat-7.0.39\webapps\ROOT Apr 10, 2013 10:17:45 AM
org.apache.coyote.AbstractProtocol start INFO: Starting
ProtocolHandler ["http-bio-8080"] Apr 10, 2013 10:17:45 AM
org.apache.coyote.AbstractProtocol start INFO: Starting
ProtocolHandler ["ajp-bio-8009"] Apr 10, 2013 10:17:45 AM
org.apache.catalina.startup.Catalina start INFO: Server startup in
4929 ms
i used these lib as the tutorial gives
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
log4j-1.2.9.jar
ognl-3.0.6.jar
struts2-core-2.3.12.jar
xwork-core-2.3.12.jar
A:
How can you possibly think there are no errors in your log?
SEVERE: Exception starting filter struts2
java.lang.ClassNotFoundException:
org.apache.struts2.dispatcher.StrutsPrepareAndExecuteFilter at
Which is true, there is no such class. The filter is:
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
It looks as though you also have a number of class/library issues, possibly caused by version conflicts.
|
[
"serverfault",
"0000186199.txt"
] | Q:
Cisco 3550 internal queue statistics under IOS 12.1?
I am seeing slow-down in a switched network. Looking at the points where the users are reporting slow-down to/from, I have located two Cisco 3550 as the most likely points to start digging.
Normally, I would've checked the internal queues with show platform port-asic stats, but taht command does not seem to be available in IOS 12.1, any ideas on other things I can look at to verify if these switches are (or are not) part of where the network issues are?
show interface does not show any input or output drops/errors, but when we've had similar issues in the past, it's only really been evident with the ASIC stats, so I am at a bit of a loss what to check next.
Edit: One of the interfaces is a trunk interface (GigE, carrying 28 Mbps of traffic), the other interfaces are access ports, 100 Mbps each, none of the ports is even close to "full" (the 28 Mbps is, essentially, the aggregate of the other ports).
A:
maybe a very simple and horrible wrong answer, but did you check the bitrate of the connections? and the connection between these 2 switches is set to trunk i assume?
|
[
"stackoverflow",
"0041955232.txt"
] | Q:
shared_ptr that cannot be null?
Using a std::shared_ptr expresses shared ownership and optionality (with its possibility to be null).
I find myself in situations where I want to express shared ownership only in my code, and no optionality. When using a shared_ptr as a function parameter I have to let the function check that it is not null to be consistent/safe.
Passing a reference instead of course is an option in many cases, but I sometimes would also like to transfer the ownership, as it is possible with a shared_ptr.
Is there a class to replace shared_ptr without the possibility to be null, some convention to handle this problem, or does my question not make much sense?
A:
You could write a wrapper around std::shared_ptr that only allows creation from non-null:
#include <memory>
#include <cassert>
template <typename T>
class shared_reference
{
std::shared_ptr<T> m_ptr;
shared_reference(T* value) :m_ptr(value) { assert(value != nullptr); }
public:
shared_reference(const shared_reference&) = default;
shared_reference(shared_reference&&) = default;
~shared_reference() = default;
T* operator->() { return m_ptr.get(); }
const T* operator->() const { return m_ptr.get(); }
T& operator*() { return *m_ptr.get(); }
const T& operator*() const { return *m_ptr.get(); }
template <typename XT, typename...XTypes>
friend shared_reference<XT> make_shared_reference(XTypes&&...args);
};
template <typename T, typename...Types>
shared_reference<T> make_shared_reference(Types&&...args)
{
return shared_reference<T>(new T(std::forward<Types>(args)...));
}
Please note that operator= is missing yet. You should definitely add it.
You can use it like this:
#include <iostream>
using std::cout;
using std::endl;
struct test
{
int m_x;
test(int x) :m_x(x) { cout << "test("<<m_x<<")" << endl; }
test(const test& t) :m_x(t.m_x) { cout << "test(const test& " << m_x << ")" << endl; }
test(test&& t) :m_x(std::move(t.m_x)) { cout << "test(test&& " << m_x << ")" << endl; }
test& operator=(int x) { m_x = x; cout << "test::operator=(" << m_x << ")" << endl; return *this;}
test& operator=(const test& t) { m_x = t.m_x; cout << "test::operator=(const test& " << m_x << ")" << endl; return *this;}
test& operator=(test&& t) { m_x = std::move(t.m_x); cout << "test::operator=(test&& " << m_x << ")" << endl; return *this;}
~test() { cout << "~test(" << m_x << ")" << endl; }
};
#include <string>
int main() {
{
auto ref = make_shared_reference<test>(1);
auto ref2 = ref;
*ref2 = test(5);
}
{
test o(2);
auto ref = make_shared_reference<test>(std::move(o));
}
//Invalid case
//{
// test& a = *(test*)nullptr;
// auto ref = make_shared_reference<test>(a);
//}
}
Output:
test(1)
test(5)
test::operator=(test&& 5)
~test(5)
~test(5)
test(2)
test(test&& 2)
~test(2)
~test(2)
Example on Coliru
I hope I didn't forget anything that might result in undefined behaviour.
A:
You are asking for not_null wrapper class. Fortunately your issue is already addressed by C++ experts guideline and there are already example implementations - like this one. Search for not_null class template.
|
[
"stackoverflow",
"0031258102.txt"
] | Q:
Surface Plot in Python - MemoryError
I'm trying to create a surface plot using coordinates using the following code:
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import gaussian_kde
fig = plt.figure()
ax = Axes3D(fig)
X = []
Y = []
XY = np.vstack([X, Y])
x, y = np.meshgrid(X, Y)
z = gaussian_kde(XY)(XY).tolist()
ax.plot_surface(x, y, z)
plt.show()
Assume that X and Y are long lists of floating point numbers. However, when I execute the code I get a MemoryError, which traces back to the meshgrid method: in meshgrid return [x * mult_fact for x in output].
Does anyone know how to solve this?
(When I alter the code to use a subset of the lists by writing XY = np.vstack([X[0:10], Y[0:10]]) and x, y = np.meshgrid(X[0:10], Y[0:10]) the surface plot works, but overlaps. I suppose this is due to the points not being plotted in order. Does anyone know how to resolve this also? I am new to Python...)
A:
You are trying to plot too many points. To see this give your example some fake data:
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import gaussian_kde
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
npoints = 100
X = np.linspace(0, 1, npoints)
Y = np.sin(X)
XY = np.vstack([X, Y])
x, y = np.meshgrid(X, Y)
z = gaussian_kde(XY)(XY).tolist()
ax.plot_surface(x, y, z)
plt.show()
This will work just fine, but if we make npoints=10000 then (on my machine) I can reproduce your error.
The solution depends on exactly what X and Y are. For example if they are some measured data output then you need to ask the question "do I need to plot all of this data?". In my experience if your trying to plot so many points that you get a memory error, then you won't be able to see all of the data when it is plotted anyway! So, you could down sample it, just pick every nth point. First I would suggest turning X and Y into numpy arrays
import numpy as np
X = np.array(X)
Y = np.array(Y)
Then, to get every 100th point do:
X = X[::100]
Y = Y[::100]
For more information on array slicing and indexing see the docs.
Alternatively you may feel that this "looses" some valuable information, in which case you could apply a rolling window average then separately consider the variations in each window to check you haven't missed anything. Ultimately it will all depend on what the data is.
|
[
"stackoverflow",
"0005983525.txt"
] | Q:
Removing extraneous characters in column using T-SQL
I am attempting to remove extraneous characters from data in a primary key column..the data in this column serves as a control number, and the extra characters are preventing a Web application from effectively interacting with the data.
As an example, one row may look like this:
ocm03204415 820302
I want to remove everything after the space...so the characters '820302'. I could manually do it, but, there are around 2,000 records that have these extra values in the column. It would be great if I could remove them programmatically. I can't do a simple Replace because the characters have no pattern...I couldn't define a rule to discover them...the only thing uniform is the space...although, now that I look at the data set, they do all start with 8.
Is there a way I could remove these characters programmatically? I am familiar with PL/SQL in the Oracle environment, and was wondering if Transactional SQL would offer some possibilities in the MS-SQL environment?
Thanks so much.
A:
You may want to look into the CHARINDEX function to find the space. Then you can use SUBSTRING to grab everything up to the space in a single UPDATE statement.
A:
Try this:
UPDATE YourTable
SET YourColumn = LEFT(YourColumn,CHARINDEX(' ',YourColumn)-1)
WHERE CHARINDEX(' ',YourColumn) > 1
|
[
"salesforce.stackexchange",
"0000135742.txt"
] | Q:
Custom summary formula in report using related user field
I'd like to use a custom summary formula in an opportunity report that references a user in a user lookup field on the opportunity, but not the opportunity owner themselves. Is this possible?
Currently when I create the formula, I'm able to access the opportunity owner fields and pull in the field I want, but I want to access a different user who is inside a user lookup field on the opportunity.
Any guidance is appreciated -- thanks!
A:
OOB reports on Opportunity will not make lookup records other than Account and Owner (User) available.
To get lookup fields for a custom lookup to User,
create a custom report type on Opportunity
click edit layout
add via lookup fields ( right hand side of edit layout screen)
|
[
"stackoverflow",
"0062615263.txt"
] | Q:
Consuming JSON from another API in own .NET Core API
For my project at the company I do an internship at, I was tasked with creating an API that could manage multiple admin-interfaces of other services. These admin-interfaces are controlled by API endpoints.
They asked me to start with the admin API of their "forms engine". An API which allows "tenants" (people that have a contract to use said engine) to make surveys and such. My task is to make an interface that can get the tenants, create and delete. The usual.
Thing is, I'm not getting any output from the API, even though I should. This is also the first time I am consuming JSON in .NET Core so I might be missing something.
The data structure for the /admin/tenants endpoint looks as follows:
{
"_embedded": {
"resourceList": [
{
"id": "GUID",
"name": "MockTenant1",
"key": "mocktenant1",
"applicationId": "APPGUID",
"createdAt": "SOMEDATE",
"updatedAt": "SOMEDATE"
},
{
"id": "GUID",
"name": "MockTenant2",
"key": "mocktenant2",
"applicationId": "APPGUID",
"createdAt": "SOMEDATE",
"updatedAt": "SOMEDATE"
}
]
},
"_page": {
"size": 10,
"totalElements": 20,
"totalPages": 2,
"number": 1
},
"_links": {
"self": {
"href": "SOMELINK"
},
"first": {
"href": "SOMELINK"
},
"last": {
"href": "SOMELINK"
},
"next": {
"href": "SOMELINK"
}
}
}
So I let Visual Studio automatically create following structure from said JSON:
public class Rootobject
{
public _Embedded _embedded { get; set; }
public _Page _page { get; set; }
public Dictionary<string, Href> _links { get; set; }
}
public class _Embedded
{
[JsonProperty("resourceList")]
public Tenant[] tenantList { get; set; }
}
public class Tenant
{
public string id { get; set; }
public string name { get; set; }
public string key { get; set; }
public string applicationId { get; set; }
public DateTime createdAt { get; set; }
public DateTime updatedAt { get; set; }
}
public class _Page
{
public int size { get; set; }
public int totalElements { get; set; }
public int totalPages { get; set; }
public int number { get; set; }
}
public class Href
{
public string href { get; set; }
}
I changed the Classname from ResourceList to Tenant, because that's what it is.
So, now coming to the code that gets the tenants:
public async Task<List<Tenant>> getTenants()
{
List<Tenant> tenantList = new List<Tenant>();
if (accessToken == "" || validUntil < DateTime.Now)
{
getNewAccessToken();
}
using (var request = new HttpRequestMessage(new HttpMethod("GET"), baseUrl + "admin/tenants"))
{
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}");
request.Headers.TryAddWithoutValidation("apikey", apiKey);
using (var response = await httpClient.SendAsync(request))
{
if (response.IsSuccessStatusCode)
{
try
{
Rootobject result = JsonConvert.DeserializeObject<Rootobject>(await response.Content.ReadAsStringAsync());
tenantList.AddRange(result._embedded.tenantList);
}
catch (Exception ex)
{
Debug.Write(ex);
}
}
}
}
foreach (Tenant t in tenantList)
{
Debug.Write(t);
}
return tenantList;
}
The Debug.Write(t) and the return give me nothing. It is an empty list.
Anybody have any idea as to why this is, and what I can do about it?
Thanks in advance and kind regards
Lennert
A:
Property name must match json object name either directly or via JsonPropertyAttribute
public class _Embedded
{
[JsonProperty("resourceList")]
public List<Tenant> tenantList { get; set; }
}
You may optimize the hrefs
public class Rootobject
{
public _Embedded _embedded { get; set; }
public _Page _page { get; set; }
public Dictionary<string, Href> _links { get; set; }
}
public class Href
{
public string href { get; set; }
}
HttpResponseMessage is IDisposable
using(var response = await httpClient.SendAsync(request))
{
// reading response code
}
As per Documentation
HttpClient is intended to be instantiated once per application, rather than per-use.
remove
using (var httpClient = new HttpClient())
and add field
private static readonly HttpClient httpClient = new HttpClient();
foreach(Tenant tenant in result._embedded.tenantList) can be optimized
foreach(Tenant tenant in result._embedded.tenantList)
{
tenantList.Add(tenant);
}
Or single line
tenantList.AddRange(result._embedded.tenantList);
Or simply
foreach(Tenant t in result._embedded.tenantList)
{
Debug.Write(t);
}
return result._embedded.tenantList;
|
[
"stackoverflow",
"0011444009.txt"
] | Q:
Single Page Application Server Separation of Concern
Im just in the process of putting together the base framework for a multi-tenant enterprise system.
The client-side will be a asp.net mvc webpage talking to the database through the asp.net web api through ajax.
My question really resides around scalability. Should I seperate the client from the server? i.e. Client-side/frontend code/view in one project and webapi in another seperate project server.
Therefore if one server begins (server A) to peak out with load/size than all need to do is create another server instance (server B) and all new customers will point to the webapi's on server B.
Or should it be all integrated as one project and scale out the sql server side of things as load increase (dynamic cloud scaling)?
Need some advice before throwing our hats into the ring.
Thanks in advance
A:
We've gone with the route of separating out the API and the single page application. The reason here is that it forces you to treat the single page application as just another client, which in turn results in an API that provides all the functionality you need for a full client...
In terms of deployment we stick the single page application as the website root with a /api application containing the API deployment. In premise we can then use application request routing or some content-aware routing mechanism to throw things out to different servers if necessary. In Azure we use the multiple websites per role mechanism (http://msdn.microsoft.com/en-us/library/windowsazure/gg433110.aspx) and scale this role depending upon load.
Appearing to live in the same domain makes things easier because you don't have to bother with the ugliness that is JSONP or CORS!
Cheers,
Dean
|
[
"stackoverflow",
"0046462943.txt"
] | Q:
Jersey client side receive pojo us bytes
small question, but I can't find an answer on the internet... or I just don't know where to search. Is there any possibility to have a Restful method (Java EE) that returns back to the client a POJO serialized us bytes (using ByteArrayOutputStream, FlatBuffers or some other library). And the client to cast the bytes back to a POJO object by using jquery or javascript in general ( us client side )? ( What I had found until now, is receiving back a JSON/ XML)
Thanks in advanced
A:
Directly converting POJO to bytes won't work as your client (javascript or so) won't know how to convert the bytes back to POJO. What you can do is this. Say your response is objA. The do this. Convert objA to String (JSON maybe) and then Base64 encode it to get byte[]. Put it inside a wrapper object objB. Return objB as a JSON from your service. Your client can just take that byte[] and since it knows that the byte[] is base64 it will be able to get the original information from there.
May I ask the intent of doing this instead of XML/JSON?
|
[
"stackoverflow",
"0007851022.txt"
] | Q:
Stopping auto-scrolling to bottom of listbox
I am using Telerik's RadGridView within a UserControl to display a list of messages received from an XMPP server. I have been able to set it so that when I receive a message I can scroll to the bottom of the list with something like this:
private GridViewScrollViewer scrollViewer;
void controller_OnMessageReceived(object sender, EventArgs e)
{
scrollViewer = receivedMessageList.ChildrenOfType<GridViewScrollViewer>().FirstOrDefault();
scrollViewer.ScrollToBottom();
}
However what I want to be able to do is disable the auto scrolling when the user uses the scroll bar and then re-enable it when he scrolls to the bottom of the list. I thought I could attach to the ScrollChanged event but that doesn't seem to hold enough information for me to use.
As a slight addition to this in the Loaded event of the control, and the RadGridView the scrollViewer call I have above comes as null. I thought that once the control was Loaded that all UI elements are ready?
A:
About the null scrollViewer variable, I guess when you load the control, the scrollViewer is not shown since there is nothing in it yet. Try setting:
ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollBarVisibility="Visible"
In your XAML
Now for the actual problem:
You could monitor the HorizontalOffset and the VerticalOffset of the scrollviewer:
Create two Double fields in your class to store them and then, before calling ScrollToBottom(), compare the current values to the ones saved.
If the user manually moved the scrollbars, the values will be different and you don't scroll, otherwise you ScrollToBottom().
|
[
"math.stackexchange",
"0000542645.txt"
] | Q:
Calculate double integral of ...
I was doing a homework problem but now I'm stuck. The problem says:
Calculate $\iint_{S} \frac{dx dy}{\sqrt{2a - x}}$ where S is a circle of radius $a$ which is tangent to to both coordinate axes and is in the first quadrant
The cartesian equation for a circle of radius a, and center C(a,a) is:
$$(x-a)^{2}+(y-a)^{2} = a^{2}$$
Sketching this equation for different values of $a$ I obtained the limits of integration for the double integral:
$$4\int_{a}^{2a} \int_{a}^{a+\sqrt{2ay-y^{2}}} \frac{1}{\sqrt{2a-x}}dx dy$$
It is multiplied by 4 because that double integral only calculates a quarter of the desired area. Then evaluating the double integral I obtained this:
$$4 \left ( 2a^{3/2}+2\int_{a}^{2a} \sqrt{a+\sqrt{2ay-y^{2}}} dy \right )$$
But I was stuck on this (I've tried to put the indefinite integral$\int \sqrt{a+\sqrt{2ay - y^{2}}} dy$ into Wolfram Alpha and I obtained this ), then I said "why I don't use polar coordinates?" and I used them, and I obtained this double integral:
$$4\int_{0}^{\pi /2} \int_{0}^{a}\frac{r}{\sqrt{2a-rcos\theta}} dr d\theta$$
I evaluated it, and I obtained:
$$4\left ( \int_{0}^{\pi/2} -\frac{2}{3}\left ( \sec ^{2} \theta \sqrt{2a-\arccos {\theta}} \left ( 4a + acos\theta \right ) \right ) d\theta \right )$$
But Wolfram says this for the indefinite integral so... What can I do? Am I wrong in something? Is there another way to do it? I would appreciate any help.
A:
Change the order of integration.
$$\begin{align}
\iint_S \frac{dx\,dy}{\sqrt{2a-x}} &= \int_0^{2a} \frac{1}{\sqrt{2a-x}}\left(\int_{a-\sqrt{a^2-(x-a)^2}}^{a+\sqrt{a^2-(x-a)^2}}dy\right) dx\\
&= \int_0^{2a}\frac{2\sqrt{2ax-x^2}}{\sqrt{2a-x}}\,dx\\
&= \int_0^{2a} 2\sqrt{x}\,dx.
\end{align}$$
You can take it from there, I'm sure.
|
[
"stackoverflow",
"0058266984.txt"
] | Q:
dxScheduler timeline view centered at current time indicator
I went through devExtreme documentation and examples but I can't find a solution for this...
In a Razor view I am loading a dxScheduler as follows (it's bound to a db object where "orders" and "resources" are defined):
<div id="scheduler"></div>
and
<script>
$(function () {
$("#scheduler").dxScheduler({
dataSource: orders,
views: ["timelineDay"],
currentView: "timelineDay",
showCurrentTimeIndicator: true,
shadeUntilCurrentTime: true,
firstDayOfWeek: 0,
startDayHour: 0,
endDayHour: 24,
cellDuration: 15,
groups: ["areaId"],
resources: [{
fieldExpr: "areaId",
allowMultiple: false,
dataSource: resources,
label: ""
}],
height: "100%"
})
});
</script>
It works fine. However, while keeping cellDuration = 15 mins:
I would like the scheduler to be centered around the current time indicator (i.e. the vertical line that represents datetime.now...)
At the same time "startDayHour" has to be "0" and "endDayHour" has to be "24", as they are now.
Any suggestion would be appreciated. Thanks.
A:
It turned out that I was looking at the "Configuration" section only. But there are "Methods" too...
The answer is to use the "scrollToTime" method.
Reference:
https://js.devexpress.com/Documentation/ApiReference/UI_Widgets/dxScheduler/Methods/#scrollToTimehours_minutes_date.
Updated working example (it's straightforward then to set the argument of "scrollToTime" dynamic).
$(function () {
$("#scheduler").dxScheduler({
dataSource: orders,
views: ["timelineDay"],
currentView: "timelineDay",
showCurrentTimeIndicator: true,
shadeUntilCurrentTime: true,
firstDayOfWeek: 0,
startDayHour: 0,
endDayHour: 24,
cellDuration: 15,
groups: ["areaId"],
resources: [{
fieldExpr: "areaId",
allowMultiple: false,
dataSource: resources,
label: ""
}],
height: "100%",
onContentReady: function (e) {
e.component.scrollToTime(5, 30, new Date());
}
})
});
|
[
"stackoverflow",
"0048186343.txt"
] | Q:
How do I find newlines in vi?
How do I find all newlines in a text file in vi? In fact, I'm trying to find two newlines in succession.
For the moment I'm just trying to find single newlines:
:\n
But that gives:
E10: \ should be followed by /, ? or &
A:
: is used to enter commandos. You need the / (without anything in advance).
/\n\n
finds two consecutive newlines.
:%s/\n\n/\r/
replaces two consecutive newlines with a single one. Note the \r in the replacement section.
|
[
"codereview.stackexchange",
"0000083359.txt"
] | Q:
Simplifying Tic Tac Toe game
I'm in a little bit of a pickle on my Tic Tac Toe program because I can't see how to simplify the code without breaking it. Do I need to make my code modular?
public partial class dglassAssign4 : Form
{
string[] asImArr;
const int ciArrSize = 9;
int[] aiOrdArr;
int turn = 1;
bool click0 = false, click1 = false, click2 = false, click3 = false, click4 = false, click5 = false, click6 = false, click7 = false, click8 = false;
bool x0, o0, x1, o1, x2, o2, x3, o3, x4, o4, x5, o5, x6, o6, x7, o7, x8, o8,over;
public dglassAssign4()
{
asImArr = new string[] {"WO.jpg", "WX.jpg", "BO.jpg", "RX.jpg" };
aiOrdArr = new int[ciArrSize];
InitializeComponent();
}
private void btnGame_Click(object sender, EventArgs e)
{
gameOver();
}
private void dglassAssign4_Load(object sender, EventArgs e)
{
}
private void pb0_Click(object sender, EventArgs e)
{
if (click0==false)
{
if(turn%2!=0)
{
pb0.Image = Image.FromFile("WX.jpg");
x0 = true;
}
else
{
pb0.Image = Image.FromFile("WO.jpg");
o0 = true; ;
}
turn++;
click0 = true;
endGame(turn);
}
}
private void pb1_Click(object sender, EventArgs e)
{
if (click1 == false)
{
txtOut.Text = "";
if (turn % 2 != 0)
{
pb1.Image = Image.FromFile("WX.jpg");
x1 = true;
}
else
{
pb1.Image = Image.FromFile("WO.jpg");
o1 = true;
}
turn++;
click1 = true;
endGame(turn);
}
}
private void pb2_Click(object sender, EventArgs e)
{
if (click2 == false)
{
txtOut.Text = "";
if (turn % 2 != 0)
{
pb2.Image = Image.FromFile("WX.jpg");
x2 = true;
}
else
{
pb2.Image = Image.FromFile("WO.jpg");
o2 = true;
}
turn++;
click2 = true;
endGame(turn);
}
}
private void pb3_Click(object sender, EventArgs e)
{
if (click3 == false)
{
txtOut.Text = "";
if (turn % 2 != 0)
{
pb3.Image = Image.FromFile("WX.jpg");
x3 = true;
}
else
{
pb3.Image = Image.FromFile("WO.jpg");
o3 = true;
}
turn++;
click3 = true;
endGame(turn);
}
}
private void pb4_Click(object sender, EventArgs e)
{
if (click4 == false)
{
txtOut.Text = "";
if (turn % 2 != 0)
{
pb4.Image = Image.FromFile("WX.jpg");
x4 = true;
}
else
{
pb4.Image = Image.FromFile("WO.jpg");
o4 = true;
}
turn++;
click4 = true;
endGame(turn);
}
}
private void pb5_Click(object sender, EventArgs e)
{
if (click5 == false)
{
txtOut.Text = "";
if (turn % 2 != 0)
{
pb5.Image = Image.FromFile("WX.jpg");
x5 = true;
}
else
{
pb5.Image = Image.FromFile("WO.jpg");
o5 = true;
}
turn++;
click5 = true;
endGame(turn);
}
}
private void pb6_Click(object sender, EventArgs e)
{
if (click6 == false)
{
txtOut.Text = "";
if (turn % 2 != 0)
{
pb6.Image = Image.FromFile("WX.jpg");
x6 = true;
}
else
{
pb6.Image = Image.FromFile("WO.jpg");
o6 = true;
}
turn++;
click6 = true;
endGame(turn);
}
}
private void pb7_Click(object sender, EventArgs e)
{
if (click7 == false)
{
txtOut.Text = "";
if (turn % 2 != 0)
{
pb7.Image = Image.FromFile("WX.jpg");
x7 = true;
}
else
{
pb7.Image = Image.FromFile("WO.jpg");
o7 = true;
}
turn++;
click7 = true;
endGame(turn);
}
}
private void pb8_Click_1(object sender, EventArgs e)
{
if (click8 == false)
{
txtOut.Text = "";
if (turn % 2 != 0)
{
pb8.Image = Image.FromFile("WX.jpg");
x8 = true;
}
else
{
pb8.Image = Image.FromFile("WO.jpg");
o8 = true;
}
turn++;
click8 = true;
endGame(turn);
}
}
private void endGame(int turn)
{
if(turn >= 5)
{
if (x0 == true && x1 == true && x2 == true || x3 == true && x4 == true && x5 == true || x6 == true && x7 == true && x8 == true || x0==true && x3==true && x6 ==true || x1==true && x4==true && x7==true ||x2==true && x5==true && x8==true|| x0==true && x4==true && x8==true ||
x2 == true && x4 == true && x6 == true || o0 == true && o1 == true && o2 == true || o3 == true && o4 == true && o5 == true || o6 == true && o7 == true && o8 == true || o0 == true && o3 == true && o6 == true || o1 == true && o4 == true && o7 == true || o2 == true && o5 == true && o8 == true || o0 == true && o4 == true && o8 == true ||
o2 == true && o4 == true && o6 == true)
{
txtOut.Text = ("Winner!!!");
over = true;
gameOver();
}
}
}
private void gameOver()
{
pb0.Image = null;
pb1.Image = null;
pb2.Image = null;
pb3.Image = null;
pb4.Image = null;
pb5.Image = null;
pb6.Image = null;
pb7.Image = null;
pb8.Image = null;
click0 = false;
click1 = false;
click2 = false;
click3 = false;
click4 = false;
click5 = false;
click6 = false;
click7 = false;
click8 = false;
x0 = false;
x1 = false;
x2 = false;
x3 = false;
x4 = false;
x5 = false;
x6 = false;
x7 = false;
x8 = false;
o0 = false;
o1 = false;
o2 = false;
o3 = false;
o4 = false;
o5 = false;
o6 = false;
o7 = false;
o8 = false;
turn = 1;
}
}
}
A:
All your click event handlers can be condensed to one handler. Also instead of keeping track of which picturebox has been clicked you could simple disable the picturebox once it's been clicked. Possible something like this:
private void pb_Click_1(object sender, EventArgs e)
{
PictureBox pb = (PictureBox)sender;
txtOut.Text = "";
if (turn % 2 != 0)
{
pb.Image = Image.FromFile("WX.jpg");
}
else
{
pb.Image = Image.FromFile("WO.jpg");
}
turn++;
pb.Enabled = false;
endGame(turn);
}
}
Assigning more than one control to a handler is easily done in VS via the event properties. Simply give the click event for each control the same method to use.
|
[
"stackoverflow",
"0022008198.txt"
] | Q:
Haskell, MongoDB driver, >>=, and <<=
EDIT: Wanted to get this in real quick before the forum moderator trolls shut this down (they've been retroactively going through my posts which are months old, down voting them, then closing them). The problem is either the driver or the docs, because the example code has the same issue when I run it.
I'm trying to evaluate Haskell in terms of using it with MongoDB. I've tried to write my own simple program to do simple things to a database using examples on this driver page https://github.com/TonyGen/mongoDB-haskell . I can get as far as opening a connection and even making inserts into a database (I checked the DB, everything makes it inside). The problem I'm running into is, once I open a connection and do something, I can't get the Haskell program to "come back" to the interpreter, print some value, or do anything else. This may be the wrong word, but I think the program is essentially "locked."
Not sure, but I believe that I'm not terminating correctly inside the "do" notation, thus I think it's just sitting there. In looking at the examples on the driver page, I notice that it makes use of operators such as >>= and <<=. I suspect (not sure) that I need one or both of these operators to terminate from the "do," or somehow finish what I'm doing.
I'd just like some clear examples of an operator or operators I need and how to use them to finish this "do" and get back to the interpreter, possibly with some return value like "finished" or whatever. The explanation should be in very basic, practical, plain-spoken, matter of fact terms, spoken in an almost unsophisticated or juvenile way. The explanation should not focus on how it does what it does, why it does what it does, or what goes on inside this operator or operators. It should just be how to use it to do "such and such."
An example (wrong in what it instructs, correct in how the instruction should look):
"See that thing that looks like a backwards arrow (<<=)? That's called the
'backwards arrow operator.' Any time we want to stop execution from a do,
and shoot information back from the monadic world to the world of pure Haskell,
we use that operator to do it. How it works is, you stick the information you
want to shoot back on the right hand side. On the left, you
stick...."
I don't want any explanation of what a monad is, how to use a monad, what goes on inside a monad, how a monad works, etc. I've consulted the literature numerous times.
I also don't want explanations of what these operators such as >>= or <<= are, or how they work, what they are doing, etc. I want explanations of HOW TO USE THEM (if needed), just not the theoretical (or other) stuff.
I've already scanned this website and other documentation but couldn't find what I was looking for in the format I wanted it (described above).
EXAMPLE CODE
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-}
import Database.MongoDB
import Control.Monad.Trans (liftIO)
main = do
pipe <- runIOE $ connect (host "127.0.0.1")
e <- access pipe master "test" run
close pipe
print e
run = do
test_insert
-- missing something here? tried return "finished" and other things
test_insert = insertMany "blah" [ stuff... ]
A:
So, the request is to explain the bind operator (>>=) -- the central operation of the Moand class -- without getting into Monads. Why not, I love a challenge.
Start with >> it works like a semicolon in other languages. It lets you stick two actions in one line. This is a lie, but you don't want to face the truth. (The truth involves understanding the difference between actions and functions.)
But what happens if we need to use the result of one action in the next? The >>= operator take the result of one action and feeds it as the argument to the next one (=<< does the same thing only backwards).
So, allTeams >>= printDocs "All Teams" is the same as
do
teams <- allTeams
printDocs "All Teams" teams
And, allTeams = rest =<< find (select [] "team") {sort = ["home.city" =: 1]}
allTeams = do
cursor <- find (select [] "team") {sort = ["home.city" =: 1]}`
rest cursor
In fact, you can translate any do block into a set of >>= equations and any set of >>= equations into a do block mechanically.
At this point, you should really be confused about why the need for such convoluted syntax with actions and also be running into some really obtuse type errors. When you have become too frustrated by these things I will lay before you two choices:
Admit that you need to actually know a little something about why haskell is very different from imperative languages; need to understand the differenc between actions and functions; and figure out that this isn't just all about a lousy syntax, or
Decide that haskell has nothing interesting to offer you and return to coding in Prolog.
Should you choose option 1 Here is where you need to start.
Update debugging
So what we know is that the insertMany action hit the database. Did it actually return. I note that you are using master access mode which means that access is going to wait until MongoDB gets back to it with confirmation that the data is written.
There is also that close pipe action. This could block in theory. lets do this the cheap way and just add some print statements:
main = do
putStrLn "Start --"
pipe <- runIOE $ connect (host "127.0.0.1")
e <- access pipe master "test" run
liftIO $ putStrLn "before close pipe"
close pipe
print e
putStrLn "\n Finished"
run = do
liftIO $ putStrLn "before insert"
test_insert
liftIO $ putStrLn "after insert"
test_insert = insertMany "blah" [ stuff... ]
From what you describe we should see
Start --
before insert
^C -- we got stuck here
If this is the case, I will need to see stuff...
If you get farther through the program (my gut says you will see "after insert" but not "before close pipe") then we need to talk about whether haskell is communicating correctly with Mongo. Even if it recorded the insert correctly, the pipe may still be "on hold" waiting for a synchronizing event that is not coming.
We can then believe that it is not incorrect use of haskell but incorrect use of the MongoDB library and ask another SO question with that in mind.
|
[
"math.stackexchange",
"0002641583.txt"
] | Q:
Is a smooth injective map an immersion?
I am trying to work out some basic properties of immersions/submersions/embeddings etc. Is the following reasoning correct?
Let $M,N$ be smooth manifolds, and $f:M \rightarrow N$ a smooth injective map.
Since $rk (f_*)$ is equal to the dimension of $M$, then $f$ is a map of constant rank, and hence an embedding.
A:
The conclusion $rk(f_*)$ is equal to the dimension of $M$ is not correct.
Consider the map $f : \mathbb{R} \to \mathbb{R}$ given by $f(x)=x^3$.
The rank of its derivative at $x=0$ is 0.
Consider a map $f : M \to N$. Let $f_*$ denote the derivative of $f$. Let's recall some definitions:
Immersion: $f_*$ is everywhere injective
Embedding: $f_*$ is everywhere injective + $f$ is a homeomorphism onto its image.
Example of immersion that is not an embedding: immersing the circle as a figure eight on the plane $\gamma : (-\frac{\pi}{2},\frac{3\pi}{2}) \to \mathbb{R}^2$ given by $\gamma(t)=(\sin(2t),\cos(t))$.
It is injective. But it is not an embedding: the figure eight is not compact in the subspace topology of $\mathbb{R}^2$, whereas the domain is compact in the subspace topology coming from $\mathbb{R}$.
On the other hand, if a smooth injective map has constant rank then it is an immersion. This follows from the constant rank theorem, i.e. that in local coordinates any smooth map $f : M \to N$, $m=\dim M$, $n=\dim N$, with constant rank $k$ can be written as $(x_1,\cdots,x_k,x_{k+1},\cdots, x_m) \mapsto (x_1,\cdots,x_k,0,\cdots,0)$.
Finally, if $f: M \to N$ is an injective immersion and either $M$ is compact or $f$ is proper, then $f$ is an embedding.
|
[
"moderators.stackexchange",
"0000003050.txt"
] | Q:
Marketing & Promoting Your Community
I'm starting a new online business which focuses heavily on media, but I'm not sure the best way to communicate with my audience and clients via social media.
A rough plan is to have multiple social networks for business purposes, but to have a single account to for making contact with people and communicating what's happening accross different areas of my business - Like so:
Business ... @business
Business : Media Division ... @business_media
Business : Media Division : Brand ... @brandname
Administration For Media & Brands ... @_???
So should my Administration account reflect the business in some way (@business_media_???), or could it be a personal (@my_name)?
Any ideas on the best way to go about this?
A:
There's two different situations where one might be better than another: if you're sending the email personally or for your business.
If you're speaking on behalf of the business: use @business_media_???. This way it's clearer that it's coming from the company and not just you.
If you're speaking on behalf of only yourself: use @my_name. This way it's clear that you're the one sending the email, not the company.
|
[
"crypto.stackexchange",
"0000047700.txt"
] | Q:
Modelling broadcast functionality in Universally Composable Framework
I'm studying the UC framework by Canetti. While I understand the basic idea, there are still a lot of details that I need to work through.
One thing that's puzzling me is how to achieve concurrency under the UC execution mode. For example, in many distributed algorithms, a machine may broadcast a message and then every receiver may do some computation on the message. The result of the computation may be broadcasted again.
The paper says
In order to simplify the process of determining the next ITI to be activated, we allow an ITI to execute at most a single external-write instruction per activation.
In that case, how does one capture a broadcast functionality, both as an ideal functionality as well as a real protocol?
A:
I think this would be the relevant paper to understand how to model synchronicity in the UC model:
Universally composable synchronous computation: Jonathan Katz and Ueli Maurer and Bjoern Tackmann and Vassilis Zikas (TCC 2013)
Basically, they define a "clock" functionality that performs a "tick" (increments a public counter) only after all honest parties indicate that they are done with the current round's activities.
To answer your question about "sending a message to all parties": In this paper, communication channels are modeled by having parties explicitly poll the channel to receive a message when they're ready. So to broadcast a message, send a command to the broadcast functionality. The functionality waits to be activated by honest parties who request to read from the broadcast channel.
|
[
"stackoverflow",
"0004933980.txt"
] | Q:
How do I correctly populate a listbox from an observable collection?
I've simplified this just to show what is needed to demonstrate the problem - which is that while 8 items are clearly in the listbox they have no content, i.e. 'Name' does not display, they are just blanks. If I set a breakpoint just after the ItemSource has been set I can see that the the source has been correctly populated with the collection so I assume something must be wrong with my xaml. Here is the code and xaml:
public partial class MainPage : UserControl
{
private ObservableCollection<ToolboxItem> ToolboxItems;
public MainPage()
{
InitializeComponent();
InitToolboxItems();
lstToolbox.ItemsSource = ToolboxItems;
}
private void InitToolboxItems()
{
ToolboxItems = new ObservableCollection<ToolboxItem>();
ToolboxItems.Add(new ToolboxItem(name: "Item1"));
ToolboxItems.Add(new ToolboxItem(name: "Item2"));
ToolboxItems.Add(new ToolboxItem(name: "Item3"));
ToolboxItems.Add(new ToolboxItem(name: "Item4"));
ToolboxItems.Add(new ToolboxItem(name: "Item5"));
ToolboxItems.Add(new ToolboxItem(name: "Item6"));
ToolboxItems.Add(new ToolboxItem(name: "Item7"));
ToolboxItems.Add(new ToolboxItem(name: "Item8"));
}
public struct ToolboxItem
{
public String Name;
public ToolboxItem(String name) { Name = name; }
}
}
<Grid x:Name="LayoutRoot" Background="White">
<ListBox Name="lstToolbox" Width="200" Height="280">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Width="100" Height="20" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
A:
Even though it isn't really a Question (cf. earlier comments), your problem stems from the fact that the Field 'Name' on your ToolBoxItem needs to be a Property to be able to bind to. So change it to:
public string Name {get; set;}
and it should work.
|
[
"stackoverflow",
"0012964006.txt"
] | Q:
Get Photo_ID in PHP SDK
How do i get the Photo_ID from an photo which my app uploaded with the PHP SDK Code:
$facebook->setFileUploadSupport(true);
$img = '/tmp/mypic.png';
$photo = $facebook->api(‘/me/photos’, ‘POST’,
array( ‘source’ => ‘@’ . $img,
‘message’ => ‘Photo uploaded via the PHP SDK!’
));
Didnt see that it will give any response.
A:
The response of a successful upload is the id of the photo, example:
{
"id": "1001207389476"
}
So $photo should hold a similar value.
|
[
"stackoverflow",
"0051791732.txt"
] | Q:
When tunnelling a TLS connection, how to pass additional information?
I have created a bare-bones HTTP proxy that performs HTTP tunnelling using HTTP CONNECT method.
const http = require('http');
const https = require('https');
const pem = require('pem');
const net = require('net');
const util = require('util');
const createHttpsServer = (callback) => {
pem.createCertificate({
days: 365,
selfSigned: true
}, (error, {serviceKey, certificate, csr}) => {
const httpsOptions = {
ca: csr,
cert: certificate,
key: serviceKey
};
const server = https.createServer(httpsOptions, (req, res) => {
// How do I know I here whats the target server port?
res.writeHead(200);
res.end('OK');
});
server.listen((error) => {
if (error) {
console.error(error);
} else {
callback(null, server.address().port);
}
});
});
};
const createProxy = (httpsServerPort) => {
const proxy = http.createServer();
proxy.on('connect', (request, requestSocket, head) => {
// Here I know whats the target server PORT.
const targetServerPort = Number(request.url.split(':')[1]);
console.log('target server port', targetServerPort);
const serverSocket = net.connect(httpsServerPort, 'localhost', () => {
requestSocket.write(
'HTTP/1.1 200 Connection established\r\n\r\n'
);
serverSocket.write(head);
serverSocket.pipe(requestSocket);
requestSocket.pipe(serverSocket);
});
});
proxy.listen(9000);
};
const main = () => {
createHttpsServer((error, httpsServerPort) => {
if (error) {
console.error(error);
} else {
createProxy(httpsServerPort);
}
});
};
main();
The server accepts a HTTPS connection and responds with "OK" message without forwarding the request further.
As you can see in the code (see // Here I know whats the target server PORT.), I can obtain the target server's port within the HTTP CONNECT event handler. However, I am unable to figure out how to pass this information to the createHttpsServer HTTP server router (see // How do I know I here whats the target server port?).
When tunnelling a TLS connection, how to pass additional information?
The above code can be tested by running:
$ node proxy.js &
$ curl --proxy http://localhost:9000 https://localhost:59194/foo.html -k
The objective is to respond with "OK localhost:59194".
A:
You can't add anything to a TLS stream (thankfully), short of tunneling it inside another protocol—which is what the Connect method already does. But, since you have the HTTP proxy and the HTTPS server in the same codebase, you don't need to fling the TLS stream over the network another time. Instead, you want to parse the TLS stream, and then you can pass any variables to the code that handles it.
However, after parsing TLS you'll still have a raw HTTP stream, and you'll need an HTTP server to turn it into requests and to handle responses.
The quick and rather dirty way to go about it is to use Node's HTTPS server to both decode TLS and parse HTTP. But the server's API doesn't provide for dealing with sockets that are already connected, and server's code isn't cleanly separated from connection code. So you need to hijack the server's internal connection-handling logic—this is of course susceptible to breakage in case of future changes:
const http = require('http');
const https = require('https');
const pem = require('pem');
const createProxy = (httpsOptions) => {
const proxy = http.createServer();
proxy.on('connect', (request, requestSocket, head) => {
const server = https.createServer(httpsOptions, (req, res) => {
res.writeHead(200);
res.end('OK');
});
server.emit('connection', requestSocket);
requestSocket.write('HTTP/1.1 200 Connection established\r\n\r\n');
});
proxy.listen(9000);
};
const main = () => {
pem.createCertificate({
days: 365,
selfSigned: true
}, (error, {serviceKey, certificate, csr}) => {
createProxy({
ca: csr,
cert: certificate,
key: serviceKey
});
});
};
main();
To avoid creating an HTTPS server instance on every request, you can move the instance out and tack you data onto the socket object instead:
const server = https.createServer(httpsOptions, (req, res) => {
res.writeHead(200);
// here we reach to the net.Socket instance saved on the tls.TLSSocket object,
// for extra dirtiness
res.end('OK ' + req.socket._parent.marker + '\n');
});
proxy.on('connect', (request, requestSocket, head) => {
requestSocket.marker = Math.random();
server.emit('connection', requestSocket);
requestSocket.write('HTTP/1.1 200 Connection established\r\n\r\n');
});
With the above code, if you do several successive requests:
curl --proxy http://localhost:9000 https://localhost:59194/foo.html \
https://localhost:59194/foo.html https://localhost:59194/foo.html \
https://localhost:59194/foo.html https://localhost:59194/foo.html -k
then you'll also notice that they're processed on a single connection, which is nice:
OK 0.6113572936982015
OK 0.6113572936982015
OK 0.6113572936982015
OK 0.6113572936982015
OK 0.6113572936982015
I can't quite vouch that nothing will be broken by handing the socket to the HTTPS server while the proxy server already manages it. The server has the presence of mind to not overwrite another instance on the socket object, but otherwise seems to be rather closely involved with the socket. You'll want to test it with longer-running connections.
As for the head argument, which can indeed contain initial data:
you might be able to put it back on the stream with requestSocket.unshift(head), but I'm not sure that it won't be immediately consumed by the proxy server.
Or, you might be able to chuck it over to the HTTPS server with requestSocket.emit('data', head) since the HTTP server seems to use the stream events, however TLS socket source calls read() for whatever reason, and that's mutually exclusive with the events, so I'm not sure how they even work with each other.
One solution would be to make your own wrapper for stream.Duplex that will forward all calls and events, except for read() in the case when this initial buffer exists—and then use this wrapper in place of requestSocket. But you'll then need to replicate the 'data' event also, in accordance with the logic of Node's readable streams.
Finally, you can try creating a new duplex stream, write head and pipe the socket to it, like you did initially, and use the stream in place of the socket for the HTTPS server—not sure that it will be compatible with HTTP server's rather overbearing management of the socket.
An cleaner approach is to decode the TLS stream and use a standalone parser for the resultant HTTP stream. Thankfully, Node has a tls module that is nicely isolated and turns TLS sockets into regular sockets:
proxy.on('connect', (request, requestSocket, head) => {
const httpSocket = new tls.TLSSocket(requestSocket, {
isServer: true,
// this var can be reused for all requests,
// as it's normally saved on an HTTPS server instance
secureContext: tls.createSecureContext(httpsOptions)
});
...
});
See caveats on tls.createSecureContext regarding replicating the behavior of the HTTPS server.
Alas, Node's HTTP parser isn't so usable: it's a C library, which necessitates quite a bit of legwork between the socket and the parser calls. And the API can (and does) change between versions, without warnings, with a larger surface for incompatibilities compared to the HTTP server internals used above.
There are NPM modules for parsing HTTP: e.g. one, two, but none seem too mature and maintained.
I also have doubts about the feasibility of a custom HTTP server because network sockets tend to require plenty of nurture over time due to edge cases, with hard-to-debug timeout issues and such—which should all be already accounted for in the Node's HTTP server.
P.S. One possible area of investigation is how the Cluster module handles connections: afaik the parent process in a cluster hands connection sockets over to the children, but it doesn't fork on every request—which suggests that the child processes somehow deal with connected sockets, in code that's outside of an HTTP server instance. However, since the Cluster module is now in the core, it may exploit non-public APIs.
|
[
"superuser",
"0000176456.txt"
] | Q:
What's the shortcut to Device Manager?
What is the shortest route to Device Manager?
A:
Click on the Start menu and type (or type the same in a command-line window, CMD.EXE):
devmgmt.msc
Or you can just type Device Manager and it should come up.
A:
My typical route to get to the Device Manager window is Windows Key + Pause/Break. This will get you to the System Properties window. Device Manager is just two clicks away:
A:
Create a new shortcut.
Enter devmgmt.msc as the target.
Give the shortcut a name. For example: Device Manager.
Optionally, pin the resulting shortcut to your taskbar for even faster access.
|
[
"scifi.stackexchange",
"0000056520.txt"
] | Q:
Why didn't Thanos come to Earth to retrieve Tesseract by himself?
In the Avengers movie, why didn't Thanos personally come to Earth instead of Loki? Or, if Loki's skills were required, why didn't he come with Chitauri? He knew that humans were primitive; there wouldn't be any threat and he could personally secure Tesseract.
AFAIK, the movie didn't display much. Is there any other source answering this?
A:
Thanos is a consummate mastermind. Though his physical, mental and metahuman capacities easily rival any being on Marvel's Earth, he is prone to work with proxies when he deems the challenge insufficient to warrant his direct attentions.
Earth-616 Marvel's Primary Continuity
Thanos is one of the most highly developed of the major Marvel villains in their prime continuity. Having swung from completely evil to even doing a good deed every now and then, Thanos' motivations are almost always his own. He is complex, contrary (not even sure of his own mind, hence his failures to ultimately destroy the Universe while he used the Infinity Gauntlet), and unfathomable by most beings who interact with him.
Thanos employs agents to do his bidding to keep his enemies unaware of his existence until he is ready to engage the enemy directly. He isn't shy. He is perfectly capable of engaging his enemies but he prefers to gather intelligence through his proxies to better know his enemies when and if he confronts them directly. Direct confrontation with Thanos, particularly if he has had the chance to study you usually equals defeat (or death if he is in a bad mood.)
Thanos manhandles Thor and the Thing
His proxies have included Gamora, Adam Warlock, Nebula and even the Guardians of the Galaxy.
Marvel Cinematic Universe
While almost nothing is known about the Marvel Cinematic Universe's version of Thanos, the fact he is able to send Loki to Earth to do his bidding is already a testament to his capability. But since we don't know how much Thanos knows about Earth, we are forced to assume, at this point he knows very little and sends Loki as an initial probe of Earth's potential defenses. Yes, we look primitive, but a spear can still kill a man with a gun if the spear thrower gets the drop on the soldier.
Why didn't he go himself? By sitting in the shadows, he learned about the Avengers, Thor, Asgard, the Tesseract and where it ended up, Loki's capabilities, SHIELD and its capabilities and just what every one of those groups was willing to do when faced with an all out invasion of this type.
For Thanos, knowledge is power. Not gaining the Tesseract was surely a bit dissapointing but he already has (if he is similar to his Earth-616 counterpart) fast spaceships, legions of flunkies, and more capable lieutenants at his beck and call. Thanos will surely claim the Tesseract and the Aether when he is ready.
|
[
"stackoverflow",
"0058568336.txt"
] | Q:
Angular Jest or Jasmine Testing: How to Properly Spy/Mock a Static Object Called From Within a Tested Class?
I have an AppConfigService that loads an object from a JSON file into a static settings variable that is part of the service. Various components and/or services throughout the application reference the object with AppConfigService.settings., with a simple reference (no injection). How can I test a service that is referencing this kind of construction?
For example
@Injectable()
export class SomeService {
someVariable;
constructor() {
// I can't get the test to not give me a TypeError: Cannot read property 'someSettingsVariable' of undefined on this line
this.someVariable = AppConfigService.settings.someSettingsVariable;
}
}
I have two projects, one using Jest and another Jasmine/Karma and I need to figure out the pattern of how to get the test to work in this construction.
I have tried things like:
const spy = spyOnProperty(SomeService, 'someVariable')
.and.returnValue('someValue');
Example spec:
import { TestBed } from '@angular/core/testing';
import { NgRedux } from '@angular-redux/store';
import { Injectable } from '@angular/core';
import { DispatchHelper } from '../reducers/dispatch.helper';
import { ContributorActions } from '../actions/contributor.action';
import { MockDispatchHelper } from '../_mocks/DispatchHelperMock';
import { DiscrepancyService } from '../discrepancies/discrepancy.service';
import { DiscrepancyAPIService } from '../discrepancies/discrepancy-api.service';
import { DiscrepancyAPIServiceMock } from '../_mocks/DiscrepancyAPIServiceMock';
import { Observable } from 'rxjs';
import { Guid } from 'guid-typescript';
import { getInitialUserAccountState } from '../functions/initial-states/user-account-initial-state.function';
import { LoggingService } from '../security/logging/logging.service';
import { MockLoggingService } from '../_mocks/LoggingServiceMock';
describe('discrepancyService', () => {
let discrepancyService: DiscrepancyService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: Injectable, useClass: Injectable },
{ provide: DispatchHelper, useClass: MockDispatchHelper },
{ provide: ContributorActions, useClass: ContributorActions },
{ provide: NgRedux, useClass: NgRedux },
{ provide: DiscrepancyService, useClass: DiscrepancyService },
{ provide: DiscrepancyAPIService, useClass: DiscrepancyAPIServiceMock },
{ provide: LoggingService, useClass: MockLoggingService },
]
})
.compileComponents();
const userStateObservable = Observable.create(observer => {
const userState = getInitialUserAccountState();
userState.userId = Guid.parse('<guid>');
userState.organization_id = Guid.parse('<guid>');
observer.next(userState);
console.log('built user state observable');
observer.complete();
});
discrepancyService = TestBed.get(DiscrepancyService);
const spy4 = spyOnProperty(discrepancyService, 'userState$', 'get').and.returnValue(userStateObservable);
});
// TODO: Fix this
it('should create service and loadDiscrepancies', () => {
// in this example, discrepancyService constructor sets the
// value of a variable = ApiConfigService.settings.endPoint
// ApiConfigService.settings is static; how do I "replace"
// the value of endPoint in a call like this so I don't get
// an error because ApiConfigService.settings is undefined
// when called from a service in the test?
const spy = spyOn(discrepancyService.dispatcher, 'dispatchPayload');
discrepancyService.loadDiscrepancies();
expect(spy.calls.count()).toEqual(1);
});
});
karma.conf.js
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma'),
require('karma-spec-reporter')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
customLaunchers: {
ChromeDebug: {
base: 'Chrome',
flags: [ '--remote-debugging-port=9333','--disable-web-security' ]
},
ChromeHeadlessCI: {
base: 'Chrome',
flags: ['--no-sandbox', '--headless', '--watch=false'],
browserDisconnectTolerance: 10,
browserNoActivityTimeout: 10000,
browserDisconnectTimeout: 5000,
singleRun: false
}
},
reporters: ['progress', 'kjhtml', 'spec'],
port: 9876,
host: 'localhost',
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeDebug', 'ChromeHeadlessCI'],
singleRun: false
});
};
Any assistance from testing gurus would be appreciated.
A:
Three ways I can see about it
Set the value directly
// TODO: Fix this
it('should create service and loadDiscrepancies', () => {
// in this example, discrepancyService constructor sets the
// value of a variable = ApiConfigService.settings.endPoint
// ApiConfigService.settings is static; how do I "replace"
// the value of endPoint in a call like this so I don't get
// an error because ApiConfigService.settings is undefined
// when called from a service in the test?
AppConfigService.settings = { endpoint: 'http://endpoint' }
const spy = spyOn(discrepancyService.dispatcher, 'dispatchPayload');
discrepancyService.loadDiscrepancies();
expect(spy.calls.count()).toEqual(1);
});
Add a null check and a setter
@Injectable()
export class SomeService {
someVariable;
constructor() {
// I can't get the test to not give me a TypeError: Cannot read property 'someSettingsVariable' of undefined on this line
if (AppConfigService && AppConfigService.settings) {
this.someVariable = AppConfigService.settings.someSettingsVariable;
}
}
}
set endPoint(value) {
this.someVariable = value
}
Hide the static implementation behind a service
This for me is by far the best solution. Instead of going with a static implementation, create a single instance service that can be spied upon easily. This is not only a problem for you as you can imagine, but a problem for all OOP languages where the static implementations are avoid.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ConfigService {
private endpoint: string;
constructor() { }
get endPoint(): string {
return this.endPoint;
}
}
Full example for runtime angular configuration here
|
[
"stackoverflow",
"0051836599.txt"
] | Q:
passing multiple variable to one view in laravel 5.6
hello to all I want to pass multiple variables to one view
this is my CategoryController.php
public function site()
{
$categories = Category::all();
return view('template.sitemap', ['categories' => $categories]);
}
and this is SubCategoryController.php
public function index2(){
$subcategories = SubCategory::all();
return view('template.sitemap',['subcategories'=>$subcategories]);
}
this is my route for this action in web.php
Route::get('sitemap.html','CategoryController@site')->name('sitemap')
Route::get('sitemap.html','SubCategoryController@index2')->name('sitemap');
and this is the view i am trying to do this sitemap.blade.php
@foreach($categories as $category)
<li><a href="category.html">{{$category->name}}</a></li>
<ul>
@foreach($subcategories as $subcategory)
<li><a href="category.html">{{$subcategory->category_name->name}</li>
@endforeach
</ul>
@endforeach
but i constantly see undefind vairalble
alone they work good
but when i want user both variables seee undefined vairable.
A:
Your site will go to the first route and will never go to your second controller.
You should rather write.
Route
Route::get('sitemap.html','CategoryController@site')->name('sitemap');
Controller
public function site(){
$data = array();
$data['subcategories'] = SubCategory::all();
$data['categories'] = Category::all();
return view('template.sitemap',compact("data"));
}
View
@foreach($data['categories'] as $category)
<li><a href="category.html">{{$category->name}}</a></li>
<ul>
@foreach($data['subcategories'] as $subcategory)
<li><a href="category.html">{{$subcategory->category_name->name}}</li>
@endforeach
</ul>
@endforeach
|
[
"stackoverflow",
"0044587412.txt"
] | Q:
Is it possible to access underlying Xamarin UI elements using SkiaSharp?
In a cross platform Xamarin.Forms application, I would like to add a SKCanvas on top of other UI elements to allow the user to draw e.g. on images. I know it is possible to load an image directly into an SKCanvas, but images are not the only application I need.
A perfect solution would be able to load the underlying content of the page, including all of its UI elements into the Canvas/Surface, so that the user can then draw on it and save the drawing + underlying content into an image (probably using the snapshot method?).
Is this possible?
A:
I didn't find a way to do this exactly as planned originally, but ended up doing a workaround that satisfied the requirements at the time.
I added a transparent canvas on top of my content, such that the underlying content would be shown through the canvas, but anything on the canvas would always be drawn on top. The drawings were saved and transmitted separately from the content and re-drawn when needed. On demand, when the user would need to export both together for a snapshot/share/export function, I then loaded the underlying content as image into the canvas and exported it together with the drawings from the canvas into a new image.
|
[
"stackoverflow",
"0024714426.txt"
] | Q:
java - onMousePressed() only detecting once
I have an array of JLabels[7] and I filled all JLabels with same image and added them to a JPanel.
When I click on a JLabel position(e.g I click on JLabel[5]) the console will print out "you have clicked JLabel 5" and change the JLabel image from imageOne to imageTwo.
I realized something about my codes which is after I clicked on a JLabel (e.g I click on JLabel[5]), the image changes from imageOne to imageTwo and the console print out "you have clicked JLabel 5" but if I clicked again and again on JLabel[5], the program will not detect my mouse click event and the console will not print out "you have clicked JLabel 5".
How do I make it such a way that after image has changed on the first click on a JLabel, it will still contiune and detect no mater how many times I clicked on the same JLabel again?.
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class LearningSwing {
public Image imageOne() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("imageOne.jpg"));
} catch (Exception e) {
}
return img;
}
public Image imageTwo() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("imageTwo.jpg"));
} catch (Exception e) {
}
return img;
}
public static void main(String[] args) {
final JLabel[] jLabelArr = new JLabel[7];
final JPanel jPanel = new JPanel(new FlowLayout());
JFrame frame = new JFrame();
final LearningSwing learningSwing = new LearningSwing();
for(int i = 0; i< 7; i++) {
jLabelArr[i] = new JLabel(new ImageIcon(learningSwing.imageOne()));
jPanel.add(jLabelArr[i]);
jLabelArr[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
for(int i = 0; i < 7; i ++) {
if(e.getSource() == jLabelArr[i]) {
System.out.println("You clicked on JLabel" + i);
jPanel.remove(i);
jLabelArr[i] = new JLabel(new ImageIcon(learningSwing.imageTwo()));
jPanel.add(jLabelArr[i],i);
jPanel.revalidate();
jPanel.repaint();
}
}
}
});
}
frame.add(jPanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(400,600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
A:
In your code you are removing the old JLabel when the listener invokes mouseClicked, and you are recreating it again with the new image. This causes the JLabel to lose the listener.
You could instead change the image of the label as follows:
@Override
public void mouseClicked(MouseEvent e) {
for (int i = 0; i < 7; i++) {
if (e.getSource() == jLabelArr[i]) {
System.out.println("You clicked on JLabel" + i);
jLabelArr[i].setIcon(new ImageIcon(learningSwing.imageTwo()));
}
}
}
|
[
"mathematica.stackexchange",
"0000116371.txt"
] | Q:
How to overlay ListPlot on a ContourPlot with correct range?
I am trying to superimpose a scatter (Listplot) on a contour plot.
If p1 is a contour plot and p2 is a scatter plot imported from some data, how do I plot them on top of each other?
I tried Show and Overlay but neither worked. Simply gave the error:
Show::gcomb: "Could not combine the graphics objects in
Show[p1,p2,PlotRange->All]."
Please help. Thank you! :)
EDIT:
p1 = ContourPlot[
Min[0.10376 (x^2.5 + Sqrt[2] y^2.5),
0.0964395 (x/100000000000000000000000000 + 8 y^2)], {x, 0,
0.75}, {y, 0, 0.75}, BaseStyle -> {FontSize -> 20},
Contours -> Function[{min, max}, Range[min, max, 0.002]],
ColorFunction -> "BlueGreenYellow", PlotLegends -> Automatic]
p2 = ListPlot[{altdata, sliddata}, PlotMarkers -> Automatic]
where
altdata = {{0.01, 0.01}, {0.05, 0.02}, {0.05, 0.03}, {0.05,
0.04}, {0.05, 0.05}, {0.11, 0.05}, {0.05, 0.06}, {0.11,
0.06}, {0.05, 0.07}, {0.11, 0.11}, {0.18, 0.2}, {0.2, 0.2}, {0.22,
0.2}, {0.24, 0.2}, {0.26, 0.2}, {0.28, 0.2}, {0.3, 0.2}, {0.32,
0.2}, {0.34, 0.2}, {0.1, 0.2}, {0.12, 0.2}, {0.14, 0.2}, {0.16,
0.2}, {0.3, 0.25}, {0.3, 0.3}, {0.3, 0.35}, {0.3, 0.4}, {0.3,
0.45}, {0.3, 0.5}, {0.3, 0.55}, {0.3, 0.6}}
and
sliddata = {{0.05, 0.01}, {0.11, 0.02}, {0.11, 0.03}, {0.11,
0.04}, {0.3, 0.1}, {0.3, 0.15}}
Show[p1, p2]
A:
Are you looking for
cp1 = ContourPlot[Cos[x] + Cos[y] == 1/2, {x, 0, 4 Pi}, {y, 0, 4 Pi}]
testData = Prime[Range[25]]
lp1 = ListPlot[testData, PlotStyle -> Red]
Show[cp1, lp1]
but be carefull and check the sequence of Show, because Show uses the options from the first graphic
Show[lp1, cp1]
cp2 = ContourPlot[Cos[x] + Cos[y] == 1/2, {x, 0, 25}, {y, 0, 100}]
Show[cp2, lp1]
So, Show[cp2, lp1, PlotRange -> All] is a wrong call for Show, it works without PlotRange -> All, because Show uses the options from the first graphic.
With your Edit and your Data I get:
Is that OK with you?
|
[
"ru.stackoverflow",
"0000419428.txt"
] | Q:
Почему jQuery не выдает никаких ошибок, если задать невалидный селектор?
Просто интересно, почему подобный код:
$(undefined).css({...})
или
$(123).css({...})
или
$(false).css({...})
не вызывает никаких ошибок в консоли, ведь это явно невалидные значения?
A:
Почему невалидные значения? Просто это не селектор. Мы можем передать в функцию jQuery не только строку, но и объект. В ответ мы получим jQuery-объект, в котором будет доступна функция css, просто она ничего не будет модифицировать.
|
[
"stackoverflow",
"0005380506.txt"
] | Q:
Improve this PHP bitfield class for settings/permissions?
I have been trying to figure out the best way to use bitmask or bitfields in PHP for a long time now for different areas of my application for different user settings and permissions. The farthest I have come so far is from a class contributed by svens in the Stack Overflow
post Bitmask in PHP for settings?. I have slightly modified it below, changing it to use class constants instead of DEFINE and making sure the get method is passed an int only. I also have some sample code to test the class's functionality below.
I am looking for any suggestions/code to improve this class even more so it can be used in my application for settings and in some cases user permissions.
Answered in the comment below by mcrumley
In addition, I have a question about the numbering of my constants. In other classes and code sample for this type it will have things listed in powers of 2. However, it seems to work the same as far as I can tell even if I number my constants 1,2,3,4,5,6 instead of 1, 2, 4, 8, 16, etc. So can someone also clarify if I should change my constants?
Some ideas... I would really like to figure out a way to extend this class so it is easy to use with other classes. Let's say I have a User class and a Messages class. Both the User and Messages class will extend this class and be able to use the bitmask for their settings/permissions (along with other classes later on). So maybe the current class constants should be changed so they can be passed in or some other option? I really would rather not have to define (define('PERM_READ', 1);) in other parts of the site/script and would like to keep it somewhat encapsulated, but flexible as well; I am open to ideas. I want this to be rock solid and flexible like I said to use with multiple other classes for settings or permissions. Possibly some kind of array should be used? @Svens from my previous question linked above posted a comment with "implement some automagic getters/setters or ArrayAccess for extra awesomness. – svens" What do you think about something like that as well?
Include example source code if possible, please.
<?php
class BitField {
const PERM_READ = 0;
const PERM_WRITE = 1;
const PERM_ADMIN = 2;
const PERM_ADMIN2 = 3;
const PERM_ADMIN3 = 4;
private $value;
public function __construct($value=0) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function get($n) {
if (is_int($n)) {
return ($this->value & (1 << $n)) != 0;
}else{
return 0;
}
}
public function set($n, $new=true) {
$this->value = ($this->value & ~(1 << $n)) | ($new << $n);
}
public function clear($n) {
$this->set($n, false);
}
}
?>
Example Usage...
<?php
$user_permissions = 0; //This value will come from MySQL or Sessions
$bf = new BitField($user_permissions);
// Turn these permission to on/true
$bf->set($bf::PERM_READ);
$bf->set($bf::PERM_WRITE);
$bf->set($bf::PERM_ADMIN);
$bf->set($bf::PERM_ADMIN2);
$bf->set($bf::PERM_ADMIN3);
// Turn permission PERM_ADMIN2 to off/false
$bf->clear($bf::PERM_ADMIN2); // sets $bf::PERM_ADMIN2 bit to false
// Get the total bit value
$user_permissions = $bf->getValue();
echo '<br> Bitmask value = ' .$user_permissions. '<br>Test values on/off based off the bitmask value<br>' ;
// Check if permission PERM_READ is on/true
if ($bf->get($bf::PERM_READ)) {
// can read
echo 'can read is ON<br>';
}
if ($bf->get($bf::PERM_WRITE)) {
// can write
echo 'can write is ON<br>';
}
if ($bf->get($bf::PERM_ADMIN)) {
// is admin
echo 'admin is ON<br>';
}
if ($bf->get($bf::PERM_ADMIN2)) {
// is admin 2
echo 'admin 2 is ON<br>';
}
if ($bf->get($bf::PERM_ADMIN3)) {
// is admin 3
echo 'admin 3 is ON<br>';
}
?>
A:
In other classes and code sample for this type it will have things listed in powers of 2 however it seems to work the same as far as I can tell even if I number my constants 1,2,3,4,5,6 instead of 1,2,4,8,16 etc. So can someone also clarify if I should change my constants?
You don't need to, because the code is already taking care of that. This explanation is going to be a bit roundabout.
The reason that bit fields are handled as powers of two is that each power of two is represented by a single bit. These individual bits can be bitwise-ORed together into a single integer that can be passed around. In lower-level languages, it's "easier" to pass around a number than, say, a struct.
Let me demonstrate how this works. Let's set up some permissions using the powers of two:
define('PERM_NONE', 0);
define('PERM_READ', 1);
define('PERM_WRITE', 2);
define('PERM_EDIT', 4);
define('PERM_DELETE', 8);
define('PERM_SUPER', 16);
Let's inspect the bit values of these permissions at the PHP interactive prompt:
php > printf('%08b', PERM_SUPER);
00010000
php > printf('%08b', PERM_DELETE);
00001000
php > printf('%08b', PERM_EDIT);
00000100
php > printf('%08b', PERM_WRITE);
00000010
php > printf('%08b', PERM_READ);
00000001
php > printf('%08b', PERM_NONE);
00000000
Now let's create a user that has READ access and WRITE access.
php > printf('%08b', PERM_READ | PERM_WRITE);
00000011
Or a user that can read, write, delete, but not edit:
php > printf('%08b', PERM_READ | PERM_WRITE | PERM_DELETE);
00001011
We can check permission using bitwise-AND and making sure the result is not zero:
php > $permission = PERM_READ | PERM_WRITE | PERM_DELETE;
php > var_dump($permission & PERM_WRITE); // This won't be zero.
int(2)
php > var_dump($permission & PERM_EDIT); // This will be zero.
int(0)
(It's worth noting that PERM_NONE & PERM_NONE is 0 & 0, which is zero. The "none" permission I created doesn't actually work here, and can promptly be forgotten about.)
Your class is doing something slightly different, but the end result is identical. It's using bit shifting to move an "on" bit over to the left X times, where X is the number of the permission. In effect, this is raising 2 to the power of the permission's value. A demonstration:
php > echo BitField::PERM_ADMIN3;
4
php > echo pow(2, BitField::PERM_ADMIN3);
16
php > printf('%08b', pow(2, BitField::PERM_ADMIN3));
00010000
php > echo 1 << BitField::PERM_ADMIN3;
16
php > printf('%08b', 1 << BitField::PERM_ADMIN3);
00010000
While these methods are effectively identical, I'd argue that simple ANDing and ORing is easier to read than the XORing and bit-shifting.
I am looking for any suggestions/code to improve this class even more so it can be used in my app for settings and in some cases user permissions.
I have one suggestion, and one warning.
My suggestion would be making the class abstract and not defining any permissions within it. Instead, build classes that inherit from it and define their own permissions. You don't want to consider sharing the same permission names across unrelated bit fields, and prefixing them with class names is pretty sane. I expect you were going to do this anyway.
My warning is simple but dire: PHP can not reliably represent an integer larger than 31 bits. In fact, it can only represent 63-bit integers when it's compiled on a 64-bit system. This means that, if you are distributing your application to the general public, you will be restricted to no more than 31 permissions if you wish to use the built-in math functions.
The GMP extension includes bitwise operations that can function on arbitrary-length integers.
Another option might be using code from this answer on large integers, which could allow you to represent a huge integer as a string, though doing bitwise operations on that might be ... interesting. (You could down-convert it to base-2, then do a substr check for string "1" or "0" at the expected location, but that's gonna be a huge performance drag.)
A:
Others have helped with further explaining the bit masking bit of this, so I'll concentrate on
"I do like the idea of making it more
extensible/generic so different
classes can extend this and use it for
different sections, i'm just not sure
how to do it yet"
from your comment on @Charles' post.
As Charles rightly said, you can re-use the functionality of your Bitmask class by extracting the functionality into an abstract class, and putting the actual "settings" (in this case permissions) into derived concrete classes.
For example:
<?php
abstract class BitField {
private $value;
public function __construct($value=0) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function get($n) {
if (is_int($n)) {
return ($this->value & (1 << $n)) != 0;
}else{
return 0;
}
}
public function set($n, $new=true) {
$this->value = ($this->value & ~(1 << $n)) | ($new << $n);
}
public function clear($n) {
$this->set($n, false);
}
}
class UserPermissions_BitField extends BitField
{
const PERM_READ = 0;
const PERM_WRITE = 1;
const PERM_ADMIN = 2;
const PERM_ADMIN2 = 3;
const PERM_ADMIN3 = 4;
}
class UserPrivacySettings_BitField extends BitField
{
const PRIVACY_TOTAL = 0;
const PRIVACY_EMAIL = 1;
const PRIVACY_NAME = 2;
const PRIVACY_ADDRESS = 3;
const PRIVACY_PHONE = 4;
}
And then usage simply becomes:
<?php
$user_permissions = 0; //This value will come from MySQL or Sessions
$bf = new UserPermissions_BitField($user_permissions);
// turn these permission to on/true
$bf->set($bf::PERM_READ);
$bf->set($bf::PERM_WRITE);
$bf->set($bf::PERM_ADMIN);
$bf->set($bf::PERM_ADMIN2);
$bf->set($bf::PERM_ADMIN3);
And to set privacy settings, you just instantiate a new UserPrivacySettings_BitField object and use that instead.
This way, you can create as many different sets of BitField objects as your application requires simply by defining a set of constants that represent your options.
I hope this is of some use to you, but if not, perhaps it will be of some use to someone else who reads this.
A:
Here is my proposal:
<?php
class BitField {
const PERM_READ = 1;
const PERM_WRITE = 2;
const PERM_ADMIN = 4;
const PERM_ADMIN2 = 8;
const PERM_ADMIN3 = 16;
private $value;
public function __construct($value=0) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function get($n) {
return $this->value & $n;
}
public function set($n, $new=true) {
$this->value |= $n;
}
public function clear($n) {
$this->value &= ~$n;
}
}
?>
As you can see, I used 1, 2, 4, 8, etc (powers of 2) to simplify the calculations. If you map one permission to one bit you have:
0 0 0 0 0 0 0 1 = PERM_READ = 1
0 0 0 0 0 0 1 0 = PERM_WRITE = 2
0 0 0 0 0 1 0 0 = PERM_ADMIN = 4
etc...
Then you can use logic operations, for example you have this initially:
0 0 0 0 0 0 0 1 = PERM_READ = 1
If you want to add permissions to write, you only need to use the bitwise OR operator:
0 0 0 0 0 0 0 1 = PERM_READ = 1
OR 0 0 0 0 0 0 1 0 = PERM_WRITE = 2
= 0 0 0 0 0 0 1 1 = both bits enabled R & W
To remove one bit you have to use $value & ~$bit, for example remove the write bit:
0 0 0 0 0 0 1 1 = both bits enabled R & W
AND 1 1 1 1 1 1 0 1 = Bitwise negated PERM_WRITE
= 0 0 0 0 0 0 0 1 = result, only the R bit
Finally, if you want to test if one bit is enabled the operation you have to AND $value against the PERM_XXX you want to test:
0 0 0 0 0 0 1 1 = both bits enabled R & W
AND 0 0 0 0 0 0 1 0 = Want to test PERM_WRITE
= 0 0 0 0 0 0 1 0 = result
If the result is not zero you have the permission, otherwise you don't.
|
[
"stackoverflow",
"0033352401.txt"
] | Q:
Generate a unique number/value for a column that does not have UNIQUE constraint
I am having this Entity (both in database and Entity Framework):
public class LanguageValue
{
public int ID { get; set; }
public long Key { get; set; } // bigint in database
public int LanguageID { get; set; } // FK with a Language table in database
public string Value { get; set; } // nvarchar(MAX) in database
public bool Active { get; set; } // bit in database
}
I have already read this article, but my problem is a bit different: EF6: How to generate a unique number automatically based on entity Id
My Key column does not have unique constraint, because there can be multiple rows with the same Key value. For example:
ID Key LanguageID Value
---------------------------------------------------
1 1 1 Name in Language 1
2 1 2 Name in Language 2
I cannot use a Mapping table to enforce a FK instead of Key because multiple tables uses this same table (Product's Name, Category's Name, Article's Content).
Now whenever I need to insert a Product or Category record, I need to insert their corresponding Language Value. However, I have yet to find a way to generate a Key that is unique among them, and more over, need to be unique in case two insert are being processed at once (for example, adding a Product and Category at the same time).
I am thinking about Guid, should that be my safe bet with RNG, or is there any better way/design for achieving it?
A:
OK, I think my problem was from bad database design. I seperated the LanguageValue table into two tables, like the following diagram, and realize 2 pros that the previous design did not have:
I can now safely insert the LanguageKey with IDENTITY.
I can now have FK for Product and Category's NameLanguageKey, which were impossible before because Key was not unique.
|
[
"stackoverflow",
"0039235842.txt"
] | Q:
Switch axes and handedness of a quaternion?
I have a quaternion, coming from a system with the following:
Right handed.
Forward direction: Y axis
Right direction: X axis
Up direction: Z axis
I need to convert this into a coordinate system that is:
left-handed.
Forward direction: X axis
Right direction: Y axis
Up direction: Z axis
I have tried negating the axis, and angle, I have tried switching values, i cannot get this to work. All help greatly appreciated! I am working in C#, with
Microsoft.Xna.Quaternion.
A:
A quaternion is a structure of four values (w, x, y, z). If it represents a rotation, then w = cos(phi/2) (phi being the rotation angle) and (x, y, z) = sin(phi/2) * (ax, ay, az) ((ax, ay, az) being the rotation axis).
In order to convert the quaternion to another system, it is sufficient to transform the rotation axis. For your example, the transform is:
/ 0 1 0 \
T = | 1 0 0 |
\ 0 0 1 /
Finally, since you are changing handedness, you must invert the quaternion or it will rotate in the wrong direction. Summarizing, the transformed quaternion is:
(w*, x*, y*, z*) = (w, -y, -x, -z)
In general:
(x*, y*, z*) = det(T) T (x, y, z) //Assuming column vectors
|
[
"math.stackexchange",
"0000276786.txt"
] | Q:
How to prove that a skew-symmetric matrix with integer entries has a determinant that is a square of some integer?
Possible Duplicate:
Determinant of a real skew-symmetric matrix is square of an integer
I know that in general, a skew-symmetric matrix with indeterminate elements has a determinant that can be written as a square of some multivariable polynomial. How to prove this?
And if I do not know anything about the Pfaffian, can I prove the statement that a skew-symmetric matrix with integer entries has a determinant that is a square of some integer? I mean if someone knows how to prove it without using the Pfaffian?
A:
This is for the second part, a skew-symmetric matrix with integer entries
First, if $n$ is odd, then since $\det(A) = \det(A^T) = \det(-A) = (-1)^n \det(A)$, so $\det(A)= 0$, which is the square of an integer.
Now for $n$ even, we proceed by induction, and will show the statement is true over the rationals. Base case $n=2$ is obvious.
Inline Edit: Induction step. Suppose we want to show it for some $n=2k+2$. Consider the entries. We already know that the diagonals satisfy $a_{i, i} = 0$. If all the other entries are also 0, then we are done. Otherwise, WLOG we have $a_{1,2}\neq 0$. We will proceed to calculate the determinant of $A$. end edit
Using only row operations, where we add a rational linear multiple of the second row to the others, we can make the first column to be $(0, a_{2, 1}, 0, 0, \ldots, 0)^T$. Specifically, for row $k\neq 1, 2$, we have $b_{k, i} = a_{k, i} - \dfrac {a_{k, 1}}{a_{2, 1}} a_{2,i}$. Now, we use column operations, where we add a rational linear multiple of the second column to the others, and we can make the first row to be $(0, a_{1, 2}, 0, 0, \ldots, 0)$. Specifically, for column $k\neq 1, 2$, we have $c_{i, k} = b_{i, k} - \dfrac {b_{1, k}}{b_{1, 2}} b_{i, 2}$. Then, $\det(A) = a_{1, 2}^2 \det(C)$, and so it remains to show that $C$ is still a skew symmetric matrix.
For rows and columns 1 and 2, nothing changed throughout, (so those entries are skew symmetric).
For $i=k$, $b_{i,i} = 0- \dfrac {a_{i,1}}{a_{2,1}}a_{2,i}$, $c_{i,i} = b_{i,i} - \dfrac {b_{1,i}}{b_{1, 2}} b_{i, 2} = (0 - \dfrac {a_{i,1}}{a_{2,1}}a_{2,i})- \dfrac {a_{1,i}}{a_{2,i}} a_{i,2}=0$
For $i\neq k$, $c_{i,k} = b_{i, k} - \dfrac {b_{1, k}}{b_{1, 2}} b_{i, 2} = b_{i, k} - \dfrac {a_{1, k}}{a_{1, 2}} a_{i, 2}= (a_{i, k} - \dfrac {a_{i, 1}}{a_{2, 1}} a_{2,k})- \dfrac {a_{1, k}}{a_{1, 2}} a_{i, 2}$. Hence, it follows that $c_{i,k}=-c_{k,i}$.
Hence, $C$ is a skew symmetric matrix.
Now, $A$ has an integer determinant, which is also the square of a rational number, hence is a perfect square.
|
[
"stackoverflow",
"0056972840.txt"
] | Q:
Recalculate the new weighted mean when merging two factors by group, and keep original data
I'm working on a data frame that contains:
counts per cluster (flow cytometry data)
of several files
and mean, max, min, total for lots of variables recorded by the machine.
In the case that I want to reduce the number of groups (pool similar clusters together) I would want to merge all the information in a file for group 'a' and 'b' by file
So far, following this SO Question I have already worked out the min, max, and total, but am stuck on how to get the following calculation working in this structure (mutate_at) using a custom function which would do:
(counts of 'a' * mean of 'a' + counts of 'b' * mean of 'b') /
sum(counts for 'a', counts of 'b' )
in order to recalculate the new mean for each of the mean_i columns, where "mean" in the equation refers to 1 of the columns containing mean values I'm calling with vars(mean_cols)
The code so far:
library(dplyr)
set.seed(123)
df <- data.frame(ID = 1:20,
total_X = runif(20),
min_X = runif(20),
max_X = runif(20),
mean_X = runif(20),
total_Y = runif(20),
min_Y = runif(20),
max_Y = runif(20),
mean_Y = runif(20),
Counts = runif(20)*1000,
category = rep(letters[1:5], 4),
file = as.factor(sort(rep(1:4, 5))))
total_cols = names(df)[which(grepl('total', names(df)))]
min_cols = names(df)[which(grepl('min', names(df)))]
max_cols = names(df)[which(grepl('max', names(df)))]
mean_cols = names(df)[which(grepl('total', names(df)))]
recalmean <- function() { sum(Counts * vars)/sum(Counts)}
#counts of 'a' * mean of 'a' + counts of 'b' * mean of 'b' / sum(counts for 'a', counts of 'b' )
x <- df %>% bind_rows(
df %>%
filter(category %in% c('a' , 'b')) %>%
group_by(file) %>%
mutate_at(vars(total_cols), sum) %>%
mutate_at(vars(min_cols), min) %>%
mutate_at(vars(max_cols), max) %>%
# mutate_at(vars(mean_cols), recalmean) %>% ## this line needs to do the custom weighed mean calculation
mutate(category = paste0(category,collapse='')) %>%
filter(row_number() == 1 & n() > 1)
) %>% mutate(ID = row_number())
A:
got to admit it was challenging...you should reconsider the data structure
library(tidyverse)
set.seed(123)
df <- data.frame(ID = 1:20,
total_X = runif(20),
min_X = runif(20),
max_X = runif(20),
mean_X = runif(20),
total_Y = runif(20),
min_Y = runif(20),
max_Y = runif(20),
mean_Y = runif(20),
Counts = runif(20)*1000,
category = rep(letters[1:5], 4),
file = as.factor(sort(rep(1:4, 5))))
x <- df %>% bind_rows(
gather(df,metric,value,-ID,-file,-category,-Counts) %>%
mutate(group=str_extract(metric,"[A-Z]$"),metric = str_replace(metric,"_.$","")) %>%
filter(category %in% c('a' , 'b')) %>%
spread(metric,value) %>%
group_by(file,group) %>%
summarise(Counts = mean(Counts),
category = paste0(category,collapse = ''),
max = max(max),
min = min(min),
total = sum(total),
mean = sum(Counts * mean)/sum(Counts)) %>%
ungroup() %>%
gather(metric,value,-file,-group,-category,-Counts) %>%
mutate(metric = paste(metric,group,sep='_'),group=NULL) %>%
spread(metric,value) %>%
mutate(ID=0)
) %>% mutate(ID = row_number())
|
[
"serverfault",
"0000324026.txt"
] | Q:
Have I been compromised?
Possible Duplicate:
My server's been hacked EMERGENCY
Looking thru my logs, I found this:
http://paste.u4ik.us/2294$
(The log files are on that paste).
Question is, this guy began using "all requests allowed" which is...? (Explain it please?) and eventually was making requests from "127.0.0.1" which means he's using my local system?
If anyone can explain this, or help prevent it, I'd like to know, and this would be highly appreciated.
Thanks!
PS: I've since blocked their IP, but what's stopping this from happening again?
A:
Don't panic. As a general advice, before reading logs and trying to get some security-related meaning out of them, be sure to have a sufficiently thorough understanding of what it does mean. Otherwise you end up with a heart attack over too many "dangerously looking" log entries.
What you see is simply Internet background noise - someone trying to pick on your configuration for possible weaknesses. Such "attacks" are usually simply blind attempts to exploit configuration problems or implementation bugs, most of them without any effect. There is absolutely no way to prevent this.
The 127.0.0.1 log entry you see in your original log paste is an entry which has been induced by your own system - most probably not on the behalf of the attacker but through your own actions.
|
[
"stackoverflow",
"0011667645.txt"
] | Q:
How to select TreeViewItem on select
<HierarchicalDataTemplate x:Key="SchemTemplate">
<TextBlock Text="{Binding Path=path}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="SchemesTemplate">
<TreeViewItem TextBlock.FontStyle="Italic"
Header="{Binding name}"
ItemsSource="{Binding schemes}"
ItemTemplate="{StaticResource SchemTemplate}" />
</HierarchicalDataTemplate>
<DataTemplate x:Key="ProjectTemplate">
<TreeView>
<TreeViewItem Header="{Binding Path=name}"
ItemsSource="{Binding schemes}"
ItemTemplate="{StaticResource SchemesTemplate}">
</TreeViewItem>
</TreeView>
</DataTemplate>
using:
<ListBox Style="{StaticResource ListProjectsStyle}"
x:Name="projects"
Grid.Row="0" Grid.Column="0"
ItemsSource="{Binding projects_models, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemTemplate="{StaticResource ProjectTemplate}"
SelectedItem="{Binding active_project, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
</ListBox>
When I click right mouse button over TreeView then ListBox's SelectedItem changed, but left click does this. Left click puts the focus on TreeView or expand TreeView items. How can I change focus on ListBox when focus is on TreeView?
A:
Solution:
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource ListBoxItem}">
<EventSetter Event="ListBoxItem.PreviewMouseLeftButtonDown"
Handler="ListBoxItem_Select" />
</Style>
</ListBox.Resources>
private void ListBoxItem_Select(object sender, MouseEventArgs e)
{
var mouseOverItem = sender as ListBoxItem;
if (mouseOverItem != null&& e.LeftButton == MouseButtonState.Pressed)
{
mouseOverItem.IsSelected = true;
}
}
|
[
"stackoverflow",
"0041332510.txt"
] | Q:
Translating a whole array continuously in d3
var bardata = []; //array that holds the current value for the candlestick chart
var pastRectangles = [50,12,14,15,35,64] //holds the data for the historical rectangles to be drawn
var data;
setInterval(function () {
var x = Math.floor(Math.random() * 100) //generate a random whole number between 0-99
bardata.push(x); // push that value into the bardata array
// console.log(bardata)
data = x; //set the value of x to data, will be used to update the pastRectangles array every 10 seconds
}, 1000);
var height = 900
, width = 900
, barWidth = 50
, barOffset = 55;
var offset = pastRectangles.length * (barOffset + barWidth);
var scale = d3.scale.linear()
.range([0, pastRectangles])
.domain([0, height]);
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.style('background', 'black')
.append("g")
.attr("class", "rectangles")
update(pastRectangles[pastRectangles.length-1]);
pastDraw(); // call post draw to draw the dummy data first before the update function starts running
function pastDraw()
{
var pastRect = svg.selectAll('rect').data(pastRectangles); //This function will loop through the pastRectangles array and will
pastRect.enter() //draw a rectange for every index in the array
.append("rect") //The reason for not using bardata is that it only holds one value
.attr("g", "rectangles")
.attr("x", function(d,i){return i * (barWidth+barOffset)}) //every second and therefore a second array is needed to hold the
.attr("y", function(d){return height - d}) //historical data
.attr("height", function(d){return d})
.attr("width", 60)
.attr("id", "history")
.attr("fill", "steelblue")
pastRect.transition()
.duration(1000)
.ease('linear')
.attr("height", function (d) {
return d
})
pastRect.exit()
}
function update(bardata) {
var rect = svg.selectAll('rect').data([bardata]); //This function essentially draws a new rectangle for every
rect.enter() //value of bardata, however, because bardata is constantly
.append("rect") //removing the current value for a new value every second
.attr("x",offset) //it gives the illusion of one rectangle updating regularly
.attr("y", function(d){return height - d})
.attr("id", "updateBar")
.attr("height", bardata)
.attr("width", 60)
.attr("fill", "steelblue")
rect.transition()
.duration(1000)
.ease('linear')
.attr("height", function (d) {
return d
})
// rect.exit().transition()
// .duration(1000)
// .attr("transform", "translate(-80,0)")
// .remove();
//
//console.log(bardata);
}
function moveBar()
{
svg.selectAll("#history")
.transition()
.duration(1000)
.attr("transform", "translate(-80,0)")
svg.select("#updateRect")
.transition()
.duration(1000)
.attr("transform", "translate(80,0)")
}
setInterval(function () {
update(bardata); //call the update function with the current value of bardata
bardata.shift(); // remove the the last index of the array from bardata
}, 1000)
setInterval(function () {
pastRectangles.push(data) //update pastrectangles array with the most current value of x every 10 seconds
pastDraw(); // call the pastDraw function to draw the latest recatngle
moveBar();
}, 10000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Messing around with d3 and trying to make a live bar chart, I want it to behave like a candle stick chart
reference image for people who dont know what that is:
(source: chart-formations.com)
I want a live updating bar and after a set amount of time I want to draw a rectangle to the left of it and I've succeeded in that so far by using two arrays, one that only has one value in it every second to draw the updating bar, and another that will hold data for all the past rectangles.
The rectangles in pastRectangles however are being drawn in the wrong order, I can only assume this is because when d3 goes through the dataset it goes from the beginning of the array to the end of the array, I've tried reversing the array to try prevent that but still no help.
I've fixed it up and got it working somewhat how I would like it to be, however Im unable to translate it how I want it, it seems to be only translating the newest rectangle to the array and not the whole array each time, is there anyway to do that? or alternatively, move the updating bar forward each time too.
A:
Instead of shifting the whole array of numbers to the left, I finally got the updatebar to move to the right by writing a simpe moveBars function
function moveBar()
{
var bar = svg.selectAll("#updateBar")
.transition()
.duration(50)
.attr("transform", "translate("+move+",0)")
move += (barWidth+barOffset);
console.log(move)
}
And then I just called that in my pastDraw() function that gets called every ten seconds
var bardata = []; //array that holds the current value for the candlestick chart
var pastRectangles = [50,12,14,15,35,64] //holds the data for the historical rectangles to be drawn
var data
, height = 250
, width = 800
, barWidth = 50
, barOffset= 55;
var move = 0;
setInterval(function () {
var x = Math.floor(Math.random() * 100) //generate a random whole number between 0-99
bardata.push(x); // push that value into the bardata array
data = x; //set the value of x to data, will be used to update the pastRectangles array every 10 seconds
}, 1000);
data = (barOffset+barOffset)
var offset = pastRectangles.length * (barOffset + barWidth);
var scale = d3.scale.linear()
.range([0, pastRectangles])
.domain([0, height]);
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.style('background', 'red')
.append("g")
.attr("class", "rectangles")
update(pastRectangles[pastRectangles.length-1]);
pastDraw()
function pastDraw()
{
var pastRect = svg.selectAll('rect').data(pastRectangles); //This function will loop through the pastRectangles array and will
pastRect.enter() //draw a rectange for every index in the array
.append("rect") //The reason for not using bardata is that it only holds one value
.attr("g", "rectangles")
.attr("x", function(d,i){return i * (barWidth+barOffset)}) //every second and therefore a second array is needed to hold the
.attr("y", function(d){return height - d}) //historical data
.attr("height", function(d){return d})
.attr("width", 60)
.attr("id", "history")
.attr("fill", "steelblue")
pastRect.transition()
.duration(1000)
.ease('linear')
.attr("height", function (d) {
return d
})
pastRect.exit()
var bar = svg.selectAll("#updateBar")
.transition()
.duration(1000)
.attr("transform", "translate("+move+",0)")
move += (barWidth+barOffset);
setTimeout(function()
{
pastRectangles.push(data)
pastDraw();
},30000)
}
function update(bardata) {
var rect = svg.selectAll('rect').data([bardata]); //This function essentially draws a new rectangle for every
rect.enter() //value of bardata, however, because bardata is constantly
.append("rect") //removing the current value for a new value every second
.attr("x",offset) //it gives the illusion of one rectangle updating regularly
.attr("y", function(d){return height - d})
.attr("id", "updateBar")
.attr("height", bardata)
.attr("width", 60)
.attr("fill", "white")
.attr("stroke", "black")
rect.transition()
.duration(1000)
.ease('linear')
.attr("height", function (d) {
return d
})
rect.exit();
//console.log(bardata);
}
setInterval(function () {
update(bardata); //call the update function with the current value of bardata
bardata.shift(); // remove the the last index of the array from bardata
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
running this code on chrome can tend to stall because of how Chrome handles SetInterval() so instead I opted to use recursive setTimeouts() instead
|
[
"salesforce.stackexchange",
"0000182271.txt"
] | Q:
MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa)
I have created a basic trigger and want to insert a content library whenever an application is created but am receiving this error:
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger GenerateLibraryTrigger caused an unexpected exception, contact your administrator: GenerateLibraryTrigger: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): ContentWorkspace, original object: Application__c: []: Trigger.GenerateLibraryTrigger: line 9, column 1
Code:
trigger GenerateLibraryTrigger on Application__c (after insert) {
ContentWorkspace lib = new ContentWorkspace();
for(Application__c a: trigger.new){
lib.name=a.Account__c;
insert lib;
System.debug('lib' + lib); } }
A:
You are going to have to move your logic to a future method to create a separate transaction. To do so, you will need to move this logic to a separate class (which you should be doing anyway). Note that you also should not be calling any DML, futures, etc within a for loop. This is bulkification 101. Create a collection of names, then pass them in once your loop is done.
public class ApplicationService
{
public static void createContentWorkspaces(List<Application__c> records)
{
Set<String> names = new Set<String>();
for (Application__c record : records)
names.add(record.Account__c);
createContentWorkspaces(names);
}
@future
public static void createContentWorkspaces(Set<String> name)
{
List<ContentWorkspace> records = new List<ContentWorkspace>();
for (String name : names) records.add(new ContentWorkspace(Name=name));
insert records;
}
}
See also: Mixed DML Operations in Test Methods.
|
[
"math.stackexchange",
"0003774247.txt"
] | Q:
Prime Ideal with 1
I know that it is possible for a prime ideal $P$ to not contain $1$ (the even numbers are a prime ideal of $\mathbb{Z}$), but I can't figure out if every prime ideal does not contain $1$, and I can't find an example of a prime ideal with 1.
A:
One of the defining properties of an ideal $I$ of a ring $R$ is that for any $i\in I$ and any $r\in R$, you have $r\cdot i\in I$.
Now assume that $1\in I$. Then for any $r\in R$, we have $r=r\cdot 1 \in I$, therefore $I=R$.
Now one of the defining properties of a prime ideal is that it is not the full ring. Therefore a prime ideal cannot contain $1$.
|
[
"stackoverflow",
"0028653722.txt"
] | Q:
font awesome ios icons all the same
I'm trying to use FontAwesome on my ios app (ios8, xcode6), and am having trouble. I've downloaded the font, tried the TTF and OTF versions separately. I've included the font name in my plist file, and have included the NSString+FontAwesome and UIFont+FontAwesome categories that are standard out there.
The problem is that every font awesome symbol showing is always this same one. Everything works, it just never changes the character.
id github = [NSString fontAwesomeIconStringForEnum:FAGithub];
id twitter = [NSString fontAwesomeIconStringForEnum:FATwitter];
label1.font = [UIFont fontWithName:kFontAwesomeFamilyName size:32.f];
label1.text = [NSString stringWithFormat:@"%@ %@", github, twitter];
If I use the unicode string directly instead of the helpers, it is still always the same
@"\uf001"
@"\uf002"
// etc
When I debugged the category classes and printed out the unicode array with all the font-awesome codes in the console, all the symbols were identical to the ones above.
[NSString fontAwesomeUnicodeStrings]
Has anyone seen this problem of the repeating symbol, or know a resolution?
EDIT
2 weeks later, after fixing by re-install: I believe the symbol shown is, which was always the same, is the result of the label's font either not being set correctly to FontAwesome, or the font not being loaded so it is not able to be set. That is the symbol that shows up when font is set to something like "System".
A:
Steps taken for this to work:
File > Add File > Added ios-fontawesome in it entirety (copied folder)
Removed all .m files from fontawesome besides NSString+FontAwesome.m from compile sources
Added FontAwesome.tff to info.plist key Fonts Provided By Application
(Compiled for iPhone 5s Sim, 8.1 using XCode 6.1.1)
Test project listed here: https://github.com/spacedrabbit/StackScratchPad
As the comments indicate, this doesn't explain why it wasn't working it just is the way I was able to make it work.
|
[
"stackoverflow",
"0006041863.txt"
] | Q:
Are there any Controls to show the nephogram?
I want to show the nephogram like the above which show the many-to-many relationships of objects.
Are there any free Controls? Or, maybe some suggestion? Thanks a lot!
A:
I have used Graphviz for similar problems.
Graphviz can create an images similar to the one in your post which you can display to the user in a picturebox.
|
[
"japanese.stackexchange",
"0000051702.txt"
] | Q:
Sentence translation help (「そう長く生きていない」「まだここに来て日の浅い」)
I was having trouble translating this sentence, specifically the last part:
だが、そう長く生きていないとはいえ、人生の半分以上をここで暮らし、また言葉を操る『言ノ葉使い』である僕には彼がまだここに来て日の浅い使用人であることが分かった。
I understand that 「長く生きていないとはいえ」 means something along the lines of 'although I haven't lived that long', however I'm not sure about the function of 'そう' in that sentence. I translated the next part as 'living here for over half my life', and the next one is about him being able to use 'Kotonoha' to manipulate words. However the last part confuses me a bit, specifically the use of 'まだ', and also the use of te-form in '来て日'.
Also '浅い' usually translates to 'shallow', but can it be translated to 'young' in this context?
A:
そう corresponds to that in "that long". It's interchangeable with そんなに and それほど.
そう簡単ではない。 = そんなに簡単ではない。
It's not that easy.
(te-form) + 日が + 浅い is a set phrase meaning "it hasn't been long (since ~)". の is replacing が because this part is in a relative clause. まだ is simply still or yet, and is often used with this set phrase.
彼はここに来て日が浅い。
It hasn't been long since he came here.
The sentence is about the time after he came, not about his age.
|
[
"askubuntu",
"0000232072.txt"
] | Q:
Changed LAMP WWW directory to Dropbox, now getting 403 Forbidden
I wan to use my Dropbox/Web directory as the server directory for LAMP. I cahnged /etc/apache2/sites-available/default
DocumentRoot /home/me/Dropbox/Web #changed from /etc/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /home/me/Dropbox/Web/> #changed from /etc/www
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
And now I get
Forbidden
You don't have permission to access / on this server.
Apache/2.2.22 (Ubuntu) Server at localhost Port 80
A:
Apache probably can't read from your Dropbox directory. In Ubuntu, Apache is configured to run as user www-data. Make sure you set the permissions on your filesystem to allow Apache reading the whole path.
To test whether this is really your issue, try in a terminal
sudo su -l www-data -s /bin/bash
and then cd step by step to your Dropbox folder:
cd /home
cd me
cd Dropbox
cd Web
Fix the permissions, e.g.
chmod o+rx on directories and chmod o+r on files, or
change groups on files/directories chgrp www-data and allow only the www-data group to read/access: chmod g+r for files and chmod g+rx for directories.
A:
www-data, the group/user Apache runs is not allowed to read in your home directory.
You can use regular permissions to change that as gertvdijk explained in its answer.
I would consider using acl instead of regular permissions, allowing to add permission to apache instead of replacing the group in home directory or making the directory world readable.
For that, you need to install acl:
sudo apt-get install acl
You can use man setfacl to have more info.
To add permissions to apache:
sudo setfacl -m d:g:www-data:X,g:www-data:X /home/me
sudo setfacl -m d:g:www-data:X,g:www-data:X /home/me/Dropbox
sudo setfacl -Rm d:g:www-data:rX,g:www-data:rX /home/me/Dropbox/Web
1st and 2nd commands will allow Apache (www-data) to change directory only through the path (without allowing other subdirectories) in your home. They are probably not needed if you are using default config but if you already changed permissions (or will change in the future) to disalow other users to read in your home, they are needed.
The 3rd one is the command that will allow Apache to read and change directories in Dropbox/web and sub-directories).
Obs: uppercase X will act only on directories instead of lowercase x that would act on both files and directories (this way apache user is only able to change directories, not executing files).
|
[
"stackoverflow",
"0037003660.txt"
] | Q:
Should we delete DataLake Analytic Job after completion?
We are submitting U-SQL jobs very frequently and we a see a list of jobs previously submitted in ADLA.
We see the total storage utilization of Data Lake store is increasing day by day. All of our jobs submitted only update one single output file and size is around 10 MB.
The current storage utilization of Data Lake store is 9.3 GB. We think it's due to the previous jobs resources are still saved in the Data Lake. Should we take care of this or we should do something here?
A:
I think the job data expires after a couple of weeks, but if you are concerned and do not need the data for auditing or investigations, feel free to delete them.
Given that the store has no limit and the storage cost 4c/GB/month according to the current pricing website, it is not a big cost though.
|
[
"stackoverflow",
"0007529124.txt"
] | Q:
PHP license code implementation
Does anyone have any suggestions on how to implement a activation license for PHP applications? Whilst I'm not planning on encrypting the source, and I'm not expecting there to be some magical way to stop people breaking the license check (people who want to do it, are going to do it anyway), I'd still like to find the balance between being annoying for people trying to break it, and being too annoying for me that it wouldn't be worth doing.
I'd like the license check to mainly work locally without having to call home, but also to on occasion call home to confirm (say once a day/week or something) if possible. Any thoughts on how to do it?
A:
You could implement a simple licensekey system, and maybe setup your own "license" server to query all your systems for a valid license key once or two times a day. Maybe also implement a license check during login to your product.
What exactly are you building this for? A CMS, offline intranet software or?
|
[
"hinduism.stackexchange",
"0000026782.txt"
] | Q:
Is there any mention of the Mahamrityunjay Mantra in the Puranas?
The Mahamrityunjay Mantra is a famous verse found in the Rig Veda which glorifies a "three-eyed deity". According to Shaivites, the mantra refers to Lord Shiva whereas Vaishnavas believe it to be referring to Lord Narasimha. I have heard that some Puranas have references to this mantra. Can anybody provide me these alleged references? Do any of these Puranic references indicate the "three-eyed deity" it glorifies?
A:
Here is a verse from the Shiva Gita (Padma Purana) where different mantras are chanted in praise of Lord Shiva/Rudra and the Trayambakam mantra is mentioned:
सौन्दर्यसारसंदोहां ददर्श रघुनन्दनः।
स्वस्ववाहनसंयुक्तान्नानायुधलसत्करान ।।
बृहद्रथन्तरादीनि सामानि परिगायतः।
स्वस्वकान्तासमायुक्तान्दिक्पालान्परितः स्थितान।।
अग्रगं गरुडारूढं शंखचक्रगदाधरम।
कालाम्बुदप्रतीकाशं विद्युत्कान्त्या श्रिया युतम।।
जपन्तमेकमनसा रुद्राध्यायं जनार्दनम।
पश्चाच्चतुर्मुखं देवं ब्रह्माणं हंसवाहनम।।
चतुर्वक्त्रैश्चतुर्वेदरुद्रसूक्तैर्महेश्वरम।
स्तुवन्तं भारतीयुक्तं दीर्घकूर्चं जटाधरम।।
अथर्वशिरसा देवं स्तुवन्तं मुनिमण्डलम।
गङ्गादितटिनीयुक्तमम्बुधिं नीलविग्रहम।।
श्वेताश्वतरमन्त्रेण स्तुवन्तं गिरिजापतिम।
अनन्तादिमहानागान्कैलासगिरिसन्निभान।।
कैवल्योपनिषत्पाठान्मणिरत्नविभूषितान।
सुवर्णवेत्रहस्ताढ्यं नन्दिनं पुरतः स्थितम।।
दक्षिणे मूषकारूढं गणेशं पर्वतोपमम।
मयूरवाहनारूढमुत्तरे षण्मुखं तथा।।महाकालं च चण्डेशं पार्श्वयोर्भीषणाकृतिम।
कालाग्निरुद्रं दूरस्थं ज्वलद्दावाग्निसन्निभम।।
त्रिपादं कुटिलाकारं नटद्भृङ्गिरिटिं पुरः।
नानाविकारवदनान्कोटिशः प्रमथाधिपान।।
नानावाहनसंयुक्तं परितो मातृमण्डलम।
पञ्चाक्षरीजपासक्तान्सिद्धविद्याधरादिकान।।
दिव्यरुद्रकगीतानि गायत्किन्नरवृन्दकम।
तत्र त्रैयम्बकं मन्त्रं जपद्द्विजकदम्बकम।।
गायन्तं वीणया गीतं नृत्यन्तं नारदं दिवि।
नृत्यतो नाट्यनृत्येन रम्भादीनप्सरोगणान।।
गायच्चित्ररथादीनां गन्धर्वाणां कदम्बकमकम्बलाश्वतरौ शंभुकर्णभूषणतां गतौ।।
गायन्तौ पन्नगौ गीतं कपालं कम्बलं तथा।
एवं देवसभां दृष्ट्वा कृतार्थो रघुनन्दनः।।
हर्षगद्गदया वाचा स्तुवन्देवं महेश्वरम।
दिव्यनामसहस्रेण प्रणनाम पुनः पुनः।।
Raghunanda there saw the essence of beauty. Riding on their own vehicles and carrying respective weapons were the Digpalas shining in their own lusture in their respective places and singing the Brihad And Ranthara Saman. In the front sitting on the Garuda and with the Sankha Chakra and Gada along with the lustrous Lakshmi was Janardana and singing SRI Rudram with the concenterated mind. In the back was seated Brahma in the swan, singing the Rudra Suktas of four Vedas from the four mouths along with Bharati. Devas and Munis were chanting the Arthavasiras and praising the Lord. God of ocean standing beside Ganga was also signing Svetasvatara hymns in praise of Lord of Girija. Great serpents like Aananta who looked as huge as Kailash mountain were seen singing hymns from kaivalya Upanishad. Nandi was seen in the front carrying a golden danda in his hands. In the south Ganesha was sitting in his Kartikeya) was seen sitting in his peacock. In the left and right side of Paramesvara were seen the Mahakala and Chandes. In a far distance was seen the Kalagni Rudra. Three legged Bhringi was dancing in the front along with the Ganas with various faces. In their respective vehicles were seated the divine mothers. Siddha Vidhyadharas were chanting the panchakshari Mantra. Kinnars were singing the Divya Rudra Gita. Divine Brahmanas were chanting the Tryambakam mantra. Narada was dancing in joy singing song from his Veena. Gandharvas like ChitraRathas were singing. All the Gods of heaven, heavenly snakes etc.. were seen all around singing the songs of Maheswara. Rama became ecstasic on seeing this beautiful scene. Then he started chanting Maheswara Sahasranama With many salutions.
Here is a verse from Linga Purana:
अदृश्यंति वशिष्ठं च प्रणम्यारुन्धतीं तत ।
कृत्वैकलिंगं क्षणिकं पांसुना मुनिसन्निधौ ।।
संपूज्य शिवसूक्तेन त्र्यंबकेन शुभेन च।
जप्त्वा त्वरितरुद्रं च शिवसंकल्पमेव च।।
नीलरुद्रं च शाक्तेयस्तथा रुद्रं च शोभनम्।
वामीयं पवमानं च पंचब्रह्म तथैव च।।
होतारं लिंगसूक्तं च अथर्वशिर एव च।
अष्टांगमर्घ्यं रुद्राय दत्वाभ्यर्च्य यथाविधि।। (Linga Purana, Chapter 64)
Here Sage Vashishta sang mantras in praise of Lord Shiva/Rudra.
Then Parashara bowed in reverence to Adryasanti - his mother, Vasistha and Arundhati - his grandparents. In presence of the sage Vasistha, he made a temporary Iinga of clay. Then he reciting the hymns from the Shiva Sukta,Trayambakam Mantra,,Tvarita Rudra, Siva Sankalpa, Nila Rudram, Shakteya- Rudra, Vamiya, Pavaman Sukta, PanchaBrahman Sukta, Linga-Sukta and Atharvasiras mantras, adored the Shivalinga. After worshipping the linga appropriately, he offered Ashtangya Arghya to Rudra.
Until now I came up with 2 references. I will update the answer if I find more.
A:
Linga Purana, Vol 2, Chapter 54 is completely dedicated to Tryambaka mantra alone. It describes the procedure of worshipping Shivalinga with Tryambaka mantra.
त्रियंबकेण मंत्रेण देवदेवं त्रियंबकम्।
पूजयेद्वाणलिङ्ग वा स्वयंभूतेऽपि वा पुनः॥१॥
Uttering the Tryambaka mantra, a devotee should worship Tryambaka in Bāņa-linga and Svayambhu-linga.
A:
From the Viniyogah of the Mahamrityunjaya Stotra which is found in the Rudra Yamala Tantra:
4.Om Asya Sri Maha Mrithyunjaya Kavachasya , Sri Bhairava Rishi, Gayathri Chanda,
Sri Mrityunjaya rudro devathaa , Om bheejam, Jram Shakthi , Sa keelakam Houm ithi thathwam, Chaturvarga phala sadhane pate
viniyoga.
Om, for the armour of the great Mrithyunjaya , the sage is Bhairava ,
The meter is Gayathri ,
The God addressed is Mrityunjaya Rudra , the root is “Om”, the power is “jram”, The nail is Sa” and the principle is “Houm” and
offering four types of fruits this is being chanted.
Also, apart from being one of the most famous Vedic Mantras, it is also a Tantrik Mantra. MahAmrityunja Mantra, MahAmrityunjaya Yantra and it's Prayoga are given in the Tantras.
From the Viniyogah of this Mantra we find (quoting from the TantrasAra's pp 502):
atha tryambaka mantrah | tryambakam yajAmahe ... mAmritAm ||
Vashishtohasya munih proktashchandahonushtupAhritah devatAsya
samuddishtA tryambakah pArvatipatih ||
So, consort of Goddess PArvati or Lord Shiva is the Deity for the Mantra.
And, from the DhyAna Sloka for Tryambaka, we find:
hastAbhyAm kalasadvayAmritaghatam kailAsakAntam shivam
svacchAmbhojagatam navendumukutam devam trinetram bhaje .. ||
The Mrityunjaya Prayoga in the Tantras is also based on the Mrityunjaya Yantram and which is one of the Yantras for Lord Shiva.
So, "Mrityunjaya" or "Mahamrityunjaya" always refer to the three-eyed Lord Shiva/Rudra.
|
[
"spanish.stackexchange",
"0000012926.txt"
] | Q:
When to use indirect object pronoun in subjunctive mood?
I just cannot figure out when's the correct time to use IOP when writing sentences in subjunctive mood/tense.
For example, I say my parents demand me to read three books a day.(sounds kinda weirdo, better with "want", but whatever) I can say mi Padres (me) exige que lea tres libros cada días.
PS: I AM NOT SURE IF I SHOULD USE INDIRECT OR DIRECT. I LEARNED FROM A POST THAT SOMETIMES IN SPAIN INDIRECT IS ALSO ACCEPTABLE.
A:
There are a number of things that need to be corrected before answer.
You example sentence ought to be
Mis padres (me) exigen que lea tres libros cada día.
The reality is, it's virtually always optional from a grammatical standpoint.1 It's useful when there could be confusion in the subordinate clause:
Mis padres exigen que lean tres libros cada día.
Are they demanding this of y'all (formal)? Or of some other group of people? Or even of themselves?
Mis padres exigen que lea tres libros cada día.
Are they demanding this of me? Or someone else?
There are two ways to clarify. You can either explicitly put the subject in the subordinate clause, or you can use an indirect object pronoun (this will always be an indirect object pronoun, because the subordinate clause is the direct object, it's just a noun clause rather than a pronoun):
Mis padres le exigen que lea tres libros cada día.
Using indirect object: They're demanding, just thankfully it's not me.
Mis padres me exigen que lea tres libros cada día.
Using indirect object: They're demanding of me!
Mis padres exigen que ella lea tres libros cada día.
Using explicit subject: They're demanding of her.
Mis padres exigen que yo lea tres libros cada día.
Using explicit subject: They're demanding of me!
1. The only time that you would have to use the indirect object pronoun is if person A is telling person B to have person C do something. Like, say, I dunno, my boss's boss tells him to tell me to do something: «La jefa le exigió (al otro jefe) que haga yo algo». But even then, if you make the indirect object explicit, the indirect object pronoun becomes optional again: «La jefa exigió al otro jefe que haga yo algo» is perfectly fine.
|
[
"stackoverflow",
"0018568543.txt"
] | Q:
Does a static final Object ever get deleted by Garbage Collector?
I have previously used Custom Objects in a Service in Java that always keeps running at the back end and I have sometimes got Bug reports with traces that showed NULL_POINTER_EXCEPTION as the object was destroyed by the Garbage Collector. As I have all high end devices I am unable to test this that does a static final object get destroyed by the garbage collector or not?
A:
In normal Java App (I'm not sure about Android), a static final referenced Object is GCed only when its proper ClassLoader is unloaded.
For example when having multiple web-apps in a container (such as Tomcat), undeploying each web-app, unloades application's ClassLoader, so application's static final referenced Object will be GCed. But objects loaded by other ClassLoaders (such as other web-app's ClassLoaders, common ClassLoader, boot-strap ClassLoader) won't be GCed.
So the answer to your question is: it depends on whether the ClassLoader is de-activated or not.
A:
Does a static final Object ever get deleted by Garbage Collector?
I can think of three circumstances where this could happen:
The classloader that loaded the class with the static becomes unreachable. But this can only happen after your code has reached a point where nothing could possibly notice that the object is GC'd!
Something has used "nasty reflective tricks" to assign null to the static final. (Yes, it can be done ...)
Something is subtly corrupting the heap; e.g. some buggy JNI / JNA code.
Note that since you are (apparently) observing the effect of the object being GC'd, it CANNOT be a direct result of the classloader being GC'd. Something else must have happened to make it possible for the classloader and the final static to be GC'ed ... if that is what is actually happening here.
Actually, I suspect that your problem is not GC-related. Rather, I suspect that your service is dying due to an unchecked exception that is not being logged. The default behaviour for uncaught exceptions on threads other than "main" is to silently ignore them.
I suggest that you check that your service threads are logging all exceptions, either with a catch in the run() method, or in an "uncaught exception handler".
|
[
"stackoverflow",
"0004869679.txt"
] | Q:
Using checkboxes to filter records
I am trying to learn rails from zero programming experience and have an app im trying to make. With much help from people on here, I have an index page of venues which are filterable by which area they belong to via a dropdown menu. I would like to be able to have the same affect but using checkboxes and also being able to select multiple areas to add to the filter. This is what I have so far:
Model :
class Venue < ActiveRecord::Base
belongs_to :user
has_many :reviews
belongs_to :area
scope :north, where(:area_id => "2")
scope :west, where(:area_id => "3")
scope :south, where(:area_id => "4")
end
Controller:
def index
if (params[:area] && Area.all.collect(&:name).include?(params[:area][:name]))
@venues = Venue.send(params[:area][:name].downcase)
else
@venues = Venue.all
end
end
Venues index.html.erb:
<div class="filter_options_container">
<form class="filter_form", method="get">
<%= select("area", "name", Area.all.collect(&:name), {:prompt => 'All Areas'}) %><br>
<input type="submit" value="Filter" />
</form>
<br><br>
<form class="filter_form", method="get">
<% Area.find(:all).each do |a| %>
<%= check_box_tag("area", "name") %>
<%= a.name %>
<% end %>
<input type="submit" value="Filter" />
</form>
</div>
<div class="venue_partials_container">
<%= render :partial => 'venue', :collection => @venues %>
<div class="clearall"></div>
<%= link_to 'add a new venue', new_venue_path, :class => "add_new_venue_button" %>
</div>
The first form (the dropdowns) in the filter_options_container works fine but the checkboxes (the second form) is returning "can't convert Symbol into Integer" what am I missing/doing wrong?
Thankyou for any help.
A:
I don't know exactly what's causing your error, but I can tell you that the check_box_tag helper isn't working the way you expect it to. From the documentation, it's defined like this:
check_box_tag(name, value = "1", checked = false, options = {})
So calling check_box_tag("area", "name") repeatedly will just give you <input id="area" name="area" type="checkbox" value="name" /> multiple times. Note that the "value" attribute (which is the value that gets sent to your server when that form is submitted) is always "name" - not what you want!
Instead, try the following:
<% Area.all.each do |a| %>
<%= check_box_tag("areas[]", a.id) %>
<%=h a.name %>
<% end %>
The things I've changed:
I used Area.all instead of Area.find(:all) - I did it for cosmetic reasons, but DanneManne's answer claims it's obsolete in Rails 3 (I wouldn't know - I'm still on 2.3.8).
I used the area's ID instead of its name in the value field; it's always good to look things up by ID if you can - IDs are integers, and compare faster than strings, and there'll always be an index on the id column in your database for extra-fast lookups.
And last, but way most importantly I threw in [] after the input name. This lets Rails collect all the values submitted with this name into an array, rather than just taking the last one. See below:
Throwing the URL...
/whatever?a=3&a=17&a=12
...at a Rails app gives you the params hash...
{:a => 12}
...but the URL...
/whatever?a[]=3&a[]=17&a[]=12
...gives you what you want:
{:a => [3, 17, 12]}
And if you have an array of all the area_ids you're interested in, you can get all the venues that are in any of those areas in a one-liner (isn't Rails great?):
filtered_venues = Venue.all(:conditions => {:area_id => params[:areas]})
Just make sure you have a valid array of area ids before calling that finder - if you don't, your conditions hash will evaluate to {:area_id => nil}, and Rails'll find you all the venues that don't have an area_id - probably none, and definitely not what you want.
Hope this helps!
|
[
"stackoverflow",
"0048207599.txt"
] | Q:
How can i search a datagridview using multiple checkboxes
This is my first question on this site so i apologise in advance if I format it incorrectly.
I am creating a system which should be able to search a database (dataGridView) using multiple checkboxes. I found some code online to search it using 3 checkboxes but am unsure how to extend this. I will need to be able to search using 50+ checkboxes. The following code is executed upon pressing of a search button which will display corresponding rows in my database. I want to know to most efficient way to extend this solution to 50+ checkboxes.
private void button1_Click(object sender, EventArgs e)
{
String filterdata = "";
if (checkBox1.Checked)
{
if (checkBox2.Checked || checkBox3.Checked)
{
filterdata = "'T05A1.1',";
}
else
{
filterdata = "'T05A1.1'";
}
}
if (checkBox2.Checked)
{
if (checkBox3.Checked)
{
filterdata = filterdata + "'C16D6.2',";
}
else
{
filterdata = filterdata + "'C16D6.2'";
}
}
if (checkBox3.Checked)
{
filterdata = filterdata + "'F41E7.3'";
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//cmd.CommandText = "Select * from Table1 where elegansgeneID ='" + filterdata + "'";
cmd.CommandText = "Select * from Table1 where elegansgeneID in(" + filterdata + ")";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
A:
Try this more shorter approach:
private void Button1_Click(object sender, EventArgs e)
{
var values = new List<string>();
if (checkBox1.Checked)
values.Add("'T05A1.1'");
if (checkBox2.Checked)
values.Add("'C16D6.2'");
if (checkBox3.Checked)
values.Add("'F41E7.3'");
// and so on
String filterdata = string.Join(",", values);
...
}
|
[
"stackoverflow",
"0029670991.txt"
] | Q:
ReactJS: text-align justify not working
I have been using text-align: justify to evenly distribute menus. Following this tutorial and it is working perfectly.
However, it breaks when I use ReactJS to create the view. A comparison can be found here: http://jsfiddle.net/j7pLprza/1/. I use these two simple components to populate the menus:
var MenuItem = React.createClass({
render: function() {
return (
<li>
{this.props.title}
</li>
);
}
});
var TopMenus = React.createClass({
render: function() {
return (
<div className="break">
<nav>
<ul>
{this.props.menus.map(function(menu) {
return (<MenuItem title={menu.title} />);
})}
</ul>
</nav>
</div>
);
}
});
After exploration, I think it is caused by ReactJS, which removes all line-break and white-space after <li> items. This will disable text-align: justify.
It happens for AngularJS as well (but I can fix it by using a add-space-all directive).
I reached only this issue after googling: https://github.com/facebook/jsx/issues/19. But I quickly got lost.
I tried to add some extra content, such as {'\n'} and {' '}, but ReactJS reports syntax errors.
Please help. Thanks.
UPDATE 1:
Following the accepted answer, my menus works in Chrome Emulator. However, when I visit from iPhone 5c (Chrome browser), the result is as if the extra space is not recognized.
After trying different combinations, this one works:
var TopMenus = React.createClass({
render: function() {
return (
<div className="break">
<nav>
<ul>
{this.props.menus.map(function(menu) {
return [(<MenuItem title={menu.title} />), ' '];
})}
</ul>
</nav>
</div>
);
}
});
Please be noted that the extra space in is necessary. Missing either or breaks it.
It works then on Nexus 7, iPhone 5c (Chrome and Safari). However, I do not know the exact reason. If anyone knows, please help.
UPDATE 2:
Still buggy. So I switched to Flex layout. And it is super easy. An example is: http://jsfiddle.net/j7pLprza/4/
A:
React doesn't remove anything in this case, since there is no whitespace between elements in the first place. If you want to add whitespaces between the li elements, you can interleave the array with ' '. In this case it is as simple as returning an array from the .map function (arrays are flattened):
var TopMenus = React.createClass({
render: function() {
return (
<div className="break">
<nav>
<ul>
{this.props.menus.map(function(menu) {
return [<MenuItem title={menu.title} />, ' '];
})}
</ul>
</nav>
</div>
);
}
});
Example: https://jsfiddle.net/j7pLprza/2
|
[
"stackoverflow",
"0021478806.txt"
] | Q:
Tkinter - Only show filled values of an array in a OptionMenu
I've the following code:
self.array_lt = ['foo', 'bar', '', 'moo']
var = StringVar()
self.menult = OptionMenu(randomwindow, var, *self.array_lt)
self.menult.config(width=30)
self.menult.grid(row=0, column=0, padx=(5,5), pady=(5,5))
This shows me a OptionMenu with the four values, foo, bar, (the empty space) and moo.
How can I show the OptionMenu without showing the empty value of the array? In another words, I want to show only foo, bar and mooon the OptionMenu and ignore the empty space.
The array_ly is just an example, I would like to have something general to ignore always the blank spaces.
Thanks in advance.
A:
You can use filter with None as the filter function to filter out values that would evaluate to False when interpreted as a boolean:
>>> filter(None, ["1", 0, " ", "", None, True, False, "False"])
['1', ' ', True, 'False']
Use this when you pass the list to the OptionMenu
self.menult = OptionMenu(randomwindow, var, *filter(None, self.array_lt))
|
[
"stackoverflow",
"0024601118.txt"
] | Q:
Vectorize column wise operation in octave or matlab
How can I vectorize the following code? It is basically computing the mean of each column.
mu(1) = sum(X(:,1))/C
mu(2) = sum(X(:,2))/C
and this (normalized each element, each column has different mean and std): (X is 47x2. mu, sigma are both 1x2)
X_norm(:,1) = (X(:,1)-mu(1))/sigma(1)
X_norm(:,2) = (X(:,2)-mu(2))/sigma(2)
A:
It's as simple as:
mu = sum(X) ./ C
sum by default operates along the first dimension (on columns).
EDIT:
For the second part of the question:
X_norm = bsxfun(@rdivide, bsxfun(@minus, X, mu), sigma)
It is similar to doing repmat's, but without the memory overhead.
|
[
"math.stackexchange",
"0001388133.txt"
] | Q:
Finding the minimal polynomial of $e^{2\pi i/5}$ over $\mathbb Q(\cos(2\pi/5))$
How would one find the minimal polynomial of $e^{2\pi i/5}$ over $\mathbb{Q}(\cos(2{\pi}/5))$?
The $\mathbb{Q}(\cos(2{\pi}/5))$ is what is confusing me the most. I know that $\mathbb{Q}(\cos(2\pi/5))$ is an extension of $\mathbb{Q}$ where we have polynomials with rational numbers and $\cos(2\pi/5)$ as coefficients, but I don't know how to combine with finding the minimal polynomial.
I tried setting $x=e^{2\pi i/5}$ and I know that $x^5=1$. Then I could do $$x^5-1=0 \rightarrow x^5-1=(x-1)(x^4+x^3+x^2+x+1)$$ but after that I don't know how to proceed.
A:
Hint: Using the fact that $$\cos \theta = \frac{e^{i\theta}+e^{-i\theta}}2,$$
we have $\mathbb Q(\cos\frac{2\pi}5)=\mathbb Q(e^{2\pi i/5}+e^{-2\pi i/5})$.
Can you find a polynomial with $x=e^{2i\pi/5}$ as a root, whose coefficients lie in the field $\mathbb Q(e^{2\pi i/5}+e^{-2\pi i/5})=\mathbb Q(x+\frac1x)$?
A:
You've got it down to $x^4+x^3+x^2+x+1$ and the remaining question is whether to factor that further within $\mathbb Q(\cos(2\pi/5))$. In $\mathbb C$, you can get that down to four first-degree factors, in two complex-conjugate pairs, hence two quadratics. So the question is whether that one of those quadratics whose roots are $\exp(\pm 2\pi i/5)$ has its coefficients in $\mathbb Q(\cos(2\pi/5)$. The polynomial is
$$
(x - e^{2\pi i/5}) (x - e^{-2\pi i/5}) = x^2 - 2x\cos(2\pi/5) + 1.
$$
And then I think the answer becomes clear.
PS: A quicker way: First find the minimal polynomial of $e^{2\pi i/5}$ over $\mathbb R$ and then ask whether its coefficients are in $\mathbb Q(\cos(2\pi/5))$. The minimal polynomial over $\mathbb R$ of anything in $\mathbb C\setminus\mathbb R$ is a quadratic polynomial whose other root is the complex conjugate.
|
[
"stackoverflow",
"0014573627.txt"
] | Q:
KML DOM Walking is SLOW! How To Avoid Walking Children?
I have been having some problems with performance related to navigating a KML DOM that I get from a KMZ file on a web server (using fetchKml). I am using the gex.dom.walk approach described and discussed here:
https://developers.google.com/earth/articles/domtraversal
http://code.google.com/p/earth-api-utility-library/wiki/GEarthExtensionsDomReference
Essentially, I am just trying to turn on/off visibility of folders when a folder name matches some criteria from a GUI click event. As I said, this works but performance is not great. It maybe takes 30 - 60 seconds for the visibility settings to be updated in the application. I read in the links above that you can turn off the walking of children nodes and I have attempted to do this with the object literal approach below. The code that I have included doesn't produce any javascript errors but it doesn't improve performance. I'm not sure if I am creating the object literal correctly and setting the walk children property properly. Any advice? A good example of turning off the walk children property with the use of gex.dom.walk would be very helpful. I couldn't find an example online.
These folders have a number of placemarks in them (100s) and I have 25 folders. So, I would like to avoid walking them and suspect this is at least part of the culprit for the performance issues. The KMZ file is about 250 Kb and the KML inside is about 7.5 Mb. This file will grow over time somewhat, as well.
I have also read about Gzip compression and will have to do a bit more research on that. I suspect that might help, too.
Thanks for any direct response or related tips!
function visibilityKml(context) {
//this is called by click events on the GUI
//if a menu item click, traverse the KML DOM to process the visibility request
//
//
var gex = new GEarthExtensions(ge);
var walkStatus = {
walkChildren : true
};
gex.dom.walk({
rootObject: ge,
visitCallback: function(walkStatus) {
// 'this' is the current DOM node being visited.
if ('getType' in this && this.getType() == 'KmlFolder') {
if ( context.match("AXYZ") && this.getName().match("AXYZ") && this.getVisibility() == false) {
this.setVisibility(true);
}
else if ( context.match("AXYZ") && this.getName().match("BXYZ") && this.getVisibility() == true) {
this.setVisibility(false);
}
else if ( context.match("BXYZ") && this.getName().match("BXYZ") && this.getVisibility() == false) {
this.setVisibility(true);
}
else if ( context.match("BXYZ") && this.getName().match("AXYZ") && this.getVisibility() == true) {
this.setVisibility(false);
}
else if ( context.match("All XYZ") && this.getName().match("XYZ") && this.getVisibility() == false) {
this.setVisibility(true);
}
if ( this.getName().match("XYZ") ) {
this.walkChildren = false;
}
}
}
});
}
A:
First: In your KML file, you need to edit these lines
OLD
<Folder>
<name>Name of Folder</name>
<Placemark>
..........
</Placemark>
</Folder>
NEW
<Folder id="unique_id">
<name>Name of Folder</name>
<Placemark>
..........
</Placemark>
</Folder>
Second: When you wish to toggle the visibility of this folder, use the Accessors
Depending on how you load your KML (eg fetch,parse,networklink) you use a different Accessor. I am going to presume you are using fetchKml() so I suggest you look into using
getElementByUrl()
So, you end up doing something like this:
(you need the # symbol)
var url = 'http://www.domain.com/yourFile.kml';
var folder = ge.getElementByUrl(url + '#' + 'unique_id');
folder.setVisibility(true|false);
Hope that helps!
|
[
"stackoverflow",
"0054320039.txt"
] | Q:
With Spring-Boot auto-configured JavaMailSender, how to support encrypted (username/password) properties using Jasypt library?
JavaMailSender is being auto configured in my Spring Boot application. How can I use annotations to allow encrypted values in my properties file for the properties "spring.mail.username"and "spring.mail.password"
using the Jasypt library? please help.
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SimpleMailController {
@Autowired
private JavaMailSender sender;
A:
I was able to crack it.
Add the annotation @EnableEncryptableProperties to my Application class.
Add jasypt spring boot starter dependency in gradle script -
compile('com.github.ulisesbocchio:jasypt-spring-boot-starter:2.0.0')
All the properties used in my application now support encrypted values by default.
|
[
"stackoverflow",
"0038603164.txt"
] | Q:
How to calculate the overall value of the row?
The results I want
Please Help Me, Thanks for attention.
A:
You can use group by with rollup along with ifnull:
select ifnull(customer, 'Total') customer, sum(qty)
from yourtable
group by customer
with rollup
SQL Fiddle Demo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.