qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
28,372,424
I can't understand the following behavior of ranges in Haskell. Enumerating 1 to 1 gives me a list contain only 1, and 2 to 2 gives me a list contain only 2 as given below. ``` Prelude> [1..1] [1] Prelude> [2..2] [2] ``` But enumerating infinity to infinity gives me a list which is infinite in length and all the elements are infinity, as shown below. ``` Prelude> [1/0..1/0] [Infinity,Infinity,Infinity,Infinity,Infinity,Infinity,Interrupted. ``` I am aware that Infinity is a concept not to be treated as a number, but what justifies that behavior ?
2015/02/06
[ "https://Stackoverflow.com/questions/28372424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148851/" ]
As Luis Wasserman and Tikhon Jelvis have indicated, the basic problem is that the `Num` and `Enum` instances for `Float` and `Double` are *weird*, and really should not exist at all. In fact, the `Enum` class itself is pretty weird, as it attempts to serve several different purposes at once, none of them well—it is probably best considered a historical accident and a convenience rather than a good example of what a typeclass should look like. The same is true, to a significant extent, of the `Num` and `Integral` classes. When using any of these classes, you must pay close attention to the specific types you are operating on. The `enumFromTo` methods for floating point are based on the following function: ``` numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a] numericEnumFromTo n m = takeWhile (<= m + 1/2) (numericEnumFrom n) ``` So `2 <= 1+1/2` is *false*, but because of the weirdness of floating point, `infinity <= infinity + 1/2` is *true*. As Tikhon Jelvis indicates, it's generally best not to use any `Enum` methods, including numeric ranges, with floating point.
I believe the implementation of `[a..b]` continues incrementing `a` by one until it is greater than `b`. This is never going to happen with infinity, so it goes forever. I believe your code will probably default to `Double` the way you've written it, which has well-defined semantics for infinity. IIRC, Haskell follows <http://en.wikipedia.org/wiki/IEEE_floating_point>.
74,541,684
I am using Webview\_Flutter. The header of the site overlaps the position of the statusbar and I would like to add padding to avoid this. This is the process of inserting padding to avoid the statusbar if the webview is opened or if there is a scroll position at the top. ``` body: Padding( padding: (controller?.getScrollY() == null || controller?.getScrollY() == 0) ? EdgeInsets.only(top: height) : EdgeInsets.only(top: 0), child: Expanded( child: Padding( padding: const EdgeInsets.only(bottom: 0.0), child: WebView( javascriptMode: JavascriptMode.unrestricted, initialUrl: Uri.parse(widget.link).toString(), onWebResourceError: (error) { // print(error.domain); }, onWebViewCreated: (controller) { this.controller = controller; }, onProgress: (progress) { setState(() { this.progress = progress / 100; progressPercent = progress; }); }, ), ```
2022/11/23
[ "https://Stackoverflow.com/questions/74541684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18096205/" ]
To detect WebView scroll event, you can use the [`flutter_inappwebview`](https://github.com/pichillilorenzo/flutter_inappwebview) plugin (I'm the author) and implement the `InAppWebView.onScrollChanged` event. However, probably you don't need to add top padding for your WebView. You can set the `AppBar.toolbarHeight` to `0`, so the app bar will have the right height to cover the status bar. Here is a full code example with both cases using the current latest version 6 available of the plugin ([`6.0.0-beta.16`](https://pub.dev/packages/flutter_inappwebview/versions/6.0.0-beta.16)): ```dart import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && kDebugMode && defaultTargetPlatform == TargetPlatform.android) { await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); } runApp(const MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { final GlobalKey webViewKey = GlobalKey(); InAppWebViewController? webViewController; int scrollY = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( toolbarHeight: 0, ), body: Padding( padding: EdgeInsets.only(top: scrollY <= 0 ? 25 : 0), child: Column( children: [ Expanded( child: InAppWebView( key: webViewKey, initialUrlRequest: URLRequest(url: WebUri("https://github.com/flutter")), onWebViewCreated: (controller) { webViewController = controller; }, onScrollChanged: (controller, x, y) { setState(() { scrollY = y; }); }, ), ) ], ), )); } } ``` ![Simulator Screen Recording - iPhone 14 Pro Max - 2022-11-25 at 01 21 15](https://user-images.githubusercontent.com/5956938/203877475-c08bb794-4f76-47eb-baac-e8dbe12b7343.gif)
I tried to find the listener of the webView scroll, I couldn't find it , you're right. There is a solution ^^, it's simple, we could wrap WebView in ListView then we could use scrollListener(1) or notificationListener(2) and don't forget to use setState to update Padding values ``` class _HomeScreenState extends State<HomeScreen> { WebViewController? _webViewController; ScrollController _scrollController = ScrollController(); @override Widget build(BuildContext context) { return Scaffold( body:Scaffold( backgroundColor: Colors.green, appBar: AppBar( title: const Text('Flutter WebView example'), // This drop down menu demonstrates that Flutter widgets can be shown over the web view. actions: <Widget>[ ], ), //NotificationListener(2) body: NotificationListener<ScrollNotification>( onNotification: (scrollNotification) { if (scrollNotification is ScrollStartNotification) { WidgetsBinding.instance.addPostFrameCallback((_) { print("ScrollStartNotification / pixel => ${scrollNotification.metrics.pixels}"); }); } else if (scrollNotification is ScrollEndNotification) { WidgetsBinding.instance.addPostFrameCallback((_) { setState(() { print("ScrollEndNotification / pixel =>${scrollNotification.metrics.pixels}"); }); }); } return true; }, child: ListView( physics: ClampingScrollPhysics(), controller: _scrollController, children: <Widget>[ ConstrainedBox( constraints: BoxConstraints(maxHeight: 10000), child: WebView( initialUrl: 'https://flutter.dev', javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (WebViewController webViewController) {}, onProgress: (int progress) { print('WebView is loading (progress : $progress%)'); }, javascriptChannels: <JavascriptChannel>{ }, onPageStarted: (String url) {}, onPageFinished: (String url) {}, gestureNavigationEnabled: true, backgroundColor: const Color(0x00000000), ), ), ], ), ))); } @override void initState() { super.initState(); //scrollListener(1) _scrollController.addListener(() { print("scrollListener / pixel =>${_scrollController.position.pixels}"); }); } } ```
170,885
The following integral can be obtained using the [online Wolfram integrator](http://integrals.wolfram.com/index.jsp?expr=1%2F%281%2BCos%5Bx%5D%5E2%29): $$\int \frac{dx}{1+\cos^2 x} = \frac{\tan^{-1}(\frac{\tan x}{\sqrt{2}})}{\sqrt{2}}$$ Now assume we are performing this integration between $0$ and $2\pi$. Hence the result of the integration is zero. On the other hand when looking at the integrand, $\displaystyle \frac{1}{1+\cos^2 x}$, we see that it is a periodic function that is never negative. The fact that it is never negative guarantees that the result of the integration will never be zero (i.e., intuitively there is a positive area under the curve). What is going on here?
2012/07/14
[ "https://math.stackexchange.com/questions/170885", "https://math.stackexchange.com", "https://math.stackexchange.com/users/19717/" ]
Quite simple: the $\arctan$ function is multivalued, so you have to add the appropriate multiples of $\pi$ to the function to get at the right result; i.e., $\sqrt{2}\pi$
The antiderivative you are using is not continuous from $0$ to $2\pi$. Ask Wolfram to graph it. Then try to see if you can adjust it by constants on various intervals to make it continuous, and you will see that the integral is quite far from $0$.
66,431,744
Suppose I have a 3D array, how can I fill the diag of the first two dimensions to zero. For example ``` a = np.random.rand(2,2,3) for i in range(3): np.fill_diagonal(a[:,:,i], 0) ``` Is there a way to replace the for loop?
2021/03/02
[ "https://Stackoverflow.com/questions/66431744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14513243/" ]
The following is one of the solution ``` a = np.random.rand(2,2,3) np.einsum('iij->ij',a)[...] = 0 ```
The np.diag function returns a 2D diagonal matrix. ``` a[:,:,0] = np.diag((1,1)) ```
5,137
Hey, so I'm just playing around with a usb cable and an LED. I plugged in the usb to my computer and connected ground with the LED ground and the last usb pin (+) to the LED. It stays lit bright. I moved the wire from the usb power pin to the D+ pin. Is it possible that I could send a bit stream through usb that would in turn light up this LED? I'm not even a beginner with usb, drivers, etc. I just had the idea that hit me and wanted to see if it was possible as a sort of show off to friends.
2010/12/25
[ "https://unix.stackexchange.com/questions/5137", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/3170/" ]
Another alternative might be a usb-serial or usb-parrallel port dongle. Note you will need a resistor in series with your LED to limit the current to suitible amount to avoid burning out something (either the LED or the interface). Another option is, there are off the shelf devices available that do something like what you ask, e.g. at time of writing 'googling' "usb gpio" produced many links.
If you have an old-style parallel or serial port, this is much easier.
31,809,201
Here's my current code: ``` private void searchTextBox_TextChanged(object sender, EventArgs e) { (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", searchTextBox.Text); } ``` However my data grid table filters everything and becomes blank whenever I type something into the textbox. Any idea why? Thank you in advance!
2015/08/04
[ "https://Stackoverflow.com/questions/31809201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5169032/" ]
The *likely* reason you are seeing a blank `DataGridView` is due to your filter string searching for exact matches to the `TextBox` text. > > > ``` > "Name='{0}'" > > ``` > > Because you are updating this filter in the `TextBox.TextChanged` event, the first time you enter a character - no matches are found. For example, given the following grid: ``` ╔════╦══════╗ ╔════════╗ ║ ID ║ Name ║ searchTextBox ║ ║ ╠════╬══════╣ ╚════════╝ ║ 1 ║ Foo ║ ║ 2 ║ Bar ║ ║ 3 ║ Baz ║ ╚════╩══════╝ ``` Entering `Bar` will give the following results: ``` ╔════╦══════╗ ╔════════╗ ║ ID ║ Name ║ searchTextBox ║ B ║ ╠════╬══════╣ ╚════════╝ ╚════╩══════╝ ╔════╦══════╗ ╔════════╗ ║ ID ║ Name ║ searchTextBox ║ Ba ║ ╠════╬══════╣ ╚════════╝ ╚════╩══════╝ ╔════╦══════╗ ╔════════╗ ║ ID ║ Name ║ searchTextBox ║ Bar ║ ╠════╬══════╣ ╚════════╝ ║ 2 ║ Bar ║ ╚════╩══════╝ ``` If this is the case, I've provided a few options below. If this is not the case, then you have a mystery. --- 1. **Exact matches:** consider using the following event handler instead so that the filter is only applied once you've entered the full search text: ``` private void searchTextBox_Leave(object sender, EventArgs e) { if (string.IsNullOrEmpty(searchTextBox.Text)) { (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty; } else { (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", searchTextBox.Text); } } ``` 2. **StartsWith matches:** for more fluid filtering on text changes: ``` private void searchTextBox_TextChanged(object sender, EventArgs e) { (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name LIKE '{0}%'", searchTextBox.Text); } ``` 3. **Contains matches:** again, fluid filtering: ``` private void searchTextBox_TextChanged(object sender, EventArgs e) { (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name LIKE '%{0}%'", searchTextBox.Text); } ```
OhBeWise answer is the best but until i add something to get points i'm not allowed to like it. so i'll add this, remember in OhBeWise's answer that your filtering the rows to be listed but using the column name from the query. the query used to set the datasource of the datagridview. For Instance in my example "LoginID" is in the select statement. ``` (dataGridViewTheToGrid.DataSource as DataTable).DefaultView.RowFilter = string.Format("LoginID LIKE '{0}%'", textBoxFindUserID.Text); ```
36,772,523
My method interface is ``` Boolean isAuthenticated(String User) ``` I want to compare from list of values if any of the users are passed in the function from the list, then it should return true. ``` when(authService.isAuthenticated(or(eq("amol84"),eq("arpan"),eq("juhi")))).thenReturn(true); ``` I am using additional argument matcher 'or' but above code is not working. How can I resolve this issue?
2016/04/21
[ "https://Stackoverflow.com/questions/36772523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157704/" ]
`or` does not have a three-argument overload. ([See docs.](http://site.mockito.org/mockito/docs/current/org/mockito/AdditionalMatchers.html#or(T,%20T))) If your code compiles, you may be importing a different `or` method than `org.mockito.AdditionalMatchers.or`. `or(or(eq("amol84"),eq("arpan")),eq("juhi"))` should work. You might also try the [`isOneOf` Hamcrest matcher](http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#isOneOf(T...)), accessed through the [`argThat` Mockito matcher](http://site.mockito.org/mockito/docs/current/org/mockito/hamcrest/MockitoHamcrest.html#argThat(org.hamcrest.Matcher)): ``` when(authService.isAuthenticated(argThat(isOneOf("amol84", "arpan", "juhi")))) .thenReturn(true); ```
For me this works: ``` public class MockitoTest { Mocked mocked = Mockito.mock(Mocked.class); @Test public void test() { Mockito.when(mocked.doit(AdditionalMatchers.or(eq("1"), eq("2")))).thenReturn(true); Assert.assertTrue(mocked.doit("1")); Assert.assertTrue(mocked.doit("2")); Assert.assertFalse(mocked.doit("3")); } } interface Mocked { boolean doit(String a); } ``` Check if you're setting up mockito correctly, or if you're using the same Matchers as I do.
3,671,062
I don't want to deal with users who have javascript turned off, so I want to just prevent them from using my application. I want to detect if the user has javascript turned on so I can redirect them to a page that tells them they need to use javascript. I'm sure its in the request header. Anyone have any ideas how I can do this?
2010/09/08
[ "https://Stackoverflow.com/questions/3671062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43792/" ]
The `noscript` tag is the easiest solution, though not exactly whay you're looking for. ``` <noscript>Get outta here.</noscript> ```
You can't. The server has no idea what the client has enabled. You can't even "detect" if Javascript is disabled from the client (because what would you use to do so?). You can use tricks to show content when Javascript is disabled (for instance, a `<noscript>` tag, or using Javascript to hide content that is meant for JS-only).
2,707,476
How to recover a deleted row from SQL Server 2005 table?
2010/04/25
[ "https://Stackoverflow.com/questions/2707476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239128/" ]
Rollback the transaction (if you started one). Restore a backup (if you have one). [edit] If you have transaction logs, you should be able to restore the backup of the database to the point roughly just before the row was deleted (assuming you know when that was).
The [ApexSQL Log](http://www.apexsql.com/sql_tools_log.aspx) tool can be the solution for deleted rows. In case the DELETE operation exists (the database was not using the Simple recovery model) in database transaction logs (online, backups), the tool can create an undo T-SQL script for the operation. *Disclaimer: I work as a Product Support Engineer at ApexSQL*
206,734
I tried this: ``` tcpdump -s 1500 -A -l -i eth0 '(port 6667) and (length > 74)' ``` I need only the ascii part of it. How do I remove the rest?
2010/11/28
[ "https://serverfault.com/questions/206734", "https://serverfault.com", "https://serverfault.com/users/61783/" ]
I feel the most elegant solution is just to ditch tcpdump. No pipes of any kind: ``` tcpflow -c port 6667 ``` And that's it.
I had the same problem last week - I used the wireshark gui instead and did a "copy readable ascii" for the interesting packets. I was (successfully) trying to pin down a problem with a http request to a web-service and its XML-answer.
114,187
I've got an Pentax K-r DSLR camera ([tech specs here](https://www.ricoh-imaging.co.uk/en/digital-slr/pentax-kr.html)). This camera is about 9 years old. And I have the stock 18-55mm lens. I've also got an iPhone 11 Pro ([tech specs here](https://www.apple.com/uk/iphone-11-pro/)). Both have circa 12mp sensors. Which sensor is better? And which camera would ultimately produce a better image? I intend to use either for some interior photography, so it's a 'planned use' rather than an ad hoc requirement. If using the iPhone, I would do it using an iPhone-to-tripod adaptor.
2020/01/18
[ "https://photo.stackexchange.com/questions/114187", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/10167/" ]
Use both. Use whatever is fun right now. Depending on the situation, one or the other will be better. A DSLR tends to give results that are just the photo + very basic and deterministic postprocessing (you are free to postprocess it on a computer), while smartphones cameras try to be smart and sometimes phony with the postprocessing. A DSLR is more weight to carry but, with practice, can be much quicker in handling, especially when you want to work in semi-automatic and manual modes. Subjective, out of camera image quality will likely be better with the phone, at least by contemporary "beauty standards" for a photograph - however, both options will yield more than enough image quality for most users. Theoretically, the much larger sensor will be at an advantage in image quality and lowlight capability - however, device ages will about level the playing field here. DSLR/mirrorless photos tend to look good when viewed full size on an HD or better monitor, or printed ... smartphones tend to optimize their output towards having great impact in smaller formats (web images among others on a web page, screens of other smartphones). This becomes even more apparent when looking at enlarged portions (or cropping a part of the image out!). What WILL make a DSLR lose out to a smartphone is a mediocre zoom lens - get something like a (used) f2.8 zoom lens and/or reasonably modern prime (vintage primes have their merit but they tend to have a strong "character" that will sometimes make, sometimes *break* your picture). If you have the 18-55 DA WR (just a guess with that camera...) ... not horrible, but not the best that camera can have mounted to it ;) Usually, one weakness of smartphones is telephoto operation (less so with a multi-camera phone like you have) - however, you can fit a 400mm or 600mm lens to the Pentax, not so much the phone. One or the other option can be better accepted to use in social situations - sometimes, the smartphone user will be more accepted, in other cases it is better to be mistaken as a serious photographer or press guy. One disadvantage of consumer DSLRs like the K-r is that these have two precision problems, compared to mirrorless cameras and smartphones - the viewfinder frames inexactly (the specs say it is a 96% viewfinder), and there can be autofocus precision problems (mirrorless cameras and quality smartphones autofocus using the image sensor itself as a reference. DSLRs use a separate sensor for that, and these two sensors can go out of whack with respect to each other). The Pentax has two advantages to many other (even current) DSLRs, that it has in common with smartphones: It is designed in a somewhat weatherproof way (Pentax is reputed for that, even though the K-r is not sold as a weatherproof camera), and has an image stabilizer.
In terms of image quality a larger sensor (of the same generation/technology) always wins because it gets more light (same composition/SS/Ap). It is also less demanding of lens resolution. The I-phone has a sensor that is just over 7mm long edge, the K-r has a sensor that's just under 24mm. That's ~ 9x the size in area, and ~ 9x the amount of light/information. It also means a detail can be recorded 9x as large (area) and still be just as sharp. Granted, the generations/technologies are a bit different; but I highly doubt any phone sized sensor can overcome such a handicap.
99,946
1. In situation when body exposed by light, is 'color' characteristics of a body or characteristics of light? Is there any difference on macro/micro levels? 2. Will exist such term as 'color' in [parallel universe](http://en.wikipedia.org/wiki/Parallel_universe) where electro-magnetic waves doesn't exists?
2014/02/20
[ "https://physics.stackexchange.com/questions/99946", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/40955/" ]
The "color" of a body is not a property of the body nor of the light it reflects or emits, but rather of the human eye and brain that receive and process the light. Of course, this is based on a property of the light, for this is how the eye receives the information that there is some object in there in the first place. This property is the *spectrum* of the light: the relative intensity that the light has at different wavelengths. It is easily observable by using a prism or diffraction grating to spatially separate the components with different wavelengths. Within the human eye, the spectrum of the light gets translated into nerve impulse signals which are later interpreted by the brain. This translation stage is *lossy*: the nerve signals contain less information than the spectrum did, and it is not possible to reconstruct the latter from the former. To put this another way, there exist light sources (of, for example, 'yellow' light) which have different spectra but nevertheless look the same to human eyes. To a good approximation, the nerve signals can be considered to consist of three 'channels': one for red, one for green, and one for blue light, which correspond to the spectral regions where three types of retinal cells are most sensitive. The combination of how much of each of those signals you receive then gets interpreted as your subjective experience of color. Other animals also follow similar models, but the number of channels can vary between species. Some have only two types of receptors, and some have more than three, ranging from four or five to sixteen, in the case of the mantis shrimp; some animals like certain snakes can see in the infrared. In as much as it makes sense to ask about the subjective experience of an animal, there is really no way for humans to comprehend what vision with more than three channels 'feels' like. Certain humans do have one or two of those channels impaired, and are known as colorblind; to a certain extent it is possible for non-colorblind humans to understand what colorblindness is like. And as for your second question, it would depend entirely on the sort of beings that inhabited the hypothetical world, whether their cognitive structures and subjectjve experiences were analogous to ours, and whether there was some other physical property which they detected through analogous mechanisms. In short, the question doesn't make much sense, really.
Color is nothing but interpretation of electromagnetic waves into various nerve signals by our brain. It is the property of the object to reflect various wavelengths when photons strike their electrons. Electrons then vibrates up and down atleast 1000 times each second emmiting electromagnetic waves which our eyes receives. Each different wavelength of visible spectrum has its own color representation by our brain.
65,957,634
I've searched anywhere for this info, and only found a broken link to an old stockfish support page which doesn't work anymore. I can't seem to figure out how to change the depth parameter at which stockfish minimaxes via my python program. Any help would be truly appreciated.
2021/01/29
[ "https://Stackoverflow.com/questions/65957634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I hope this is right. If I understand your question you just want to count the yes's for each category. I've put it into a function so just change x = Sick to whatever your dataframe is called and run the function. **EDIT** I forget which package the pipe and columns\_to\_rownames comes from, I've added dplyr as a require but it may come from magrittr. If in doubt just load the tidyverse. ``` sick_tbl <- function(x = Sick){ require(dplyr) sick_piv <- pivot_longer(x, names_to = "names", values_to = "values", -c(age)) count <- sick_piv%>% count(values, names, age) %>% filter(values == "Yes") %>% select(!values) sick_out <- pivot_wider(count, names_from = "age", values_from = "n") %>% column_to_rownames(var = "names") sick_out[is.na(sick_out)] <- 0 sick_out <<- sick_out} ``` To run on your example data: ``` sick_tbl(x = Sick) Adult Child Elderly Infant chills 1 2 4 NA cough 4 2 5 1 fatigue 3 3 2 1 fever 2 4 2 2 ```
First reshape, then use the [`datasummary` function from the `modelsummary` package](https://vincentarelbundock.github.io/modelsummary/articles/datasummary.html) (self-promotion alert). The benefit of this solution is that you can customize the look of your table and save it to many formats (html, latex, word, markdown, etc.): ```r library('modelsummary') library('tidyverse') dat = pivot_longer(Sick, -age, names_to = "Symptom") %>% filter(value == "Yes") datasummary(Symptom ~ N * age, data = dat) ``` | | Adult | Child | Elderly | Infant | | --- | --- | --- | --- | --- | | chills | 1 | 2 | 0 | 4 | | cough | 2 | 4 | 1 | 5 | | fatigue | 5 | 4 | 0 | 2 | | fever | 3 | 3 | 0 | 1 |
120,639
Is there another way of saying “less is more" in the following context? > > They changed their packaging and left only the essential branding on it. It epitomizes "*less is more".* > > >
2013/07/28
[ "https://english.stackexchange.com/questions/120639", "https://english.stackexchange.com", "https://english.stackexchange.com/users/48676/" ]
A similar, but less dramatic phrase is *keep it simple*, or the more emphatic *keep it simple, stupid*, often abbreviated to [*KISS*](http://en.wikipedia.org/wiki/KISS_principle). You also might consider *[lean and mean](http://dictionary.cambridge.org/us/dictionary/business-english/lean-and-mean)* > > using only what is necessary, and determined to work effectively in order to compete successfully > > >
Instead of "less is more", how about "efficiency"?
168,686
Well,this is a homework problem. I need to calculate the differential entropy of random variable $X\sim f(x)=\sqrt{a^2-x^2},\quad -a<x<a$ and $0$ otherwise. *Just how to calculate* $$ \int\_{-a}^a \sqrt{a^2-x^2}\ln(\sqrt{a^2-x^2})\,\mathrm{d}x $$ I can get the result with Mathematica,but failed to calculate it by hand.Please give me some idea.
2012/07/09
[ "https://math.stackexchange.com/questions/168686", "https://math.stackexchange.com", "https://math.stackexchange.com/users/5971/" ]
If you let $x = a\sin(\theta)$, your integral becomes $$a^2\int\_{-{\pi \over 2}}^{\pi \over 2} \ln(a\cos(\theta))\cos^2(\theta)\,d\theta$$ $$= 2a^2\int\_0^{\pi \over 2} \ln(a\cos(\theta))\cos^2(\theta)\,d\theta$$ $$= 2a^2\ln(a)\int\_0^{\pi \over 2}\cos^2(\theta)\,d\theta + 2a^2\int\_0^{\pi \over 2} \ln(\cos(\theta))\cos^2(\theta)\,d\theta$$ The first integral is standard, and we get $$={\pi a^2 \ln(a)\over 2} + 2a^2\int\_0^{\pi \over 2} \ln(\cos(\theta))\cos^2(\theta)\,d\theta$$ The integral here is ${\displaystyle {d \over dn}\bigg|\_{n = 2} \int\_0^{\pi \over 2} \cos^n(\theta)\,d\theta}$. According to Wolfram Alpha, $$\int\_0^{\pi \over 2} \cos^n(\theta)\,d\theta = {\sqrt{\pi} \over 2}{\Gamma({n +1 \over 2}) \over \Gamma({n \over 2} + 1)}$$ Taking the derivative of this and setting $n = 2$ works out to $(\sqrt{\pi}/4)(\Gamma'({3/2}) - \Gamma'(2)\Gamma(3/2))= (\sqrt{\pi}/4)(\Gamma'({3/2}) - \Gamma'(2)(\sqrt{\pi}/2))$. So plugging this in gives as your answer: $$={\pi a^2 \ln(a)\over 2} + {\sqrt{\pi}a^2 \over 2}(\Gamma'({3/2}) - \Gamma'(2){\sqrt{\pi} \over 2})$$ Using $\Gamma'(3/2) = {\sqrt{\pi} \over 2}(2 - \gamma - \ln 4)$ and $\Gamma'(2) = 1 - \gamma$, where $\gamma$ is the Euler-Mascheroni constant, this becomes $$={\pi a^2 \ln(a)\over 2} + {\sqrt{\pi}a^2 \over 2}({\sqrt{\pi} \over 2} -{\sqrt{\pi} \ln 4 \over 2})$$ $$= {\pi a^2 \ln(a)\over 2} + {\pi a^2 \over 4} -{\pi a^2 \over 4} \ln 4$$
[Some ideas] You can rewrite it as follows: $$\int\_{-a}^a \sqrt{a^2-x^2} f(x) dx$$ where $f(x)$ is the logarithm. Note that the integral, sans $f(x)$, is simply a semicircle of radius $a$. In other words, we can write, $$\int\_{-a}^a \int\_0^{\sqrt{a^2-x^2}} f(x) dy dx=\int\_{-a}^a \int\_0^{\sqrt{a^2-x^2}} \ln{\sqrt{a^2-x^2}} dy dx$$ Edit: Found a mistake. Thinking it through. :-)
3,601,620
As Title. It's really a two part question. Part one is to show if R is an integral domain and $\omega$ is a primitive n th root unity in R, then for any $a\in R$, Show $x^{n}-a^{n}= \prod\_{k=0}^{n-1}(x-a\omega^{k})$ Which I've already done. I don't see the connection between the two questions, could someone please provide some hints? \*Edit: typo and formatting.
2020/03/30
[ "https://math.stackexchange.com/questions/3601620", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
For $n=6$ and $\omega=\zeta\_6$ the complex roots of $X^6+2=0$ are $\xi\_k=\omega^k\sqrt[6]{-2}$ for $k=1,\ldots ,6$. Hence over $\Bbb C$, we have $$ X^6+2=(X-\xi\_1)(X-\xi\_2)\cdots (X-\xi\_6). $$
Over $\Bbb C$ it splits, by the fundamental theorem of algebra. Use a primitive sixth root of unity and $(-2)^{1/6}$, to get the six roots. Over $\Bbb R$, we get quadratic factors. The roots come in conjugate pairs, three times. We get $(x^2+\sqrt[3]2)(x^2-\sqrt[6]2\sqrt3x+\sqrt[3]2)(x^2+\sqrt[6]2\sqrt3x+\sqrt[3]2)$.
65,095
What are the common algorithms being used to measure the processor frequency?
2008/09/15
[ "https://Stackoverflow.com/questions/65095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Intel CPUs after Core Duo support two Model-Specific registers called IA32\_MPERF and IA32\_APERF. MPERF counts at the maximum frequency the CPU supports, while APERF counts at the actual current frequency. The actual frequency is given by: ![freq = max_frequency * APERF / MPERF](https://chart.apis.google.com/chart?cht=tx&chl=%5CLARGE%5C%21freq%20%3D%20%5Cfrac%7Bmax%20frequency%20%5Ccdot%20APERF%7D%7BMPERF%7D) You can read them with this flow ``` ; read MPERF mov ecx, 0xe7 rdmsr mov mperf_var_lo, eax mov mperf_var_hi, edx ; read APERF mov ecx, 0xe8 rdmsr mov aperf_var_lo, eax mov aperf_var_hi, edx ``` but note that rdmsr is a privileged instruction and can run only in ring 0. I don't know if the OS provides an interface to read these, though their main usage is for power management, so it might not provide such an interface.
I'm not sure why you need assembly for this. If you're on a machine that has the /proc filesystem, then running: ``` > cat /proc/cpuinfo ``` might give you what you need.
26,279,179
I made a Windows Form in VB.NET that has a Panel with a Datagridview on it, and underneath it a FlowLayoutPanel with Save and Close buttons on it, call it frmParent. Then I created frmChild and on it I inherited frmParent. I then hooked up my DataGridView to some data and it worked fine. Next I tried to add code to save changes to the datagrid and the buttons are locked. I checked the modifiers: both buttons and the FlowLayoutPanel that contains them are Protected. I read that there are frequently problems accessing controls that are contained in a collection of another control. But the DataGridView is fine, so my question: What do I need to do to get the Save and Cancel buttons to be available on the child form? Do I need to do away with the FlowLayoutPanel, or is there another way? In this simple example it isn't that big of a deal, but I would like to start using visual inheritance regularly and I would like to know the best way to do things.
2014/10/09
[ "https://Stackoverflow.com/questions/26279179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2551936/" ]
To expose an action on a base class control as an event (another answer shows how to do this via an overridable method): Base Form: ``` Public Event SaveClick As EventHandler Protected Overridable Sub OnSaveClick(ByVal e As EventArgs) RaiseEvent SaveClick(Me, e) End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click OnSaveClick(e) End Sub ``` Child Form: ``` ' the event will show up in the event list like any other ' this may be what you want if each child form is supposed to do everything Private Sub Form1_SaveClick(sender As Object, e As EventArgs) Handles Me.SaveClick ' save some stuff End Sub ' hybrid where the child form does some stuff, base form does some stuff Protected Overrides Sub OnSaveClick(e As EventArgs) MyBase.OnSaveClick(e) ' base form activities 'save some stuff End Sub ``` So the base form could raise some abstracted events like `SaveItem`, `NewItem`, `DeleteItem` and the child forms act on that much like how an interface works. --- The flaw in this approach is that the controls are still locked on the BaseForm, as they should be (controls are Friend). Each child *could* pass a parameter to the base form indicating a "mode": ``` Public Sub New() MyBase.New("Customer") ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. End Sub ``` But to make use of it means that the base form has to have logic to handle all those various "modes" which negates the value of inherited forms specialized to handle Foo, Bar, Customer etc. So, I am not sure form inheritance is what you want: the controls described seem too specialized.
Your best bet, both from a functional standpoint and design standpoint, is to create events in your child form, i.e. `OnSaveRequested` and `OnCancelRequested`. In your parent form, declare your child form using `WithEvents` and create handlers for those events. When you want to save from the child form, raise the `OnSaveRequested` event and handle it in the parent form (same with Cancel). Of course, in this scenario your parent form will need to know *what* to save, so you can either pass the data in as an argument to the event or expose a public property to the data in your child form.
8,255,205
How can I write below sql query in linq ``` select * from Product where ProductTypePartyID IN ( select Id from ProductTypeParty where PartyId = 34 ) ```
2011/11/24
[ "https://Stackoverflow.com/questions/8255205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/287100/" ]
Syntactic variations aside, you can write it in practically the same way. ``` from p in ctx.Product where (from ptp in ctx.ProductTypeParty where ptp.PartyId == 34 select ptp.Id).Contains(p.ProductTypePartyID) select p ``` I prefer using the existential quantifier, though: ``` from p in ctx.Product where (from ptp in ctx.ProductTypeParty where ptp.PartyId == 34 && ptp.Id == p.ProductTypePartyID).Any() select p ``` I expect that this form will resolve to an `EXISTS (SELECT * ...)` in the generated SQL. You'll want to profile both, in case there's a big difference in performance.
There is no direct equivalent in LINQ. Instead you can use contains () or any other trick to implement them. Here's an example that uses `Contains`: ``` String [] s = new String [5]; s [0] = "34"; s [1] = "12"; s [2] = "55"; s [3] = "4"; s [4] = "61"; var result = from d in context.TableName where s.Contains (d.fieldname) select d; ``` check this link for details: [in clause Linq](http://developmentsolutionsjunction.blogspot.com/2011/09/in-clause-with-linq-to-sql.html) ``` int[] productList = new int[] { 1, 2, 3, 4 }; var myProducts = from p in db.Products where productList.Contains(p.ProductID) select p; ```
7,889,038
**How can i tell my controller/model what kind of culture it should expect for parsing a datetime?** I was using some of [this post](http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx) to implement jquery datepicker into my mvc application. When i submit the date it gets "lost in translation" i'm not using the US formatting for the date, so when it gets sent to my controller it simply becomes null. I have a form where the user chooses a date: ``` @using (Html.BeginForm("List", "Meter", FormMethod.Get)) { @Html.LabelFor(m => m.StartDate, "From:") <div>@Html.EditorFor(m => m.StartDate)</div> @Html.LabelFor(m => m.EndDate, "To:") <div>@Html.EditorFor(m => m.EndDate)</div> } ``` I've made an edit template for this, to implement the jquery datepicker: ``` @model DateTime @Html.TextBox("", Model.ToString("dd-MM-yyyy"), new { @class = "date" }) ``` I then create the datepicker widgets like this. ``` $(document).ready(function () { $('.date').datepicker({ dateFormat: "dd-mm-yy" }); }); ``` All this works fine. Here is where the problems start, this is my controller: ``` [HttpGet] public ActionResult List(DateTime? startDate = null, DateTime? endDate = null) { //This is where startDate and endDate becomes null if the dates dont have the expected formatting. } ``` This is why i would like to somehow tell my controller what culture it should expect? Is my model wrong? can i somehow tell it which culture to use, like with the data annotation attributes? ``` public class MeterViewModel { [Required] public DateTime StartDate { get; set; } [Required] public DateTime EndDate { get; set; } } ``` --- Edit: [this link](http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx) explains my issue and a very good solution to it aswell. Thanks to gdoron
2011/10/25
[ "https://Stackoverflow.com/questions/7889038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665879/" ]
You can create a Binder extension to handle the date in the culture format. This is a sample I wrote to handle the same problem with Decimal type, hope you get the idea ``` public class DecimalModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); ModelState modelState = new ModelState { Value = valueResult }; object actualValue = null; try { actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture); } catch (FormatException e) { modelState.Errors.Add(e); } bindingContext.ModelState.Add(bindingContext.ModelName, modelState); return actualValue; } } ``` **Update** To use it simply declare the binder in Global.asax like this ``` protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); //HERE you tell the framework how to handle decimal values ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); DependencyResolver.SetResolver(new ETAutofacDependencyResolver()); } ``` Then when the modelbinder has to do some work, it will know automatically what to do. For example, this is an action with a model containing some properties of type decimal. I simply do nothing ``` [HttpPost] public ActionResult Edit(int id, MyViewModel viewModel) { if (ModelState.IsValid) { try { var model = new MyDomainModelEntity(); model.DecimalValue = viewModel.DecimalValue; repository.Save(model); return RedirectToAction("Index"); } catch (RulesException ex) { ex.CopyTo(ModelState); } catch { ModelState.AddModelError("", "My generic error message"); } } return View(model); } ```
Why not simply inspect the culture of the data and convert it as such? This simple approach allowed me to use strongly typed dates in models, show action links and edit fields in the desired locale and not have to fuss at all binding it back into a strongly typed DateTime: ``` public class DateTimeBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); return value.ConvertTo(typeof(DateTime), value.Culture); } } ```
46,345,356
I am having trouble understanding how to create a schema for the following type of flatfiles due to the fact that the tag identifier is not on the second field. I removed some extra data from the below example, but my problem is pretty much that the tag identifier (HDR/ODR and END) is preceded by an incremental number. ``` 000001 HDR 0000031001 1DP 000002 ORD 0000031001 0001 000003 ORD 0000031001 0001 000004 ORD 0000031001 0001 000005 ORD 0000031001 0001 000006 END ``` Solutions I have seen on google seem to be debatching the lines based on the first element assuming it is the same for all fields but that doesn't work in this case. Is there a way to set up the tag as the second element? The file is tab separated.
2017/09/21
[ "https://Stackoverflow.com/questions/46345356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/465651/" ]
If there are only those 3 tags, and the HDR and END only occur once, just create a schema where you have a schema where you have three records, 1 for the HDR, 1 for the ORD which can occur multiple times, and one for the END. You also have to alter the Lookahead depth from the default 3 to 0 (infinite). For example the following schema would parse that correctly. ``` <?xml version="1.0" encoding="utf-16"?> <xs:schema xmlns="http://Scratch.46345356" xmlns:b="http://schemas.microsoft.com/BizTalk/2003" targetNamespace="http://Scratch.46345356" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:annotation> <xs:appinfo> <schemaEditorExtension:schemaInfo namespaceAlias="b" extensionClass="Microsoft.BizTalk.FlatFileExtension.FlatFileExtension" standardName="Flat File" xmlns:schemaEditorExtension="http://schemas.microsoft.com/BizTalk/2003/SchemaEditorExtensions" /> <b:schemaInfo standard="Flat File" codepage="65001" default_pad_char=" " pad_char_type="char" count_positions_by_byte="false" parser_optimization="speed" lookahead_depth="0" suppress_empty_nodes="false" generate_empty_nodes="true" allow_early_termination="false" early_terminate_optional_fields="false" allow_message_breakup_of_infix_root="false" compile_parse_tables="false" root_reference="Root" /> </xs:appinfo> </xs:annotation> <xs:element name="Root"> <xs:annotation> <xs:appinfo> <b:recordInfo structure="delimited" child_delimiter_type="hex" child_delimiter="0xD 0xA" child_order="infix" sequence_number="1" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" /> </xs:appinfo> </xs:annotation> <xs:complexType> <xs:sequence> <xs:annotation> <xs:appinfo> <groupInfo sequence_number="0" xmlns="http://schemas.microsoft.com/BizTalk/2003" /> </xs:appinfo> </xs:annotation> <xs:element name="HDR"> <xs:annotation> <xs:appinfo> <b:recordInfo structure="delimited" child_delimiter_type="hex" child_delimiter="0x9" child_order="postfix" sequence_number="1" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" /> </xs:appinfo> </xs:annotation> <xs:complexType> <xs:sequence> <xs:annotation> <xs:appinfo> <groupInfo sequence_number="0" xmlns="http://schemas.microsoft.com/BizTalk/2003" /> </xs:appinfo> </xs:annotation> <xs:element name="Line" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="1" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="Tag" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="2" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="Data1" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="3" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="Data2" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="4" /> </xs:appinfo> </xs:annotation> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element minOccurs="0" maxOccurs="unbounded" name="ORD"> <xs:annotation> <xs:appinfo> <b:recordInfo structure="delimited" child_delimiter_type="hex" child_delimiter="0x9" child_order="infix" sequence_number="2" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" /> </xs:appinfo> </xs:annotation> <xs:complexType> <xs:sequence> <xs:annotation> <xs:appinfo> <groupInfo sequence_number="0" xmlns="http://schemas.microsoft.com/BizTalk/2003" /> </xs:appinfo> </xs:annotation> <xs:element name="Line" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="1" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="Tag" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="2" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="Data1" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="3" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="Data2" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="4" /> </xs:appinfo> </xs:annotation> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="END"> <xs:annotation> <xs:appinfo> <b:recordInfo structure="delimited" child_delimiter_type="hex" child_delimiter="0x9" child_order="infix" sequence_number="3" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" /> </xs:appinfo> </xs:annotation> <xs:complexType> <xs:sequence> <xs:annotation> <xs:appinfo> <groupInfo sequence_number="0" xmlns="http://schemas.microsoft.com/BizTalk/2003" /> </xs:appinfo> </xs:annotation> <xs:element name="Line" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="1" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="Tag" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" sequence_number="2" /> </xs:appinfo> </xs:annotation> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ``` Resulting in ``` <Root xmlns="http://Scratch.46345356"> <HDR xmlns=""> <Line>000001</Line> <Tag>HDR</Tag> <Data1>0000031001</Data1> <Data2>1DP</Data2> </HDR> <ORD xmlns=""> <Line>000002</Line> <Tag>ORD</Tag> <Data1>0000031001</Data1> <Data2>0001</Data2> </ORD> <ORD xmlns=""> <Line>000003</Line> <Tag>ORD</Tag> <Data1>0000031001</Data1> <Data2>0001</Data2> </ORD> <ORD xmlns=""> <Line>000004</Line> <Tag>ORD</Tag> <Data1>0000031001</Data1> <Data2>0001</Data2> </ORD> <ORD xmlns=""> <Line>000005</Line> <Tag>ORD</Tag> <Data1>0000031001</Data1> <Data2>0001</Data2> </ORD> <END xmlns=""> <Line>000006</Line> <Tag>END</Tag> </END> </Root> ```
Use Tag Identifier and Tag Offset you achieve your objective: ``` <?xml version="1.0" encoding="utf-16"?> <xs:schema xmlns:b="http://schemas.microsoft.com/BizTalk/2003" xmlns="http://BizTalkMassCopy.FlatFileSchema6" targetNamespace="http://BizTalkMassCopy.FlatFileSchema6" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:annotation> <xs:appinfo> <schemaEditorExtension:schemaInfo namespaceAlias="b" extensionClass="Microsoft.BizTalk.FlatFileExtension.FlatFileExtension" standardName="Flat File" xmlns:schemaEditorExtension="http://schemas.microsoft.com/BizTalk/2003/SchemaEditorExtensions" /> <b:schemaInfo standard="Flat File" codepage="65001" default_pad_char=" " pad_char_type="char" count_positions_by_byte="false" parser_optimization="speed" lookahead_depth="3" suppress_empty_nodes="false" generate_empty_nodes="true" allow_early_termination="false" early_terminate_optional_fields="false" allow_message_breakup_of_infix_root="false" compile_parse_tables="false" root_reference="Root" /> </xs:appinfo> </xs:annotation> <xs:element name="Root"> <xs:annotation> <xs:appinfo> <b:recordInfo structure="delimited" child_delimiter_type="hex" child_delimiter="0xD 0xA" child_order="infix" sequence_number="1" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" /> </xs:appinfo> </xs:annotation> <xs:complexType> <xs:sequence> <xs:annotation> <xs:appinfo> <groupInfo sequence_number="0" xmlns="http://schemas.microsoft.com/BizTalk/2003" /> </xs:appinfo> </xs:annotation> <xs:element name="Header"> <xs:annotation> <xs:appinfo> <b:recordInfo structure="positional" tag_name="HDR" tag_offset="8" sequence_number="1" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" /> </xs:appinfo> </xs:annotation> <xs:complexType> <xs:sequence> <xs:annotation> <xs:appinfo> <groupInfo sequence_number="0" xmlns="http://schemas.microsoft.com/BizTalk/2003" /> </xs:appinfo> </xs:annotation> <xs:element name="Count" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" pos_offset="0" pos_length="8" sequence_number="1" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="TagId" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" pos_offset="0" pos_length="3" sequence_number="2" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="Item" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" pos_offset="0" pos_length="17" sequence_number="3" /> </xs:appinfo> </xs:annotation> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element minOccurs="4" maxOccurs="4" name="Ord"> <xs:annotation> <xs:appinfo> <b:recordInfo structure="positional" sequence_number="2" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" tag_name="ORD" tag_offset="8" /> </xs:appinfo> </xs:annotation> <xs:complexType> <xs:sequence> <xs:annotation> <xs:appinfo> <groupInfo sequence_number="0" xmlns="http://schemas.microsoft.com/BizTalk/2003" /> </xs:appinfo> </xs:annotation> <xs:element name="Count" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" pos_offset="0" pos_length="8" sequence_number="1" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="TagId" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" pos_offset="0" pos_length="3" sequence_number="2" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="Item" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" pos_offset="0" pos_length="17" sequence_number="3" /> </xs:appinfo> </xs:annotation> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="End"> <xs:annotation> <xs:appinfo> <b:recordInfo structure="positional" sequence_number="3" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" tag_name="END" tag_offset="8" /> </xs:appinfo> </xs:annotation> <xs:complexType> <xs:sequence> <xs:annotation> <xs:appinfo> <groupInfo sequence_number="0" xmlns="http://schemas.microsoft.com/BizTalk/2003" /> </xs:appinfo> </xs:annotation> <xs:element name="Count" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" pos_offset="0" pos_length="8" sequence_number="1" /> </xs:appinfo> </xs:annotation> </xs:element> <xs:element name="TagId" type="xs:string"> <xs:annotation> <xs:appinfo> <b:fieldInfo justification="left" pos_offset="0" pos_length="3" sequence_number="2" /> </xs:appinfo> </xs:annotation> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ``` The result is this: ``` <Root xmlns="http://BizTalkMassCopy.FlatFileSchema6"> <Header xmlns=""> <Count>000001</Count> <TagId>HDR</TagId> <Item> 0000031001 1DP</Item> </Header> <Ord xmlns=""> <Count>000002</Count> <TagId>ORD</TagId> <Item> 0000031001 0001</Item> </Ord> <Ord xmlns=""> <Count>000003</Count> <TagId>ORD</TagId> <Item> 0000031001 0001</Item> </Ord> <Ord xmlns=""> <Count>000004</Count> <TagId>ORD</TagId> <Item> 0000031001 0001</Item> </Ord> <Ord xmlns=""> <Count>000005</Count> <TagId>ORD</TagId> <Item> 0000031001 0001</Item> </Ord> <End xmlns=""> <Count>000006</Count> <TagId>END</TagId> </End> </Root> ```
38,099,195
Is the solution of this exercise the below regular expression? I found it in the internet but I don't believe that this is correct. ``` (1*011*(0+011*))* ``` According to the theory of Chapter 1 in the book "The handbook of computational linguistics and natural language processing", how could I solve this exercise? I would like a regular expression that will satisfy the below regular language ``` L = {010,0101,0110,0101010,01011110,.....} ```
2016/06/29
[ "https://Stackoverflow.com/questions/38099195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3410338/" ]
You can go with: ``` ^(?!.*00.*)(?=.*0.*0).*$ ``` You can play with it [here](https://regex101.com/r/mY2xD7/5). Explanation: * `(?!.*00.*)` the input can't have two consecutive `0` * `(?=0.*0)` the input have to contains at least two `0` --- If you don't want to use lookaround use Maria's answer
``` 1*01(1|01)*01* ``` I think this would work perfectly
21,611
If I try to draw a grid in Inkscape, there are two different options: 1. `Extensions` -> `Render` -> `Grid` 2. `Extensions` -> `Render` -> `Kartesian Grid` But both of them use pixel-metric(?). Is it possible to use other metrics (e.g. millimeter). As a workaround, I converted pixel->millimeter, but it didn't work. There is always an odd scale factor in the conversion :-(. Do you have any solution?
2013/10/01
[ "https://graphicdesign.stackexchange.com/questions/21611", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/15720/" ]
Sadly, menu **Extensions -> Render -> Grids > Grid..**. does only take pixels as the measurement. So I am pretty sure conversion is the way to do it. I find the easiest, most accurate way to do conversion calculations for Inkscape is to do it in Inkscape. Use the rectangle tool to draw a rectangle on the canvas, then in the tools control bar for the rectangle tool, change the units to **mm**, and set the rectangle to the value you need (in the picture below, I set it to 5 mm square). ![Enter image description here](https://i.stack.imgur.com/cClId.png) Now, simply change the units back to **px**, and the width and height should have been converted to the pixel value: ![Enter image description here](https://i.stack.imgur.com/32nf4.png)
I don't know if the answer is to specific, but since their is no general solution to this problem, I cloned Inkscape and patched the grid functionality. I'll try to improve my patch, so it will be maybe in a release version one day (so please don't down-vote instantly). Until then, one has to clone [my repository](https://github.com/tik0/inkscapeGrid) and [build it](http://wiki.inkscape.org/wiki/index.php/CompilingUbuntu). My solution is as follows: `Extra` -> `Render` -> `Grids` -> `Grid` -> `Divide Selection by Spacing FA` By using this option, one can use the factor given in "Horizontal/Vertical Spacing" as subdivision factor for the selection. 1. Parameterize the selection in pt/cm/m/in/.. (or whatever) [![enter image description here](https://i.stack.imgur.com/lVJMd.png)](https://i.stack.imgur.com/lVJMd.png) 2. Create a grid by `Extra` -> `Render` -> `Grids` -> `Grid` 3. Set a tip at `Divide Selection by Spacing FA` 4. Select how many subdivisions of you selection you want to have [![enter image description here](https://i.stack.imgur.com/YPXjt.png)](https://i.stack.imgur.com/YPXjt.png) 5. Et voilà, a grid with 50mm/10=5mm vertical spacing and 50mm/20=2.5mm horizontal spacing [![enter image description here](https://i.stack.imgur.com/hfZmr.png)](https://i.stack.imgur.com/hfZmr.png) 6. It is also possible, to have an offset in the scale of a subdivision [![enter image description here](https://i.stack.imgur.com/dPMkB.png)](https://i.stack.imgur.com/dPMkB.png) 7. The grid is now shifted in x and y direction respectively [![enter image description here](https://i.stack.imgur.com/p9vd4.png)](https://i.stack.imgur.com/p9vd4.png)
874,316
A couple of weeks ago, I wrote a simple Ruby script to test a couple of FTP commands in a Windows XP environment. Everything worked as expected, and I wasn't even aware of the time taken for the code to run (I'd guess 3-4 seconds at the very most.) A few days ago, a much more involved Ruby application I'm developing started running very slowly. As I investigated the issue, I isolated the problem to the FTP commands. I've now rerun the original test script, and it takes over two *minutes* to run. Command-line FTP is essentially instantaneous. No files in the ruby directory structure have been changed. I do not believe any new applications have been installed - certainly no other applications appear to be running. Can anyone suggest why the following code should run so slowly? Manually timing the intervals between `print` statements suggest the `nlst` and `ls` take about 65 seconds each! The profiler gives a much more plausible total ms/call of 16 for `nlst` and 31 for `ls`. ``` require 'net/ftp' Net::FTP.open("ip_redacted", "user_redacted", "password_redacted") do |ftp| ftp.chdir("dir_redacted") files = ftp.nlst print "files = #{files.sort!}\n" list = ftp.ls print "list = #{list}\n" file = "filename_redacted" size = ftp.size(file) print "size = #{size}\n" end ```
2009/05/17
[ "https://Stackoverflow.com/questions/874316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74598/" ]
I had a similar issue and found Passive mode increased the speed, eg. `ftp.passive=true`.
Try removing the `#sort!` (just `puts "files = #{files}"`) since that can be fairly expensive if there's a bunch of files in the directory. This would account for the large lag around the `#nlst` and the `#ls`
31,339
I'm interested in computer music, where there are approaches to treat pieces of music as sentences in generative grammars or L-systems. Instead of composing, one could then specify a grammar and let the computer generate the music. E.g. the Yale group around the late Paul Hudak are very strong in that. It has struck me that we use seemingly one-dimensional representations of information to represent higher-dimensional things, like [plant growth with L-systems](https://en.wikipedia.org/wiki/L-system#Example_7:_Fractal_plant). Music, to me, seems to have at least two dimensions: The obvious time dimension and the "instrument" dimension, i.e. the ability to have several different sounds at the same time. And indeed, music notation has exactly these two dimensions. There are 2-dimensional programming languages like [Befunge](https://en.wikipedia.org/wiki/Befunge), which didn't strike me as very useful (yet), but I couldn't find anything about generative grammars, where the sentences are 2-dimensional. By a 2-dimensional sentence I mean that the characters are spread on a 2-dimensional grid, e.g. like this: ``` ab cde aabce dca b ``` Production rules could have 2-dimensional sentences on either side of the rule as well: ``` a -> bc e b -> cd e ab ``` **Has something like this been studied before?** For example in computer music, this could be quite useful. Pieces like [Ravel's Boléro](https://en.wikipedia.org/wiki/Bol%C3%A9ro#Structure) could be generated by a 2-dimensional production rule like this: ``` t -> tt t ``` This should be read as "If in a piece, the theme `t` is played by instrument 1 at some time, then we can produce a new piece in which `t` is played by instrument 1 at the same time, and immediately after by instrument 1 and 2."
2015/05/01
[ "https://cstheory.stackexchange.com/questions/31339", "https://cstheory.stackexchange.com", "https://cstheory.stackexchange.com/users/32941/" ]
Yes, there are n-dimensional grammars and in some cases specifically applied to music, see for example [Grammar-based music composition by Jon McCormack](http://users.monash.edu/~jonmc/research/Papers/L-systemsMusic.pdf), which talks about parametric extensions to L-grammars, or more generally, [Regulated Array Grammars of Finite Index, Part I: Theoretical Investigations by Henning FERNAU, Rudolf FREUND and Markus HOLZER](https://www.researchgate.net/publication/2608733_REGULATED_ARRAY_GRAMMARS_OF_FINITE_INDEX_Part_I_Theoretical_Investigations) which talk about n-dimensional array grammars.
there is some theoretical/ scientific/ applied research into modelling music with CS formal grammars. see eg * [Formal Grammars for Computational Musical Analysis](http://homepages.inf.ed.ac.uk/steedman/papers/music/slides5.pdf) / Steedman * [Musical grammars and computer analysis: a Review](http://www.jstor.org/stable/832733) / Snell however grammars may generally be too "regular" to *generate* interesting music. for that there are different approaches being explored eg genetic algorithms & there are many references on that. following, one highly cited article. this now known as the field of [evolutionary music](http://en.wikipedia.org/wiki/Evolutionary_music) * [COMPOSING WITH GENETIC ALGORITHMS](https://ece.umd.edu/~blj/papers/icmc95.pdf) / Jacobs
42,624,680
Build Unity project, add other libraries, Xcode return error. How fix it? ![Screenshot](https://i.stack.imgur.com/gVbmA.png)
2017/03/06
[ "https://Stackoverflow.com/questions/42624680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7637668/" ]
Make sure you're opening the .xcworkspace and not the .xcproject file in Xcode. Close the project and open .xcworkspace
![screenshot error code](https://i.stack.imgur.com/zqa1P.png) I also had such a problem, but only Xcode 10.2.1 had a problem, and Xcode 11.1 had no such problems. I solved this problem Select Target, go to BuildSettings and Search for Enable Bitcode flag and set it to No. ![screenshot xcode](https://i.stack.imgur.com/bGiRo.png)
8,489,557
I have the following code ``` $(function() { $('.apply').click(function(e) { var z = $(this).attr('z-id'); var r = $(this).attr('r-id'); $.post( "/r-set-z", "z_id=" + z + "&r_id=" + r, function(data) { alert(data); } ); }); }); ``` It works correct except that i see no alert with response data. Everything on server goes well. All data processing there done every time I click corresponding button. The data returning by the server is of type `application/javascript` and consist of the following ``` {"msg": "save successful"} ``` Why there is no alert after clicking a button?
2011/12/13
[ "https://Stackoverflow.com/questions/8489557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396862/" ]
> > > > > > For system block was set to 32. I tried SET RMS/BLOCK=32/BUF=8. That already gave an improvement. > > > > > > > > > [edit: If there is no process setting, then the system setting us used. So the test done added buffers, but did not make them bigger] 32 is just 16KB. Great for 1992, lame for 2012. If more buffers already helped, then larger buffers is likely to help even more. The larger the better. Multiples of 8KB may help just a but extra. Thus try 128, and also try 255 at the SET RMS process level. If it brings happiness, then you may want to adapt the process to select its own RMS settings and not rely on DCL settings. The RMS $GET call will normally only get a single record, but you could 'lie' about the the file, with SET FIL/ATTR=(RFM=UDF) or perhaps (RFM=FIX,LRL=8192). You can do that temporarily in a program using SYS$MODIFY. After that you can read in big chunks but your program will need to decode the real records in the spoofed records. That will be much like using SYS$READ / SYS$QIOW (BlockIO) but sticking to record mode will give you free 'read ahead'. Yeah you can code that yourself with aysnc IO, but that's a hassle. Btw... don't go crazy on the number of buffers. In benchmarks (many years ago) I saw little or negative benefits with more than 10 or so. The reason is that RMS does 'read ahead' but not 'keep ahead'. It fills all buffers asynchroneously, but then posts no additional read as buffers get processed. Only when all data is consumed will is re-issue IOs for all buffers, instead ot trying to keep ahead as buffers are processed. Those 'waves' of IOs can confuse storage subsystem, and the first IO in the wave may be slowed down by the rest of the wave... so the program waits. How much data is in play? tens of megabytes or gigabytes> Will the XFC cache have a change to cache it between the exports and the processing? Met vriendelijke groetjes. Hein.
Use C. Bypass RMS. **fopen** the file. **fseek** to end. **ftell** to get file size **malloc** a chunk of memory that size **fread** it in one go. One might suspect if your file is a lot larger than your working set, that paging may be what is eating your wall clock.
125,343
I would like to understand the term "system call". I am familiar that system calls are used to get kernel services from a userspace application. The part i need clarification with is the difference between a "system call" and a "C implementation of the system call". Here is a quote that confuses me: > > On Unix-like systems, that API is usually part of an implementation of > the C library (libc), such as glibc, that provides wrapper functions > for the system calls, often named the same as the system calls that > they call > > > What are the "system calls that they call"? Where is their source? Can I include them directly in my code? Is the "system call" in a generic sense just a POSIX defined interface but to actually see the implementation one could examine the C source and in it see how the actual userspace to kernel communication actually goes? Background note: I'm trying to understand if, in the end, each c function ends up interacting with devices from `/dev`.
2014/04/18
[ "https://unix.stackexchange.com/questions/125343", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/29436/" ]
A *system call* is a way to ask your operating system (kernel) to do some operation on behalf of your program, that the program can't do by itself (or is just inconvenient). The reason for not being able to do some operation is normally that allowing a random program to do them might compromise the integrity of the system, like doing I/O (directly to RAM, overwriting anything). POSIX defines an interface for programs, certain functions that your program can call. Some of those translate more or less directly to system calls, others require more elaboration. It is the runtime for your language, e.g. the C library, who is responsible for offering the POSIX interface, and to package arguments and receive results back to hand to the caller. Unixy systems offer POSIX interfaces more or less directly as system calls. Typically there is a way to invoke system calls directly, look for `syscall(2)` for the details on how to use this facility in Linux.
In Linux at least the system call mechanism works under most architectures by placing some specifically formatted data (usually some kind of c struct) in either some registers or predefined memory addresses. The issue comes however in actually forcing the CPU to do the switch into kernel space so it can run the privileged kernel code to service the call. This is done by forcing a fault of some sort (a fault being a divide by 0, an undefined overflow or a segfault, etc) this forces the kernel to take over execution to handle the fault. Normally the kernel handles faults by either killing the causing process or running a user supplied handler. However in the case of a syscall it will instead check the predefined registers and memory locations and if they contain a syscall request it will run that using the data provided by the user process in the in-memory struct. This usually has to be done with some specially hand crafted assembly and to ease the use of the syscall for the user the system's C library has to wrap it as a function. For a lower level interface please see <http://man7.org/linux/man-pages/man2/syscall.2.html> for some information on how syscalls work and how you can call then without a C wrapper. This is given an oversimplification, it is not true in all architectures (mips has a special syscall instruction) and not necessarily working the same on all OSes. Still, if you have any comments or questions please ask. Amended: Note, regarding your comment about things in /dev/ this is actually a higher level interface to the kernel, not a lower one. These devices actually use (about) 4 syscalls underneath. Writing to them is the same as a write syscall, reading a read syscall, open/closing them equivalant to the open and close syscalls and running an ioctl causes a special ioctl syscall which in itself is an interface to access one of the system's many ioctl calls (special, usually device specific calls with too narrow usage to write a whole syscall for them).
41,807,364
I'm using promises inside express middleware. I want to use the async/await methods. ``` app.get('/data1',async function(req,res) { data = await getData1(); // This line throw an error, res.send(data) }) app.get('/data2',async function(req,res) { data = await getData2(); // This line throw an error res.send(data) }) ``` This makes the browser wait forever. On the server I see ``` (node:251960) UnhandledPromiseRejectionWarning: Unhandled promise rejection ``` Now, to fix it for one middleware I'm doing: ``` app.get('/data1',async function (req,res){ return (async function(){ data = await getData1() })().catch(() => { res.send("You have an error") } }) app.get('/data2',async function (req,res){ return (async function(){ data = await getData2() })().catch(() => { res.send("You have an error") } }) ``` I don't like this repetion. How can I set default error? I have tried for example: ``` app.use(function(error,req,res,next)){ res.send('You have an error') } ``` But it didn't work. **In other words:** How to set default function to be called when Express middlewares returning a rejected promise?
2017/01/23
[ "https://Stackoverflow.com/questions/41807364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1229624/" ]
Now I found a way how to do it, I'm still keep the question open for more suggestions ``` app.get("/data1", wrap_middleware(async (req, res) => { data1=await getData1() res.send(data1) }) } app.get("/data1", wrap_middleware(async (req, res) => { data2=await getData2() }) } function wrap_middleware(func) { return async (req, res, next) => { func(req, res, next).catch(err => { console.log(err.message); res.send("Error"); }); }; } ```
I don't understand the use of sending the same error for different function but I think the handling error code could be write in more readable way (just catch the error and do with them what you want the same way you catch errors in any route middleware): ``` function getData1(){ return new Promise( (resolve,reject) => { setTimeout(() =>{ reject(new Error('error has occur!')); },2000); }); } router.get('/data1', async (req,res, next) => { try{ const data = await getData1(); res.send(data); } catch(ex){ res.send(ex.message); // next(ex); => sending it to express to handle it } }); ``` If you want a global error handling then its not any different from any code you want catch errors globally - you can set a function that take as param , the response object and the async code and create general catch for every async call comes from middleware (which has response object)
15,140,206
I'm working on a theme using Twitter Bootstrap, and I'm trying to get the drop down navigation to be centered instead of left-aligned. To be clear: I'm talking about centering the whole drop down box relative to its parent, not about centering the text inside the box. The markup looks like this: ``` <ul id="nav" class="nav ww-nav pull-right hidden-phone"> <li class="active"><a href="#">Words</a></li> <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Articles</a> <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel"> <li><a href="#">Published</a></li> <li><a href="#">Categorized</a></li> <li><a href="#">Uncategorized</a></li> <li><a href="#">Award Winning</a></li> </ul> </li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> ``` To clarify what I mean, I'll attach a screenshot: ![Bootstrap dropdown menu](https://i.stack.imgur.com/V4BAu.png) **Note:** I'm looking for a general solution, that works with different parent items. Since it is a theme, the navigation items can be anything from 3 characters to 20 characters wide. A simple margin by X pixels doesn't cut it, unfortunately. PS: As requested in the comments, I put the whole thing on JSFiddle: <http://jsfiddle.net/zdCYX/4/> Thanks
2013/02/28
[ "https://Stackoverflow.com/questions/15140206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199685/" ]
I solved this using jQuery, calculating and adjusting the margin-left of every sub menu. This way my navigation items have the same space between each other. ``` document.onreadystatechange = function() { if (document.readyState === 'complete') { $("ul.ww-nav ul.dropdown-menu").each(function(){ var parentWidth = $(this).parent().innerWidth(); var menuWidth = $(this).innerWidth(); var margin = (parentWidth / 2 ) - (menuWidth / 2); margin = margin + "px"; $(this).css("margin-left", margin); }); } } ```
Jsfiddle [Demo in browser](http://jsfiddle.net/shail/h56LW/show/) What you can do is set the width to the main nav element and than to the drop down : like following : ``` .navbar .nav > li { width: 116px; } .dropdown-menu { display:none; width:116px; min-width:116px; margin:0 auto; } ``` You will have to change the following code align elements ``` .dropdown-menu > li > a { text-align:center; } ```
9,913,151
Good day, I am trying to copy files back and forth to my Xyboard from my Ubuntu machine. From my understanding, Motorola only allows this to happen via the USB cable if Motocast is running on the computer which is currently only available for Windows and Mac. I had to create a file sharing service and then download an FTP client app to my Xyboard to accomplish the goal, but I was looking for a quicker way view the usb cable. Does anyone know how? I would also like to avoid 1) a virtual windows box 2) WINE
2012/03/28
[ "https://Stackoverflow.com/questions/9913151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1226843/" ]
On my `Droid Razr`, I just use `ES File Explorer`. It lets me browse and copy any shared Samba network files, or folders, just like any other computer. The Droid Razr is a Linux machine, and it works just like any other Linux machine. You just need to set permissions on your shared folders to write or whatever. On my home network, I have a public movie/music folder that anyone can read, but nobody can write to. I also have permissions set for individual user home folders, and private group folders. `ES File Browser` also lets you browse all the way to root on the Android device. In case you are curious, the flash cards are mounted under `/mnt/sdcard` for the internal card, and `/mnt/sdcard-ext` for the external removable card. People seem to be a little confused by the Android file system, but it's Linux, with the Android windows environment running. Android phones are Linux systems WITHOUT X-windows compiled and installed on them. You can compile and install X-Windows on your Droid device. Here's an Android phone running Ubuntu. [Ubuntu on Android Phone](http://www.youtube.com/watch?v=JVSNIJs0lWw)
I installed mtpfs from synaptic. I restarted my computer and my tablet but I don't think you have to. Worked perfect. EDIT: only works for camera mode. not MTP. :-(
129,456
I was looking at my bank website's certificate and discovered that it's issued to multiple websites, and the bank's domain name is only listed among many other domains in the 'alternative names' field. Is this considered a bad practice? What risks are their customers subjected to? (man in the middle? impersonation?) [![SSL Labs screenshot](https://i.stack.imgur.com/gdwnW.png)](https://i.stack.imgur.com/gdwnW.png)
2016/07/07
[ "https://security.stackexchange.com/questions/129456", "https://security.stackexchange.com", "https://security.stackexchange.com/users/116881/" ]
Notice `incapsula.com` in the subject. [Incapsula](https://www.incapsula.com/) is a company that offers web application security that includes WAF, DDOS protection and a few more services. My guess is that your banks website is actually proxied through their server and so are all those other sites. That server gives out the same certificate on all those sites because they are all actually proxied through the same server. There is no reason to worry here.
I'm with the Imperva Incapsula Team. There seem to be a lot of confusion, so I'd like to point out a few facts: 1. The vast majority of all websites use a CDN. 2. We are PCI-certified and SOC2-certified company, all data processing, access and any other compliance-related issue is tightly regulated, audited and logged. 3. We have some of the biggest banks, financial and healthcare organizations, and governments using our service and trusting us with their certificates. 4. Honestly, Bank IT departments are some of the most scrutinized in the IT industry, you can trust they know SSL/TLS cert best-practices. **But most importantly - it's just not a security hazard. In any way.** Take all the comments here with a big chunk of salt. I feel it's important to state that these comments (even if written in good intention) are baseless, misguided and false: * "Compromise of any of there other sites can mean that your SSL traffic is no longer safe" --nope * "Adding a new domain for service involves re-issuing the certificate with its associated downtime." --nope * "Forward HTTP (notice, no S) traffic to the real servers inside the CDN network." --nope * "Your bank may be violating privacy laws in your country by letting a company from another country, under a different legislature, process customers' personally identifiable data." --may, but nope HTH
157,329
There is apparently a vulnerability (CVE-2014-6271) in bash: [Bash specially crafted environment variables code injection attack](https://securityblog.redhat.com/2014/09/24/bash-specially-crafted-environment-variables-code-injection-attack/) I am trying to figure out what is happening, but I'm not entirely sure I understand it. How can the `echo` be executed as it is in single quotes? ```none $ env x='() { :;}; echo vulnerable' bash -c "echo this is a test" vulnerable this is a test ``` --- **EDIT 1**: A patched system looks like this: ```none $ env x='() { :;}; echo vulnerable' bash -c "echo this is a test" bash: warning: x: ignoring function definition attempt bash: error importing function definition for `x' this is a test ``` **EDIT 2**: There is a related vulnerability / patch: [CVE-2014-7169](https://access.redhat.com/articles/1200223) which uses a slightly different test: ```none $ env 'x=() { :;}; echo vulnerable' 'BASH_FUNC_x()=() { :;}; echo vulnerable' bash -c "echo test" ``` *unpatched output*: ```none vulnerable bash: BASH_FUNC_x(): line 0: syntax error near unexpected token `)' bash: BASH_FUNC_x(): line 0: `BASH_FUNC_x() () { :;}; echo vulnerable' bash: error importing function definition for `BASH_FUNC_x' test ``` *partially (early version) patched output*: ```none bash: warning: x: ignoring function definition attempt bash: error importing function definition for `x' bash: error importing function definition for `BASH_FUNC_x()' test ``` *patched output* up to and including CVE-2014-7169: ```none bash: warning: x: ignoring function definition attempt bash: error importing function definition for `BASH_FUNC_x' test ``` **EDIT 3**: story continues with: * [CVE-2014-7186](http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-7186) * [CVE-2014-7187](http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-7187) * [CVE-2014-6277](http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-6277)
2014/09/24
[ "https://unix.stackexchange.com/questions/157329", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/16841/" ]
bash stores exported function definitions as environment variables. Exported functions look like this: ```none $ foo() { bar; } $ export -f foo $ env | grep -A1 foo foo=() { bar } ``` That is, the environment variable `foo` has the literal contents: ```none () { bar } ``` When a new instance of bash launches, it looks for these specially crafted environment variables, and interprets them as function definitions. You can even write one yourself, and see that it still works: ```none $ export foo='() { echo "Inside function"; }' $ bash -c 'foo' Inside function ``` Unfortunately, the parsing of function definitions from strings (the environment variables) can have wider effects than intended. In unpatched versions, it also interprets arbitrary commands that occur after the termination of the function definition. This is due to insufficient constraints in the determination of acceptable function-like strings in the environment. For example: ```none $ export foo='() { echo "Inside function" ; }; echo "Executed echo"' $ bash -c 'foo' Executed echo Inside function ``` Note that the echo outside the function definition has been unexpectedly executed during bash startup. The function definition is just a step to get the evaluation and exploit to happen, the function definition itself and the environment variable used are arbitrary. The shell looks at the environment variables, sees `foo`, which looks like it meets the constraints it knows about what a function definition looks like, and it evaluates the line, unintentionally also executing the echo (which could be any command, malicious or not). This is considered insecure because variables are not typically allowed or expected, by themselves, to directly cause the invocation of arbitrary code contained in them. Perhaps your program sets environment variables from untrusted user input. It would be highly unexpected that those environment variables could be manipulated in such a way that the user could run arbitrary commands without your explicit intent to do so using that environment variable for such a reason declared in the code. Here is an example of a viable attack. You run a web server that runs a vulnerable shell, somewhere, as part of its lifetime. This web server passes environment variables to a bash script, for example, if you are using CGI, information about the HTTP request is often included as environment variables from the web server. For example, `HTTP_USER_AGENT` might be set to the contents of your user agent. This means that if you spoof your user agent to be something like '() { :; }; echo foo', when that shell script runs, `echo foo` will be executed. Again, `echo foo` could be anything, malicious or not.
*I wrote this as a tutorial-style recasting of the excellent answer by Chris Down above.* --- In bash you can have shell variables like this ``` $ t="hi there" $ echo $t hi there $ ``` By default, these variables are not inherited by child processes. ``` $ bash $ echo $t $ exit ``` But if you mark them for export, bash will set a flag that means they will go into the environment of subprocesses (although the `envp` parameter is not much seen, the `main` in your C program has three parameters: `main(int argc, char *argv[], char *envp[])` where that last array of pointers is an array of shell variables with their definitions). So let's export `t` as follows: ``` $ echo $t hi there $ export t $ bash $ echo $t hi there $ exit ``` Whereas above `t` was undefined in the subshell, it now appears after we exported it (use `export -n t` if you want to stop exporting it). But functions in bash are a different animal. You declare them like this: ``` $ fn() { echo "test"; } ``` And now you can just invoke the function by calling it as if it were another shell command: ``` $ fn test $ ``` Once again, if you spawn a subshell, our function is not exported: ``` $ bash $ fn fn: command not found $ exit ``` We can export a function with `export -f`: ``` $ export -f fn $ bash $ fn test $ exit ``` Here's the tricky part: an exported function like `fn` is converted into an environment variable just like our export of the shell variable `t` was above. This doesn't happen when `fn` was a local variable, but after export we can see it as a shell variable. However, you can **also** have a regular (ie, non function) shell variable with the same name. bash distinguishes based on the contents of the variable: ``` $ echo $fn $ # See, nothing was there $ export fn=regular $ echo $fn regular $ ``` Now we can use `env` to show all shell variables marked for export and both the regular `fn` and the function `fn` show up: ``` $ env . . . fn=regular fn=() { echo "test" } $ ``` A sub-shell will ingest both definitions: one as a regular variable and one as a function: ``` $ bash $ echo $fn regular $ fn test $ exit ``` You can define `fn` as we did above, or directly as a regular variable assignment: ``` $ fn='() { echo "direct" ; }' ``` Note this is a high unusual thing to do! Normally we would define the function `fn` as we did above with `fn() {...}` syntax. But since bash exports it through the environment, we can "short cut" directly to the regular definition above. Note that (counter to your intuition, perhaps) this does **not** result in a new function `fn` available in the current shell. But if you spawn a \*\*sub\*\*shell, then it will. Let's cancel export of the function `fn` and leave the new regular `fn` (as shown above) intact. ``` $ export -nf fn ``` Now the function `fn` is no longer exported, but the regular variable `fn` is, and it contains `() { echo "direct" ; }` in it. Now when a subshell sees a regular variable that begins with `()` it interprets the rest as a function definition. But this is **only** when a new shell begins. As we saw above, just defining a regular shell variable starting with `()` does not cause it to behave like a function. You have to start a subshell. ***And now the "shellshock" bug:*** As we just saw,when a new shell ingests the definition of a regular variable starting with `()` it interprets it as a function. However, if there is more given after the closing brace that defines the function, it **executes whatever** is there as well. These are the requirements, once more: 1. New bash is spawned 2. An environment variable is ingested 3. This environment variable starts with "()" and then contains a function body inside braces, and then has commands afterward In this case, a vulnerable bash will execute the latter commands. Example: ``` $ export ex='() { echo "function ex" ; }; echo "this is bad"; ' $ bash this is bad $ ex function ex $ ``` The regular exported variable `ex` was passed to the subshell which was interpreted as a function `ex` but the trailing commands were executed (`this is bad`) as the subshell spawned. --- ***Explaining the slick one-line test*** A popular one-liner for testing for the Shellshock vulnerability is the one cited in @jippie's question: ``` env x='() { :;}; echo vulnerable' bash -c "echo this is a test" ``` Here is a break-down: first the `:` in bash is just a shorthand for `true`. `true` and `:` both evaluate to (you guessed it) true, in bash: ``` $ if true; then echo yes; fi yes $ if :; then echo yes; fi yes $ ``` Second, the `env` command (also built into bash) prints the environment variables (as we saw above) but also can be used to run a single command with an exported variable (or variables) given to that command, and `bash -c` runs a single command from its command-line: ``` $ bash -c 'echo hi' hi $ bash -c 'echo $t' $ env t=exported bash -c 'echo $t' exported $ ``` So sewing all of this stuff together, we can run bash as a command, give it some dummy thing to do (like `bash -c echo this is a test`) and export a variable that starts with `()` so the subshell will interpret it as a function. If shellshock is present, it will also immediately execute any trailing commands in the subshell. Since the function we pass is irrelevant to us (but must parse!) we use the shortest valid function imaginable: ``` $ f() { :;} $ f $ ``` The function `f` here just executes the `:` command, which returns true and exits. Now append to that some "evil" command and export a regular variable to a subshell and you win. Here is the one-liner again: ``` $ env x='() { :;}; echo vulnerable' bash -c "echo this is a test" ``` So `x` is exported as a regular variable with a simple valid function with `echo vulnerable` tacked on to the end. This is passed to bash, and bash interprets `x` as a function (which we don't care about) then perhaps executes the `echo vulnerable` if shellshock is present. We could shorten the one-liner a little by removing the `this is a test` message: ``` $ env x='() { :;}; echo vulnerable' bash -c : ``` This doesn't bother with `this is a test` but runs the silent `:` command yet again. (If you leave off the `-c :` then you sit in the subshell and have to exit manually.) Perhaps the most user-friendly version would be this one: ``` $ env x='() { :;}; echo vulnerable' bash -c "echo If you see the word vulnerable above, you are vulnerable to shellshock" ```
141,413
Should the sole user of a \*nix (particularly Linux and MacOS) have two accounts, one with sudo privileges and one without? Years ago I read that on your personal computer you should do your daily tasks as an unprivileged user and switch to a privileged user for administration tasks. Is this true? Note: I am *not* referring to whether or not you should log in as root for daily use. That's obviously a bad idea, but should your daily use account be able to use sudo? Second note: I am specifically referring to personal devices that are *not* being used as servers or to host any functionality for remote users.
2016/10/31
[ "https://security.stackexchange.com/questions/141413", "https://security.stackexchange.com", "https://security.stackexchange.com/users/129232/" ]
Every machine needs a admin account, whatever the OS. Ok, most Linux flavours *hide* root user by giving it an inexistant password - in the sense that any input will return false - but root does exist and has user id 0. That admin account can change anything to the system, including things that are not allowed to normal users. The line of defense here, is that if an attacker gains access to the root user *by chance* (\*) he can easily install a backdoor to be able to gain it again at will. And you will hardly notice it unless you consitently analyze the security of your systems (logs, changes in system files, ...) on a regular base. If an attacker gains access to a non root account by chance, he will only be able to make changes to what is accessible to this account. Ok, he could change the password if he managed to get a shell, but you will certainly notice it next time you try to login! That means that the defence line of not using root is only against distant attacks - if somebody has physical access to a machine, he can read everything that in not strongly encrypted and write/erase absolutely everything - including the password database to add other admin accounts. The only exception here is that if the whole disk is encrypted, the only possible action is to erase everything and fresh re-install. But I admit that even if I know that sudo is a great software and can be used to allow fine grained permission. I do not like very much the default Linux way where sudo can do anything, because it is vulnerable to this: * an attacker gains access to a non root shell allowed to sudo * he changes the account password * he sudoes as root and installs a backdoor (or a modified version of su that asks no password - trivial to write) * he breaks the master password file and goes away Next time you try to login, you will notice that you cannot, use the recovery procedure to discover that the master password is broken, rebuild it or re-install it from an archived version and if you do not carefully analyze the system, never notice the back door. --- When I said *gain access by chance*, I mean in a non reproductible way, for instance, if it uses a vulnerability when you connect to a malicious site. Unless the attacker install a backdoor, he will only gain access again when you come back to that site, which may or not occur. TL/DR: My opinion is that any machine should have at least 2 account: one non priviledged one for normal usage, and an administrative one for administrative tasks.
Aren't backups the solution to this problem? Backing up the entire hard drive on a regular basis looks like a good idea in general for various reasons, the possibility of screwing up .bashrc is one of them.
543
While most of the gyms and dojos where I've trained so far had mirrors to help you work on your technique I think videos are underused. In my opinion, taking a video of e.g. a sparring session or while training technique is much better than looking at a mirror, because you can fully concentrate on what you are doing and watch the resuls *later*. Historically, this is understandable, as video cameras used to be expensive and replaying the videos used to be cumbersome. But nowadays, where smartphones have ridiculously good cameras I believe it could and should be used more. What is your take on this? Does filming and analyzing yourself in training help to improve technique?
2012/02/19
[ "https://martialarts.stackexchange.com/questions/543", "https://martialarts.stackexchange.com", "https://martialarts.stackexchange.com/users/129/" ]
A tool is only as dangerous as its user. Analyzing yourself is only as good as you are able to be objective, and **only as good as you will be at analyzing yourself**. Sending a video to a teacher because of geographical reasons is a good idea, if the teacher agrees to it. The teacher can make corrections.
There is a huge problem with videotaping yourself and playing it back for your own purposes, in my experience. When I was first starting out, I would often times (along with another *buyu*) film classes and go back and review the footage, especially what I was doing, and correct my technique based on that while I practiced between classes. Let's take, for example, the *waza* of *ganseki nage*. I'm going to show you the technique the way *Takamatsu Toshitsugu* performed it as an authoritative reference. See it on [YouTube](http://www.youtube.com/watch?v=D0oOI4P_Vf4). Now, since I was performing the technique as a new student, I was watching videos of myself with a hunched over back straining with all my muscle (I didn't have much) to make the technique work, and eventually my partner's balance would get disrupted by me pushing my leg out wide, etc. So I was watching what worked, and unable to see that it was ***wrong***. My first clue was years later when I learned the real fundamentals; the principles on which the art operates. I kept my back in alignment to maintain balance, I used my strong (rigid/bones) parts against their weak (flexible/joints). I took their space. It took years of training to learn how to have eyes for the art. I had to learn how to examine the art from my instructor so I could see the problems I was facing the way he did. We are subjective animals. We want to view our abilities as flawless, but we are inherently flawed. As soon as we start to have the ability to some degree to perform an act, we want to think we are the best at performing that act. This is human nature; we are naturally biased toward our own abilities because it helps us have a desire to continue to learn. But we are completely unable to learn solely on our own. We make mistakes that we can not recognize, even in subjects such as math and science. We see farther by standing on the shoulders of giants. If you want to film someone, film your instructor. It'll be far less of a waste of tape.
20,041,931
I need to modify Dijkstra's algorithm so that if there are several shortest paths I need to find the one with minimum number of edges on the path. I've been stuck on how to use Dijkstra's method to find multiple shortest paths, how do you do that? doesn't it always output only 1 shortest path? pseudo code or any general direction would be very helpful.
2013/11/18
[ "https://Stackoverflow.com/questions/20041931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2321926/" ]
Instead of assigning every node with the distance from source you can assign the number of edges traversed so far also. So each node will have `(distance,edges)` instead of `distance` only. Everything else works as usual and for every terminal node you record the one with minimum value of `(distance,edges)`.
Another option would be to add some small number `ε` to the weight of every edge, where `ε << edgeWeights` *(for integer edge-weights you can choose `ε < gcd(edgeWeights)/numberOfEdges`)* The advantage of this approach is that you don't need to write your own pathfinder, you can just use any off-the-shelf implementation.
54,659,491
At my job, I am occasionally tasked with entering data from an HTML page into an excel file manually. This usually details something like a course offering list where I have to get the title, degree type, link to the page, and other information. Is there a way I can programmatically handle this? I have beginner to intermediate programming skills in Java, Python, and PHP and I've got very solid foundations in Web Dev. Conceptually from what I understand, I would have to loop to find certain text between tags/classes and then dump that into another text file? From there I'm pretty lost. What should I do?
2019/02/12
[ "https://Stackoverflow.com/questions/54659491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11053179/" ]
You just need to add parenthesis around the returned object literal. ```js const my_arr = [1,2,3,4,5]; const data = my_arr.map((element, index) => ({ a: element, b:index })); // ^ ^ console.log(data); ``` The reason is that the JavaScript parser rules assume that the `{` following the `=>` is the start of a function body. To go around this, we wrap the object in `()` (alternatively we can add a `return` statement) Read more here: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Returning_object_literals>
So, it works See output: ```js var results = []; [...Array(11).keys()].forEach((el) => { if (el % 2 === 0) { results.push({ a: el, b: el + 1 }) } }) console.log('results',results) ```
38,555,588
according to Aamir in [When to use an interface instead of an abstract class and vice versa?](https://stackoverflow.com/questions/479142/when-to-use-an-interface-instead-of-an-abstract-class-and-vice-versa) > > When you derive an Abstract class, the relationship between the > derived class and the base class is 'is a' relationship. e.g., a Dog > is an Animal, a Sheep is an Animal which means that a Derived class is > inheriting some properties from the base class. > > > Whereas for implementation of interfaces, the relationship is "can > be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog > can be a race dog. Which means that you implement certain methods to > acquire something. > > > But how about the abilities? Like, "A dog can bark", "a cat can jump", "a snake can slither", where will I put these, in an abstract or an interface?
2016/07/24
[ "https://Stackoverflow.com/questions/38555588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872912/" ]
If you have some common abilities, like move, you can have an interface of those and have the abstract class implement those methods (if animals are the only thing you'll work with, then you wouldn't really gain much by having that interface I believe). If you are having specific abilities that would apply only on certain derived classes, have them implement the interface. Dog barking seems to be an ability only for a single derived class, why not leave it be implemented by that derived class? Having it in the abstract class would mean all animals would be able to bark, but then again having a dog class implement an interface that has bark in it seem a bit weird if dog is your only animal capable of barking. Side note: interfaces don't necessarily have to be defined as "can be" relationship.
The ability to do something would probably be best suited to an interface, unless you are looking to provide some default behaviour if the method is not implemented. Keep in mind that C# does not support inheriting from multiple classes, but does support implementing multiple interfaces. This allows for some flexibility. Such as this: ``` interface IBreathes() { void Breathe(); } interface IMoveable() { void Move(int x, int y); } class Snake : Animal, IBreathes, IMoveable { void Breathe() { ... } void Move(int x, int y) { ... } } ``` For the above example use of abstract classes would be fine, but with large, complex projects it may become quite frustrating to work around the single-inheritance issue.
419,331
There seems to be two (main) ways of pronouncing "Los Angeles": 1. Los An-jel-eeze 2. Los An-jel-ess It's clearly Spanish, and my limited Spanish skills suggest option 2, but I've heard many people use option 1 (including commercial aircraft pilots over the intercom). Which is "correct"? --- ### Update: In the classic 1938 movie *Double Indemnity*, at 1:18:00 into the movie, Edward G Robinson clearly pronounces Los Angeles to rhyme with cheese!
2017/11/22
[ "https://english.stackexchange.com/questions/419331", "https://english.stackexchange.com", "https://english.stackexchange.com/users/12060/" ]
According to *Oxford Dictionaries Online,* the [British pronunciation](https://en.oxforddictionaries.com/definition/los_angeles) rhymes with *cheese* (as the comments say, it's closer to the last syllable of Hercules), while the [American pronunciation](https://en.oxforddictionaries.com/definition/us/los_angeles) does not; rather, it nearly rhymes with *scandalous* (or maybe *evangelist*).
It depends on what you *want* it to rhyme with. From ["Coming Into Los Angeles"](https://www.youtube.com/watch?v=q9xL_OVvPn0) by Arlo Guthrie: "Coming into Los Angeles, Bringing in a couple of keys, Don't touch my bags if you please, Mr. Customs man." It really doesn't work very well if you rhyme with "mess".
4,974,238
Python has this beautiful function to turn this: ``` bar1 = 'foobar' bar2 = 'jumped' bar3 = 'dog' foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1 # The lazy dog jumped over the foobar ``` Into this: ``` bar1 = 'foobar' bar2 = 'jumped' bar3 = 'dog' foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1) # The lazy dog jumped over the foobar ``` Does JavaScript have such a function? If not, how would I create one which follows the same syntax as Python's implementation?
2011/02/11
[ "https://Stackoverflow.com/questions/4974238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/464744/" ]
Taken from YAHOOs library: ``` YAHOO.Tools.printf = function() { var num = arguments.length; var oStr = arguments[0]; for (var i = 1; i < num; i++) { var pattern = "\\{" + (i-1) + "\\}"; var re = new RegExp(pattern, "g"); oStr = oStr.replace(re, arguments[i]); } return oStr; } ``` Call it like: ``` bar1 = 'foobar' bar2 = 'jumped' bar3 = 'dog' foo = YAHOO.Tools.printf('The lazy {0} {1} over the {2}', bar3, bar2, bar1); ```
JavaScript does not have a string formatting function by default, although you can create your own or use one someone else has made (such as [sprintf](http://www.diveintojavascript.com/projects/javascript-sprintf))
43,313,071
``` INSERT INTO EMP_1 (EMP_NUM, EMP_LNAME, EMP_FNAME, EMP_INITIAL, EMP_HIREDATE, JOB_CODE) VALUES ('101', 'News', 'John', 'G', '08-Nov-00', '502'), ('102', 'Senior', 'David', 'H', '12-Jul-89', '501'); ``` I've been searching for quite some time and most people say to but the comma between the two sets but when I do that it says that it is missing a `;` at the end of the SQL statement so then I separate them with the `;` and get the error that talks about code after the semi-colon, which is understandable. I've even tried `SELECT` and `UNIONALL` to no avail and was just checking out [this](https://stackoverflow.com/questions/62504/is-there-any-way-to-create-multiple-insert-statements-in-a-ms-access-query "Using select and union all") but it still recommended the `SELECT` and `UNIONALL`. Is there something I'm missing completely? I'm using MS Access 2016, thanks in advance for the help.
2017/04/09
[ "https://Stackoverflow.com/questions/43313071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3681583/" ]
MS Access does not permit multiple rows being inserted with a single `insert . . . values`. I think the "typical" MS Access solution is: ``` INSERT INTO EMP_1 (EMP_NUM, EMP_LNAME, EMP_FNAME, EMP_INITIAL, EMP_HIREDATE, JOB_CODE) VALUES ('101', 'News', 'John', 'G', '08-Nov-00', '502'); INSERT INTO EMP_1 (EMP_NUM, EMP_LNAME, EMP_FNAME, EMP_INITIAL, EMP_HIREDATE, JOB_CODE) VALUES ('102', 'Senior', 'David', 'H', '12-Jul-89', '501'); ```
The link you have given already state that you CANNOT do ``` insert into foo (c1, c2, c3) values ("v1a", "v2a", "v3a"), ("v1b", "v2b", "v3b"), ("v1c", "v2c", "v3c") ``` Which is exactly the way you are doing it now. Try ``` INSERT INTO EMP_1 (EMP_NUM, EMP_LNAME, EMP_FNAME, EMP_INITIAL, EMP_HIREDATE, JOB_CODE) SELECT * FROM (select top 1 "101" AS EMP_NUM, "News" AS EMP_LNAME, "John" AS EMP_FNAME, "G" AS EMP_INITIAL, "08-Nov-00" AS EMP_HIREDATE, "502" AS JOB_CODE from onerow union all select top 1 "102" AS EMP_NUM, "Senior" AS EMP_LNAME, "David" AS EMP_FNAME, "H" AS EMP_INITIAL, "12-Jul-89" AS EMP_HIREDATE, "501" AS JOB_CODE from onerow) ``` I am not sure about MS-Access SQLs. But `"` is differ from `'` in SQL. It seems that the link you give uses `"` as the answer. Why not give it a try? But generally `'` should be used for string values.
1,866,100
I have just sucessfully tested my Zend based application on the localhost.When I deployed it on a shared hosting site I got the error below.It happens whenever I try navigate to protected pages of my application. ``` Warning: include(/home/davidkag/public_html/prototype/application/models/DbTable//Users.php) [function.include]: failed to open stream: No such file or directory in /home/davidkag/public_html/prototype/library/Zend/Loader/Autoloader/Resource.php on line 176 ``` I have a feeling that the double slashes > > models/DbTable//Users.php) > > > are causing this problem. The error is caused at this particular line in my code: ``` Fatal error: Class 'Model_DbTable_Users' not found in /home/davidkag/public_html/prototype/application/controllers/AuthController.php on line 24 ``` How do I trouble shoot this problem.Keep in mind that on my localhost machine its working fine.
2009/12/08
[ "https://Stackoverflow.com/questions/1866100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197208/" ]
This doesn't answer the question, just wanted to share something. From [PHP Manual: String Operators](http://php.net/manual/en/language.operators.string.php), someone posted this which I find rather interesting. Notice how the space plays a part in the output. **Excerpt:** If you attempt to add numbers with a concatenation operator, your result will be the result of those numbers as strings. ``` <?php echo "thr"."ee"; //prints the string "three" echo "twe" . "lve"; //prints the string "twelve" echo 1 . 2; //prints the string "12" echo 1.2; //prints the number 1.2 echo 1+2; //prints the number 3 ?> ```
While this isn't the historical reason it maybe show you why it is good to have a separate operator for addition and concatenation in the case of PHP. The reason is what we see in JavaScript. We use the `+` character for concatenation and addition too. In PHP we have a separate operator for the two which is important for dynamically typed languages where implicit type conversion also present. In PHP ------ ```php echo 5 + 1; //6 echo 5 . 1; //51 echo "5" + 1; //6 echo "5" . 1; //51 ``` This isn't surprising for anyone because we always explicitly stated whether we want to add or concatenate the two variable. Or in other words if we think about them as numbers or as strings. In JavaScript ------------- ```js console.log( 5 + 1); //6 console.log("5" + 1); //51 console.log( 5 + "1"); //51 console.log("5" + "1"); //51 ``` Without the knowledge of how implicit type conversions happen under the hood, in many cases (especially if they are complex) surprising results can happen, because we don't know what will be the outcome, because it isn't explicitly stated. In Python --------- Python also uses the `+` operator for concatenation and for addition too, but it doesn't let implicit type conversion to happen. You have to explicitly mark the type conversion. ```python print 5 + 1 //6 print "5" + 1 //TypeError: cannot concatenate 'str' and 'int' objects ``` We have to do type conversion to make it work: `a + int(b)` All in all ---------- If we think about it, we can see that almost the same thing happens in PHP what we see in Python but instead of explicitly marking the type conversion, we mark with the operator that how we see the variables in terms of types.
14,507,370
I got a WebView that load an HTML file with a text. The problem is that the color inside the html and outside isn't the same. Here is a screenshot: ![The Activity With the WebView](https://i.stack.imgur.com/fVOcdl.png) The HTML FIle is: ``` <html dir="rtl"> <head> <title>About</title> <meta content="text/html; charset=UTF-8" http-equiv="content-type"/> <body bgcolor="#FFFFFF"> <p>This is a Testpp</p> <p>See the problem.</p> <p>last test:</p> </body> </html> ``` (If I remove the: `bgcolor="#FFFFFF"` color stays the same) Thanks!
2013/01/24
[ "https://Stackoverflow.com/questions/14507370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1621927/" ]
**To change your background (if this is in fact what you are looking to do):** in styles.xml ``` <style name = "MyDefaultStyle" parent = "@android:style/Theme"> <item name = "android:windowBackground">@drawable/default_drawable_bg</item> </style> ``` and in your manifest ``` <application android:name="MyApp" android:theme="@style/MyDefaultStyle" > ```
Default color is black. If you use style, go to "values/styles.xml" and there is solution of you issue. Now you can check bg color. About themes and styles : <http://developer.android.com/guide/topics/ui/themes.html> **EDIT :** Layout background color changing - [Setting background colour of Android layout element](https://stackoverflow.com/questions/7378636/setting-background-colour-of-android-layout-element) **EDIT 2:** If in styles.xml is @android:style/Theme.Light your bg color is white.
53,432,596
I'm new Asp.Net.I have input type="text" also I have css class for input[type="text"]. So I have an asp:textbox. How can I write css class for my asp:textbox which is a different css class then the one for input? My asp:textbox takes properties from .login-box input[type=text], input[type=password] ``` <div class="login-box" style="padding:70px 30px"> <img src="Images\human.png" class="man"/> <h1>Login Here</h1> <p>Username</p> <input id="username" type="text" name="username" placeholder="Enter Username" runat="server"/> <p>Password</p> <input type="password" name="password" placeholder="Enter Password"/> <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click"/> <asp:TextBox ID="txtError" CssClass="text-hide" runat="server">Incorrect username or password!</asp:TextBox> <a href="#">Forgot Password</a> </div> ``` My style.css below: ``` .login-box input { width: 100%; margin-bottom: 20px; } .text-hide { height:40px; border-color:Transparent; background-color:Transparent; color:Red; } .login-box input[type=text], input[type=password] { height: 40px; border: 0; border-bottom: 1px solid #fff; background-color: transparent; color: #fff; font-size: 16px; outline: none; } ```
2018/11/22
[ "https://Stackoverflow.com/questions/53432596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10552187/" ]
You want to use a label, literal or panel all can be used with asp: prefix to show some message in ASP.Net Web Form. You don't add messages in input fields like in your example ``` <asp:Label ID="txtError" CssClass="text-hide" runat="server" Text="Incorrect username or password!"></asp:Label> ``` After this you can reference this class in your CSS like this: ``` .text-hide { } ```
Username ``` <input id="username" type="text" name="username" placeholder="Enter Username" runat="server"/> <p>Password</p> <input type="password" name="password" placeholder="Enter Password"/> <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click"/> <asp:TextBox ID="txtError" class="text-hide" runat="server">Incorrect username or password!</asp:TextBox> ```
14,475,797
I know this is a very basic problem, but I cannot move forward without it and its not clearly explained elsewhere. Why is this programming giving me so many errors of undeclared identifier? I have declared it, though. These are the error i am getting. ```none Error 2 error C2143: syntax error : missing ';' before 'type' Error 3 error C2065: 'ptr' : undeclared identifier Error 4 error C2065: 'contactInfo' : undeclared identifier Error 5 error C2059: syntax error : ')' Error 15 error C2223: left of '->number' must point to struct/union ``` and more... ``` #include<stdio.h> #include<stdlib.h> typedef struct contactInfo { int number; char id; }ContactInfo; void main() { char ch; printf("Do you want to dynamically etc"); scanf("%c",&ch); fflush(stdin); struct contactInfo nom,*ptr; ptr=(contactInfo*)malloc(2*sizeof(contactInfo)); nom.id='c'; nom.number=12; ptr->id=nom.id; ptr->number=nom.number; printf("Number -> %d\n ID -> %c\n",ptr->number,ptr->id); } ```
2013/01/23
[ "https://Stackoverflow.com/questions/14475797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1482108/" ]
C is a case sensitive language. `ptr=(contactInfo)malloc(2*sizeof(contactInfo));` which should be: `ptr=malloc(2*sizeof(ContactInfo));`
``` struct contactInfo nom,*ptr; ptr=(contactInfo*)malloc(2*sizeof(contactInfo)); ``` here you are using contactInfo to typcast where as it should be struct contactInfo. and as you have typedef it into ContactInfo you can use that also. ``` struct contactInfo nom,*ptr; ptr=(ContactInfo*)malloc(2*sizeof(ContactInfo)); ```
1,714
I edit novels (among other works). I was having a discussion with someone (not an editor) who didn't understand my technique. What I do is read through the document, and the moment something occurs to me — whatever reaction I'm having for good or ill, whatever I catch, any questions I have, mistakes I spot, delightful turns of phrase I notice — I mark it. When I get to the end, I then go back and briefly review my remarks, so that if I wrote something like "Is there a reason that Dave went to the deli?" and I find later that Dave needed to be at the deli so he could overhear Sarah, I can delete that comment. My friend thought that I should read through the entire book first, *as though I were reading it for pleasure* rather than as an editor, and then do a second round as an editor. He thought that reading it first as an editor was somehow unfair to the "spell" that the writer was trying to create with the book. I really think that it's important for a writer to get my first-read impressions. If I already know that we aren't going to return to Blandings Castle for another 150 pages, then I don't feel impatient. But if I'm reading through for the first time, as a reader I'm wondering "when TF are we going to get back to Blandings Castle already? It's been over 100 pages!" I think the author needs to know that the reader is feeling impatient. If that's deliberate, or if the author doesn't care, that's a legitimate choice. But the writer can't know that unless as a reader (and editor) I give her that feedback. So I ask any other editors here: what's your technique? Mark as you read on first draft, or read and then mark? Or something else altogether?
2011/02/22
[ "https://writers.stackexchange.com/questions/1714", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/553/" ]
I will pile onto the "both methods will work" bandwagon, with a qualification. **Your first impressions are important enough that they should be preserved if possible, even if any concerns are addressed later.** For example, you provide a comment that you struck once the question was answered: > > "Is there a reason that Dave went to the deli?" > > > In that case, rather than striking the comment, I would modify it to something like: > > "I was wondering why Dave went to the deli. *Insert additional commentary, such as 'Good hook' or 'Seemed irrelevant at the time, but good job maintaining continuity' or 'You could have telegraphed a little more/less with this'*" > > > That can provide a hint to the author on the value or impact of his decision. **Basically, if you noticed it, the author's decision was noteworthy in some way and merits consideration.** Obviously, some comments will offer very little value after a complete reading. Strike those. However, **a lot of times, a comment that was rendered moot by further reading can be rendered insightful by further consideration.**
My process is to only mark things that interfere with the reading process on the first pass. This is that I try to read for pleasure, and anything that reminds me that the world actually exists out side of the story gets marked now. The second pass is for plot, the third pass is for story telling, the forth is for grammar spelling and punctuation. then I start over. the ninth pass is layout. Then I read something else, anything else.
179,984
I have some cronjob that sometimes gets stuck in running status. That makes me think that for some reason they produce an error but I cannot find any related log. ( the column messages in `cron_schedule` is empty ) How can I be sure cron execution produces logs in case of errors? How can I proceed to debug this issue, any advice? **UPDATE** It looks like my question is not clear, so I'm adding some more content ( I am not sure it gonna help because most of the people seem to read the title and guess the question ... ) * I know how cron works * I know how to check if a cronjobs run or not * My cronjobs correctly run **The problem is some of the cronjobs do not end.** To be more clear: `Mage_Cron_Model_Observer::_processJob()` ``` $schedule ->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', time())) ->save(); call_user_func_array($callback, $arguments); $schedule ->setStatus(Mage_Cron_Model_Schedule::STATUS_SUCCESS) ->setFinishedAt(strftime('%Y-%m-%d %H:%M:%S', time())); ``` The *status* is never reached for some cron, that is the problem. **Please avoid give the random answer or just the first result google provide ( I know how to use google, I did my research ... )** If the answer is not clear, just let me know. If you wanna help you are more than welcome if you just won't waste my and your time you are not. ( this site is meant for quality answers, it is not a forum where everybody says his opinion ... posting not related answers will not help other people with the same issue ... but will just create confusion )
2017/06/21
[ "https://magento.stackexchange.com/questions/179984", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/70/" ]
you can try as following : ``` /rest/V1/orders?searchCriteria[filterGroups][0][filters][0][field]=status&searchCriteria[filterGroups][0][filters][0][value]=complete&searchCriteria[filterGroups][0][filters][0][conditionType]=eq ``` There is ?searchCriteria before SearchCriteria filters. For more information you can refer : <http://devdocs.magento.com/guides/v2.0/howdoi/webapi/search-criteria.html>
I was looking around and I believe the issue is `[conditionType]=eq`, which seems to only compare ints and not Strings. Instead, try `[conditionType]=like`, which worked for me. The request would look like: ``` rest/V1/orders?searchCriteria?searchCriteria[filterGroups][0][filters][0][field]=status& searchCriteria[filterGroups][0][filters][0][value]=complete& searchCriteria[filterGroups][0][filters][0][conditionType]=like ``` A year late, but I was encountering the same problem, so hopefully some others might see this in the future.
17,751,168
I have amended your fiddle a little [link](http://jsfiddle.net/dipens/5rwcB/2/). What I am trying to do is NOT to load both images in at the start - just the first one. Then when the user clicks on the house loaded in - I want to, at this point, load in the second house. I am trying to mimick this behaviour using the fiddle: 1) User clicks on the image 2) Server generates and chucks across the name of the generated jpg. To avoid doing this in the fiddle, I have just added this line: `var newHouse = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house3.jpg";` 3) This jpg then replaces the existing one when the original image is clicked. For some reason, this code isn't doing it: ``` var newImage = new Image(); newImage.onload = function () { var image = new Kinetic.Image({ id: i, image: newImage, x: 0, y: 0, width: 205, height: 205, name: 'image', stroke: 'red', strokeWidth: 2, strokeEnabled: false }); }; newImage.src = newHouse; // keep the Kinetic.Image object // but replace its image ImageObject.setImage(newImage); ``` Many Thanks for any help!
2013/07/19
[ "https://Stackoverflow.com/questions/17751168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486303/" ]
**Loading a new image from your server & using it to replace an existing image object's image** The key is to wait until the new image (house3) has been fully loaded before trying to do the swap. ``` function swap(){ // get the image object from the selected group var ImageObjects = group.get("Image"); var ImageObject=ImageObjects.toArray()[0]; // load a second image var house3=new Image(); house3.onload=function(){ // now we know the second image has been downloaded // keep the Kinetic.Image object // but replace its image ImageObject.setImage(house3); layer.draw(); } house3.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house3.jpg"; } ``` Here is code and a Fiddle: <http://jsfiddle.net/m1erickson/wsCfv/2/> ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Prototype</title> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.4.min.js"></script> <style> #container{ border:solid 1px #ccc; margin-top: 10px; width:400px; height:400px; } </style> <script> $(function(){ var stage = new Kinetic.Stage({ container: 'container', width: 400, height: 400 }); var layer = new Kinetic.Layer(); stage.add(layer); var group=new Kinetic.Group({width:205,height:205}); layer.add(group); var house1=new Image(); house1.onload=function(){ start(); } house1.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house1.jpg"; var image; var rect; var currentImageIndex; function start(){ image=new Kinetic.Image({ image:house1, x:0, y:0, width:204, height:204, }); group.add(image); currentImageIndex=0; rect = new Kinetic.Rect({ x: 0, y: 0, width: 205, height: 205, stroke: "blue", strokeWidth: 4 }); group.add(rect); layer.draw(); console.log("started"); } function swap(){ currentImageIndex = (currentImageIndex==0 ? 1 : 0); // get the image object from the selected group var ImageObjects = group.get("Image"); var ImageObject=ImageObjects.toArray()[0]; // load a second image var house3=new Image(); house3.onload=function(){ // now we know the second image has been downloaded // keep the Kinetic.Image object // but replace its image ImageObject.setImage(house3); layer.draw(); } house3.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house3.jpg"; } $("#swap").click(function(){ $("#swap").hide(); swap(); }); }); // end $(function(){}); </script> </head> <body> <div id="container"></div> <button id="swap">Swap Images</button> </body> </html> ```
You just had to rearrange your `newImage.onload` function: ``` var newImage = new Image(); newImage.onload = function() { // keep the Kinetic.Image object // but replace its image ImageObject.setImage(newImage); layer.draw(); }; newImage.src = newHouse; ``` [JSFiddle](http://jsfiddle.net/projeqht/cMLB4/)
2,458,839
would it be possible to bind a Java application to a Cocoa graphical interface? I'm working in Eclipse right now, on my mac, and am wondering if Interface Builder could be used to construct a new interface so that I don't have to look at Swing all day. Any ideas/suggestions? Thanks!
2010/03/16
[ "https://Stackoverflow.com/questions/2458839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38776/" ]
Check out [Rococoa](http://code.google.com/p/rococoa/). It's a great Java-Cocoa compatibility layer that's built on top of [JNA](https://github.com/twall/jna/). If you don't find what you are looking for in the documentation, try the mailing list. The Rococoa developers are very helpful. P.S. I'm not a Cocoa/Objective-C expert, but the section on "[NIB loading](http://code.google.com/p/rococoa/wiki/NIBLoading)" might be what you're looking for.
Some good (ANCIENT) historical info here (written 2002): <http://cocoadevcentral.com/articles/000024.php> The original Java/Cocoa bridge (since Mac OS X 10.0) became marked deprecated in 10.4, and is considered unusable. The Rococoa answer above is basically your best bet. Just thought I'd chime in with the historical note.
35,178,153
I'm trying to open a **MD Date Picker** from my Controller when click on a single element but it's not working, I'm using the last version of [Angular Material](https://material.angularjs.org) > `1.0.4` I've tried to $inject the **$mdDatePicker** but it says that couldn't find the module. ``` MyController.$inject = [ '$mdDatePicker' ]; ``` I've also digged into the last documentation but couldn't find anything related to this
2016/02/03
[ "https://Stackoverflow.com/questions/35178153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580325/" ]
I managed to hack this added functionality in with an extending directive: ``` .directive('mdDatepickerAutoopen', function ($timeout) { return { restrict: 'A', require: 'mdDatepicker', link: function (scope, element, attributes, DatePickerCtrl) { element.find('input').on('click', function (e) { $timeout(DatePickerCtrl.openCalendarPane.bind(DatePickerCtrl, e)); }); } }; }) ``` ``` <md-datepicker md-datepicker-autoopen> ``` I'd be careful with this regarding future compatibility, since it depends on internal implementation details instead of any public API. Having said that, this is probably as gentle a hack as possible.
Here's another hacky way to do it if you only need the dialog itself and not the date field. Add the datepicker to a directive template, but hide it: ``` <md-datepicker id="datepicker" ng-model="selectedDate" ng-change="dateChanged()" style="position: absolute; visibility: hidden;"> </md-datepicker> ``` Open it by clicking the button programmatically. When a date is selected, the `dateChanged` function will fire and you can do what you need to do with the date. ``` (function () { 'use strict'; angular.module("app").directive("someDirective", someDirective); someDirective.$inject = ["$timeout"]; function someDirective($timeout) { return { templateUrl: 'app/directives/someDirective.html', restrict: 'EA', scope: {}, link: function(scope, element) { scope.openDatePicker = function () { $timeout(function() { element.find("#datepicker button")[0].click(); }, 0); }; scope.dateChanged = function () { // Do something with scope.selectedDate }; } }; } })(); ```
100,953
Ok, according to the ERD workbadge has a lookup to workbadgedefinition: <https://developer.salesforce.com/docs/atlas.en-us.198.0.object_reference.meta/object_reference/sforce_api_erd_badge.htm#topic-title> So why can't I get this simple query to work: ``` Select Id, Description, WorkBadgeDefinition.Name from WorkBadge ``` I keep getting a malformed query. Also, Is there a easy visual way to build these cross object queries, I am using the workbench right now.
2015/11/30
[ "https://salesforce.stackexchange.com/questions/100953", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/26333/" ]
I wish there was concept like merge field in Lightning components where some functions were global and directly accessible but looks like only way to do this will be code with server side call. Below is sample code ``` public with sharing class SimpleServerSideController { //Use @AuraEnabled to enable client- and server-side access to the method @AuraEnabled public static String getUserName() { return userinfo.getName(); } } ``` --- ``` <aura:component controller="SimpleServerSideController"> <aura:attribute name="Name" type="String"/> <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> </aura:component> ``` --- ``` ({ doInit: function(cmp){ var action = cmp.get("c.getUserName"); action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS") { cmp.set("v.Name", response.getReturnValue()); } }); $A.enqueueAction(action); } }) ```
We can fetch from email field if it is 'FirstName.LastName@company.com on user profile without server call. Lightning Component : ``` <aura:component implements="flexipage:availableForRecordHome> <aura:attribute name="UserName" type="String" default=""/> </aura:component> ``` javaScript controller : ``` ({ doInit : function(component, event, helper) {  var UserName =  $A.get("$SObjectType.CurrentUser.Email");   cmp.set("v.UserName",(UserName.substring(0, UserName.lastIndexOf("@")))); alert(cmp.get("v.UserName")); }  }) ```
6,916,250
When using snipmate + vim, is it possible to have many snippet files load for a given language/filetype? Ex: snipmate comes with `javascript.snippets` I've also loaded the mootools snippets and added this to my vimrc: `autocmd FileType javascript set ft=javascript.mootools` Now I can use * the stock js snippets * the mootools snippets I want to add a 3rd set of snippets, `javascript.myCustomSnippets`, that will *also* load for the filetype `javascript`. When I try to add my custom snippets using something like this `autocmd FileType javascript set ft=javascript.myCustomSnippets` it overwrites/disables the mootools snippets, however the default javascript snippets continue to work. How do I accomplish this, or is it possible? *ps: I know I could just add my snippets to the default javascript snippets file, but since I have the snipmate github repo synced inside my `.vim/bundle/` folder, I want to keep the personal stuff separate from the live repo.* **My Solution** The specific solution that finally got my files working side-by-side was to structure my files like this (by the way, I'm using [pathogen](https://github.com/tpope/vim-pathogen) to auto-load the `bundle` dir) ``` ~/.vim/bundles/ snipmate.vim/snippets/javascript.snippet vim-snippets.mootools/snippets/mootools.snippet vim-snippets.myCustomSnippets/snippets/javascript.snippets ``` By naming my file "javascript.snippets" it's auto-loaded along with the defaults.
2011/08/02
[ "https://Stackoverflow.com/questions/6916250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123781/" ]
Create a snippets folder inside your .vim directory and place your snippets there. Create a file called javascript.snippets in there and you should have both the snipmate snippets and your custom ones available.
Since you are using pathogen than all you need do is add a custom Snippets folder to the bundles directory. For example: `~/.vim/bundles/mySnippets/snippets/php.snippets`
3,991,806
My coworker is trying to register some COM components (which I wrote) via RegAsm.exe and it says he needs Administrator privileges. His account has admin privileges but he is not logged in as Administrator. Is there a way to use his regular user account and succeed at this task?
2010/10/21
[ "https://Stackoverflow.com/questions/3991806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73804/" ]
Admin privileges are required to allow Regasm.exe to update the registry. If this is a UAC restriction then create a shortcut on the desktop for cmd.exe and check the "Run this program as an administrator" checkbox. Or change this setting on the Visual Studio Command Prompt shortcut, that's easier.
I think this question belongs elsewhere, but Windows uses least privilege so if he is a user that is both a normal user and an Administrator than he gets normal user privileges. Use runas to make this work or right click the item and "run as administrator"
13,934,711
I'm trying to use autohotkey to simulate elements of Mac keyboard on a PC (Windows) keyboard. My muscle memory reaches for the Command key for simple tasks like copying and pasting, so I'd like to remap the left alt+letter key combinations to appropriate ctrl+letter. ``` <!c::Send ^c ``` Most of the time it works fine, except for part of the time in IE and Office applications. When pressing the left Alt, it screws with the office ribbon/menus (i.e. the menu bar shows in IE, or ribbon letters start appearing in Office 2010), and the ctrl+letter combination fired does not reach destination. I've read the AHK FAQ + forums, tried a couple of options with UP and $ modifiers to the hotkey, but it did not fix the problem. Any ideas?
2012/12/18
[ "https://Stackoverflow.com/questions/13934711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34704/" ]
This prevents the left-hand side Alt key from activating the menu bar for most applications (under Windows 7 and AutoHotkey 1.1.11.01): ``` ~LAlt Up:: return ``` It doesn't work with Internet Explorer but I don't use IE often anyway. :) BTW, I also killed the annoying start menu popup via: ``` ~LWin Up:: return ~RWin Up:: return ```
you could also swap the two buttons. Something like: ``` LAlt::LCtrl LCtrl::LAlt ``` In the limited testing I did, it works, but you might need to relearn some of your window key shortcuts. It basically just swaps the two buttons.
51,558,483
I can't use two cursors in a page on the different elements can anyone help me why is happening? ```css .c-scrolldown{ cursor:pointer; } .c-scrolldown2{ cursor:pointer; } ``` ```html <div class="c-scrolldown2" id="pointer-cursor"> <div class="c-line2"></div> </div> <div class="c-scrolldown"> <div class="c-line"></div> </div> ```
2018/07/27
[ "https://Stackoverflow.com/questions/51558483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8430293/" ]
Just add some content inside divs and change cursor that you need. ```css .c-scrolldown{ cursor: pointer; } .c-scrolldown2{ cursor: progress; } ``` ```html <div class="c-scrolldown2" id="pointer-cursor"> Test 1 <div class="c-line2"></div> </div> <div class="c-scrolldown"> Test 2 <div class="c-line"></div> </div> ``` [Here](https://www.w3schools.com/cssref/pr_class_cursor.asp) you can find a bunch of different mouse cursors.
Sure you can. You just need either some content or a defined height for your DIVs (in your code the DIVs have zero height): ```css .c-scrolldown, .c-scrolldown2 { height: 200px; background: #ddd; } .c-scrolldown { cursor: pointer; } .c-scrolldown2 { cursor: crosshair; } ``` ```html <div class="c-scrolldown2" id="pointer-cursor"> <div class="c-line2"></div> </div> <br> <div class="c-scrolldown"> <div class="c-line"></div> </div> ```
52,046,815
Suppose I have an expression of the form ![First Form](https://latex.codecogs.com/gif.latex?a%5Ccdot%20x%20+%20b%5Ccdot%20x%20-%20c%5Ccdot%20x%20-%20a%5Ccdot%20y-b%5Ccdot%20y+c%5Ccdot%20y%20+%20d). I know that I can simplify the expression like so: ![Second Form](https://latex.codecogs.com/gif.latex?%28x-y%29%28a+b-c%29+d). However, `sympy.simplify` and `sympy.factor` both return the original expression. To work around this, I've been operating on the expression at a low level: ``` factor_map = defaultdict(set) additive_terms = expr.as_coeff_add()[-1] for term1, term2 in combinations(additive_terms, 2): common_terms = ( set(term1.as_coeff_mul()[-1]) & set(term2.as_coeff_mul()[-1]) ) if common_terms: common_factor = sympy.Mul(*common_terms) factor_map[common_factor] |= {term1, term2} ``` `factor_map` now looks like so: ``` { a: {a⋅x, -a⋅y}, b: {b⋅x, -b⋅y}, c: {-c⋅x, c⋅y}, x: {a⋅x, b⋅x, -c⋅x}, y: {-a⋅y, -b⋅y, c⋅y} } ``` I sort it by the number of operations represented by the terms: ``` factor_list = sorted( factor_map.items(), key = lambda i: (i[0].count_ops() + 1) * len(i[1]) )[::-1] ``` I then just rebuild the expression: ``` used = set() new_expr = 0 for item in factor_list: factor = item[0] appearances = item[-1] terms = 0 for instance in appearances: if instance not in used: terms += instance.as_coefficient(factor) used.add(instance) new_expr += factor * terms for term in set(additive_terms) - used: new_expr += term ``` This gives `new_expr = d + x*(a + b - c) + y*(-a - b + c)`. Not great, but better. I can also improve on this by dividing each combination of additive terms by each other, checking if the result is a number, and using that information to further reduce the output to `new_expr = d + (x - y)*(a + b - c)`. I've also tried to apply `sympy.factor` to every possible combination of additive terms, but obviously that blows up very quickly for any reasonably big expression. --- Edit: Here's an implementation that uses `sympy.factor` on all partitions of the set of additive terms (partitions function borrowed from [this answer](https://stackoverflow.com/questions/19368375/set-partitions-in-python)): ``` def partition(collection): if len(collection) == 1: yield [ collection ] return first = collection[0] for smaller in partition(collection[1:]): # insert `first` in each of the subpartition's subsets for n, subset in enumerate(smaller): yield smaller[:n] + [[ first ] + subset] + smaller[n+1:] # put `first` in its own subset yield [ [ first ] ] + smaller def partial_factor(expr): args = list(expr.as_coeff_add()[-1]) # Groupings is just a cache to avoid duplicating factor operations groupings = {} unique = set() for p in partition(args): new_expr = 0 for group in p: add_group = sympy.Add(*group) new_expr += groupings.setdefault(add_group, sympy.factor(add_group)) unique.add(new_expr) return sorted(unique, key=sympy.count_ops)[0] ``` For an expression like `a*x + b*y + c*z + d + e*x + f*y + h*z`, it takes 7.8 seconds to run on my computer, whereas the other method takes 378 microseconds and gives the same result. Seems like there should be a way to be more rigorous than the first method without taking 20,000 times longer to solve it. --- I feel like it shouldn't be this hard to get what I want. Is there an easier way to do this?
2018/08/27
[ "https://Stackoverflow.com/questions/52046815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9235907/" ]
[This similar question](https://stackoverflow.com/questions/40620585/expression-simplification-in-sympy/40643065) has an answer involving the `func` parameter to `collect()`. It seems to work in this particular case as well, although you have to explicitly mention `d`: ``` from sympy import * a, b, c, d, x, y = symbols('a, b, c, d, x, y') expr = a * x + b * x - c * x - a * y - b * y + c * y + d collect(expr, d, func=factor) => d + (x - y)*(a + b - c) ``` This helps in this specific case, however a more general and automatic solution does not exist. Also I could not find any documentation for this `func` parameter anywhere, other than it existing. [Github issue tracking this problem](https://github.com/sympy/sympy/issues/11869)
It's hard to suggest a strategy of "partial factoring" that works most of the time. Here is a thing to try, devised with your example in mind (a polynomial of several variables). Given an expression: Attempt to factor it. If unsuccessful, look at the coefficient of each symbol that it contains; the method `Expr.coeff(Symbol)` does that. The symbol with the smallest coefficient (measured by the number of symbols contained) is considered an obstacle to factoring and is removed from the expression. Repeat. This logic is encoded below, and `partial_factor(a*x + b*x - c*x - a*y - b*y + c*y + d)` does return `d + (x - y)*(a + b - c)`. ``` def partial_factor(expr): to_factor = expr non_factorable = 0 while to_factor != 0: if factor(to_factor) != to_factor: return factor(to_factor) + non_factorable coeffs = {v: to_factor.coeff(v) for v in to_factor.free_symbols} min_size = min([len(coeffs[v].free_symbols) for v in coeffs]) for v in coeffs: if len(coeffs[v].free_symbols) == min_size: non_factorable += v*coeffs[v] to_factor -= v*coeffs[v] break return expr ```
19,904,636
I have horizontal news which look like this: [DEMO](http://jsfiddle.net/9nn29/) If you run this fiddle in Firefox, it displays different then in other browsers. On my webpage it position random position (always same). I have to use `position: absolute;` because I want to keep the date and buttons at the same level in all columns. I google it but all solution doesn't work for me. So my question is how to position in to look like [DEMO](http://jsfiddle.net/9nn29/).
2013/11/11
[ "https://Stackoverflow.com/questions/19904636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2978769/" ]
Looks like: <http://bugzil.la/203225> It was logged over 10 years ago. As a workaround you could use a div within the TD and set that to position:relative instead of setting it on the TD directly.
try this one, ``` .col { width: 235px; margin: 0px; border: 0px; padding: 0px; vertical-align: top; background-color: white; display: table-cell; position: relative; float:left; } ``` <http://jsfiddle.net/9nn29/3/>
4,507,149
My Rails views and controllers are littered with `redirect_to`, `link_to`, and `form_for` method calls. Sometimes `link_to` and `redirect_to` are explicit in the paths they're linking (e.g. `link_to 'New Person', new_person_path`), but many times the paths are implicit (e.g. `link_to 'Show', person`). I add some single table inheritance (STI) to my model (say `Employee < Person`), and all of these methods break for an instance of the subclass (say `Employee`); when rails executes `link_to @person`, it errors with `undefined method employee_path' for #<#<Class:0x000001022bcd40>:0x0000010226d038>`. Rails is looking for a route defined by the class name of the object, which is employee. These employee routes are not defined, and there is no employee controller so the actions aren't defined either. This question has been asked before: 1. At [StackOverflow](https://stackoverflow.com/questions/1773367/link-to-issue-with-inherited-active-record-class), the answer is to edit every instance of link\_to etc in your entire codebase, and state the path explicitly 2. On [StackOverflow](https://stackoverflow.com/questions/702728/get-route-for-base-class-of-sti-class-in-rails) again, two people suggest using `routes.rb` to map the subclass resources to the parent class (`map.resources :employees, :controller => 'people'`). The top answer in that same SO question suggests type-casting every instance object in the codebase using `.becomes` 3. Yet another one at [StackOverflow](https://stackoverflow.com/questions/4432858/broken-rails-routes-after-implementing-single-table-inheritance), the top answer is way in the Do Repeat Yourself camp, and suggests creating duplicate scaffolding for every subclass. 4. [Here's](https://stackoverflow.com/questions/943300/single-table-inheritance-routing) the same question again at SO, where the top answer seems to just be wrong (Rails magic Just Works!) 5. Elsewhere on the web, I found [this blog post](http://strugglingwithruby.blogspot.com/2008/10/single-table-inheritance.html) where F2Andy recommends editing in the path everywhere in the code. 6. On the blog post [Single Table Inheritance and RESTful Routes](http://blog.lrdesign.com/2009/03/single-table-inheritance-and-restful-routes/) at Logical Reality Design, it is recommended to map the resources for the subclass to the superclass controller, as in SO answer number 2 above. 7. Alex Reisner has a post [Single Table Inheritance in Rails](http://www.alexreisner.com/code/single-table-inheritance-in-rails), in which he advocates against mapping the resources of the child classes to the parent class in `routes.rb`, since that only catches routing breakages from `link_to` and `redirect_to`, but not from `form_for`. So he recommends instead adding a method to the parent class to get the subclasses to lie about their class. Sounds good, but his method gave me the error `undefined local variable or method `child' for #`. So the answer that seems most elegant and has the most consensus (but it's not all *that* elegant, nor *that* much consensus), is the add the resources to your `routes.rb`. Except this doesn't work for `form_for`. I need some clarity! To distill the choices above, my options are 1. map the resources of the subclass to the controller of the superclass in `routes.rb` (and hope I don't need to call form\_for on any subclasses) 2. Override rails internal methods to make the classes lie to each other 3. Edit every instance in the code where the path to an object's action is invoked implicitly or explicitly, either changing the path or type-casting the object. With all these conflicting answers, I need a ruling. It seems to me like there is no good answer. Is this a failing in rails' design? If so, is it a bug that may get fixed? Or if not, then I'm hoping someone can set me straight on this, walk me through the pros and cons of each option (or explain why that's not an option), and which one is the right answer, and why. Or is there a right answer that I'm not finding on the web?
2010/12/22
[ "https://Stackoverflow.com/questions/4507149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336563/" ]
Use *type* in the routes: ``` resources :employee, controller: 'person', type: 'Employee' ``` <http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-2/>
You can create method that returns dummy Parent object for routing purpouse ```html class Person < ActiveRecord::Base def routing_object Person.new(id: id) end end ``` and then simply call form\_for @employee.routing\_object which without type will return Person class object
4,124,810
In the book [Coders at Work](http://apress.com/book/view/1430219483) (p355), Guy Steele says of C++: > > I think the decision to be > backwards-compatible with C is a fatal > flaw. It’s just a set of difficulties > that can’t be overcome. **C > fundamentally has a corrupt type > system**. It’s good enough to help you > avoid some difficulties but it’s not > airtight and you can’t count on it > > > What does he mean by describing the type system as "corrupt"? Can you demonstrate with a simple example in C? **Edit**: 1. The quote sounds polemic, but I'm not trying to be. I simply want to understand what he means. 2. Please give examples in **C** not **C++**. I'm interested in the "fundamentally" part too :)
2010/11/08
[ "https://Stackoverflow.com/questions/4124810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/201665/" ]
You'd have to ask him what he meant to get a definitive answer, or perhaps provide more context for that quote. However, it is pretty clear that if this is a fatal flaw for C++, the disease is chronic, not acute - C++ is thriving, and continually evolving as evidenced by ongoing Boost and C++0x efforts. I don't even think about C and C++ as coupled any more - a few weeks on the respective *fora* here quickly cures one of any confusion over the fact that they are two different languages, each with its own strengths and foibles.
Here, "corrupt" means that it is not "strict", leading to never-ending delight in C++ (because of the many custom types (objects) and overloaded operators, casting becomes a superior nuisance in C++). The attack against C comes in regard to its MISPLACED USAGE as a strict OOP basis. C has never been designed to limit coders, hence, maybe the frustration of Academia (and the flamboyant splendor of the ++ given to the World by B.S.). *"I invented the term Object-Oriented, and I can tell you I did not have C++ in mind"* (Alan Kay)
133,848
Publish...Publish, I am worried about publications as I don't have any yet, I just have few in masters, but was not a good quality, now in Ph.D., I am working on a new topic and to get a significant and validated results it takes times, I focused on developing a model that could really explain the phenomena which are not explained yet by any researchers. However, as I am apart of the project, all other members are getting papers so fast and every meeting they mention, how their methods are great, I feel low and less confident, maybe I am stupid as I take time. According to the current situation, I didn't do any success which I think my career in academia is impossible, as I see all successful researchers have tons and tons of citations. I don't know if I should give up, I bring this to my supervisor, however, he does not care so much, he is not recognized in the field, so it is not a big deal. I am serious, feel low and lost because of the high competition and I did not have even one good paper yet. Should I wait or withdraw from Ph.D., I really like research and my topic, what you recommend me to do in that case? P.S. I am also getting psychotherapy as I am suffering from terrible OCD because of the past experience, I am doing my utter best and fight, but no one knows that in my lab. I am also so ambitious and hard worker, but not intelligent enough as peers that's why I am asking whether I am wasting time in the wrong direction maybe.
2019/07/26
[ "https://academia.stackexchange.com/questions/133848", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/-1/" ]
Until your supervisor starts worrying, I wouldn't start worrying. Pure paper count isn't the best measure because some topics yield more papers and others much less. For example 2018 Nobel Laureate in Physiology & Medicine, [James Allison](https://scholar.google.com/citations?user=Vq6NVkAAAAAJ&hl=en), has a h-index of 127. Meanwhile 2018 Nobel Laureate in Economics [Paul Romer](https://scholar.google.com/citations?user=b5oj894AAAAJ&hl=en) has a h-index of 49. This doesn't mean James Allison is 3x more accomplished than Paul Romer; it just means they're from different fields. In the same way even if your labmate has published 3 papers and you have zero, it doesn't mean they're 3x as capable as you. Your supervisor knows what is expected of a PhD student at your university. If you are performing badly, he/she will let you know (or it will come up during a performance review). Until that happens, it's not time to start worrying. If you are *really* concerned, you can ask your supervisor if you're making expected progress, or ask him/her to set some targets for you to strive for.
A question you might ask yourself: Do you really need to have publications for your goals? (If it is not a requirement for your phd or supervisor or if you don't want to stay in academia, maybe you don't need any.) If no, you can just work on your big project (if your supervisor is fine with it) and relax a little bit! Often the people who publish a lot are under a lot of pressure because they want to stay in academia, whereas many PhD students who know they will leave academia can enjoy their research and live a good work-life-balance. If your big project works out, you have good material for a publication -- if not, well then at least you tried! Don't make your happiness dependent on other people (or their success)!
47,613,271
My code is a dictionary with values that are 2d lists. I need to write a function that will total up all of the same index numbers in each list within the dictionary. Here is what I have so far: ``` def totalQty(theInventory): totalQuantity = 0 for key in theInventory: for book in key: totalQuantity += book[3] ``` theInventory is the dictionary , and book is each list stored in the dictionary. I keep getting this error: ``` builtins.IndexError: string index out of range ```
2017/12/02
[ "https://Stackoverflow.com/questions/47613271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8724001/" ]
In a dict `for key in theInventory` doesn't give you each element but the key for each element, so you have to access the element via `theInventory[key]` you could also use `for key, value in theInentory.items()`. Then you can iterate over `value`. Try: ``` for key, value in theInventory.items(): for book in value: totalQuantity += int(book[3]) ```
``` def totalQty(theInventory): totalQuantity = 0 for key in theInventory: totalQuantity += theInventory[key][3] ``` The key variable is a string of the key name not a list
18,889
I remember learning this in high school, but have forgotten it, and can't seem to find it anywhere online. Air travels from areas of high pressure to low pressure...correct? So if I have a cold room in my house, does the air move from the warm rooms to the cold room or the other way around?
2011/12/30
[ "https://physics.stackexchange.com/questions/18889", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/6902/" ]
Air does indeed flow from high pressure to low pressure area (see the wind arrows on a weather chart), but in the case of two rooms the much more important effect is that of warm thinner air rising towards the ceiling when the air from the two rooms gets mixed. Thus, cold air from the cold room will be leaving the room close to the floor (if the temperature difference is large enough you can actually feel it, otherwise you can use a candle to detect the direction of air movement). At the same time, warm air from the warm room will rise and move into the cold room close to the ceiling (again, sometimes you can feel this otherwise you can detect it with a candle). Similar air movements take place between your house and the outside when you open your house's door in winter or summer. The tendency of warm air to rise towards the ceiling is actually exploited in floor heating. This was understood and taken advantage of already by the ancient Romans, see [hypocaust](http://en.wikipedia.org/wiki/Hypocaust).
In hot room the air will be much thinner thus reducing the pressure so the air flows from cold room to hot rooms.
257,684
I have two new-ish 1TB hard drives in my server, both running at 38 degrees C at the moment. Should I be worried?
2011/04/09
[ "https://serverfault.com/questions/257684", "https://serverfault.com", "https://serverfault.com/users/77798/" ]
What does the manufacturer's datasheet/documentation have to say about temperature ?
Be careful of the interpretation of your sensors. I have Munin running, and the smartd results shows my drives have "Temperature\_Celcius" of around 230.0 (which if true would probably indicate they were on fire) but another probe called "HDD Temperature" records them around 27 and 29 C, which seems much more likely to me.
3,132
![enter image description here](https://i.stack.imgur.com/52NA4.jpg) *Welcome to installment #2 of my "the science of animals falling" series of questions....* I've heard it said many times since childhood that if you are to find a baby bird on the ground which appears to have fallen from the nest you should not pick it up and put it back. I was told that once the baby bird has your scent on it, the mother will not take it back. It's possible that this is just something parents tell their kids to keep them from touching birds which are notorious for carrying germs (as are kids), but it is a very commonly held belief in America. * **Is there any scientific evidence to explain why this would happen?** * **Has this been studied?**
2011/05/12
[ "https://skeptics.stackexchange.com/questions/3132", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/486/" ]
From [Fortean Times](http://web.archive.org/web/20140712025704/http://www.forteantimes.com/strangedays/mythbusters/710/abandoned_birds.html): > > **Birds have little or no sense of > smell**, and will be unaware of your > molestation. Besides, they will not > lightly abandon their offspring. > > > From [National Geographic](http://web.archive.org/web/20140323044514/http://kids.nationalgeographic.com/kids/stories/animalsnature/animal-myths-busted/): > > "***Most birds have a poorly developed > sense of smell***," says Michael Mace, > bird curator at San Diego Zoo's Wild > Animal Park. "*They won't notice a > human scent*." > > > One exception: vultures, > who sniff out dead animals for dinner. > But you wouldn't want to mess with a > vulture anyway! > > > [Snopes](http://www.snopes.com/critters/wild/babybird.asp) also debunks it: > > Mother birds will not reject their babies because they smell human scent on them, nor will they refuse to [sit] on eggs that have been handled by a person. **Many birds have a limited sense of smell and cannot detect human scent, or if they can detect it, do not react to it.** > > >
Touching the baby bird [will not cause the mother to abandon it](https://skeptics.stackexchange.com/a/3134/21644), but it may be illegal under [the Migratory Bird Treaty Act of 1918](http://www.fws.gov/laws/lawsdigest/migtrea.html), which states: > > Establishment of a Federal prohibition, unless permitted by regulations, to "pursue, hunt, take, capture, kill, attempt to take, capture or kill, possess, offer for sale, sell, offer to purchase, purchase, deliver for shipment, ship, cause to be shipped, deliver for transportation, transport, cause to be transported, **carry, or cause to be carried by any means whatever**, receive for shipment, transportation or carriage, or export, at any time, or in any manner, any migratory bird, included in the terms of this Convention . . . for the protection of migratory birds . . . or **any part, nest, or egg of any such bird**." (16 U.S.C. 703) > > > The [list of birds covered by this law](http://www.fws.gov/birds/management/managed-species/migratory-bird-treaty-act-protected-species.php) is quite comprehensive. While the law is not often enforced, penalties are severe - up to six months in jail and a fine of up to $15,000.
64,549,275
I have async socket server file and client file. When i send something like that "download filename.ex" to the client, this client's code hande my request: ```py try: content = read(sp_data[-1]).decode('utf-8') print(content) msg = json.dumps({'file': sp_data[-1], 'command': data, 'content': content, 'msg': f'[+] File {sp_data[-1]} has been successfully downloaded.'}).encode('utf-8') except FileNotFoundError: msg = json.dumps({'msg': f'[-] File {sp_data[-1]} not found', 'command': data}).encode('utf-8') s.send(msg) ``` When client send some data to the socketserver, this server's code handle received message: ```py def recv_message(client_socket): global messages data = json.loads(client_socket.recv(4096).decode('utf-8').strip()) ##Important here i got this error json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 67 (char 66) raddr = get_raddr(str(client_socket)) raddr = f'{raddr[0]}:{raddr[1]}' message = f'From: {raddr}\nCommand: {data["command"]}\nOutput: \n\n{data["msg"]}' try: d = messages[raddr] d.append(message) messages[raddr] = d except KeyError: messages[raddr] = [message] except AttributeError: print(message, messages) if 'content' in data.keys(): ##Important print(data['content']) threading.Thread(target=create_file, args=(data['file'], data['content'],), daemon=False).start() ``` Error: ```py data = json.loads(client_socket.recv(4096).decode('utf-8').strip()) json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 67 (char 66) ``` But server's code above give me this error when it receive message from the first code(when i send something like that "download file.ex" to the client, client detect my command as its special command, execute the first code, send json file to the server. But if i send "dir" command to the client, it will detect my command like shell command, will run command through subprocess, will send result to the server back and i won't get any errors.) Note: I also reduced socketserver's code. Therefore, something in my code can work worse. The main goal of this post - make download feature works. I also understand that my code is big. I left "**##Important"** comments in my files. U can watch only code that located by these comments. **Server**: ```py import selectors import socket import threading import json import base64 import shlex selector = selectors.DefaultSelector() connections = {} def accept_conn(server_socket): sock, addr = server_socket.accept() connections[len(connections) + 1] = [sock, f'{addr[0]}:{addr[-1]}'] selector.register(fileobj=sock, events=selectors.EVENT_READ, data=recv_message) s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('localhost', 4444)) s.listen() selector.register(fileobj=s, events=selectors.EVENT_READ, data=accept_conn) messages = {} ##Important def create_file(file, content): #content - base64 string print(content) with open(file, 'wb') as f: f.write(base64.b64decode(content.encode('utf-8'))) def recv_message(client_socket): global messages data = json.loads(client_socket.recv(4096).decode('utf-8').strip()) ##Important here i got this error json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 67 (char 66) raddr = get_raddr(str(client_socket)) raddr = f'{raddr[0]}:{raddr[1]}' message = f'From: {raddr}\nCommand: {data["command"]}\nOutput: \n\n{data["msg"]}' try: d = messages[raddr] d.append(message) messages[raddr] = d except KeyError: messages[raddr] = [message] except AttributeError: print(message, messages) if 'content' in data.keys(): ##Important print(data['content']) threading.Thread(target=create_file, args=(data['file'], data['content'],), daemon=False).start() def get_raddr(string): '''Get raddr parameter from client socket''' raddr = string.replace('>', '') return eval(raddr[raddr.find('raddr')::].replace('raddr=', '')) def is_manage_string(sub, string): tokens = shlex.split(string) try: if len(tokens) == 2 and tokens[0] == sub and str(int(tokens[-1])): return True, int(tokens[-1]) except Exception as e: print(e) return False manage_process = False def manage(): global manage_process while True: manage_process = False command = input('>>> ').strip() if command == 'list': try: for i in range(1, len(connections) + 1): print(f'{i}\t{connections[i][-1]}') except KeyError: pass if len(connections) == 0: print('[-] There are not any connections') elif 'manage' in command: index = is_manage_string('manage', command) if index: index = index[-1] else: print('[-] Invalid command\nUse manage "number_of_connection"\nEx: manage 1') continue if index >= 1 and index <= len(connections): sock, addr = connections[index] print(addr) print(f'{addr} is used') while True: ##Important here i launch loop which send data to socket manage_process = True command = input('>>> ').strip() if command == 'messages': try: if messages[addr] == list(): print() continue except KeyError: pass try: print('\n\n'.join(messages[addr])) except KeyError: print() elif command == 'message': try: print(messages[addr][-1]) except: print() elif command == 'clear_messages': try: if messages[addr]: messages[addr] = [] except KeyError: print('[-] There are not any messages for cleaning up') elif command == 'leave': print(f'Leaving connection {addr}') break elif command: ##Important if command hasn't been detected as my special command(leave, messages), it will be executed like shell command try: sock.send(command.encode('utf-8')) print( 'Your input has not been detected as special command and will execute like shell command or like client special command(ex: download; see client file)') except ConnectionResetError: print("Connection has been lost, therefore shell commands can't be used") else: continue else: print('[-] Invalid number of connection') elif command: print('[-] Invalid command\nType "help" to see avalible commands') ##Important def event_loop(): while True: data = selector.select() for key, _ in data: try: key.data(key.fileobj) except ConnectionResetError: selector.unregister(key.fileobj) ##Important threading.Thread(target=manage, daemon=True).start() event_loop() ``` **Client**: ```py import socket import subprocess import shlex import threading import json import base64 s = socket.socket() s.connect(('localhost', 4444)) ##Important def read(file): with open(file, 'rb') as f: return base64.b64encode(f.read()) def runner(data): sp_data = shlex.split(data) try: print(sp_data) if len(sp_data) == 2 and sp_data[0] == 'download': ###Important here we create json object which will be send to socketserver try: content = read(sp_data[-1]).decode('utf-8') print(content) msg = json.dumps({'file': sp_data[-1], 'command': data, 'content': content, 'msg': f'[+] File {sp_data[-1]} has been successfully downloaded.'}).encode('utf-8') except FileNotFoundError: msg = json.dumps({'msg': f'[-] File {sp_data[-1]} not found', 'command': data}).encode('utf-8') s.send(msg) return '' except Exception as e: print(e) command = subprocess.run(data, shell=True, encoding='cp866', text=True, capture_output=True) command = command.stderr if command.stderr else command.stdout command = json.dumps({'msg': command, 'command': data}) s.send(command.encode('utf-8')) while True:##Important data = s.recv(4096).decode('utf-8').strip() threading.Thread(target=runner, args=(data,)).start() ```
2020/10/27
[ "https://Stackoverflow.com/questions/64549275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12214758/" ]
You use them to overwrite something you wrote previously. You wouldn't normally use them in the same string, but in different output calls, e.g. ``` printf("hello"); fflush(stdout); // need to flush because we didn't write a newline // do some stuff here printf("\rgoodbye\n"); // This replaces hello ```
\n" for new line "\b" for a backspace, means if u print it, cursor will print and come back 1 character. For example.... cout<<"hello\bHi"; will print "HellHi". because after printing Hello, compiler found a \b escape sequence. so it came 1 character back (at 'o' of Hello) and stat printing Hi from o of Hello..... so u got HellHi instead of HelloHi. '\r' is used for carriage return to come 1 line back or in start of line. \b = it's purpose is backspace \r = purpose is carriage return \r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line. The cursor is the position where the next characters will be rendered. So, printing a \r allows to override the current line of the terminal emulator. Whereas \b is backspace character it takes the cursor one character backward so that when you will type next thing the characters ahead of cursor will be overwritten. Thus \b illustrates the working of backspace whereas carriage return simply moves the cursor to the starting of the current line.
31,378
When I restart httpd, I get the following error. What am I missing? ``` [root@localhost ~]# service httpd restart Stopping httpd: [ OK ] Starting httpd: Syntax error on line 22 of /etc/httpd/conf.d/sites.conf: Invalid command 'SSLEngine', perhaps misspelled or defined by a module not included in the server configuration ``` I have installed mod\_ssl using `yum install mod_ssl openssh` ``` Package 1:mod_ssl-2.2.15-15.el6.centos.x86_64 already installed and latest version Package openssh-5.3p1-70.el6_2.2.x86_64 already installed and latest version ``` My sites.conf looks like this ``` <VirtualHost *:80> # ServerName shop.itmanx.com ServerAdmin webmaster@itmanx.com DocumentRoot /var/www/html/magento <Directory /var/www/html> Options -Indexes AllowOverride All </Directory> ErrorLog logs/shop-error.log CustomLog logs/shop-access.log </VirtualHost> <VirtualHost *:443> ServerName secure.itmanx.com ServerAdmin webmaster@itmanx.com SSLEngine on SSLCertificateFile /etc/httpd/ssl/secure.itmanx.com/server.crt SSLCertificateKeyFile /etc/httpd/ssl/secure.itmanx.com/server.key SSLCertificateChainFile /etc/httpd/ssl/secure.itmanx.com/chain.crt DocumentRoot /var/www/html/magento <Directory /var/www/html> Options -Indexes AllowOverride All </Directory> ErrorLog logs/shop-ssl-error.log CustomLog logs/shop-ssl-access.log </VirtualHost> ```
2012/02/10
[ "https://unix.stackexchange.com/questions/31378", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/15401/" ]
On CentOS 7 installing the package "mod\_ssl" and restarting the apache server worked for me: ``` yum install mod_ssl systemctl restart httpd ```
On Ubntu 18.04 bionic. ``` sudo a2enmod ssl sudo service apache2 restart ```
127,602
This might have some duplicated inquiry that [this question](https://physics.stackexchange.com/questions/1586/what-if-physical-constants-were-increased-or-decreased) [or this question](https://physics.stackexchange.com/questions/78684/why-is-it-meaningless-to-speak-about-changes-in-a-dimensional-constant) had, and while I think I have some of [my own opinions](https://en.wikipedia.org/wiki/Planck_units#Planck_units_and_the_invariant_scaling_of_nature) about it, I would like to ask the community here for more opinions. So referring to [Duff](http://arxiv.org/abs/hep-th/0208093) or [Tong](http://www.coursehero.com/file/p2q03qm/It-has-the-value-k-B-1-381-10-23-JK-1-In-some-sense-there-is-no-deep-physical/), one might still beg the question: Why is the speed of light 299792458 m/s? Don't just say "because it's defined that way by definition of the metre." Before it was defined, it was measured against the then-current definition of the metre. Why is $c$ in the ballpark of $10^8$ m/s and not in the order of $10^4$ or $10^{12}$ m/s? A similar questions can be asked of $G$ and $\hbar$ and $\epsilon\_0$. To clarify a little regarding $c$: I recognize that the reason that $c\approx10^9$ m/s is that a meter is, by no accident of history, *about* as big as we are and a second represents a measure of how fast we think (i.e. we don't notice the flashes of black between frames of a movie and we can get pretty bored in a minute). So light appears pretty fast to us because it moves about $10^9$ lengths about as big as us in the time it takes to think a thought. So the reason that $c\approx10^9$ m/s is that there are about $10^{35}$ Planck lengths across a being like us ($10^{25}$ Planck lengths across an atom $10^5$ atoms across a biological cell and $10^5$ biological cells across a being like us). Why? And there are about $10^{44}$ Planck times in the time it takes us to think something. Why? Answer those two questions, and I think we have an answer for why $c\approx 10^9$ in anthropometric units. The other two questions referred do **not** address this question. [Luboš Motl](https://physics.stackexchange.com/a/3666/37102) gets closest to the issue (regarding $c$), but he does not answer it. I think in the previous EDIT and in the comments, I made it (the question) pretty clear. I was **not** asking so much about the **exact** values which can be attributed to historical accident. But there's a reason that $c \approx 10^9$ m/s, not $10^4$ or $10^{12}$. Reworded, I suppose the question could be "*Why are the anthropometric units (which are about as big as we are) as large as they are relative to their corresponding Planck units?*" (which **is** asking a question about dimensionless values). If we answer those questions, we have an answer for not just why $c$ is what it is, but also why $\hbar$ or $G$ are what they are.
2014/07/22
[ "https://physics.stackexchange.com/questions/127602", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/37102/" ]
You are correct in that the core of your question is indeed nontrivial, but you need to be a bit more subtle than that. The fundamental constants don't "take" values - they are what they are, and that's that. It is valid to ask "how did this 3×108 number come about", but the answer lies less with the speed of light than with the units we use to measure it. The real question, then, is > > why did we choose units of length and time such that the speed of light has a value of ~3×108 in those units? > > > Now, the gritty details of why we chose, say, the meter over the yard, are not really that important, and the reasons for those choices are historical - but mostly, we just had to choose *something*. As you've realized, these gritty details don't really matter; what really matters is the rough ballpark size of those units. So, why did we choose the meter as the fundamental unit? Quite simply, because we ourselves are roughly meter-sized. This also came to mean that the world we built around us was also roughly meter-sized, so most of the things we measure in everyday life are roughly meter-sized. On the other hand, we are made of atoms, and the size of atoms is a (fairly) fundamental constant of physics (particularly the Bohr radius $a\_0$, which is a function of $ħ,\epsilon\_0$ and $m\_e$, and which is a good "standard atomic radius"). Let me pose, then, a similar question to yours, > > why is the 'standard' size of atoms, $a\_0$, roughly 5×10-11 m? > > > and rephrase it as before: > > why did we choose units of length which are roughly 2×1010 times the 'standard' atom? > > > Since our units were chosen because we ourselves are about that size, the real question is therefore > > **why are humans roughly 2×1010 'standard' atoms tall?** > > > The reason I call this the 'real' question is that this is actually (at least in principle) an answerable question. However, it is not a physics question! It is a question about biology and about evolution, and it's not clear what the balance between those two is. There is some sort of 'allowed' range of lengthscales in which intelligent life is possible (it is hard to imagine intelligence at the level of tens of atoms, and also at the star-sized lengths of 1019 atoms), but just how broad this range is is a hard question in biology. There is also the historical, evolutionary question of how we came to occupy our particular spot on that range, and that is also a hard question. This is also made much more complicated by the anthropic-principle fact that we only know one instance of intelligent species. On balance, then, we don't really know the answer to your question. But at least it is possible to ask the right question.
I can always choose units where $c = 1$. This is almost always done in context of General Relativity, Special Relativity and Quantum Field Theory. As ACuriousMind said in the comments above, how we measure quantities tells us nothing useful about the physics of it, since units can be rescaled. As of why the speed of light is in the order of $10^8$? In my eyes, it is simply because compared to ordinary speeds where humans are used to, the speed of light is simply almost $10^8$ greater! Edit: You have asked in the comments why human speeds are so small compared to $c$. Well recall that the speed of light is the speed a massless particle travels through the universe. For massive particles you need energy to accelerate them close to c. Humans are a collection of massive particles and hence you require a lot of energy to accelerate them at those high speeds. That energy is way too high than what we extract out of food/fuel etc.
39,001,305
I have a problem with my code that I can't find the solution as well. I ask for questions that has to be valid but the loops just continues, and let me input. ``` print('Do you want to go to the store or woods?') lists = ('woods', 'store') while True: answers = input() if answers == 'store': break print('Going to the store...') elif answers == 'woods': break print('Going to the woods...') while lists not in answers: print('That is not a valid answer') ```
2016/08/17
[ "https://Stackoverflow.com/questions/39001305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6715279/" ]
You want to check if the user's answer is not in your list of valid answers. What you're doing is the other way around. Try this: ``` if answers not in lists: print('That is not a valid answer') ``` You'll also want to either `break` at that point, or print your prompt message again.
Try this: ``` print('Do you want to go to the store or woods?') places = ('woods', 'store') while True: answer = input() if answer in places: print ("Going to the {0}...".format(answer)) break else: print('That is not a valid answer') ```
16,300,495
I have a console application that is using a log4net setup for logging information to the console output only at the moment. I have various `log.Debug("Debug info")` statements which I only want to print out to the console if a debug flag within my application is set. The debug variable is set by reading a switch passed to the application when it is invoked. The arguments are read using `NDesk.Options`. I want to avoid wrapping every debug statement in an if:- ``` bool debug = false; // read switches var p = new OptionSet() { { "d|debug", "debug mode", v => debug = v != null }, }; if (debug) { log.Debug("Debug info") } ``` Is there anything I can put in the `<log4net><appender>` section of the configuration to enable this, or is there a way of overriding log.Debug to provide the logic ?
2013/04/30
[ "https://Stackoverflow.com/questions/16300495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317603/" ]
Yes there is, e.g.: ``` <root> <level value="DEBUG" /> <appender-ref ref="LogFileAppender" /> <appender-ref ref="AdoNetAppender" /> <appender-ref ref="EventLogAppender" /> </root> ```
You can try to create your own appender like this : ``` public class MyAppender : AppenderSkeleton { private static bool TurnDebugOn = false; public static SetDebugLogging(bool toSet){ TurnDebugOn = toSet; } protected override void Append(LoggingEvent loggingEvent) { bool logEvent = true; LogLevel logLevel = LogLevel.Err; switch (loggingEvent.Level.Name) { case "DEBUG": logEvent = TurnDebugOn; logLevel = LogLevel.Debug; break; case "WARN": case "INFO": logLevel = LogLevel.Info; break; case "ERROR": logLevel = LogLevel.Err; break; case "FATAL": logLevel = LogLevel.Critical; break; } if(logEvent){ LogService.Log(LogNameEnum.Exception, LogCategoryEnum.BusinessLogic, logLevel, RenderLoggingEvent(loggingEvent)); } } } ``` Then in your code : ``` MyAppender.SetDebugLogging(true); ``` in your config file: ``` ... <appender name="AppenderToUse" type="MyAppender"> ... ```
4,337,666
I'm searching the best way to do what I'm trying to do, so I ask here... I have a webpage in PHP who's requesting a song by TCP to another server. The song is loaded into a temporary file on the server. While it's loading, I want to play it into the webpage OR into the user's favorite player. Is it possible to simply refer the file to the player, even if it's not fully loaded ? Thanks ! EDIT: I found a great open-source player named JW Player, seems to be able to do what I want, but I'm not sure how ...
2010/12/02
[ "https://Stackoverflow.com/questions/4337666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527315/" ]
It depends what you mean by "it". The iterator knows what index it's reached, yes - in the case of a `List<T>` or an array. But there's no general index within `IEnumerator<T>`. Whether it's iterating over an indexed collection or not is up to the implementation. Plenty of collections don't support direct indexing. (In fact, `foreach` doesn't always use an iterator at all. If the compile-time type of the collection is an array, the compiler will iterate over it using `array[0]`, `array[1]` etc. Likewise the collection can have a method called `GetEnumerator()` which returns a type with the appropriate members, but without any implementation of `IEnumerable`/`IEnumerator` in sight.) Options for maintaining an index: * Use a `for` loop * Use a separate variable * Use a projection which projects each item to an index/value pair, e.g. ``` foreach (var x in list.Select((value, index) => new { value, index })) { // Use x.value and x.index in here } ``` * Use my [`SmartEnumerable`](http://www.yoda.arachsys.com/csharp/miscutil/usage/smartenumerable.html) class which is a little bit like the previous option All but the first of these options will work whether or not the collection is naturally indexed.
The sequence being iterated in a foreach loop might not support indexing or know such a concept it just needs to implement a method called GetEnumerator that returns an object that as a minimum has the interface of IEnumerator though implmenting it is not required. If you know that what you iterate does support indexing and you need the index then I suggest to use a `for` loop instead. An example class that can be used in `foreach`: ``` class Foo { public iterator GetEnumerator() { return new iterator(); } public class iterator { public Bar Current { get{magic} } public bool MoveNext() { incantation } } } ```
172,627
Could you give me a hint on this problem? > > Show that $f:A\subset\mathbb{R}^n\longrightarrow \mathbb{R}^m$ is continuous if and only if for every subset $B$ of $A$ , $f(A\cap\overline{B}) \subset \overline{f(B)}$. > > > Currently I know these definitions of continuity: $(\rm i)$ In terms of pre-image of open sets. $(\rm ii)$ In terms of $\epsilon$-$\delta$ $(\rm iii)$ In terms of convergent sequences. By the statement of the problem I could guess the definition to use in this case is the first one. Maybe you could tell me how to start so I can give it a try, thanks in advance.
2012/07/18
[ "https://math.stackexchange.com/questions/172627", "https://math.stackexchange.com", "https://math.stackexchange.com/users/85162/" ]
HINTS: ($\Rightarrow$) Let $x\in A\cap\operatorname{cl}B$. There is a sequence $\langle x\_n:n\in\Bbb N\rangle$ in $B$ that converges to $x$. What do you know about $\langle f(x\_n):n\in\Bbb N\rangle$? ($\Leftarrow$) Prove the contrapositive: suppose that $f$ is not continuous, and show that there is some $B\subseteq A$ such that $f[A\cap\operatorname{cl}B]\nsubseteq\operatorname{cl}f[B]$. If $f$ is not continuous, there is at least one point $x\in A$ such that $f$ is not continuous at $x$. Can you show that there are an $\epsilon>0$ and a sequence $\langle x\_n:n\in\Bbb N\rangle$ in $A$ that converges to $x$ such that $\|f(x\_n)-f(x)\|\ge\epsilon$ for every $n\in\Bbb N$? What can you then say about $B=\{x\_n:n\in\Bbb N\}$?
To do (⇐) I think it's a bit slicker (and doesn't use the metric structure) to take B to be the preimage of an arbitary closed set in the range. What does the condition tell you?
44,801,649
I just read an ARM instruction book, and I saw one instruction that I couldn't interpret. It says `LDR` loads a 32-bit constant into the `r0` register: ``` LDR r0, [pc, #const_number-8-{pc}] .......... const_number DCD 0xff00ffff ``` I couldn't understand what `[pc, #const_number-8-{pc}]` means. Specifically: 1. What does `#` mean? 2. What do the curly braces (`{}`) mean? 3. Why does this example subtract 8 and `pc`? 4. How does `r0` have the value `0xff00ffff?`
2017/06/28
[ "https://Stackoverflow.com/questions/44801649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8225902/" ]
Just change the root selector. **UPDATE** Select every `div` and use the [filter method](http://api.jquery.com/filter/). Clone the `div` you're filtering, select all the children (nested divs), remove them then "come back" to the parent `cloned div` and retrieve the text. Having the text, compare the contents with the text you're searching. ```js $("#clickMe").click(function(){ $("div").filter(function(idx, val) { return /heinrich/gi.test($(this).clone().children().remove().end().text()); }).css("background-color", "limegreen") }); ``` ```css .normal { width: 100px; height: 100px; display: inline-block; } .red { background-color: red; border: 1px solid black; } .blue { background-color: blue; border: 1px solid black; } .yellow { background-color: yellow; border: 1px solid black; } #masterdiv { border: 10px solid gray; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="masterdiv"> My favorite frends are: <div class="red normal" id="div1"> hans </div> <div class="blue normal" id="div2"> franz </div> <div class="yellow normal" id="div3"> heinrich </div> </div> <button id="clickMe"> Clicking me should make only heinrichs div limegreen </button> ```
Since you didn't want to use ids I can suggest you to try this. ``` $('div > div:contains(heinrich)').css("background-color", "limegreen") ``` Working Fiddle: <https://jsfiddle.net/g50cfqzw/>
23,113
If I were to say, > > Can't I just be wearing my swim suit already? > > > Would "be wearing" be improper English?
2011/04/28
[ "https://english.stackexchange.com/questions/23113", "https://english.stackexchange.com", "https://english.stackexchange.com/users/7942/" ]
Your sentence makes perfect sense in this context: > > Parent: You need to wear something warm, and find someplace to change into your swimsuit. > > > Child: If I wear other clothes over it, **can't I just be wearing my swim suit already?** That way I won't have to find a changing room. > > >
Maybe your example sentence would work if you were indicating that you want your character in, say, a novel to "be wearing" a swimsuit in a certain scene: > > You: Can't I just be wearing my swim suit already? My character is just about to go to the beach. > > > Author of the novel: No, your character has to look as unattractive as possible up until the beach scene. She can change in a bathroom there. > > >
20,459,668
i have made a program but the output that i'm getting is ``` (<q3v3.Student instance at 0x023BB620>, 'is doing the following modules:', ' <q3v3.Module instance at 0x023BB670> <q3v3.Module instance at 0x023BB698>') ``` For example , the above output should give me Alice is doing following module : biology, chemistry Help this is my full code: ``` class Student : def __init__(self,students): self.students= students print self.students #def __str__(self): # when i used this i've got error type TypeError: __str__ returned non-string (type NoneType) #print str(self.students) class Module: def __init__(self,modules): self.modules = modules print self.modules #def __str__(self): #print str(self.modules) class Registrations (Student,Module): def __init__(self): self.list= [] self.stulist = [] self.modulist= [] def __iter__(self): return iter(self.list) def __str__(self): return str(self.list) def add(self,students,modules): self.list.append((students,modules)) #print (self.list) def students(self,modules): for i in self.list: if i[1] == modules: self.modulist.append((i[0])) return iter(self.modulist) def __str__(self): return str(self.students) def modules(self,students): for i in self.list: if i[0] == students: self.stulist.append((i[1])) return iter(self.stulist) def __str__(self): return str(self.modules) ``` i need to import my program to be able to run it to this : ========================================================== ``` from q3v4 import * james = Student('james') alice = Student('alice') mary = Student('mary') agm = Module('agm') ipp = Module('ipp') r = Registrations() r.add(james,agm) r.add(alice,agm) r.add(alice,ipp) mstr = '' for m in map(str,r.modules(alice)): mstr = mstr+' '+m print(alice, 'is doing the following modules:', mstr) sstr = '' for s in map(str,r.students(agm)): sstr = sstr+' '+s print(agm, 'has the following students:', sstr) print(r) ```
2013/12/08
[ "https://Stackoverflow.com/questions/20459668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3072782/" ]
You could define a `__str__` method in your `Student` class, and do something like this: ``` def __str__(self): return self.name # Here the string you want to print ```
Are you using Python 2? If so, `print` is a keyword, not a function. There are two ways to solve your problem: 1. Write `print foo, bar` instead of `print(foo, bar)`. The difference is that `print(foo, bar)` is actually printing out the *tuple* `(foo, bar)`, which uses the `repr()` representation of each element, rather than its `str()`. 2. At the very top of your file, write `from __future__ import print_function`. This will magically convert `print` from a keyword into a function, causing your code to work as expected. If you *are* using Python 3, my answer is irrelevant.
31,733,253
I am new to C, now I am making a linked list for face detection. Below is the struct and the method for appending face at the end of linked list. ``` //Structure for storing a face with x, y and window size typedef struct Face { int window; int x; int y; struct Face* next; } Face; //Append face(window, x, y) to the end of linked list starting from head void push(Face* head, int window, int x, int y) { Face* temp = (Face *)malloc(sizeof(Face)); temp->window = window; temp->x = x; temp->y = y; temp->next = NULL; Face* cur = head; if (head == NULL) { printf("Called\n"); head = temp; } else { while (cur->next != NULL) { cur = cur->next; } cur->next = temp; } } ``` In another file, the executable, I called push(head, 1, 2, 3)[head here is initialized to NULL]. Only "Called' is printed on the screen. And the head is still NULL in the executable when I examine the linked list. I have no idea why the head is not updated, but when I have it in the same file, it seems to work fine.
2015/07/30
[ "https://Stackoverflow.com/questions/31733253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5054713/" ]
``` if (head == NULL) { printf("Called\n"); head = temp; } ``` The assignment `head = temp` only modifies the *local* copy of the head pointer. So it is not propagated to the code that called `push()`. If `head` was `NULL` in the code that calls `push()`, then it will remain so. You could for example return the list head, as in: ``` Face *push(Face* head, int window, int x, int y) { Face* temp = (Face *)malloc(sizeof(Face)); temp->window = window; temp->x = x; temp->y = y; temp->next = NULL; Face* cur = head; if (head == NULL) { printf("Called\n"); head = temp; } else { while (cur->next != NULL) { cur = cur->next; } cur->next = temp; } return head; } ``` And then use it like this: ``` /* ... */ head = push(head, window, x, y); /* ... */ ``` Another alternative is to pass a pointer to pointer to `head` (`Face **`), and replace that assignment with `*head = temp;`, but if you're a beginner I'd stick to the previous approach (and in my opinion, using double indirection is not necessary in most of the cases, but this can be subjective). Finally, you might want to handle possible `malloc(3)` errors: the allocation can fail, you should check and handle that case.
I believe it is because you are passing in the value of the pointer `head`, which creates a copy of the pointer. By setting `head` to another address, you're not modifying `head` outside of scope, but rather the `head` within the method scope. You'd need to pass in a pointer to the pointer to change it.
749,160
I am having a problem with a regex find and replace in Word 2010 (Windows 7). I want to convert reference citation numbers in parentheses to the same numbers in brackets. For example, (20-23) should become [20-23], (19, 20) should become [19, 20]. I have the following Find what: `\(([0-9], -]*)\)` and Replace with: [\1] But this puts the found expression before the brackets, instead of within. (20-23) becomes 20-23[], (19, 20) becomes 19, 20[] Can anyone tell me the correct syntax for this replace?
2014/05/03
[ "https://superuser.com/questions/749160", "https://superuser.com", "https://superuser.com/users/169801/" ]
When you run as `sudo` add `-s` to preserve your environment. It's not maintaining your environment, thus your `HOME` directory is lost. [Emacs looks in](http://www.gnu.org/software/emacs/manual/html_node/emacs/Init-File.html) `~/.emacs, ~/.emacs.el, or ~/.emacs.d/init.el`, so if you lose HOME, you lose the pathing to your startup files.
You can easily run emacs with the init file of your choice. For example, the following command ``` sudo emacs --load ~/.emacsroot -nw filename.ex ``` Loads emacs * as super user -> `sudo` * with `.emacsroot` init file located in the home directory -> `--load ~/.emacsroot` * in console mode -> `-nw` * opening `filename.ex` file
12,377,283
My mind is swimming with all of the options out there for responsive navigation but I'm having a hard time finding what I want that works in IE! I'm hoping somebody out there has used the 'perfect' system for me! What I'm looking for is a navigation that is: 1) built on a simple ul li structure in CSS 2) in smaller viewports the navigation will turn into a navigation icon which will slide open the nav 3) sublevels will, in turn, slide open on small devices (simple accordion) 4) WORK IN IE! The last item is the kicker. I've gotten my hopes up so many times only to find that it's not compatible :( Any recommended tutorials or tools would be MOST appreciated! Thanks so much! Len p.s. I've been researching responsive frameworks such as foundation and gumby. If there are any widgets out there for the nav I'm describing for frameworks like these HAPPY DAY!
2012/09/11
[ "https://Stackoverflow.com/questions/12377283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1663141/" ]
The best way to make @media-queries work in IE is [respond.js](https://github.com/scottjehl/Respond). I've tested it in IE8+ and it works great, only that you can't see it locally, you have to upload it. About the navigation, you can adapt the way everything looks using [media queries](http://www.w3.org/TR/css3-mediaqueries/). If there is something you can't achieve with them, then you can maybe use jQuery to show/write a different navigation bar.
I found a great tutorial with the cleanest code I've seen for this responsive menu! <http://webdesign.tutsplus.com/tutorials/site-elements/big-menus-small-screens-responsive-multi-level-navigation/> Hopefully this will help somebody else and save some searching :)
48,355,556
I have a splash screen where I want one textview i.e the name of the app to appear in the center of the screen for 2 seconds and then animate to top of the screen and stay on top until the activity ends.
2018/01/20
[ "https://Stackoverflow.com/questions/48355556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5097842/" ]
This just happened to me as of 23 July, 2019. It looks like Apple is now enforcing TLS 1.2 for the sandbox voip push notification server at ``` gateway.sandbox.push.apple.com - port 2195 feedback.sandbox.push.apple.com - port 2196 ``` I found that I had to check out the latest code from <https://github.com/Redth/PushSharp> (master branch), build it, and then manually add a reference to the built DLLs in my project. Previously I was incuding the NuGet PushSharp package, which is now 3 years old and hasn't been updated. If you look at the recent commits on the master branch there is some change there related to Apple and TLS, so I am certain this has fixed it.
i think the issue related to the Push Sharp so please try this solution by changeing the SSl3 to Tls in the class called **ApplePushChannel.cs** and here is the change ``` The orginal code in the file is stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Ssl3, false); replace it with stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Tls, false); ``` Hope this will hellp you
67,125,307
I'm learning Golang and as an exercise in using interfaces I'm building a toy program. I'm having some problem trying to use a type that "should implement" two interfaces - one way to solve that in C++ and Java would be to use inheritance(there are other techniques, but I think that is the most common). As I lack that mechanism in Golang, I'm not sure how to proceed about it. Below is the code: ``` var ( faces = []string{"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"} suits = []string{"Hearts", "Diamonds", "Spades", "Clubs"} ) type Card interface { GetFace() string GetSuit() string } type card struct { cardNum int face string suit string } func NewCard(num int) Card { newCard := card{ cardNum: num, face: faces[num%len(faces)], suit: suits[num/len(faces)], } return &newCard } func (c *card) GetFace() string { return c.face } func (c *card) GetSuit() string { return c.suit } func (c *card) String() string { return fmt.Sprintf("%s%s ", c.GetFace(), c.GetSuit()) } ``` What I'm trying to achieve: * I would like to hide my struct type and only export the interface so that the clients of the code use only the *"Card"* interface * I would like to have a string representation of the struct, hence the implementation of the interface with the *"String()"* method in order to be able to call *"fmt.Println()"* on instantiations of my struct The problem comes when I'm trying to use a new card though the "Card" interface and also trying to get the string representation. I cannot pass the interface as the parameter of the implementation of the *"String()"* method as there is a compiler error which is related to the addressability of an interface at the core language level(still digging through that documentation). The very simple example of testing exposes the issue: ``` func TestString(t *testing.T) { card := NewCard(0) assert.EqualValues(t, "AceHearts ", card.String(), " newly created card's string repr should be 'AceHearts '") } ``` The compiler tells me, for good reason, that *"card.String undefined (type card has no field or method string)"*. I could just add the *"String()"* method to my *"Card"* interface, but I do not find that to be clean: I have other entities implemented with the same model and I would have to add that redundancy everywhere; there is already an interface with that method. What would be a good solution for the above issue that I'm having? **Edit:**(to address some of the very good comments) * I do not expect to have another implementation of the *Card* interface; I'm not sure I grasp why would I want to do that, that is change the interface * I would like to have the *Card* interface to hide away implementation details and for the clients to program against the interface and not against the concrete type * I would like to always have access to the String() interface for all clients of the "card struct" instantiations(including the ones instantiated via the Card interface). I'm not interested in having clients only with the String interface. In some other languages this can be achieved by implementing both interfaces - multiple inheritance. I'm not saying that is good or wrong, or trying to start a debate about that, I'm just stating a fact! * My intent is to find out if the language has any mechanism to fulfill those requirements simultaneously. If that is not possible or maybe from the point of view of the design the problem should be tackled in a different manner, then I'm ready to be educated * Type assertions are very verbose and explicit and would expose implementation details - they have their places but I do not think they are appropriate in the situation I have
2021/04/16
[ "https://Stackoverflow.com/questions/67125307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59775/" ]
I should go over some prefacing points first: * Interfaces in Go are not the same as interfaces in other languages. You shouldn't assume that every idea from other languages should transfer over automatically. A lot of them don't. * Go has neither classes nor objects. * Go is not Java and Go is not C++. It's type system is significantly and meaningfully different than those languages. --- From your question: ------------------- > > I would like to have the Card interface to hide away implementation details and for the clients to program against the interface and not against the concrete type > > > This is the root of your other problems. As mentioned in the comments, I see this in multiple other packages and regard it as a particularly pesky anti-pattern. First, I will explain the reasons why this pattern is "anti" in nature. * Firstly and most pertinently, this point is proven by your very example. You employed this pattern, and it has resulted in bad effects. As pointed out by mkopriva, it has created a contradiction which you *must* resolve. * this usage of interfaces is contrary to their intended use, and you are not achieving any benefit by doing this. Interfaces are Go's mechanism of polymorphism. The usage of interfaces in parameters makes your code more versatile. Think of the ubiquitous `io.Reader` and `io.Writer`. They are fantastic examples of interfaces. They are the reason why you can patch two seemingly unrelated libraries together, and have them just work. For example, you can log to stderr, or log to a disk file, or log to an http response. Each of these work exactly the same way, because [log.New](https://golang.org/pkg/log/#New) takes an `io.Writer` parameter, and a disk file, stderr, and http response writer all implement `io.Writer`. To use interfaces simply to "hide implementation details" (I explain later why this point fails), does not add any flexibility to your code. If anything, it is an abuse of interfaces by leveraging them for a task they weren't meant to fulfill. Point / Counterpoint -------------------- 1. "Hiding my implementation provides better encapsulation and safety by making sure all the details are hidden." * You are not achieving any greater encapsulation or safety. By making the struct fields unexported (lowercase), you have already prevented any clients of the package from messing with the internals of your struct. Clients of the package can only access the fields or methods that you have exported. There's nothing wrong with exporting a struct and hiding every field. 2. "Struct values are dirty and raw and I don't feel good about passing them around." * Then don't pass structs, pass pointers to struct. That's what you're already doing here. There's nothing inherently wrong with passing structs. If your type behaves like a mutable object, then pointer to struct is probably appropriate. If your type behaves more like an immutable data point, then struct is probably appropriate. 3. "Isn't it confusing if my package exports `package.Struct`, but clients have to always use `*package.Struct`? What if they make a mistake? It's not safe to copy my struct value; things will break!" * All you realistically have to do to prevent problems is make sure that your package *only returns* `*package.Struct` values. That's what you're already doing here. A vast majority of the time, people will be using the short assignment `:=`, so they don't have to worry about getting the type correct. If they do set the type manually, and the choose `package.Struct` by accident, then they will get a compilation error when trying to assign a `*package.Struct` to it. 4. "It helps to decouple the client code from the package code" * Maybe. But unless you have a realistic expectation that you have multiple existent implementations of this type, then this is a form of premature optimization (and yes it does have consequences). Even if you *do* have multiple implementations of your interface, that's still not a good reason why you should actually *return* values of that interface. A majority of the time it is still more appropriate to just return the concrete type. To see what I mean, take a look at the [`image`](https://golang.org/pkg/image/) package from the standard library. When is it actually useful? --------------------------- The main realistic case where making a premature interface *AND* returning it *might* help clients, is this: * Your package introduces a second implementation of the interface + AND clients have statically and explicitly (not `:=`) used this data type in *their* functions or types + AND clients want to reuse those types or functions for the new implementation also. Note that this wouldn't be a breaking API change even if you weren't returning the premature interface, as you're only **adding** a new type and constructor. If you decided to only *declare* this premature interface, and still return concrete types (as done in the `image` package), then all the client would likely need to do to remedy this is spend a couple minutes using their IDE's refactor tool to replace `*package.Struct` with `package.Interface`. It significantly hinders the usability of package documentation --------------------------------------------------------------- Go has been blessed with a useful tool called Godoc. Godoc automatically generates documentation for a package from source. When you export a type in your package, Godoc shows you some useful things: * The type, all exported methods of that type, and all functions that return that type are organized together in the doc index. * The type and each of its methods has a dedicated section in the page where the signature is shown, along with a comment explaining it's usage. Once you bubble-wrap your struct into an interface, your Godoc representation is hurt. The methods of your type are no longer shown in the package index, so the package index is no longer an accurate overview of the package as it is missing a lot of key information. Also, each of the methods no longer has its own dedicated space on the page, making it's documentation harder to both find and read. Finally it also means that you no longer have the ability to click the method name on the doc page to view the source code. It's also no coincidence that in many packages that employ this pattern, these de-emphasized methods are most often left without a doc comment, even when the rest of the package is well documented. In the wild ----------- <https://pkg.go.dev/github.com/zserge/lorca> <https://pkg.go.dev/github.com/googollee/go-socket.io> In both cases we see a misleading package overview, along with a majority of interface methods being undocumented. (Please note I have nothing against any of these developers; obviously every package has it's faults and these examples are cherry picked. I'm also not saying that they had no justification to use this pattern, just that their package doc is hindered by it) Examples from the standard library ---------------------------------- If you are curious about how interfaces are "intended to be used", I would suggest looking through the docs for the standard library and taking note of where interfaces are declared, taken as parameters, and returned. <https://golang.org/pkg/net/http/> <https://golang.org/pkg/io/> <https://golang.org/pkg/crypto/> <https://golang.org/pkg/image/> Here is the only standard library example I know of that is comparable to the "interface hiding" pattern. In this case, reflect is a very complex package and there are several implementations of `reflect.Type` internally. Also note that in this case, even though it is necessary, no one should be happy about it because the only real effect for clients is messier documentation. <https://golang.org/pkg/reflect/#Type> tl;dr ===== This pattern will hurt your documentation, while accomplishing nothing in the process, except you might make it slightly quicker in very specific cases for clients to use parallel implementations of this type that you may or may not introduce in the future. These interface design principles are meant for the benefit of the client, right? Put yourself in the shoes of the client and ask: what have I really gained?
The go language does not have [subtype polymorsphism](https://en.wikipedia.org/wiki/Subtyping). Therefore, the pattern you want to achieve is not *encouraged* by the very foundations of the language. You may achieve this undesirable pattern by composing structs and interfaces, though.
61,660,933
Context ======= I have a database with a collection of documents using this schema (shortened schema because some data is irrelevant to my problem): ``` { title: string; order: number; ... ... ... modificationsHistory: HistoryEntry[]; items: ListRow[]; finalItems: ListRow[]; ... ... ... } ``` These documents can easily reach 100 or 200 kB, depending on the amount of items and finalItems that they hold. It's also very important that they are updated as fast as possible, with the smallest bandwidth usage possible. This is inside a web application context, using Angular 9 and `@angular/fire` 6.0.0. Problems ======== When the end user edits one item inside the object's `item` array, like editing just a property, reflecting that inside the database requires me to send the entire object, because firestore's `update` method doesn't support array indexes inside the field path, the only operations that can be done on arrays are adding or deleting an element [as described inside documentation](https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array). However, updating an element of the `items` array by sending the entire document creates poor performances for anyone without a good connection, which is the case for a lot of my users. Second issue is that having everything in realtime inside one document makes collaboration hard in my case, because some of these elements can be edited by multiple users at the same time, which creates two issues: * Some write operations may fail due to too much contention on the document if two updates are made in the same second. * The updates are not atomic as we're sending the entire document at once, as it doesn't use transactions to avoid using bandwidth even more. Solutions I already tried ========================= Subcollections -------------- ### Description This was a very simple solution: create a subcollection for `items`, `finalItems` and `modificationsHistory` arrays, making them easy to edit as they now have their own ID so it's easy to reach them to update them. ### Why it didn't work Having a list with 10 `finalItems`, 30 `items` and 50 entries inside `modificationsHistory` means that I need to have a total of 4 listeners opened for one element to be listened entirely. Considering the fact that a user can have many of these elements opened at once, having several dozens of documents being listened creates an equally bad performance situation, probably even worse in a full user case. It also means that if I want to update a big element with 100 items and I want to update half of them, it'll cost me one write operation per item, not to mention the amount of read operations needed to check permissions, etc, probably 3 per write so 150 read + 50 write just to update 50 items in an array. Cloud Function to update the document ------------------------------------- ```js const { applyPatch } = require('fast-json-patch'); function applyOffsets(data, entries) { entries.forEach(customEntry => { const explodedPath = customEntry.path.split('/'); explodedPath.shift(); let pointer = data; for (let fragment of explodedPath.slice(0, -1)) { pointer = pointer[fragment]; } pointer[explodedPath[explodedPath.length - 1]] += customEntry.offset; }); return data; } exports.updateList = functions.runWith(runtimeOpts).https.onCall((data, context) => { const listRef = firestore.collection('lists').doc(data.uid); return firestore.runTransaction(transaction => { return transaction.get(listRef).then(listDoc => { const list = listDoc.data(); try { const [standard, custom] = JSON.parse(data.diff).reduce((acc, entry) => { if (entry.custom) { acc[1].push(entry); } else { acc[0].push(entry); } return acc; }, [ [], [] ]); applyPatch(list, standard); applyOffsets(list, custom); transaction.set(listRef, list); } catch (e) { console.log(data.diff); } }); }); }); ``` ### Description Using a diff library, I was making a diff between previous document and the new updated one, and sending this diff to a GCF that was operating the update using the transaction API. Benefits of this approach being that since transaction happens inside GCF, it's super fast and doesn't consume too much bandwidth, plus the update only requires a diff to be sent, not the entire document anymore. ### Why it didn't work In reality, the cloud function was really slow and some updates were taking over 2 seconds to be made, they could also fail due to contention, without firestore connector knowing it, so no possibility to ensure data integrity in this case. *I will be edited accordingly to add more solutions if I find other stuff to try* Question ======== I feel like I'm missing something, like if firestore had something I just didn't know at all that could solve my use case, but I can't figure out what it is, maybe my previously tested solutions were badly implemented or I missed something important. What did I miss? Is it even possible to achieve what I want to do? I am open to data remodeling, query changes, anything, as it's mostly for learning purpose.
2020/05/07
[ "https://Stackoverflow.com/questions/61660933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4102561/" ]
Try this: It works fine ``` class MyHomePage extends StatelessWidget { List<UsersData> user = [ UsersData( name: 'Zack Alex', msg: 'Im on my way.', status: '3 hours ago', dp: 'assets/Zack.jpg', seenMsgs: false, unreadMsgs: 12, ), UsersData( name: 'Ali sho', msg: 'Send an attachemnt', status: 'false', dp: 'assets/Ali.jpg', seenMsgs: false, unreadMsgs: 3), UsersData( name: 'Marie', msg: 'Gud Morning', status: '23 seconds ago', dp: 'assets/Marie.jpg', seenMsgs: true, unreadMsgs: 6, ), ]; // variable to hold sum of unread messages int sumOfUnreadMsgs = 0; @override Widget build(BuildContext context) { // use a for loop to loop through your list for (var person in user){ // add all the messages here sumOfUnreadMsgs += person.unreadMsgs ; } return Scaffold( body: Center( // display sum of unread messages here child: Text('Sum of unread message is $sumOfUnreadMsgs'), ), ); } } ``` OUTPUT [![enter image description here](https://i.stack.imgur.com/xNbmz.png)](https://i.stack.imgur.com/xNbmz.png)
You can make use of operator overloading here. Probably it's not the best way but one of the possible way. ```dart class Item { Item({this.id, this.msg}); String id; int msg; Item operator +(Item other) { return Item(id: "", msg: (this.msg + other.msg)); } } void main() { List<Item> data = [ new Item(id: "A1", msg: 100), new Item(id: "A2", msg: 200), new Item(id: "A2", msg: 350) ]; print(data.reduce((curr, next) => curr + next).msg); } ```
11,639,424
I have a `Questions` table which looks like that ![enter image description here](https://i.stack.imgur.com/RGmxl.png) as you see, there are 2 id rows that are nearly same: `id`, `question_id`. `id` - is autoincremented, unique id of each question, and `question_id` - is, for example, course 1 lesson 1 has 5 questions like: question 1, 2, 3, 4, 5. And course 1 lesson 2 has 3 questions: 1, 2, 3 etc.. In other words it's like autoincrement field for each unique `course_id`, `lesson_id` combination. I decided to add manually `question_id` based on `course_id`, `lesson_id` for keeping database structure readability and not messing up database, with bunch of association tables between `course-lesson-question unique id` values. First question is ================= How do you think, is it good solution or not? How you'd design this database? --- The problem is, when I want to insert new question with given `course_id`, `lesson_id` the `id` field will auto-increment, but I got Second question =============== How can I get, last `question_id` column value based on unique `course_id`, `lesson_id` combination. For example, if course 1 lesson 2 has 3 questions: 1, 2, 3 and I want to add 4th question (as I said, in current db design I'm inserting `question_id` value manually), how do I know that, the last question of course 1 lesson 2 is 3th, and insert new question with (last\_number=3)++=4? Update ====== Situation is a bit complicated but I will try to explain: It's online tutorials website. There are different courses, and each course has bunch of lessons. Now I'm designing question-answer part, in which teacher posts questions, and users getting dedicated questions. [Full size image here](http://screencast.com/t/0DxyNNZL) ![enter image description here](https://i.stack.imgur.com/g6JYh.png) Now, the table `questions` is dedicated for course>lesson based questions. `question_from_to_assoc` - It's for, creating assoications between question author and receiver user. For example admin (id=.) sends question to some user with id=5. `qa_assoc` - question-answer associations table.
2012/07/24
[ "https://Stackoverflow.com/questions/11639424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978733/" ]
First of all, this is not an optimal database design. Your schema is denormalized, which is not really good. To answer your first question. I would split Lesson, Course, Question and Author into **separate tables**. Then I would add a number field beside the Primary Key for *Course*, *Lesson* and *Question*. The PK will only ensure uniqueness of a row, but the number field will be your course number, question number, etc. Using the PK to represent a question number for instance is not a good idea in my opinion, because it should be kept unchanged. For instance, if your questions are changed to letters instead of numbers, your PK would have to be changed and this might break referential integrity. After that, I would add a unique constraint on question numbers and FK like [question\_no, lesson\_id] to ensure that you cannot have two question 1 for the same lesson. Same thing for *Lesson*. *Course* would have a unique constraint on course\_no. Finally, to automatically increment question numbers depending on lesson, I would use a trigger which would do something like : ``` CREATE TRIGGER tr_question_number BEFORE INSERT ON questions FOR EACH ROW BEGIN SET NEW.question_no = (SELECT MAX(question_no)+1 FROM questions WHERE lesson_id = NEW.lesson_id FOR UPDATE) END; ``` This trigger will set the question number field with the latest value + 1. The *FOR UPDATE* clause is very important, because it will lock the row to avoid concurrent insertion to get the same number. The trigger is just a draft, but that's just a general idea of what I would have done. I hope this will help you.
1. You should try to get rid of `question_id` and only leave the autoincrement `id` as a primary key. Otherwise inserting will get messy. > > The problem is, now when I want to insert new question with given course\_id, lesson\_id the id field wil auto-increment. > > > I don't understand the problem - auto\_increment fields usually do that :). 2. You can use ``` SELECT MAX(question_id) WHERE course_id = <something> AND lesson_id = <some_other_thing> ``` To get the current max id for a given course\_id and lesson\_id. But you will have to lock the table (or use FOR UPDATE and a transaction if the table is InnoDB) and unlock it after you insert the new record to make sure it remains consistent.
43,694,560
So I have this class "Member" : ``` package pkgData; import java.io.Serializable; public class Member implements Comparable<Member>, Serializable{ /** * */ private static final long serialVersionUID = 1L; private String name; private String city; public Member(String nameOfMember,String location) { super(); this.name = nameOfMember; this.city=location; } public String getNameOfMember() { return name; } public String getLocationOfMember() { return city; } public void setNameOfMember(String nameOfMember) { this.name = nameOfMember; } @Override public String toString() { return name +", " + city; } @Override public int compareTo(Member o) { int result =this.getNameOfMember().compareTo(o.getNameOfMember()); if(result==0){ result = this.getLocationOfMember().compareTo(o.getLocationOfMember()); } return result; } } ``` And I have a JComboBox which is EDITABLE and the model of the ComboBox is DefaultComboBoxModel. So the problem is that if I cast the selectedItem: ``` Member nameOfMember = (Member)memberModel.getSelectedItem(); if(nameOfMember== null) throw new Exception("please select a name and a location"); ``` It only checks if the entered string is empty. If I enter a string like "Name, Location" I always get the exception that String cannot be cast to Member. Which String to I have to enter that the String can be cast to Member? Here is my JComboBox: ``` private JComboBox<Member> getComboBoxMember() { if (comboBoxMember == null) { comboBoxMember = new JComboBox<Member>(); comboBoxMember.setEditable(true); comboBoxMember.setModel(memberModel); } return comboBoxMember; } ``` and here the global variables: ``` private DefaultComboBoxModel<Member> memberModel; private JComboBox<Member> comboBoxMember; ```
2017/04/29
[ "https://Stackoverflow.com/questions/43694560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7055250/" ]
``` String nameOfMember = (String) memberModel .getSelectedItem();if(nameOfMember==null)throw new Exception("please select a name and a location");else { String[] parts = nameOfMember.split(","); String part1 = parts[0]; // name String part2 = parts[1]; // location Member member=new Member(part1, part2); } ```
**String split & cast method** What you can do is first of all test if the string you get is null, or if it matches well you format. Then, you can create a new object with these elements. Here's a small example code : ``` String memberData = (String)memberModel.getSelectedItem(); if(memberData == null || memberData.split(", ")[0].isEmpty() || memberData.split(", ")[1].isEmpty()) { throw new Exception("Data is incorrect, please provide name and location separated with ", "); } Member member = new Member(memberData.split(", ")[0], memberData.split(", ")[1]); ``` --- **JComboBox method** With Java 7 happened a new possibility of extension to `JComboBox`, which can now be generically parameterized (as for `ArrayList`s) in the form `JComboBox<Type>`. Thus, the objects you can get with `getSelectedItem()` can now be casted to the generic type you gave in parameter to `JComboBox`. The only problem is that, when a `JComboBox` is edited, as in your case, the data is casted to a simple `String`. What you can do in your listener method (I will use `ActionListener`) is the following : ``` class ItemAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { try { //In case the user has not modified the object Member member = (Member)box.getSelectedItem(); //Just an example here if(member != null) { System.out.println(member.toString()); } } catch(ClassCastException ex) { //In case the object has been modified String data = (String)box.getSelectedItem(); //Apply first method here } } } ``` But the problem with this method is that you end up using the first method still.
4,005,663
This is a conic equation: ${4x^{2}−4xy+7y^{2}+12x+6y−9=0}$ I tried a way like this: 1.)${B^{2}-4AC <0} --> ((-4)^2-4x4x7 = 16-112 = -96 < 0)$ "So this is an ellipse" 2.)${Tan2θ = \frac{B}{A-C} = \frac{4}{3} ->θ = 27}$ "degree" 3.) (I saw them using these formulas on a site) There are formulas for ${A^{'}, B^{'}, C^{'}, D^{'}, E^{'}, F^{'}}$ Taking **B = 0 to get rid of the xy expression**, and the others are: ${A^{'} = Acos^{2}θ+Bcosθsinθ+Csin^{2}θ}$ Plug in the angle "θ" 27 degrees and A 'is about 2,96. ${B^{'} = 0 }$ ${C^{'} = Asin^{2}θ+Bsinθcosθ+Ccos^{2}θ}$ Plug in the angle "θ" 27 degrees and A 'is about 4,73 ${D^{'} = Dcosθ+Esinθ}$ Plug in the angle "θ" 27 degrees and A 'is about 13,38 ${E^{'} = -Dsinθ+Ecosθ}$ Plug in the angle "θ" 27 degrees and A 'is about -0,06 ${F^{'} = F = -9}$ 4.)Since this is an ellipse according to 1, the standard form of the general equation given is: ${\frac{(x-h)^{2}}{b^{2}}+\frac{(y-k)^{2}}{a^{2}}=1}$ it must be. Finally, I've got this: ${2,96x^{2}+4,73y^{2}+13,38x-0,06y=9}$ Well, what should I do now? As a result of my various researches, there are completely different solutions and I am confused. I request your help
2021/01/30
[ "https://math.stackexchange.com/questions/4005663", "https://math.stackexchange.com", "https://math.stackexchange.com/users/880546/" ]
Given a set $X$ and some property elements of $X$ might satisfy, say *is green*. We can filter out the subset of all elements of $X$, which are green by writing $$\{x \in X \mid x \text{ is green}\}.$$ The appearance of $x$ does **not** mean that there can only be one element of $X$, which is green. Rather, if we want to speak of an element which is green, we have to give it a name: In this case the *variable* $x$. So in your specific instance we have the set $\operatorname{Fun}(X,X)$ of functions from $X$ to $X$ and want to filter out the subset of all elements (which are functions!), which are bijective. This is what $S(X)$ does: $$S(X) = \{f \in \operatorname{Fun}(X,X) \mid f \text{ bijective}\}$$
In a sense, $S(X)$ "comes prior" to (abstract) groups: are precisely the four properties fulfilled by $S(X)$ endowed with map composition as operation (closure, associativity, identity, inverses), that the definition of (abstract) group just mimics and axiomatizes for any set endowed with a binary operation.
56,681,970
I'm trying to implement React Navigation with AuthLoading, AuthStack, and AppStack. The AppStack will contain a bottomTabNavigator with 2 tabs: Home + Profile. The Profile screen will have an edit button that should route to the EditProfile screen. Here's what it looks like when I navigate from Profile to Edit Profile. [Issue](https://imgur.com/a/Do6L8Pq) It has a double header and no bottomTabNavigator? **Full Code:** ``` // Imports: Dependencies import React, { Component } from 'react'; import { createAppContainer, createBottomTabNavigator, createSwitchNavigator, createStackNavigator } from 'react-navigation'; import Icon from 'react-native-vector-icons/MaterialIcons'; import { Provider } from 'react-redux'; import store from './store/store'; import { Button } from 'react-native'; // Imports: Screens import AuthLoading from './screens/AuthLoading'; import Login from './screens/Login'; import SignUp from './screens/SignUp'; import Home from './screens/Home'; import Profile from './screens/Profile'; import EditProfile from './screens/EditProfile'; import Filters from './screens/Filters'; // React Navigation: Bottom Tab Navigator export const BottomTabNavigator = createBottomTabNavigator( { Home: { screen: Home, navigationOptions: { tabBarLabel: 'Home', tabBarIcon: ({ tintColor }) => ( <Icon name="menu" color={tintColor} size={26} /> ), } }, Profile: { screen: Profile, navigationOptions: { tabBarLabel: 'Profile', tabBarIcon: ({ tintColor }) => ( <Icon name="perm-identity" color={tintColor} size={26} /> ), } } }, { mode: 'screen', navigationOptions: ({ navigation }) => { const { routeName } = navigation.state.routes[navigation.state.index]; return { headerTitle: routeName }; } } ); // React Navigation: Authentication Stack Navigator export const AuthStack = createStackNavigator({ // Screens SignUp: SignUp, Login: Login, }); // React Navigation: Home Stack Navigator export const HomeStack = createStackNavigator({ Home: Home, Filters: Filters, }); // React Navigation: Profile Stack Navigator export const ProfileStack = createStackNavigator({ Profile: Profile, EditProfile: EditProfile, }); // React Navigation: Application Stack Navigator export const AppStack = createStackNavigator({ // Navigators BottomTabNavigator: BottomTabNavigator, // Screens Home: HomeStack, Profile: ProfileStack, }); // React Navigation: Switch Container export const AppContainer = createAppContainer(createSwitchNavigator( { AuthLoading: AuthLoading, AuthStack: AuthStack, AppStack: AppStack, }, // Options { initialRouteName: 'AuthLoading', } )); // React Native: Application export default class App extends React.Component { render() { return ( <Provider store={store}> <AppContainer /> </Provider> ); } } ```
2019/06/20
[ "https://Stackoverflow.com/questions/56681970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9378367/" ]
``` android:layout_margin="15dp" ``` There's your problem, you are adding margin, where you don't want it in your cell's main `LinearLayout`. Remove that line and you should be good. --- Side Note: Since you are using `RecyclerView` instead of using `android:background="@drawable/list_cell_border_main"` to add borders to your cells, use `DividerItemDecoration` check out this great [SO Answer](https://stackoverflow.com/a/27037230/1889768) which guides you on how to do exactly that.
The problem is on `android:layout_margin="15dp"` in the `LinearLayout` ;)
12,652,889
I have a table with a couple of thousand rows: from this I need to extract a total for column `WTE` for each value in column `band`, including those where the total is 0. I also need each total to be in a column of its own, so that I can easily update a summary table. The code I have at present returns the values from the relevant rows: ``` SELECT IF(band="E",WTE,0) AS `Band6_WTE` FROM `orthoptists` AS o LEFT JOIN `instances` AS i ON o.instance_FK = i.id WHERE i.region = 14 ``` But when I add SUM(), the return is incorrect (zero, when it should be several thousands): ``` SELECT IF(band="E",SUM(WTE),0) AS `Band6_WTE` FROM `orthoptists` AS o LEFT JOIN `instances` AS i ON o.instance_FK = i.id WHERE i.region = 14 ``` I have looked at <http://en.wikibooks.org/wiki/MySQL/Pivot_table>, but I do not understand how that approach should be applied to my problem. What should I do?
2012/09/29
[ "https://Stackoverflow.com/questions/12652889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/721931/" ]
In this particular case, wouldn't it be easier to use `WHERE`? ``` SELECT SUM(WTE) AS `Band6_WTE` FROM `orthoptists` AS o LEFT JOIN `instances` AS i ON o.instance_FK = i.id WHERE i.region = 14 AND band = "E" ``` For the general case, you could use `GROUP BY` since you say you need the result for each band (each value in column band): ``` SELECT band, SUM(WTE) AS `WTE` FROM `orthoptists` AS o LEFT JOIN `instances` AS i ON o.instance_FK = i.id WHERE i.region = 14 GROUP BY band ``` This will give either NULL or 0, you can instead use `IFNULL` to convert NULL to 0 if you like: ``` IFNULL(SUM(WTE), 0) ``` **Edit**: as you pointed out in the comments, you'd like multiple columns for the different bands rather than multiple rows. Generally speaking, you should not do that from SQL (use the second query and perform a pivot operation from your code), but there are exceptions, cases where it's significantly more complicated to do that outside of SQL, so here's how you could do it: ``` SELECT (SELECT SUM(WTE) FROM `orthoptists` AS o LEFT JOIN `instances` AS i ON o.instance_FK = i.id WHERE i.region = 14 AND band = "E") AS `Band6_WTE`, (SELECT SUM(WTE) FROM `orthoptists` AS o LEFT JOIN `instances` AS i ON o.instance_FK = i.id WHERE i.region = 14 AND band = "F") AS `Band7_WTE`, (SELECT SUM(WTE) FROM `orthoptists` AS o LEFT JOIN `instances` AS i ON o.instance_FK = i.id WHERE i.region = 14 AND band = "G") AS `Band8_WTE` ``` The precise syntax might need a little bit of tweaking (some databases require each `SELECT` to include a `FROM` clause, some may require a name for each column in a subselect, I don't think MySQL does but I can't check right now), but the principle should be applicable regardless.
Noody has explained why your original query give you the incorrect result. The original query has an aggregation function in the `SELECT` clause. This tells MySQL that this is an aggregation. There is no `GROUP BY` clause, so it returns one row, treating all rows as a single group. Now, what happens to `band` in this case? In the SQL standard or any other dialect of SQL, the original query would return an error, saying something like `band` is not aggregated. MySQL has a (mis)feature called Hidden Columns, which allows this syntax. It takes a random value of `band` from all the rows for the comparison. The value might have the value "E", in which case the sum of all WTE is returned. Or, it might have another value, in which case 0 is returned. In general, you should avoid using Hidden Columns. Any "bare" column in your `SELECT` statement should also be in the `GROUP BY` clause, when you have an aggregation query.
59,906,286
I'm trying to understand why my snippet of code ends up with the class "list" as opposed to a Tuple. The way I'd like it to work is to open a CSV, check for the user/password header and use those to append to a tuple so that I can retrieve accounts by doing accounts[1], accounts[2] It's important that the list of accounts is immutable to me, so I'm trying to end up with the class tuple. ``` # our csv file name filename = "resources/accounts.csv" with open(filename) as infile: reader = csv.DictReader(infile) accounts = [] for row in reader: accounts.append((row['user'],row['password'])) print(type(accounts)) ```
2020/01/25
[ "https://Stackoverflow.com/questions/59906286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004379/" ]
``` accounts = [] for row in reader: accounts.append((row['user'],row['password'])) ``` You're starting with an empty list `[]` and appending items to it, so you end up with a list. If you want a tuple you could convert the list to one at the end: ``` accounts = [] for row in reader: accounts.append((row['user'],row['password'])) accounts = tuple(accounts) ``` Better yet, [use a generator expression to create a tuple](https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python) from the get go. That way you avoid creating a temporary list just to throw it away. ``` with open(filename) as infile: reader = csv.DictReader(infile) accounts = tuple((row['user'], row['password']) for row in reader) ```
As you already know a tuple is immutable. So you are correct in making `accounts` a list. If you want to store it as a tuple afterwards you can convert it like this: ```py accounts = tuple(accounts) ```
57,715,569
Suppose I've got: “Aliud est grâtiam habêre, aliud grâtiam referre. Nôn omnês quî tibi prô beneficiîs grâtiäs agunt, ipsî posteâ, sî opus fuerit, grâtiam tibi referent. Facile est grâtiäs agere prô beneficiîs, nec vërô quidquam difficilius esse vidētur quam beneficiôrum meminisse.” But I want “Aliud est grātiam habēre, aliud grātiam referre. Nōn omnēs quī tibi prō beneficiīs grātiās agunt, ipsī posteā, sī opus fuerit, grātiam tibi referent. Facile est grātiās agere prō beneficiīs, nec vērō quidquam difficilius esse vidētur quam beneficiōrum meminisse.” I.e. â ä -> ā, etc ëê -> ē, etc I'm thinking a big keyboard macro doing lots of search and replaces, but is there a better way?
2019/08/29
[ "https://Stackoverflow.com/questions/57715569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254837/" ]
In many cases it saves a lot of time writing Emacs lisp functions instead of storing kbd-macros etc. Emacs comes with excellent debugging tools. For example call `M-x edebug-eval-top-level-form RET` at your example with solution below: ``` (defun accent-replace () "Does what I want" (interactive "*") (dolist (ele (list ?â ?ä ?ê ?ë ?î ?ô)) (setq elt (char-to-string ele)) (goto-char (point-min)) (while (search-forward elt nil t 1) (replace-match (char-to-string (pcase ele (`?â ?ā) (`?ä ?ā) (`?ê ?ē) (`?ë ?ē) (`?î ?ī) (`?ô ?ō))))))) ```
Inspired by the comments, I came up with this interactive command: ``` (defun tr (from to beg end) "Replace each character in FROM with the character at the same position in TO. Operates from BEG to END, or within the marked region if called interactively. If TO is shorter than FROM, any characters in FROM beyond the length of TO are just deleted." (interactive "sTranslate from: \nsTranslate to: \nr") (goto-char beg) (setq end (copy-marker end)) (let ((regexp (regexp-opt (mapcar 'string from)))) (while (search-forward-regexp regexp end t) (let* ((index (cl-search (match-string 0) from)) (replace-with (if (> (1+ index) (length to)) "" (substring to index (1+ index))))) (setf (buffer-substring (match-beginning 0) (match-end 0)) replace-with))))) ``` Mark the region that contains the text, call `M-x tr`, and pass `âäëê` as the first string and `āāēē` as the second string.
1,209,383
I've been scouring the web and my textbook to no avail. I understand how to transform a matrix with respect to the standard basis, but not to a basis comprised of matrices. I need to find the matrix of T with respect to a basis. My transformation matrix is: $$ A = \begin{bmatrix} 1 & 2 \\ 0 & 3 \\ \end{bmatrix} $$ and I need to find it with respect to the basis: $$ B = \left\{ \begin{bmatrix} 1& 0 \\ 0 &0 \\ \end{bmatrix} , \begin{bmatrix} 0 & 1 \\ 0 & 0 \\ \end{bmatrix}, \begin{bmatrix} 0 & 1 \\ 0 & 1 \\ \end{bmatrix}\right\} $$ I'm sorry my formatting is rough, the three B matrices are in the book as B = (Matrix 1, Matrix 2, Matrix 3). I really don't understand this. My book has a column by column method that has completely stumped me.
2015/03/27
[ "https://math.stackexchange.com/questions/1209383", "https://math.stackexchange.com", "https://math.stackexchange.com/users/226942/" ]
I think your difficulty is purely "conceptual". A vector space is ANY set that obeys the axioms of a vector space (such a definition assumes an associated "field of scalars"). In particular, over a given field $F$, the set: $\text{Hom}\_F(U,V)$ = all linear transformations $U \to V$ is a vector space. So "matrices" are vectors, too! Look, we can add them: if $A = (a\_{ij}), B = (b\_{ij})$ then $A + B = (c\_{ij})$, where for each $i,j: c\_{ij} = a\_{ij} + b\_{ij}$, and we can "multiply by a scalar": $rA = (ra\_{ij})$ (sometimes this is written as $(rI)A$). One way to "ease the conceptual transition" is called the "vectorization" of matrices: we just string the columns "head-to-toe" into one long column, so that: $A = \begin{bmatrix}1&2\\0&3\end{bmatrix}$ becomes: $A = \begin{bmatrix}1\\0\\2\\3\end{bmatrix}$, transforming an element of $\text{Mat}\_2(F)$ into an element of $F^4$ (you can take $F = \Bbb R$, for concreteness, if you primarily deal with real vector spaces). Seen this way, it becomes clear that the second coordinate of your basis vectors is "unnecessary baggage", as it is always $0$. This is no different than identifying the subspace: $U = \{(x,0,y,z) \in \Bbb R^4\}$ with $\Bbb R^3 = \{(x,y,z):x,y,z \in \Bbb R\}$ It should be clear that $\phi:U \to \Bbb R^3$ given by $\phi(x,0,y,z) = (x,y,z)$ is a bijective linear transformation. So, in your situation, you want to find $a,b,c$ such that: $A = \begin{bmatrix}1\\0\\2\\3\end{bmatrix} = a\begin{bmatrix}1\\0\\0\\0\end{bmatrix} + b\begin{bmatrix}0\\0\\1\\0\end{bmatrix} + c\begin{bmatrix}0\\0\\1\\1\end{bmatrix}$ Which is just a system of 3 linear equations in 3 unknowns: $a = 1\\b+c = 2\\c = 3$ that you should be proficient in solving by now.
From the nature of your question, I'm not sure you've transcribed it correctly for us. I suspect that the answer is this: $$ \begin{bmatrix} {1} & {2} \\ {0} & {3} \\ \end{bmatrix} = 1 \cdot \begin{bmatrix} {1} & {0} \\ {0} & {0} \\ \end{bmatrix} + (-1) \cdot \begin{bmatrix} {0} & {1} \\ {0} & {0} \\ \end{bmatrix} + 3 \cdot \begin{bmatrix} 0 &1 \\ 0 & 1 \\ \end{bmatrix} $$ so that the coordinates of your matrix, $A$, with respect to the basis given, are $1, -1, 3$. Perhaps you're supposed to write that as a vector, in which case it'd be $$ \begin{bmatrix} 1 \\ -1 \\ 3 \end{bmatrix}. $$
188,556
Where can I find the syslog config file under SLES 12? `rsyslog` and `syslog-service` are installed according to YaST2 and `rcsyslog status` outputs: ``` ServerName:~ # rcsyslog status Usage: /sbin/rcsyslog {start|stop|status|try-restart|restart|force-reload|reload} rsyslog.service - System Logging Service Loaded: loaded (/usr/lib/systemd/system/rsyslog.service; enabled) Active: active (running) since Wed 2015-03-04 16:05:46 CET; 1 day 17h ago Main PID: 787 (rsyslogd) CGroup: /system.slice/rsyslog.service ââ787 /usr/sbin/rsyslogd -n ```
2015/03/06
[ "https://unix.stackexchange.com/questions/188556", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/94195/" ]
I don't know of a single-command way to do this. The GUI programs are doing a fair bit of interrogation of the disk to take the "right" approach and you'll need to do some of that work yourself. You don't need sudo, though, and I think the resulting sequence of events is relatively painless. The Short Answer ---------------- Use `udisksctl` from the `udisks2` package: ``` udisksctl unlock -b /path/to/disk/partition udisksctl mount -b /path/to/unlocked/device ``` Your user account will need to be appropriately authorized in order for the above to work. On Debian and Ubuntu, that means adding your account to the `plugdev` group. When you're done with the disk: ``` udisksctl unmount -b /path/to/unlocked/device udisksctl lock -b /path/to/disk/partition udisksctl power-off -b /path/to/disk/or/partition ``` How to Set Things Up -------------------- Here's how you can set things up (via the command line) to make the process of using the disk as painless as possible. I'll assume you want to use the entirety of the USB drive as a single filesystem. Other configurations will require modifications to the instructions. Caveat on variations: I haven't found a way to use LVM in the encrypted container that will allow an unprivileged account to disconnect everything. (I don't see a way to deactivate a volume group via `udisksctl`.) For purposes of illustration, we'll say that the disk is `/dev/sda`. You'll need a name for the filesystem to make it easier to reference later. I'll use "`example`". ### Partition the Disk Run `sudo parted /dev/sda` and run the following commands: ``` mklabel gpt mkpart example-part 1MiB -1s quit ``` The `mkpart` command will probably prompt you to adjust the parameters slightly. You should be okay accepting its recommended numbers. The partition will now be available via `/dev/disk/by-partlabel/example-part`. ### Create and Mount the LUKS Partition ``` sudo cryptsetup luksFormat /dev/disk/by-partlabel/example-part ``` Go through the prompts. ``` sudo cryptsetup luksOpen /dev/disk/by-partlabel/example-part example-unlocked ``` The encrypted device is now available at `/dev/mapper/example-unlocked`. This is not going to be a permanent thing; it's just for the setup process. ### Create Your Filesystem Let's assume that the filesystem you're using is XFS. Pretty much any other traditional filesystem will work the same way. The important thing is to add a label that you can reference later: ``` sudo mkfs -t xfs -L example /dev/mapper/example-unlocked ``` The filesystem's block device can now be accessed via `/dev/disk/by-label/example`. ### Set Filesystem Permissions By default, the filesystem will be only accessible by root. In most cases, you probably want the files to be accessible by your user account. Assuming your account name is "`user`": ``` udisksctl mount -b /dev/disk/by-label/example sudo chown user:user /media/user/example ``` ### Close Everything Down ``` udisksctl unmount -b /dev/disks/by-label/example sudo cryptsetup luksClose example-unlocked ``` ### Use Your Filesystem This is what you'll do regularly. After plugging in the USB drive, ``` udisksctl unlock -b /dev/disks/by-partlabel/example-part udisksctl mount -b /dev/disks/by-label/example ``` If your user account is "`user`", the filesystem will now be mounted at `/media/user/example`. To unmount the filesystem: ``` udisksctl unmount -b /dev/disks/by-label/example udisksctl lock -b /dev/disks/by-partlabel/example-part udisksctl power-off -b /dev/disks/by-partlabel/example-part ``` Now you can disconnect the USB drive.
On Debian you can use the definitions in `/etc/crypttab` and `/etc/fstab`: ``` cryptdisks_start <name> mount <mountpoint> umount <mountpoint> cryptdisks_stop <name> ```
3,173,939
How to split these strings in jquery? * Mode1 * 2Level I want to get only the numbers from the above two strings in jquery... The strings may be `Mode11,Mode111,22Level,222Level` etc the characters `Mode` and `Level` wont change...
2010/07/04
[ "https://Stackoverflow.com/questions/3173939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
var myString="Mode111"; var num =myString.replace(/[a-zA-Z]/g,"");
You could do something like this: ``` var numbers = "Mode111".match(/\d/g).join("") var alpha = "Mode111".match(/[a-z]/gi).join("") ``` I think there is an easier way with match collections but I can't find anything to show whether javascript supports them. I will see if I can find it.
438,014
I have media box in my network that hard coded to use specific DNS servers like Google DNS. But I want force this device to use my own DNS servers instead of hard coded DNS. Only way I think this is possible to mangle the DNS request coming from that media box IP to DNAT to my DNS server IP. but I'm not quite sure how do I put rule with mentioning source port and source ip at the same time I use openwrt router with openwrt 15.0 chaos calmer on it. ``` iptables -t nat -A PREROUTING -p tcp --sport 53 -j DNAT --to-destination 192.168.1.153 ``` Above query will do the job but it will mangle all the port 53 request. how can I specify this rule with IP address. or is there any other way to do it ?
2018/04/16
[ "https://unix.stackexchange.com/questions/438014", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/408254/" ]
I use ``` iptables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT iptables -t nat -A PREROUTING -p tcp --dport 53 -j REDIRECT ``` The redirect just redirects the requests to the router.
Just add `-d a.b.c.d` immediately after `tcp`, to restrict the rule to packets with destination address `a.b.c.d`. And add `-s e.f.g.h` to also restrict by source address.
159,182
If I know the frequency of individual notes being played (let's assume D, F# and A), how do I determine the final frequency if they are played (nearly) simultaneously as a chord. To put the problem in context, I am writing a program where user inputs are classified and chords are played as output. My programming knowledge is limited (my degrees are in biochemistry and neuroscience), and the help file gave me the following options: 1. Play a frequency 2. Use a recording for playback As I do not wish to use the second option, I was wondering how to calculate the resulting frequency or to represent resultant sound mathematically. If someone could explain the theory behind this or post a link for the same, I'd be especially grateful.
2015/01/13
[ "https://physics.stackexchange.com/questions/159182", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/70683/" ]
A chords does not have a single frequency as it consists of three notes of different frequencies being played at the same time. It may sounds like a single note to you since the three frequencies that make up the chords have to be in harmony. If you wish to play a certain tune or song using only single frequencies I would suggest you only play the root note of each chords rather than the full chord. This gives you the typical monotone ringtone sounds from the 90s.
You know that a single note in an instrument contains multiple frequencies and harmonics. The wave shape is never an ideal sine wave carrying one frequency. So combining two notes can be done with a [convolution integral](http://en.wikipedia.org/wiki/Convolution_theorem). You convert each note to the frequency domain via a Fourier transform and combine the signals using the convolution integral. In the end you have the frequency spectrum of the resulting sound.
6,982,797
``` for ( var i=0; i<MyArrayObj.length; i++ ) { } ``` I am getting an error called, Cannot call MyArrayObj, since its is NULL
2011/08/08
[ "https://Stackoverflow.com/questions/6982797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733644/" ]
Assuming there isn't a logical error with `MyArrayObj` being null: ``` if(MyArrayObj) { for ( var i=0; i<MyArrayObj.length; i++ ) { } } ```
Did you declare the MyArrayObj and assigned a correct value to it? Could you provide the code where you assign the array to a value? Otherwise check if the array is not null first.
533,863
I migrated an SVN server today and ran into an issue. I have a repo that has an svn:externals property on a trunk subfolder. This folder has been branched a bunch of times and now this svn:externals reference needs updated on every single branch to refer to the new server. Is there an easy way to update all of these properties? I'm not excited about updating them individually by hand. I'm on windows, too, so a fancy [bash script](http://www.thomaskeller.biz/blog/2009/01/05/change-svnexternals-quickly/) won't work. There's got to be an easier way! Note: this is from the old pre-1.5 days when svn:externals references had to be absolute. --- Update: a simple `relocate` won't do it since these are absolute URLs.
2009/02/10
[ "https://Stackoverflow.com/questions/533863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29/" ]
Potentially, make them members of another type. Nested types work well here, too. That makes a lot of sense if they form a logical group, and let you write several methods using the same type. Beyond that, we'd have to know details of what you're doing to comment further I suspect.
Do *not* turn them into member/global variables. They make reasoning about application state an order of magnitude more difficult, even without multithreading - and with it, as you say, it becomes a total nightmare. You might try collapsing them into simple objects and passing those around instead, if you notice that certain parameters are always being passed around in groups.
2,119,680
On the client side using jQuery, I want to know if I can just check if a link URL is valid (i.e. doesn't return a 404). This link points to another domain, so if I just use $.get() then I end up with a permission issue. I remember reading something about using a JSONP request, but I don't remember.
2010/01/22
[ "https://Stackoverflow.com/questions/2119680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17635/" ]
JSONP works if the server you are calling on can return JSONP formatted response. Which basically means a script that calls a callback function on your page after getting loaded. see <http://en.wikipedia.org/wiki/JSON#JSONP> In your case it won't work unless the other site is willing to cooperate or you have a proxy script on your own site. If you want your script to work with sites not under your control, your best bet will be to use a proxy or a iframe hack.
You can't make a request like that to another domain. That is a security feature in the browser. You may have to try doing something in an iframe or something and checking that.
12,142,851
i wanna use the back button on the mobile itself to make a dialog box appear to ask me whether am sure i wanna exit or not? ``` public void onBackPressed() { // TODO Auto-generated method stub AlertDialog.Builder dialog=new AlertDialog.Builder(MainActivity.this); dialog.setTitle("Confirm"); dialog.setMessage("Are you sure you want to exit?"); return; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText text=(EditText)findViewById(R.id.Text); TextWatcher watch=new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub onBackPressed(); } }; text.addTextChangedListener(watch); } ```
2012/08/27
[ "https://Stackoverflow.com/questions/12142851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1602896/" ]
As i considered your `onBackPressed()` is the override method to handle android back key. Just add `dialog.create().show()` to your `onBackPressed();`. It will display **AlertDialog**.. Also removed `onBackPressed();` from `afterTextChanged(Editable s)` else it will calling every time when user try to enter some character in `EditText`.. **Update:** one more thing your `onBackPressed()` should be like, ``` @Override public void onBackPressed() { super.onBackPressed(); AlertDialog.Builder dialog = new AlertDialog.Builder(TestActivity.this); dialog.setTitle("Confirm"); dialog.setMessage("Are you sure you want to exit?"); dialog.create().show(); } ``` Change if you don't.
\**First Way :*\*try as by @Override `onKeyDown` method in your Current Activity: ``` public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == event.KEYCODE_BACK) { showAlert("", "Do you really want to exit?"); } return super.onKeyDown(keyCode, event); } private void showAlert(final String title, final String msg) { AlertDialog.Builder dialouge = new AlertDialog.Builder(CategoriesList.this); dialouge.setMessage(msg); dialouge.setPositiveButton(" Yes ", new DialogInterface.OnClickListener() { public void onClick( DialogInterface arg0, int arg1) { CurrentActivity.this.finish(); } }); dialouge.setNegativeButton(" No ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }); dialouge.show(); } ``` **Second Way:** by @Override `onBackPresed()` ``` public void onBackPresed(){ Log.d(TAG,"inside onBackPressed()"); showAlert("", "Do you really want to exit?"); } ```
22,261,693
All, Does anyone know of a preconfigured Linux-based virtual machine I can use as a Ruby on Rails development environment? My laptop runs Windows 8.1, which is not an ideal platform for Rails development and is not used by professional Rails developers. What I'm specifically looking for is an off-the-shelf Ubuntu VM image I can download and run inside VMWare Player for Windows. The image would already have Ruby and Rails installed and come pre-configured with some common gems like RSpec and Capybara. This way, I don't have to install Ubuntu and all my development tools from scratch. I already tried the VM image that is used in UC Berkeley's free online Rails-based software engineering course (BerkeleyX CS-169.1x), which can be found at: <https://courses.edx.org/courses/BerkeleyX/CS-169.1x/2013_Summer/wiki/CS169.1x/illustrated-vm-install/>. Unfortunately, this image uses Oracle VirtualBox, which did not jive well with my Windows installation and screwed up my power settings and sleep mode badly. Just to clarify, I'm not looking for a VM to host and deploy production Rails apps in (i.e., Amazon AWS/Cloud Services). I'm just looking for a VM to develop in, with access to the Linux terminal and the Rails command line.
2014/03/07
[ "https://Stackoverflow.com/questions/22261693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394524/" ]
You do need a vm. Period. Developing Rails on any type of windows based environment is foolish. You can certainly do your coding there (while running it on a nix box), but Rails is built to be run on a server, virtually no one runs a windows based server for Rails for precisely the reasons you are running into. By far the easiest method to do that is through services such as <https://c9.io/> or <https://www.nitrous.io>. They give you a box to work off of for free. My other suggestion is actually a bit different. Don't. By that I mean don't use a preconfigured box. If you are in the beginning phases using one of the virtual VM's, but if you know you want to get deeper with Rails having gone through the process of setting up a box and install rails on it is both instructive and not as difficult as you might think. I could post a list of instructions here but they would fairly quickly become obsolete. Everything changes including Rails and you will need the skill-set of updating and installing thinks in a nix environment to survive with Rails or web development as a whole. I assure you it isn't as hard as it sounds.
Don't get a VM, you don't need it Windows 8.1 works fine with Rails - just use something like [RailsInstaller](http://railsinstaller.org/en) to install Ruby & Rails, and then you'll be able to install as many gems as you want
15,379
My friend and I want to do a hands on tutorial on Bayes theorem for the Seattle [LessWrong](http://lesswrong.com/) group. Neither of us have done this before, so we're searching for prior art; techniques that other people have tried before and descriptions of how they turned out. What are good techniques and resources for teaching bayes theorem? Reports of both successes and failures are useful, I'd like to know what *not* to do in addition to what to do. The audience is a group of ~8 programmers and natural science students. They'll be smart and capable but not necessarily used to doing much math.
2011/09/09
[ "https://stats.stackexchange.com/questions/15379", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/1146/" ]
The LessWrong website actually has a great visual explanation of Bayes' Theorem: [Bayes' Theorem Illustrated (My Way)](http://lesswrong.com/lw/2b0/bayes_theorem_illustrated_my_way).
Use a deck of cards. What are the chances this card is a spade? What are the chances this card is a spade if I know the card is black? What are the chances this card is a king? What are the chances this card is a king if I know it is a diamond? What are the chances it is a king if I know it is a face card? Show them how it's used in everyday life. What are the chances it will take me less than 30 minutes to get to work.. What if I leave at 8am? What are the chances I will wait in line at the check out counter? What if it is 6pm? What are the chances this person committed the murder? what if we know he has the same blood type as the murderer.
50,195,049
I am new to android and I was able to setup the firebase for my app in kotlin. If i run the app in the **Nexus 5X API 27** emulator I am able to get the database but when i run the app in the actual device **SAMSUNG S5** (Google play Services V 12.5.29, android V 5.0) i don't get the ***addValueEventListener*** call back. ``` ref = FirebaseDatabase.getInstance().reference ref!!.addValueEventListener(object : ValueEventListener { override fun onCancelled(p0: DatabaseError?) { Log.d("firebase", "cancelled") } override fun onDataChange(p0: DataSnapshot?) { if (p0!!.exists()){ Log.d("firebase", "date = $p0") } else { Log.d("firebase", "no data") } } }) ``` Gradle file: ``` apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 26 defaultConfig { applicationId "com.example.wonder" minSdkVersion 21 targetSdkVersion 21 versionCode 1 versionName "1.0" multiDexEnabled true testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support:support-v4:26.1.0' implementation 'com.android.support:design:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' implementation 'com.google.firebase:firebase-messaging:11.2.2' implementation 'com.google.firebase:firebase-database:11.2.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso- core:3.0.1' //implementation 'com.google.android.gms:play-services-maps:11.2.2' implementation 'com.android.support:recyclerview-v7:26.1.0' implementation 'com.google.firebase:firebase-core:11.2.2' // implementation 'com.google.android.gms:play-services-ads:12.0.0' } apply plugin: 'com.google.gms.google-services' ``` I know its not database rule issue because they are set to public. If you have any suggestions please let me know. Thanks EDIT: I do have permissions added in the manifest file **Update: Looks like its working for the device, I just have to wait for 30 minutes. I left the device and came back after a while and the data was there. Could it be threading issue? I am not doing any threading, thought Firebase handles it by itself.**
2018/05/05
[ "https://Stackoverflow.com/questions/50195049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/740972/" ]
Make sure in your Manifest file for the app (the Main manifest file) that you have: `<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/>`
It may happen if you are using release build on the device. Make sure you have added your release sha1 in your firebase app console. [![enter image description here](https://i.stack.imgur.com/OmNwk.png)](https://i.stack.imgur.com/OmNwk.png) Click on Add Fingerprint to enter your release sha1. In your emulator maybe it is working because you have added your debug sha1 and package name in your firebase app key. [Check this for generating sha1 for release build](http://android-er.blogspot.in/2015/09/generate-sha1-fingerprint-of-release.html)
26,516,965
I am new to c# and have gotten stuck on an assignment. The idea is to create an Arraylist with multiple arguments from another class. I am supposed to sort only one of the arguments in a list. If there is only one argument there is no problem´, but I have 5. What do I do? ``` ArrayList people = new ArrayList(); people.Add(new Student("Maria", "Svensson", "1989-06-14", "C#Programming", 7)); people.Add(new Student("Bahar", "Nasri", "1992-08-04", "C#Programming", 5)); people.Add(new Student("Kent", "Kaarik", "1967-12-12", "Software Development", 8)); people.Add(new Student("Ahmed", "Khatib", "1990-06-06", "C#Programming", 9)); people.Add(new Student("Lisa", "Lundin", "1984-01-22", "Software Development", 6)); people.Add(new Student("Peter", "Stark", "1987-08-24", "Software Development", 4)); people.Add(new Student("Christer", "Stefansson", "1987-04-02", "C#Programming", 10)); people.Sort(); foreach (Student item in people) { Console.WriteLine(item.firstN + " " + item.lastN + " " + item.birthD + " " + item.courseT + " " + item.gradeH); } ``` I also get the "Failed to compare two elements in the array" This leads me to believe I need the ICompare command, but I am not sure how to use it. What am I doing wrong? Thanks for any help!!
2014/10/22
[ "https://Stackoverflow.com/questions/26516965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4171590/" ]
Instead of an Arraylist consider a generic list List. Then use LINQ to sort your list. ``` List<Student> people = new List<Student>(); people.Add(new Student("Maria", "Svensson", "1989-06-14", "C#Programming", 7)); people.Add(new Student("Bahar", "Nasri", "1992-08-04", "C#Programming", 5)); people.Add(new Student("Kent", "Kaarik", "1967-12-12", "Software Development", 8)); people.Add(new Student("Ahmed", "Khatib", "1990-06-06", "C#Programming", 9)); people.Add(new Student("Lisa", "Lundin", "1984-01-22", "Software Development", 6)); people.Add(new Student("Peter", "Stark", "1987-08-24", "Software Development", 4)); people.Add(new Student("Christer", "Stefansson", "1987-04-02", "C#Programming", 10)); var orderedPeople = people.OrderBy(x => x.lastN); foreach (Student item in orderedPeople) { Console.WriteLine(item.firstN + " " + item.lastN + " " + item.birthD + " " + item.courseT + " " + item.gradeH); } ``` To sort by multiple columns, use ThenBy. ``` var orderedPeople = people.OrderBy(x => x.lastN).ThenBy(x => x.firstN); ```
Thanks for all the advice. I ended up doing a generic list List and everything worked smoothly in the end. For the assignment I was supposed to do one with ArrayList, but in the end the generic one seemed way better. I am hoping that it will be ok!