text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
jquery ui selectable() and sortable() combine
I am using a twitter jquery plugin to display a list (ul/li) of twitter posts .
Also I want my users to be able to rearrange the posts as they want and I want the moved post to be marked.
I saw a post here how to do so.
If I use this the selectable function doesn't work(I can rearrange but can't select):
$(document).ready(function() {
$(".ul_sortable" ).sortable().selectable();
});
If I use this the sortable function doesn't work(I can select but cant re arrange):
$(".ul_sortable" ).sortable().selectable();
The key is to use the sortable handle option as shown in the link to the other question.
Sortable and selectable both take over the mouse events for the items they are applied to, however the handle option allows you to apply the sorting to a part of the item therefor allowing selectable to work on the rest of the item.
It should also be noted that selecting a bunch of items then sorting them all together is not natively supported.
For marking if an item is moved you can use a variety of sortable events such as stop and change docs
| common-pile/stackexchange_filtered |
Clustering with probabilities
I will ask my question beginning by an example (I am novice in stats)
I have a set of probabilities from a given observation A={0.3,0.2,0.001, 0.02, ...}
I want to partition A on subsets or clusters so as each one will contain the closest probabilities. And after, i will be interested in calculating the distances between the clusters. Is there any simple algorithm I can use for this?
Thanks
I am not completely sure of your question, but it seems like you could be satisfied with some simple clustering algorithm like http://en.wikipedia.org/wiki/K-means_clustering
I don't understand what you mean. Maybe it would help if you explained more what you mean by "observation." Also, what do you mean by closest? What's this for? The dude that answered above me is probably onto something, though.
This sounds like latent class analysis - I suggest looking into that
I will explain: we observe a system and we have a set of subjects that have done a given action. After observation we infer a set A with the probabilities relative to each subject having done the action. I want to cluster the set of subjects on subsets or clusters which groups subjects according to the prababilities. I want to cluster and measure the distance between clusters for evaluate the amount of information we have after observation. I am also interested in detecting outliers.
There are several algorithms to do this.
The simplest is k-means, one implementation of which is:
you pick the number of clusters you want, K
you choose the centre of the clusters randomly to start with. There are K clusters, so K cluster centers
now you iterate:
first you look at each point, and assign it to the nearest cluster centre
then, once you've assigned all the points to the clusters, you take the average of all the points in each cluster, and that becomes the new cluster centre, of that cluster
A good resource for learning clustering is 'Pattern Recognition and Machine Learning', by Christopher M. Bishop, chapter 9 'Mixture models and EM'.
but the number of clusters is not known
If A is an one-dimensional data set like the one you mentioned, I think a simple histogram will give the simple of clustering and distance.
(+1) or Kernel Density estimation as a more generic approach
| common-pile/stackexchange_filtered |
Initialization of the data source failed - Excel 2016
I'm trying to refresh a query in Excel 2016 (new install) and I get the above error. I've looked around, the problem seems quite common, but none of the answers seem to fit my issue.
In Excel, I have a couple of tabs of data in Excel tables. I use Get & Transform to import these tables into Power Query from where I generate 4 further tables of data, which are uploaded to the Data Model. I then create 3 relationships and generate 3 pivot tables with a single slicer to operate the tables.
When I come out of Excel and go back in and select "Refresh All", this is when I get the error:
Initial of the data source failed.
Check the database server or contract your db admin. Make sure the
external db is available and then try the operation again. If you see
this message again, create a new data source to connect to the DB
The data source is the excel workbook. I tried re-creating the Power Query queries etc, but to no avail.
Repair on Power Pivot also didn't work.
Given it's a new install of 2016, which comes with Power Query and Pivot as standard, I'm not sure where to try next.
Any help much appreciated.
Have you tried it on a non new install? I know the first thing I do on any new install of Excel/PQ is set it to "Ignore Privacy Settings", because this never fails to break something for me. Normally my issue is due to references to external files on a network, but I'm sure there are other things that setting can break.
Yes, I should have explained in my initial email. I tried it first on my own PC, which was an upgrade of a previous Excel version, and then I tried on another user's PC that had a fresh install of Excel on an entirely new build PC. Typically, I am not in the office today, but I'll give the Ignore Privacy Settings a try when I am back in. Thanks for your response.
I ran a repair on my installed version of Excel 2010, and that seems to solve the issue for me, I've seen sometimes when the user has multiple versions of excel installed library references can get broken, resulting in this error.
| common-pile/stackexchange_filtered |
Does this code make sense? C++ copy return vs ptr in
Which version of this code is better (or is there an even better way to do it)?
Copy out
void TranslatMat(float x, float y, float z) {
Matrix matTranslation = {
1.0f, 0.0f, 0.0f, x,
0.0f, 1.0f, 0.0f, y,
0.0f, 0.0f, 1.0f, z,
0.0f, 0.0f, 0.0f, 1.0f };
return matTransltion;
}
OR Ptr in
void rlTranslateMat(float x, float y, float z, Matrix *result) {
*result = {
1.0f, 0.0f, 0.0f, x,
0.0f, 1.0f, 0.0f, y,
0.0f, 0.0f, 1.0f, z,
0.0f, 0.0f, 0.0f, 1.0f };
}
I just learned the rule of fifths and move constructors. Does that even apply here?
I know a 4x4 Matrix struct isn't huge but I plan to use this function every frame and this pattern for larger structs than a matrix.
Your first example "copy out" won't compile. It is declared as a void function but returns a value.
Begin by defining "better". What do you want to optimize for? Memory usage? Speed? Readability? Something else?
Witch version of this code is better -- First, write the code without any usage of pointers. Use pointers when you must use them. Also, overly using pointers when you don't need to can and will render the compiler optimizations lessened or even not doable due to pointer aliasing (in other words, slowing your code down, not speeding it up). Those "pointer tricks" may have worked back in the 80's and 90's, but today's compiler optimization techniques renders those tricks useless.
The first one should be written as return Matrix{/*...*/}; or, assuming the return type on the function is already declared as Matrix, alternatively return {/*...*/};. Not using an intermediate variable doesn't change the meaning of the code except that it guarantees copy elision since C++17. (Minor exceptions apply since = {/*...*/} doesn't 100% do the same, but there should be no difference for a reasonably behaved class.)
To PaulMcKenzie's point above: return by value here will almost certainly trigger NRVO (the copy elision would even be guaranteed in C++17 or above if you got rid of the unnecessary function-local temporary variable), so no copies will be made at all. A pointer to an out parameter will likely require your result matrix to first be default-initialized and then copy-assigned to, which could easily end up being slower (though it remains to be seen if the performance difference would matter).
Matrix TranslatMat(float x, float y, float z) {
gives the most readable calling code
auto M = TranslatMat( x, y, z );
This will save you hours of work debugging your application
Once your application is working, then you can think about optimizing, but only code where time profiling shows it will make a significant improvement - likely not this code.
The first example you are making a local matrix and then 'returning by value'. However, you have defined it as 'void'. This means you won't be able to return anything. If you attempted to compile the first example it will fail. to fix it you need to change type 'void' to type 'Matrix'
The second example you are passing a pointer to the function, directly modifying said data, then should return void (nothing).
There is no best case and to know which one to use.
If you are looking for a function to generate a matrix and you start working with it, lean towards the first example.
If you have an existing matrix and want to modify it, then you can use the second example.
However, given that this is c++, you could also choose to pass by reference.
Given the nature of this question, I would recommend you to read up on: pass by value, pass by reference, and pass by pointer.
Afterwards, look into learning more about return types as well as dynamically allocated memory.
Once all of these are understood, then go back to the rule of 3 or 5 and move/copy constructors.
Returning the matrix will be better because:
it's more readable
it allows copy elision
it avoids potential aliasing with other Matrix * or float *
The last too will result in faster code.
Note: the compiler will turn it into ptr in if it can't optimize it, except it will use the structure return register instead of the 4th argument register.
| common-pile/stackexchange_filtered |
How to find the coordinates of the point on a sphere closest to another point?
Take the sphere $x^2 + y^2 + z^2 = 4$ and find the point on it that is closest to the point $(3,1,-1)$ without using calculus.
The point on a surface closest to a point not on the surface (called an "external point") lies on a normal line from the surface point to the external point. All radii of a sphere are normal (perpendicular) to the sphere's surface. So the closest point to $ \ (3,1,-1) \ $ will lie along the radius from the origin (the center of the sphere) connecting to that external point. You need to find the point on the sphere that is found on that line.
Maybe even easier: the point on the sphere has to be 2 units away from the origin. Find the line $ ^* $ passing through $ \ (0,0,0) \ $ and $ \ (3,1,-1) \ $ , then locate the point on that line which is 2 units from the origin.
$ ^* $ EDIT: To remove the ambiguity that I clumsily left, which Thomas Andrews properly points out, perhaps I should say "the line segment" connecting the two points.
There are, of course, two points on that line meeting that condition. You really want the point on a particular ray from $(0,0,0)$...
True, you would then have to chose the point at the smaller distance from the external point. The problem is really simple if you use vectors (which aren't generally covered in pre-calculus) and automatically gives you that ray.
| common-pile/stackexchange_filtered |
AWS Cognito: Getting error in Auth.signIn (Validate that amazon-cognito-identity-js has been linked)
I'm new to Amplify integration with Cognito and working on a react-native app using Amplify with Cognito for Authentication. I have configured the user pool and Federated Identity in the AWS console.
I have created my own signup and login interface with the respective screens using the react-navigation 5.x version.
Below are the AWS related modules I added in package.json
"@aws-amplify/auth": "^3.4.24",
"@aws-amplify/core": "^3.8.16",
Here is the Amplify configuration in the App.js
Amplify.configure({
Auth: {
identityPoolId: 'eu-west-2:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
region: 'eu-west-2',
userPoolId: 'eu-west-2_xxxxxxxx',
userPoolWebClientId: 'xxxxxxxxxxxxxxxxxxxxxx',
authenticationFlowType: 'USER_PASSWORD_AUTH'
}
});
I'm able to successfully invoke Auth.signUp but getting error when I'm trying to invoke Auth.signIn(username, password)
Validate that amazon-cognito-identity-js has been linked
How do I able to invoke Auth.signIn successfully, please help in resolving the issue?
You need amazon-cognito-identity-js dependency installed.
Thanks that it helped to resolve.
I had the same problem and I fix it by installing cognito identity.
Run the following:
npm i amazon-cognito-identity-js
After install start again rn
npm start
please edit your question and add more information about your errors, logs, and codes.
npm i amazon-cognito-identity-js this work for me thanks
If you're running on ios, in addition to installing amazon-cognito-identity-js as mentioned, remember to also run pod install
| common-pile/stackexchange_filtered |
Filter last word after matching a string
I need to filter out some hexadecimal value from a return string of a command in bash for example:
hexVal=`mmc extcsd read /dev/mmcblk1 | grep 'Max Enhanced Area Size'`
Will return the value of hexVal as:
Max Enhanced Are Size [MAX_ENH_SIZE_MULT]: 0x000bd8
Now, I need the value of hexVal to be returned as:
0x000bd8
Yes @jimmij. They are the last words
Instead of grep, you could use awk as it is more useful in pattern matching and printing out the matched fields
mmc extcsd read /dev/mmcblk1 | awk -F: '$1 ~ "^""Max Enhanced Area Size" { print $2 }'
You could also remove the leading space in the above result
awk -F: '$1 ~ "^""Max Enhanced Area Size" { sub(/^[[:space:]]/,"",$2); print $2 }'
If you are to use grep and have the GNU version of it installed, use the PCRE mode
grep -oP '^Max Enhanced Area Size.*:(\s+)\K(.+)'
Thanks a million @Inian. The grep command you suggested works perfectly
| common-pile/stackexchange_filtered |
how to set UIView background programmatically
in the interface builder,i can find the background tag,and select the color and the opacity.
if I create the UIView programmatically,if I want to change color,I can set the backgroundColor property
the question is if I want to change the opactiy,What is the property should I change?
Thanks a lot.
Use the view's alpha property, or, if you don't want the view's content to have the same opacity change applied to it, change the alpha component of the background color (as created with +colorWithRed:green:blue:alpha:, +colorWithHue:saturation:brightness:alpha:, or +colorWithWhite:alpha:) to something other than 1.
You can just use
self.alpha = someFloat;
in your view class.
If you want to change it from viewcontroller, use
self.view.alpha = someFloat;
| common-pile/stackexchange_filtered |
What is the percentage of Earth's hemisphere seen from different orbital heights or distances?
We often see photos of Earth from space, but it is rarely clear what percentage of Earth's hemisphere is actually visible from any particular orbit.
• Is there a graphic or diagram that would show the percentage of Earth's hemisphere that is visible from low Earth orbit? • high Earth orbit? • geosynchronous orbit? • lunar orbit? • 1 million miles? • the Sun?
• Alternatively, is there a graphic or diagram that would show the percentage of a mathematical hemisphere "seen" from various points at multiples of a sphere's radii?
• Is there a website with interactive graphics that can calculate the above?
• I am a fan of space exploration (and accurate graphics). My working knowledge of math and geometry is limited.
Assuming the surface of the earth is a sphere, or more realistically?
$\frac{h/2}{r+h}$ of the surface of a sphere with radius $r$ can be seen when viewed from an altitude of $h$. I'll write this up.
$\frac{h}{r+h}$ of the surface of a hemisphere of a sphere with radius $r$ can be seen when viewed from an altitude of $h$. I've written this up.
Suppose we are at an altitude of $h$ above a sphere with radius $r$. $\triangle ABD\cong\triangle DCB$; therefore,
$$
\frac{BC}{BD}=\frac{BD}{AD}
$$
Since $AD=h+r$ and $BD=r$, we get $BC=\frac{r^2}{h+r}$. Subtracting from $r$ gives the width of the cap to be $\frac{hr}{h+r}$. The surface area of any cap or band on a sphere is the width of the cap or band times the circumference of the sphere: $2\pi r\frac{hr}{h+r}$. Since the surface area of the hemisphere is $2\pi r^2$, the portion of the hemisphere area in the cap is
$$
\bbox[5px,border:2px solid #C0A000]{\frac{h}{h+r}}
$$
| common-pile/stackexchange_filtered |
How to center the view on the "Time Cursor" in the Video Sequence Editor?
I have three markers in the timeline, and I am working in one of these three areas in the sequencer around the 3rd mark:
I try to use the first marker in the timeline, so that the sequencer jumps to that position without having to zoom out in the sequencer and look for that 1st mark manually and then zoom in around it.
There is a menu entry 'jump to the previous marker', but then only the time cursor (green line) jumps and gets out of sight, but the sequencer keeps showing the same area I was working in.
Is there a way to tell the sequencer to pan to the area where the green line is? I want the whole view to jump to where the previous marker is, and not only the green line.
Not sure I understood the question, but I guess you're looking for "Jump to the next marker" function in the Marker menu (of any animation Editor). You can assign a shortcut to it by right clicking on it.
@thibsert Yes, but then the green line jumps and gets out of sight. But the sequencer keeps showing the same area. I want the view in the sequencer to jump, not only the green line. Or, is there a way to say "pan to the area where the green line is" to the sequencer?
Once the green line is on the desired marker, you can press Numpad 0 to center the view on it.
@thibsert Yes, I thought the same...
@thibsert You solved my question, thanks! :) Please write that comment as a short answer and I will accept it.
You're looking for "Jump to the next marker" function in the Marker menu (of any animation Editor). You can assign a shortcut to it by right clicking on it.
Once the Current frame (the green line) is on the desired marker, you can use Numpad 0 to center the view on it.
| common-pile/stackexchange_filtered |
Mint leaves look chewed up and burned
I have a mint plant outdoors in a pot that grew rapidly and then suffered from some insect which just loved eating it. It's in a mostly sunny spot next to a high bed. I sprayed it with a solution of water, liquid soap and canola oil. But later, it looks like the leaves are burnt--not always from the edges but from spots in the middle as well. Could this be the canola oil in the spray? Also wondering if it could be something else.
I let the new growth grow without spraying, but it seems to be affecting new young leaves as well. They turn black and are almost crispy.
Thanks, M
just general advice - not sure what would be eating your mints leaves.
Mints in general like a water retentive moist soil.
Placing it in sun will make the oils that are attractive to us stronger, but it will need close attention to moisture levels to stay healthy.This may mean watering daily.
You state that it is in a pot so in sunny weather will dry quite quickly and the sun on the pot, if it is dark in colour will add to the heat affecting the roots. It may be that the plant is stressed which could reduce its ability to defend itself against predators. The spray ingredients may or may not have affected the plant. What may have 'burnt' the leaves could be spraying liquid onto the plants leaves in bright sunshine as the droplets act as lenses for sunlight and scorch the tissue on which they sit.
As mint are invasive, its good to keep them in a pot or container but it may be beneficial to sink/bury the pot in the ground. This will contain the mint, slow water loss and allow the mints roots to go through the bottom of the pot, if needs be, to get moisture. Planting amongst sun-tolerant/sun-loving plants will shade the mints roots and help keep them cool but whilst allowing its foliage to take advantage of the sun.
| common-pile/stackexchange_filtered |
How to update filter on wpf datagrid?
i want to filter wpf datagrid, and i do that in this way,i use datagridcolumnsheader and put a textbox in headers and use them filter each column:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textSearch = (sender as TextBox).Text;
CollectionViewSource.Filter += new FilterEventHandler(FilterEvent);
}
and
private void FilterEvent(object sender, FilterEventArgs e)
{
if (propertyName == null)
return;
var a = e.Item.GetType().GetProperty("Name");
if (a != null)
{
if (textSearch != "")
{
var s = a.GetValue(e.Item, null);
if (s != null)
e.Accepted = s.ToString().Contains(textSearch);
else
e.Accepted = false;
}
else
e.Accepted = true;
}
}
it works fine for a column like id,but when i want to make filter on another column like name ,it filters the list just by name and dosen't keep the past filter,for example if i filter the list by id=2 ,and then filter it by name='a' ,it just filters list by name='a'!
To apply multiple filters to a collection bound to a WPF DataGrid you should instantiate a CollectionViewSource object as a proxy between the view and the collection (this will also work with other collection controls). Doing so will allow you to subscribe multiple filter event handlers to it's Filter event. Filters are applied in the order in which they are subscribed and can be removed by unsubscribing them.
If you used the CollectionViewSource.GetDefaultView() static method in your codebehind or ViewModel, this will return an instance of an ICollectionView which will only support a single filter with a Filter property.
Your can find an example with source code here http://www.codeproject.com/Articles/442498/Multi-filtered-WPF-DataGrid-with-MVVM
| common-pile/stackexchange_filtered |
Get occurrences of a string in a list of strings.
I have 2 textboxes and a button, when the button is clicked I want it to take a list I have created and have put into lower case and check the amount of occurrences each string appears.
My code:
Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1.Click
Dim count As Integer = 0
Dim userString As String = userInput.Text
userString = userString.ToLower()
Dim inputList As New List(Of String)(userString.Split(" "))
While count <= inputList.Count - 1
output.Text &= inputList(count) & " Occurred: " & NEED TO GET OCCURRENCE & Environment.NewLine
count = count + 1
End While
End Sub
What would be the best way to keep a count for each and every word?
Thanks,
Matt
You can use a simple LINQ expression:
Dim userString As String = "How much wood would a woodchuck chuck if a woodchuck could chuck wood"
Dim userStringGroupByWords = userString.Split(" ").GroupBy(Function(word) word)
For Each word In userStringGroupByWords
Console.WriteLine($"Word: {word.Key}, Count: {word.Count}")
'Or Console.WriteLine("Word: {0}, Count: {1}", word.Key, word.Count)
'if you are not using VS 2015 and .NET >= 4.6
Next
Output:
Group: How, Count: 1
Group: much, Count: 1
Group: wood, Count: 2
Group: would, Count: 1
Group: a, Count: 2
Group: woodchuck, Count: 2
Group: chuck, Count: 2
Group: if, Count: 1
Group: could, Count: 1
You could use a Dictionary to store the words and their counts:
Option Infer On
' ....
Dim s = "The only cat sat only on the cat mat"
Dim d As New Dictionary(Of String, Integer)
Dim ws = s.ToLower().Split(" "c)
For Each w In ws
If d.ContainsKey(w) Then
d(w) += 1
Else
d.Add(w, 1)
End If
Next
For Each de In d
Console.WriteLine(String.Format("{0,-10}{1,2}", de.Key, de.Value))
Next
Console.ReadLine()
Outputs:
the 2
only 2
cat 2
sat 1
on 1
mat 1
(The descending counts are only coincidence.)
What would be the best way to append that to a textbox? http://pastebin.com/vXmZk9a9
@MeeMeme Use output.AppendText(String.Format("{0,-10}{1,2}" & VbCrLf, de.Key, de.Value)) instead of the Console.WriteLine(...) line.
@MeeMeme Please see my comment of Sep 21 at 9:49.
I now have this outputted: http://s10.postimg.org/4mzj1vyt5/Capture.png
@MeeMeme Sorry, I was under the impression that output was a some control which would have .AppendText. Try output.Text &= String.Format("{0,-10}{1,2}" & VbCrLf, de.Key, de.Value). You really should have looked at what was going on and tried something yourself ;)
| common-pile/stackexchange_filtered |
Is it legal for police to use their lights to go through a red light?
Many of us have seen this. A police car stops at a red light and after ten seconds with no cross-traffic, they put their lights on only (no siren) drive across the intersection against the red light, then turns off their lights on the other side and drives slowly away.
I assume that flashing their police lights is to avoid a fine in case they are caught by a red-light camera. Is it legal for police who don't have an urgent police reason to do this?
"to avoid a fine if they are caught by a camera": that's an odd way of putting it. Either the behavior is legal or not, whether it is recorded by a camera or by a witness. Surely, too, the behavior existed before automatic traffic enforcement cameras were developed.
@phoog A person might see the whole incident. A camera will only take one or two photos and all you'll see is that the car's police lights are on.
But in fact as the answer shows the use of the lights is one of the facts required for the passage through the red signal to be legal in NSW, yet for some reason you have not upvoted the answer, let alone accepted it.
This is an excellent explanation.
All Australian jurisdictions have (in general) common road rules. In NSW these are enacted by Road Rules 2014 regulation under the Road Transport Act 2013.
The relevant provision is Clause 306:
306 Exemption for drivers of emergency vehicles
A provision of these Rules does not apply to the driver of an emergency vehicle if:
(a) in the circumstances:
(i) the driver is taking reasonable care, and
(ii) it is reasonable that the rule should not apply, and
(b) if the vehicle is a motor vehicle that is moving-the vehicle is displaying a blue or red flashing light or sounding an alarm.
From your statement (a)(i) and (b) would seem to apply so it becomes a question if (a)(ii) does. Well, you don't know the circumstances so you can't judge if it is reasonable that the rule not apply: if the police car were involved in a collision, caught on a red light camera or booked then the driver would have to show that it was.
It is worth noting that some road offences like drink or dangerous driving are not in the Road Rules, they are in the Crimes Act and so the exemption doesn't apply to them. It is also not a shield from civil liability although the difficulty of proving negligence goes up because disobeying the road rules is no longer enough.
What I find fascinating is that "reasonable" is not defined and is completely opinion based. So maybe it's reasonable that the police shouldn't have to wait for the green light and maybe it's reasonable that they wait just like everyone else. It seems only the police in the car can say whether it's reasonable or not, and when questioned after the fact will always say it's reasonable.
@CJDennis you couldn’t be more wrong - “reasonable” is one of the most rigidly objective terms in the whole legal system - it has nothing to do with the participants’ state of mind.
What is ‘fair’ and ‘reasonable’ depends a lot on your perspective January 2014 Chris Wheeler Deputy NSW Ombudsman https://www.ombo.nsw.gov.au/__data/assets/pdf_file/0011/50006/What-is-fair-and-reasonable-depends-a-lot-on-your-perspective.pdf
@CJDennis Read the document in full - it says "fair" is subjective but "reasonable" is objective.
@CJDennis "reasonable" doesn't refer to the offender's state of mind, it's from the perspective of other people (a so-called "reasonable person").
It is certainly possible that it is justified. Many police departments have a policy of not flashing lights and turning on sirens when not actually necessary to get past other traffic so as to minimize neighborhood disturbance, even when they are permitted to do so.
Also, the rule cited by Dale M "it is reasonable that the rule not apply" is susceptible to varied interpretations.
If it is an abuse of that traffic provision, and it certainly could be, as a practical matter, it will not be enforced, and so there is no point in getting worked up over it.
scotland england-and-wales
Although I can't find relevant legislation for traffic signals, section 87 of the Road Traffic Regulation Act 1984 provides the exemption from speed limits, and I expect the provisions to be similar for traffic signs:
No statutory provision imposing a speed limit on motor vehicles shall apply to any vehicle on an occasion when it is being used for … police purposes, if the observance of that provision would be likely to hinder the use of the vehicle for the purpose for which it is being used on that occasion.
Note that there is no requirement for flashing blue lights or siren - that's a choice for the driver to make depending on the circumstances.
Interpretation of "police purposes" and "hinder" requires some judgement. It's clear that reaching the scene of an incident is police purposes that would be hindered; returning to the nick for a cuppa probably isn't. Although patrolling more of the beat is "police purposes", it's doubtful that is hindered by observing traffic rules.
Regardless of legality, misuse of blue lights is typically a disciplinary matter for police officers, and not treated lightly.
| common-pile/stackexchange_filtered |
Force NSLocalizedString to use a specific language using Swift
With swift, how can I force my app to read data from a specific Localizable.strings.
I put this in didFinishLaunchingWithOptions before instantiate the ViewController but it still show me the App in English.
NSUserDefaults.standardUserDefaults().removeObjectForKey("AppleLanguages")
NSUserDefaults.standardUserDefaults().setObject("fr", forKey: "AppleLanguages"
NSUserDefaults.standardUserDefaults().synchronize()
And I tried to pass an Array for the "AppleLanguages" key like this but it still doesn't work:
NSUserDefaults.standardUserDefaults().setObject(["fr"], forKey: "AppleLanguages"
And once this is done, can I call this inside the App and take the changes in consideration without restarting the App?
It's not possible to change app's language immediately by changing the value of AppleLanguages. It requires restarting the app before the change takes effect.
It seems that your problem is accessing the localization strings of different languages rather than changing the app's language, right? If you want your app to support multiple languages, you can just provide the translations and rely on settings.app for the actual change.
If you want to access the localization strings from other than currently used localization, you need to get access to the proper translations bundle. And then just query that bundle for the translations. The following piece of code should do the trick.
let language = "en"
let path = Bundle.main.path(forResource: language, ofType: "lproj")
let bundle = Bundle(path: path!)
let string = bundle?.localizedStringForKey("key", value: nil, table: nil)
The language changes was taken in consideration but I missed to restart the app after executing my code.
Good to know, if you want to change the language without the app restart, you do that with the aforementioned code example too. Just wrap it in a function/class and use it instead of NSLocalizedString. Though I'd recommend using the standard Apple way for changing the language.
Doesn't work for me. path is nil. It may be that I cannot access these from XCUITests ? That would suck...
@Radu I've also encountered the same problem with XCUITest, but made it work thank to Markus, see my answer below.
Friendly reminder for anyone who may have missed out, I found that it looks into Localizable.strings not Main.strings! Hope this saves someone time! Edit: I found the answer to pull from Main.strings -> let string = bundle.localizedString(forKey: "Language", value: nil, table: "Main")
It is not working for me I have created a global function to use everywhere in app.
let value: String = NSLocalizedString(key, bundle: Bundle.main, comment: comment)
debugPrint("default String value: (value)")
guard
let path: String = Bundle.main.path(forResource: "fr", ofType: "lproj"),
let bundle: Bundle = Bundle(path: path)
else { return value }
debugPrint("lang specific value: (bundle.localizedString(forKey: key, value: nil, table: nil))")
return bundle.localizedString(forKey: key, value: nil, table: "Main")
}
With NSLocalizedString you can specify the bundle.
let language = "fr"
let path = Bundle.main.path(forResource: language, ofType: "lproj")!
let bundle = Bundle(path: path)!
let localizedString = NSLocalizedString(key, bundle: bundle, comment: "")
Or with a bundle, you may also call localizedStringForKey:value:table: directly too.
I find all the other answers very helpful. However, I'd like to add a little safeguard here. For once, for the case that the requested language might not be available. And twice, for the case that we have a more complex locale identifier.
Especially in the latter case it's not as straight forward as to simply map the locale to the right lproj folder because they might not be named exactly the same way. Thus, I found it easier to leave this part up to the system. Bundle.preferredLocalizations does exactly that.
Imagine you request en-GB but your app only supports en-US or just en in this matter. Since there is no en-GB.lproj folder in the project, no bundle will be returned. However, a call to preferredLocalizations should resolve it to en.lproj. As a side note, the same is mostly true for Chinese as well (zh, zh-Hans, zh-Hant, etc.).
func localizedBundle(locale: String?) -> Bundle {
if let locale {
if let preferredLocale = Bundle.preferredLocalizations(from: Bundle.main.localizations, forPreferences: [locale]).first {
if let path = Bundle.main.path(forResource: preferredLocale, ofType: "lproj") {
if let bundle = Bundle(path: path) {
return bundle
}
}
}
}
return Bundle.main
}
Please be aware that preferredLocalizations should at least return one value, which might not necessarily match the requested locale. If you want to know if a locale cannot be resolved, you have to create two Locale objects for each, the input locale string and the returned locale string, and then compare the language tags. But this is not part of this answer here.
Call NSLocalizedString with the bundle as follows.
NSLocalizedString("key", bundle: bundle, comment: "")
By the way, if the bundle is the main bundle, then it's equivalent to calling NSLocalizedString with just the key and comment argument, so no worries.
It also makes sense to cache the bundle and not retrieving it each time before calling NSLocalizedString.
@Radu I also made this working for XCUITests thanks to @Markus' original answer :
You can specify explicitly the path to your MainBundle, it will only work on your Mac with the Simulator, but it is often used in continuous integration platforms so this might be acceptable :
let language: String = "en"
let path = "/Users/{username}/{path_to_your_project}/\(language).lproj"
let bundle = Bundle(path: path)
let string = bundle?.localizedString(forKey: "key", value: nil, table: nil)
In swift 4, I have solved it without needing to restart or use libraries.
After trying many options, I found this function, where you pass the stringToLocalize (of Localizable.String, the strings file) that you want to translate, and the language in which you want to translate it, and what it returns is the value for that String that you have in Strings file:
func localizeString (stringToLocalize: String, language: String) -> String
{
let path = Bundle.main.path (forResource: language, ofType: "lproj")
let languageBundle = Bundle (path: path!)
return languageBundle! .localizedString (forKey: stringToLocalize, value: "", table: nil)
}
Taking into account this function, I created it as global in a Swift file:
struct CustomLanguage {
func createBundlePath () -> Bundle {
let selectedLanguage = //recover the language chosen by the user (in my case, from UserDefaults)
let path = Bundle.main.path(forResource: selectedLanguage, ofType: "lproj")
return Bundle(path: path!)!
}
}
To access from the whole app, and in each string of the rest of ViewControllers, instead of putting:
NSLocalizedString ("StringToLocalize", comment: “")
I have replaced it with
let customLang = CustomLanguage() //declare at top
NSLocalizedString("StringToLocalize", tableName: nil, bundle: customLang.createBundlePath(), value: "", comment: “”) //use in each String
I do not know if it's the best way, but I found it very simple, and it works for me, I hope it helps you!
| common-pile/stackexchange_filtered |
Please make entries in "responses" link to the respones directly
When following a link in the "activity" page, you are directed to the entry directly. That is, if the activity was a comment, you directly jump to the comment.
But in the "responses" page, if you follow an entry and the entry relates to a question, you merely jump to that question and not to the response itself. (If the entry relates to an answer, then you jump to the comment itself, as expected.)
I find that behavior annoying, as it makes it difficult to directly link to a response, in particular if that response was a comment. I need to inspect the page source to find the comment-id to link to.
Seems to work for me. For a comment listed on the "responses" page, when I click on the relevant question title I'm directed straight to the comment in question. The link is like http://meta.stackexchange.com/questions/96097/question-layout-all-messed-up/96100#comment-241627
@Tomalak weird. it doesn't do that for me.
It works for me too: a link to a comment in the "responses" tab takes me to the comment, and a link to an answer takes me to that answer.
@Kiam if you go to "http://stackoverflow.com/users/34509/johannes-schaub-litb?tab=responses" and click on the comment "@Johannes: The idea of having references seems very dangerous to me, because the references will ..." or to "@Johannes: I suppose if the end iterator points to a sentinel value within the container, then the" does it take you to the comment?
@Tomalak ^^^^^^
@Johannes Schaub - litb I cannot access your "responses" tab. If I look at your account page, I see just three tabs: "stats," "bounties," and "accounts." I can only try on my account, and I cannot reproduce what you are reporting.
Actually I'm seeing the same thing @Tomalak and @kiamlaluno are seeing, the links do indeed include the #comment-xxxx pieces which link to the comment directly, so I deleted my answer.
@Daniel it appears that links to comments to questions do not include the "comment-xxxx" pieces. But only links to comments to answers do.
Related: Comment links on Responses tab do not work correctly when the comment is hidden
@Tomalak ^^^^^^^
@kiam ^^^^^^^^^^
@Johannes: Ah, yes. For comments on answers the functionality is present; for comments on questions, not. Whether the bug is that the comment anchor is missing for entries relating to questions, or that the comment rather than answer anchor is used for entries relating to answers, there is a bug here.
Hence the real complaint is about not wanting to fix it, and not wanting to handle the collapsed comments.... not really about whether the link is useful or not. If the link weren't useful, I have no real reason why it still works in some cases at all.
@Tomalak and Johannes: The comment anchor is present. I just requested that it should be used for questions, too, and found this very question only now.
| common-pile/stackexchange_filtered |
What non-symmetric matrices satisfy $x^TAx>0,\forall x\neq 0$
Let $A\in R^{n\times n}$ be a matrix. It is positive definite if and only if $A$ is symmetric and $x^TAx>0,\forall x\in R^n$.
My question is: if $x^TAx>0,\forall x\in R^n$ but $A$ is not symmetric, what does $A$ look like?
I have an example. For a rotation matrix $A$ whose rotation angle is less than 90 degrees, $x^TAx>0,\forall x\in R^n$ but $A$ is not symmetric. Is this the only type of non-symmetric matrices that satisfy $x^TAx>0,\forall x\in R^n$? Can you give any other examples of this kind of matrices? Many thanks.
There is a unique way of decomposing $A$ into the sum of a symmetric matrix $A_{+}$ and an antisymmetric matrix $A_{-}$, namely $A = (A + A^{T})/2 + (A - A^{T})/2$. Then note that $x^{T} A x = x^{T} A_{+} x$. That is, $x^{T} A x$ does not depend on the antisymmetric part $A_{-}$, so the matrix $A$ satisfying $x^{T} A x > 0$ for all $x \neq 0$ is characterized as the sum of a positive definite matrix and an antisymmetric matrix.
why not post it as an answer?
Well, it's because I think someone may find a more enlightening answer...
@sos440: Thanks for the good answer. Then $x^TAx>0, \forall x\neq 0$ if and only if $A+A^T$ is positive definite. Then a further question appears: what kind of non-symmetric $A$ has $A+A^T$ as a positive definite matrix?
Any $B+C$ with $B$ symmetric and positive definite, and $C$ anti-symmetric...
@sos440: It's the job of the voters to decide which answer is the most enlightening! :)
@Didier: I see. Thanks. @sos440: by the way, please post an answer so I can accept it. Thanks
Something related...
@J.M.: Thanks. That seems a good reference for this problem.
For the sake of having an answer, here is sos440's answer from the comments.
There is a unique way of decomposing $A$ into the sum of a symmetric matrix $A_{+}$ and an antisymmetric matrix $A_{-}$, namely $A = (A + A^{T})/2 + (A - A^{T})/2$. Then note that $x^{T} A x = x^{T} A_{+} x$. That is, $x^{T} A x$ does not depend on the antisymmetric part $A_{-}$, so the matrix $A$ satisfying $x^{T} A x > 0$ for all $x \neq 0$ is characterized as the sum of a positive definite matrix and an antisymmetric matrix.
| common-pile/stackexchange_filtered |
How to obtain the bibtex item for a question with a program or HTTP request?
Which request should my program send to mathoverflow.net to get the bibtex, which is so well hidden behind the share button?
Rephrased: what I'm after is something analogous to a link like:
adsabs.harvard.edu/cgi-bin/nph-bib_query?bibcode=2011arXiv1111.3349P&data_type=BIBTEX
which serves the bibtex for arXiv articles.
Disclaimer:
I asked the very same question also at meta.mathoverflow (Q 2262) and at Meta Stack Exchange(Q 256587), where it finally was recommended to ask it here.
The question is about the "cite" feature available on some (but not all) Stack Exchange sites, like Math Overflow, math.stackexchange, etc. This question is not about extending the feature to other sites.
Background:
The FindStat project encourages contributors to provide references for combinatorial statistics.
I am currently redesigning the way such references are processed. In future, a contributor should only type something like [[arxiv:1234.5678]] or [[MO168885]], without providing any further information. The program then will fetch author and title from the various websites. This was (relatively) easy for the arXiv, but for Math Overflow citations (which occur a lot, by nature of the site), I'm hitting a problem.
It's pretty easy to get the bibtex, just send a GET request formatted like so:
https://mathoverflow.net/posts/{POST NUMBER}/citation
For example, for this Math Overflow question, you can get the bibtex for the question and top 2 answers with:
mathoverflow.net/posts/105922/citation (Question)
mathoverflow.net/posts/105930/citation (Answer 1)
mathoverflow.net/posts/105929/citation (Answer 2)
The results are returned in a JSON object that looks like this:
{
"bibtex": "@MISC {105929,\r\n TITLE = {Von Neumann algebra associated to the infinite Cuntz algebra},\r\n AUTHOR = {Ollie Margetts (https://mathoverflow.net/users/10779/ollie-margetts)},\r\n HOWPUBLISHED = {MathOverflow},\r\n NOTE = {URL:https://mathoverflow.net/q/105929 (version: 2013-07-28)},\r\n EPRINT = {https://mathoverflow.net/q/105929},\r\n URL = {https://mathoverflow.net/q/105929}\r\n}",
"amsref": "\\bib\\{105929}{misc}{ \r\n title={Von Neumann algebra associated to the infinite Cuntz algebra}, \r\n author={Ollie Margetts (https://mathoverflow.net/users/10779/ollie-margetts)}, \r\n note={URL: https://mathoverflow.net/q/105929 (version: 2013-07-28)}, \r\n eprint={https://mathoverflow.net/q/105929}, \r\n organization={MathOverflow} \r\n}",
"example": "<p><b>Example citation:</b></p><p>Ollie Margetts (https://mathoverflow.net/users/10779/ollie-margetts), Von Neumann algebra associated to the infinite Cuntz algebra, URL (version: 2013-07-28): https://mathoverflow.net/q/105929</p>"
}
The bibtex property contains the bibtex in a formatted string. For example, the above prints out as:
@MISC {105929,
TITLE = {Von Neumann algebra associated to the infinite Cuntz algebra},
AUTHOR = {Ollie Margetts (https://mathoverflow.net/users/10779/ollie-margetts)},
HOWPUBLISHED = {MathOverflow},
NOTE = {URL:https://mathoverflow.net/q/105929 (version: 2013-07-28)},
EPRINT = {https://mathoverflow.net/q/105929},
URL = {https://mathoverflow.net/q/105929}
}
| common-pile/stackexchange_filtered |
Angularjs ui-router add parent url parameter to current state
This is my app state
.state('app', {
url: "/?:site_id",
templateUrl: "/controls/angular/templates/partial/app.html",
abstract: true
})
.state('app.popup', {
url: "popup",
templateUrl: "/controls/angular/templates/popup.html",
controller: 'PopupController'
})
The app root (that config as abstract) has parameter (site_id) that I can use in all other pages in the application.
I have drop-down list that can change the site.
How can I add the site url parameter to current page with all other parameters that exist
Just change the root site_id parameter.
var oSelect = $('#site_select_tag').select2();
oSelect.on("change", function (e) {
var curr_site_id = e.val;
$state.go to => ?????????
//scope.site_id = e.val;
scope.onChange()(e.val);
});
Are you looking to pass the parameters in $state.go ??
I don't know what the options to add single parameter to current state (with parameters), I add the "state go" just for example.
Thanks
The solution is simple
$state.go('.', {site_id: e.val})
Keep all other parameters and set the new parameter
quick and easy way. It should be the answer.
If I understand you correctly your trying to manipulate the state data after it is set up in the $stateProvider. If so you should set up your own state provider like Mean.io do
// $meanStateProvider, provider to wire up $viewPathProvider to $stateProvider
angular.module('mean.system').provider('$meanState', ['$stateProvider', '$viewPathProvider', function($stateProvider,viewPathProvider){
function MeanStateProvider() {
this.state = function(stateName, data) {
if (data.templateUrl) {
data.templateUrl = $viewPathProvider.path(data.templateUrl);
}
$stateProvider.state(stateName, data);
return this;
};
this.$get = function() {
return this;
};
}
return new MeanStateProvider();
}]);
You can pass options to the go method of $state:
$state.go(to [, toParams] [, options])
https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stategoto--toparams--options
$state.go('myState', {'myParam': myValue});
And you can set parameters on ui-sref:
ui-sref='stateName({param: value, param: value})'
https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-sref
<a ui-sref="myState({'myParam': myValue})">myLink</a>
You can access the current state as $state.current.name and the current parameters as $state.params so what you can do is this:
var params = $state.params;
params.id = 123; // Set new ID
$state.go($state.current.name, params);
But like I said I don't know what the state is and what the other parameters are.
Ok, edited my answer. Hope i understood you correctly this time.
| common-pile/stackexchange_filtered |
Eclipse won't export as a JAR
I realize similar questions have been asked, but mine seems to be unique. When I attempt to export my project as a JAR the project itself does not appear in the export window. Can anyone help me?
Also, I'm not sure if this changes anything, but I used a Java Decompiler to decompile the source, put it in a folder, and created a project with the same name as said folder to be able to edit it. As well I have asked the devs of the JAR and they said it was fine.
Does the project have an output folder? Is it an actual Java project that is compiling? Take a look at the build path and see if anything is funky.
You're missing the tell-tale "J" in the project icon that indicates it's a Java Project, which is the kind of project it expects to export as a .jar file. Without it being a real Java Project, it doesn't know what's source and where the correct root of your output is.
| common-pile/stackexchange_filtered |
use of undeclared identifier 'git_diff_perfdata' with libgit2
I'm trying to write some code that uses git_diff_perfdata from the Libgit2 library.
git_diff_perfdata s;
However, when compiling on my Mac I get the error:
use of undeclared identifier 'git_diff_perfdata'
My understanding is that Libgit2 is meant to be used exclusively through the inclusion of git2.h. Is that correct?
git_diff_perfdata is defined in sys/diff.h and used in status.h
Should I be including sys/diff.h directly. If so, why? Alternatively, what errors might I be making? Looking at the header code I'm unable to see how sys/diff.h is included through anything that is included by git2.h.
Additionally, from what I can tell git_diff_perfdata isn't meant to be an opaque data type (i.e. only the pointer is defined).
I'm using the code downloaded from:
https://github.com/libgit2/libgit2/archive/v0.26.0.zip
The headers in sys are part of the public API, but they're a bit lower level. You can think of them as internal implementation details that have been made public because they might be useful to application developers. If you want to use them, include them directly.
| common-pile/stackexchange_filtered |
Angular 4 unexpected end of json in service get
I' m getting unexpected end of JSON error when i use this code in the service to get a client:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable()
export class ClientsService {
constructor(private http: Http) {
}
getClient(clientId: number): Observable<any> {
return this.http.get(`/api/client/getbyid/` + clientId)
.map((res: Response) => res.json());
}
}
when i modify this code, that error dissappears.
getClient(clientId: number) {
return this.http.get(`/api/client/getbyid/` + clientId)
.map((res: Response) => res);
}
I don't understand why the error happens in the first case but not in the second. Why does it behaves like that ?
Because in the first case, you try to parse the body as JSON, whereas you don't in the second case.
If you are using HttpClient (which was introduced in angular 4.3), then now by default response is serialized to json. Since HttpClient depends on Content-Type in reponse headers.
| common-pile/stackexchange_filtered |
Check if the given time is between two times (Hour,Minute) format
I have next 6 fields in MySQL.
TIME_RIGHT_NOW_HOUR (INT)
TIME_RIGHT_NOW_MINUTE (INT)
TIME_WORKING_FROM_HOUR (INT)
TIME_WORKING_FROM_MINUTE (INT)
TIME_WORKING_TO_HOUR (INT)
TIME_WORKING_TO_MINUTE (INT)
Hour and minutes are in 24 time format.
I need to check is the right now time between two working times.
for example if TIME_RIGHT_NOW_HOUR is 15 and TIME_RIGHT_NOW_MINUTE is 30 -> 15:30
is it between TIME_WORKING_FROM_HOUR 10, TIME_WORKING_FROM_MINUTE 15
10:15 and TIME_WORKING_TO_HOUR 18, TIME_WORKING_TO_MINUTE 20 -> 18:20
Perhaps maketime() is what you are seeking.
SELECT 1
FROM table
WHERE
MAKETIME(TIME_RIGHT_NOW_HOUR,TIME_RIGHT_NOW_MINUTE,0)
BETWEEN MAKETIME(TIME_WORKING_FROM_HOUR,TIME_WORKING_FROM_MINUTE,0)
AND MAKETIME(TIME_WORKING_TO_HOUR,TIME_WORKING_TO_MINUTE,0);
This is ok. But when i put work time from 23:00 to 5:00 and right now time to 3:00 it is not showing result can i solve this somehow?
Add in the date. In your application, you can specify the date and time of the work as individual fields, but then before inserting it into the database do some manipulations of those values to create a datestring (2013-11-27 23:00:00), and store that in a single column as a timestamp. That way, you don't even need MAKETIME(), and can simply do NOW() BETWEEN TIME_WORKING_FROM AND TIME_WORKING_TO
You can solve this by observing that if the start time is greater than the stop time, the test results are reversed. So, since 3 is not between 5 and 23, and 23 is more than 5, then 03:00 is between 23:00 and 05:00; and is not between 05:00 and 23:00. See my answer for the test.
Very easy solution: Convert hour&time to float then compare:
TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100 -----> 10.15
TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100; ------> 18.20
TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100; ------> 15.30
SQL WHERE:
WHERE ( (TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100) <= (TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100) )
AND ( (TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100) >= (TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100) )
Solution of @Ian Schoonover is good but it only work for MySQL. My solution can work with ALL SQL databases.
yes but still i have a problem when working time is 23:00 -> 5:00
@Vuk Vasić: See my new another answer and let me know your result.
You can use XOR (or the IF function), in order to cope with midnight rolling (i.e., FROM is 22:00, TO is 06:00, and the question is "is 23:30 inside or outside this period?", which mathematically is outside, but clock-wise is inside).
SELECT
( TIME_WORKING_FROM_HOUR*60+TIME_WORKING_FROM_MINUTE <
TIME_WORKING_TO_HOUR*60+TIME_WORKING_TO_MINUTE )
XOR NOT
(
TIME_RIGHT_NOW_HOUR*60+TIME_RIGHT_NOW_MINUTE BETWEEN
TIME_WORKING_FROM_HOUR*60+TIME_WORKING_FROM_MINUTE
AND
TIME_WORKING_TO_HOUR*60+TIME_WORKING_TO_MINUTE
)
Test
CREATE TABLE test ( TIME_RIGHT_NOW_HOUR integer, TIME_RIGHT_NOW_MINUTE integer,
TIME_WORKING_FROM_HOUR integer, TIME_WORKING_FROM_MINUTE integer,
TIME_WORKING_TO_HOUR integer, TIME_WORKING_TO_MINUTE integer );
INSERT INTO test VALUES
( 7, 30, 8, 00, 17, 00 ),
( 12, 30, 8, 00, 17, 00 ),
( 4, 30, 22, 00, 06, 00 ),
( 0, 0, 22, 00, 06, 00 ),
( 22, 0, 6, 0, 6, 5 );
SELECT TIME_WORKING_FROM_HOUR AS FROM_H,
TIME_WORKING_FROM_MINUTE AS FROM_M,
TIME_WORKING_TO_HOUR AS TO_H,
TIME_WORKING_TO_MINUTE AS TO_M,
TIME_RIGHT_NOW_HOUR AS NOW_H,
TIME_RIGHT_NOW_MINUTE AS NOW_M,
( TIME_WORKING_FROM_HOUR*60+TIME_WORKING_FROM_MINUTE <
TIME_WORKING_TO_HOUR*60+TIME_WORKING_TO_MINUTE )
XOR NOT
(
TIME_RIGHT_NOW_HOUR*60+TIME_RIGHT_NOW_MINUTE BETWEEN
TIME_WORKING_FROM_HOUR*60+TIME_WORKING_FROM_MINUTE
AND
TIME_WORKING_TO_HOUR*60+TIME_WORKING_TO_MINUTE
) AS in_orario FROM test;
Result:
+--------+--------+------+------+-------+-------+-----------+
| FROM_H | FROM_M | TO_H | TO_M | NOW_H | NOW_M | in_orario |
+--------+--------+------+------+-------+-------+-----------+
| 8 | 0 | 17 | 0 | 7 | 30 | 0 |
| 8 | 0 | 17 | 0 | 12 | 30 | 1 |
| 22 | 0 | 6 | 0 | 4 | 30 | 1 |
| 22 | 0 | 6 | 0 | 0 | 0 | 1 |
| 6 | 0 | 6 | 5 | 22 | 0 | 0 |
+--------+--------+------+------+-------+-------+-----------+
5 rows in set (0.00 sec)
In this SQLfiddle, the condition has been moved into the WHERE.
This will work for both 5:00 -> 23:00 and 23:00 -> 5:00 ( NEXT day)
WHERE
(
-- CASE: 5:00 -> 23:00
(
TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100.00 < TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100.00
)
AND
(
(
TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100.00 <= TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100.00
)
AND
(
TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100.00 >= TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100.00
)
)
)
OR
(
-- CASE: 23:00 -> 5:00 of Next day
(
TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100.00 >= TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100.00
)
AND
(
(
TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100.00 >= TIME_WORKING_FROM_HOUR + TIME_WORKING_FROM_MINUTE / 100.00
)
OR
(
TIME_RIGHT_NOW_HOUR + TIME_RIGHT_NOW_MINUTE / 100.00 <= TIME_WORKING_TO_HOUR + TIME_WORKING_TO_MINUTE / 100.00
)
)
)
@Lserni: I have 2 statements. The first one is for FROM < TO and second one is for FROM > TO (of NEXT day). I believe it works.
Yes, now it does. I've prepared a SQLfiddle for it: http://sqlfiddle.com/#!2/d7768/1
@lserni: Thanks for your test. Please check My answer is correct.
I did; it is (sorry. Forgot to upvote). There are three "inside" rows in my test data, and your answer now fetches all three, and none of the others (before, I believe you had an OR instead of an AND in your code).
| common-pile/stackexchange_filtered |
Redirection to another tab from within a tab fails in Microsoft Teams
I have installed an app in a tab and wanted to redirect to another tab.
The url of the tab is of the form https://teams.microsoft.com/l/channel/<entityId>/<tabId>?label=Wiki&groupId=<groupId>&tenantId=<tenantId>
For doing this I have tried the following -
window.location.href= url //Tabs Url
When viewing the console, I see a mixed content error saying that msteams is being accessed from https page. This is inspte of the fact that I am redirecting to a https url. Also, no redirection.
microsoftTeams.navigateCrossDomain(url);
Shows in the console that this method is deprecated but nothing on the documentation page and no redirection.
microsoftTeams.navigateToTab(tabName...)
No error or any redirection
1. What should I change for redirection to be successful?
2. What is the proper way to do this?
Edit 1:
The link that I have posted in the question is a deep link.
The problem does not lie in redirection. I can directly enter the url in the address bar and get redirected to the tab. The issue lies with getting this screen.
It appears even when I am within Teams desktop app and no redirection takes place after that. If I do the same process via the Teams web app, I can open the console and see a mixed content warning error that a https page is trying to call a msteams url.
When I directly enter this url in browser, even though this screen appears my teams app is able to display the channel.
Note -
navigateCrossDomain does not redirect instead prints to console that it is deprecated.
navigateToTab also does not seem to do anything as it is not printing any error in console nor is it performing any redirection.
Edit 2 -
I tried opening the Teams web app in Edge and it's able to redirect properly using window.location.href.
What doesn't work
Redirecting inside Teams desktop app
Redirecting in Teams web app in Chrome
Redirecting using navigateCrossDomain()
Could you please try generating a deep link to your tab?
I have updated the question to reflect that the problem is not with the link.
Redirection to another tab only works when I open the teams app in Edge and then redirect which opens my team app with the new channel. No other browser will work.
There are two options to navigate to another channel tab:
Create a tab deep link and provide hyper link with target="_blank". This would open up the link in browser first and then take you to channel tab.
Get Tab details using getTabInstances() and use navigateToTab() to perform navigation. Note: This method takes TabInstance as parameter.
I can confirm that hyperlink works but simply setting window.location to url doesn't. I can simulate a hyperlink click on page load but is there any other way to redirect on page load??
How about navigateToTab() option?
| common-pile/stackexchange_filtered |
Centroid of a non-polygonal concave shape determined by an equilateral triangle an its incircle
I have a diagram here of an equilateral triangle ABC, centre O, where circle centre O has tangents which are all three sides of the triangle ABC. M is the midpoint of AB, and F is the intersection of arc DE and line MC. I know each coordinate of the triangle, and the triangle has edges of length 1.
I need to calculate the centroid of the shape CDE, where the DE vertex is the arc passing through point F. I understand the centroid will be along the line CM, because the shape is symmetrical. I have no idea how to find the exact point though. One thought is that it's the midpoint of line FC, and another thought is
that it's the midpoint of the perpendicular bisector of line DE through C.
Are any of these presumptions right? Or is there no way of working out the centroid of it without actually having it in real life and using a plumbline?
We can do this using calculus.
Coordinatize by placing the center of the circle, of radius $r$, at the origin. Generalizing slightly, I'll take $\angle COE = \theta$ instead of specifically $\pi/3$; thus,
$$C = r(0,\sec\theta) \qquad D = r(-\sin\theta,\cos\theta) \qquad E = r(\sin\theta,\cos\theta)$$
As OP notes, the centroid of region $CDFE$ lies on $\overline{CM}$, so its $x$-coordinate is $0$. One sees that the $y$-coordinate of that centroid must match that of the half-region $CFE$, which is bounded by $\overleftrightarrow{CE}$ ($f(x) = - x \tan\theta + r \sec\theta$) and the circle ($g(x) = \sqrt{r^2-x^2}$).
By the formula for the centroid of a bounded region,
$$\begin{align}
\bar{y} \cdot (\text{area}\;CFE) &= \frac12\int_{0}^{r\sin\theta}f(x)^2 - g(x)^2 \;dx \tag{1a}\\[4pt]
&= \frac12\int_{0}^{r\sin\theta}( x^2\tan^2\theta - 2 r x\tan\theta\sec\theta + r^2\sec^2\theta) - (r^2-x^2) \;dx \tag{1b}\\[4pt]
&= \frac1{2\cos^2\theta}\int_{0}^{r\sin\theta} x^2\sin^2\theta - 2 r x\sin\theta + r^2 - r^2\cos^2\theta + x^2\cos^2\theta) \;dx \tag{1b}\\[4pt]
&= \frac1{2\cos^2\theta}\int_{0}^{r\sin\theta} x^2 - 2 r x\sin\theta + r^2\sin^2\theta \;dx \tag{1c}\\[4pt]
&= \frac1{2\cos^2\theta}\int_{0}^{r\sin\theta} \left( x - r\sin\theta\right)^2 \;dx \tag{1d}\\[4pt]
&= \left.\frac1{6\cos^2\theta} \left( x - r\sin\theta \right)^3\;\right|_{0}^{r\sin\theta} \tag{1e}\\[4pt]
&= \frac{r^3\sin^3\theta}{6\cos^2\theta} \tag{1f}
\end{align}$$
(Note: We could get from $(1a)$ to $(1d)$ fairly immediately by observing that $f(x)^2-g(x)^2$ gives the "power", with respect to the circle, of a variable point along $\overline{CE}$. But I digress ...) Then, since
$$\begin{align}
\text{area}\;CFE &= \text{area of }\; \triangle COE - \text{area of sector}\;FOE \tag{2a}\\[4pt]
&= \frac12 \cdot r \cdot r\tan\theta - \frac12 r^2 \cdot \theta \tag{2b}\\[4pt]
&= \frac12 r^2 (\tan\theta - \theta) \tag{2c}
\end{align}$$
we have
$$\bar{y} = \frac{r\sin^3\theta}{3\cos\theta(\sin\theta-\theta \cos\theta)} \qquad\stackrel{\theta=\pi/3}{\to}\qquad
\frac{3r\sqrt{3}}{2(3\sqrt{3} -\pi)} = r\cdot 1.26454\ldots
\tag{$\star$}$$
Alternatively, we can use geometric decomposition.
Writing $\bar{p}$ for the $y$-coordinate of the centroid of $\triangle DCE$ and $\bar{q}$ for the $y$-coordinate of the centroid of sector $DFE$, we have
$$\bar{y} \cdot(\text{area} \;CDFE) = \bar{p}\cdot (\text{area}\; \triangle DCE) - \bar{q}\cdot (\text{area}\; DFE) \tag{3}$$
We "know" that a triangle's centroid is $1/3$ of the way up along a median, and its area is $1/2$-base-times-height, so
$$\begin{align}
\bar{p} \cdot (\text{area}\;DCE) &= \left( r\cos\theta + \frac13 r ( \sec\theta - \cos\theta ) \right) \cdot \frac12 \cdot 2r\sin\theta \cdot r(\sec\theta - \cos\theta) \tag{4a}\\
&= \frac{r \sin^3\theta}{3 \cos^2\theta} \left( 1 + 2 \cos^2\theta\right) \tag{4b}
\end{align}$$
Consulting a convenient list of centroids, we find
$$\bar{q}\cdot(\text{area}\;DFE) = \frac{4 r \sin^3 \theta}{3(2\theta - \sin 2\theta)}\cdot \frac{r^2}{2}(2\theta-\sin 2\theta) = \frac23 r^3 \sin^3 \theta \tag{5}$$
So, the right-hand side of $(3)$ is $(4b)-(5)$, which reduces to twice the value of $(1f)$. Since the area of $CDFE$ is likewise twice the value in $(2c)$, the "twice"s cancel, and $(3)$ yields the result shown in $(\star)$. $\square$
Looks great - really appreciate the time and effort you put into this. I'm going through it now and I'm confused how you deduced the equation of the line through C and E, f(x). I feel like it'll be obvious when you explain it but I'm having a mental-block right now!
Actually don't worry - after manipulating the unit circle around I figured why the equation is that :)
The centroid is $.3650417045$ from point O. I figured it out by determining the centroid $C_k$ of the kite CDOE and the centroid $C_s$ of sector ODFE and by subtracting moments using areas was able to determine the centroid of CDFE.
| common-pile/stackexchange_filtered |
Percent in url next js
I want to create an url using:
const click = () => {
router.push(
{
pathname:`/cars?{color}${doors}$`,
},
undefined,
{
shallow: true,
},
);
When i hit the button which trigger the function i get in url: /cars%3Fcolor=red&doors=5. How to create this url: /cars?color=red&doors=5,?
Does this answer your question? How to handle % and # characters with next-routes
A query string cannot be part of a pathname. The ? delimits the query string from the pathname; if a pathname were to contain a ?, it would be encoded as %3F. This is why you're seeing this result.
Try this instead:
router.push(
{
pathname: '/cars',
query: { color, doors },
},
// ...
)
anyway in the url appears others signs that shouldn't be there, like %26, i want to get something like this: /cars?color=red&doors=5, just simple signs not encoded url, do you know jow?
That's just the URL encoding of &, which is probably also due to not properly separating pathname from query string. Can you confirm if the solution I posted is failing?
yes it doesn't give the wanted result. Do you know an alternative?
could you help please with this? https://stackoverflow.com/questions/66410826/get-accesstoken-in-auth0. It will help a lot
| common-pile/stackexchange_filtered |
Best practices for bringing in content from other sites?
This answer features a bunch of blockquotes, with text that came copy-pasted from another website. The text was presented with a link back to the original material, but something about it just doesn't seem in line with what is expected on this site.
It's certainly a good idea to keep the relevant information contained within this site, so that the question does not become unexpectedly unanswered when URLs become invalid. On the other hand, is blockquoting the best option in terms of respecting copyright, preserving the data, and writing a well-formed answer?
Link-only answers, even if the content is blockquoted, are discouraged.
It's usually better to link and paraphrase an external webpage. If you really want to blockquote it, then you should:
Sum it up in your own words
Possibly have some addenda
Generally, the webpage doesn't really answer the exact same question, so you can write a "wrapper" for the blockquote, that fits it into the question.
In this particular case, I think it's OK, but I would prefer if there was more of his own text.
I agree that the blockquotes are rather extensive in this particular example, but they should still be covered under fair use (I'm guessing US jurisdiction applies to SE sites), if that's what you're mainly worried about.
@embedded.kyle did sum up the content from those two quotes, so he's technically done the "right thing". But I agree that his answer could have done with a lot less text, mostly because the quotes didn't add much detail to his recap of them.
It's a bit of a balancing act because we also discourage link-only answers. In general, it's probably best to sum up a source but provide a link to it and quote only where it substantially improves the answer
I guess the followup question is: if we edit the text that's blockquoted, at what point can we unquote it?
The answer did appear to be a copy of the entirety of the significant content of the web page linked to. I don't think that would be considered fair use.
What do you think is the best way to improve that answer so it's not an infringement (or so that it's more appropriate for the style of this site)?
I don't think it would be considered infringement, not that I have any expertise on the matter whatsoever but, as far as I understand it, he only quotes relevant bits. Both original articles are a lot longer. That said, I'm not happy with the answer either. I'd say, the HowStuffWorks bit is fine, since he's summing it up and just quoting it to give a reference. So the same should probably be done with the interview. Also, on a quick glance, I'd skip the quotes and only read the OP's bits, which at the moment would leave out a lot of detail.
Tricky one...
StackExchange is always fighting other sites that blatantly rip-off SE content... so it would be hypercritical for SE sites to rip-off other site's (and even sites' before I get hauled before the EL&U crew) content.
Also, there was a case a few years back (IIRC it got to the High Court, in the UK) about one new-site copying content from another, even with attribution!
Having said that, small quotes, with correct attribution is usually considered OK under fair use (IMHO bit IANAL)
A SE answer should be a proper researched answer... copying and pasting someone else's work is rarely such, and the answerer may not fully understand what they are posting. I suppose the correct approach would be to contact the other website BEFORE POSTING for permission to use their content... maybe then the original author maybe able to answer the question better than anyone else? Although that is not often practical or realistic!
At the end of the day, common sense should be the guideline... both by the poster, us the community, and ultimately the moderators. I'm sure I'm as guilty as others in quoting...
If a website doesn't grant you rights to reuse it's content then you are technically violating copyright to re-use that content elsewhere. Doing this might have consequences, both direct and indirect.
In the worse case, a site like How Stuff Works could ask Stack Exchange to remove infringing content.
At the other end of the scale, contributors might just get annoyed with a site which hosts infringing content and refuse to promote or support it. This could potentially lose us some valuable contributors, if their first interaction with our site is someone ripping off their work.
In most coses, linking to the original site (providing attribution) and only quoting portions (fair use in some countries, including the US where stack exchange is hosted) of the linked to page which are needed to answer the question should be sufficient. Wholesale copying of the entire (significant) content of a page on another site really should be discouraged though.
As an aside, one of the main reasons I stick to quoting from Wikipedia is that their content license is compatible with the license of content here on stack exchange:
Wikipedia: Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. See Terms of Use for details. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.
Stack exchange sites: site design / logo © 2012 stack exchange inc; user contributions licensed under cc-wiki with attribution required
Due to DMCA and all that, it's fine if you post it, SE only has to take action if a DMCA notice is filed with them. So there are no consequences, really. But it's better to avoid the matter entirely :)
@Manishearth - The point I was trying to make was that there are potential non DMCA consequences of using copyrighted material, such as annoying and thus driving away the very same expert roboticists we need to make this site the best it can be. Thus encouraging link and summarise is this a much better policy than encouraging link and plagiarise.
Of course; just pointing out that there are no legal consequences :)
@Manishearth - Although unlikely, a DCMA takedown notice is a legal consequence. It is backed by law and in theory, a failure to act on it could (technically) lead to legal action. Anyway, we should continue this in [chat] if necessary.
| common-pile/stackexchange_filtered |
Need a SQL statement to filter rows
There is a table which look like this:
I need to retrieve only highlighted records. And I need a query which should work on bigger table where are millions of records are exists.
Criteria:
There are 4 sets, 1st and 3rd have the similar values but 2nd and 4th sets have different values
Edit:
I made slight modification in the table( ID column added). How can we achieve the same with the ID column?
Nice. And I want a new Mac book, but without showing effort no one will buy it for me.
Won't select cola,colb from table where cola in (2,4) work
What is the criteria for a row to be highlighted?
Not able to see image due to firewall. See this for more details as it does not only apply to code: https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557
Dear @Deepak Either you need very basic understanding of SQL. here people come up with much bigger issues than this one which can be solved by an entry level programmer. Your requirement too is not understandable that the records would only have this pattern or there may be varied, So be clear about the things you want and try it yourself. If it seems complex then put it here with a brief explanation as the people here are coders not Ginnie who can assume of all your million rows. And this would also save you from disaster. Thanks
@TheGameiswar if there are millions of rows how will u find them?
@Richard you see there are 4 sets, 1st and 3rd have the similar values but 2nd and 4th sets have different values
Thats right,i think Richard asked the right question
@MaulikModi I have some knowledge about SQL. The real table much complex and bigger, I made this for the simplicity, I just need to element this pattern of records
This would have been a great question,if you could have explained the criteria first
@Deepak But what we need is pattern dude. What can be pattern here? Tell us the pattern
OK, what makes the 1st and 3rd sets different to the 2nd and 4th? (I can see a pattern – see TheGameiswar's comment – but is that all the pattern that there is in just a example of the data?)
@MaulikModi check first 3 rows, 3 of them are duplicates, then row 4 to 6 colB has two different values, I need to return only this kind of set where 1 or more different value exists in the set
return only this kind of set where 1 or more different value exists in the set
create table #ab
(
col1a int,
colb char(2)
)
insert into #ab
values
(1,'a'),
(1,'a'),
(1,'a'),
(2,'b'),
(2,'c'),
(2,'c')
select id,col1a,colb
from #ab
where col1a in (
Select col1a from #ab group by col1a having count (distinct colb)>1)
Regarding the performance over millions of rows,i would probably check the execution plan and deal with it.with my sample data set and my query ,Distinct sort takes nearly 40% of cost..with millions of rows,it can probably go to tempdb as well..so i suggest below index which can eliminate more rows
create index nci on #ab(colb)
include(col1a)
Glad it helped you,if you could post DDL,DML(test data like the one in my answer) and expected result as text along with explanation and what you have tried.. you will get much faster results
No I don't want to create index on existing table, I just need to select this kind of rows
can we do the same when id column also exists in the table. Please check above edit.
You can also achieve it using INNER JOIN instead of IN as it is million rows query.
SELECT f.colA,f.colB
FROM
filtertable f
INNER JOIN
(
SELECT colA
FROM filtertable
GROUP BY colA
HAVING COUNT(DISTINCT colB)>1
) f1
ON f.colA = f1.colA
| common-pile/stackexchange_filtered |
Why there are 65520 dnp3 source addresses instead of 65536?
DNP3 link-layer source and destination addresses are 16 bits each. It means it can have 2^16 = 65536 total different addresses. Based on official DNP3 docs, there are 65536 destination addresses, which I understand. But there are only 65520 source addresses, why is that? What are other remaining 16 addresses for?
On what I said above, you can read from any dnp3 docs or this link also works: https://www.ixiacom.com/company/blog/scada-distributed-network-protocol-dnp3
I'm not familiar with DNP3, but I found a specification for a DNP3 link layer protocol implementation at https://library.e.abb.com/public/06e4e2267fd04c3884515a0360210068/1MRK511380-UUS_-_en_Point_list_manual__DNP_650_series_2.1.pdf. See page 36:
1.4.1 Data Link Address: Indicates if the link address is configurable over the entire valid range of 0 to 65,519. Data link addresses 0xFFF0 through
0xFFFF are reserved for broadcast or other special purposes.
While the source doesn't indicate what these 16 addresses are reserved for (possibly as a precaution for future needs), it does indicate that they are reserved.
thank you. Yes they are reserved, but I don't know what are some use cases for what these reserved addresses have been used.
Many protocols reserve addresses, flags, bits.. and fact is for plenty of them you never know until you need them :)
| common-pile/stackexchange_filtered |
how to make layout to be in front? androidstudio
<LinearLayout
android:id="@+id/toplayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintBottom_toTopOf="@id/filterlayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="@+id/menulayout"
android:layout_width="65dp"
android:layout_height="50dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="15dp"
android:background="@drawable/formenulayout"
android:elevation="10dp"
android:orientation="vertical"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
>
<ImageButton
android:id="@+id/menu"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center"
android:backgroundTint="@color/white"
app:srcCompat="@drawable/menu_button" />
<ImageButton
android:id="@+id/settings"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center"
android:layout_marginTop="2dp"
android:background="@drawable/gear"
android:visibility="gone"
app:useMaterialThemeColors="false" />
</LinearLayout>
<com.google.android.material.card.MaterialCardView
android:id="@+id/materialCardView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
app:cardCornerRadius="12dp"
app:cardElevation="8dp"
app:cardUseCompatPadding="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/menulayout"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:iconifiedByDefault="false"
app:layout_constraintStart_toStartOf="@id/menulayout"
app:queryBackground="@android:color/transparent"
app:queryHint="Search here" />
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
Hello, this is my code for my mainacitivty. when i press menu imageButton the menulayout increases in height and it works perfectly except the problem is that becuase menulayout increases in height it causes the toplayout to increase in height as well that i dont want it to do.
how can i make it so when the height is increased for menulayout it will be in front of everything and the top layout stays the same.
instead of wrap content try match_parent
Hello, that will not work because now the layout will be on the whole screen. my xml contains the top layout than in the middle its filter layout that will be visible or gone depends if the button is clicked or not and than at the bottom a recycler view. so making match parent wont work.
if you don't want it to be on whole screen , still don't want to resize , set a constant height
if i set constant height then the expanded part of the menulayout is being cut
i want that expanded part to go over the toplayout, elevation does not work.
You trying something like z-index,
check this https://stackoverflow.com/questions/4182486/placing-overlappingz-index-a-view-above-another-view-in-android
also tell me if anything work, thanks
i tried framelayout and relativelayout but it still does not work, the expanded part being cut because of other layouts
Have you tried the SetZ()
Unless you've a well explained answer that isn't one liner, you could have put it as a comment
SetZ() is inside the above link I commented
| common-pile/stackexchange_filtered |
How to checkout to a different branch in submodules?
We are have 2 rails projects for which /models are common for both of the projects and so we maintained a separate repo by using submodules concept.
Now in project1 I created a branch rails3_upgrade from master for my submodules i.e., in app/models.
how can I checkout to that branch in project2 models from master?
I tried get fetch --all and git remote -v and some other options but couldn't see the branch I created.
Googled but couldn't find. Can anyone tell me how can I do this?
in this case, you can do pull request for project2
Possible duplicate of Git submodules: Specify a branch/tag
A branch created in a parent repo project1 won't be visible by other repos (submodules or project2)
You can create that branch in a submodule of Project1, and see it in the same submodule in project2
cd /path/to/project1/submodule1
git checkout -b newBranch
git push -u origin newBranch
cd /path/to/project2/submodule1
git fetch
git checkout newBranch --track origin/newBranch
As usual, is you make any modification in a submodule, don't forget to add and commit in the parent repo as well.
Creating a branch in a submodule does not mean the submodule will always checkout the latest of that branch though.
For that, see "Git submodules: Specify a branch/tag" I wrote before.
And for the submodule to update itself to the latest of that branch, you would need a
git submodule update --recursive
HI, I created a branch in my submodule only in Project1. I mean my app/models are submodules for both Project1 and Project2. So in Project1 I moved to app/models and from master I created a branch new_branch.
After that I went to Project2 app/models and I tried to checkout to the branch which I created in Project1 app/models(new_branch).
@Thisisme OK, but did you push the branch you created in project1/app/models? Because app/model is its own git repo, and the same git repo in project2 will need to fetch that branch before being able to checkout it.
Yes I pushed and I can see the branch in the github repo as well. I have lot of commits in that branch as well.
@Thisisme So what is your question? What is the problem? Are you able or not to see that same branch and commits in your same submodule in project2?
Yes, am not able to see the branch in project2
@This project2 would not see a branch created in another repo. Only Project2/app/model would see that branch
| common-pile/stackexchange_filtered |
What's Flow State, and what does it mean to the SE community?
I recently became aware that Stack Exchange is running a conference called Flow State. The banner on Stack Overflow says:
Register to virtually attend our inaugural conference focused on our products, with relevant content for all developers everywhere.
A cursory look at MSO, and well I'm an MSE mod so, a less cursory look at MSE shows that there's literally no mention of this apart from the blog. Stack's supposed to be a little more knowledge worker centric than purely dev centric but consider how this post on Joel Spolsky's blog about the 2009 edition - it talks about specific things and what would be interesting to the target audience of the time, and what's essentially the elevator pitch for that is on tech crunch. I'm wondering what's the equivalent for this as far as the community or non specifically invited folks are concerned?
From the looks of the thing, and the language used and some of the FAQs, it's almost like it's felt like the community is an afterthought. In many cases, these would be the folks who'd be the subject matter experts in these tools should they be adopted.
From the Flow State FAQ:
I’m a Stack Overflow public community member. Can I attend?
We love interacting with members of the community! You are welcome to
register and attend our virtual live stream. Keep in mind that the
presentations at this event will center around challenges and
solutions for large-scale organizations and not our public platform.
Product presentations will specifically focus on Stack Overflow paid
products and features.
Will there be a Stack Overflow community event?
Nothing is currently scheduled, but we are always looking for new and
exciting ways to engage with the community.
Feels like it's more designed around 'management' sorts who might not be familiar with the network sites, SO included. This also seems at odds with "relevant content with all developers". I'm going to assume the 'invited' guests, virtual or physical would know what it is about, but what's the specific intended audience, and the pitch for this?
Even virtually - What would be the 'benefit' of someone who's a public Q&A user, and a non decision making knowledge worker to keep up with events of the conference and what would be relevant for us?
If it's primarily focused on business - are there any plans for community centric events?
From reading the short description I'd assume that this is mostly a sales pitch for Teams.
Just quoting this: "For additional information, feel free to contact us at<EMAIL_ADDRESS>
Make sure to read the Agenda, there are hints about what's going to take place, and the link to it isn't very obvious. (Top right of the screen, where we usually expect to see something else)
@RandomPerson sure, but since it's SE-related, we can and better ask here as well.
@RandomPerson sure - if you were an individual interested in the conference. I'm more asking this cause, well there's a general lack of communication with the community about this, and its not about communication with "me" but rather well, everyone here or MSO, depending.
I just found it frustrating that it states it has relevant content for all devs everywhere, when after digging in more it's... well, not that at all. Seemingly more of the same stretching of the truth to present a convenient message. I don't have a problem with this event occurring or it being about what it's about, or even being informed of it via a banner.. just get the messaging fixed before stuff like this goes out.
By the way, the psychological concept of flow state ("a person performing some activity is fully immersed in a feeling of energized focus, full involvement, and enjoyment in the process of the activity") was popularized by Mihaly Csikszentmihalyi; see e.g. the TED talk, Flow, the secret to happiness.
| common-pile/stackexchange_filtered |
How to apply data into useState constant?
I was trying to set a value to a input, and I usead setState to update the value of the Input, but now I cant use the variable I was going to use in the Value inside Input.
This is the Input
<input
type="text"
className="mt-1 focus:ring-indigo-500 focus:border-[#604d9b] block w-full shadow-sm sm:text-sm border-gray-300 rounded-md"
value={name}
placeholder="Type any name you want"
onChange={(e) => setName(e.target.value)}
/>
and this is my hook.
const [name, setName] = useState('');
Now, I want to apply this variable but I cant do it directly to the constant inside the useState
userData[0]?.name;
Anyone knows how to apply my
userData[0]?.name;
Into
const [name, setName] = useState('');
Hey you want to set userData[0]?.name in the name hook? onChange of input or initial value?...can you reframe you question it is not clear what exactly you want.
You can use useEffect to handle this kind of problems:
useEffect(() => {
if(userData[0]?.name){
setName(userData[0]?.name)
}
},[userData])
Thank you, it worked, I will try to study useEffect
@Nathan Your welcome, for sure useEffect function is a very important topic in React world.
It sounds like you're trying to set the initial value for your name state.
If this is the case, you can simply pass it as an argument to useState:
const [name, setName] = useState(userData[0]?.name || '');
| common-pile/stackexchange_filtered |
qt pyside - qsql*model, qabstractitemmodel and qtreeview interaction
I want to produce a simple enough application which uses a QTreeView widget to show hierarchical data from a SQLite3 (flat) table, use QDataWidgetMapper to populate some lineedit fields, allow user to edit, which in turn updates the table. Simple & basic (for most!).
I have been working on the basis that the following process would be the best way of doing this:
Connect to Dbase
Query data
Create and populate custom QAbstractItemModel from the data (manipulating it through a dict to create nodes, parents and children dynamically - for each dict entry a 'node' is generated with an associated parent)
Use QDatawidgetmapper to populate other widgets
User edits data
QAbstractItemModel (QAIM) is updated
Then have to run an UPDATE, INSERT or whatever query using new values in the QAIM model.
Refresh the QAIM and associated widgets.
I realise if I were just using a QTableView or QListView I would not need the custom model and could just write straight back into the database. The process I have outlined above seems to mean having to keep two sets of data going - i.e. the SQLite table and the custom QAIM and ensure that they are both kept up to date. This seems a bit cumbersome to me and I'm sure there must be a better way of doing it where the QTreeView is taking its data straight from the SQLite table - with the obvious need for some manipulation to convert the flat data into hierarchical data.
I am wondering, of course, whether I have completely misunderstood the relationship between QAbstractItemModel and the QSQL*Models and I am overcomplicating it through ignorance?
Thanks
what format have your hierarchical data? i usually use headers and lines (invoices for example) but they use a model every one.
for (relative) simplicity I am currently just using a single table with a 'parent' column. This indicates which node/record the child should be appended to.
well without take a look at the concrete data i can't say for sure you should store it in other way but the chances that store parents and childs in the same table would be a good idea are small, i have one case in production though, anyway i think you will have to stick with your idea of maintain your model and SQL in sync, Qt don't have to begin with a perfect support for editing SQL tables, i have created a QSqlQueryModel subclass to have a better QSqlTableModel, maybe you could do the same too, but if you only are going to use one time, i don't recommend you to do it, would much more work.
What you want is a proxy model that acts as a bridge between QSql*Model and the view. For that, you need to subclass QAbstractProxyModel. You have to have a consistent way of finding parent-child relationships in proxy model and mapping them to the source model, so that might require keeping some tally in the proxy model.
When you are sub-classing QAbstractProxyModel, you need to re-define, at minimum, these methods:
rowCount
columnCount
parent
index
data
mapToSource
mapFromSource
Also, keep in mind that QAbstractProxyModel does not auto-propagate signals through. So, in order to have the view be aware of changes in source model (like insert, delete, update), you need to pass them in the proxy model (while of course, updating your mappings in the proxy model).
It will require some work, but in the end you'll have a more flexible structure. And it will eliminate all the stuff that you need to do for synchronizing database and custom QAbstractItemModel.
Edit
A custom proxy model that groups items from a flat model according to a given column:
import sys
from collections import namedtuple
import random
from PyQt4 import QtCore, QtGui
groupItem = namedtuple("groupItem",["name","children","index"])
rowItem = namedtuple("rowItem",["groupIndex","random"])
class GrouperProxyModel(QtGui.QAbstractProxyModel):
def __init__(self, parent=None):
super(GrouperProxyModel, self).__init__(parent)
self._rootItem = QtCore.QModelIndex()
self._groups = [] # list of groupItems
self._groupMap = {} # map of group names to group indexes
self._groupIndexes = [] # list of groupIndexes for locating group row
self._sourceRows = [] # map of source rows to group index
self._groupColumn = 0 # grouping column.
def setSourceModel(self, source, groupColumn=0):
super(GrouperProxyModel, self).setSourceModel(source)
# connect signals
self.sourceModel().columnsAboutToBeInserted.connect(self.columnsAboutToBeInserted.emit)
self.sourceModel().columnsInserted.connect(self.columnsInserted.emit)
self.sourceModel().columnsAboutToBeRemoved.connect(self.columnsAboutToBeRemoved.emit)
self.sourceModel().columnsRemoved.connect(self.columnsRemoved.emit)
self.sourceModel().rowsInserted.connect(self._rowsInserted)
self.sourceModel().rowsRemoved.connect(self._rowsRemoved)
self.sourceModel().dataChanged.connect(self._dataChanged)
# set grouping
self.groupBy(groupColumn)
def rowCount(self, parent):
if parent == self._rootItem:
# root level
return len(self._groups)
elif parent.internalPointer() == self._rootItem:
# children level
return len(self._groups[parent.row()].children)
else:
return 0
def columnCount(self, parent):
if self.sourceModel():
return self.sourceModel().columnCount(QtCore.QModelIndex())
else:
return 0
def index(self, row, column, parent):
if parent == self._rootItem:
# this is a group
return self.createIndex(row,column,self._rootItem)
elif parent.internalPointer() == self._rootItem:
return self.createIndex(row,column,self._groups[parent.row()].index)
else:
return QtCore.QModelIndex()
def parent(self, index):
parent = index.internalPointer()
if parent == self._rootItem:
return self._rootItem
else:
parentRow = self._getGroupRow(parent)
return self.createIndex(parentRow,0,self._rootItem)
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
parent = index.internalPointer()
if parent == self._rootItem:
return self._groups[index.row()].name
else:
parentRow = self._getGroupRow(parent)
sourceRow = self._sourceRows.index(self._groups[parentRow].children[index.row()])
sourceIndex = self.createIndex(sourceRow, index.column(), 0)
return self.sourceModel().data(sourceIndex, role)
return None
def flags(self, index):
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def headerData(self, section, orientation, role):
return self.sourceModel().headerData(section, orientation, role)
def mapToSource(self, index):
if not index.isValid():
return QtCore.QModelIndex()
parent = index.internalPointer()
if not parent.isValid():
return QtCore.QModelIndex()
elif parent == self._rootItem:
return QtCore.QModelIndex()
else:
rowItem_ = self._groups[parent.row()].children[index.row()]
sourceRow = self._sourceRows.index(rowItem_)
return self.createIndex(sourceRow, index.column(), QtCore.QModelIndex())
def mapFromSource(self, index):
rowItem_ = self._sourceRows[index.row()]
groupRow = self._getGroupRow(rowItem_.groupIndex)
itemRow = self._groups[groupRow].children.index(rowItem_)
return self.createIndex(itemRow,index.column(),self._groupIndexes[groupRow])
def _clearGroups(self):
self._groupMap = {}
self._groups = []
self._sourceRows = []
def groupBy(self,column=0):
self.beginResetModel()
self._clearGroups()
self._groupColumn = column
sourceModel = self.sourceModel()
for row in range(sourceModel.rowCount(QtCore.QModelIndex())):
groupName = sourceModel.data(self.createIndex(row,column,0),
QtCore.Qt.DisplayRole)
groupIndex = self._getGroupIndex(groupName)
rowItem_ = rowItem(groupIndex,random.random())
self._groups[groupIndex.row()].children.append(rowItem_)
self._sourceRows.append(rowItem_)
self.endResetModel()
def _getGroupIndex(self, groupName):
""" return the index for a group denoted with name.
if there is no group with given name, create and then return"""
if groupName in self._groupMap:
return self._groupMap[groupName]
else:
groupRow = len(self._groupMap)
groupIndex = self.createIndex(groupRow,0,self._rootItem)
self._groupMap[groupName] = groupIndex
self._groups.append(groupItem(groupName,[],groupIndex))
self._groupIndexes.append(groupIndex)
self.layoutChanged.emit()
return groupIndex
def _getGroupRow(self, groupIndex):
for i,x in enumerate(self._groupIndexes):
if id(groupIndex)==id(x):
return i
return 0
def _rowsInserted(self, parent, start, end):
for row in range(start, end+1):
groupName = self.sourceModel().data(self.createIndex(row,self._groupColumn,0),
QtCore.Qt.DisplayRole)
groupIndex = self._getGroupIndex(groupName)
self._getGroupRow(groupIndex)
groupItem_ = self._groups[self._getGroupRow(groupIndex)]
rowItem_ = rowItem(groupIndex,random.random())
groupItem_.children.append(rowItem_)
self._sourceRows.insert(row, rowItem_)
self.layoutChanged.emit()
def _rowsRemoved(self, parent, start, end):
for row in range(start, end+1):
rowItem_ = self._sourceRows[start]
groupIndex = rowItem_.groupIndex
groupItem_ = self._groups[self._getGroupRow(groupIndex)]
childrenRow = groupItem_.children.index(rowItem_)
groupItem_.children.pop(childrenRow)
self._sourceRows.pop(start)
if not len(groupItem_.children):
# remove the group
groupRow = self._getGroupRow(groupIndex)
groupName = self._groups[groupRow].name
self._groups.pop(groupRow)
self._groupIndexes.pop(groupRow)
del self._groupMap[groupName]
self.layoutChanged.emit()
def _dataChanged(self, topLeft, bottomRight):
topRow = topLeft.row()
bottomRow = bottomRight.row()
sourceModel = self.sourceModel()
# loop through all the changed data
for row in range(topRow,bottomRow+1):
oldGroupIndex = self._sourceRows[row].groupIndex
oldGroupItem = self._groups[self._getGroupRow(oldGroupIndex)]
newGroupName = sourceModel.data(self.createIndex(row,self._groupColumn,0),QtCore.Qt.DisplayRole)
if newGroupName != oldGroupItem.name:
# move to new group...
newGroupIndex = self._getGroupIndex(newGroupName)
newGroupItem = self._groups[self._getGroupRow(newGroupIndex)]
rowItem_ = self._sourceRows[row]
newGroupItem.children.append(rowItem_)
# delete from old group
oldGroupItem.children.remove(rowItem_)
if not len(oldGroupItem.children):
# remove the group
groupRow = self._getGroupRow(oldGroupItem.index)
groupName = oldGroupItem.name
self._groups.pop(groupRow)
self._groupIndexes.pop(groupRow)
del self._groupMap[groupName]
self.layoutChanged.emit()
Thanks for this. I've been doing a bit of research and was coming to the conclusion that QAbstractProxyModel might be the route. It looks very complicated for me at the moment though :)
@StevenLee: Right now, I don't have a working example. Sorry. But I'm working on a custom proxy that groups items from a table model (like QSqlTableModel) based on a given column. If you like, I can share it when I'm done.
That would be very much appreciated. Thanks
yeah this can be a good way to get what you want, i don't have used never a proxy for hierarchical data but it is flexible in what lets you to do indeed.
@StevenLee: I included my custom proxy that groups items from a flat model. Sorry for the delay, I hardly had time to finish this. To be honest, this might be a bit crude and possibly it could use some clean-up but for now it works as expected. It might give you some ideas.
| common-pile/stackexchange_filtered |
how to configure a vpn service on ubuntu
I want to make my navigation in secure way and I won't buying vpn services as expressvpn etc.. openvpn can do this by installing on the PC that I use to navigate?
If yes can you link me any guide to configure it ?
Thanks a lot.
might this help: /609772/vpn-plugin-for-14-04?
btw are you asking for openvpn's server?
@Ravan I don't know if I need to configure a vpn server. I want to use only my single pc to connect in vpn. What I need to do this ?
please see linked question....
also this one http://askubuntu.com/questions/187284/how-to-configure-vpn-settings
Visit the official Ubuntu Help Community you'll get the detailed info here
@jaysheelutekar all the officila links are covered in linked post..=)
@Ravan ok but I have to follow the guide for VPN setup in Ubuntu – General introduction here or Setting up an OpenVPN server here ?
How I said I don't need to connect other device on vpn but only a single pc
| common-pile/stackexchange_filtered |
With a magic item that has no overall restrictions, but special bonuses when used by a certain race, can a L13 Rogue gain that bonus?
Imagine a homebrew weapon, for example, a dagger that behaves like a normal +1 dagger to everyone except elves, who are conferred an additional bonus as well other abilities or effects. For this weapon, there are no other properties which impose restrictions on use or benefits.
When a rogue uses any given magic device, how does this work? Is the rogue effectively "emulating" a certain combination of race/class/level, in order to coax magic out of the device? Or is the rogue simply ignoring or bypassing restrictions to use a magic device?
In the specific case of the above dagger, the weapon has no requirements that prevent anyone from using it. However, if the rogue is effectively presenting itself as an elf to the weapon, it might expect to get the bonus. Given that the description of UMD doesn't really address this specifically, how does this rule?
The Moonblade is an existing example. The Moonblade states that it "(requires attunement by a Elf or Half-Elf of Neutral Good Alignment)" - this is the kind of restriction that the Rogue can ignore.
The kind of wording that would not be affected is wording within the text such as "If an elf wields the weapon, they get +1 to hit", since that wording is not to do with "using" the item.
Here is an example of an item where the Rogue could not use the effect:
Elven Dagger
Weapon (dagger), uncommon
You have a +1 bonus to attack and damage rolls made with this magic weapon. When wielded by a Elf, the dagger scores a critical on a roll of 19 or 20.
Berserk's Axe is a good example if you want the rogue to be able to use the effect:
Elven Dagger
Weapon (dagger), uncommon (requires attunement by a Elf)
You gain a +1 bonus to attack and damage rolls made with this magic weapon. In addition, while you are attuned to this weapon, the dagger scores a critical on a roll of 19 or 20.
Depending on what you want the outcome of your homebrew item to be, you could use similar wording.
Very helpful to see specific examples. Thanks, this will help us clarify the currently-unclear definition of the weapon.
Is wielded by an elf a requirement that applies on use of the weapon? I believe that this answer is categorically wrong due to the narrow definition of "use". In plain English, use means to put something such as a tool, skill, or building to a particular purpose: such as attacking with a weapon - the requirement "Is wielded by an elf" thus is circumvented, and the bonus applies.
If the rogue's class feature said on equipment/attunement, then your answer would be correct.
Or if that is more accessible if "is wielded by an elf" was not a requirement to attain a bonus on use, you may as well ignore the text as it is deprived of meaning, and no condition qualifies for fulfilment due to nothing being required.
@Akixkisu It is not required to use the item, therefore it is not a "requirement on use".
@gszavae ah there is where your misunderstanding comes from, it is "You ignore all class, race, and level requirements on the use of Magic Items." - so you ignore all requirements when you use the item (such as whacking someone's face with said item). It is not "you ignore all requirments to attune/equip the item." Emphasis on "on the use" not "requirements to use" (use is a much broader definition in plain English that also includes equipment and attunement).
@Akixkisu It's not "On use, you ignore all requirements", it's "you ignore all requirements on the use". If it's not a "requirement on the use", you don't get to ignore it. "Requirements on the use" means that the requirements must be met in order to use the item! In the case of "you get a bonus if you are an elf" that is not a requirement on the use of the item, since you can use the item without meeting it.
It's Unclear
Here's the text of the rogue Use Magic Device ability:
You ignore all class, race, and level requirements on the use of Magic Items.
If a weapon gives extra bonuses to elves, is that a "race requirement", or merely a bonus specific to that race? We don't know!
There aren't any rules about what counts as a race requirement and what doesn't.
Your DM Decides
We're not an official rules source, and we're not allowed to issue rulings. When the rules are ambiguous, as happens frequently in D&D 5e, it's your DM's job to tell you what happens.
That's especially true for homebrew stuff.
It would be wrong for us to try to tell anyone how to resolve this issue, because someone might go to their DM and say: "your homebrew has to work in this way because the people on this website said so!"
Ask your DM.
By 13th level, you have learned enough about the workings of magic that you can improvise the use of items even when they are not intended for you. You ignore all class, race, and level requirements on the use of Magic Items.
This seems quite clear to me. All restrictions to the use of the magic item are removed so the Rogue uses it as if they are an Elf i.e. get the full benefits.
Mechanically, the Rogue isn't emulating the required class/level/race restrictions of the item. They are simply irrelevant when the magic item is being used by the Rogue.
Homebrew is fundamentally problematic for published rule adjudication.
It's 100% possible that your DM has specifically designed the dagger in some way that overrides any and all published information. Check with your DM for a definitive answer.
However, taking your description as entirely true, it's the latter: the Rogue ignores the restrictions.
The text of Use Magic Device says that
Use Magic Device
By 13th level, you have learned enough about the workings of magic that you can improvise the use of items even when they are not intended for you. You ignore all class, race, and level requirements on the use of magic items.
You ignore all class, race, and level requirements strongly suggests that the restrictions are bypassed, not faked (though there's room in the description for the bypassing to be due to some sort of magical imitation, if you prefer).
So, lore-wise, the Rogue knows enough about how magic works that they can use any magic item by interacting with the magic directly.
In the specific case of the homebrewed dagger, I don't see any reason that bypassing this magical requirement would be different. The Rogue doesn't need to present themselves as an elf, they simply cause the magic in the dagger to behave as it would for an elf.
Essentially I agree with your answer, but I think it could be better argued, see https://rpg.stackexchange.com/questions/172285/with-a-magic-item-that-has-no-overall-restrictions-but-special-bonuses-when-use#comment462566_172291 for reference.
| common-pile/stackexchange_filtered |
How can I separate a filename from folders in ActionScript?
How can I separate a filename from a folder in a string in ActionScript? It should split the variable and save it in two separate variables that I can use later on.
I guess I'd have to use a regex but I'm not that good at regexes.
For example:
var filepath = "/Users/folder1/folder2/test.zip";
How can I separate it into this?:
var filename = "test.zip";
var path = "/Users/folder1/folder2/";
A non-regex approach could be something like this:
var fullpath:String = "/Users/folder1/folder2/test.zip";
var arr:Array = fullpath.split("/");
var filename:String = arr.pop();
var path:String = arr.join("/") + "/";
trace(filename); // outputs test.zip
trace(path); // outputs /Users/folder1/folder2/
Or without an Array :
var fullpath:String = "/Users/folder1/folder2/test.zip";
var filename:String = fullpath.substr(fullpath.lastIndexOf("/")+1,fullpath.length);
var filepath:String = fullpath.substr(0,fullpath.lastIndexOf("/")+1);
trace("filename = " + filename);
trace("filepath = " + filepath);
trace("fullpath = " + fullpath);
/*
filename = test.zip
filepath = /Users/folder1/folder2/
fullpath = /Users/folder1/folder2/test.zip
*/
| common-pile/stackexchange_filtered |
I2C communication with Wire.h(ESP32)
I trying to connect with nitric oxide sensor over I2C bus. I'm using Wire.h library.
http://semeatech.com/uploads/SensorModule/7-Smart_EN-v1.0.pdf <- Aplication note
My code:
Wire.beginTransmission(0x0B);
Wire.write(0x00);
Wire.write(0x01);
byte err = Wire.endTransmission(false);
Wire.requestFrom(0x0B, 3);
while(Wire.available()){
//Read data
}
Sensor returns msb = 0, lsb = 0 and checkSum = 255
Am I doing something wrong with I2C bus?
The checksum of the reading is valid. Are you sure your NO2 concentration is within the range of the sensor? Or does the sensor need to be running for some time until the measurements are accurate?
Yes I'm sure the measurement should be diffrent than zero. But when im trying to read temperature(change 0x01 to 0x02) it response with values over 200°C. Thats why I'm thinking something is wrong with my I2C communication
If the checksum is ok, it's a strong indication that the I2C communication is ok. Have you divided the temperature value by 100 as required?
Yes, it's response something like 0xD9, 0x32 -> 0xD932 -> 55602 -> 556,02°C
I was thinking about 7-bit addresses in I2C. If sensor addres is 0x0B should I send data to 0x16 and recive it from 0x017?(0x0B <<1 == 0x16)
No, your code is correct. The Arduino Core shifts the address to the left by 1 bit and then sets the R/W bit. You specify the same address for reading and writing. So 0x0b should result in the NO2 bit pattern shown in the data sheet.
| common-pile/stackexchange_filtered |
How to disable zooming in Windows Mobile?
Is there some way of disabling zooming in Windows Mobile smartphones? For example HTC Titan.
I have this in my head html section:
<meta content='width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;' name='viewport' />
But I am still able to zoom in and out.
not sure if this helps, but I'm just guessing since IE is so sensitive to scripts and certain calls. Correct syntax is with commas http://stackoverflow.com/questions/5555125/viewport-tag-syntax
<meta name="viewport" content="width=device-width" />
The setting you have in your question is correct and works on Windows Phone as tested on both my Nokia Lumia 900 (Tango) and Dell Venue Pro (Mango).
If you're having problems with the dynamic viewport setting you can try setting the resolution directly.
<meta name="viewport" content="width=480" />
Reference: Windows Team Blog: Windows Phone Viewport
<meta content='True' name='HandheldFriendly' />
<meta content='width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;' name='viewport' />
<meta name="viewport" content="width=device-width" />
| common-pile/stackexchange_filtered |
Import own class file in .java
Hey an question i have this compiled .class file that contains in the .java file this:
package my.mypackage;
public class MyClass {
//SPACE START
public static void space(int spacecount) {
int spacepos = 1;
while (spacepos <= spacecount) {
System.out.println("");
spacepos++;
}
}
//SPACE END
//HASH START
public static int encrypt(String pass) {
int total = 0;
int countone = 0;
int counttwo = 0;
String charlist = "abcdefghiklmnopqrstuvwxyz";
for (int l = 0; l < pass.length(); l++) {
countone = pass.charAt(l);
counttwo = (charlist.indexOf(countone));
counttwo++;
total *= 17;
total += counttwo;
}
return total;
}
//HASH END
}
and i want to to import it into an other file named a.java it contains this:
import my.mypackage.MyClass;
import java.util.Scanner;
public class a {
public static void main(String[] args) {
MyClass.space(4);
Scanner in = new Scanner();
System.out.println("Input pass: ");
String a = in.nextLine();
int b = MyClass.encrypt(a);
MyClass.space(4);
System.out.println(b);
}
}
both are in one folder.
but when im trying to compile it it shows me this:
a.java:1: error: package my.mypackage does not exist
import my.mypackage.MyClass;
^
a.java:5: error: cannot access MyClass
MyClass.space(4);
^
bad class file: ./MyClass.class
class file contains wrong class: my.mypackage.MyClass
Please remove or make sure it appears in the correct subdirectory of the classpath.
2 errors
can anyone show me how to bring it together step by step ?
Here is the culprit:
both are in one folder.
Java compiler relies on a convention of naming source files and folders in a way that lets it find the source code by examining only the names of files, i.e. without checking their content; package name is part of the naming convention. That is why the compiler expects to find MyClass.java in a different folder.
Since class MyClass is in the my.mypackage package, while class a is in the default package, their .java files must not be placed in the same folder. Instead, MyClass.java file needs to be placed in the my/mypackage/ (on Windows, my\mypackage\) folder in relation to the a.java file's location.
that means if my a.java file is in the folder C:\JAVA\ the MyClass has to be in C:\JAVA\my\myclass\ ?
how is it when i pack both in the package my ?
@Ch3t0r "that means if my a.java file is in the folder C:\JAVA the MyClass.java has to be in C:\JAVA\my\myclass?" Absolutely (except that you typed myclass instead of mypackage). "how is it when i pack both in the package my?" All .java files from the same package need to go in the same folder - in this case, that would be C:\JAVA\my.
okay now i now what i do wrong. The CLASSPATH variable had the value "." not . problem fixed.
| common-pile/stackexchange_filtered |
Nested Data reformat
I am trying to use D3js and having some problems getting data in the format I want. What I have is an array of objects that each have a key and values, each value has an id and fields (A, B). I am trying to have an array of objects that each have a key and values, each value must have the fields (A, B). I don't know how to do this.
What I have What I want
Can you help me?
Hi, welcome to SO. Could you please add code snippets of what you actually tried so far?
Hello,when I execute this :
console.log(data[0].values[3].fields);
I have :
Object { A: Array[1], B: Array[1]}
And this code : var data1 = data.forEach(function(d){return d.forEach(function(v){return v})}); didn't work.
@Mar.Gar and it won't because you can't return inside a array.forEach(), if you have an object and want to check it with a for... try for(var k in Object){}, plus d3 have a .nest Documentation that i think can help you a lot with your question.
if i did understand your question , this should do the work(very rude way tho)
var size = a.length; //a is your object
for(var i = 0; i < size; i++) {
var inSize = a[i].values.length;
for(var j = 0; j < inSize; j++) {
a[i].values[j] = a[i].values[j].fields;
}
}
https://jsfiddle.net/vuLr99hh/
| common-pile/stackexchange_filtered |
Font-face not working for firefox or on mobile phones?
I've included some fonts in my css like this
@font-face {
font-family: 'veneer';
src: url('/fonts/Veneer_10.eot');
src: url('/fonts/Veneer_10.eot?#iefix') format ('embedded-opentype'),
url('/fonts/Veneer_10.ttf') format ('truetype'),
url('/fonts/Veneer_10.otf') format ('opentype');
}
This works fine for chrome and safari, but not for firefox or on mobiles (tested on android browser and chrome)
Anybody know why this could be?
Use woffor woff2 makes compatible with major browsers. Try to convert to woff and you'll obatin more compatibility with less lines and files
Format woff, otf try:
Example
@font-face {
font-family: "MyriadPro Light";
src: url(/css/fonts/MyriadPro-Light.woff), url(/css/fonts/MyriadPro-Light.otf);
font-weight: normal;
font-style: normal;
}
| common-pile/stackexchange_filtered |
At what point in their employment should security policies be explained to an employee?
There are the basic things that need to be explained to every employee about a security policy. For example:
How sensitive information must be handled.
How to properly maintain your ID, and password, as well as any other accounting data.
How to respond to a potential security incident, intrusion attempt, etc.
How to use workstations and Internet connectivity in a secure manner.
How to properly use the corporate e-mail system.
But at what point in their employment should these security policies be explained to an employee?
Start early and do it often. For most organizations there are all sorts of annual re-trainings or recertifications/sign-offs as well.
The question could also be asked: "how long should an employee have access to data before they are trained in how to use and protect that data?"
For most organizations, the answer is "0 minutes". You wouldn't place an employee in front of machinery without training them, and you shouldn't place employees in front of a computer without training either.
Each organization needs to assess the risks of this, but the typical answer is that this training is done during orientation.
Exactly. We train day one before allowing users to log in and we require users to retrain yearly (taking roughly 30 minutes each time)
Yep. "How long would you have someone operate a forklift before they were trained in how to use it and be safe?" "0 minutes." -- This is true even if they have already driven a forklift somewhere else.
My first job, my last stop in the interview was with the chief of security. It was the most intimidated I've been in my entire life.
@corsiKa: Why intimidated? I feel like there's an interesting story to be shared here :)
I was 18, it was for a defense contractor, the guy was ex military (probably special ops, but none of the brass ever talked about it). It was a very intense 45 minute one way conversation about the consequences of releasing even tiny bits of information to the wrong people. A "loose links sink ships" kinda speech.
Do it as part of new employee orientation and follow up with more training at regular intervals.
Security policy is part of our new employee orientation. We also require a short online "securing the human" training to be completed once every other year. Introduction of this regular training has had noticable positive results.
Ah I see, Phoenix Foundation...
not sure what you mean, Deer Hunter?
https://en.wikipedia.org/wiki/Organizations_in_MacGyver
oh. I thought you were talking about https://en.wikipedia.org/wiki/Phoenix_Foundation
First, when the employee starts. Not in order for them to learn a lot, but to get the impression that you are taking security seriously, so they don't do anything stupid.
Then a week or two later, when the employee has some clue about the job they are doing, and can actually appreciate the security training.
Then a while later when they are firmly and securely in their job, when the security training may get rid of bad habits, and where they fully understand the security training and the reasons for it.
'Stay aware and alert' is the mantra for information security. As for your question, the awareness should be part of the induction program for new employees. Basic security etiquettes like
Not flashing ID cards
No scribbling of sensitive information.
Governing policies like web access restrictions etc.
These are basic policies that need to be put forth before you give access to your organizational data to the new inductees.
Apart from new inductees, security policies like this (though are understood, but not practiced by existing employees) that apply to everyone in the organization should be told to everyone on a regular basis. You can have monthly meetings for the same. You can put up awareness posters in around you office are so that people are reminded of it. Reinforcement is key for such initiatives. You can circulate internal newsletters that allow employees to stay aware of new vulnerabilities and the countermeasures that can be used to prevent them.
Could you clarify what you mean by "flashing ID cards"?
@Lilienthal: At least in movies and television, it's common for people to show a guard an ID badge briefly and immediately put it away, before the guard has a chance to scrutinize it. Of course, in many movies and television shows this is essential to the plot, as guards' willingness to accept such behavior allows sneaky people to get by with very poorly-faked credentials.
@supercat It's not just in movies and TV. I see it all the time in real life.
@MosheKatz: The "getting in with poorly-faked credentials" part, or people unknown to the guard being allowed without much scrutiny?
@supercat both. I work on a large college campus. In the "poorly faked" category, students enjoy a brisk trade in faked IDs for underage drinking. In the "unknown to the guard" category, IDs are used to get on the bus here and people just flash random cards at the driver. (Off-campus at night, they are much more careful, but the rest of the time they don't really look too hard.)
Well, I just wanted to say that I saw a security awareness video by a renowned security firm. A hack carried out via a group on a large corporation. To bypass the physical access control, an access card was needed (Probably RFID) and the security guards were present to check the ID's. The hacker group stood outside the corporation and clicked photographs of the card and then duplicated them to bypass the system and fool the guard. Hence I thought it was important.
Data security policy should be introduced conceptually to the employee before they sign the contract, and explained and/or provided to them in detail before they sit down at their desk for the first time.
Before employment? In North America, that would be very strange, indeed.
@schroeder You're saying you wouldn't introduce the concept of security at all before employment? If any of it was part of the employment contract it would be unavoidably introduced pre-employment...
"the concept of security" might be introduced during the interviews, but not the policies or their content. Typically, there is an assumption that one would comply with all legally enforceable corporate policies no matter what their content. If the ability to work securely is a requirement, specifically, of a position, then the interviews would not be introducing security, but would be querying the applicant's experience with security.
@schroeder That's why I said "conceptually." :-)
| common-pile/stackexchange_filtered |
NodeJs with Express and Handlebars - handlebars.engine is undefined
I am following the tutorials in O'Reilly's "Web Development with Node & Express" by Ethan Brown.
They use handlebars as the view engine.
Here is my code:
var express = require ('express'),
handlebars = require('express3-handlebars'),
app = express();
handlebars.create({ defaultLayout: 'main' });
app.engine('handlebars', handlebars.engine);
The problem I am having is that handlebars.engine is undefined, resulting in a "Callback function expected" error when running the application.
I have tried searching online without any luck.
Is this some legacy syntax with handlebars? My packages have installed fine and I have tried reinstalling them.
Is there a fix/updated code for this?
You have to get the engine from the object you got from the create()-call!
Like this:
var expHbs = require('express-handlebars');
var handlebars = expHbs.create({
defaultLayout: 'layout',
extname: '.hbs',
helpers: handlebarsHelpers
});
app.engine('.hbs', handlebars.engine);
app.set('view engine', '.hbs');
Just saying: express3-handlebars got renamed to express-handlebars. You should consider switching.
Thanks so much. Was really stumped on this. For the purposes of this book, I'm going to use the old one, but will have a play around with the renamed one. Are all the methods and syntax the same? Is it just the name that changed? If so, I probably will make the switch now
The most things are the same, but some functions, like res.status(404).end(); are not allowed anymore (req.sendStatus(404); is now the correct one)
Here is the changelog, since renamed from express3-handlebars:
https://github.com/ericf/express-handlebars/blob/master/HISTORY.md#100-2014-08-07
| common-pile/stackexchange_filtered |
ms access syntax error invalid column specification (#0)
I am doing a union of two queries.
The queries run individually without an issue yet the union throws up this query. Any ideas?
The Query is
SELECT CStr([REFERENCE]) AS CostID,CSng([RATE]) AS HRates FROM [Qry 1 Project Budget pt1 labour rates]
UNION ALL SELECT CStr([REFERENCE]),CSng([Rate]) FROM [Qry 1 Project Budget pt2 3rd party];
access 2007
show us your table schema.
Both CStr() and CSng() will throw an error with Null. Check whether any of your [REFERENCE] and [RATE] values are Null.
SELECT
[REFERENCE],
[RATE]
FROM [Qry 1 Project Budget pt1 labour rates]
WHERE [REFERENCE] Is Null OR [RATE] Is Null
UNION ALL
SELECT
[REFERENCE],
[Rate]
FROM [Qry 1 Project Budget pt2 3rd party]
WHERE [REFERENCE] Is Null OR [RATE] Is Null;
| common-pile/stackexchange_filtered |
Async thunk breaks react app in useEffect
I’ve been working on a react crud application to teach myself redux toolkit, and I can’t seem to get a particular async function to work. I’m trying to fetch recipes from a certain user from firebase - this function worked when I was just playing around and didn’t have any users or authentication (i.e., the database was just recipes), but now that I have authentication and users, I cannot fetch or display the recipes, and the recipes are not added to the recipes state array. Thanks to redux logger, I can see that the recipes are accessed from firebase, but they're not displayed or added to the recipes state. Once I refresh the page, the application breaks. I can add and delete recipes to a user in firebase, though.
Here’s what the async thunk looks like:
'user/getRecipes',
async(uid, thunkAPI) => {
const snapshot = await getDocs(collection(db, `users/${uid}/recipes`))
const array = []
snapshot.forEach((doc) => {
array.push(doc.data())
})
return array
}
)
Here’s where I call it inside a useEffect. I’ve tried using the uid as an argument and getting the uid with getState() inside the thunk - it doesn’t seem to make a difference but maybe I’m doing that wrong, as well?
const RecipeApp = () => {
const dispatch = useDispatch()
const recipes = useSelector((state) => state.recipes)
const auth = getAuth()
const navigate = useNavigate()
const [user, loading, error] = useAuthState(auth)
const uid = useSelector(state => state.users.uid.user)
useEffect(() => {
if (loading) return;
if (!user) return navigate("/");
}, [user, loading])
useEffect(() => {
dispatch(getRecipes(uid))
console.log(uid)
}, [dispatch])
const addRecipe = (name, ingredients, instructions, notes) => {
const date = new Date()
const newRecipe = {
name: name,
ingredients: ingredients,
instructions: instructions,
notes: notes,
recipeId: uuidv4(),
date: date.toLocaleDateString(),
createdAt: Date.now(),
}
dispatch(addRecipeToFirestoreAndRedux(newRecipe))
}
return (
<div className="recipeapp">
<h1 className='recipeapp__heading'>Recipes</h1><button onClick={logout}>Log out</button>
<div className="recipeapp__container">
<ErrorBoundary
FallbackComponent={ErrorFallBack}>
<RecipeList
recipes={recipes}
/>
</ErrorBoundary>
<AddRecipe
addRecipe={addRecipe}
/>
</div>
</div>
);
}
export default RecipeApp;
Here’s what the relevant code (and a little more) of the recipes reducer looks like:
export const recipeSlice = createSlice({
name: 'recipesSlice',
initialState: {
recipes: []
},
reducers: {
ADD_RECIPE: (state, action) => {
state.recipes.push(action.payload)
},
DELETE_RECIPE: (state, action) => {
state.recipes = state.recipes.filter((recipe) => recipe.recipeId !== action.payload.recipeId)
},
extraReducers: builder => {
builder.addCase(getRecipes.fulfilled, (state, action) => {
state.recipes = action.payload
})
}
})
export const { ADD_RECIPE, DELETE_RECIPE } = recipeSlice.actions;
export default recipeSlice.reducer
And here's what the store.js file looks like:
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import recipeReducer from './features/recipeslice'
import userReducer from './features/authentication'
import thunk from "redux-thunk";
import logger from "redux-logger";
const rootReducer = combineReducers({
recipes: recipeReducer,
users: userReducer
})
export const store = configureStore({
reducer: rootReducer,
middleware: [thunk, logger]
})
Apologies if this is overkill. Hopefully this makes sense, and thank you in advance for any and all help!
Any errors in the console when it breaks or after refresh?
After refresh, which is also when it breaks. But even when it isn't throwing an error, I'm still not able to see the data from from firebase in the "recipes" state object, if that makes sense
What does getDocs look like?
The uid is missing from the useEffect dependency array.
@MuhammadNoumanRafique unfortunately, adding uid to the dependency array did not work.
@markerikson getDocs returns a promise that, when looped over, returns an array of objects from firestore (which is what I expect).
| common-pile/stackexchange_filtered |
How can I specify types on a camel to snake case conversion function
I have a function that converts the case of a target string, array, or object from camel case to snake case.
convertCamelToSnake (target) {
// Complex logic to convert target depending on what type it is
return convertedTarget
}
I want to specify types on this function using a Generic like so:
convertCamelToSnake <T>(target: T):T {
// Complex logic to convert target depending on what type it is
return convertedTarget
}
This works for strings and arrays, but we convert the keys of a given object to snake case. But typescript doesn't realize this and assumes that the keys remain the same because we declare that we are returning T.
How can I retain the ability to know the type that is returned. I.e. string, array, object, while leaving the keys of the dictionary ambiguous?
For instance let's say we pass in:
const a = { helloWorld: "bob", age: 21 }
a = convertCamelToSnake(a); // { hello_world: "bob", age: 21 };
a.hello_world; // Property 'hello_world' does not exist on type
How can we make it so we're allowed to access the hello_world property after converting the object, while also still being able to infer that the return value is of type object (since we could for instance also be passing in an array into this function)?
It's not trivial, but @jcalz has a great answer on this: https://stackoverflow.com/questions/64932525/is-it-possible-to-use-mapped-types-in-typescript-to-change-a-types-key-names
| common-pile/stackexchange_filtered |
Memory managment. Dealloc. iOS
Is this correct?
- (void)dealloc {
[super dealloc];
[stageObjects release];
}
Or should I call
[super dealloc]
Always after all releases, I mean last line of this function?
You must always call [super dealloc]; last. After all, this very object might always be deallocated after the call to super returns.
[super dealloc];
should be the last line to call in dealloc method.
You can also make macro as below for dealloc objects and because of it you should not write method every time.
RELEASE_SAFELY (object) [object release], object=nil
| common-pile/stackexchange_filtered |
Is there a school of informal logic that treats it as determining how to transcribe arguments into formal logic?
I've noticed it is often nontrivial to transcribe informal arguments into formal logic, but most introductory texts on formal logic make a show of it. Is this for pedagogical reasons only, or is there more advanced literature on this topic?
The paradoxes of implication, for me so far, have been the largest hidden trap in logic. Perhaps it is because texts strongly associate implication with if-then statements, but now I nearly want to remove implication from any logic that I would want to rely on. Negation, conjunction, and disjunction could be sufficient on their own.
I also worry about other potential hidden traps in logic, as well as the plurality of logical systems. The existence of intentional contexts seems like another hidden trap for someone who isn't aware of it. It also isn't altogether clear into which logical system one should transcribe an argument into. It is hard to see much similarity between a logic that allows "It is possible that I could be making more money than I am" and "It is possible that I'm a paper spoon." It is hard to make use of modal logic when it becomes too difficult to reign these possibilities in. Sometimes I feel lost in possible worlds just trying to articulate a mundane concept.
Is there advanced work on how to deal with these problems and others that I might not be aware of?
Can you give an example? Most people don't find it very difficult. All men are mortal. "For all x if x is a man then x is mortal."
Concerning your first question: If you're looking for some kind of algorithm for translating natural language arguments into formal languages have a look at Richard Montague's work on formal semantics. Montague's target language is a higher-order modal logic, that is capable of dealing with a variety of 'intensional contexts'. For an introduction see Dowty et al.: Introduction to Montague Semantics.
@user4894 Sure. Lets say for a particular photoelectric device, as solar input increases, electric output also increases. Therefore, as solar input decreases, electric output also decreases. Is this valid or not? At the moment, I'm not even sure.
Thinking about it, I would use some kind of modal logic: In every situation in which the input is greater than the current input, the output is greater than the current output. Therefore, in every situation in which the input is less than the current input, the output is less than the current output. But is this logically valid? In any case, I wouldn't call this transcription trivial.
I can only comment in saying that I share your concern. Some statements can be tricky. For starters...Here are some good tips for common English notions. http://legacy.earlham.edu/~peters/courses/log/transtip.htm
@sequitur Is that just linguistics though? I've seen some of his work online, and wonder how it coheres with Quine's maxim of shallow analysis? Basically, is Montague's work useful for logical analysis, for determining logical validity or consistency?
@Casey Thanks, that page goes into more depth than I've seen before. Are those tips from Copi's book on symbolic logic? Partly I want to know where are these transcription tips are coming from, or are they all from teachers? But I'm looking for information more advanced, or if this topic ends at the pedagogical level.
@KevinHolmes I don't know where they come from; I stumbled across them online once. I'm afraid I don't know of any real material devoted to this topic.
In simple answer, no, there is no contemporary group involved in informal logic that thinks it should all be a question of formalization.
Historically, there were those including Quine who believed all statements in normal languages could be transcribed into formal logic. This claim is by and large the central thesis of logical positivism. The idea has largely passed ...
Nope, the project of formalization defines a very vital branch of linguistics and philosophy: (formal) semantics, whose aim it has always been to provide algorithms for formalization based on various kinds of logics stronger than classical first-order. So the idea has not passed. What has passed is Quine's ludicrous idea that classical first-order logic is the ideal target of the translation process.
@sequitur I've never met someone in philosophy who is still writing who believes what you state above. And I know plenty of analytic philosophers. Moreover, Quine didn't believe it needed to be classical first-order logic. He did believe he didn't need the question mark or so the apocryphal story goes.
| common-pile/stackexchange_filtered |
Extracting levels of a factor from column number-R
I have a data.frame (df) with column name v1 which is a factor. Like:
df
# v1
# --
# a
# b
# c
When I want to get levels of the factor I get:
By column name:
levels(df$v1)
# [1] "a" "b" "c"
By column number:
levels(df[1])
# NULL
Why do I get NULL when I use column number.
Thanks a lot.
levels(df[[1]]) should work. df[1] extracts a list with one element df[[1]] extracts the contents
Why is that? df is not defined as a list. It is defined as data frame in my example.
data.frames are also/primarily lists. try is.list(iris) ;-)
Or try df[,1]. This means selecting all rows and the first column.
Thanks a lot. I got the idea. Thanks again for sharing your time.
Always useful to have a gander at http://stackoverflow.com/questions/1169456/in-r-what-is-the-difference-between-the-and-notations-for-accessing-the
Thanks @MichaelChirico. Recommended topic is very useful.
levels(df[,1])
[1] "a" "b" "c"
| common-pile/stackexchange_filtered |
Refresh ListView from update ViewModel
I am trying to bind a ListView (AllDocuments) to a List of Objects (DocumentSummary). I am trying to do the binding using mostly XAML. But I am having difficulty getting my ListView to refresh. The call to get the data MainPage.xaml.cs.OnButtonClick is working just fine. The object AllDocuments gets updated correctly with each press of the button and the data is good. I just can't figure out why the ListView is not being update after I add a new item to the AllDocuments. Obviously I am not binding something correctly.
I have provided the current code.
ViewModel Code:
using CommunityToolkit.Mvvm.Input;
using System.Windows.Input;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Diagnostics;
namespace peMove.Maui.ViewModels
{
public class DocumentSummary
{
public string Id { get; set; }
public string Name { get; set; }
public string DocType { get; set; }
public decimal Onhand { get; set; }
public string Note { get; set; }
public Color Color { get; set; }
}
public class DocsViewModel : IQueryAttributable
{
public ObservableCollection<DocumentSummary> AllDocuments { get; }
public DocsViewModel()
{
this.AllDocuments = new();
this.DocSummary = new();
}
public void AddDocument(Document _doc)
{
//DocSummary = new();
DocSummary.Id = _doc.Id1;
DocSummary.Name = _doc.Name;
DocSummary.DocType = "Part";
DocSummary.Onhand = _doc.Onhand;
DocSummary.Note = "Some note goes here";
DocSummary.Color = MauiProgram.colorPart;
this.AllDocuments.Add(DocSummary);
Debug.Print("");
}
}
}
MAINPAGE.XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:peMove.Maui.ViewModels"
x:Class="peMove.Maui.Pages.MainPage"
x:DataType="viewModels:DocsViewModel"
Title="Lookup">
<ContentPage.BindingContext>
<viewModels:DocsViewModel/>
</ContentPage.BindingContext>
<VerticalStackLayout Margin="20">
<Button Text="Load"
VerticalOptions="Center"
HorizontalOptions="Center"
Clicked="OnButtonClicked"/>
<Entry x:Name="documentId"
FontSize="24"
Keyboard="Chat"
Placeholder="Enter\Scan Id"
ClearButtonVisibility="WhileEditing"/>
<ListView ItemsSource="{Binding AllDocuments}"
HasUnevenRows="True"
VerticalOptions="FillAndExpand"
SeparatorColor="Black">
<!--<ListView.BindingContext>
<viewModels:DocsViewModel/>
</ListView.BindingContext>-->
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid RowDefinitions="Auto"
ColumnSpacing="5"
ColumnDefinitions="Auto,*,Auto" Margin="10,0">
<!--Column 1-->
<Border
Grid.Column="0"
WidthRequest="40"
StrokeShape="RoundRectangle 20,20,20,20"
VerticalOptions="Center"
HorizontalOptions="Center"
BackgroundColor="LightBlue"
Padding="12,6"
Margin="10"
HeightRequest="40">
<Label FontSize="20"
Text="{Binding DocSummary.DocType}"
TextColor="#FFFFFFDE"
VerticalOptions="Center"
HorizontalOptions="Center"/>
</Border>
<!--Column 2-->
<VerticalStackLayout Grid.Column="1"
Spacing="5"
Margin="0,0,0,0">
<Label Text="{Binding DocSummary.Id}"
HeightRequest="20"
VerticalOptions="Start"
HorizontalOptions="Start"
FontSize="14"
FontAttributes="Bold"
TextColor="Black" VerticalTextAlignment="Start"/>
<Label Text="{Binding DocSummary.Name}"
HeightRequest="20"
HorizontalOptions="Start"
VerticalOptions="Start"
TextColor="{AppThemeBinding Light='#99000000'}"
FontSize="16"/>
<Label Text="{Binding DocSummary.Note}"
HorizontalOptions="Start"
VerticalOptions="StartAndExpand"
LineBreakMode="WordWrap"
TextColor="Black"
FontSize="12"/>
</VerticalStackLayout>
<!--Column 3-->
<Label Grid.Column="2"
Text="{Binding DocSummary.Onhand, StringFormat='{0:F2}'}"
HorizontalOptions="EndAndExpand"
VerticalOptions="Start"
TextColor="Black"
FontSize="18"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</VerticalStackLayout>
</ContentPage>
MAINPAGE.XAML.CS
using peMove.Maui.Models;
using peMove.Maui.ViewModels;
using System.Diagnostics;
using System.Text;
namespace peMove.Maui.Pages
{
public partial class MainPage : ContentPage
{
int count = 0;
DocsViewModel docs = new();
public MainPage()
{
InitializeComponent();
//this.BindingContext= docs;
}
async void OnButtonClicked(object sender, EventArgs args)
{
DocId key = new DocId();
key.Id1 = "Default";
key.Id2 = "WF201B";
key.Id3 = "000";
ErpPart erpDocument = new();
erpDocument = await ErpPart.LoadAsync(key);
// This is working and returning a valid ErpPart.
Document _doc = new();
_doc.Id1=erpDocument.Part.Id1;
_doc.Name=erpDocument.Part.Name;
_doc.DocType = erpDocument.Part.Type;
_doc.Onhand=0;
_doc.UofM=erpDocument.Part.UofM;
_doc.Value01 = erpDocument.Part.Source;
_doc.Value02 = erpDocument.Part.Purchased;
_doc.Status=erpDocument.Part.Status;
docs.AddDocument(_doc);
}
}
}
use an ObservableCollection<T> instead of a List<T>
This is what I have now. Still not refreshing ..
you are also creating the VM in both the code behind and the XAML. Pick one or the other. I'd suggest removing it from the XAML, and then in the constructor of the page add this.BindingContext = docs;
Edited code to use suggestion, still not refreshing.
please [edit] your post to include the revised code
So the this.BindingContext in the code-behind worked but the XAML didn't. Why?? Everything I am reading says to do as much in the XAML as possible.
You can do it that way, but you were doing both, so that your XAML was bound to one instance of the VM, but the code-behind was updating a different instance.
I can get it to work in the code-behind with the this.BindingContext. But commenting that out and using the XAML '
<ListView.BindingContext>
<viewModels:DocsViewModel />
</ListView.BindingContext>' it does not work.
first, you generally assign BindingContext at the page level. Second, if you want to use that approach, then you should bind your controls to commands in your VM instead of using event handlers
Same with you Jason. Thank you so much for all your effort. You are keeping me sane.
Jason, I have been tinkering around with this and can not get the list to refresh unless I use the this.BindingContect in the code-behind and removing the BindingContext in the xaml. I even set the BindingContext for the ContentPage section of the xaml. Are you saying that I can't bind VM elements in my listview without using a command which I need to define in my VM? I can't just us {Binding Name}. It just doesn't seem like that is what I am seeing in all the tutorials.
no, I'm saying that if you are using MVVM then you would generally bind VM commands instead of using event handlers in the code-behind. You CAN mix data binding with event handlers, it just isn't ideal. Without knowing exactly what you've tried its difficult to say what you might be doing wrong.
also, if you are setting the BindingContext in XAML, then you will have to cast BindingContext to the correct type in order to use the VM instance from the code-behind
@Jason I have refreshed the code after applying some things I have learned (i hope). But it is still weird that I can not get the ListView to refresh. I wanted you to see the current code. Appreciate all of your help.
you are still creating two separate instances of the VM, one in the XAML and one in the code-behind.
In MainPage.xaml.cs I have the line 'DocsViewModel docs = new();' in the class definition. This creates a new instance of the view model. But when the InitializeComponent executes in the MainPage initiator it creates another instance of the View Model from the BindingContext (I think). I think this is my problem, but if I don't define docs in the code behind, how would I call the AddDocument method at the end of "OnButtonClicked" to add the results to the AllDocuments list?
you are creating two separate instances of your VM, one in XAML, which your UI is bound to
<viewModels:DocsViewModel/>
and one in code, which your UI is not bound to
DocsViewModel docs = new();
then you add a document to the instance that the UI is not bound to, so the UI does not update
docs.AddDocument(_doc);
you can either, 1) get rid of the VM in the XAML and set it in code instead
this.BindingContext = docs = new DocsViewModel();
or 2, keep it in XAML and modify your code behind to use that instance of the VM
docs = (DocsViewModel)BindingContext;
Sorry Jason, I did not see this. Yes, I FINALLY see this. And I don't see an advantage to the keeping it in the XAML. I still am using it in the XAML like your #2, and I get the items in the list, but it is not picking up the bindings for the elements in each Item (Id, Name, etc.). I suspect it has to do with 'x:DataType="viewModels:DocsViewModel"' in the ContextPage. I can bind the ListView to AllDocuments, but I can't bind the elements of each listview item (Id, DocType, Name, etc.).
I guess I would need to make each of them properties of the ViewModel so I can use them as Bindings
you just need to add x:DataType with the correct type to the DataTemplate node
YES!! Thank you so much .. now to the next hurdle ... Again Thank you!!
From the code you shared, I found that you are confusing the use of in the code-behind with the this.BindingContext and MVVM.
Based on the code, I created a demo and added some fake data to achieve this function.
You can refer to the following code:
1.added some fake data to view model DocsViewModel.cs.
public class DocsViewModel//: IQueryAttributable
{
public ObservableCollection<Document> AllDocuments { get; }
public ICommand NewCommand { get; }
public ICommand SelectDocumentCommand { get; }
//public List<Document> Documents { get; set; }
public DocsViewModel()
{
this.AllDocuments = new();
NewCommand = new Command(NewDocumentAsync);
//SelectDocumentCommand = new AsyncRelayCommand<ViewModels.DocsViewModel>(SelectDocumentAsync);
}
private void NewDocumentAsync()
{
/* DocId key = new DocId();
key.Id1 = "Default";
key.Id2 = "WF201B";
key.Id3 = "000";
ErpPart erpDocument = new();
erpDocument = await ErpPart.LoadAsync(key);*/
// here I added some fake data, you can modify it based on your needs.
Document _doc = new();
_doc.Id1 = "01";
_doc.Name = "doc1";
_doc.DocType = "type1";
_doc.Onhand = 0;
_doc.UofM = "UofM01";
_doc.Value01 = "value1";
_doc.Value02 = "value2";
_doc.Status = "status";
AllDocuments.Add(_doc);
}
public void AddDocument(Document _doc)
{
this.AllDocuments.Add(_doc);
Debug.Print("");
}
}
2.set the BindContext for the page in xaml and set the <ListView ItemsSource="{Binding AllDocuments}" for the ListView.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiAddDocToListApp.MainPage"
xmlns:viewmodels="clr-namespace:MauiAddDocToListApp.ViewModels"
>
<!-- set BindingContext here -->
<ContentPage.BindingContext>
<viewmodels:DocsViewModel></viewmodels:DocsViewModel>
</ContentPage.BindingContext>
<VerticalStackLayout Margin="20">
<Button Text="Load"
VerticalOptions="Center"
HorizontalOptions="Center"
Command="{Binding NewCommand}"
/>
<Entry x:Name="documentId"
FontSize="24"
Keyboard="Chat"
Placeholder="Enter\Scan Id"
ClearButtonVisibility="WhileEditing"/>
<!--<Entry x:Name="documentId"
Placeholder="Enter Document Id"
TextChanged="OnDocumentIdTextChanged"
Completed="OnDocumentIdCompleted"
ClearButtonVisibility="WhileEditing"/>-->
<ListView ItemsSource="{Binding AllDocuments}"
HasUnevenRows="True"
VerticalOptions="FillAndExpand"
SeparatorColor="Black"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid RowDefinitions="Auto"
ColumnSpacing="5"
ColumnDefinitions="Auto,*,Auto" Margin="10,0">
<!--Column 1-->
<Border
Grid.Column="0"
WidthRequest="40"
StrokeShape="RoundRectangle 20,20,20,20"
VerticalOptions="Center"
HorizontalOptions="Center"
Padding="12,6"
Margin="10"
HeightRequest="40">
<Label FontSize="20"
Text="{Binding DocType}"
TextColor="#FFFFFFDE"
VerticalOptions="Center"
HorizontalOptions="Center"/>
</Border>
<!--Column 2-->
<VerticalStackLayout Grid.Column="1"
Spacing="5"
Margin="0,0,0,0">
<Label Text="{Binding Id1}"
HeightRequest="20"
VerticalOptions="Start"
HorizontalOptions="Start"
FontSize="14"
FontAttributes="Bold"
TextColor="Black" VerticalTextAlignment="Start"/>
<Label Text="{Binding Name}"
HeightRequest="20"
HorizontalOptions="Start"
VerticalOptions="Start"
FontSize="16"/>
<Label Text="{Binding Value01}"
HorizontalOptions="Start"
VerticalOptions="StartAndExpand"
LineBreakMode="WordWrap"
TextColor="Black"
FontSize="12"/>
</VerticalStackLayout>
<!--Column 3-->
<Label Grid.Column="2"
Text="{Binding Onhand, StringFormat='{0:F2}'}"
HorizontalOptions="EndAndExpand"
VerticalOptions="Start"
TextColor="Black"
FontSize="18"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</VerticalStackLayout>
</ContentPage>
Note:
Since we are using MVVM to achieve this, we also need to set the command for the Button to trigger the click event on the DocsViewModel.cs .
<Button Text="Load"
VerticalOptions="Center"
HorizontalOptions="Center"
Command="{Binding NewCommand}"
/>
Wow, I appreciate the effort to help me! I will look into this example as I get some time this week. Again, thank you!
This will work with the fake data, but the call to get live data goes through the Asynchronous ErpPart.LoadAsync(key) method. I would need to make NewDocumentAsync a Task. Will that work??
You can first recheck if you could get the data from ErpPart.LoadAsync(key) method and add it to AllDocuments correctly.
| common-pile/stackexchange_filtered |
Trying to receive emails AND store them into an S3 bucket
I'm trying to store emails i receive into an s3 bucket, i followed this tutorial and multiple others :
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-getting-started.html
My MX record is set to my mail.Domain like this :
Domain MX 10 mail.domain
When i change it to
Domain MX 10 inbound-smtp.us-east-1.amazonaws.com
I do not receive mails anymore and still do not get emails stored.
I do not know what is missing exactly ? someone help please.
Update : Managed to follow Mlu answer and i'm now at a very close step to getting my answer, the only problem is that AWS SES does not accept a "FROM" that is outside of my domain reaching another outside domain.
For example A sends email to B, B forwards (looks more like redirects) email to C, so C sees that he got a message from A not B, that, AWS SES doesn't like and will give this error for example :
554 Message rejected: Email address is not verified. The following identities failed the check in region US-EAST-1<EMAIL_ADDRESS>Jon Doe (in reply to end of DATA command).
Unfortunately this will be difficult for us to help you with, as you've provided no diagnostic information. I suggest you either find another tutorial, or hire an AWS Consultant who can work this out for you.
First some DNS / email background - even if you have multiple MX records for example.com in your DNS the emails are only received by one of the servers listed. Typically the sender contacts the one with the lowest preference but in your case if both have priority 10 the sender server will just choose one randomly.
If you want to both receive email on your mail.example.com and through AWS SES to store it in S3 you will have to feed it from one to the other explicitly.
I've got a similar setup in one of our projects and we receive the mails by Postfix (that's our mail.example.com) and from there we forward it to SES using the always_bcc postfix configuration directive.
In this case the example.com MX record only points to mail.example.com, not to SES. However we also have a record for ses.example.com being a MX record pointing to inbound-smtp.us-east-1.amazonaws.com. Then our always_bcc =<EMAIL_ADDRESS>and obviously in SES we've got the domain ses.example.com configured to store emails to S3.
If you want you can also do it the other way around - receive on SES first and from there save to S3 and forward to your other mail server.
The bottom line is that you can'y simply list both SES and the mail server and expect that the emails will arrive to both. You have to explicitly receive at one and forward to the other.
Hope that helps :)
Hi, here is the new thread :
https://serverfault.com/questions/1002025/how-to-use-ses-as-an-outbound-relay-for-postfix
| common-pile/stackexchange_filtered |
Linking source installed pandas to homebrew'd python
I am attempting to install the python package pandas.
All my existing python gear has been installed using home-brew / easy_install / pip, however pip and easy_install both fail on pandas -- claiming that i do not have numpy > 1.6 (though when in python numpy.__version__ returns 1.6.2).
Despite this pip install numpy --upgrade reports that I am up-to-date.
To hack around this, I git-cloned the source code down, and ran python setup.py install in my /Library/Python/... directory. It seemed to build okay, however when i import pandas, i get an error and i'm not sure what to do about it.
Can anyone help me link the compiled library to my existing install?
The error follows:
dlopen(/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.9.1.dev_5a152bd-py2.7-macosx-10.7-x86_64.egg/pandas/lib.so, 2): Symbol not found: _floatify
Referenced from: /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.9.1.dev_5a152bd-py2.7-macosx-10.7-x86_64.egg/pandas/lib.so
Expected in: flat namespace
in /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.9.1.dev_5a152bd-py2.7-macosx-10.7-x86_64.egg/pandas/lib.so
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.9.1.dev_5a152bd-py2.7-macosx-10.7-x86_64.egg/pandas/__init__.py", line 10, in <module>
import pandas.lib as lib
ImportError: dlopen(/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.9.1.dev_5a152bd-py2.7-macosx-10.7-x86_64.egg/pandas/lib.so, 2): Symbol not found: _floatify
Referenced from: /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.9.1.dev_5a152bd-py2.7-macosx-10.7-x86_64.egg/pandas/lib.so
Expected in: flat namespace
in /usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.9.1.dev_5a152bd-py2.7-macosx-10.7-x86_64.egg/pandas/lib.so
This problem's solution was to delete the version of numpy found in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python. To figure this out i had to brew uninstall python, and use the system python to import numpy and then print numpy.__version__ -- which confirmed that it was the old one. I think identified the location of the crusty bumpy via print(numpy), and finally cd'd into the directory and sudo rm -r numpy. Only after this was done would pip install pandas work -- meaning i did not need to git clone it down.
This was discussed and resolved on GitHub: https://github.com/pydata/pandas/issues/2188. The issue had to due with Clang's C99 behavior w.r.t. inline C functions.
i deleted and git cloned the new one down, and now i see: "raise ImportError('C extensions not built: if you installed already '
ImportError: C extensions not built: if you installed already verify that you are not importing from the source directory". The odd thing is that pip still cannot see my NumPy when i try and pip install pandas. pip and easy_install sure can see that my numpy is up to date, so i think this is a pandas issue. a shame, as i really want to get pandas working and buy your book mate.
Did you python setup.py install in the git clone (pandas has C extensions that must be built. also, you should not import pandas from the source directory right after installing)? If there's something wrong with your environment you should consider the 100% free Anaconda CE distribution which is bundled with everything you need.
yep i did python setup.py install but i did do it in the /Library/Python/... folder, and i did try to import right after the build. i have used pip to get Cython. what should i do instead?
Fixed the root problem (pip install pandas failing) on my MBP, and then tested it on another box -- the problem seems to be a conflict between the old version of numpy that comes with the mac install, and the newer one subsequently installed using pip. Pandas sees the old numpy, and fails.
To fix this, cd to the location of the default packages. Yours is probably the same as mine:
$ cd /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/
$ sudo rm -r numpy
$ sudo pip install pandas
With that out of the way, sudo pip install pandas worked for me on both boxes.
| common-pile/stackexchange_filtered |
R: create index for xts time object from calendar week , e.g. 201501 ... 201553
I know how to get the week from an index, but don't know the other way around: how to create an index if I have the calendar weeks (in this case, from an SAP system with 0CALWEEK as 201501, 201502 ... 201552, 201553.
Found this:
How to Parse Year + Week Number in R?
but the day is needed and it's not clear how to set it, especially at the end of the year (Year - week - day: YEAR-53-01 does not always exist, since the first day of week 53 might be Monday, then 01 (Sunday) is not in that week.
I could try to get in the source system the first day of the corresponding week (through SQL) but thought R might do it easier...
Do you have any suggestions?
(Which first day of the week would be not important , since I will create all objects the same way and then merge/cbind them, then continue the analysis. If zoo is easier, I'll go with it)
Thanks!
The problem is that all indices end in 2015-07-29:
data <- 1:4
weeks <- c('201501','201502','201552','201553')
weeks_2 <- as.Date(weeks,format='%Y%w')
xts(data, order.by = weeks_2)
[,1]
2015-07-29 1
2015-07-29 2
2015-07-29 3
2015-07-29 4
test <- xts(data, order.by = weeks_2)
index(test)
[1] "2015-07-29" "2015-07-29" "2015-07-29" "2015-07-29"
You can use as.Date() function, I think is the easiest way:
weeks <- c('201501','201502','201552','201553')
as.Date(paste0(weeks,'1'),format='%Y%W%w') # paste a dummy day
## [1] "2015-01-05" "2015-01-12" "2015-12-28" NA
Where:
%W: Week 00-53 with Monday as first day of the week
or
%U: Week 01-53 with Sunday as first day of the week
%w: Weekday 0-6 Sunday is 0
For this year, week number 53 doesn't exist. And If you want to start with 2015-01-01, just set the right week day:
weeks <- c('201500','201501','201502','201551','201552')
as.Date(paste0(weeks,'4'),format='%Y%W%w')
## [1] "2015-01-01" "2015-01-08" "2015-01-15" "2015-12-24" "2015-12-31"
You may try with substr() and lubridate
library(lubridate)
# a number from your list: 201502
# set the year
x <- ymd("2015-01-1")
# retrieve second week
week(x) <- 2
x
[1] "2015-01-08"
you can use the result for your Index or rownames().
zoo and xts are great for time series once you have set the names,
be sure to remove any column with dates from your data frame
| common-pile/stackexchange_filtered |
Oracle sql make strings inside single qoutes
What I wanted is to place every string inside single qoutes even if it is delimited by a dot something like this:
Input: Hi.Hello.World
Output: 'Hi'.'Hello'.'World'
Note: Inputs can be 2 or more words delimited by a dot
You could try this:
SELECT '''' || REPLACE(string, '.', '''.''') || ''''
FROM yourTable
Demo
The idea here is we replace every dot . with dot in single quotes '.'. This covers all internal dots/quotes. Then, to handle the outside single quotes, we can concatenate them on both sides.
thanks @Tim. this solved my problem! it also makes a string without dot inside single qoutes which I also needed but I forgot to include in my question. :D
| common-pile/stackexchange_filtered |
Comparing 2 HashSets for common object
I have one question, I have two HashSets,
Set<String> list1 = new HashSet<String>(oldList1);
Set<String> list2 = new HashSet<String>(oldList2);
And I would like to check if a "String" in list1 is present in list2. What would be the fastest way to go trough this? Keeping in mind that both sets have over 10k Strings, so something relatively fast would be nice.
Any help is appreciated!
I wouldn't call a Set list - is confusing.
list2.retainAll(list1).
If you want to check whether there is any string in list1 that is also in list2, you can just write
!Collections.disjoint(list1, list2)
which is true if they have any elements in common. If you want to find the answer, just do the straightforward loop:
for (String str : list1) {
if (list2.contains(str)) {
return str;
}
}
Yes thanks! but I would also like to what that String is
Then just do a loop: for (String str : list1) { if (list2.contains(str)) { return str; }} ...which does the same thing anyway, and you're not going to get more efficient than that. (Though frankly 10k elements isn't big enough to worry about.)
@BoristheSpider it doesn't seem worth it to mutate the data structure if it's not actually necessary? The simple loop does the job just fine.
Another option is to use Set restriction to add duplicate. Method add() will help you find all identical strings.
Adds the specified element to this set if it is not already present
(optional operation). More formally, adds the specified element e to
this set if the set contains no element e2 such that (e==null ?
e2==null : e.equals(e2)). If this set already contains the element,
the call leaves the set unchanged and returns false. In combination
with the restriction on constructors, this ensures that sets never
contain duplicate elements.
Set<String> list1 = new HashSet<String>();
list1.add("a");
list1.add("b");
list1.add("c");
Set<String> list2 = new HashSet<String>();
list2.add("b");
list2.add("c");
list2.add("d");
Set<String> listCommon = new HashSet<String>();
for (String element : list2) {
if (!list1.add(element)) {
listCommon.add(element);
}
}
// all collected duplicates
for (String element : listCommon) {
System.out.println(element);
}
| common-pile/stackexchange_filtered |
What are the legal tournament formats for MtG?
What are the current legal tournament formats for Magic: The Gathering? What are the differences/definitions of each format? At what point do sets rotate in/out of a format?
You can visit the Banned / Restricted Lists for DCI-Sanctioned Magic: The Gathering Tournaments page to see a list of formats, plus deck construction rules and a list of banned/restricted cards for each format.
With the exception of prerelease Limited, new sets enter their appropriate formats on the day of their official release. The specific dates for upcoming sets are spelled out in the "New Releases" section of the most current Magic Tournament Rules (PDF link).
As for a description of each format, plus differences and defining characteristics, is probably overly broad as a question.
Note: While it's not a tournament format, Commander does have rules listed in the CR. Cards are legal in Commander as of their set's prerelease.
| common-pile/stackexchange_filtered |
Getting document ID when decoding firestore document using Swift Codable
I'm using a class to decode retrieved firestore documents, and it works as expected if I don't want to manipulate the data:
class Room: Identifiable, Codable {
@DocumentID public var id:String?
var name:String
}
However if I try to use my own init to set values, I can't get the firestore document ID?
class Room: Identifiable, Codable {
@DocumentID public var id:String?
var name:String
enum Keys:String, CodingKey {
case name
case capacity
case photo = "url"
}
required init(from decoder: Decoder) throws {
// How do I get the document ID to set the id value?
let container = try decoder.container(keyedBy: Keys.self)
name = try container.decode(String.self, forKey: .name)
capacity = try container.decode(Int.self, forKey: .capacity)
photo = try container.decode(String.self, forKey: .photo)
// Do some more stuff here...
}
}
how did you solve this?
Found the answer elsewhere, and this works perfectly. Posting for anyone else who arrives here with the same query.
TL;DR -
Use the following to decode the DocumentReference in your init function:
ref = try container.decode(DocumentID<DocumentReference>.self, forKey: .ref)
.wrappedValue
Longer explanation:
I won't pretend to understand this 100%, but there's a good explanation here https://github.com/firebase/firebase-ios-sdk/issues/7242
| common-pile/stackexchange_filtered |
free language/database for standalone application
Can you advice me please on a "free" language and database that I can use to create a standalone application e.g. simple HR application w/ (forms,reports and queries) that I can copy and use in my flash memory ?
what platform(s) does it need to run on?
Almost any language will work. And most languages these days are free both as in beer and as in liberty. As for the database, definitely SQLite: http://www.sqlite.org/
Mono + C# + SQLLite
| common-pile/stackexchange_filtered |
Error while running a test: "You must add a reference to assembly..."
I am trying to launch a test but I obtain this error
The type 'System.Web.Security.MembershipUser' is defined in an
assembly that is not referenced. You must add a reference to assembly
'System.Web.ApplicationServices, Version=<IP_ADDRESS>, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'.
I looked for google and found that I have to Add Reference System.Web.ApplicationServices to my project, i do it but still dont work.
I wrote it in web.config to but nothig, I obtain the same error
<assemblies>
<add assembly="System.Web.ApplicationServices, Version=<IP_ADDRESS>, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
Any idea!!! Thanks.
http://stackoverflow.com/questions/11161203/where-is-system-web-security-membershipprovider http://stackoverflow.com/questions/4708280/class-library-cant-find-membershipuser Basically you can find this System.Web.ApplicationServices.dll under C:\Windows\Microsoft.NET\Framework\v4.0.30319
When do you get this problem? When building your project, or when actually running the test?
If you get it when you build your project, follow these steps to see if it resolves your problem:
1 - Search your machine for this file: "System.Web.Security.MembershipUser.dll"
2 - Once you find it, open your project and choose the "Add Reference" menu command
3 - Choose the file you found in step 1
Thanks JosephStyons, but what happen if I don't have this file... System.Web.Security.MembershipUser.dll
This question might help as well.
| common-pile/stackexchange_filtered |
jQuery: check the type of SVG element
How can I check the type of an svg object in JavaScript or jQuery?
I want to check whether a tag is of type SVGAnimatedString.
When I output the object to the console it outputs the following:
console.log(this.href);
SVGAnimatedString // is an object and can be expanded
In my code I try to check whether it is a SVG object but the check does not work.
if (this.href == 'SVGAnimatedString'){ //this check does not work
//it s an svg object
var url = this.href.animVal
}
else{
var url = this.href; //get the href from the <a> element
}
How do I correctly check whether it is a SVGAnimatedString object?
You should not compare the types using ==. You need to use instanceof. You can do this way:
if (this.href instanceof SVGAnimatedString){ //this check works!!!
//it s an svg object
var url = this.href.animVal
}
else{
var url = this.href; //get the href from the <a> element
}
The SVGAnimatedString has less browser support. Keep that in mind. :)
Thanks it works now. Regarding browser compatibility: I only want to check the type, since the SVGAnimatedString object is returned from an svg object I created with D3. I tested it with Chrome and FF, and it works. Do you think I will run into issues using other browsers?
That should work, you could probably also use something like if ('animVal' in this.href)
| common-pile/stackexchange_filtered |
inline javascript function call - missing ] after element list
I have a code:
var data = $('<span onclick="someFunction(' + element + ');"><a href="#">Element information</a></span>');
where element is a object.
Also, I have a function defined:
someFunction: function(element) {
console.log(element);
.... // some code
}
But when span element tries to call that function, I get error:
SyntaxError: missing ] after element list
someFunction([object Object]);
When I debug it in Firebug, I see
<span onclick="someFunction([object Object]);">
<a href="#">Element information</a>
</span>
How can I normally call that function with concrete element as an argument?
what type of object is element?
You will not be able to pass the element as it is converted to string in your concatenation. When an object is converted to string it outputs: [Object object]. This is what you are seeing in your debug.
My suggestion:
You may add the element as data to the span like:
$('span).data('element', element);
And in someFunction retrieve it like:
var element = $(this).data('element');
Another option is to bind to click in Javascript at the place where your element is initialized. Like this
function anotherFunction() {
var element = {};
// Initialize element
...
// I have already got the element initialized, now I can bind the click
$('span').click(function() {
// For your debug and validation
console.log(JSON.stringify(element));
});
}
If you try to build some DOM elements with jQuery, you should do this:
// Wrong: $('<span onclick="someFunction(' + element + ');"><a href="#">Element information</a></span>');
// Right: build up the element step by step
var data = $('<span/>')
.append(
// build up the child <a> element here
$('<a href="#"/>')
.text("Element information")
//.attr('href',"#") Don't really need this
)
.click(
// Here is a real inline function
function(){
someFunction(element);
}
);
Note: .click in jQuery can be used to assign an event handler for the Click event.
In your original code, you are trying to concatenate a string with an object, which will result in applying toString to that object, converting it to a string:
console.log((new Object()).toString()); // [object Object]
console.log("blah" + (new Object())); // blah[object Object]
In your code, it seems that your object is in fact a jQuery object, but it won't make any differences.
So the resulting "code" used to form onclick is invalid:
someFunction([object Object]);
[ and ] is used to construct an Array in JavaScript, like [1, 2] is an Array with two elements. However [object Object] is an invalid JavaScript syntax so you get the error.
Anyway, this is not a correct way to build up DOM element with events, even with jQuery. The above shown the correct way.
You could also try:
var data = $('<span onclick="someFunction(' + JSON.stringify(element) + ');"><a href="#">Element information</a></span>');
The function:
someFunction: function(element) {
console.log(element);
.... // some code
}
Should return a JSON Object when called.
| common-pile/stackexchange_filtered |
Hibernate, search by primary key returns all from table
I have this issue with Hibernate that when i try to retrieve unique result using criteria hibernate returns all the content from the table.
Session session = HibernateUtil.beginTransaction();
Customer c = new Customer();
c.setCustId(custId);
Example ex = Example.create(c);
Criteria criteria = HibernateUtil.getSession().createCriteria(Customer.class);
criteria.add(ex);
Customer customer = (Customer)criteria.uniqueResult();
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
However querying the table with:
Customer customer = (Customer)session
.createSQLQuery("select * from customer_ where custid = :id")
.addEntity(Customer.class)
.setInteger("id", custId)
.uniqueResult();
returns correct entry.
custId is the table's primary key. And the Customer class contains 2 @OneToMany mappings.
Do I need to add something to the criteria example above??
The documentation says:
Version properties, identifiers and associations are ignored.
(emphasis mine)
Why not simply using Session.get() if you have the identifier?
Thanks for reply. I did not realize that i can use session.get(). I was just following an example. So identifier == primary key?? and associations == annotated fields?? Is it not strange that i cant use them with criteria search?? Sorry for stupid questions, its my first time using hibernate.
associations = OneToOne, OneToMany, ManyToOne, and ManyToMany. An association with another entity.
| common-pile/stackexchange_filtered |
How to use translation strings in flutter, and use Multiple languages
Kindly guide How to use multiple languages in Flutter, how to give the option to the user to switch between languages.
I have some strings to use in Flutter for multiple languages
English
"sensor_title": "SENSORS",
"sensor_gyroscope_title": "GYROSCOPE",
"sensor_accelerometer_title": "Accelerometer",
Turkish
"sensor_title": "SENSÖRLER",
"sensor_gyroscope_title": "JİROSKOP",
"sensor_accelerometer_title": "İvmeölçer",
Using the code below each time you want to translate a String just invoke Translator class like this Translator.of(context).translate("sensor_title"); for instance
This assumes that you have json files saved in a i18n folder at the root of your project
You can also use getx dependency, it is so simple not only for localisation but State management, route management also..
There are multiple options you can try:
Implement i18n for your app:
With this, you need to implement the config yourself to make your app internationalized. You can use the build_runner to generate most of the config for you. What is left is just putting your key/value pairs of words into the json files.
Use the easy_localization package: This package is what I usually use for small scale app since it does the heavy work for me.
you can use get package it's easy to customize your translations and make offline multi language app. Just check on the internationalization part.
| common-pile/stackexchange_filtered |
st_transform does not work
I am trying to transform a geometry from srid 4326 to 26915.
SELECT
ST_Transform(s.geompos, 26915)
FROM sites s
But i got error :
ERROR: could not form projection (LWPROJ) from 'srid=4326' to 'srid=26915'
SQL state: XX000
I am on ubuntu 22.04, Postgresql 14, postgis :
POSTGIS="3.2.2 628da50" [EXTENSION] PGSQL="130" GEOS="3.10.2-CAPI-1.16.0" PROJ="6.3.1" LIBXML="2.9.10" LIBJSON="0.13.1" LIBPROTOBUF="1.3.3" WAGYU="0.5.0 (Internal)" TOPOLOGY
use ST_SetSRID https://gis.stackexchange.com/a/185202/276
I dont need to use set srid because the geom has this srid. Also the error that i got, mentionned it.
But when I try to user ST_Transform(s.geompos, 32647) for example, this works fine.
This post may be helpful https://gis.stackexchange.com/questions/396058/postgis-st-transform-fails-for-many-srid-on-ubuntu-20-04-2-lts. It looks like your postgis installation is missing GDAL
Does select * from spatial_ref_sys where srid=26915find one row?
| common-pile/stackexchange_filtered |
What is the meaning of 奴 this poem from 红楼梦?
Poetry is never easy to understand. 奴 is used twice in this poem. I think this 奴 means I or me, in a sense of 'me, this poor slave'.
怪奴底事倍伤神?半为怜春半恼春。
怜春忽至恼忽去,至又无言去不闻。
昨宵庭外悲歌发,知是花魂与鸟魂。
花魂鸟魂总难留,鸟自无言花自羞。
愿奴胁下生双翼,随花飞落天尽头。
天尽头,何处有香丘?
一般的女性第一人称谦称罢了,我所读过的版本也作“侬”
我读的有:尔今死去侬收葬,未卜侬身何日丧?
Hey, Pedroski, long time no see - welcome back.
It is kind of 谦称 of a woman in ancient China, there are others of course
妾 or 妾身 or 奴婢 for you being the wife
奴 or 奴家 for you being the wife or general cases
小女子 for general cases
老身 for older ladies
And for men of course, their 谦称 could be
小人 for you being the servant
鄙人 for general but unofficial use
在下 for you being in a relatively lower social hierarchy
晚生 if you are younger to your friend
不才 for proposing suggestions
不肖 for referring yourself with respect to your older relatives
愚弟 or 愚兄 for closer relationship
| common-pile/stackexchange_filtered |
Multilingual database - Get all languages of post
I want to write an application where multilingual data is stored in a database. There are posts with an unique ID which are written in several languages (at least 2 languages, other languages will possibly be added). I already looked through several posts of stackoverflow and found these nearly satisfying answers:
Multi-language Category Titles in Mysql Database
What's the best database structure to keep multilingual data?
Schema for a multilanguage database
They all suggest to put up 3 tables like this:
[ languages ]
id (INT)
name (VARCHAR)
[ products ]
id (INT)
price (DECIMAL)
[ translation ]
id (INT, PK)
model (VARCHAR) // product
field (VARCHAR) // name
language_id (INT, FK)
text (VARCHAR)
(This is from one of the links above)
I agree with that solution, but I want the application to show all the possible languages the post is written in. I already thought of reading all the translations for a post and using only one to create the page, but use the other translations to show other possible languages. I don't like this idea, because that way I retrieve too much data from the database that isn't used (because I retrieve many translations an use only one).
I also thought of retrieving all possible translations and storing them already in the page (e.g. in javascript code, in a data-attribute, etc.), but this would make the page slower, because I think most users only want to see the post in only one language.
So I guess the application has to execute 2 queries: one to get the translation and one to get all languages for the post. But I think there is a way to put this in one query, but I don't have a good idea how to do that.
Is there a easy way to read the translation for a language (given by the user or default, maybe just the first database entry) and all other language the post is written in with just a single query?
Thanks in advance.
I recommend you to use two queries for higher flexibility.
Also you can use one query - for example to get languages separated by "," in a string:
SELECT t.*,
(SELECT GROUP_CONCAT(l1.name SEPARATOR ',')
FROM translation t1
JOIN languages l1 ON l1.id = t1.language_id
WHERE t1.product_id = t.product_id
GROUP BY t1.product_id
) AS lang_names
FROM translation t
-- there put required JOIN-s --
WHERE t.id = ?
there: ? is placeholder for translation id which you wish to show.
I assume there is product_id field in the translation table.
| common-pile/stackexchange_filtered |
Solve the ODE $y(1+x^3)y'+x^2(1+y^2)=0$
Solve the ODE $y(1+x^3)y'+x^2(1+y^2)=0$,
How do you solve this?
Separating and integrating I obtain:
$- \frac{1}{2} \ln(1+y^2) = \frac{1}{3} \ln(1+x^3) + C$,
Then exponentiating:
$(1+y^2)^{-\frac{1}{2} }= (1+x^3)^{\frac{1}{3}} e^C$
And then:
$y^2=A(1+x^3)^{-\frac{2}{3}}-1$; $A=e^{-2C}$
I should then just root both sides for y and then there is the answer? I have looked at a solution online vastly different from mine and don't know why.
Note: the solution I saw is from wolfram
It is on wolfram I tried copying link but it doesn't save the equation I type in
http://www.wolframalpha.com/widgets/view.jsp?id=e602dcdecb1843943960b5197efd3f2a
The second anti-derivative should be $\frac13\ln|1+x^3|$ and in consequence $A=\pm e^C$ while $A=0$ gives the constant solution $y=0$, thus all $A\in\Bbb R$ are possible.
Everything else is correct. WA, as any CAS, sometimes does not find the "obviously" direct way, the tricks employed there are tuned towards always finding a solution in any case where a symbolic solution is possible.
In my opinion, sometimes is probably an understatement !
| common-pile/stackexchange_filtered |
Number field that deletes non-numbers without clearing previous numbers?
I am using:
<input type="text" onkeyup="this.value = this.value.replace(/\D/g, '')">
I use it to prevent the user from entering anything except a number into a field on my page. However, I noticed that if the user types a number first but then accidentally hits a non-number key, the field is cleared and they have to start over. This may cause frustration so I was wondering if there was a way to tweak the code so that it does not do this, or if there was a similar method I could use. I am limited to JavaScript, JQuery, and HTML. Any help would be appreciated! :)
Not sure what you mean; it works fine for me. Can you be more specific?
I can't reproduce the described behavior. Nevertheless, this is bad UI design. You should allow the user to enter whatever it wants (letters, symbols) and then run a validation for a number. The current kind of treatment can have unexpected side-effects (as you describe) and, worse, may leave some users disturbed, even angry, because when they type, their keyboard won't work ("damn website!", they shout). Believe me, this is way more frequent than the most of us thinks it is.
I got rid of the code above and ended up using a JS funtion. I hope this helps someone with the same issue!
$("#medianSalary").keydown(
function(event) {
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();}
});
});
Meh, there's no reason to allow a user to enter known-bad data. If I was doing client-side validation anyway, why let someone enter a letter for a US Social Security Number? There's no reason to delay feedback--as long as there's feedback, e.g., a fading warning about accepting only digits etc.
@user3784596 I think you should validate the value after filling the form. There are easy ways to do that.
Like you can use input type number.
What is problem with that?
I did that at first but that the request of the client I had to simply not allow anything else in the field to be typed at all.
I found a solution for my issue. I got rid of the code above and ended up using a JS function. I put in within my $(Document).ready(function() I hope this helps someone with the same problem!
$("#medianSalary").keydown( function(event) { if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault();} }); });
| common-pile/stackexchange_filtered |
Automate Dbeaver SQL Export
Dbeaver recently pushed an update to allow you to code an export. The documentation lists the export function as
@export {"type": "csv", "producer": {...}, "consumer": {...}, "processor": {...}}
I'm not sure how to format this to get the code to run. The JSON text in the documentation looks like the following:
{
"type": <ID of the processor>,
"producer": {
<producer settings>
},
"consumer": {
<consumer settings>
},
"processor": {
<processor-specific settings>
},
}
I'm aiming to get the code to output data to a folder and file name. The associated IDs are outputFolder and outputFilePattern which belong in the consumer settings. I've tried various permutations to get this to work, but receive errors like unterminated object at outputFolder, expecting ':' at outputFolder, invalid syntax, etc. The most obvious permutation is:
@export {"type": "csv", "producer": {}, "consumer": {"outputFolder": "C:\downloads", "outputFilePattern": "Data"}, "processor": {...}}
This returns the error 'invalid escape sequence at column 52 path $..outputFolder'. If you don't put quotes around outputFolder it returns the same error.
https://dbeaver.com/docs/wiki/Export-Command/#Producer-Settings
I realise I am quite late to the party on this one.
Try changing the direction of the "" to a forward slash '/' Or escape the backslash \
I have tried both and it appears to be successful in Win 11 environment.
Thanks for your reply. I did figure this out somewhat recently. The issue now is that you're only able to export one query at a time and still need to click through the export GUI. I have filed a ticket on the Dbeaver community page.
| common-pile/stackexchange_filtered |
glassfish servlet: how to know the referer url? if possible
with the HttpServletRequest object, we can have the getRequestURL, which shows the ressource requested, but in my case I would like to know from where the request comes:
I tried also getRemoteAddr() and getLocalAddr() that prints my local IP, (as I am running glassfish and small webserver that talks to glassfish locally.
but the IP doesn't show the full referer, that should be in my case
http://my.domain.com/wiki/aPage
from my IP I can resolve to http://my.domain.com, yet not the full url
Does this mean I need to send also "wiki/aPage" in the request, or I hope there is a better possibility?
thanks
You can read the Referer header of the request and get the value by using request.getHeader("Referer");
@Philipp Reichart, that was typo.Thanks.
| common-pile/stackexchange_filtered |
Can pytest be made to fail if nothing is asserted?
Today I had a failing test that happily succeeded, because I forgot a rather important line at the end:
assert actual == expected
I would like to have the machine catch this mistake in the future. Is there a way to make pytest detect if a test function does not assert anything, and consider this a test failure?
Of course, this needs to be a "global" configuration setting; annotating each test function with @fail_if_nothing_is_asserted would defeat the purpose.
So, you want to test the tests? I see a recursive problem coming up.
And what would happen with the exception raising testing that does not use the assert?
@IgnacioVergaraKausel If the exception is expected, it is being tested for, so it's a kind of assert. If it's not expected, then it's obviously a test failure.
@KlausD. The tests are already being "tested", in the sense that they must be valid code, and produce green. This would just be a small additional sanity check. I have worked with a testing framework that did this out of the box, although I don't remember which it was.
This is one of the reasons why it really helps to write a failing test before writing the code to make the test pass. It's that one little extra sanity check for your code.
Also, the first time your test passes without actually writing the code to make it pass is a nice double-take moment too.
Good point. Imagine, for argument's sake, that some hypothetical person would hypothetically, every now and then, write tests after writing the implementation. Any resemblance between this hypothetical person and any existing person, living or dead, is of course pure coincidence.
@Thomas I think I know this hypothetical person! To be fair, I did actually have a quick poke around Pytest to see if it was possible, because I am very guilty of post-testing myself a lot of the time.
| common-pile/stackexchange_filtered |
Weird phenomenon with the perfect squares of numbers under 14.
In math class (algebra 1), a classmate of mine realized this weird thing when asked the square or 21. In her head, knowing that $12^2$ = 144, she said 12 flipped is 21 so 144 flipped is 441, which is, in fact $21^2$. This doesn't work once you go past 14.
More examples
(0)$1^2$ = (00)1 and $10^2$ = 100
$13^2$ = 169 and $31^2$ = 961
Why does this happen? Why doesn't it happen above 14? Are there other places this might work?
This just works for (some) small numbers because there is no carrying involved. It also works for longer numbers, like $112, 211$ or even $1112, 2111$ where no carrying is involved.
Just a random comment: this was one of the first observations I made as a kid that got me into learning basic number theory! It's a great field.
I think you meant $441$ where you wrote $442$.
Welcome to Mathematics Stack Exchange! A quick tour will enhance your experience. Here are helpful tips to write a good question and write a good answer. For equations, please use MathJax.
Any number only consisting of digits 0, 1, 2 & 3 and the sum of its first n digits being less than or equal to 2 + n will posses this property.
For example 23021, this number will not posses this property because the sum of the first 2 digits is 5 which is greater then 2 + 2 here n = 2
And the number 22021 will posses this property as it follows all the condition
For numbers ending with 0 like 2020
2020 ==> 0202
2020² = 4080400
The square of 0202 must be considered as 0040804
| common-pile/stackexchange_filtered |
Format of DateTime field not recognized by Spring
I am developing web application using Spring 3.2.4. I have some forms with fields containing date and time. Piece of my jsp:
<form:form method="post" action="/add" modelAttribute="licence">
...
<form:input type="datetime" path="beginDate"/>
<form:input type="datetime" path="endDate"/>
<form:input path="quantityLimit"/>
...
</form:form>
Normal form, nothing fancy. I am using datepicker, which gives me date in format yyyy-MM-dd HH:mm, so I've added this to my controller:
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
dateFormat.setLenient(true);
webDataBinder.registerCustomEditor(DateTime.class, new CustomDateEditor(dateFormat, true));
}
Also, I have added <mvc:annotation-driven/> to my servlet configuration xml, as stated on some blogs.
There's target controller:
@RequestMapping(value = "/{softwareId}/licence/add", method = RequestMethod.POST)
public String addLicence(@PathVariable("softwareId") Long softwareId, Licence licence, Model model) {
Software software = softwareRepository.findOne(softwareId);
licence.setSoftware(software);
licenceRepository.save(licence);
return ADMIN_PATH + "softwareEdit";
}
And software class looks like this:
@Entity
@Table(name = "licences")
public class Licence {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "begin_date")
private DateTime beginDate;
@Column(name = "end_date")
private DateTime endDate;
@Column(name = "quantity_limit")
private Long quantityLimit;
@ManyToOne
private Software software;
//getters, setters, etc.
}
The problem is: when I submit my form with dateTime field empty it works perfectly, but when I have anything in date field (no matter if it's properly formatted or not) I get HTTP Error 400: Bad Request. No exceptions in console, only bad request, but I am pretty sure it has something to do with date parsing.
Is there a well described method of dealing with date and time fields in forms in Spring applications?
Set your logging to DEBUG. Spring will tell you what's up. Also, show us your command class.
Use firebug and see the "Net" tab and see the outgoing parameters, you might get some clue.
So, logging on DEBUG level shows literally nothing when form has been sent.
Also, net tab in Chrome, Firefox and Safari shows normal POST with all fields.
That's not possible. Check your loggers. Spring will always log something when it responds with 400.
Make your life simple and use @DateTimeFormat, getting rid of your WebDataBinder configuration. It seems CustomDateEditor only works with java.util.Date and Spring has no other (default/not-specified) mechanism to convert from a String to a DateTime.
@DateTimeFormat is such a mechanism.
@Column(name = "begin_date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
private DateTime beginDate;
| common-pile/stackexchange_filtered |
The particle size distribution in this exposure tells us we're looking at classic wind-sorted material - notice how consistently it sits in that 20 to 60 micrometer range.
But the question is whether this accumulated rapidly or slowly. Look at these darker bands - they suggest periods when soil formation outpaced deposition.
That's the key insight about loess formation. When sedimentation rates are high, the wind keeps dumping material faster than pedogenic processes can alter it. But during slower periods, weathering penetrates deeper into previously deposited layers.
The source material matters too. This thickness suggests we're dealing with glacial-origin loess rather than desert loess. The Missouri | sci-datasets/scilogues |
Retain root privileges during long processes
I have a bash script that makes a backup of my data files (~50GB). The script is basically something like this:
sudo tar /backup/mydata1 into old-backup-1.tar
sudo tar /backup/mydata2 into old-backup-2.tar
sudo rsync /mydata1 to /backup/mydata1
sudo rsync /mydata2 to /backup/mydata2
(I use sudo because some of the files are owned by root).
The problem is that after every command (because it takes a long time) I loose root privileges and if I'm not present at the computer then the su prompt gets timed out and the script ends in the middle of the job.
Is there a way to retain su privileges during the entire script? What is the best way to approach this situation? I prefer to run the script under my user.
Put your commands without sudo in a script and run your script with sudo.
I actually though about this and if there won't be any other elegant way to do it, this would be the method I'll choose, thanks
Configure sudo on your system to allow those commands to run without a password.
Alternative solution here that keeps resetting the timeout... https://serverfault.com/a/702019
With a second shell:
sudo bash -c "command1; command2; command3; command4"
What's the difference between this and running the script with sudo?
With this variant you can save the sudo with every call of the script.
Perhaps like this:
#!/bin/bash -eu
exec sudo /bin/bash <<'EOF'
echo I am $UID
whoami
#^the script
EOF
Alternatively, you could put something like:
if ! [ $(id -u) -eq 0 ]; then
exec sudo "$0" "$@"
fi
at the top.
The first approach has issues if "the script" itself tries to read from standard input, as bash is already reading the script itself from that file handle.
| common-pile/stackexchange_filtered |
Resizing Photoshop CS6 from 30" Cinema display to 21" iMac (OS 10.8.5)
I am using old Photoshop CS6 on 21" iMac (OS 10.8.5) with 30" Cinema display. When I take only my iMac on a trip, if I had Photoshop sized for the 30" display, the bottom right of the workspace runs outside the 21" active monitor. How can I resize it to fit without having the 30" to do it?
Long time since I've seen Mountain Lion or CS6... I'm presuming you can't see the red/yellow/green dots at top left of the window?
If you can, the green dot will resize it.
If you can't, Opt ⌥ Shift ⇧ & drag any visible window edge will resize the entire window equally [I hope that functionality existed at 10.8]. Once you can see all 4 sides, you can then drag them out to the correct edges again individually if needed.
If that doesn't work, see if the window will just drag down the screen - I've known the title bar with the dots to hide itself under the menu bar, which most Mac Apps can't do.
Thanks. One more thing: I do not remember what I did, but I was able to shrink the workspace to the exact size of the drawing, but now it stays like that. I prefer being able to have the workspace larger than the drawing (how it originally was). Do you know how to undo what I did?
cmd/0 [zero not 'oh'] will size to viewport. btw - If the answer helped, please mark it as 'accepted' with the check/tick mark & give it an upvote too ;-)
| common-pile/stackexchange_filtered |
Is there a limit on how many questions can be asked in a given time frame?
I'm new to the site, and part of a group that is relatively new to Pathfinder. I've been asking a lot of questions (I think, anyway) and I can't help but wonder if I'm breaking a rule. I have more questions to ask, but I'm worried about getting banned or the like.
Good question. In general we ask you to use common sense. Let these 5 questions get real answers and then move on. I would suggest that you don't have more than 3-4 active at any given time.
Could you define 'active,' please? Would that imply that I've chosen an answer, or that people have stopped giving answers?
@Zach: A good definition would probably be "on the first page if you sort by by active questions".
Active = on first page with an unaccepted answer. We recommend that you wait 24 hours or so before accepting, cause not everyone obsessively watches this stack.
| common-pile/stackexchange_filtered |
Ubuntu 12.10 64 bits not booting on a Dell Inspiron 15z Puissance (French) in UEFI mode
When trying to start Ubuntu from my USB key in UEFI mode (it works in Legacy mode, but I have to keep Windows) on a Dell Inspiron 15z , Grub starts, but when I choose any option, I get a black screen and my USB key stop teling me it is being read.
EDIT: when using the legacy mode and trying to install Ubuntu, I get a blank partition table with Ubiquity…
… and a very strange partition table from GParted (I have a hybrid 32Go SSD + 500Go HDD disk) :
Thanks everyone, I have found the solution, I had two problems:
Ubuntu didn't want to boot in EFI mode, except when the firmware was set to Legacy (and let me boot using EFI ¿).
I just clicked "Fix" in all the question screen-shots and then, GPARTED let me change everything I wanted and Ubiquity let me install Ubuntu !
The installation has just finish and I'm going to reboot now.
Those partitioning errors suggest that you've either got a damaged partition table or you've got a system that's confused about RAID options. The latter seems more likely. Either the disk was partitioned with RAID features active but you're reading it in Linux with RAID inactive or vice-versa. Either way, you should work to get the RAID situation sorted out. Check the options in the firmware and in Windows related to RAID. If it's active, you probably need to ensure that the dmraid package is up and running in the Ubuntu installer; if not, you need to uninstall it, and you may need to remove stray RAID data. I'm afraid I don't have more detailed references handy, but some Web searches should turn up more information.
Concerning your inability to boot in EFI mode, I'm not entirely sure what's going wrong, although it could be related to Secure Boot. You could try disabling this feature in your firmware. (Ubuntu 12.10 supposedly includes Secure Boot support, but this feature is brand-new and may yet be buggy on some systems.) It's also possible you're running into a GRUB bug. Note that it is possible to install Ubuntu in BIOS/legacy mode and then switch the boot mode. For greatest flexibility, I recommend you create a separate FAT, ext2fs, ext3fs, or ReiserFS /boot partition when you install. This will make it relatively easy to experiment with certain boot loaders and boot managers, such as rEFInd, gummiboot, and ELILO. All of these boot programs require that the kernel be readable by the EFI, which can be arranged if the kernel is on a FAT, ext2fs, ext3fs, or ReiserFS partition. (For anything but FAT, you'll need filesystem drivers that ship with rEFInd.) You can install one of these programs from Windows and configure it to boot your Linux kernel in EFI mode, which can simplify the process of converting from a BIOS/legacy-mode boot to an EFI-mode boot.
I disabled Secure Boot, and I have the same problems.
I'm running this laptop with Ubuntu GNOME 13.04.
The first step is to disable SSD as a cache from Windows, using Intel Matrix Storage software. Yes, it can't be done through the firmware. Without that, you won't be able to use more than 8GB on the SSD.
If you want to boot automatically in UEFI, you need to disable Legacy. Currently, Linux is hitting bug with the NIC card in full UEFI mode, so you have to disable it. Once you booted Ubuntu in UEFI mode, you'll notice you wont have sound either.
That's a trade off. I suggest you to keep using legacy mode until full support is here.
Regards,
Now, it's good… No more problems, even the sound works… I didn't have to "disable SSD as a cache from Windows". But I can't use 8 GB of the disk (32-8=24GB allowed, not just 8). For the sound, let me time to found the answer again…
Which version are you using ? I reverted the modification I did with 12.10 to get the sound working, and it's still working with 13.04. (I added "options snd-hda-intel model=ref" in "/etc/modprobe.d/alsa-base.conf".)
I'm using 12.10 with kernel 3.8 in Legacy mode.
| common-pile/stackexchange_filtered |
Don't show job descriptions writing in languages the user cannot read
At the moment when you live in the Netherlands, Stack Overflow Jobs will show jobs from Germany, while this is fine, this creates the problem of Stack Overflow jobs assuming that I understand the German language.
An example here:
The job description should either be translated to English, or the job should be hidden from view.
This post is not a duplicate of Provide option to filter jobs by natural languages as that post talks about the mail from jobs, but my post is about the jobs recommendations you get as advertisements.
If you cannot read German, it seems unlikely that you would be a good candidate for that job. So not displaying these jobs at all would be more sensible than translating them, only to hide the surprise.
@CodyGray I have to disagree with that, inside the company where I work there are multiple people who cannot read or write Dutch, and we communicate in english with them
Thank you for your feedback. You raise an excellent point: seeing content in a language you don't read isn't useful.
We have explored some options for language-tagging job postings and using info from, say, your browser to determine which jobs to show you. There are a number of complexities in this approach, and it's not a project that has made it to the top of the priority heap just yet. Occasionally, employers post job listings in multiple languages, so that's another wrinkle.
We prefer to show you only relevant jobs, and we're always looking for ways to improve how we do so. Feedback like yours helps us know what to prioritize, so thanks again.
| common-pile/stackexchange_filtered |
How to correctly recreate sklearn (python) logistic regression predict_proba outcome for a binary classification
I have tried to recreate the outcome from sklearn's logistic regression predict_proba using the logistic/sigmoid function. However, I end up slightly off with my result. I am only looking at a binary classification (yes/no) and not multiclass.
After fitting the model I get the following weights (where the first weight is the Intercept):
print np.transpose(model.coef_)
>>>
[[-0.19727816]
[ 0.53109229]
[-1.31937397]
[-0.98187463]
[-0.3479746 ]
[-0.54423188]
[ 0.36497145]
[-0.15778131]
[-0.21998587]
[-0.35944243]]
If I then use predict_proba on a test case I get the following outcome (again, the first "1" in the test sample represents the Intercept):
test_sample = np.array([1, 0, 1, 0, 1, 0, 0, 0, 1, 1])
print model.predict_proba(test_sample)
>>>
[[ 0.9334748 0.0665252]]
However, when I then try to recreate this outcome using the logistic function I get a slightly different result:
new_profile = test_sample*model.coef_
print np.transpose(new_profile)
>>>
[[-0.19727816]
[ 0. ]
[-1.31937397]
[-0. ]
[-0.3479746 ]
[-0. ]
[ 0. ]
[-0. ]
[-0.21998587]
[-0.35944243]]
np_sum = (new_profile).sum()
score = 1/(1+np.exp(-np_sum))
print score
>>>
0.0798743821296
I get ~8% instead of 6,6%, most likely because I am missing a step in my calculations.
I know that in the multiclass example you should do normalization:
score /= score.sum(axis=1).reshape((-1, 1))
However, this does not work as I am just using a binary classification with 1 outcome!?
Can anyone spot what step am I missing in order to correctly calculate the same outcome as the predict_proba?
I suggest looking through the LinearClassifierMixin class here
I think you just pointed me to the right place! I ended up with a dead end looking for that _predict_proba_lr which is part of the LinearClassifierMixin! Thanks a lot.
Have you added new_profile = test_sample*model.coef_ + self.intercept_
| common-pile/stackexchange_filtered |
PyCharm: How to run with prompt for params?
I am parsing the command line arguments in my Python code:
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--epochs', type=int, default=50)
parser.add_argument('-ts', '--train-size', type=int, default=None)
parser.add_argument('-ti', '--title', default=None)
args = parser.parse_args()
So everytime I run the Python file I am able to specify title and other things I need. But since PyCharm needs run config to run, I have to manually edit run configs and save everytime I want to run.
Is there way hack to make this thing pop-up just before I run the experiment?
One simple way is to use the terminal from inside and just run the script with args like I do in command prompt, but I lose other configuration like the env vars, Python interpreter, conda environment, etc., when I'm doing this.
Not currently possible, please vote for IDEA-74031 and linked tickets to be notified on any progress with this feature (currently planned for the next major release)
Well ... user can tick Show this page option in specific Run/Debug Configuration ... so IDE will show Configuration and user can edit any info before actually executing it. I strongly believe OP wants this rather than some variables in Configuration...
This is possible now because run configuration parameters can include Jetbrains Macros, one of which triggers an input prompt. There are some limitations:
there is no label for the prompt
you can add multiple prompts, but since they aren't labelled you would have to remember the order you added the $Prompt$s in, since that will be the order they pop up when you run your Run Configuration.
How should parameters be entered in the prompt? using the syntax --parameter-name parameter_value --another-parameter another_value does not work for me
| common-pile/stackexchange_filtered |
Will we write all the code in views python file?
I'm just learning Django. My English is not good, I apologize in advance.
Can't I create separate files for each view, such as Codeigniter or Laravel?
Do I have to write the codes of all pages in a single file? This is very difficult and complicated for me. There will be thousands of lines of code. Is there a good way?
No, you can make a separate file for each view. But it is not very "Pythonic" to do that in the first place. The same holdss for 1000 lines of code. Usually that amount means some modeling is not entirely correct.
for example: loginView.py blabla function and codes...... homeView.py blabla function and codes...can't?
you can perfectly do that. But it is more "Java" and "C#" to do so. Note that Python supports the OO paradigm, but it is not an OO programming language.
Thank you Willem, so Is there an example?
first of all, I think you're using function-based views
but you should use class-based views
https://docs.djangoproject.com/en/dev/topics/class-based-views/
secondly, following this guide will help you splitting your view into multiple files
https://simpleisbetterthancomplex.com/tutorial/2016/08/02/how-to-split-views-into-multiple-files.html
| common-pile/stackexchange_filtered |
2007 Hyosung GT250R not starting, some repairs have been made
Hoping to find some good advice on fixing my (above mentioned) motorcycle. I'll try to keep it brief but with as much details as I can.
I had an issue with the bike and it sucked up some varnish from not properly winterizing the bike. I've since cleaned and used repair kits off ebay for the carburetor, siphoned out the old gas and replaced the gas filter. I've also had the battery on a trickle charger and had it tested twice by two different stores (both reported the battery is fine).
When I tried to start the bike after the first round of fixes, it started to crank over with some throttle but didn't fire up and assumed that the engine may have flooded. So it was left for a few hours and on return after starting it sounded like the battery was dying. Now I'm at a point where the solenoid only clicks once when the start button is pressed. I've replaced the solenoid with a brand new one and I still haven't had any luck starting the bike.
I have also tried bridging the solenoid to try and start the bike that way as well but with no luck. I'm not entirely sure what's wrong with the bike any more and I'm trying to save myself the money by going to a repair shop. Any help would be greatly appreciated.
Thanks everyone!
Edit: Added the year in the title
It sounds like the battery is flat. Could you check the voltage with a multimeter? If it's low, this tells me that something is draining the battery, in which case you'd want to try to narrow down what is causing the parasitic draw
Can you throw in the model year as well. There's some profound differences between years if it's not the battery as @Zaid has eluded to........although he is probably correct.
@Zaid, I'll certainly check the battery with the multimeter when I can get my hands on one. Thanks for the advice.
I've also had the battery on a trickle charger and had it tested
twice by two different stores (both reported the battery is fine).
Batteries can report to be fine but still not work. This really seems like a bad battery. Do the following test with a multi-meter:
Hook the meter leads to the appropriate pole
Try to start the engine
Look at the meter and make note of the reading
If the battery reads anything less than 11.5v it will need replacement.
Another thing to look for is a voltage drainage. Measure the battery volts before hooking it up to the terminals. Then take another reading. There should be no real difference in the readings. If you see a difference of more than .2V then you have a short that is consuming power. Go to the fuse box and start pulling fuses one by one to see where the power is being consumed from. Then track down the wiring for that fuse and try to find any nicks or bad parts.
| common-pile/stackexchange_filtered |
Resolution independent UNet implementation?
I'm wondering what's the easiest way to make a UNet model work with varying input resolutions? What I mean is that if I downsample 3 times, then with e.g. a 320x320 size image the spatial dimensions of feature layers will be:
320 -> 160 -> 80 -> 40 -> 80 -> 160 -> 320
On the other hand, if I input an image of size, say, 960x540, then I get
540 -> 270 -> 135(!) -> 68 -> 136(!) ->...
The network will blow up with such an input image, because the tensor sizes have a mismatch when concatenating the tensor from the skip.
Is there some standard trick for handling this?
You can resize the input image to the nearest multiple of 8 (while maintaining the aspect ratio). In such a case, dividing by 2 three times will have integer output every time. Might not be a standard trick, but it should work.
Yeah, I guess if I choose e.g. reflection padding of the input and then remove that from the output, then it should work OK.
I meant resize using something like opencv's cv2.resize function. So, it will resize the image using bilinear interpolation I think. So, your image looks like the original one, just the size changes.
That won't work on images that are highly rectangular, since the change in aspect ratio will e.g. prevent the network from recognizing common objects. However, padding to a size that can handle the downsampling (i.e. make dimensions divisible with the right numbers) and then removing the padding from the output seems to work.
| common-pile/stackexchange_filtered |
Java classpath command line with opencsv writer
How to include all jar files in Java? I'm using command prompt.
My jar files is stored on C:\test\java
jarfiles is:
commons-io.jar, commons-lang.jar, opencsv.jar
And my java program is also stored on C:\test\java
I've searched on google but it seems I cannot find the proper way of using classpath.
I'm currently on C:\test\java and using this command
javac -cp ".;commons-io.jar;commons-lang.jar;opencsv.jar;" JavaTest.java
And it's compiling successfully but when I run my java program with this line
Java JavaTest
I'm having a error with the opencsvWriter.
Exception in thread "main" java.lang.NoclassDefFoundError: au/com/bytecode/opencsv/CSVWriter
I cannot determine if classpath is wrong or on the writer is wrong.
Thanks in advance!
What happens when you try adding the same -cp as in your Javac command to your Java command?
WTH! It works! You're awesome!
;) cool. I'll make it into an answer then
The javac command will not link togther libraries into a single executable file unlike how the c/c++ linker can with object files. Instead, you have to specify the same classes in your classpath when you go to run the compiled java file:
java -cp ".;commons-io.jar;commons-lang.jar;opencsv.jar;" JavaTest
You could optionally bundle all of the files into a single jar, and then specify your classpath inside the manifest file located in the newly created jar.
Some additional reading on that here:
Reference jars inside a jar
| common-pile/stackexchange_filtered |
Translation of Ex. 4:8–9
Sh'mos 4:8–9:
וְהָיָה אִם לֹא יַאֲמִינוּ לָךְ וְלֹא יִשְׁמְעוּ לְקֹל הָאֹת הָרִאשׁוֹן וְהֶאֱמִינוּ לְקֹל הָאֹת הָאַחֲרוֹן.
וְהָיָה אִם לֹא יַאֲמִינוּ גַּם לִשְׁנֵי הָאֹתוֹת הָאֵלֶּה וְלֹא יִשְׁמְעוּן לְקֹלֶךָ וְלָקַחְתָּ מִמֵּימֵי הַיְאֹר וְשָׁפַכְתָּ הַיַּבָּשָׁה וְהָיוּ הַמַּיִם אֲשֶׁר תִּקַּח מִן הַיְאֹר וְהָיוּ לְדָם בַּיַּבָּשֶׁת.
I've always understood this as:
(And) it will be that if they won't believe you... then they will believe....
And it will be that if they won't believe... then you shall take....
That seems like the most obvious translation. The JPS chumash, however, has (with emphasis supplied):
And it shall come to pass, if they will not believe thee, neither hearken to the voice of the first sign, that they will believe the voice of the latter sign.
And it shall come to pass, if they will not believe even these two signs, neither hearken unto thy voice, that thou shalt take of the water of the river, and pour it upon the dry land; and the water which thou takest out of the river shall become blood upon the dry land.
Note the difference between the translations: Mine has an overarching "will be" governing an if-then statement. The JPS's, on the other hand, has the "will be" ("shall come to pass") logically attached to the "then", with the "if" clause parenthetical: logically, its translation is the same as:
And, if they will not believe thee, neither hearken to the voice of the first sign, it shall come to pass that they will believe the voice of the latter sign.
And, if they will not believe even these two signs, neither hearken unto thy voice, it shall come to pass that thou shalt take of the water of the river, and pour it upon the dry land; and the water which thou takest out of the river shall become blood upon the dry land.
The effect, of course, is the same (if the people don't believe, then Moshe pours the water); but how it's presented is different: what it is that's "coming to pass" (will be) is different.
(L'havdil, Christian translations that translate "והיה" generally do so to match the JPS's, though the Witnesses' matches mine. Translations that don't render "והיה", like some Christian ones and, l'havdil, Rabbi Kaplan's, don't have to choose between the JPS's translation and mine.)
My question is whether there's any source to support either translation.
It's a bit illogical to have an "it will be" on an event that's only an "if", so I would think that the "it will be" in both translations are supporting the latter clauses.
@YDK, I think both ways make sense logically. Either "if X then it will be that Y" or "it will be that {if X then Y}".
On Deut. 21:14, where we have the same ...והיה אם... ו formulation (about the husband of the yefas toar hating her and sending her away), Rashi comments (from Sifri) that "the verse is predicting that you will end up hating her." So in that case, at least, the "it will be" refers to both the אם clause and its outcome. (If the אם clause was parenthetical - "It will be, if you don't like her, that you shall send her away" - then that's like any other conditional, not a certainty. By contrast, if we translate, "It will be that if you don't like her, then you shall send her away" - that brings out more clearly that the "if you don't like her" is a guaranteed outcome ("it will be").)
On the other hand, in Zech. 6:15 the usual order is inverted, with the result ("People from far away will come and build Hashem's palace...") preceding the condition ("והיה אם you listen to the voice of Hashem your G-d"). The commentaries there say that והיה refers back to the first half of the sentence - i.e., "People from far away will come..., if you listen..." Which would make the condition parenthetical, as in the JPS translation of the verses in Shemos.
Generally, though, it probably does make more sense to assume that והיה covers both halves of the sentence. This would contrast with verses in which אם precedes והיה, like Gen. 32:9 and Lev. 25:28. (Although it is true that in neither of those cases is there another verb following והיה, unlike in the verses under discussion.)
Thinking further about this, another proof for your translation (that והיה refers to both the condition and the outcome) might be this: When והיה is followed by an auxiliary verb, then that second verb doesn't have a ו (for example, והיה הוא יהיה לך לפה, Ex. 4:16; והיה הוא ותמורתו יהיה קדש, Lev. 27:10 and 33). Here, by contrast, the outcome (והאמינו לקל האת האחרון or ולקחת ממימי היאר) is introduced with a ו, as are other places where you have "והיה X, then Y." This seems to me, then, to indicate that in this case the outcome is not a continuation of והיה, but of the condition.
+1. The proof from Deut. is based on the fact that Rashi quotes both the v'haya and im lo...? If not, I don't get the proof; would you mind explaining? Rashi to Zech. seems strongly to say the "if..." is parenthetical (though as you note it's a different sentence structure than the usual and ); many thanks for finding that. The verses in Gen. and Lev. seem to be using "והיה" with an explicit subject which is not a clause, respectively the second camp and the item sold, so would not seem to be relevant here. Unless I'm missing something....
@msh, about Deut., the point is that Rashi seems to be taking והיה as definitive: "it will most certainly happen that you will hate her..." If אם... בה was parenthetical, that wouldn't work. And about the last two cited verses - not sure what you're saying: isn't the והיה in each of those serving the same syntactic function as the first והיו in Ex. 4:9? All three of them are introducing something that will happen to the noun: "the second camp will be saved," "the sold property will remain in the buyer's possession," and "the water... will become blood."
Still don't understand the Deut. proof. Sorry. As to Ex. 4:9, I agree. But והיה in Ex. 4:9 is different: it applies to a clause, not a thing.
והיה is and it was in simple translation.
But in the Bible language, (an antique language), it is exactly like - if !!!
I mean:
והיה אם=IF / and it was that if = IF
| common-pile/stackexchange_filtered |
How to uncheck checkboxes on a button click?
I have the following 3 input checkboxes, after checking the checkboxes, I would like to clear all the checked items after the "Clear Checkbox" button is clicked. I attempted the following but it doesn't work.
Stackblitz working Example
app.component.html
<ul *ngFor="let d of data">
<li>
<input id="checkbox" type="checkbox" class="checkbox" />
{{ d }}
</li>
</ul>
<button (click)="myFunction()">Clear Checkbox</button>
app.component.ts
export class AppComponent {
data = ['tea', 'coffe', 'soda'];
public myFunction() {
(<HTMLInputElement>document.getElementById('checkbox')).checked === false;
}
}
Try <HTMLInputElement>document.getElementById('checkbox')).checked = false, With ===, you are making a comparison.
@T.Trassoudaine my bad, now it works but only changes value to one item
Yes because you are selecting by id, you can't have several HTML elements with same id, use class instead. Nimitt Shah answer gives details.
You should really investigate the Angular Way of doing this. This implementation will cause you headaches eventually..
I would do it in an angular fashion and use ViewChildren instead. So attach a ref to your checkboxes and access them with ViewChildren, as this would be a perfect case for that. So I attached chkboxes to the input
<input #chkboxes id="checkbox" type="checkbox" class="checkbox" />
I define the querylist:
@ViewChildren('chkboxes') chkboxes: QueryList<ElementRef>;
and to uncheck I loop the elements and set them to false:
myFunction() {
this.chkboxes.forEach(x => x.nativeElement.checked = false)
}
DEMO
You can use document.querySelectorAll() to uncheck all the checkboxes.
StakBlitz Working Example
In myFunction, you code should be as below:
document.querySelectorAll('.checkbox').forEach(_checkbox=>{
(<HTMLInputElement>_checkbox).checked = false;
});
Also, make sure you are assinging false value (=) not checking (===)!
You still should make sure the id of the checkboxes are not all the same.
yea, I am not using id
In the question and in your StackBlitz example, all the checkboxes have the id checkbox.
| common-pile/stackexchange_filtered |
Procedure in PL/SQL with create and cursor
Can we have a Procedure with
First create a table suppose
create table INCOME_GROUP(income_compare_groups varchar(100)) ;
Then insert data into this table.
insert into INCOME_GROUP values (10-20);
Then Use this table into a cursor.
CURSOR c1 IS(select *from INCOME_GROUP);
For Example I am doing this.
BEGIN
create table INCOME_GROUP(income_compare_groups varchar(100)) ;
DECLARE
CURSOR c1 IS(select * income_Group);
BEGIN
FOR acct IN c1 LOOP -- process each row one at a time
INSERT INTO temp_test
VALUES (acct.income_compare_groups);
END LOOP;
COMMIT;
END;
END;
But I am getting some Error.
ORA-06550: line 2, column 4:
PLS-00103: Encountered the symbol "CREATE" when expecting one of the following:
( begin case declare exit for goto if loop mod null pragma
raise return select update while with <an identifier>
<a double-quoted delimited-identifier> <a bind variable> <<
continue close current delete fetch lock insert open rollback
savepoint set sql execute commit forall merge pipe purge
After reading the comments I tried this -
BEGIN
EXECUTE IMMEDIATE 'create table INCOME_GROUP
(
income_compare_groups varchar(100)
)';
DECLARE
CURSOR c1 IS
(select * from
INCOME_GROUP
);
BEGIN
FOR acct IN c1 LOOP -- process each row one at a time
INSERT INTO temp_test
VALUES (acct.income_compare_groups, null);
END LOOP;
COMMIT;
END;
END;
But seems it is not creating table.!!!!
You cannot run DDL statements (create) in a procedure directly. You need to use dynamic SQL.
Update question with errors you are getting.
@a_horse_with_no_name could you please elaborate how to use dynamic sql because i am new for procedure programming.
@Bishan Done with the required!!!
See the manual for details on how to use dynamic SQL: http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/dynamic.htm#LNPLS011
It must be like this:
DECLARE
cur SYS_REFCURSOR;
v_income_compare_groups VARCHAR(100);
BEGIN
EXECUTE IMMEDIATE 'CREATE TABLE INCOME_GROUP(income_compare_groups VARCHAR(100))';
OPEN cur FOR 'SELECT * income_Group';
LOOP
FETCH cur INTO v_income_compare_groups;
EXIT WHEN cur%NOTFOUND;
INSERT INTO temp_test VALUES (v_income_compare_groups);
END LOOP;
CLOSE cur;
COMMIT;
END;
You have to use dynamic Cursor because when you compile the package then the table INCOME_GROUP does not exist yet and you would get an error at CURSOR c1 IS(select * income_Group);
However, there are several issue:
You will get an error if the table already exist. You have to check this first or write an exception handler.
The procedure is useless because you first create an (empty) table and then you select it - it will never select anything!
can we insert data also using execute immediate
If suppose i have table INCOME_GROUP with multiple column then how to iterate it.
You can put almost everything into EXECUTE IMMEDIATE '', include insert statements with several columns.
You can do it like this:
create or replace procedure cpy_inc_comp_grps
as
cur_1 sys_refcursor;
compare_group varchar2(100);
begin
execute immediate 'create table income_group(income_compare_groups varchar2(100))';
open cur_1 for 'select income_compare_groups from income_group';
LOOP
FETCH cur_1 INTO compare_group;
DBMS_OUTPUT.PUT_LINE('INSERT INTO temp_test VALUES (rec.income_compare_groups');
EXIT WHEN cur_1%NOTFOUND;
END LOOP;
close cur_1;
execute immediate 'drop table income_group';
end;
And test it with the following code:
begin
cpy_inc_comp_grps;
end;
You have to replace the dbms_output.put_line(...) part with whatever inserts you want to do.
If suppose i have table INCOME_GROUP with multiple column then how to iterate it.
FETCH cur_1 INTO compare_group, var_for_COLUMN2, var_for_COLUMN3, ...
And if you want to insert Data, just use the normal SQL statement INSERT INTO table_name VALUES (value1, value2, ...). You don't need execute immediate for the INSERT-statement
one more thing why this procedure is taking lot of time to execute!!
I don't know, it's executing pretty fast for me. Do you mean this example or your final statement?
Try this.
execute immediate 'create table INCOME_GROUP(income_compare_groups varchar(100))';
| common-pile/stackexchange_filtered |
Inheritance vs composition: How would you implement an "unordered list"? Subclass of list, or composition?
This came up at work and left me thinking about the best way to model this:
In Python, we have the built-in list container, which is a mutable sequence. Equality between two lists is defined as equality of all items in the list, in their respective positions.
Now a colleague felt the need to define a type that's a list for all practical purposes, except that two lists should be considered equal if they contain the same elements, in the same quantities, but in arbitrary order. Basically,
unordered_list_1 = UnorderedList([1,2,3])
unordered_list_2 = UnorderedList([3,2,1])
unordered_list_1 == unordered_list_2 # True!
The colleague solved this by inheriting from list and overriding the __eq__ special method:
class UnorderedList(list):
def __eq__(self, other):
if isinstance(other, UnorderedList):
return ordered(self) == ordered(other)
else:
return NotImplemented
In this form it runs into a gotcha, because the builtin python types such as list take some shortcuts with their special methods; the not-equal __ne__ special method does not just fall back onto the __eq__ special method, so you get the funny scenario where two of these unordered lists can both be equal and not equal.
I suggested inheriting from UserList instead, which is meant to be subclassed, or maybe from one of the collections.abc abstract base classes. Another colleague chimed in with the familiar "Favor composition over inheritance" advice.
I feel that composition in this case would lead to a lot of boilerplate delegation code:
class UnorderedListUsingDelegation:
def __init__(self):
self._list = list()
def __eq__(self, other):
if isinstance(other, UnorderedListUsingDelegation):
return ordered(self._list) == ordered(self.other._list)
else:
return NotImplemented
def append(self, item):
self._list.append(item)
# Basically def every method implemented by class list and write delegation code for it:
# pop, push, extend, __getitem__, __setitem__ and so on
So from that consideration, I feel like inheritance is exactly right here: A teeny tiny specialization of behavior.
But on the other hand: Is the UnorderedList actually substitutable for the list class? Not so sure here. If you do "normal" list operations, then you shouldn't notice whether you are using an instance of the list class or of the UnorderedList class. Inserting and retrieving of elements works just fine. On the other hand, you might get unexpected behavior when comparing lists:
list1 = UnorderedList()
list2 = UnorderedList()
list1.append(1)
list2.append(3)
list1 == list2 # False
list1.append(2)
list2.append(2)
list1 == list2 # False
list1.append(3)
list2.append(1)
list1 == list2 # True!
I guess what I'm after is some clarity on how broadly or narrowly the Liskov substitution principle should be applied. Or maybe the solution is something altogether different. Maybe we shouldn't put such a "hack" into the __eq__ special method and rather be explicit about what we're doing, by writing a function like
def sorted_equal(a, b):
return sorted(a) == sorted(b)
I assume the colleague is working with some framework that expects to be working with list objects but wants to inject this special way of comparing lists.
Are you sure that in the end {1,2,3} == {3,2,3}?
Been wondering if that was a typo myself.
Sorted-ness is an interesting quality; it is not just sorted vs. unsorted, but rather by what comparison function (or not sorted at all), which is difficult to encode in the type system. There are efforts to do that, for example see here: https://kataskeue.com/gdp.pdf
Sets have equality. I was expecting this to act like a set with cardinality.
Is there any benefit in defining a new container over just providing a new comparison function that sorts its two container inputs? If one of the goal is that "so that the container with modified behavior can be used in place of the built-in List", this is a kind of Liskov situation where you can use that "hack" to cause any other pieces of software to break (to become "hacked"), if that other software assumed that a List is a List with no unexpected behavior.
One argument that can be made in favor of defining a new container is that it can have a more efficient amortized runtime: the container can maintain both a List and a Map (hashtable) internally, so that the container all-members equality comparison can be performed on the Map with O(n), and maintenance of the Map (if based on hashtable) is nearly constant O(1) per element operation.
Also, just because List doesn’t use __eq__ to define __ne__ doesn’t mean UnorderedList cant.
It's a multiset.
@rwong while that's true, the given implementation certainly doesn't have that advantage.
@candied_orange Indeed we can define __ne__. That whole part of the question is a bit tangential; it was the "gotcha" that the colleague encountered that caused them to post about it on our Slack channel, and from there the discussion kicked off about how it should best be modeled...
In Python, we have the built-in list container, which is a mutable sequence.
Your new list is not a list according to Liskov. Your list is not a sequence, it is a Multiset otherwise known as a bag. Bags are equal if they contain the same elements in no specific order. There are several implementations already: google MultiSets in Python.
Don't forget about set which is built in. If your bag will only contain unique values.
A fatal flaw of that approach is that the equals method is not "symmetric":
For any reference values x and y, x.equals(y) must return true if and
only if y.equals(x) return true.
Consider when you have an instance unOrderedList and another standard python orderedList. They have the same elements but in different order.
unOrderedList == orderedList // true
but
orderedList == unOrderedList // false
This will break a lot of things in hard to debug ways.
It sounds like going with a single utility method is the way to go. But it should have a name. sorted_equal is named for the implementation. A name like contains_the_same_values puts the emphasis on the true purpose of the function.
| common-pile/stackexchange_filtered |
Is centrifugal force equal in magnitude to the centripetal force in the frame of a body undergoing circular motion?
I was working out the minimum tangential velocity required for a swing to complete a full revolution and assumed the centripetal force is equal to the centrifugal force, so that I could set the weight force equal to the formula for centripetal (i.e. net force 0 at the top so swing won't fall). I'm pretty sure the answer is correct but doubt my reasoning.
If you set your reference frame to be fixed to the swing (let's call the origin the pivot point of the swing), you are now dealing with a rotating reference frame.
In a rotating reference frame, all objects observe a centrifugal force that pulls them outwards from the origin. For any stationary object in your rotating reference frame (the seat on the swing), the sum of forces must be equal to 0. The name we've ascribed to whatever force is equal and opposite to the centrifugal force is "centripetal force".
In your case, this magical "centripetal force" is some combination of the tension in the swing's chain/rope and the force due to gravity acting on whatever is in the seat of the swing.
To answer your question directly:
Your thinking appears correct, but beware that centripetal force is only equal in magnitude to centrifugal force when the object it is acting on is stationary in your rotating frame. Furthermore, this case is what defines "centripetal force" in the first place.
And don't say "weight force" unless you're explicitly describing the apparent weight of an object (i.e. what the object "feels"; e.g. the weight on the seat of the swing). It can be confused with the weight of an object (force solely attributed to gravity).
Your reasoning should be improved. In an inertial system there are no centrifugal force. You may in that system speak about a centripetal force, which is not a real force but an expression for how much net force is needed for the object to perform a circular motion. You probably mean that the expression for the centripetal force should be equal to the physical force at hand, the weight force.
Centripetal force is a real force. Centrifugal force is an apparent force.
wgrenad - I try to tell students that the expression for the centripetal force $F_c=mv^2/r$ is not a real force, but rather an expression for how large force perpendicular to the orbit is needed. There is always som real force that create this, e.g. from a string or gravitational force.
| common-pile/stackexchange_filtered |
How to save string value to another string in c# Windows Applications
I have a user_name defined above in class Form1 : Form
And user_name is defined above as,
string user_name = "Rammy";
and i want to use this user_name in below line, but it is not executing, and giving error "A field initializer cannot reference the non-static field, method, or property".
string copyright_bottom_text = user_name;
Can someone please help with this? I am using visual studio 2012.
can you share your whole class code
move below line to a constructor or method
string copyright_bottom_text = user_name;
Compiler Error CS0236
Instance fields cannot be used to initialize other instance fields
outside a method. If you are trying to initialize a variable outside a
method, consider performing the initialization inside the class
constructor. For more information, see Methods (C# Programming Guide).
public class MyClass
{
public int i = 5;
public int j = i; // CS0236
public int k; // initialize in constructor
MyClass()
{
k = i;
}
public static void Main()
{
}
}
You probably try to access the user_name variable from a static method.
There are static and instance variables/methods. Static ones belongs to the class itself, and don't belong to instances created from that class. All instances an access the data through the class, but if you change it, it will change for all the instances -of course because it belongs to the class.
This is how it looks like:
class Something {
private static string StaticString = "I belong to the class";
...
//constructor
...
}
Then, when you make a instance of this class:
Something s = new Something();
You can't say
string x = s.StaticString;
because it belongs to the class "Something", not the instance "s".
You can say however
string x = Something.StaticString;
In your example, you try to reach a instance variable, from a static method. This is the opposite of the above:
the user_name is unique in each instance (say, You can have a instance with name Joe, a instance with name Robert, etc). But you try to use it on a class level. The class doens't know anything about instances created based on it.
It's like when you give your dog a name, all dog should be called the same. It's not working.
Try to use static string as user_name, so it will compile, but it won't be correct.
Instead, keep the variable as a instance variable (not static), and use it in instance methods (not static). Keep in mind that you CAN use static methods and variables in instance methods, but you can't use instance variables or methnds in static methods.
I hope that helped. :)
But OP is not using static method. It is a field initialzer
| common-pile/stackexchange_filtered |
What is the space of closed curves (regardless of scale)?
Consider the set of closed curves in $\mathbb{R}^2$ trough the origin and do the quotient by the following:
Two curves are equivalent if one can be reparametrized into the other
Two curves are equivalent if (the appropiate reparametrized versions) one is a scaled version of the other
I'm wondering if something is known about this space. What is its cardinality? Is there a standard topology? Does anything change if we only consider $\mathcal{C}^k$ curves for some $k\le\infty$? What if the regions enclosed by the curves are required to be convex?
I ask for the convex-differentiable case because I think it's really no different from the space of functions $f:[0,1]\to\mathbb{R}^2$ such that $f(0)=f(1)=0 (up to scale) and that space must be well understood.
Thanks in advance
| common-pile/stackexchange_filtered |
How can I prevent twine from wrecking spindle bearings in a mower?
I have a grasshopper 725D mower. This is a 3 blade ztr mower.
Blades are mounted on 1"shaft that passes through a pair of 1" x 2" x 1/2" bearings. Bearings rest on a step in the spindle case, and also have a sleave that supports the centres. The spindle housing is about 2.5" in diameter.
The blade is bolted with a 3/8" NCF bolt to the shaft. There is a metal washer between bolt and blade about 2" in diameter, and a fiber washer between blade and bearing.
In operation if you hit any plastic bailing twine it wraps tightly between the blade and spindle housing, then melts and moves into the space between the fiber washer and the bearing. There it destroys the bearing seal. Net result is a $200 repair about once a season.
I'm looking for ways to prevent the plastic from melting and getting into the bearing space.
One thought I had was to fabricate a metal cup that went between the blade and the fiber washer that covered the spindle housing. This would spin with the blade. However the top edge of this would have to have some clearance, and I anticipate that it would collect dust, mud, shattered dry grass. Not sure if this would be a win or not. I also worry about water collected there, as I frequently have to mow wet grass.
This must be a frequent problem in mechanical engineering -- running bearings in a hostile environment.
Pointers to any standard ways to deal with this.
I would install a drag rake under the front end of the mower to snag the string before it gets into the blades.
Failing that, I would replace the bearing with one that has a metal shield that won't melt like the urethane or neoprene shields will.
Also consider inspecting the mowed area for string before starting the job. it might take your assistant an hour to do so but if that costs you $25 then you still come out ahead.
while the spindle assembly is out of the mower deck I would also install a grease fitting into it so you can pump the insides of the spindle housing full of lube at the end of the season; this will prevent water from collecting inside it where it will ruin the spindle bearings.
Steel shields are a good idea however.
home-use mowers do not have spindles with grease fittings. Being a cheap engineer, I added them to mine so I wouldn't have them rust out on me. Up here, we use industrial mowers with great big trimmer string on tree farms; have you tried one of those? -NN
Mower is a grasshopper. 25 hp diesel. 20 yrs old is was $8000. Not a home mower.
Spindle housings already have grease fittings. As the area is a tree farm and twine is used regularly for staking trees, and the grass isn't mowed until about 6" high searching for twine is counter productive. The mowing area is about 10 acres Walking the area on ten foot grid strips = 4200 feet per acre. This adds about 4 hours to the job, and finds about half the twine. Rakes clog almost instantly with clippings or thatch.
You're on the right track. Many commercial mowers have a disk (like a saucer) that mounts below the blade, has two cutouts for the blade, and curves up to catch string and stuff. We have about 10 acres of ponds and a lot of sneaky fishermen. We mow about 150 acres each week, and can pull a drum full of fishing line out of our mowers over the course of a season. But we check and clean all the decks several times a week. I haven't changed a bearing in our '80s Toro 228D in ten years.
Couldn't get the image to load, so here's a link to a groundsmaster deck showing the disks -
https://cdn2.toro.com/en/-/media/Toro-Media-Sharepoint-Libraries/_Images/ProductCatalog594X694/7GaugeWeldedSteelDecksGM7200_SteelDecks,-d-,jpg.ashx?mw=600&mh=171&hash=C0058CCAB12B449FE2D4495937D6F99BA6C8EFA7
[edit] Jinxed it—I threw a shaft bearing on the 228 yesterday.
| common-pile/stackexchange_filtered |
SVN Merge Between Sibling Branches
In SVN I have two branches, 1.0 and 2.0. If I fix an issue in 1.0, how do I merge that fix into 2.0 and vice versa?
Consider the following scenario:
I make a fix on the 1.0 branch and it creates a new file A (rev X).
I do a plain merge with just that fix from 1.0 to 2.0 (rev X+1)
I then make a fix on the 2.0 branch and it modifies A (rev Y).
If I merge that fix back to 1.0 I get a merge conflict!
I suppose I can always force that fixes are made on the 1.0 branch first or I could manually block the X+1 revision on the 1.0 branch. Both of these are non-ideal and I was wondering if there were a better way to handle sibling branches.
We do not do it often, but whenever it happens we go with manual block (i.e. --record-only).
The 'best' way is going to depend on the purpose of your branches.
For example, if branch 1.0 is for bug fixes and branch 2.0 is for testing then it makes sense to do all fixes on 1.0 first, then push to 2.0.
If they're different projects and you want to cherrypick which features get merged between branches then you could use the trunk as the centralised point.
If both branches are going to have the same files and changes and neither is authoritative it begs the question do you really need both?
Ultimately, you're going to have conflicts if both branches involve making changes on the same files, it's just down to your circumstances as to which is less hassle to deal with day to day.
The branches are different releases of the same product. We have to continue to support customers still on 1.0 and release patches while at the same time do new development on 2.0. Engineers maintaining the 1.0 branch will often discover bugs and fix them and those same bugs apply on the 2.0 branch. Engineers developing the new 2.0 branch discover bugs that also could affect the 1.0 release and want to push those changes back as well.
After more discussion I believe using the trunk as a centralized point is the ideal scenario.
| common-pile/stackexchange_filtered |
symmetric relation definitions
Definition One: A relation over a set $X$ is symmetric if for all $a,b$ $\in X$, $(a,b)\in R$ if and only if $(b,a)\in R$.
Definition Two: A relation over a set $X$ is symmetric if for all $a,b$ $\in X$, $(a,b)\in R$ if $(b,a)\in R$.
Am I correct to believe that, if I want to prove a relation over a set $X$ is symmetric, then it does not matter if I use definition one or definition two? I think that those two definitions are the exact same despite the fact that one has a lone "if" and then other has "if and only if." Although this may seem really obvious, I want to double check that my thinking is correct.
Def. $1$ clearly implies Def. $2$.
You can easily show that Def. $2$ implies Def. $1$: we are already given that $(b,a)\in R\rightarrow(a,b)\in R$. Thus $(a,b)\in R\rightarrow (b,a)\in R$, which follows from interchanging $a,b$ in Def. $2$.
| common-pile/stackexchange_filtered |
Why is my Datepicker not updating the value of input field?
I have an input field whose value I want to change when I select a date in my date picker but its not doing that. The reason I want to change the value of the input field is because I want to eventually submit this as a part of a form and for that value has to be updated
<input id='datepicker' class='ok' type="text" autocomplete="off" />
<script>
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
maxDate: '0',
onSelect: function (d) {
$('#datepicker').val(d);
}
});
</script>
Many similar questions in stack overflow but none of the solutions work. Pls advise
The jQuery documentation for select reads:
The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes.
You want the change event.
The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements.
Also, the argument passed to the callback function (d) is not the value of the element, but an event object. To get the value you need to call d.currentTarget.val().
onChange: function ( event ) {
$( '#datepicker' ).val( event.currentTarget.val() );
}
| common-pile/stackexchange_filtered |
Central limit theorem for sequence of r.v.s with "extending" uniform distributions
Does the Central Limit Theorem hold for independent r.v. $U_n \sim \mathrm{U}([0,n])$? Are there any deterministic $a_n, b_n$ such that
$$
\frac{\sum_{k=1}^n U_k - a_n}{b_n} \implies \mathrm{N}(0,1)
$$
I guess the answer is no. Do I have to prove that Lindeberg's condition($\forall \epsilon > 0\frac{1}{b_n^2}\sum_{k=1}^n\mathbb{E}(X_k - m_k)^2\mathbb{1}_{(|X_k - m_k| > \epsilon b_n)} \to 0$ as n $\to \infty$) can not hold?
No it doesn't work.
Are you talking about individual $U_n$ or $\sum U_n$ ?
@Henry Oh, $\sum U_n$. I have edited the question.
@math_beginner Please think more carefully about what it is you want to ask. Currently your notation does not make sense. Do you mean $\frac{(\sum_{i=1}^n U_i) - a_n}{b_n}$? or something else? Some sanity checks you can do is checking that the mean and variance of your terms must tend to $0$ and $1$ respectively; this should help determine what $a_n$ and $b_n$ could be, and then you can check if the limiting distribution is normal or not (if it exists at all).
The sum of the first $n$ uniform random variables has mean $n(n+1)/4$ and, assuming independence, a standard deviation of $\sqrt{n(n+1)(2n+1)/72}$
| common-pile/stackexchange_filtered |
Deserializing Json With Unknown Key - ASP.Net Core 3.1
I'd like to deserialize the following JSON with .Net 3.1
My difficulty is the "1234" key for this object is unknown when this object is serialized. How could I deserialize this? The values I want to keep are the nested "first_name" and "last_name" attributes
{
"1234":{
"id":1234,
"first_name":"John",
"last_name":"Doe"
}
}
Any help is appreciated!
In case you're using the Newtonsoft.Json.JsonConverter library, you could create a custom JsonConverter to handle dynamic properties and override the ReadJson and WriteJson methods.
public class MyConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// write your custom read json
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// write your custom write json
}
}
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverter.htm
You could use a dictionary:
public class Child
{
[JsonPropertyName("id")]
public string ID { get; set; }
[JsonPropertyName("first_name")]
public string FirstName { get; set; }
[JsonPropertyName("last_name")]
public string LastName { get; set; }
}
public class Parent
{
public Dictionary<string, Child> Children { get; set; }
}
You can then enumerate through Children using Foreach or Linq.
| common-pile/stackexchange_filtered |
Can diffusion create a vacuum?
As I understand it, helium diffuses at appreciable rates even through materials like glass or metal that are essentially impermeable to atmospheric gases.
So if I have a metal canister filled with helium at atmospheric pressure, the helium will diffuse into the walls of the canister and from there into the outside atmosphere.
That implies the pressure inside the container will fall to zero, since the partial pressure of helium outside the container basically remains at zero, and atmospheric gases can’t diffuse in the other direction. So after enough years, I’ll have a vacuum that I could use to do work.
That sounds wrong but I’m not clear why. Is this what would actually happen, and if so, where is the work “coming from”?
Why can atmospheric gases not diffuse into the container?
Diffusion doesn't create a vacuum this way. You have supplied a helium vacuum outside of the container.
The concentration of He in the atmosphere is 5.2 ppm,
I have actually done this very experiment, starting with a sealed, permeable vessel (Teflon) filled with helium at 1 atm surrounded by air at 1 atm. What happens is over several days the pressure falls to a low of about 0.85 to 0.9 atm, and then slowly rises back to 1 atm.
The explanation is that the vessel also permeable to air/nitrogen, but at a much lower rate. At the beginning, the helium escapes at a rate greater than the air seeps in, so the total pressure inside decreases. As time goes on (and assisted by the increasing inward pressure differential, and the helium escape rate becoming less), the air permeation replenishes the gas inside.
So, in your example the only way to truly get a vacuum inside the vessel at the end is to start with a vacuum on the outside. But, supposing you chose a hypothetical material that was permeable to helium, but with vanishingly low permeability to the outside medium (maybe water or oil), you could in theory reach an arbitrarily low pressure on the inside, which would remain indefinitely.
The driving force for this is the outward gradient in the partial pressure of helium, which can end up producing an opposite gradient in total pressure. You could also frame the helium gradient as a gradient in chemical potential, which as it evens out drives movement in total system pressure "uphill."
This idea of one type of gradient driving another type uphill against a gradient is how virtually every mechanism or cycle works. A battery uses chemical potential (which is trying to equalize within the battery) to drive electrical energy "uphill," separating charges which can then be used to do work. Any thermodynamic heat engine uses heat flow down a thermal gradient to drive mechanical work uphill against a mechanical gradient (gravity or otherwise). It is nothing but energy conversion from one form to another. Your helium example is converting chemical or entropic energy (mixing of uneven concentrations) into mechanical energy (pressure difference).
That seems perfectly reasonable to me! The pressure inside the container will indeed drop to zero after a while.
If you compare the chemical potential of helium inside and outside the container, you'll see that helium diffuses from the high-chemical-potential region (inside) to low-chemical-potential region (outside), similar to how a ball rolls downhill.
The work originates from the initial effort required to isolate the high-purity helium gas (a low-entropy state compared to the outside air, which is a mixture of nitrogen, oxygen, etc.) and filling it into the canister. This entropic effect eventually results in the "work" that can be done by the pressure difference.
Note, however, that the work is only done if the container is compressed by the vacuum ($W = P\Delta V = 0$ if $\Delta V = 0$). In other words, if the metal canister is very strong and does not collapse, then no work is done by diffusion.
It depends entirely on whether the canister allows heat flow across its walls, or is adiabatic. Temperature is average energy, regardless of quantity of particles. You can start with 1 mole of helium at 20°C and end up with 20 atoms of helium at 20°C, although at low enough particle densities, the concept of temperature begins to break down.
I think my previous comment ended up posted in the wrong place. What I responded to is not something in your answer
So after enough years, I’ll have a vacuum that I could use to do work.
Yes, if the container is permeable only to helium, then after a long time, the state will be very low pressure helium inside, much lower than the atmospheric pressure.
That sounds wrong but I’m not clear why. Is this what would actually happen, and if so, where is the work “coming from”?
It is not wrong, only non-intuitive, because it is not common to have such container and observe the pressure decrease. Similar phenomenon can be observed, perhaps more easily, in liquids. Imagine the closed container contains pure water, and the outside is salty water, and one wall of the container is made of a semipermeable membrane, allowing only water to go through the membrane, but not salt. In time, net effect of water migration will be that the amount of water inside will decrease, and pressure inside will drop.
Back to your question, the work that can be extracted comes from energy in the atmosphere. It has higher pressure and energy per unit volume than the gas inside. This imbalance of pressure allows the energy to be released. The imbalance was created spontaneously from the initial imbalance of helium concentrations.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.