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,296,708
I am replacing my `ListView` with `RecyclerView`, list showing ok, but I would like to know how to get clicked item and its position, similar to the method [`OnItemClickListener.onItemClick(AdapterView parent, View v, int position, long id)`](http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html) we use in `ListView`. Thanks for ideas!
2015/02/03
[ "https://Stackoverflow.com/questions/28296708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3540593/" ]
> > Here is the simplest and the easiest way to find the position of the clicked item: > > > I've also faced the same problem. I wanted to find of the position of the clicked/selected item of the RecyclerView() and perform some specific operations on that particular item. getAdapterPosition() method works like a charm for these kind of stuff. I found this method after a day of long research and after trying numerous other methods. ``` int position = getAdapterPosition(); Toast.makeText(this, "Position is: "+position, Toast.LENGTH_SHORT).show(); ``` You do not have to use any extra method. Just create a global variable named 'position' and initialize it with getAdapterPosition() in any of the major method of the adapter (class or similar). Here is a brief documentation from this [link](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder#getAdapterPosition()). > > getAdapterPosition > added in version 22.1.0 > int getAdapterPosition () > Returns the Adapter position of the item represented by this ViewHolder. > Note that this might be different than the getLayoutPosition() if there are pending adapter updates but a new layout pass has not happened yet. > RecyclerView does not handle any adapter updates until the next layout traversal. This may create temporary inconsistencies between what user sees on the screen and what adapter contents have. This inconsistency is not important since it will be less than 16ms but it might be a problem if you want to use ViewHolder position to access the adapter. Sometimes, you may need to get the exact adapter position to do some actions in response to user events. In that case, you should use this method which will calculate the Adapter position of the ViewHolder. > > > Happy to help. Feel free to ask doubts.
Try in this way Adapter class : ``` public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> { public interface OnItemClickListener { void onItemClick(ContentItem item); } private final List<ContentItem> items; private final OnItemClickListener listener; public ContentAdapter(List<ContentItem> items, OnItemClickListener listener) { this.items = items; this.listener = listener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_item, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.bind(items.get(position), listener); } @Override public int getItemCount() { return items.size(); } static class ViewHolder extends RecyclerView.ViewHolder { private TextView name; private ImageView image; public ViewHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.name); image = (ImageView) itemView.findViewById(R.id.image); } public void bind(final ContentItem item, final OnItemClickListener listener) { name.setText(item.name); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(item); } }); } } ``` } In your Activity or fragment : ``` ContentAdapter adapter = new ContentAdapter(itemList, this); ``` Note : Implement the OnItemClickListener based on context given by you in activity or fragment and overide methods.
41,457,721
I want to implement a **html table**. This is the screen shot. [![enter image description here](https://i.stack.imgur.com/yS3g5.png)](https://i.stack.imgur.com/yS3g5.png) The first line Categories is **static**. In the second line, the first column is static (date and images), but the second column of times and channels should be **scrollable**. There will be 24 columns, times with half an hour interval. And only that portion should be scrollable. Any ideas how I can achieve that? **This is my current code but it is no way near to what i want.** ``` <table width="100%" class="guide-table" BORDER=10 BORDERCOLOR="#EEEEEE" BORDERCOLORLIGHT="#EEEEEE" BORDERCOLORDARK="#EEEEEE"> <tr> <td>Fri, 25 Sep</td> <td>4:30 PM</td> <td>5:00 PM</td> <td>5:30 PM</td> <td>6:00 PM</td> <td>6:30 PM</td> <td>4:30 PM</td> <td>5:00 PM</td> <td>5:30 PM</td> <td>6:00 PM</td> <td>6:30 PM</td> <td>4:30 PM</td> <td>5:00 PM</td> <td>5:30 PM</td> <td>6:00 PM</td> <td>6:30 PM</td> <td>4:30 PM</td> <td>5:00 PM</td> <td>5:30 PM</td> <td>6:00 PM</td> </tr> <tr> <td><img src="https://iprx.ten.com.au/ImageHandler.ashx?w=250&h=140&f=jpg&u=https%3A%2F%2Fnetworkten-a.akamaihd.net%2Fnew%2F2199827728001%2F201612%2F86%2F2199827728001_5239789882001_5239788195001-vs.jpg%3FpubId%3D2199827728001" height="35px" width="75px"></td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> <td>Ten News</td> </tr> </table> ```
2017/01/04
[ "https://Stackoverflow.com/questions/41457721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5160493/" ]
In C all strings should be null (i.e. `\0`) terminated, so your second variable should look like the following: ``` char b[] = {'d', 'e', 'f', '\0'}; ``` You might be curious why `"defabc"` is printed with your code. The answer is, all local variables are stored in a [stack-based memory layout](http://www.geeksforgeeks.org/memory-layout-of-c-program/). So your memory layout looks like this: ``` |'d' | <-- b |'e' | |'f' | |'a' | <-- a |'b' | |'c' | |'\0'| ``` Also note that `printf("%s", ...)` reads until it reach a `\0`, so `printf("%s", a)` works as expected but `printf("%s", b)` prints `"defabc"`.
You need a null terminator at the end of both strings. your second string does not have it as its defined as an array of characters.
7,741,033
Which one of these blocks of code performs better, and which one of them is more readable? I'd guess the gain would be negligible, particularly in the second block. I am just curious. **Block #1** ``` string height; string width; if (myFlag == 1) { height = "60%"; width = "60%"; } else { height = "80%"; width = "80%"; } ``` **Block #2** ``` string height = "80%"; string width = "80%"; if (myFlag == 1) { height = "60%"; width = "60%"; } ``` --- **Updated** The results when i tested the above code were that both the blocks performed the same **Block #1** ``` myFlag = 1: 3 Milliseconds myFlag = 0: 3 Milliseconds ``` **Block #2** ``` myFlag = 1: 3 Milliseconds myFlag = 0: 3 Milliseconds ``` But one important thing i noticed here(thanks to [Matthew Steeples answer here](https://stackoverflow.com/questions/7741033/does-if-perform-better-than-if-else/7764909#7764909)) is that since the block of code that i have tested has not used the variables height and width except for assignment in the if-else and if blocks of Code Block-1 and 2 respectively, **the compiler has optimized the IL code by completely removing the if and if-else blocks in question thus showing invalid results for our test here**. *I have updated both the code blocks to write the values of both height and width to a file thus using them again and forcing the compiler to run our test blocks(I hope), but you can observe from the code that the actual file writing part does not effect our test results* This is the updated results, C# and IL Code **Results** **Block #1** ``` myFlag = 1: 1688 Milliseconds myFlag = 0: 1664 Milliseconds ``` **Block #2** ``` myFlag = 1: 1700 Milliseconds myFlag = 0: 1677 Milliseconds ``` **C#.net Code** **Block #1** ``` public long WithIfAndElse(int myFlag) { Stopwatch myTimer = new Stopwatch(); string someString = ""; myTimer.Start(); for (int i = 0; i < 1000000; i++) { string height; string width; if (myFlag == 1) { height = "60%"; width = "60%"; } else { height = "80%"; width = "80%"; } someString = "Height: " + height + Environment.NewLine + "Width: " + width; } myTimer.Stop(); File.WriteAllText("testifelse.txt", someString); return myTimer.ElapsedMilliseconds; } ``` **Block #2** ``` public long WithOnlyIf(int myFlag) { Stopwatch myTimer = new Stopwatch(); string someString = ""; myTimer.Start(); for (int i = 0; i < 1000000; i++) { string height = "80%"; string width = "80%"; if (myFlag == 1) { height = "60%"; width = "60%"; } someString = "Height: " + height + Environment.NewLine + "Width: " + width; } myTimer.Stop(); File.WriteAllText("testif.txt", someString); return myTimer.ElapsedMilliseconds; } ``` **IL Code Generated By ildasm.exe** **Block #1** ``` .method public hidebysig instance int64 WithIfAndElse(int32 myFlag) cil managed { // Code size 144 (0x90) .maxstack 3 .locals init ([0] class [System]System.Diagnostics.Stopwatch myTimer, [1] string someString, [2] int32 i, [3] string height, [4] string width, [5] string[] CS$0$0000) IL_0000: newobj instance void [System]System.Diagnostics.Stopwatch::.ctor() IL_0005: stloc.0 IL_0006: ldstr "" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: callvirt instance void [System]System.Diagnostics.Stopwatch::Start() IL_0012: ldc.i4.0 IL_0013: stloc.2 IL_0014: br.s IL_0070 IL_0016: ldarg.1 IL_0017: ldc.i4.1 IL_0018: bne.un.s IL_0029 IL_001a: ldstr "60%" IL_001f: stloc.3 IL_0020: ldstr "60%" IL_0025: stloc.s width IL_0027: br.s IL_0036 IL_0029: ldstr "80%" IL_002e: stloc.3 IL_002f: ldstr "80%" IL_0034: stloc.s width IL_0036: ldc.i4.5 IL_0037: newarr [mscorlib]System.String IL_003c: stloc.s CS$0$0000 IL_003e: ldloc.s CS$0$0000 IL_0040: ldc.i4.0 IL_0041: ldstr "Height: " IL_0046: stelem.ref IL_0047: ldloc.s CS$0$0000 IL_0049: ldc.i4.1 IL_004a: ldloc.3 IL_004b: stelem.ref IL_004c: ldloc.s CS$0$0000 IL_004e: ldc.i4.2 IL_004f: call string [mscorlib]System.Environment::get_NewLine() IL_0054: stelem.ref IL_0055: ldloc.s CS$0$0000 IL_0057: ldc.i4.3 IL_0058: ldstr "Width: " IL_005d: stelem.ref IL_005e: ldloc.s CS$0$0000 IL_0060: ldc.i4.4 IL_0061: ldloc.s width IL_0063: stelem.ref IL_0064: ldloc.s CS$0$0000 IL_0066: call string [mscorlib]System.String::Concat(string[]) IL_006b: stloc.1 IL_006c: ldloc.2 IL_006d: ldc.i4.1 IL_006e: add IL_006f: stloc.2 IL_0070: ldloc.2 IL_0071: ldc.i4 0xf4240 IL_0076: blt.s IL_0016 IL_0078: ldloc.0 IL_0079: callvirt instance void [System]System.Diagnostics.Stopwatch::Stop() IL_007e: ldstr "testifelse.txt" IL_0083: ldloc.1 IL_0084: call void [mscorlib]System.IO.File::WriteAllText(string, string) IL_0089: ldloc.0 IL_008a: callvirt instance int64 [System]System.Diagnostics.Stopwatch::get_ElapsedMilliseconds() IL_008f: ret } // end of method frmResearch::WithIfAndElse ``` **Block #2** ``` .method public hidebysig instance int64 WithOnlyIf(int32 myFlag) cil managed { // Code size 142 (0x8e) .maxstack 3 .locals init ([0] class [System]System.Diagnostics.Stopwatch myTimer, [1] string someString, [2] int32 i, [3] string height, [4] string width, [5] string[] CS$0$0000) IL_0000: newobj instance void [System]System.Diagnostics.Stopwatch::.ctor() IL_0005: stloc.0 IL_0006: ldstr "" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: callvirt instance void [System]System.Diagnostics.Stopwatch::Start() IL_0012: ldc.i4.0 IL_0013: stloc.2 IL_0014: br.s IL_006e IL_0016: ldstr "80%" IL_001b: stloc.3 IL_001c: ldstr "80%" IL_0021: stloc.s width IL_0023: ldarg.1 IL_0024: ldc.i4.1 IL_0025: bne.un.s IL_0034 IL_0027: ldstr "60%" IL_002c: stloc.3 IL_002d: ldstr "60%" IL_0032: stloc.s width IL_0034: ldc.i4.5 IL_0035: newarr [mscorlib]System.String IL_003a: stloc.s CS$0$0000 IL_003c: ldloc.s CS$0$0000 IL_003e: ldc.i4.0 IL_003f: ldstr "Height: " IL_0044: stelem.ref IL_0045: ldloc.s CS$0$0000 IL_0047: ldc.i4.1 IL_0048: ldloc.3 IL_0049: stelem.ref IL_004a: ldloc.s CS$0$0000 IL_004c: ldc.i4.2 IL_004d: call string [mscorlib]System.Environment::get_NewLine() IL_0052: stelem.ref IL_0053: ldloc.s CS$0$0000 IL_0055: ldc.i4.3 IL_0056: ldstr "Width: " IL_005b: stelem.ref IL_005c: ldloc.s CS$0$0000 IL_005e: ldc.i4.4 IL_005f: ldloc.s width IL_0061: stelem.ref IL_0062: ldloc.s CS$0$0000 IL_0064: call string [mscorlib]System.String::Concat(string[]) IL_0069: stloc.1 IL_006a: ldloc.2 IL_006b: ldc.i4.1 IL_006c: add IL_006d: stloc.2 IL_006e: ldloc.2 IL_006f: ldc.i4 0xf4240 IL_0074: blt.s IL_0016 IL_0076: ldloc.0 IL_0077: callvirt instance void [System]System.Diagnostics.Stopwatch::Stop() IL_007c: ldstr "testif.txt" IL_0081: ldloc.1 IL_0082: call void [mscorlib]System.IO.File::WriteAllText(string, string) IL_0087: ldloc.0 IL_0088: callvirt instance int64 [System]System.Diagnostics.Stopwatch::get_ElapsedMilliseconds() IL_008d: ret } // end of method frmResearch::WithOnlyIf ``` So we can say that the **IF-Else block(Block #1) runs faster than the if block(Block #2)** as pointed by many in this forum.
2011/10/12
[ "https://Stackoverflow.com/questions/7741033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507184/" ]
The performance gain here is negligible to the tune I'd call this micro-micro-micro-optimization. Go for readability here unless you plan to do this a couple of million times. **Edit:** (re: question in comments) In my opinion the first one is the more readable. It explicitly shows in a ready format what the strings should be for each case. The second one omits a case, so a reviewer would have to look through other areas of the code to determine the default value. To put it into perspective, imagine 50 lines of code between the original declaration/initialization and this particular code block. If it becomes unclear in that case then that would decide it for me.
**Warning:** It's been a while since I worked with specific CPU optimizations. That said, if I were to code this in assembly language, Block 1 would have fewer instructions per loop than block 2. At the assembly/machine code level, if/else is essentially free when compared to if, because either case expands to essentially the same instructions (load, compare, conditional-jump). Block1: best case: 5, worst: 6 ``` Load value of myFlag Compare to const 1 Jump if zero (equal) :t1 height = "80%"; width = "80%"; Jump :t2 :t1 height = "60%"; width = "60%"; :t2 ``` Block2: best case: 6, worst: 7 ``` height = "80%"; width = "80%"; Load value of myFlag Compare to const 1 Jump if non-zero (not-equal) :t1 height = "60%"; width = "60%"; :t1 ``` **Caveats:** * Not all instructions are created equal, and jumps in particular tended to be more expensive when I was studying assembly... modern processors have basically done away with this tendency. * Modern compilers do a HUGE amount of optimization, and may change the structure of your code from either one of these constructs to the equivalent of the other, or a completely different method entirely. (I've seen some rather creative use of array indices that could be used in cases like this as well) **Conclusion:** In general, the difference, even at the machine code level will be quite minimal between these two flows. Chose the one that works best for you, and let the compiler figure out the best way to optimize it. All relatively minor cases like this should more or less be treated that way. Macro-optimizations which change the number of computations for example, or reduce expensive function calls should be aggressively implemented. Minor loop optimizations like this are unlikely to make a real difference in practice, especially after the compiler is through with it.
11,535
[Gatherer](http://gatherer.wizards.com/Pages/Default.aspx) is great (sort of) for building decks, but I'd like the additional filter of specifying the search specifically to the cards I own. Is this a feature I'm just not seeing or is there an app of some sort that does this? I'd also like if it were always as up to date as Gatherer is.
2013/03/18
[ "https://boardgames.stackexchange.com/questions/11535", "https://boardgames.stackexchange.com", "https://boardgames.stackexchange.com/users/4974/" ]
**Mtgdb.Gui**, a free program I wrote can do this. The screenshot below demonstrates searching by text (left arrow) while limiting the search to the cards from collection you own (right arrow) [![a button to narrow down search to owned cards only](https://github.com/NikolayXHD/Mtgdb/raw/master/out/help/l/chart-filter-collection.jpg)](https://github.com/NikolayXHD/Mtgdb/raw/master/out/help/l/chart-filter-collection.jpg) Besides managing your physical collection, you can import your collection and decks from [Magic The Gathering Online](https://magic.wizards.com/en/content/magic-online-products-game-info), build your decks in Mtgdb.Gui and load them back into MTGO. --- [Wiki](https://github.com/NikolayXHD/Mtgdb/wiki) to get more information and screenshots
iMtG for iOS has full blown inventory management system linked with Deck Builder. It is completely free for people with collections which would fit in 3 binders. iMtG is made by myself (as someone who cares), it has had regular database updates since 2011. It is important as many other MTG collection manager apps failed to keep updating their databases over the years. <https://geo.itunes.apple.com/us/app/imtg/id412798013?mt=8&at=10l74t>
42,535,270
The title pretty much explains what I'm facing. I'm trying to test a `React` component that has some state, and I attempt to provide my store to the component in order to get what it needs. When I run the test of the component using Jest, I get the following error: `ReferenceError: regeneratorRuntime is not defined` I've determined through some reading that this is caused by `babel-polyfill` or `regenerator-runtime` not being applied correctly to Jest. However, I've tried installing both of those packages and re-running with no change in results. After reading the Jest Github issues page ([Remove auto-inclusion of babel-polyfill #2755](https://github.com/facebook/jest/pull/2755)), I found out that `babel-polyfill` is not included automatically by Jest as of version 19. My manual installation of that package should have fixed the issue, but it did not. I've included some of the files that I think are relevant `.babelrc`: ``` { "presets": ["es2015", "react", "stage-2"], "env": { "development": { "plugins": [ ["react-transform", { "transforms": [{ "transform": "react-transform-hmr", "imports": ["react"], "locals": ["module"] }] }] ] } } } ``` `jest.config`: ``` { "transform": { "^.+\\.(js|jsx)$": "<rootDir>/node_modules/webpack-babel-jest", ".*\\.(vue)$": "<rootDir>/node_modules/jest-vue-preprocessor", ".*": "babel-jest" }, "moduleNameMapper": { "\\.(jpg|jpeg|css|scss|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__tests__/__mocks__/fileMock.js", ".*\\.(vue)$": "vue/dist/vue.js" }, "testPathIgnorePatterns": ["type_parser.spec.js", "<rootDir>/__tests__/__mocks__/", "__tests__/unit/core/util/type_parser.js", "__tests__/GitlabLoader.test.js" ] } ``` `package.json`: ``` { "name": "my_project", "version": "0.2.0", "description": "My Project", "scripts": { "clean:build": "node ./bin/clean.js createdir", "build:html": "node ./bin/buildHtml.js", "deployProduction": "node ./bin/deployProduction.js", "start": "webpack-dev-server --config ./config/webpack.config.dev.js --hot --inline --progress", "serve": "npm run deployProduction&& supervisor --watch ./production-copy src/js/server", "prebuild": "npm run clean:build", "postbuild": "node ./bin/postBuild.js", "rebuild-win": "set BUILD_TYPE=preview& npm run prebuild & npm run build-win & npm run serve", "build": "set BUILD_TYPE=final& npm run prebuild & npm run build-win", "deploy": "npm run build & npm run serve", "build-win": "set NODE_ENV=production & npm run element-build & npm run build-doc & npm run build:html & webpack -p --config ./config/webpack.config.prod.js --json > webpack.log.json & npm run postbuild", "lint": "eslint config src/js/**/*.js", "jscs": "jscs src/js/", "test": "jest --no-cache --verbose --config=./__tests__/jest.config", "test:watch": "npm run test -- --watch", "element-init": "node node_modules/element-theme/bin/element-theme -i src/js/core/ui/element-theme.css", "element-build": "node node_modules/element-theme/bin/element-theme -c src/js/core/ui/element-theme.css -o src/js/core/ui/element-theme ", "build-doc": "node bin/buildDoc.js ", "storybook": "start-storybook -p 9001 -c .storybook" }, "repository": { "type": "git", "url": "my_url" }, "license": "MIT", "bugs": { "url": "my_url" }, "homepage": "my_homepage", "dependencies": { "autoprefixer": "^6.3.6", "axios": "^0.11.1", "babel-runtime": "^6.23.0", "babel-standalone": "^6.10.3", "bluebird": "^3.4.0", "brace": "^0.8.0", "browserify": "^13.0.1", "chai": "^3.5.0", "classnames": "2.2.3", "cls-bluebird": "^1.0.1", "codemirror": "^5.16.0", "connect-history-api-fallback": "^1.3.0", "continuation-local-storage": "^3.1.7", "dateformat": "^1.0.12", "diff": "^3.0.1", "element-theme": "^0.4.0", "element-ui": "^1.1.5", "express-history-api-fallback": "^2.0.0", "filedrop": "^2.0.0", "fs-extra": "^0.30.0", "history": "^2.0.2", "humps": "^1.0.0", "immutability-helper": "^2.1.1", "isomorphic-fetch": "^2.2.1", "json-loader": "^0.5.4", "jszip": "^3.0.0", "jszip-utils": "0.0.2", "material-ui": "^0.16.7", "materialize-css": "^0.97.6", "mocha": "^2.5.3", "moment": "^2.17.1", "normalizr": "^1.0.0", "raven-js": "^3.9.1", "react": "^15.0.1", "react-ace": "^3.5.0", "react-addons-update": "^15.4.2", "react-dom": "^15.0.1", "react-redux": "^4.4.5", "react-router": "^2.3.0", "react-router-redux": "^4.0.2", "redux": "^3.4.0", "redux-logger": "^2.6.1", "redux-saga": "^0.9.5", "request": "^2.72.0", "request-promise": "^3.0.0", "reselect": "^2.5.4", "save-as": "^0.1.7", "showdown": "^1.4.2", "three": "^0.79.0", "url-pattern": "^1.0.3", "vue": "^2.0.5", "vue-easy-slider": "^1.4.0", "vue-loader": "^9.8.1", "vue-router": "^2.0.1", "vue-slider-component": "^2.0.4", "walk": "^2.3.9" }, "devDependencies": { "@kadira/storybook": "^2.35.3", "babel-core": "^6.7.6", "babel-eslint": "^6.1.0", "babel-jest": "^18.0.0", "babel-loader": "^6.0.2", "babel-plugin-react-transform": "^2.0.2", "babel-polyfill": "^6.23.0", "babel-preset-es2015": "^6.22.0", "babel-preset-es2016": "^6.22.0", "babel-preset-react": "^6.23.0", "babel-preset-stage-2": "^6.5.0", "babel-register": "^6.7.2", "chai": "3.5.0", "chai-jquery": "2.0.0", "cheerio": "0.20.0", "colors": "1.1.2", "concurrently": "^2.0.0", "copy-webpack-plugin": "2.1.1", "css-loader": "0.23.1", "element-theme-default": "^1.1.5", "enzyme": "^2.7.1", "eslint": "^2.13.1", "eslint-config-airbnb": "^9.0.1", "eslint-plugin-import": "^2.2.0", "eslint-plugin-jsx-a11y": "^4.0.0", "eslint-plugin-react": "^5.2.2", "express": "^4.13.4", "extract-text-webpack-plugin": "1.0.1", "file-loader": "0.8.5", "identity-obj-proxy": "^3.0.0", "jest": "^19.0.2", "jest-cli": "^18.1.0", "jest-css-modules": "^1.1.0", "jest-enzyme": "^2.1.2", "jest-vue-preprocessor": "^0.1.2", "jquery": "2.2.3", "jscs": "3.0.3", "jsdoc-to-markdown": "^2.0.0", "jsdom": "8.4.0", "json-loader": "^0.5.4", "mocha": "^2.4.5", "ncp": "^2.0.0", "node-sass": "3.7.0", "postcss-loader": "0.8.2", "react-addons-test-utils": "^15.4.2", "react-hot-loader": "1.3.0", "react-test-renderer": "^15.4.2", "react-transform-hmr": "^1.0.4", "redux-devtools": "^3.3.1", "redux-devtools-dock-monitor": "^1.1.1", "redux-devtools-log-monitor": "^1.0.11", "regenerator-runtime": "^0.10.3", "remotedev": "^0.1.2", "rimraf": "^2.5.2", "sass-loader": "3.2.0", "storybook-addon-material-ui": "^0.7.6", "style-loader": "0.13.1", "url-loader": "0.5.7", "vueify": "^9.4.0", "webpack": "^1.13.0", "webpack-babel-jest": "^1.0.4", "webpack-dev-middleware": "^1.6.1", "webpack-dev-server": "^1.16.3", "webpack-hot-middleware": "^2.10.0" } } ```
2017/03/01
[ "https://Stackoverflow.com/questions/42535270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2593887/" ]
I am using Vuejs, Vue Jest in Laravel mix and this works for me ``` import 'regenerator-runtime/runtime' import { mount } from '@vue/test-utils' import App from '../App'; // eslint-disable-next-line no-undef test('it works', () => { // eslint-disable-next-line no-undef expect(1 + 1).toBe(2); }); // eslint-disable-next-line no-undef test('should mount without crashing', () => { const wrapper = mount(App); // eslint-disable-next-line no-undef expect(wrapper).toMatchSnapshot(); }); ```
Why --- According to the official Jest docs [`regenerator-runtime` is not longer injected](https://jestjs.io/blog/2019/01/25/jest-24-refreshing-polished-typescript-friendly#breaking-changes) automagically. > > Jest no longer automatically injects regenerator-runtime - if you get errors concerning it, make sure to configure Babel to properly transpile async functions, using e.g. @babel/preset-env. [Related PR](https://github.com/facebook/jest/pull/7595). > > > How --- Looking at the PR [a solution](https://github.com/facebook/jest/pull/7595#issuecomment-549859481) is available: Install `@babel/plugin-transform-runtime` as a dev dependancy ``` npm install --save-dev @babel/plugin-transform-runtime ``` Install `@babel/runtime` as a dependancy ``` npm install @babel/runtime ``` Then chuck this into your babel configuration (`babel.config.js`): ``` { "plugins": [ [ "@babel/plugin-transform-runtime", { "regenerator": true } ] ] } ```
31,642,449
If I draw a shape with polygon on Google Maps v2, is there a way to find out if my current location is inside the shape? please write me a clear code thanks
2015/07/26
[ "https://Stackoverflow.com/questions/31642449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4867171/" ]
I split the PolyUtil from the [Google Maps Android API Utility Library](https://github.com/googlemaps/android-maps-utils) to one class. Than just call like follow. ``` ArrayList<LatLng> polygon = new ArrayList<LatLng>(); LatLng myLocation = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()); boolean inPolygon = PolyUtil.containsLocation(myLocation, polygon, false); ``` And include the PolyUtil class in your code. ``` import static java.lang.Math.PI; import static java.lang.Math.log; import static java.lang.Math.sin; import static java.lang.Math.tan; import static java.lang.Math.toRadians; public class PolyUtil { /** * Returns tan(latitude-at-lng3) on the great circle (lat1, lng1) to (lat2, lng2). lng1==0. * See http://williams.best.vwh.net/avform.htm . */ private static double tanLatGC(double lat1, double lat2, double lng2, double lng3) { return (tan(lat1) * sin(lng2 - lng3) + tan(lat2) * sin(lng3)) / sin(lng2); } /** * Wraps the given value into the inclusive-exclusive interval between min and max. * @param n The value to wrap. * @param min The minimum. * @param max The maximum. */ static double wrap(double n, double min, double max) { return (n >= min && n < max) ? n : (mod(n - min, max - min) + min); } /** * Returns the non-negative remainder of x / m. * @param x The operand. * @param m The modulus. */ static double mod(double x, double m) { return ((x % m) + m) % m; } /** * Returns mercator Y corresponding to latitude. * See http://en.wikipedia.org/wiki/Mercator_projection . */ static double mercator(double lat) { return log(tan(lat * 0.5 + PI/4)); } /** * Returns mercator(latitude-at-lng3) on the Rhumb line (lat1, lng1) to (lat2, lng2). lng1==0. */ private static double mercatorLatRhumb(double lat1, double lat2, double lng2, double lng3) { return (mercator(lat1) * (lng2 - lng3) + mercator(lat2) * lng3) / lng2; } public static boolean containsLocation(LatLng point, List<LatLng> polygon, boolean geodesic) { return containsLocation(point.latitude, point.longitude, polygon, geodesic); } /** * Computes whether the given point lies inside the specified polygon. * The polygon is always considered closed, regardless of whether the last point equals * the first or not. * Inside is defined as not containing the South Pole -- the South Pole is always outside. * The polygon is formed of great circle segments if geodesic is true, and of rhumb * (loxodromic) segments otherwise. */ public static boolean containsLocation(double latitude, double longitude, List<LatLng> polygon, boolean geodesic) { final int size = polygon.size(); if (size == 0) { return false; } double lat3 = toRadians(latitude); double lng3 = toRadians(longitude); LatLng prev = polygon.get(size - 1); double lat1 = toRadians(prev.latitude); double lng1 = toRadians(prev.longitude); int nIntersect = 0; for (LatLng point2 : polygon) { double dLng3 = wrap(lng3 - lng1, -PI, PI); // Special case: point equal to vertex is inside. if (lat3 == lat1 && dLng3 == 0) { return true; } double lat2 = toRadians(point2.latitude); double lng2 = toRadians(point2.longitude); // Offset longitudes by -lng1. if (intersects(lat1, lat2, wrap(lng2 - lng1, -PI, PI), lat3, dLng3, geodesic)) { ++nIntersect; } lat1 = lat2; lng1 = lng2; } return (nIntersect & 1) != 0; } /** * Computes whether the vertical segment (lat3, lng3) to South Pole intersects the segment * (lat1, lng1) to (lat2, lng2). * Longitudes are offset by -lng1; the implicit lng1 becomes 0. */ private static boolean intersects(double lat1, double lat2, double lng2, double lat3, double lng3, boolean geodesic) { // Both ends on the same side of lng3. if ((lng3 >= 0 && lng3 >= lng2) || (lng3 < 0 && lng3 < lng2)) { return false; } // Point is South Pole. if (lat3 <= -PI/2) { return false; } // Any segment end is a pole. if (lat1 <= -PI/2 || lat2 <= -PI/2 || lat1 >= PI/2 || lat2 >= PI/2) { return false; } if (lng2 <= -PI) { return false; } double linearLat = (lat1 * (lng2 - lng3) + lat2 * lng3) / lng2; // Northern hemisphere and point under lat-lng line. if (lat1 >= 0 && lat2 >= 0 && lat3 < linearLat) { return false; } // Southern hemisphere and point above lat-lng line. if (lat1 <= 0 && lat2 <= 0 && lat3 >= linearLat) { return true; } // North Pole. if (lat3 >= PI/2) { return true; } // Compare lat3 with latitude on the GC/Rhumb segment corresponding to lng3. // Compare through a strictly-increasing function (tan() or mercator()) as convenient. return geodesic ? tan(lat3) >= tanLatGC(lat1, lat2, lng2, lng3) : mercator(lat3) >= mercatorLatRhumb(lat1, lat2, lng2, lng3); } } ```
Follow these - <https://developer.android.com/training/location/geofencing.html> <https://developers.google.com/android/reference/com/google/android/gms/location/Geofence> These links may be what you are looking for.
9,669,458
I just created my first Symfony2 project. But the "/web/app\_dev.php" part in the URL annoys me. It should be possible to do this *without* Virtual hosts... But when I try this through .htaccess I always get routing errors and the "web/" is always added to the url... EDIT: The whole project is also in a subdirectory named "symfonyTest". The Url to the demo page is "http://localhost/symfonyTest/web/app\_dev.php/demo/" and it should become "http://localhost/symfonyTest/demo/". Links should also have this syntax. Is this possible?
2012/03/12
[ "https://Stackoverflow.com/questions/9669458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/866447/" ]
Symfony2 comes with a built in debug mode, which is what you are using when you access url's with the app\_dev.php addition. The debug mode caches significantly less than the production mode which can be accessed by directing your browser to the url, but leaving out the app\_dev.php. If accessing this url doesn't work then it probably means that you need to clear your production cache. To clear the cache direct you terminal (command console) to the root of you Symfony project. From there type the following command: ``` php app/console cache:clear --env=prod --no-debug ``` Per comments below in Symfony 3 this has moved: ``` php bin/console cache:clear --env=prod --no-debug ``` This should clear your productions cache and allow you to access urls without the app\_dev.php. As for the web part of the url. The easiest way to remove that is to set the web root of your project to the web folder. It's best to do this with apache using virtual hosts, but there are ways to do it with the htaccess. This link explains how to use the htaccess file to change the webroot. [<http://kb.siteground.com/how_to_change_my_document_root_folder_using_an_htaccess_file/>](http://kb.siteground.com/how_to_change_my_document_root_folder_using_an_htaccess_file/) Hope this helps!
If you use an apache virtual host, you can get it working the way you desire. Here is an example virtual host from my xampp: ``` <VirtualHost *:80> ServerName myurl.local # Basic stuff DocumentRoot "C:/path/to/symfony/web" DirectoryIndex app.php <Directory "C:/path/to/symfony/web"> AllowOverride All Allow from All </Directory> </VirtualHost> ``` After restarting your apache, you can access the project through <http://myurl.local> (don't forget to configure your hosts file under `C:\Windows\system32\drivers\etc\hosts`!). If you want to have the dev environment (app\_dev.php) not showing up in the url, change the DirectoryIndex to app\_dev.php.
1,101,896
Is there a way to update the PDB file with the new source location ? I have a project which links to some libraries which are built on another machine and are debug build with the PDB file. I cannot put a breakpoint in the files which are compiled in the libs. These libs take more than 4 hours to build so I dont want to buid them on my machine. Is there a way where i can make the compiler use the new source paths. I am using VS 2005 pro c++. Thanks Amit
2009/07/09
[ "https://Stackoverflow.com/questions/1101896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90540/" ]
If you are doing this to avoid getting multiple links to the same content, you can simply don't use "register.php" anywhere on your page. I think no search engine will "guess" for a certain file type and if there are no security concerns you are on the safe side, because in my opinion no user will link to this file either. However if you want to be certain just reroute all your functionality through an index.php via one line in your .htaccess which should be placed inside your www-root directory: ``` RewriteEngine on RewriteRule ^(.*?)$ index.php?file=$1 ``` In your index.php you can then simply choose which function/file to invoke by breaking down and checking the $\_GET["file"] parameter. To make 100% certain no one can access your register.php file directly just move it (and all your others) to a separate directory and include a .htaccess file with the following line: ``` DENY from all ``` There are a couple of other options to prevent direct access. Just `define()` a variable somewhere in your index.php and at the top of your register.php just put ``` defined('access') or die('Intruder alert!'); ``` at the top. Another way could be to be honest and simply tell search engines that your content has been moved and that they no longer should use the old link: ``` header("Status: 301"); /* Content moved permanently */ header("Location: http://yourserver/Register/"); exit; ``` **Update** Just one more thing that crossed my mind, you can also check `$_SERVER["REQUEST_URI"]`, whether the user attached any ".php" and act accordingly by either denying access completely or just redirecting to the new location.
It is true that you cannot use location directive, but you can actually paste .htaccess file into any directory. Just if you put this into it, say: ``` Options -Indexes order allow,deny deny from all ``` you can copy paste this file into any (root) directory you want to protect from external execution.
17,257,041
I have a very simple JS Arrays question, my simple canvas game has been behaving differently when I replaced one block of code with another. Could you look them over and see why they are functionally different from one another, and maybe provide a suggestion? I may need these arrays to have 20+ items so I'm looking for a more condensed style. There's this one, which is short enough for me to work with, but doesn't run well: ``` var srd=new Array(1,1,1); var sw=new Array(0,0,0); var sang=new Array(0,0,0); var sHealth=new Array(20,20,20); ``` And then there's the original one, which is longer but works fine: ``` var srd = new Array(); srd[1] = 1; srd[2] = 1; srd[3] = 1; var sw = new Array(); sw[1] =0; sw[2] =0; sw[3] =0; var sang = new Array(); sang[1] = 0; sang[2] = 0; sang[3] = 0; var sHealth = new Array(); sHealth[1] = 20; sHealth[2] = 20; sHealth[3] = 20; ```
2013/06/23
[ "https://Stackoverflow.com/questions/17257041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Arrays are zero-indexed in JavaScript. The first element is `0`, not `1`: ``` var srd = new Array(); srd[0] = 1; srd[1] = 1; srd[2] = 1; ``` Also, you may want to use the more common array constructor: ``` var srd = [1, 1, 1]; ``` I have a feeling that you may be assuming that the first element is `1` instead of `0`, which is why the first version doesn't work while the second one does.
It depends on your implementation, but it's likely because of arrays being 0-indexed. In your first block of code, each number is offset by one index spot from the second block. The first one is equivalent to: ``` var srd = new Array(); srd[0] = 1; srd[1] = 1; srd[2] = 1; ``` in the way you wrote it for the second block.
514,312
It seems that changing secnumdepth does not change anything in my document for me. I want secnumdepth to be 2, so that I can label and reference subsections. However, subsection stay unnumbered for some reason, which has the consequence that when referencing these subsections, I get the section number instead. So if I were to reference subsection 1.1.2, I'd get section 1.1 instead. This is rather annoying, and I'm not quite sure what's going on. I've even tried changing secnumdepth to values ranging from 0 to 4, but even that does not change anything in my document. I do not receive any warnings or errors about this. My guess is that somewhere, a more dominant definition was made, but since my secnumdepth is defined at the bottom, that seems a bit unlikely. I'm using a template from my university, and I'd like to think that I understand it fully, but somewhere I apparently don't. ``` \documentclass[a4paper,10pt,oneside,openright]{memoir} \usepackage{pdfpages} \usepackage{fix-cm} \usepackage[breaklinks,pdfpagelabels]{hyperref} \usepackage[official]{eurosym} \usepackage{subfig} \usepackage[english]{babel} \usepackage{wrapfig} \usepackage{graphicx} \usepackage{amsmath} \usepackage{amssymb} \usepackage{units} \usepackage{amsmath} \usepackage[numbers,sort&compress]{natbib} \usepackage{todonotes} \usepackage{ctable} \usepackage{multirow} \usepackage{xfrac} \usepackage{easytable} \usepackage{gensymb} \setcounter{topnumber}{3} \setcounter{bottomnumber}{1} \setcounter{totalnumber}{4} \renewcommand{\topfraction}{0.8} \renewcommand{\bottomfraction}{0.8} \raggedbottom \settypeblocksize{*}{14cm}{1.618} \setlrmargins{3cm}{*}{*} \setulmargins{3cm}{*}{*} \checkandfixthelayout \definecolor{darkblue}{rgb}{0.0,0.0,0.3} \definecolor{darkgreen}{rgb}{0.0,0.3,0.0} \hypersetup{ colorlinks, % links are colored urlcolor=blue, % color of external links linkcolor=darkblue, % color of internal links citecolor=darkgreen, % color of links to bibliography bookmarksnumbered } \urlstyle{rm} \newcommand{\intd}[1]{\ensuremath{\,\textrm{d}#1}} \setcounter{tocdepth}{1} \setcounter{secnumdepth}{2} ``` I have also added my document assembly ``` \begin{document} \frontmatter \includepdf{frontpage} \include{abstract} \tableofcontents \mainmatter \include{chapters/Introduction} \include{chapters/Concept} \include{chapters/Digital} \include{chapters/Analog} \include{chapters/Results} \include{chapters/Discussion} \include{chapters/Conclusion} \backmatter \bibliographystyle{unsrtnat} \bibliography{icdtemplate} %requires mscthesis.bib file in your directory; use e.g. JabRef in combination with bibtex to generate it. \appendix \include{chapters/appendix1} \include{chapters/appendix2} \end{document} ```
2019/10/31
[ "https://tex.stackexchange.com/questions/514312", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/200471/" ]
The preferred method with `memoir` is to say ``` \settocdepth{section} \setsecnumdepth{subsection} ``` instead of setting the counters `tocdepth` and `secnumdepth`. If I do it and try with a skeleton document ```latex \begin{document} \frontmatter \tableofcontents \mainmatter \chapter{a} \section{b} \subsection{c} \subsubsection{d} \end{document} ``` and your very same preamble (but moving `hyperref` to be the last package loaded) I get [![enter image description here](https://i.stack.imgur.com/lqEsE.png)](https://i.stack.imgur.com/lqEsE.png) By the way, the definition of `\intd` should be ``` \newcommand{\intd}{\mathop{}\!\textrm{d}} ``` No need of `\ensuremath` nor of using arguments.
The following MWE works on my system. The packages commented out, I do not have available. It is obviously that you do something another place on your system. [![enter image description here](https://i.stack.imgur.com/b9gL7.png)](https://i.stack.imgur.com/b9gL7.png) ``` \documentclass[a4paper,10pt,oneside,openright]{memoir} \usepackage{pdfpages} \usepackage{fix-cm} \usepackage[breaklinks,pdfpagelabels]{hyperref} % Move this to be the last package loaded \usepackage[official]{eurosym} \usepackage{subfig} \usepackage[english]{babel} \usepackage{wrapfig} \usepackage{graphicx} \usepackage{amsmath} \usepackage{amssymb} \usepackage{units} %\usepackage{amsmath} \usepackage[numbers,sort&compress]{natbib} %\usepackage{todonotes} %\usepackage{ctable} \usepackage{multirow} \usepackage{xfrac} %\usepackage{easytable} %\usepackage{gensymb} \usepackage{xcolor} \setcounter{topnumber}{3} \setcounter{bottomnumber}{1} \setcounter{totalnumber}{4} \renewcommand{\topfraction}{0.8} \renewcommand{\bottomfraction}{0.8} \raggedbottom \settypeblocksize{*}{14cm}{1.618} \setlrmargins{3cm}{*}{*} \setulmargins{3cm}{*}{*} \checkandfixthelayout \definecolor{darkblue}{rgb}{0.0,0.0,0.3} \definecolor{darkgreen}{rgb}{0.0,0.3,0.0} \hypersetup{ colorlinks, % links are colored urlcolor=blue, % color of external links linkcolor=darkblue, % color of internal links citecolor=darkgreen, % color of links to bibliography bookmarksnumbered } \urlstyle{rm} \newcommand{\intd}[1]{\ensuremath{\,\textrm{d}#1}} \setcounter{tocdepth}{1} \setcounter{secnumdepth}{2} \begin{document} \part{1} \chapter{2} \section{3} \subsection{4} \end{document} ```
47,038,677
I am writing a SQL query using the AdventureWorks 2014 database. I want to show Which orders contain more than two products? Show order number, order value, and number of products that the order contains. I tried to write statement by itself (see below), but I'd like to be able to solve the relation : ``` select SalesOrderID , ProductID , LineTotal from Sales.SalesOrderDetail order by SalesOrderID ``` [![enter image description here](https://i.stack.imgur.com/iFphM.png)](https://i.stack.imgur.com/iFphM.png)
2017/10/31
[ "https://Stackoverflow.com/questions/47038677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8858893/" ]
``` SELECT SalesOrderID, COUNT(ProductID) as total_products, SUM(LineTotal) as total_invoice FROM SalesOrderDetail s GROUP BY SalesOrderID HAVING COUNT(ProductID) > 2 ORDER BY s.SalesOrderID ```
This code would give your expected answer ``` SELECT SalesOrderID ,ProductID ,LineTotal ,'Sales Order ' +CAST(SalesOrderID AS VARCHAR(100))+' Contains Productid of'+CAST(ProductID AS VARCHAR(100)) AS [ProductsCountPerOrder] ,Productscount FROM ( SELECT salesorderid , productid , linetotal , Count(productid)OVER(partition BY salesorderid ORDER BY salesorderid) AS productscount FROM sales.salesorderdetail )dt WHERE dt.productscount>2 ORDER BY salesorderid ```
43,576,211
I have a listview and created it with an arrayadpter but when i try to add data it shows empty rows for everytime ive tried to empty data, ive checked the database and the information is getting entered just never showing on the rows. Code Below: ``` public class Column_Adapter extends ArrayAdapter<Income>{ public LayoutInflater inflater; public ArrayList<Income> incomes; public int viewResource; public Column_Adapter(Context context, int textViewResourceId, ArrayList<Income> incomes){ super(context, textViewResourceId, incomes); this.incomes = incomes; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); viewResource = textViewResourceId; } public View getView(int position, View convertView, ViewGroup parent){ convertView = inflater.inflate(viewResource, null); Income income = incomes.get(position); if(income !=null) { TextView infoView = (TextView) convertView.findViewById(R.id.expense_type); TextView amountView = (TextView) convertView.findViewById(R.id.expense_amount); TextView budgetView = (TextView) convertView.findViewById(R.id.expense_budget); if (infoView != null) { infoView.setText(income.getiDate()); }if(amountView != null){ amountView.setText(income.getiAmount()); }if(budgetView != null){ budgetView.setText(income.getiMethod()); } } return convertView; } } ``` Layout template: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/expense_budget" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/eExpInc" android:layout_marginLeft="32dp" android:layout_marginStart="32dp" android:layout_alignBaseline="@+id/expense_amount" android:layout_alignBottom="@+id/expense_amount" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textSize="18sp" android:textStyle="bold" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <TextView android:id="@+id/expense_type" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/eDefaultType" android:layout_marginRight="52dp" android:layout_marginEnd="52dp" android:layout_alignBaseline="@+id/expense_amount" android:layout_alignBottom="@+id/expense_amount" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="@+id/expense_amount" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="51dp" android:text="@string/eDefaultAmount" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textSize="18sp" android:textStyle="bold" /> </RelativeLayout> ```
2017/04/23
[ "https://Stackoverflow.com/questions/43576211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7875040/" ]
You can only encode Unicode strings. If you call encode on a bytestring, Python tries to *decode* it first, using the default encoding - hence the error. (Note that this confusing behaviour only occurs in Python 2, it has been removed in Python 3).
Let me tear down your confusion to pieces. Let's start first by the the distinction between `str` and `unicode`. In Python 2.X: 1. `str` is a string of 8-bit characters (1-byte) that prints as ASCII whenever possible. `str` is really a sequence of bytes and is the equivalent of `bytes` in Python 3.X. \*There's no encoding for `str`. 2. `unicode` is a string of Unicode code-points. Second, encoding means according to [Python documentation](https://docs.python.org/2/howto/unicode.html#encodings): > > *"The rules for translating a Unicode string into a sequence of bytes are called an encoding."* > > > Then, ask yourself this question: does it makes sense to encode `str` which is already a sequence of bytes? The answer is no. Because `str` is already a sequence of bytes. It does make sense however to encode `unicode`, why? Because it's a string of Unicode character code-points (i.e, U+00E4').
44,403,165
I have a React component which contains some other components that depend on access to a Redux store etc., which cause issues when doing a full Enzyme mount. Let's say a structure like this: ```js import ComponentToMock from './ComponentToMock'; <ComponentToTest> ...some stuff <ComponentToMock testProp="This throws a warning" /> </ComponentToTest> ``` I want to use Jest's `.mock()` method to mock out the sub-component, so that it is not a concern for the test. I'm aware that I can mock out a straight component with something like: `jest.mock('./ComponentToMock', () => 'ComponentToMock');` However, as this component would normally receive props, React gets upset, giving a warning about unknown props (in this case, `testProp`) being passed to `<ComponentToMock />`. I've tried to return a function instead, however you can't return JSX (from what I could tell) in a Jest mock, due to it being hoisted. It throws an error in this case. So my question is how can I either a) get `ComponentToMock` to ignore props passed to it, or b) return a React component that can be used to mock the child component that I'm not worried about testing. Or... is there a better way?
2017/06/07
[ "https://Stackoverflow.com/questions/44403165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3422667/" ]
There's a note at the bottom of the [docs for `jest.mock()`](https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options) for preventing the hoisting behavior: > > Note: When using `babel-jest`, calls to `mock` will automatically be > hoisted to the top of the code block. Use `doMock` if you want to > explicitly avoid this behavior. > > > Then you can do as you described: return a function that is a stub of the component you don't need to test. ```js jest.doMock('./ComponentToMock', () => { const ComponentToMock = () => <div />; return ComponentToMock; }); const ComponentToTest = require('./ComponentToTest').default; ``` It's helpful to name the stub component since it gets rendered in snapshots.
``` const mockComponent = ComponentName => ({ children, ...props }) => ( <ComponentName {...{ '[mockComponent]': true }} {...props}> {children} </ComponentName> ); export default mockComponent; ``` ``` jest.mock('../ComponentToMock', () => { const mockComponent = require('./mockComponent').default; return mockComponent('ComponentToMock'); }); ```
113,898
Whether or not to reply inline in emails, is something to disagree on. When I write an email, I aim at producing a text with a beginning and an end, complete with greetings and other politeness forms. After all, if I meet a colleague at the coffee machine, I also greet politely before starting to discuss, and when leaving I greet again (said colleagues do the same). So why not do the same in email? Now, when a colleague responds inline in an email, I end up reading my own words mixed with their answer, completely destroying any line of reasoning in both my original mail and their response. I rather see that they respond in multiple paragraphs, at the beginning of each they concisely summarise their understanding of my point that they refer to. This serves a great purpose: at least I can verify if the first communication (from me to them) went without noise. Moreover, even though modern email readers attempt to give different colors to the old email text at different levels of indentation / quotation, inline answering produces an unreadable mess of voices and colours. As if we are all talking at the same time and interrupting each other at the same time. It happens to me often that I miss comments that colleagues injected into my email to them. Do not understand me wrong: this fashion of responding that I advocate does not at all have to produce very long emails. It can be as brief as: "Regarding your point about x, ...." Now, how do I raise my colleagues without pointing them to this very stackexchange question, which is too lengthy to attach to any email and which would be a very arrogant thing to write to begin with ("Let me teach you some manners, because I have the authority to do so.")?
2018/06/12
[ "https://workplace.stackexchange.com/questions/113898", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/88000/" ]
I can only speak about my own experience. You be the judge whether this applies to your colleagues. Personally, I don't usually reply inline, but when I do reply inline, it's because the email I am replying to is very long to begin with and I want to make sure I don't forget anything. So to encourage me not to reply inline, I would recommend you compose shorter emails, break up larger emails into multiple messages, reduce the number of recipients per email (when it makes sense to do so), and/or when you find yourself enumerating a list of things to talk about, I would recommend you use an online project management tool like [Asana](https://asana.com/) instead. When it comes to assigning tasks, reassigning tasks, forwarding tasks, requesting updates, and requesting approvals, using a tool like Asana should also help in reducing the number of back and forth emails, which should then reduce the number of levels in the nesting of replies. And along the same lines as KlaymenDK is suggesting, numbering your points or paragraphs should help too, but ultimately, you should also keep your points short if you want to mitigate against the overflowing of those points onto new lines when there is too much nesting.
This depends on the intent of the email. What are you looking for in return? I respond in-line when presented with a bulleted or numbered list in the email. In this case this it helps to keep each response with the particular line item in the list. I will do the same with paragraphs that each need a response. In these cases the response will be in a different color (red) and font to emphasize that this is a response instead of the original email. For all others, responding after the original text is the clearest (at least to me). Example: * List item * List item2 * List item3 Response (colors not working in chrome but you should get the idea): * List item *Blah, blah.* * List item2 *Blah, blah, blah.* * List item3 *Blah, blah, blah, blah, blah.*
52,696
We are making a simple [Likert scale](http://en.wikipedia.org/wiki/Likert_scale) radio group for feedback and will group it as follows: > > Please rate the service you received: > > > * Very poor > * Poor > * Average > * Good > * Very good > > > According to usability guru Jakob Neilsen, [radio choices should have one option selected as a default](http://www.nngroup.com/articles/checkboxes-vs-radio-buttons/). In a typical Likert scale like above, what would be the most appropriate to select as default? 'Average', as it is in the middle or 'Very good', which might appear presumptuous?
2014/02/21
[ "https://ux.stackexchange.com/questions/52696", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/43895/" ]
It is perfectly acceptable for a radio group not to have a default selection if you don't want to influence the user's response (such as in a survey). Microsoft provides this advice in its [design guidelines for radio buttons](http://msdn.microsoft.com/en-us/library/windows/desktop/aa511488.aspx): > > Don't have a default selection if...The goal is to collect unbiased > data. Default values would bias data collection. > > >
> > Select a single radio button by default in most cases. **Reasons to** > **deviate or not: expedite tasks, the power of suggestion, user** > **expectations, safety nets.** > > > Same source: <https://www.nngroup.com/articles/radio-buttons-default-selection/>
12,218,678
I need to sort a point array (a point is a struct with two `float` types - one for `x` and one for `y`) in a special fashion. The points have to be sorted so when they are traversed, they form a zig-zag pattern starting at the **top leftmost point**, moving to the **top rightmost point**, then down to the **second leftmost point**, to the **second rightmost point** and so on. ![Illustration](https://i.stack.imgur.com/otd4u.png) I need this to be able to convert arbitrary polygons to triangle strip arrays which I can then draw using GLes. **What would be the most efficient way of sorting those points**, by either using pointers (ie. passing and rearranging the pointers to the point structures) or by copying and moving the data in the structures directly?
2012/08/31
[ "https://Stackoverflow.com/questions/12218678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160868/" ]
I'd use qsort() with a custom compare() function that as @stefan noted, sorts descending by y then alternates (max/min) for x.
It seems you are trying to reinvent some kind of monotone polygonal chain. Some polygon triangulation methods are in short described in [wiki](http://en.wikipedia.org/wiki/Polygon_triangulation) and [here](http://vterrain.org/Implementation/Libs/triangulate.html) with links to code
6,367,379
``` int main() { int i=3; (i << 1); cout << i; //Prints 3 } ``` I expected to get 6 because of shifting left one bit. Why does it not work?
2011/06/16
[ "https://Stackoverflow.com/questions/6367379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796608/" ]
Because the bit shift operators return a value. You want this: ``` #include <iostream> int main() { int i = 3; i = i << 1; std::cout << i; } ``` The shift operators don't shift "in place". You might be thinking of the other version. If they did, like a lot of other C++ binary operators, then we'd have very bad things happen. ``` i <<= 1; int a = 3; int b = 2; a + b; // value thrown away a << b; // same as above ```
You need to reassign the value back to `i` with `i<<=1` (using "left shift and assign operator")
42,300,463
I'm trying to use the Flink 5.x Elasticsearch sink connector to insert data to ES 5.2.1 instance hosted on a tiny VM. As this is a tiny VM in development mode, I cant get it to start up to accept TransportClient remote client connections on 9300 without failing the bootstrap checks. ``` [2017-02-17T09:02:48,581][INFO ][o.e.n.Node ] [Z_fiBnl] starting ... [2017-02-17T09:02:48,866][INFO ][o.e.t.TransportService ] [Z_fiBnl] publish_address {xxxxxx:9300}, bound_addresses {127.0.0.1:9300} [2017-02-17T09:02:48,878][INFO ][o.e.b.BootstrapChecks ] [Z_fiBnl] bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks ERROR: bootstrap checks failed max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536] max number of threads [1024] for user [xxx] is too low, increase to at least [2048] max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144] system call filters failed to install; check the logs and fix your configuration or disable system call filters at your own risk ``` I've played around with the below settings but just cant get it to startup(http clients on 9200 work fine) ``` transport.publish_host: 0.0.0.0 transport.bind_host: 0.0.0.0 http.host: "xxx" http.host: 169.117.72.167 network.host: 0.0.0.0 network.publish_host: 0.0.0.0 ``` Note that ES is running on a tiny VM just for dev purposes and I don't have access to change for ex. the file descriptor limits on this box.
2017/02/17
[ "https://Stackoverflow.com/questions/42300463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581243/" ]
> > max file descriptors [4096] for elasticsearch process is too low, > increase to at least [65536] > > > ``` ulimit -n 65536 ``` or set `nofile` to `65536` in `/etc/security/limits.conf` > > max number of threads [1024] for user [xxx] is too low, increase to at > least [2048] > > > ``` ulimit -u 2048 ``` Or set the `nproc` value to `2048` or above in `/etc/security/limits.conf` before starting elasticsearch. > > max virtual memory areas vm.max\_map\_count [65530] is too low, increase > to at least [262144] > > > set `vm.max_map_count=262144` in `/etc/sysctl.conf` then do `sysctl -p` **If you want to run elasticsearch in development environment despite failing bootstrap checks:** Set the following in your `elasticsearch.yml` ``` transport.host: 127.0.0.1 http.host: 0.0.0.0 ``` Please note you cant form a cluster in development mode. **Dont use elasticsearch that is failing bootstrap checks in production!!**
Following steps helped us get started with ES 5.5.2. On Azure with 3 master, 3 client and 8 data nodes using Ubuntu servers 1. Ensure following configurations in "/etc/security/limits.conf" > > \*soft memlock unlimited > > > \*hard memlock unlimited > > > 2. ulimit -l unlimited 3. ulimit -n 65536 4. sudo sysctl -w vm.max\_map\_count=262144 5. Make sure that elasticsearch.yml has following configurations parameter > > transport.tcp.compress: true > > > transport.tcp.port: 9300 > > > **Note** We also had to stop "apparmor" service to fix connectivity issue between nodes.
60,216,204
When I tried to run my code on Eclipse IDE, this error keeps on poping up: ``` Error occurred during initialization of boot layer java.nio.file.InvalidPathException: Illegal char <?> at index 24: (path to project). ``` I don't know what this error meant. First, I thought it was some problem caused by some of my own code. But when I tried to run the Hello World program, the same problem existed. It isn't a problem with Java, because I reinstalled it and the same problem still happens(Plus, when I use the command line tools, the program compiled and ran perfectly fine). It is not that Java can't access my code from a different drive either(I kept my project on the D: drive, not the C: drive), because I moved my project to C:\Users\username\Documents\Eclipse Workspace and the problem still existed. I also tried reinstalling eclipse, but that didn't change anything. Can anyone tell me what is causing the problem?
2020/02/13
[ "https://Stackoverflow.com/questions/60216204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12494226/" ]
Not sure to understand your question. Why couldn't you use `aes_string()` and define a function like below ? ```r make.histogram <- function(variable) { p <- ggplot(my.data, aes_string(x = variable, fill = "type")) + (...) + xlab(variable) print(p) } ```
Since ggplot is part of the *tidyverse*, I think *tidyeval* will come in handy: ``` make.histogram <- function(var = "foo", bindwith = 0.01) { varName <- as.name(var) enquo_varName <- enquo(varName) ggplot(my.data, aes(x = !!enquo_varName, fill = type)) + ... labs(x = var) } ``` Basically, with `as.name()` we generate a name object that matches `var` (here var is a string like "foo"). Then, following [Programming with dplyr](https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html), we use `enquo()` to look at that name and return the associated value as a *quosure*. This quosure can then be unquoted inside the `ggplot()` call using `!!`.
70,919,047
I created a .Net 6 class library and now I am trying to create a test project. a .net 6 test project is not available. Online I found the information to use .Net Framework or .Net core in order to test. I created a .Net Framework 4.8 test project an referenced my class library. I receive the Compiler error: > > Project '..\CircularList\CircularList.csproj' targets 'net6.0'. It cannot be referenced by a project that targets '.NETFramework,Version=v4.8'. UnitTests > > > How do I do Unit tests then? Is there any way to target .Net 6.0 from .Net Framework 4.8?
2022/01/30
[ "https://Stackoverflow.com/questions/70919047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8695110/" ]
I created a NET 6.0 class library and received the same message. I went into properties, just to double check that my project and my test project were set the same and noticed that the Target OS was not set in my library. It was in my project, but not in my class library. Once I changed my class library "Target OS" - to be windows, the same as my project, the error messages went away.
This is A solution, not likely THE only solution: I also have a .NET 6.0 project that I would like to test. With the project template picker, I picked the C# NUnit Test for .NET Core. When advancing to next screen, there was a dropdown that allowed me to pick a Target framework. .NET 6.0 was the default option.
50,026,939
I am using php `mysqli_connect` for login to a MySQL database (all on localhost) ``` <?php //DEFINE ('DB_USER', 'user2'); //DEFINE ('DB_PASSWORD', 'pass2'); DEFINE ('DB_USER', 'user1'); DEFINE ('DB_PASSWORD', 'pass1'); DEFINE ('DB_HOST', '127.0.0.1'); DEFINE ('DB_NAME', 'dbname'); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); if(!$dbc){ die('error connecting to database'); } ?> ``` this is the mysql.user table: [![mysql.user table](https://i.stack.imgur.com/fyMXv.jpg)](https://i.stack.imgur.com/fyMXv.jpg) MySQL Server ini File: ``` [mysqld] # The default authentication plugin to be used when connecting to the server default_authentication_plugin=caching_sha2_password #default_authentication_plugin=mysql_native_password ``` with `caching_sha2_password` in the MySQL Server ini file, it's not possible at all to login with user1 or user2; > > error: mysqli\_connect(): The server requested authentication method unknown to the client [caching\_sha2\_password] in... > > > with `mysql_native_password` in the MySQL Server ini file, it's possible to login with user1, but with user2, same error; --- how can I login using `caching_sha2_password` on the mySql Server?
2018/04/25
[ "https://Stackoverflow.com/questions/50026939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3806340/" ]
If you're on Windows and it's not possible to use `caching_sha2_password` at all, you can do the following: 1. rerun the MySQL Installer 2. select "Reconfigure" next to MySQL Server (the top item) 3. click "Next" until you get to "Authentication Method" 4. change "Use Strong Password Encryption for Authentication (RECOMMENDED)" to "Use Legacy Authentication Method (Retain MySQL 5.X Compatibility) 5. click "Next" 6. enter your Root Account Password in Accounts and Roles, and click "Check" 7. click "Next" 8. keep clicking "Next" until you get to "Apply Configuration" 9. click "Execute" The Installer will make all the configuration changes needed for you.
I ran the following command `ALTER USER 'root' @ 'localhost' identified with mysql_native_password BY 'root123';` in the command line and finally restart MySQL in local services.
19,115,617
Within a Java EE 5 environment I have the problem to ensure the existence of some data written by another part before continue processing my own data. Historically (J2EE time), it was done by putting the data object to be processed into an internal JMS queue after waiting for e.g. 500ms via Thread.sleep. But this does not feel like the best way to handle that problem, so I have 2 questions: 1. Is there any problem with using the sleep method within an Java EE context? 2. What is a reasonable solution to delaying some processing within an Java EE 5 application? --- **Edit:** I should have mentioned, that my processing takes place while handling objects from a JMS queue via an MDB. And it may be the case, that the data for which I'm waiting never shows up, so there must be some sort of timeout, after which I can do some special processing with my data.
2013/10/01
[ "https://Stackoverflow.com/questions/19115617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/817543/" ]
I agree with @dkaustubh about timers and avoiding threads manipulation in JavaEE. Another possibility is to use JMS queue with delayed delivery. Although it is not a part of JavaEE API, most of messaging systems vendors supports it. [check here](http://java.dzone.com/articles/sending-delayed-jms-messages).
Use notifications and `Object#wait()` / `Object#notifyAll()` i.e. Multithreaded, the producer notifies the consumer.
27,677,793
Below worksheet code defines two functions. fun accepts a function parameter of type `Int => Int` and invokes the function with parameter value 2 `funParam` accepts an Int parameter and returns this parameter + 3. This is a contrived example so as gain an intuition of how functions are passed around when writing functional code. ``` object question { println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet def fun(f : Int => Int) = { f(2) } //> fun: (f: Int => Int)Int def funParam(param : Int) : Int = { param + 3 } //> funParam: (param: Int)Int fun(funParam) //> res0: Int = 5 } ``` Why can't I use something like : fun(funParam(3)) This causes compiler error : `type mismatch; found : Int required: Int => Int` Does this mean I cannot invoke function "fun" passing a variable into funParam ? This is what I attempt to achieve using fun(funParam(3)) , perhaps there is an way of achieving this ?
2014/12/28
[ "https://Stackoverflow.com/questions/27677793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470184/" ]
I had similar error and calling: npm cache clean Helped me solve it.
`npm` is telling you that you lack the permissions to modify permissions on the affected file. This is probably a race condition, several of which were fixed in the `npm@1.4` codebase. I will guess that the reason you see it on one disk and not the other is that the disks have different latency and read access times, causing non-reproducible behavior. You should upgrade to the current version of `npm` (and node, for that matter). If you are using a Debian-based distribution, you can follow the instructions here < <https://github.com/nodesource/distributions#usage-instructions> > `curl -sL https://deb.nodesource.com/setup | sudo bash - sudo apt-get install -y nodejs nodejs-legacy sudo npm -g install npm@latest` If that doesn't fix your problem, please let me know; for a quicker response, create an issue on the `npm` tracker <https://github.com/npm/npm/issues> and tag me ( @smikes ) in the issue.
184,734
Usually, in Ubuntu 10.04 Netbook, if I want to open a program, it usually goes from this: ![An arbitrary open program](https://i.stack.imgur.com/7zbtD.png) (An open program) to this: [Using a program launcher to launch another program http://a.yfrog.com/img251/3201/workspace2002thumb.png](http://a.yfrog.com/img251/3201/workspace2002thumb.png) (Opening another program using [Kupfer](http://kaizer.se/wiki/kupfer/)) to this: ![The other program launches and ends up on top of the current program](https://i.stack.imgur.com/GoZRG.png) How can I change the behavior so that after launching the program, the focus is set back to (and stays on) the original program, or in other words, make all new windows open in the background? I'm using Ubuntu 10.04 Netbook using Mutter, though this happened when using Metacity also.
2010/09/04
[ "https://superuser.com/questions/184734", "https://superuser.com", "https://superuser.com/users/23420/" ]
From the Ubuntu Software Center, install "Advanced Desktop Effects Settings (ccsm)". After the installation, a new menu item called "CompizConfig Settings Manager" will appear in the System->Preferences menu. Click on that and navigate to General->General Options->Focus and Raise Behaviour. Set the "Focus Prevention Level" to "High" or "Very High" to prevent new windows from opening in the foreground.
hi! Try this: ``` #!/bin/bash delay=0.5 while true; do windowId=`xdotool getwindowfocus` xdotool getwindowname $windowId xdotool windowactivate $windowId; sleep $delay; done ``` This script depends on you setting the "Focus prevention level" high enough so that new opened windows wont get the focus. It works on Ubuntu 10.04 and 12.04 at least, but should work anywhere... if it fails for you, say so and we can think together! This is an endless loop (break it with ctrl+c) that will "activate" the window that has focus (focus for keyboard input). So it will make the focused window "jump" to foreground each 0.5 seconds (you can lower or up the delay value to your needs/taste). So all new opened applications and windows will still open in the foreground but will be promptly hidden by the window that has focus! Just to make it clear, they will not open in the background but this script will provide almost the same effect. Almost because if you are very unlucky you can still click on the new opened window before the focused one be put to foreground, what will make the new window be the focused one... Lowering the delay will help prevent that but consume more cpu, I think less than 0.1 is not good, but you must test to see what works better for you... PS.: your xdotool version must support these commands: getwindowfocus, getwindowname, windowactivate
42,882,170
Hi I have a code that shows date + 5 days in DD.MM format Please help me to add current year to this code. DD.MM.YYYY Year also should be like day and month and not this way `+ "2017"` ``` <script> function get(dday) { var newdate = new Date(); newdate.setDate(newdate.getDate()+dday); return newdate.getDate() + "." + ''+['01','02','03','04','05','06','07','08','09','10','11','12'][newdate.getMonth()]; } </script> <span><script type="text/javascript">document.write(get(5));</script></span> ```
2017/03/19
[ "https://Stackoverflow.com/questions/42882170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6215911/" ]
SIGSEGV are not always thrown due to a root cause of memory access problems... Perl throws a 139 on Unix usually because of file I/O. You might have accidentally deleted your input files.
On Perl programmation RC 139 caused by "Out of memory" for me. Because there have been too much data in a variable (millions). I have done a segmentation manualy by release (undef) this variable regularly. This solved this.
37,513,660
This is my first time using Scala and ApacheSpark for a project. I'm trying to print the contents of an matrix when I run my code in the terminal, but nothing I try is working so far. Instead I only get this printed: ``` org.apache.spark.mllib.linalg.distributed.MatrixEntry;@71870da7 org.apache.spark.mllib.linalg.distributed.CoordinateMatrix@1dcca8d3 ``` I just using `println()` but when I use `collect()`, that doesn't give a good result either.
2016/05/29
[ "https://Stackoverflow.com/questions/37513660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5560818/" ]
Building on @zero323 's comment ( aside would you like to put an answer out there?): given an RDD[SomeType] you can call ``` rdd.collect() ``` or ``` rdd.take(k) ``` Then you can print out the results using normal toString() methods that depend on the type of the rdd contents. So if `SomeType` were a `List[Double]` then the ``` println(s"${rdd.collect().mkString(",")}") ``` would give you a single-line comma separated output of the results. As @zero323 another consideration is: "do you *really* want to print out the contents of your rdd?" More likely you might only want a summary - such as ``` println(s"Number of entries in RDD is ${rdd.count()}") ```
Iterate over the `rdd` like this, ``` rdd.foreach(println) ```
1,257,725
group box, flow layout panel, panel, split container,and tab control do not drag. I believe uninstalling resharper is when it started to happen. I've done a repair on visual studio. I've uninstalled and reinstalled. Any idea where I would look or what is wrong? When I click on the drag icon. the mouse snaps left to the resize handle, and does not let me drag.
2009/08/10
[ "https://Stackoverflow.com/questions/1257725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57883/" ]
I had the same issue and happened to stumble upon this solution ... If you have your table view controller (eg. `UISearchDisplayController`) nested in a Tab Bar or Navigation controller using Interface Builder, you need to set the "Nib Name" in the "Attributes Inspector" window. The Nib name will be the one that holds the table view and has the controller (eg. `UISearchDisplayController`) as the File's Owner.
Ok, I have found how to solve it. In my case, the problem was due to the fact that I was using a controller embedded within the UITabBarController as one of its managed tabs (i.e. as a child). Removing the controller from the UITabBarController, then adding an UINavigationController to the UITabBarController instead, and finally putting my controller as a child of the UINavigationController solved completely the issue. I do not understand why this is so (there is no related information in the documentation, as often happens); however, it now works like a charm. With kind regards.
1,764,647
Hiya i'm creating a web form and i want a user to be able to make certain selections and then add the selections to a text box or listbox. Basically i want them to be able to type someone name in a text box ... check some check boxes and for it up date either a text for or a list box with the result on button click... e.g. John Smith Check1 Check3 Check5 any help would be great .. thanks
2009/11/19
[ "https://Stackoverflow.com/questions/1764647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214753/" ]
Ensure that the security settings of the "C:/Program Files (x86)/Aspell" folder for the current user allow for modifying and writing. I had the same issue, and this cleared it right up.
> > "Ensure that the security settings of the "C:/Program Files (x86)/Aspell" folder for the current user allow for modifying and writing" > > > > > > > "I took the read only off of "C:/Program Files/Aspell" folder. [The error message remains]" > > > > > > > > > It's not a read-only problem, but permissions. In Security give "Users" "Full control" over the .prepl and .pws files.
29,898
From my understanding, when the money supply curve shifts to the right, interest rates go down, it follows that the price level decreases and the prices should go down? Thanks in advance.
2019/06/21
[ "https://economics.stackexchange.com/questions/29898", "https://economics.stackexchange.com", "https://economics.stackexchange.com/users/23493/" ]
Price levels are not necessarily linked to interest rates, especially real rates. Speaking strictly from an IS-LM standpoint, an expansionary monetary policy will increase the real money supply and depress interest rates, holding output constant. This will cause a rightward shift in the LM curve; holding money demand constant, the relative value of currency must fall. Speaking practically, lower rates reduce the hurdle rate for investments and thus promote asset inflation. Further, the lower rates will also find their way into consumer credit, increasing purchasing power among consumers and thus driving up prices of consumer goods. Mind that the former precedes the latter by a good couple years. Hope that answered your question.
More money chasing the same amount of goods causes prices to rise until all demand is satisfied at the higher price.
53,319,441
I have put together this section of code which does what it's supposed to do. The only problem is when I deselect the first checkbox the shopping cart box remains. I want the top box to be the master, so if that's not selected the program will display nothing. Here's what I have so far: ```js function shoppingcartFunction() { // Get the checkbox var checkBox = document.getElementById("myCheck"); // Get the output text var text = document.getElementById("text"); // If the checkbox is checked, display the output text if (checkBox.checked == true) { text.style.display = "block"; } else { text.style.display = "none"; } } function shoppingcart1Function() { // Get the checkbox var checkBox = document.getElementById("shopping_cart"); // Get the output text var text = document.getElementById("text1"); // If the checkbox is checked, display the output text if (checkBox.checked == true) { text.style.display = "block"; } else { text.style.display = "none"; } } ``` ```html Checkbox: <input type="checkbox" id="myCheck" onclick="shoppingcartFunction()"> <p id="text" style="display:none"><label for="sender_name">Shopping Cart: <input type="checkbox" id="shopping_cart" onclick="shoppingcart1Function()"> <br /><br /></p> <p id="text1" style="display:none"><label for="sender_name">Shopping Cart</label><br /> <input type="text" id="shopping_car" pattern="[A-Za-z]{ ,30}" maxlength="30" title="Max 30 characters" name="shopping_car" size="30" required>* <br /><br /></p> ```
2018/11/15
[ "https://Stackoverflow.com/questions/53319441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5743264/" ]
You can effectively simulate what you want in your `shoppingcartFunction()` by unchecking `#shopping_cart` and calling `shoppingcart1Function()` directly. ```js function shoppingcartFunction() { // Get the checkbox var checkBox = document.getElementById("myCheck"); // Get the output text var text = document.getElementById("text"); // If the checkbox is checked, display the output text if (checkBox.checked == true){ text.style.display = "block"; } else { document.getElementById("shopping_cart").checked= false; shoppingcart1Function(); text.style.display = "none"; } } function shoppingcart1Function() { // Get the checkbox var checkBox = document.getElementById("shopping_cart"); // Get the output text var text = document.getElementById("text1"); // If the checkbox is checked, display the output text if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } ``` ```html Checkbox: <input type="checkbox" id="myCheck" onclick="shoppingcartFunction()"> <p id="text" style="display:none"><label for="sender_name">Shopping Cart: <input type="checkbox" id="shopping_cart" onclick="shoppingcart1Function()"> <br /><br /></p> <p id="text1" style="display:none"><label for="sender_name">Shopping Cart</label><br /> <input type="text" id="shopping_car" pattern="[A-Za-z]{ ,30}" maxlength="30" title="Max 30 characters" name="shopping_car" size="30" required>* <br /><br /></p> ```
If I undestand you, you want to hide all what is inside the p with id="text1". So just get it with var text1 = document.getElementById("text1"); and set its display to "none" if the first checkbox is not checked, otherwise do nothing. ``` function shoppingcartFunction() { // Get the checkbox alert("The first"); var checkBox = document.getElementById("myCheck"); // Get the output text var text = document.getElementById("text"); var text1 = document.getElementById("text1"); // If the checkbox is checked, display the output text if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; text1.style.display = "none"; } } ``` But you will have a problem: if the user checks the first checkbox, and than the second (with id="shopping\_cart"), all what inside the p with id="text2" will be displayed. If now the user unchecks the first checkbox, the second one and all what is inside the p with id="text1" will be hide. If again the user checks the first checkbox, the second one will be diplayed and it is checked but the p with id="text1" will not be shown. To solve this second problem: ``` function shoppingcartFunction() { // Get the checkbox var checkBox = document.getElementById("myCheck"); // Get the output text var text = document.getElementById("text"); var text1 = document.getElementById("text1"); // If the checkbox is checked, display the output text if (checkBox.checked == true){ text.style.display = "block"; var checkBox = document.getElementById("shopping_cart"); if (checkBox.checked == true){ text1.style.display = "block"; } } else { text.style.display = "none"; text1.style.display = "none"; } } ```
3,050,984
I understand the fundamentals of algrebra, but have very limited knowledge of geometry and trigonometry. I wish to learn calculus at this point. Is it reasonable to begin learning calculus, and learn these other concepts as I encounter them rather than learning the prerequisites in the standard fixed progression (i.e. Algebra I -> Algebra 2 -> Geometry -> Trigonometry, etc)? How difficult will it be to learn these concepts without the prescribed linear progression?
2018/12/24
[ "https://math.stackexchange.com/questions/3050984", "https://math.stackexchange.com", "https://math.stackexchange.com/users/556557/" ]
> > How difficult will it be to learn these concepts without the prescribed linear progression? > > > It's not really a linear progression, not at all. All of these subjects actually deal with the same thing. Mathematics is all connected. Algebra (as it's defined by educators), geometry and trigonometry are taught separately because someone down the line thought it is the best way to teach. **It's not**. Those subjects just offer different methods/instruments to solve the same problems. However, you don't really need to know everything that's taught in geometry/trigonometry by heart. Mostly it's all just some particular theorems which are hardly ever used in practice. What you really need is to have a good grasp on the **connections** between all of these subjects. For example, all of these complicated trigonometric formulas are derived with the help of algebra together with a small set of rules, connecting $\sin$ and $\cos$. Any geometric problem is eventually reduced to an algebraic one, and any algebraic problem (for example, solving an equation) can be represented in geometric terms. Not to mention, that $\sin$ and $\cos$ are usually first defined through their geometric meaning. An example: the general solution for a cubic equation can be defined in radicals (with lots of square and cubic roots) or it can be defined in trigonometric form, which looks much neater. --- Now, in practice, if you want to study a new subject and are not sure about the prerequisites, just start learning (through textbooks or some other way) and see if you encounter some unclear concepts or methods you don't know. Then use the internet or the help of a tutor to see what you need to learn/remember to understand them. That's what I do when I need to solve an unfamiliar problem now that I am not longer a student: I just try and search for new methods if needed. It's a fine way to learn, but then again, I do have years of formal education behind me, which helps to recognize the connections I have mentioned.
Having a personal goal in mind very motivating, and backtracking to learn what you need for specific goals as they come up is *fantastic* way to learn... as long as you have the time for it. If you're in a hurry to get something done, though, it can be incredibly frustrating to interrupt your progress for long periods of time. If you're trying to keep up with your peers in calculus, it can be incredibly frustrating if you have stop, go back, and learn some basics while your peers are pushing forward. Then you have to rush to catch up. Nonetheless, I think goal-oriented learning is generally much more efficient. The benefit of having a broad base of basic knowledge in a wide variety of subjects is that you never have to backtrack too far. To answer your specific case: yes, you can learn the fundamentals of calculus without knowing too much about geometry or algebra. You *will* be at a disadvantage, mostly due to lack of practice on algebra and geometry problems, but it will be easier to work though that than to practice algebra and geometry first with no specific goals in mind.
6,796,492
Is it possible to temporarily redirect stdout/stderr in Python (i.e. for the duration of a method)? ### Edit: The problem with the current solutions (which I at first remembered but then forgot) is that they don't *redirect*; rather, they just replace the streams in their entirety. Hence, if a method has a ***local* copy** of one the variable for any reason (e.g. because the stream was passed as a parameter to something), it won't work. Any solutions?
2011/07/22
[ "https://Stackoverflow.com/questions/6796492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/541686/" ]
You can also put the redirection logic in a contextmanager. ``` import os import sys class RedirectStdStreams(object): def __init__(self, stdout=None, stderr=None): self._stdout = stdout or sys.stdout self._stderr = stderr or sys.stderr def __enter__(self): self.old_stdout, self.old_stderr = sys.stdout, sys.stderr self.old_stdout.flush(); self.old_stderr.flush() sys.stdout, sys.stderr = self._stdout, self._stderr def __exit__(self, exc_type, exc_value, traceback): self._stdout.flush(); self._stderr.flush() sys.stdout = self.old_stdout sys.stderr = self.old_stderr if __name__ == '__main__': devnull = open(os.devnull, 'w') print('Fubar') with RedirectStdStreams(stdout=devnull, stderr=devnull): print("You'll never see me") print("I'm back!") ```
We'll use the `PHP` syntax of [ob\_start](http://php.net/manual/en/function.ob-start.php) and [ob\_get\_contents](http://php.net/manual/en/function.ob-get-contents.php) functions in python3, and redirect the input into a file. The outputs are being stored in a file, any type of stream could be used as well. ``` from functools import partial output_buffer = None print_orig = print def ob_start(fname="print.txt"): global print global output_buffer print = partial(print_orig, file=output_buffer) output_buffer = open(fname, 'w') def ob_end(): global output_buffer close(output_buffer) print = print_orig def ob_get_contents(fname="print.txt"): return open(fname, 'r').read() ``` Usage: ``` print ("Hi John") ob_start() print ("Hi John") ob_end() print (ob_get_contents().replace("Hi", "Bye")) ``` Would print > > Hi John > Bye John > > >
1,406,632
Consider the following three points in $R^3$ : $P(−1, 1, 0), Q(1, 5, 6), R(3, −1, 4)$ Find the values of $x ∈ R$ for which $PR + x QR$ is perpendicular to $PR$. I was thinking that equating the dot product of those 2 vectors to $0$ might give the values. But this only gives one x value ($x=-3$) and I presume that there are more. Thoughts?
2015/08/23
[ "https://math.stackexchange.com/questions/1406632", "https://math.stackexchange.com", "https://math.stackexchange.com/users/260784/" ]
Translation is not a linear map, but can still be represented by a matrix by adding one new coordinate and setting it equal to$~1$. In your example you are dealing with a plane, so you have two coordinates $x,y$ say; you add a third coordinate $z$ and force it to be equal to$~1$. In other words you identify your (affine) plane with $P=\{\,(x,y,z)\in\Bbb R^3\mid z=1\,\}$. You are only interested in linear transformations of $\Bbb R^3$ that globally stabilise the plane $P$, which means that the last row of their matrices must be $(0~~0~~1)$. Now you can see that you can realise your translations respectively (rotation, reflection) maps that fix a chosen origin $O=(0,0,1)\in P$ by matrices of the form $$ A=\pmatrix{0&0&a\_1\\0&0&a\_2\\0&0&1} \text{ respectively } B=\pmatrix{b\_{1,1}&b\_{1,2}&0\\b\_{2,1}&b\_{2,2}&0\\0&0&1}, $$ whose action restricted to $P$ has the desired effect. Now composition of maps is given simply by matrix multiplication. Note that $A\cdot B$ and $B\cdot A$ differ in general, as expected.
I think the difficulty here is that translation by a fixed vector isn't a linear transformation. One way to see this is that a sum of translates isn't the translate of the sum. Thus not going to be able to cook up a matrix to get the job done.
25,280,064
I try to make simple dll project in Visual Studio 2013 like in <http://www.itcsolutions.eu/2009/12/10/how-to-create-a-dll-dynamic-link-library-in-c-as-visual-studio-2008-project/> But when i try to build solution it falls with an error: ``` error LNK1104: can not open file "D:\prj\dlltest1\Debug\dlltest1.lib" D:\prj\dlltest1\ConsoleApplication1\LINK ConsoleApplication1 ``` But dlltest1 is dll-project. Why there is an .lib file?
2014/08/13
[ "https://Stackoverflow.com/questions/25280064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312837/" ]
Updating for current state of things: **basarat**'s answer didn't work for me and it broke IAngularStatic typing in my app, but adding this to my global.d.ts fixed the custom angular extending function problem: ``` declare namespace angular { interface IAngularStatic { copyData:Function; } } ``` I derived the `declare module ng` to `declare namespace angular` change from Definitely Typed structure linked by **basarat**: <https://github.com/borisyankov/DefinitelyTyped/blob/master/angularjs/angular.d.ts#L9>
Since angular is a singleton instance, you can just do: ``` angular.executeAfterDigest = function(fn) { setTimeout(fn,0); } ``` When you call it, it is not guaranteed to execute after a digest. You would have to make sure that it is only called when `$scope.$$phase` is `$digest` or `$apply`. Basically, it will only work when you're in the angular world.
32,205,590
After installing laravel we get an error: > > Parse error: syntax error, unexpected T\_CLASS, expecting T\_STRING or T\_VARIABLE or '$' in C:\xampp\htdocs\laravel\public\index.php on line 50 > > >
2015/08/25
[ "https://Stackoverflow.com/questions/32205590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5264524/" ]
Laravel 5.1 uses the [`::class` property](http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.class) to get string representations of a fully qualified classname. The error you're seeing is caused by [this line](https://github.com/laravel/laravel/blob/8914be5fc864ebc6877be38ff3502997e0c62761/public/index.php#L52) ``` $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class); ``` This language feature has been introduced in PHP 5.5 which is a requirement of Laravel 5.1. Your installed PHP version is probably older than 5.5. Try to update your PHP binary. --- In case you are interested in why `::class` is used, take a look at [this answer](https://stackoverflow.com/a/30801452/1903366)
I was facing the same error but error was in app/User.php line 10. Actually, line 10 was ok but before line 10 I was missing some php syntax. After correct the php syntax error It was fixed. So you have to check C:\xampp\htdocs\laravel\public\index.php on line 49 carefully I am sure there is something wrong. Just try to correct. It will be fixed.
55,592,442
I have two arrays that I am trying to combine in GAS, arr2 is multidimensional. ``` arr1 = ["Diesel", "Solar", "Biomass"] arr2 = [ ["ABC", "Nigeria", "Diesel,Solar", 35], ["DEF", "Egypt", "Solar,Diesel", 50], ["GHI", "Ghana", "Biomass,Diesel", 70] ] ``` What I want to do is push the elements of arr1 into arr2 at index 3 in each row, so it looks like: ``` newArr = [ ["ABC", "Nigeria", "Diesel,Solar", "Diesel", 35], ["DEF", "Egypt", "Solar,Diesel", "Solar", 50], ["GHI", "Ghana", "Biomass,Diesel", "Biomass", 70] ] ``` I have tried to use .map over arr2 to .Splice each row but couldn't get it to work. Any help would be much appreciated!
2019/04/09
[ "https://Stackoverflow.com/questions/55592442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10289339/" ]
Using [`array.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) and [`array.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) **Syntax** > > `array.splice(start[, deleteCount[, item1[, item2[, ...]]]])` > > > ```js let arr1 = ["Diesel", "Solar", "Biomass"] let arr2 = [ ["ABC", "Nigeria", "Diesel,Solar", 35], ["DEF", "Egypt", "Solar,Diesel", 50], ["GHI", "Ghana", "Biomass,Diesel", 70] ] let newArr = arr2.map((v, i) => v.splice(3, 0, arr1[i]) && v) console.log(newArr) ```
Try using the following code ``` arr1 = ["Diesel", "Solar", "Biomass"] arr2 = [ ["ABC", "Nigeria", "Diesel,Solar", 35], ["DEF", "Egypt", "Solar,Diesel", 50], ["GHI", "Ghana", "Biomass,Diesel", 70] ] arr2.forEach((subArr, index) => {console.log(subArr.splice(3, 0, arr1[index]));}); console.log(arr2); ```
394,316
I want to write a script in Ruby to clean up some messed up keys in several copies of the same MySQL schema. I'd like to do something like SHOW CREATE TABLE, then look at what comes back and delete keys if they exist. I know in the Rails environment you can do this... ``` ActiveRecord::Base.connection.execute( some sql ) ``` But what you get back is a "Result" object. For this task I need a String so I can analyze it and act accordingly.
2008/12/26
[ "https://Stackoverflow.com/questions/394316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42595/" ]
If you don't want to use ActiveRecord an ORM may be a bit complicated for your usage right now), you can still use the ruby-mysql library or even better IMHO is to use the Ruby DBI/DBD library ([here](http://rubyforge.org/projects/ruby-dbi/)) which has DBD drivers for mysql & postgresql out-of-the-box. That way, you can issue straight SQL statements like this ``` require "dbi" require "dbi/dbrc" # == Configuration DB = "sympa" HOST = "saphir" cnt = 0 dup = 0 # == Crude option processing # list_name = ARGV.shift.to_s file = ARGV.shift.to_s db = DBI::DBRC.new(DB) DBI.connect(db.dsn + ":#{HOST}", db.user, db.password) do |dbh| date = Time.now.asctime if not list_name or list_name == "" then puts "List name is mandatory" exit 1 end req1 = <<-"EOR" insert into user_table (email_user,lang_user) values (?, ?) EOR ... req2 = <<-"EOR" insert into subscriber_table (user_subscriber, list_subscriber, visibility_subscriber, date_subscriber, reception_subscriber) values (?, ?, ?, NOW(), ?) EOR sth1 = dbh.prepare(req1) sth2 = dbh.prepare(req2) ... # # Insertion in user_table # begin sth1.execute(line, "en") cnt += 1 rescue DBI::DatabaseError => err $stderr.puts("DBI: #{err}") end ``` dbi/dbrc is a useful module that enables you to avoid putting login&password directly in the script. See [there](http://raa.ruby-lang.org/project/dbi-dbrc/).
There is probably a better way to do that programmatically, however if you really want to drive the interactive commands and parse the results, then [expect](http://expect.nist.gov/) may be more suitable. You could still kick off expect from your ruby script.
29,312,001
Background: I am in the process of integrating TypeScript into a Play Framework (2.2.6) and I am trying to use mumoshu's plugin to do so. Problem is, the plugin has problems when running "play dist" on a windows machine. I've forked the code from GitHub in order to make some modifications to the source so I can continue using the plugin. Question: I have a play framework plugin in the traditional source structure: ``` project/build.properties project/Build.scala project/plugins.sbt src/main/scala/TypeScriptPlugin src/main/scala/TypeScriptKeys.scala ...<other code> ``` I'd like to include this plugin into another project but I don't really know where to start and how to hookup the settings. From previous suggestions, I've been able to add the module to my project as follows: ``` // In project/Build.scala... object ApplicationBuild extends Build{ lazy val typeScriptModule = ProjectRef(file("../../../play2-typescript"), "play2-typescript") lazy val main = play.Project(<appName>, <appVersion>, <appDependencies>).settings(typescriptSettings: _*).dependsOn(typeScriptModule).aggregate(typeScriptModule) } ``` Where `typescriptSettings` is defined in the other project... I think, I'm still not 100% sure what typescriptSettings IS other than adding this settings call enabled the plugin to work. This worked fine originally when I had included the plugin in the `plugins.sbt` file and imported the package `com.github.mumoshu.play2.typescript.TypeScriptPlugin._` but now that I'm including the source and explicitly including the module, I can't just import the package... Or at least not the way I used to. I am still new to scala/sbt and I am having difficulty finding helpful resources online. Any help would be appreciated.
2015/03/27
[ "https://Stackoverflow.com/questions/29312001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612524/" ]
I used css for this, try if this help you. HTML: `<div id="chartist" class="chartist" data-x-axis="X axis label" data-y-axis="Y axis label"></div>` CSS: ``` [data-x-axis]::before { content: attr(data-x-axis); position: absolute; width: 100%; text-align: center; left: 0; bottom: 0; font-size: 11px; color: #777; } [data-y-axis]::after { content: attr(data-y-axis); position: absolute; top: 50%; left: -20px; font-size: 11px; color: #777; text-align: center; transform: rotate(-90deg)translateY(50%); } ```
Titles are currently (June 2015) not supported. The [issue for this](https://github.com/gionkunz/chartist-js/issues/27) suggests that the Chartist authors want you to label the graph outside of Chartist but does include a way to do this in your HTML though with some notable caveats.
17,932,734
If I have tests for simple functions, `fun1` and `fun2`, which need some arguments: ``` class TestOne(unittest.TestCase): def test_func1(self): a = 0 b = 1 c = 2 self.assertEquals(c, fun1(a,b)) def test_fun2(self): d = 0 e = 1 f = 2 self.assertEquals(f, fun2(d,e)) ``` and a test for a third function, which need the output of fun1 and fun2 as input ``` class TestTwo(unittest.TestCase): def test_fun3(self): a = 0 b = 1 d = 0 e = 1 g = 3 self.assertEquals(g, fun3(fun1(a,b), fun2(d,e))) ``` what is the best way to avoid having to re-write the arguments of the first functions?
2013/07/29
[ "https://Stackoverflow.com/questions/17932734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348081/" ]
You have a few of options: 1. I'm adding this one at the top as every other answer seems to want to use inheritance. If this is the case and you only want to set up the values before each test section (versus each test with `setUp`), use `setUpClass`: ``` from unittest import TestCase class BaseTest(TestCase): def setUpClass(cls): cls.a = 0 cls.b = 1 cls.c = 2 class TestOne(BaseTest): def test_func1(self): self.assertEquals(self.c, func1(self.a, self.b)) ``` 2. Use `setUp`. This is probably not the best solution if you're going to be changing the parameters often. But you can also define the setup in a base class and use inheritance (as others have suggested) . ``` from unittest import TestCase class TestingSomething(TestCase): def setUp(self): self.parameters = [(0, 1), ] def test_func1(self): params = self.parameters[0] res = func1(*params) self.assertEquals(2, res) ``` 3. Define helper functions. ``` from unittest import TestCase class TestingSomething(TestCase): def param_set_one(self): return (0, 1), 2 def test_func1(self): params, expected = self.param_set_one() res = self.obj.func1(*params) self.assertEquals(expected, res) ``` 4. Perhaps a more specific answer to your question could be use use a more specific helper function: ``` from unittest import TestCase class TestingSomething(TestCase): def setUp(self): self.obj = TestOne() def param_set(self): return (0, 1) def get_func1(self): return self.obj.func1(*self.param_set()) def get_func2(self): return self.obj.func2(*self.param_set()) def test_func1(self): params = self.param_set() res = self.obj.func1(*params) self.assertEquals(2, res) [...] def test_func3(self): retval_func1 = self.get_func1_retval() retval_func2 = self.get_func2_retval() self.assertEqual(3, func3(retval_func1, retval_func2)) ``` If you want your tests to be in separate classes, just declare the helper function outside of your test cases.
I believe you can also create another class. I've seen this done, but I haven't actually done it before. If people know that this works, please leave a comment :) while I test it out myself: ``` class Tests(unittest.TestCase): def __init__(self): self.a = 0 self.b = 1 self.c = 2 class TestOne(Tests): def test_func1(self): self.a self.b self.c class TestTwo(Tests): def test_fun3(self): self.a self.b self.c ``` UPDATE: By changing self.a~c in class Tests(), test\_func1 & test\_func3 in TestOne & TestTwo print out appropriate values.
37,877,643
I have a `ViewPager` inside a `FragmentActivity`. For each page I have a `Fragment` with an `EditText`. I want to prevent the user leaving the screen if the `EditText` value has changed, showing a warning `Dialog` asking if he/she really wants to leave the screen. For that I need to check the `EditText` value when the back `Button` is pressed. I have only found how to do it but using the `onBackPressed()` method in the container `FragmentActivity`. The problem is that I don't know how to access the `EditText` inside the `Fragment` from the parent `FragmentActivity`. Is it not possible just to do it in the `Fragment`? I've tried the method `onStop` and `onDetach` but they are called after leaving the `Fragment`, so I cannot stop it. Any ideas?
2016/06/17
[ "https://Stackoverflow.com/questions/37877643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274847/" ]
Try this in your `parent Activity`: ``` @Override public void onBackPressed() { super.onBackPressed(); YourFragment fragment = (YourFragment) getSupportFragmentManager().getFragments().get(viewPager.getCurrentItem()); } ``` Then you have access to your `Fragment` so you can add a parameter in your fragment `textHasChanged` (for example) and update it when the text changes.
You could create a Boolean value in the FragmentActivity and keep it updated with the EditText updated. In this way you can check the String value instead the EditText (In fact the fragment could not be loaded in the Pager). For example: 1) create an interface in order to declare the input protocol ``` public interface InputInterface { void setEditTextNotEmpty(Boolean notEmpty); } ``` 2) implement this interface in your FragmentActivity ``` public class MainActivity implements InputInterface { private Boolean editTextNotEmpty; ... @Override void setEditTextNotEmpty(Boolean changed){ editTextNotEmpty=changed; } @Override public void onBackPressed() { ... your custom code.... } ``` 3) You somehow notify the Fragment when it's visualized as for in this post: [How to determine when Fragment becomes visible in ViewPager](https://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in-viewpager) When the fragment is visualized, you update the activity boolean if necessary. 4) keep your MainActivity updated when you update the edit text: ``` yourEditText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { if (getActivity instanceof InputInterface){ Boolean notEmpty = !TextUtils.isEmpty(s.toString); ((InputInterface)getActivity).setEditTextNotEmpty(notEmpty); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) {} }); ``` I hope it helped.
19,456,404
``` (define (myminus x y) (cond ((zero? y) x) (else (sub1 (myminus x (sub1 y)))))) (define (myminus_v2 x y) (cond ((zero? y) x) (else (myminus_v2 (sub1 x) (sub1 y))))) ``` Please comment on the differences between these functions in terms of how much memory is required on the stack for each recursive call. Also, which version might you expect to be faster, and why? Thanks!
2013/10/18
[ "https://Stackoverflow.com/questions/19456404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2253489/" ]
They should both have a number of steps proportional to y. The second one is a tail call meaning the interpreter can do a tail elimination meaning it takes up a constant space on the stack whereas in the first the size of the stack is proportional to Y.
`myminus` creates `y` continuations to `sub1` what the recursion evaluates to. This means you can exhaust rackets memory limit making the program fail. In my trials even as little as 10 million will not succeed with the standard 128MB limit in *DrRacket*. `myminus_v2` is `tail recursive` and since `racket` have same properties as what `scheme` requires, that tail calls are to be optimized to a goto and not grow the stack, y can be any size, i.e. only your available memory and processing power is the limit to the size. Your procedures are fine examples of [peano arithmetic](http://en.wikipedia.org/wiki/Peano_arithmetic).
27,245
**Mark 15:25, 18 KJV** > > And it was the **third hour**, and they crucified him. > > > and > > And began to salute him, Hail, King of the Jews! > > > **John 19:14-16 KJV** > > And it was the preparation of the passover, and about the **sixth hour**: and he saith unto the Jews, Behold your King! > But they cried out, Away with him, away with him, crucify him. Pilate saith unto them, Shall I crucify your King? The chief priests answered, We have no king but Caesar. > Then delivered he him therefore unto them to be crucified. And they took Jesus, and led him away. > > > How can Jesus be crucified on the 3rd hour but Pilate asked for his crucification at the 6th hour?
2014/04/09
[ "https://christianity.stackexchange.com/questions/27245", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/4277/" ]
Saint Augustine gives an explication of this in his *De consensu evangelistarum* (3, 13). > > If Jesus was given up to the Jews to be crucified, when Pilate sat down at his tribunal about the sixth hour, as John relates, how could He be crucified at the third hour, as many persons have thought from not understanding the words of Mark. > > > First then let us see at what hour He might have been crucified, then we shall see why Mark said that He was crucified at the third hour. > > > *De consensu evangelistarum (3, 13)* > > > The hour of the Crucifixion =========================== > > It was about the sixth hour when He was given up to be crucified by Pilate sitting on his judgment seat, as has been said, for it was not yet fully the sixth hour, but about the sixth, that is, the fifth was over, and some of the sixth had begun, so that those things which are related to the crucifixion of our Lord took place after the finishing of the fifth, and at the commencement of the sixth, until, when the sixth was completed and He was hanging on the cross, the darkness which is spoken of took place. > > > *De consensu evangelistarum (3, 13)* > > > Why Mark says “*It was the third hour*” ======================================= > > Let us now consider, why Mark has said, "*It was the third hour.*" > > > He had already said positively, "*And when they had crucified Him, they parted His garments;*" as also the others declare, that when He was crucified His garments were divided. Now if Mark had wished to fix the time of what was done, it would have been enough to say, "*And it was the third hour,*" why did He add, "*and they crucified Him,*" unless it was that he wished to point to something which had gone before, and which if enquired into would be explained, since that same Scripture was to be read at a time, when it was known to the whole Church at what hour our Lord was crucified, by which means any error might be taken away, and any falsehood be refuted. > > > But because he knew that the Lord was fixed to the cross not by the Jews but by the soldiers, as John very plainly shews, he wished to intimate that the Jews had crucified Him, since they cried out, "*Crucify Him,*" rather than those who executed the orders of their chief according to their duty. It is therefore implied, that it took place at the third hour when the Jews cried out, "*Crucify Him,*" and it is most truly shewn that they crucified Him, when they so cried out. **But in the attempt of Pilate to save the Lord, and the tumultuous opposition of the Jews, we understand that a space of two hours was consumed, and that the sixth hour had begun, before the end of which, those things occurred which are related to have taken place from the time when Pilate gave up the Lord, and the darkness overspread the earth.** > > > Now he who will apply himself to these things, without the hard-heartedness of impiety, will see that Mark has fitly placed it at the third hour, in the same place as the deed of the soldiers who were the executors of it is related. Therefore lest any one should transfer in his thoughts so great a crime from the Jews to the soldiers, he says "it was the third hour, and they crucified Him," that the fault might rather by a careful enquirer be charged to them, who, as he would find, had at the third hour cried out for His crucifixion, whilst at the same time it would be seen that what was done by the soldiers was done at the sixth hour. > > > *De consensu evangelistarum (3, 13)* > > > **TL;DR**: > > Therefore he wishes to imply that is was the Jews who passed sentence concerning the crucifixion of Christ at the third hour; for every condemned person is considered as dead, from the moment that sentence is passed upon him. Mark therefore shewed that our Saviour was not crucified by the sentence of the judge, because it is difficult to prove the innocence of a man so condemned. > > > *De quæst. Nov. et Vet. Testam (chap. 65)* > > > --- **Source**: *[Catena Aurea](http://dhspriory.org/thomas/CAMark.htm)* of Saint Thomas Aquinas
Mark (15:25) said that Jesus was crucified in the third hour. John (19:14), on the other hand, said that it was in the sixth hour it happened. We have here what looks like a contradiction. However, it is more a paradox than a contradiction, because there seems to be a logical explanation to this dilemma. According to [Wikipedia](https://en.wikipedia.org/wiki/History_of_timekeeping_devices), people of the ancient world used stationary sundial clocks, or other clumsy devices, like water clocks, to determine time. We have to assume that this was also the case in Jerusalem, in Jesus' time; and that 'out & about' people simply used rough estimation in time-telling. Mark's third hour (9am) would then mean anything between 7.30 and 10.30, and John's sixth hour (noon) anything between 10.30 and 1.30. As also Clami219 pointed out, another important piece in the puzzle seems to be the word "about" in John's time statement. The Easy-to-Read Version and the Good News Translation also interpreted the original Greek word "ωσεί" (Strong's) to mean "almost" instead of "about". According to Oxford Advanced Learner's Dictionary, in timekeeping the word "almost" means that an event has not yet happened (p.31), while the word "about" means "near", either before or after a stated point in time (p.3). Accordingly, John's statement "it was about the sixth hour" is in some christologians' minds better read: "it was almost the sixth hour". If so, then John's accuracy window slips back a bit, say an hour, to become 9.30 - 12.30 instead of 10.30 - 1.30 Consequently, the answer to the question: "At what time of the day was Jesus crucified?" is, I believe, to be found somewhere in the convergence of Mark and John's accuracy windows, which would be sometime between 9.30 and 10.30 in the morning.
39,979,183
Relatively new to Sitecore. I've searched this one out pretty thoroughly here and on dev.sitecore.net, and haven't seen where these subjects overlap... We've got a web forms for marketers form in production. We use content delivery servers, so the file uploaded via this form saves the image file that is uploaded to "web", and that's the only location. The problem comes that if we publish that folder from master (or any parent folder) because uploaded items aren't in master, the all get wiped out, and we need to maintain these moving forward. Publishing restrictions, making the folder unpublishable, from what I understand (and have seen testing) means the same thing... a full site publish (which we want to be able to do) will wipe out these files because either the files aren't in the folder, and are lost, or the folder isn't published, which also deletes them. What's the best way to handle data like this moving forward? I'd love a simple solution like being able to simply prevent the publish from touching that folder, but not removing it from web... otherwise, is there a way to adjust that file upload to go outside of the media library? As of right now, if I select the file upload field in the form designer, I can only select where within the media library folder I can save it... it would be nice if we could select a location maybe in another database? Is there a sitecore way to do this, short of hijacking the entire process and rewriting it through the c# backend? And if that's the best approach, where's a good spot to start digging into where that process can be captured?
2016/10/11
[ "https://Stackoverflow.com/questions/39979183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2880381/" ]
The issue is not user generated content, but the configuration of the WFFM module. When installing WFFM on the CD servers you need to configure the `remoteWfmService` connection string to point to the WFFM Remote Service on the CM server. This ensures that any actions are run on the CM server, and therefore any files which are uploaded or content which is generated is done so in the `master` database. Any publish of content (user generated or otherwise) will then get published out to the CD server/web database as normal then. This also has the advantage that should you wish to delete something (e.g. a user comment) you can do so from the CM server and publish again. To configure the remote service at the following connection string: ``` <add name="remoteWfmService" connectionString="url=http://[masterserver]/sitecore%20modules/shell/Web%20Forms%20for%20Marketers/Staging/WfmService.asmx;user=[domain\username];password=[password];timeout=60000" /> ``` If you have the `wfm` connection string defined then you can remove this. You also need to make sure that your `Save Actions` **do not have** the `Client Action` checkbox ticked, otherwise the action will run on the CD server, not the CM server. You can find more details in the *Multi-server Environment* section (page 37) of the [Webforms for Marketers Reference](https://sdn.sitecore.net/upload/sdn5/products/web_forms2/2_4/web%20forms%20for%20marketers%20v2_4%20reference-a4.pdf).
There is no one good answer to your question. What in fact your question is about is how to store `User generated content`. There are plenty of articles and discussions about it available online already. Check e.g. <https://www.google.com/search?q=user+generated+content+sitecore> You may see from the articles that there are many approaches you can use to achieve what you want. You just need to select one which will match your expectations and requirements in the best way.
6,046,350
I have the following code: ``` lblMetaTag.Text = "<meta property='" + ctrl.property_name + "' content='" + ctrl.property_value + "' />"; ``` When it renders to the page - it renders the meta tag and not the string representation. How do I display it as the string?
2011/05/18
[ "https://Stackoverflow.com/questions/6046350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/185961/" ]
Change it to the following: ``` lblMetaTag.Text = "&lt ;meta property='" + ctrl.property_name + "' content='" + ctrl.property_value + "' /&gt ;"; ```
Use HTML encoding before sending putting it on your page.
7,796,010
Here is written how to set the name of a form with a class: <http://symfony.com/doc/2.0/book/forms.html#creating-form-classes> but how to set the name of this form? ``` $form = $this->createFormBuilder($defaultData) ->add('name', 'text') ->add('email', 'email') ->getForm(); ``` Well, I'm trying to get post parameters after submitting it this way: ``` $postData = $request->request->get('form_name'); ```
2011/10/17
[ "https://Stackoverflow.com/questions/7796010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248959/" ]
There is no shortcut method for this purpose. Instead you have to access the method `createNamedBuilder` in the form factory: ``` $this->get('form.factory')->createNamedBuilder('form', 'form_name', $defaultData) ->add('name', 'text') ->add('email', 'email') ->getForm(); ```
In version 2.4.1 of Symfony, the solution is: ``` $form = $this->createFormBuilder ( NULL, array ( 'attr' => array ( 'name' => 'myFormName', 'id' => 'myFormId' ) ) ) ->add (.. ``` You can also set other form attributes this way, but I've not tried. Replace NULL with your data if you want.
56,034,177
I am trying to test my Tour of Heroes Angular application using ***mocha***, ***chai*** & ***webpack***. I have followed [this post](https://hichambi.github.io/2016/12/27/testing-angular2-with-webpack-mocha-on-browser-and-node.html) & also with the help of [this guide](https://www.radzen.com/blog/testing-angular-webpack-mocha/), have gone through the setup and got the build errors fixed and tests up and running. But, my tests fails except for the test case where i don't use the `async()` in the `beforeEach` hook. ### Passing Test ```js beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [HeroService, MessageService] }); httpTestingController = TestBed.get(HttpTestingController); let mockHeroes = [...mockData]; let mockHero = mockHeroes[0]; // let mockId = mockHero.id; heroService = TestBed.get(HeroService); }); afterEach(() => { httpTestingController.verify(); }); it('is created', () => { expect(heroService).to.exist; }); ``` --- ### Failing Test ```js //imports import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { DashboardComponent } from './dashboard.component'; import { HeroSearchComponent } from '../hero-search/hero-search.component'; import { RouterTestingModule } from '@angular/router/testing'; import { HeroService } from '../hero.service'; import { expect } from 'chai'; ... beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [DashboardComponent, HeroSearchComponent], imports: [RouterTestingModule.withRoutes([])], providers: [{ provide: HeroService, useValue: heroService }] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DashboardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).to.exist; }); ``` --- ### Error Stack Trace > > 1) DashboardComponent > > > > > > > > > ``` > > "before each" hook for "should be created": > > Error: Expected to be running in 'ProxyZone', but it was not found. > > at Function.ProxyZoneSpec.assertPresent (node_modules\zone.js\dist\proxy.js:42:19) > > at runInTestZone (node_modules\zone.js\dist\async-test.js:202:23) > > at D:\Practice\Tour-Of-Heroes\node_modules\zone.js\dist\async-test.js:185:17 > > at new ZoneAwarePromise (node_modules\zone.js\dist\zone-node.js:910:29) > > at Context.<anonymous> (node_modules\zone.js\dist\async-test.js:184:20) > > > > ``` > > > > > > > I have tried [Angular 5 Testing: Expected to be running in 'ProxyZone', but it was not found](https://stackoverflow.com/q/48789782/8947616) as I thought this was some error with *zone.js* using ***mocha***, but without success. Also, I have tried following [Mocha Documentation](https://mochajs.org/#asynchronous-code) for asynchronous testing, but as a beginner, it was somewhat hard for me. I have tried googling and even in **stack-overflow**, but there are only a limited amount of posts regarding ***Angular testing*** with ***mocha***. Any help getting through this is appreciated.
2019/05/08
[ "https://Stackoverflow.com/questions/56034177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8947616/" ]
2021 Adding the line below as first import to the spec file fixed this problem for me: ``` import 'zone.js/dist/zone-testing'; ```
I see a few issues here. You have 2 beforeEach. You should only have 1. If you have async on your block of test code, then you need to call await on a function, and/or use flush or tick to progress time. I usually use fakeAsync for observables, and async/await for real async methods. For this specific example, you shouldn't need the async at all.
32,655,076
I need to parse some markup similar to this one, from an html page: ``` <div id="list"> <div class="item-level-a"> <div class="item-level-b"> <a href="http://www.example.com/1"></a> </div> </div> <div class="item-level-a"> <div class="item-level-b"> <a href="http://www.example.com/2"></a> </div> </div> <div class="item-level-a"> <div class="item-level-b"> <a href="http://www.example.com/3"></a> </div> </div> </div> ``` I did try with this code: ``` $list = []; $('div[id="list"]').each(function() { var href = $(this).find('div > div > a').attribs('href'); list.push(href); }); ``` without success: error was: ``` TypeError: Object <a href="http://www.example.com/1"></a> <a href="http://www.example.com/2"></a> <a href="http://www.example.com/3"></a> has no method 'attribs' ``` :-(. Any clue?
2015/09/18
[ "https://Stackoverflow.com/questions/32655076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/709439/" ]
In `cheerio` and `jquery`, you get attributes with `attr()`, not `attrib()`. There are a few other problems with your code. Here is a working version using `cheerio`. It probably works in `jquery` this way as well.: ``` var list = []; $('div[id="list"]').find('div > div > a').each(function (index, element) { list.push($(element).attr('href')); }); console.dir(list); ```
For those who prefer a functional style: ```js const list = $('div[id="list"]') .find('div > div > a') .toArray() .map(element => $(element).attr('href'))); ```
4,655,968
We are trying to load a flash file in a browser from local machine its loading only in Internet Explorer (IE) but not in other browsers. Please suggest me some solution.
2011/01/11
[ "https://Stackoverflow.com/questions/4655968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/571029/" ]
It is rare in C++ certainly. In C it may well show up where: * You use "objects" which are structs, and you always pass them around or create them on the heap as pointers. * You have collections of such pointers as dynamically allocated arrays thus T\*\* where T is the type. * You want to get an array so you pass in a T\*\*\* and it populates your pointer with a T\*\* (array of T\* pointers). This would be valid C but in C++: * The first step would be the same. You still allocate the objects on the heap and have pointers to them. * The second part would vary as you would use vector and not arrays. * The 3rd part would vary as you would use a reference not a pointer. Thus you would get the vector by passing in `vector<T*>&` (or `vector<shared_ptr<T> >&` not T\*\*\*
You could refer to a 3 dimensional array of ints as `int *** intArray;`
24,878
I have an array of $n$ real values, which has mean $\mu\_{old}$ and standard deviation $\sigma\_{old}$. If an element of the array $x\_i$ is replaced by another element $x\_j$, then new mean will be > > $\mu\_{new}=\mu\_{old}+\frac{x\_j-x\_i}{n}$ > > > Advantage of this approach is it requires constant computation regardless of value of $n$. Is there any approach to calculate $\sigma\_{new}$ using $\sigma\_{old}$ like the computation of $\mu\_{new}$ using $\mu\_{old}$?
2012/03/19
[ "https://stats.stackexchange.com/questions/24878", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/4319/" ]
Based on what i think i'm reading on the [linked Wikipedia article](http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Compute_running_.28continuous.29_variance) you can maintain a "running" standard deviation: ``` real sum = 0; int count = 0; real S = 0; real variance = 0; real GetRunningStandardDeviation(ref sum, ref count, ref S, x) { real oldMean; if (count >= 1) { real oldMean = sum / count; sum = sum + x; count = count + 1; real newMean = sum / count; S = S + (x-oldMean)*(x-newMean) } else { sum = x; count = 1; S = 0; } //estimated Variance = (S / (k-1) ) //estimated Standard Deviation = sqrt(variance) if (count > 1) return sqrt(S / (count-1) ); else return 0; } ``` Although in the article they don't maintain a separate running `sum` and `count`, but instead have the single `mean`. Since in thing i'm doing today i keep a `count` (for statistical purposes), it is more useful to calculate the means each time.
Given original $\bar x$, $s$, and $n$, as well as the change of a given element $x\_n$ to $x\_n'$, I believe your new standard deviation $s'$ will be the square root of $$s^2 + \frac{1}{n-1}\left(2n\Delta \bar x(x\_n-\bar x) +n(n-1)(\Delta \bar x)^2\right),$$ where $\Delta \bar x = \bar x' - \bar x$, with $\bar x'$ denoting the new mean. Maybe there is a snazzier way of writing it? I checked this against a small test case and it seemed to work.
3,006,413
I have a class with a few numeric fields such as: ``` class Class1 { int a; int b; int c; public: // constructor and so on... bool operator<(const Class1& other) const; }; ``` I need to use objects of this class as a key in an `std::map`. I therefore implement `operator<`. What is the simplest implementation of `operator<` to use here? **EDIT:** The meaning of `<` can be assumed so as to guarantee uniqueness as long as any of the fields are unequal. **EDIT 2:** A simplistic implementation: ``` bool Class1::operator<(const Class1& other) const { if(a < other.a) return true; if(a > other.a) return false; if(b < other.b) return true; if(b > other.b) return false; if(c < other.c) return true; if(c > other.c) return false; return false; } ``` The whole reason behind this post is just that I found the above implementation too verbose. There ought to be something simpler.
2010/06/09
[ "https://Stackoverflow.com/questions/3006413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
I think there is a misunderstanding on what `map` requires. `map` does not require your class to have `operator<` defined. It requires a suitable comparison predicate to be passed, which conveniently defaults to `std::less<Key>` which uses `operator<` on the `Key`. You should not implement `operator<` to fit your key in the `map`. You should implement it only if you to define it for this class: ie if it's meaningful. You could perfectly define a predicate: ``` struct Compare: std::binary_function<Key,Key,bool> { bool operator()(const Key& lhs, const Key& rhs) const { ... } }; ``` And then: ``` typedef std::map<Key,Value,Compare> my_map_t; ```
A version which avoids multiple indentation is ``` bool operator<(const Class1& other) const { if(a != other.a) { return a < other.a; } if(b != other.b) { return b < other.b; } return c < other.c; } ``` The "Edit 2" version of the author has on average more comparisons than this solution. (worst case 6 to worst case 3)
12,869,423
I'm learning C# and am trying to get my head around when to use classes and when not to. If I was writing an app for a bank, I know I would use classes for customers which would include their name, account number, balance, etc. Would I use a static class for the methods that would deposit into their account, withdraw, change their address, etc since I only need to write them once? Also, what would I use to keep track of every customer object? Having 2,000 Customers: ``` exampleName = new Customer(); ``` in my code doesn't seem right. I'm not at the point of learning database's yet and am just learning classes.
2012/10/13
[ "https://Stackoverflow.com/questions/12869423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1742690/" ]
Static classes are used when you aren't going to instantiate objects. You get one "instance" of that class - you can't do things like: ``` MyStaticClass m = new MyStaticClass(); m.SomeFunc(); ``` when you've got a static class. Instead you'd use it by using the class name itself. Something like: ``` MyStaticClass.SomeFunc(); ``` As to what would you use to keep track of every Customer object? You could use some sort of collection to hold these. Granted, in a real system there'd be some sort of persistence piece, likely a database, to hold the data. But you could just make something like: ``` IEnumerable<Customer> Customers = new List<Customer>(); ``` And then add your customers to that list ``` Customers.Add(new Customer() { ... }); ``` Back to the question about static methods... So, the deal here is that you're not going to be referencing instance members in a static method, so you wouldn't use static methods to update a particular Customer's address. Assuming your Customer class looked like: ``` public class Customer { public string Address { get; set; } } ``` You couldn't use a static method like ``` public static void SetAddress() ``` because each Customer (presumably) has a different address. You couldn't access the customer's address there because it isn't static. Get that? Instead, you'd use a static method if you were wanting to do something that didn't need to deal with instance data. I use static methods for things like utility functions. ``` public static double ComputeSomething(double someVal) { ... } ``` Here, the ComputeSomething function can be called by anybody like: ``` var result = MyStaticClass.ComputeSomething(3.15); ``` The takeaway here is that static **classes** aren't used to instantiate objects, rather they are used really as a convenient container to hold functions. Static **functions** are ones that *can* be on a non-static class but can't access any of the instance data. One place where a static function would be used would be for the Singleton pattern. You make the constructor non-public so folks can't call it, and instead provide a static method on the class to return the one and only instance of the class. Something like: ``` public class MySingleton { private static MySingleton instance; private MySingleton() {} public static MySingleton Instance { get { if (instance == null) { instance = new MySingleton(); } return instance; } } } ```
This is meant to be in addition to the other answers. This is example of polymorphism with interfaces. ``` public interface IDeposit { void Deposit(decimal amount); } public interface IWithdraw { void Withdraw(decimal amount); } public class Customer : IDeposit, IWithdraw { public void Deposit(decimal amount) { throw new NotImplementedException(); } public void Withdraw(decimal amount) { throw new NotImplementedException(); } } public class DepositOnlyATM : IDeposit { public void Deposit(decimal amount) { throw new NotImplementedException(); } } ``` Keeps concepts separate, and allows for implementing multiple interfaces, or just one. With class inheritance approaches you only get one, and you get all of it. Inevitably you end up with spaghetti in my experience because sub-classes want some of the behavior, but not all of it.
32,183,948
I'm trying to write a function which loops x times (3 in this example) through x steps (Step 1, Step 2 in this example) for x seconds (in this example, Step 1 takes 2 seconds, Step 2 takes 1 second). So I'd like it to loop as below: Step 1 (2 seconds) Step 2 (1 second) Step 1 (2 seconds) Step 2 (1 second) Step 1 (2 seconds) Step 2 (1 second) I've got the below code, but it only iterates through the loop once, and I can't work out why. ``` jQuery('input').click(function () { for(i = 0; i < 3; i++){ jQuery('div').html('Step 1'); setTimeout(function() { jQuery('div').html('Step 2'); },2000); setTimeout(function() { jQuery('div').empty(); },2000 + 1000); } }); ``` I would like the loop to continue with the same timings, but go back to the beginning after it hits `.empty();`. JSFiddle: <http://jsfiddle.net/kmyjhgvd/>
2015/08/24
[ "https://Stackoverflow.com/questions/32183948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2282086/" ]
I have not tried the code, but I think this should work ``` jQuery('input').click(function () { loopAction (3, 1, 2); // x is number of loops - s1, s2 in seconds }); function loopAction(x, s1, s2){ If (x>0){ // as long as x>0 start the iteration jQuery('div').html('Step 1'); setTimeout(function() { jQuery('div').html('Step 2'); setTimeout(function() { loopAction(x-1, s1, s2); // recursive call to self }, s2*1000); },s1*1000); } else { jQuery('div').empty(); // x>0 is false } } ```
Recursive Method answer: ``` function recursiveSteps(config) { var _step = config.step; config.step++; jQuery('div').html('Step 1'); setTimeout(function() { jQuery('div').html('Step 2'); },2000); setTimeout(function() { jQuery('div').empty(); },3000); if(config.step < 3) setTimeout(function() {recursiveSteps(config);}, config.step*1000); //you could put an "end" step here if needed } jQuery('input').click(recursiveSteps); ```
589
There are growing number of crypto currencies currently translated into public access via BigQuery by means of Google Cloud. For example, see [here](https://cloud.google.com/blog/products/gcp/bitcoin-in-bigquery-blockchain-analytics-on-public-data), [here](https://cloud.google.com/blog/products/data-analytics/ethereum-bigquery-public-dataset-smart-contract-analytics), or [here](https://xrpcommunity.blog/an-exploration-in-the-xrp-ledger-with-bigquery/). Also this [article](https://www.forbes.com/sites/michaeldelcastillo/2019/02/04/navigating-bitcoin-ethereum-xrp-how-google-is-quietly-making-blockchains-searchable/?ss=crypto-blockchain#23c94ff84248) in Forbes about this trend. In the articles above, we can clearly see the motivation that was behind that decision. Can we, as a Tezos community, make the similar effort and translate the entire blockchain into open DB format? It may be GCP+BigQuery or AWS+Redshift, etc. That effort may require a constant synchronization, but example in this direction is already exists. For instance, [this baker](https://www.tzdutch.com/quicksync/) is delivering the current DB state on regular basis. This service allow anybody to grab the recent DB snapshot and use it. Now, we may need to consider making entire DB available for SQL queries and searchable publicly. Projects involved in block exploration may be better positioned here. Just want to ask what is needed for it? Is it something that requires deep knowledge of Tezos proprietary DB? My guess that sooner or later every meaningful blockchain will be explored through Google. Everybody may have a chance to say "Hey Google, show me the block 327239 in Tezos" or simply type SQL in BigQuery and Google will present something similar to <https://tzscan.io/327239> but using BigQuery with applied visual analytics. Just dreaming. But who knows, maybe there are people who have been thinking about it as well.
2019/02/24
[ "https://tezos.stackexchange.com/questions/589", "https://tezos.stackexchange.com", "https://tezos.stackexchange.com/users/438/" ]
It seems to me this is a very good question and afaik such an effort is actively taken by [Cryptonomic](https://cryptonomic.tech/) in that direction. They are in the process of releasing a quite flexible query system called [Arronax](https://medium.com/the-cryptonomic-aperiodical/arronax-an-analysis-oriented-block-explorer-bd3b5d4f9fcb) that is powered by [Conseil/ConseilJS](https://medium.com/@CryptonomicTech/conseil-and-conseiljs-are-now-in-beta-99c00d30a808) .
Tezos BigQuery dataset is available now :) <https://medium.com/tezoscommons/tezos-public-finance-dataset-integrated-into-google-bigquery-6050726d2b96>
22,378,806
I am trying out a customized Incoming and outgoing call screen for my app. Both about the same screen and change the buttons according to state received from the broadcast. I am able to receive incoming calls properly but for making calls when I open my contacts and then click on number my customized screen opens but I don't see it making the call. I tried the following: ``` String uri = "tel:" + incomingnumber.trim(); Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse(uri)); startActivity(intent); ``` This just makes the call from the default phone dialer and doesn't show my screen. Here is my manifest file: ``` <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" /> <uses-permission android:name="android.permission.CALL_PRIVILEGED" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" > <activity android:name="com.honey.ringer.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.honey.ringer.AcceptCall" android:priority="999" android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" > <intent-filter> <action android:name="android.intent.action.ANSWER" /> <action android:name="android.intent.action.DEFAULT" /> <action android:name="android.intent.action.CALL_PRIVILEGED" /> <data android:scheme="tel" /> </intent-filter> </activity> <receiver android:name="com.honey.ringer.PhoneListenerBroad" android:priority="999" > <intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> <action android:name="android.intent.action.NEW_OUTGOING_CALL" /> </intent-filter> </receiver> </application> ``` Can somebody help me fix the outgoing call part? I would like get my customized screen with call going through? Thanks a lot!
2014/03/13
[ "https://Stackoverflow.com/questions/22378806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1443051/" ]
You may try adding this to your manifest: ``` <uses-permission android:name="android.permission.CALL_PHONE" /> ``` More info here: <http://developer.android.com/reference/android/Manifest.permission.html#CALL_PHONE>
You have not defined the [CALL\_PHONE](http://developer.android.com/reference/android/Manifest.permission.html#CALL_PHONE) permission in AndroidManifest.xml file Your manifest should look like this ``` <uses-permission android:name="android.permission.CALL_PHONE" /> <!-- permission added!--> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" > <activity android:name="com.honey.ringer.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.honey.ringer.AcceptCall" android:priority="999" android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" > <intent-filter> <action android:name="android.intent.action.ANSWER" /> <action android:name="android.intent.action.DEFAULT" /> <action android:name="android.intent.action.CALL_PRIVILEGED" /> <data android:scheme="tel" /> </intent-filter> </activity> <receiver android:name="com.honey.ringer.PhoneListenerBroad" android:priority="999" > <intent-filter> <action android:name="android.intent.action.PHONE_STATE" /> <action android:name="android.intent.action.NEW_OUTGOING_CALL" /> </intent-filter> </receiver> </application> ```
4,932,029
Can I have an enum which acts as a key value pair. ``` public enum infringementCategory { Infringement, OFN } ``` If I select `Infringement` I should get "INF0001" and if I select `OFN` I should get "INF0002" Is it possible?
2011/02/08
[ "https://Stackoverflow.com/questions/4932029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197878/" ]
How about these extensions: ``` public static class EnumExtension { /// <summary> /// Gets the string of an DescriptionAttribute of an Enum. /// </summary> /// <param name="value">The Enum value for which the description is needed.</param> /// <returns>If a DescriptionAttribute is set it return the content of it. /// Otherwise just the raw name as string.</returns> public static string Description(this Enum value) { if (value == null) { throw new ArgumentNullException("value"); } string description = value.ToString(); FieldInfo fieldInfo = value.GetType().GetField(description); DescriptionAttribute[] attributes = (DescriptionAttribute[]) fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) { description = attributes[0].Description; } return description; } /// <summary> /// Creates an List with all keys and values of a given Enum class /// </summary> /// <typeparam name="T">Must be derived from class Enum!</typeparam> /// <returns>A list of KeyValuePair&lt;Enum, string&gt; with all available /// names and values of the given Enum.</returns> public static IList<KeyValuePair<Enum, string>> ToList<T>() where T : struct { var type = typeof(T); if (!type.IsEnum) { throw new ArgumentException("T must be an enum"); } return (IList<KeyValuePair<Enum, string>>) Enum.GetValues(type) .OfType<Enum>() .Select(e => new KeyValuePair<Enum, string>(e, e.Description())) .ToArray(); } public static T GetValueFromDescription<T>(string description) where T : struct { var type = typeof(T); if(!type.IsEnum) { throw new ArgumentException("T must be an enum"); } foreach(var field in type.GetFields()) { var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if(attribute != null) { if(attribute.Description == description) { return (T)field.GetValue(null); } } else { if(field.Name == description) { return (T)field.GetValue(null); } } } throw new ArgumentOutOfRangeException("description"); // or return default(T); } } ``` With this in place you can built up your enum like this: ``` public enum Foo { [Description("Foo - Something")] Something, [Description("Foo - Anything")] Anything, } ``` And get your list like this: ``` var list = EnumExtension.ToList<Foo>(); ```
You could store the titles (INF0001)... in a `Dictionary<infringementCategory, string>`
88,890
We're studying Heuristic in my Theoretical CS class, more specifically Greedy-Algorithms for the Traveling Salesperson Problem. The first one is the "next neighbor heuristic", where you start at any given point and connect it with the nearest point and then connect that to the next nearest one until all points are covered - then going back to the first point. [![enter image description here](https://i.stack.imgur.com/JY9E8.png)](https://i.stack.imgur.com/JY9E8.png) Where "P" is the starting and ending point. The second approach, which gives the optimal answer, is the "closest pair of points" or "Engstes-Paar-Heuristic". I don't understand how this approach works because from the looks of it, you simply make a straight line but I don't understand this approach. Sorry about the possible name changes, it's originally in German. [![enter image description here](https://i.stack.imgur.com/NqaXj.png)](https://i.stack.imgur.com/NqaXj.png)
2018/03/04
[ "https://cs.stackexchange.com/questions/88890", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/84399/" ]
First let's name your points $P\_A$, $P\_B$, $P$, $P\_C$, and $P\_D$ (from left to right). With the first heuristic you start at one point ($P$) and move to the closest point. From that new point, you move to the next closest point, and so on and so forth. With the second heuristic you again start at one point ($P$) but you move to the point closest to one of the two ends of your current path. It is a simple improvement over the first heuristic. For your example: 1. Current path: $P$. Closest point to $P$: $P\_B$. 2. Current path: $P-P\_B$. Closest point to $P$ or $P\_B$: $P\_C$. 3. Current path: $P\_B-P-P\_C$. Closest point to $P\_B$ or $P\_C$: $P\_A$. 4. Current path: $P\_A-P\_B-P-P\_C$. Closest point to $P\_A$ or $P\_C$: $P\_D$. 5. Current path: $P\_A-P\_B-P-P\_C-P\_D$. The only choice left is to connect $P\_A$ to $P\_D$.
The example shows the Travelling salesman problem for the case that all points are on a straight line. That’s rarely the case. And you cant just move the points to solve the problem, they are where they are. The closest pair heuristics seems to be that you find the closest connection and add it, then again the closest connection that is still available and so on. You can easily show that this is optimal if all the points are on a straight line, but usually it’s not.
43,244,096
I'm building a virtual environment and need to simulate a real switch with devices attached. I prefer to stay away from a single vendor solution & Mininet/OVS look promising. However, I don't find snmp support in the docs. I need to obtain the switch arp & mac tables (at a minimum) via either SNMP or a cli command via ssh. This is trivial with a Cisco switch or most any hardware vendor. Any thoughts in how I can simulate this with mininet? TIA, -Steve
2017/04/06
[ "https://Stackoverflow.com/questions/43244096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1248438/" ]
Consider using a different layout manager which gives you more control over how components are laid out, for example, a `GridBagLayout` [![Example](https://i.stack.imgur.com/pOfxt.png)](https://i.stack.imgur.com/pOfxt.png) *nb: The padding around the text fields is courtesy of MacOS, in this case, I'd consider using a non-editable text field instead* ``` setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; add(new JLabel("Enter Length #1"), gbc); gbc.gridy++; add(new JLabel("Enter Length #2"), gbc); gbc.gridy++; add(new JLabel("Enter Length #3"), gbc); gbc.gridy++; add(new JLabel("Enter Length #4"), gbc); gbc.gridy++; add(new JLabel("Average"), gbc); gbc.gridx++; gbc.gridy = 0; gbc.fill = GridBagConstraints.HORIZONTAL; add(new JTextField(10), gbc); gbc.gridy++; add(new JTextField(10), gbc); gbc.gridy++; add(new JTextField(10), gbc); gbc.gridy++; add(new JTextField(10), gbc); gbc.gridy++; JLabel average = new JLabel(" "); average.setBorder(BorderFactory.createLineBorder(Color.BLACK)); add(average, gbc); ```
Set the preferred size of the result field as below ``` result_Label.setPreferredSize(length1.getPreferredSize()); ```
57,101,064
Using double float data calculate the count, average and standard deviation of any given input. Every time I run the program it gives me my count and average however my standard deviation shows up as NaN. ``` import java.util.Scanner; public class Final { public static void main (String[]args) { Scanner in = new Scanner(System.in); System.out.print("Enter a range of digits to recieive 1. Count , 2. Average , 3. StdDvn"); double input = in.nextDouble(); double count = 1; double sum = 0; double sumsquared = sum * sum; double std = 0; while (in.hasNextDouble()) { double value = in.nextDouble(); sum = input += value; count++; } double average = sum / count; std = Math.sqrt((sumsquared-(sum/count)) / (count - 1)); System.out.println("Your count of numbers is : " + count); System.out.println("Your average of numbers is : " + average); System.out.println("Your standard deviation of numbers is : " + std); } } ```
2019/07/18
[ "https://Stackoverflow.com/questions/57101064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11804800/" ]
Your `sumsquared`variable is always `0`since you calculate it from `0*0` right after the initialization of `double sum=0;`. This part should be moved below the summation. Also to calculate the standard deviation without arrays using loops, you need to know the following 3 values: * How many numbers were entered. * The sum of all numbers. * The sum of the squares of the numbers. **Formula**: `E[X^2]-(E[X])^2` see [wikipedia](https://en.wikipedia.org/wiki/Standard_deviation#Definition_of_population_values). `^2` means `squared` of course. ```java public static void main (String[]args) { Scanner in = new Scanner(System.in); double count = 10.0; // how many numbers are entered, e.g.: 10 double sum1 = 0.0; // sum of the numbers double sum2 = 0.0; // sum of the squares System.out.println("Enter 10 numbers: "); for (int i=0; i < 10; i++) { double n = in.nextDouble(); sum1 += n; sum2 += n * n; } double average = sum1 / count; double variance = (count * sum2 - sum1 * sum1) / (count * count); double stddev = Math.sqrt(variance); System.out.println("Your count of numbers is : " + count); System.out.println("Your average of numbers is : " + average); System.out.println("Your standard deviation of numbers is : " + stddev); } ```
Your `sumsquared` is zero. So, you’re using a value of `0` in your standard deviation. Here’s the fix to relocate your `sumsquared`. EDIT: I think your `std` is incorrect. You must find the mean first. Inside the square root, find the sum of `( x - mean)`, where x are your data, then divide that result by `count - 1`. ``` public static void main (String[]args) { Scanner in = new Scanner(System.in); System.out.print("Enter a range of digits to recieive 1. Count , 2. Average , 3. StdDvn"); double input = in.nextDouble(); double count = 1; double sum = 0; double std = 0; while (in.hasNextDouble()) { double value = in.nextDouble(); sum = input += value; count++; } double sumsquared = sum * sum; double average = sum / count; std = Math.sqrt((sumsquared-(sum/count)) / (count - 1)); /* fix this formula */ System.out.println("Your count of numbers is : " + count); System.out.println("Your average of numbers is : " + average); System.out.println("Your standard deviation of numbers is : " + std); } } ```
219,813
I want to add my custom template on product page just like `$this->getChildHtml('custom_product_info')`. As in magento1.9 to use `$this->getChildHtml('custom_product_info')` we add layout xml like below : ``` <catalog_product_view> <reference name="product.info"> <block type="core/template" name="custom_product_info" template="custom.phtml"/> </reference> </catalog_product_view> ``` What is the xml and process to add custom template in Magento2.1?
2018/03/26
[ "https://magento.stackexchange.com/questions/219813", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/14039/" ]
Use this ``` <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="product.info"> <block class="Magento\Framework\View\Element\Template" name="block.name" as="block.alias" template="{Vendor}_{ModuleName}::{YourTemaplte}.phtml"> </block> </referenceBlock> </body> </page> ```
``` <referenceContainer name="content"> <block class="Xcommerce\Category\Block\Overview" name="overview" template="X2commerce_Category::custom.phtml"> </block> </referenceContainer> ```
674,169
I have been looking at a few of our VB.NET dll's using FxCop and all of the errors relate to DLL setup (i.e. Strong Names, Culture Info) and the case of Variables methods. Looking at a few examples of FxCop examining a C# Dll, it appears to offer a lot more potential errors. Does this mean that FxCop is more valuable on C# developments that VB.NET or have I just chosen bad examples. I thought it was the case that FxCop worked on IL rather than the specific languages, so am I just missing rules files for VB.NET or are there more available for C#?
2009/03/23
[ "https://Stackoverflow.com/questions/674169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
As far as I am aware, FxCop is language agnostic. It is more likely that C# has more freedom than VB.NET in various areas allowing for more mistakes to occur (as FxCop interprets it) rather than FxCop being biased somehow. If this is the case, then I can see it being more valuable to a C# developer than a VB.NET developer as the former language has more scope for creating issues that FxCop can detect. However, FxCop is an invaluable tool for any .NET project, even if some languages make it harder to make mistakes.
FxCop is supposed to work on compiled code, so the language you write in shouldn't matter. I've used the tool on projects with either C# or VB, so it does indeed work. It has been rather helpful, actually.
1,214,153
All the time I have the problem that I cannot delete - move - rename folders in Windows 7 (also applies to windows 10) on network drives because of the thumbs.db file. It complains: "The action can't be completed because the file is open in Windows Explorer." I found something in a long thread that works for me.
2017/05/29
[ "https://superuser.com/questions/1214153", "https://superuser.com", "https://superuser.com/users/390837/" ]
**short answer:** windows 7: In explorer: Change file display settings from "details" to "Content" windows 10: In explorer: View->Layout->List Now the thumbs.db file can be removed. **Long answer:** <https://social.technet.microsoft.com/Forums/windows/en-US/ca2cbc1a-362f-4f01-a8f8-6f05112f1915/windows-7-bug-explorer-locks-thumbsdb-in-most-recently-viewed-folder?forum=w7itprogeneral>: > > I accidentally came across a slightly easier fix for this bug. Instead of setting "Turn off the display of thumbnails and only display icons on network folders" to Enable, **I simply changed the Windows Explorer display setting from "Details" to "Content**". Then I was able to delete my Thumbs.db files without any complaints from Windows 7, even though I have thumbnails enabled. After deleting the offending file(s), I just restore the display to "Details" again. > > > thanks my unknown hero robster8192
I had this issue in Windows 11 on a network share, and none of the above solutions worked (changed view / layout, cut/paste on local machine). However I was able to rename it to \_.db, and then I was able to delete the file.
1,005,805
I'm trying to come up with a regex that helps me validate a **Blood Group** field - which should accept only A[+-], B[+-], AB[+-] and O[+-]. Here's the regex I came up with (and tested using **[Regex Tester](http://regexpal.com/)**): ``` [A|B|AB|O][\+|\-] ``` Now this pattern successfully matches A,B,O[+-] but fails against AB[+-]. Can anyone please suggest a regex that'll serve my purpose? Thanks, m^e
2009/06/17
[ "https://Stackoverflow.com/questions/1005805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112364/" ]
Try: ``` (A|B|AB|O)[+-] ``` Using square brackets defines a [character class](http://www.regular-expressions.info/charclass.html), which can only be a single character. The parentheses [create a grouping](http://www.regular-expressions.info/brackets.html) which allows it to do what you want. You also don't need to escape the `+-` in the character class, as they don't have their regexy meaning inside of it. As you mentioned in the comments, if it is a string you want to match against that has the exact values you are looking for, you might want to do this: ``` ^(A|B|AB|O)[+-]$ ``` Without the [start of string and end of string anchors](http://www.regular-expressions.info/anchors.html), things like "helloAB+asdads" would match.
^(A|B|AB|O)[+-]?$ This will produce the correct out put.
4,497,538
This question comes from a qualifying exam. > > Let $C$ be an $n × n$ real matrix with $n ≥ 3$. > (a) For which real polynomials $q$ of degree 2 is the null space of $q(C)$ not the zero subspace? > (b) For which real polynomials $f$ of degree $k ≥ 3$ is $f(C)$ invertible? > > > I've never faced a similar question before in linear algebra. Here is my try on the first item (a). I am still looking for ways to approach item (b). We identify $C$ with its associated operator on the vector space $V = \mathbb R^n$, which will also be denoted by $C$. Let $m = p\_1^{c\_1}\cdots p\_s^{c\_s}$ be the decomposition of the minimal polynomial of $C$ into irreducible factors (possibly not in linear factors). By the primary cyclic decomposition theorem, we know that $$V = (\langle v\_{1,1}\rangle\oplus \cdots \oplus \langle v\_{1,k\_1} \rangle) \bigoplus \cdots \bigoplus ( \langle v\_{s,1} \rangle \oplus \cdots \oplus \langle v\_{s,k\_s} \rangle)$$ where $\langle v\_{i,j} \rangle$ denotes the cyclic subspace generated by $v\_{i,j}$, with the minimal polynomial of the restriction of $T$ on each $\langle v\_{i,j} \rangle$ being exactly $p\_{i}^{c\_{i,j}}$ and such that $c\_{i,1} = c\_1 \geq c\_{i,2} \geq \cdots \geq c\_{i,k\_i}$. It seems that we should be taking any product $p$ of a subcolletion of the polynomials $p\_i^{c\_{i,j}}$ such that the sum of the degrees $c\_{i,j}$ add up to $2$. Since those polynomials are relatively prime with one another when $p\_i\neq p\_k$, the product $p$ will be the minimal polynomial of the sum of the corresponding vectors $v\_{i,j}$, so $p(C)$ will have a non-trivial kernel. However, I am unsure on how to prove, in a clear manner, that there exists degree coefficients $c\_{i,j}$ adding up to $2$.
2022/07/21
[ "https://math.stackexchange.com/questions/4497538", "https://math.stackexchange.com", "https://math.stackexchange.com/users/314957/" ]
Suppose $\lambda\_i$, $(i=1,2,...)$ is the eigenvalue of matrix $C$. a) Construct a polynomial $q(x)=(x-\lambda\_i)g(x)$, where $g(x)=ax+b; a(\ne 0)\in\mathbb R, b\in\mathbb R$ is linear function. In case, $\lambda\_i$ is complex then choose $g(x)=(x-\overline\lambda\_i)$. Matrix $q(C)$ has determinant zero so it will have a non-trivial nullspace. b) Consider any polynomial $f(x)$ of degree $k\ge 3$ such that $f(\lambda\_i)\ne 0$ and $f(0)\ne0$. Matrix $f(C)$ cannot have zero determinant and hence $f(C)$ is invertible.
For **(a)** let $m(x)$ be the minimal polynomial of $C$ and write it as a product of irreducibles (which are at most degree 2 by Fundamental Theorem of Algebra). If $q$ is not in a principle ideal generated by one these irreducibles (i.e. $q$ is not divisible by each irreducible or more succinctly: $m$ and $q$ have non-zero resultant) then **(i)** $q(C)$ is invertible and conversely **(ii)** $q(C)$ has nontrivial kernel when $q$ is in one of said ideals. (A different way of stating this: assume WLOG that $q$ is monic and if irreducible, check to see if it matches a degree 2 irreducible of $A$ and if $q$ is reducible into linear factors check each of them against the linear factors of $A$.) In case of (ii) if $q(C)$ was invertible then we could find an even smaller degree annihilating polynomial contradicting $m$'s minimality. In case of (i) if you don't want to work over a splitting field, then you could probably do an argument with Bezout's identity / resultants but the expedient argument is to use Real Schur form of $C$ and observe $q$ cannot kill any diagonal block that is $2\times 2$ by uniqueness of minimal polynomial argument and the $1\times 1$ blocks are trivial -- $q(\lambda)\neq 0$ otherwise $\lambda$ would be a factor of $Q$. Conclude $q(C)$ is invertible since it is similar to a block diagonal matrix with each said (diagonal) block being invertible. **(b)** write $f$ as a product of irreducibles and if there are no common factors with $m$ then repeatedly apply (i). And if there is a common factor then apply (ii).
3,595,043
So, here's the theorem that I'm trying to prove: Let $f$ be a function. Then, if $f(x) \to L$ as $x \to x\_0$, where $L,x\_0 \in \mathbb{R}$, then $f(x)$ is bounded in some deleted neighbourhood of $x\_0$. --- Proof Attempt: Since $f(x)$ has a limit at $x = x\_0$, we have: $$\forall \epsilon > 0 : \exists \delta > 0: 0 < |x-x\_0| < \delta \implies |f(x) - L| < \epsilon$$ Let $\epsilon > 0$. Then, we are guaranteed the existence of a deleted neighbourhood of $x\_0$. So, we have: $$|f(x)-L| \geq | |f(x)|-|L| |$$ $$|f(x)-L| \geq |f(x)|-|L|$$ $$|f(x)|-|L| < \epsilon$$ $$|f(x)| < |L| + \epsilon$$ Now, let $M = |L| + \epsilon$, so that $f(x) \leq M$. We have found a real number that satisfies the condition for a function to be bounded in this deleted neighbourhood. Hence, we conclude that $f(x)$ is bounded in some deleted neighbourhood of $x\_0$. In fact, I believe that a stronger result can be given here. Based on the argument above, it seems like this should hold for any deleted neighbourhood of $x\_0$. Could someone have a look at this argument and tell me if it is correct and if the generalization I'm proposing does, indeed, hold? Thanks!
2020/03/25
[ "https://math.stackexchange.com/questions/3595043", "https://math.stackexchange.com", "https://math.stackexchange.com/users/426261/" ]
The set $\textbf{Q}$ is linearly ordered. This means that the relation ''$\leq$'' is reflexive, anti-symmetric and transitive. More precisely, (a) if $x\in\textbf{Q}$, then $x\leq x$ (reflexive) (b) if $x,y\in\textbf{Q}$ and $x\leq y$ and $y\leq x$, then $x = y$ (anti-symmetric) (c) if $x,y,z\in\textbf{Q}$, $x\leq y$ and $y\leq z$, then $x\leq z$ (transitive) However, as far as I have understood, when he says that $x < y$ iff $y > x$, he means that both notations have the same meaning.
Anti symmetric means that the only time $x < y$ and $y < x$ can ever happen is if $x = y$. And as $x < y$ and $y < x$ *never* happens, that is vacuously true. The only time $x < y$ and $y < x$ happens is .... never. So it is anti-symmetric. If you want to argue that $x < y$ and $y< x\not \implies x=y$. I will remind you that $x < y$ and $y < x$ is *FALSE* and *FALSE* $\implies$ *EVERYTHING*. So $y < x$ and $y< x\implies x = y$. And $y< x$ and $y < x\implies$ pigs fly.
45,290,192
I am developing django website and I want to use ldap authontation with my application. I am using Django 1.11 to authenticate with the django-python3-ldap. I tested the connection to my ldap using ldapsearch and it was succeeded and I got the following result: ``` ally@websrv:/web/demo_project_ally$ ldapsearch -x -W -D 'cn=admin,dc=myldap,dc=com' -b "dc=myldap,dc=com" "cn=ally ally" -H ldap://myldap.com Enter LDAP Password: # extended LDIF # # LDAPv3 # base <dc=myldap,dc=com> with scope subtree # filter: cn=ally ally # requesting: ALL # # ally ally, my_ou, myldap.com dn: cn=ally ally,ou=my_ou,dc=myldap,dc=com cn: ally ally givenName: ally gidNumber: 500 homeDirectory: /home/users/aally sn: ally loginShell: /bin/sh objectClass: inetOrgPerson objectClass: posixAccount objectClass: top userPassword:: e01ENX1kNVJuSkw0bTV3RzR3PT0= uidNumber: 1000 uid: aally # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 ``` When I try to connect from django I will get this error: ``` System check identified no issues (0 silenced). July 24, 2017 - 20:40:26 Django version 1.11, using settings 'demo_project.settings' Starting development server at http://0:8002/ Quit the server with CONTROL-C. LDAP connect failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - None - bindResponse - None [24/Jul/2017 20:40:37] "POST /accounts/login/ HTTP/1.1" 200 917 ``` Error: ``` LDAP connect failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - None - bindResponse - None ``` Here is my django configuration for the ldap connection from setting.py file: ``` LDAP_AUTH_URL = "ldap://myldap.com:389" LDAP_AUTH_USE_TLS = False LDAP_AUTH_SEARCH_BASE = "dc=myldap,dc=com" LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" LDAP_AUTH_USER_FIELDS = { "username": "uid", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_openldap" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = None LDAP_AUTH_CONNECTION_USERNAME = "admin" LDAP_AUTH_CONNECTION_PASSWORD = "password" #Print information about failed logins to your console by adding the following to your settings.py file. LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } ``` I am working under Ubuntu 16.04 and using python3.5 I used this reference for my setting: <https://github.com/etianen/django-python3-ldap> I am able to perform an initial sync of LDAP users using: ./manage.py ldap\_sync\_users Please advice how to solve this issue.
2017/07/24
[ "https://Stackoverflow.com/questions/45290192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2152275/" ]
I have encountered the same issue. Below change fix my issue ``` LDAP_AUTH_CONNECTION_USERNAME = "cn=admin,dc=myldap,dc=com" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" ```
ldap3 always authorizes using the "displayName" field. If the values of your LDAP\_AUTH\_USER\_FIELDS["username"] fields are not equal to the values of the "displayName" fields, you will have errors.
1,037
We get a lot of [equipment recommendation](https://photo.stackexchange.com/questions/tagged/equipment-recommendation) questions on this site; it's currently the 2nd-most popular tag, behind the lens tag. Many of these questions seem to start out as something vague and hard to answer, like "What SLR should I get?". Commenters ask the person to clarify their needs ("What are you going to use it for?", "Do your friends shoot Canon, Nikon, Pentax, Sony?", etc), the question becomes tailored to the asker's situation. While these are useful to the asker and can teach that person a lot, there's concern that these aren't useful to the site and to the wider Internet -- after all, every snowflake is different. What should we do with/about these questions, so that they can be useful both to the original asker (not scare them off; respect their intentions; don't insult them) and also be useful to a wider audience?
2011/04/27
[ "https://photo.meta.stackexchange.com/questions/1037", "https://photo.meta.stackexchange.com", "https://photo.meta.stackexchange.com/users/378/" ]
We should not only allow them, but embrace them as part of how we encourage new users. Denying questions like these will keep us from becoming the place on the web for getting answers for photography. Online photography forums **DO** allow for personalized gear recommendations, and as such generate more new members, as they look for answer to probably the hardest question they'll ever face "What should I buy?" It's true that personalized gear recommendations don't have value to a lot of people, but if it's valuable to at least one person, it should be valuable to our community (imo). If we keep turning away potential new members who need help with gear recommendations, we just push them to places that welcome those types of questions.
One aspect I'd like to stretch particularly is this: Even if the question is fluid and specific to one person, **I can still benefit from it.** In fact, **I spent the last three days reading various taylored 'what should I buy' questions only to get a feel for what is even relevant, which questions I have to ask myself.** With that in mind, I then went and bought my next lens, so these questions were at least indirectly useful to me and I would hesitate to discourage them just because they are too narrow or fluid.
1,291,408
I searched SO, finding little thing about negative testing, which is also a very important thing developers should keep in mind during work. What about making a list of top 10 test case for the negative testing developer should keep in mind collaboratively? Thanks! The definition of Negative Testing: In software testing, a test designed to determine the response of the system outside of what is defined. It is designed to determine if the system doesn't crash with unexpected input.
2009/08/18
[ "https://Stackoverflow.com/questions/1291408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144356/" ]
Tools like [Pex](http://research.microsoft.com/en-us/projects/Pex/) may be useful here; it is designed to try to find values / scenarios that crash the code (by exercising every code branch and likely error-case like div-by-zero/overflow/etc), based on static analysis of what it does. It has successfully found some edge-cases in code like the .NET "resx" reader.
Yes, he's talking about writing tests such that you ensure code not only does what it means to do, but doesn't do more. So imagine a test to check if a file is deleted; you could delete the entire folder and it would return true. This form of testing is arguably interesting, but potentially of dubious value. For example if you want to make sure an 'update' statement is affecting your given row, you should also have previously confirmed that it only affects *one* row. I guess what my boring mumbling is suggesting, is that this should probably be covered in a your normal tests. Maybe. Interesting to think about anyway.
4,101,746
I am trying to understand the metric we defined in class for $C(\mathbb{R})$ i.e. on the set of continuous functions $f: \mathbb{R} \to \mathbb{R}$. A little background: We developed some strong theory on the convergence of random variables for continuous functions defined on compacta and we define this metric in an effort to extend these results. We defined $$d(f,g):= \sum\_{j = 1}^{\infty}2^{-j} \frac{d\_j(f,g)}{1+d\_j(f,g)}$$ where $$ \forall j \in \mathbb{N}: d\_j(f,g):= \underset{-j \leq t \leq j}{\operatorname{sup}} |f(t)-g(t)| $$ Now I know so far that the infinite sum $\sum\_{j = 1}^{\infty}2^{-j}$ converges to $1$ and thus what we do seems to me like giving each interval $J := [-j,j]$ a weight such that the total weights sum to $1$ and then evaluating the familiar supremum-norm on these weighted compacta. In that interpretation what happens around $0$ is most important to us since the interval $[-1,1]$ carries the highest weight. So far so good. What I don't understand is the following. Why does the sum contain (or what is the meaning of) this quotient: (\*) $$\frac{d\_j(f,g)}{1+d\_j(f,g)}$$ Why do we use this and not some other function of the $d\_j(f,g)$ that guarantees convergence? Edit: I edited out the suggestion of $$d(f,g):= \sum\_{j = 1}^{\infty}2^{-j} d\_j(f,g)$$ since my point was not that this would be a valid replacement. I was aware that it probably would not converge. Thanks to geometricK for the concrete example though. My question is more about the benefits of the function (\*) over others that **do** give convergence.
2021/04/14
[ "https://math.stackexchange.com/questions/4101746", "https://math.stackexchange.com", "https://math.stackexchange.com/users/869111/" ]
My favourite metric in this setting is $$d(f,g)=\sup\{ d\_j(f,g) \wedge 1/j: j\in\mathbb N\}$$ where $a\wedge b$ is the minimum of two real numbers. It is immediate that $d(f,g)<1/k$ if and only if $d\_k(f,g)< 1/k$, and this is exactly what you want, e.g., to show that a sequence $f\_n$ converges to $f$ if and only if $d\_j(f\_n,f)\to 0$ for all $j\in\mathbb N$.
$$d(f,g):= \sum\_{j = 1}^{\infty}2^{-j} d\_j(f,g)$$ is not convergent. We can take $\sum\_j 2^{-j}\min \{{1, d\_j(f,g)}\}$ and this is also frequently used.
308,070
Imagin this, a triangular prism with one way mirrors on each face of it and with a light source on the inside and out, it seems normal, right? But, now the light turns off, will the light keep bouncing on the inside? And will it basically give if a source of energy that lasts so long? Remember this is a true one way mirror.
2017/01/28
[ "https://physics.stackexchange.com/questions/308070", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/143528/" ]
Suppose we have a light bulb with nothing around it. It gives of energy as long as it stays lit. If it stayed lit an infinite time, it would give off an infinite amount of energy. This energy has to come from somewhere. A battery, a power cord, or some such. The point is you would have to put infinite energy in to get infinite energy out. Now surround the light bulb with a mirror that is ordinary, aside from being a perfect reflector. The light cannot get out. Every time it hits a mirror, it is reflected back. So the energy given inside the mirrors grows and grows as long as the bulb is on. There is no such thing as a perfect mirror. Real mirrors always absorb at least a little light. Also the bulb inside is not a mirror. So in reality, some energy would be absorbed on each bounce. The mirror and bulb would get hot. Hot things glow, so energy would get out that way. Or hot things melt.
If both the sources are switched off and we assume that there is no external source anywhere, the prism will be able to store the energy supplied till the sources are switched (google why diamonds sparkle!). That is it, it will store that energy. It will will not act as source of energy, it just traps the light.
67,348,679
I am trying to format a number to have commas and two decimal points at the end of it like: 100,000.00 This is what I have tried, but it won't work because I can't use these number formats on each other because they require a number to be inputted into the format. ``` "{:,}".format("{:.2f}".format(grossPay[i])) ``` So if you have any ideas on how I can do that, I would greatly appreciate it :D
2021/05/01
[ "https://Stackoverflow.com/questions/67348679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11254527/" ]
Terraform currently has a limitation with the provider using `Email` protocol. It is unsupported because the endpoint needs to be authorized and does not generate an ARN until the target email address has been validated. This breaks the Terraform model and as a result are not currently supported.
CloudFormation supports this. However, as others and the docs are point out, terraform doesn't quite support it. There's a guide that suggests creating a CloudFormation stack within terraform. This stack creates the SNS topic and could also add the subscription. <http://aws-cloud.guru/terraform-sns-topic-email-list/> It could be a solution if you think the effort is worth it
17,824,440
I'm having a hard time understanding the transition from @ try to @ catch I understand that if a statement from the @try block throws an exception, the @catch block gets executed. I don't understand how an NSException object containing information about the exception gets passed as the argument. A lot of stuff I'm reading online about exceptions skip this detail. The example from my book is ``` @try { [myArray objectAtIndex: 2]; } @catch (NSException *exception){ NSLog(@"Caught %@%@", exception.name, exception.reason); } ``` So once the exception is detected is an exception object automatically created and sent to the @catch block?
2013/07/24
[ "https://Stackoverflow.com/questions/17824440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925859/" ]
Had similar issue, which was a result of update. Please make sure that names of libraries mentioned in eclipse.ini and the actual names of these files on your disk match exactly. ``` -startup plugins\org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar --launcher.library plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.1.R36x_v20100810 ``` Here is the post that I used to fix this issue on my system <http://codewithgeeks.blogspot.in/2013/11/fixing-eclipse-executable-launcher-was.html>
This worked for me On the Zipped folder of the ADT you initially downloaded unzip and navigate to: > > adt-bundle-windows-x86\_64-20140702\eclipse\plugins > > > Copy all the executable jar files and paste them on the > > C:\adt-bundle-windows-x86\_64-20140702\adt-bundle-windows-x86\_64-20140702\eclipse\plugins > > > directory (or wherever your adt is located). Any executable jar files missing in the plugin folder will be added. You should be able to launch eclipse
5,957
Does anyone know of a simple photo viewer that will let you quickly flip through a bunch of photos, and delete the ones you don't want, that will also (optionally) delete an associated RAW and/or sidecar file? I'm thinking of an app that had a buttons for Delete JPG, Delete RAW, Delete Both, or that would mark them for deletion to perform before exiting the app, or something similar to that. Edit: Windows Vista (soon to be Windows 7), camera is Nikon D90 (so .NEF raw files). I have not instaleld the bundled Nikon software yet. I've just been using the Windows photo import which just copies them onto the hard drive. If I preview using Windows Photo Gallery, deleting the file only deletes the JPG, so I have to go back and delete the raw files manually afterwards.
2010/12/22
[ "https://photo.stackexchange.com/questions/5957", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/227/" ]
[Geeqie](http://geeqie.sourceforge.net/) can do this -- turn on the "Enable Image Grouping" option, and files with the same base name will be grouped. (It doesn't do anything magic to link files by actual contents that I'm aware of, though.) You should be able to install it with `yum install geeqie` or `apt-get install geeqie` on Fedora or Ubuntu. I'm not aware of pre-built packages for Mac or Windows, but in theory it should be possible.
[FastPictureViewer](http://www.fastpictureviewer.com/) groups JPG and RAW files similar to Lightroom and, I suppose, deletes both simultaneously. Of course, it does not do everything Lightroom does, but it comes at a much lower price.
47,585,107
I'm a scripting newbie and am looking for help in building a BASH script to compare different columns in different CSV documents and then print the non-matches. I've included an example below. File 1 Employee ID Number,Last Name,First Name,Preferred Name,Email Address File 2 Employee Name,Email Address I am wanting to compare the email address column in both files. If File 1 does not contain an email address found in File 2, I want to output to a new file. Thanks in advance!
2017/12/01
[ "https://Stackoverflow.com/questions/47585107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9036634/" ]
What browser do you use? Chrome 62 and Firefox 57 fail at inline editing lambdas and both throw DOMExceptions, but Safari 11 seems to work. Try Safari(or some other browser) for editing while waiting for Amazon to fix this.
This is happening in chrome as chrome is disabling the use of cookies from cloudfront domain. 1. Go to address bar and there you would see a icon that says there are some cookies blocked on this website. 2. Click on it. 3. Click on manage. 4. Click on Blocked. 5. Click on allow to couldfront domain. 6. Reload page. I have tried it and it's working for me. Edit: This could also be tried on other browsers that are facing this issue.
10,952,413
I've written an ASP.net web application. In the interest of following the advice in "The Pragmatic Programmer" to put application logic in configuration, I wrote a large XML file that describes various business rules. When I test the application on my local development workstation, I copy the file to `c:\xxxxx\myfile.xml` and then write the code to read the file from this location. What is the correct way to deploy this xml file as part of my web application so that it gets read from the directory in which the web application is deployed? **Update:** The XML file in question is for server-side configuration and should **never** be available for download to the end-user.
2012/06/08
[ "https://Stackoverflow.com/questions/10952413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238260/" ]
I don't know if this is what you want - Click on the XML file, then open the Property Window and find the "Build Action" property. Set the value to "Embedded Resources"
If you want to make available your XML file from http requests to your server, you should place it in your web publication folder. This ASP instruction should help you to find your publication path: Request.ServerVariables("APPL\_PHYSICAL\_PATH")
94,246
There are developers out there that not only write code and solve problems, but aspire to one day be an entrepreneur and run their own company. They may participate in open source projects, go to various networking events/meetups, or even write code to help shape/start their own business outside of work. And, for example, an fully-candid interview with a prospective hire might go something like this: > > Company: *Where do you see yourself in 5 years?* > > > You: *I see myself running my own software company in City Z, doing xx projects, solving yy kind of problems.* > > > This might be a red flag to a company, who may consider this kind of developer a high risk for leaving, and that they would take with them the experience of developing a particular software or specific industry knowledge. Should developers hide these kind of aspirations/traits from their current employers, or where they are interviewing? Is it unprofessional to mention these kind of things? Does it help or hurt their chance of getting hired?
2011/07/19
[ "https://softwareengineering.stackexchange.com/questions/94246", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/14/" ]
Be honest. If you are interested in a future in business then this may even benefit the employer in case they are looking for an employee who can handle both "areas." Some companies, especially banks, even fund their employees if they want to do an MBA!
If you have entrepreneurial aspirations, i would love to hire you. **Because,** 1. It tell me you are self driven. Probably you wont to solve the problem on your own. 2. It tell me you are enterprising. Probably you will not come back saying *it-cann't-be-done* without trying enough. 3. Most likely you won't come up with answers like *it's-not-my-job*. 4. Most importantly, because you at least have *some aspiration* 5 years ahead of you, you believe in growth and inherently you are always keen to make best out of opportunities. **But yes, it will hint the recruiter some other things** 1. You may take time to appreciate heavy process driven approach 2. You may not like a boss who is very much a micro manager. I always ask this question in the interview for exact same reasons.
20,183
Don't get me wrong, I like Lion, though I do miss many things from Snow Leopard and wish to express this to the OSX team via some sort of suggestion forum. I'm visually impaired and the OS is seemingly becoming more and more visual. One thing that seems to be missing which I can barely live without is the CTRL+WHEEL to zoom in/out, the options seem to be there but don't work, or somehow work differently than they used to?
2011/08/05
[ "https://apple.stackexchange.com/questions/20183", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/4176/" ]
Here's the official Feedback form for OS X. <http://www.apple.com/feedback/macosx.html> The general feedback pages do get to the marketing and engineering people as well as measuring user satisfaction, but you also can sign up for a free developer account and file bugs more directly with the engineering team. It's best to reserve this for real bugs, but it's also appropriate to make usability / functional requests there too. <http://bugreporter.apple.com> Your issue where you can repeatably break a known function is clearly a bug and might get resolved much faster through the bug channel. You can upload specifics of your hardware and steps to reproduce and honest bugs get resolved quite efficiently through this channel.
Me too I use a lot the screen zooming and I'm quite annoyed by this small bug. In addition to the solutions already provided, I've found out that playing a bit with "System preferences" -> "Universal Access" solves the problem (until it appears next time). From this screen, after playing a bit with the options about Zooming and testing with ctrl-2fingers, I get the feature back, then it doesn't really matter if I set the zoom on or of: it keeps working. This behavior is quite odd indeed, but at least I don't have to restart services or reboot.
57,714,549
Just wanted to ask generic question about Namespaces. If class A inherits class B and doesn't explicitly reference (`using`) B's namespace, do I have to explicitly `using B` namespace in my calling code to call B's methods from an instance of A? Is this language dependent (C#, C++)? Ex in C#: ``` // Namespace X class A : B { public void methodA(){...} } // Namespace Y class B { public void methodB(){...} } ``` In other code using A: ``` using X; // do I need using Y? ... A obj = new A(); obj.methodB(); // calls methodB() using instance of A ... ```
2019/08/29
[ "https://Stackoverflow.com/questions/57714549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2898852/" ]
No namespaces are not inherited by classes in C++ (and in C#). However due to the ADL (Argument Dependent Lookup) you can "inherit" some names from the namespace of a base class. Here is a demonstrative program ``` #include <iostream> namespace N1 { struct A {}; void f( const A & ) { std::cout << "N1::f( const A & )\n" << '\n'; } } namespace N2 { struct B : N1::A { B() { f( *this ); } }; } int main() { N2::B b; return 0; } ``` Its output is ``` N1::f( const A & ) ``` To "inherit" a namespace you can use the using directive in a namespace or in a block scope. For example ``` namespace N1 { struct A {}; } namespace N2 { using namespace N1; struct B : A { }; } ``` Take into account that you may not use the using directive in a class scope. Or you can introduce only some names by means of a using declaration.
No, there is no such thing as a inherited namespace. Namespace does not have anything that can be derived/inherited. If you want to inherit a class A that is in different namespace, you need to add "using namespace ..."
6,918,185
I would like to test if the right phone number was enterred in the text field. The phone number should be ddd-ddddddd which means 3digits then must have "-" and then 7 digits. How do I set the regular expression for that ? Thanks :)
2011/08/02
[ "https://Stackoverflow.com/questions/6918185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/585639/" ]
``` var phoneNumber = '123-1234567'; if(phoneNumber.match(/^\d{3}-\d{7}$/)) { alert('blah'); } ```
That's my take: ``` /^[0-9]{3}\-[0-9]{7}$/ ```
7,745,457
I've been going through the Android development tutorials and I see a lot of calls like this: ```java String date = new StringBuilder().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" ")); ``` Seems like a nice shorthand way of doing things, but is this really a good practice? Will this have any negative side effects?
2011/10/12
[ "https://Stackoverflow.com/questions/7745457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45507/" ]
Yes, that's fine - but it's not clear what you're concerned about. If you think that that's calling the `append` method during the `StringBuilder` constructor, it's not. This code is equivalent to: ``` StringBuilder tmp = new StringBuilder(); tmp = tmp.append(mMonth + 1); tmp = tmp.append("-"); tmp = tmp.append(mDay); tmp = tmp.append("-"); tmp = tmp.append(mYear); tmp = tmp.append(" "); String date = tmp.toString(); ``` Each call to `append` will actually return `this` in `StringBuilder`, but in other similar APIs the object may be immutable and each method will build a *new* object and return that... the calling code would look the same. (I assume the real code had a `toString` call, of course, otherwise it wouldn't have compiled.) Note that this is actually equivalent to: ``` String date = (mMonth + 1) + "-" + mDay + "-" + mYear + " "; ``` ... which is really rather more readable than the original code, *and does the same thing*. The Java compiler will use `StringBuilder` under the hood anyway. Of course, you should really be using `SimpleDateFormat` or Joda's `DateTimeFormatter` to format dates, of course...
No negative side affects, just makes it harder to read. A lot of developers go by the practice of the 'less code the better'.
59,456
I like the new Menlo font on Snow Leopard a lot. I tried copying it over to my Windows machine, but Windows does not like the format. Does anyone know if there's any legitimate way of getting Menlo on Windows?
2009/10/23
[ "https://superuser.com/questions/59456", "https://superuser.com", "https://superuser.com/users/15116/" ]
This may be a bit of a workaround - but the font is very similar to Bitstream Vera Sans Mono. ~~[Here is a comparison](http://www.davidkaneda.com/post/123940811/menlo-font-macosx)~~ [(**updated link**)](http://9-bits.com/post/123940811/menlo-font-macosx) of Menlo and ~~Bitstream Vera Sans Mono~~ DejaVu Sans Mono (also based on Bitstream's original). You can download the Bitstream set [absolutely free](http://ftp.gnome.org/pub/GNOME/sources/ttf-bitstream-vera/1.10/ttf-bitstream-vera-1.10.zip) (zip file).
I used [OnlineFontConverter](http://onlinefontconverter.com/) to convert the .ttc file to multiple .ttf files. There are of course copyright issues if you distribute the converted files, so please don't do it.
11,758,616
How to determine if a checkbox is check or not through xpath Currently I am trying : ``` //input[@type='checkbox' and @checked='true')] ``` I have multiple checkboxes with same ids so I have to select the next checkbox which is not selected/checked. Specifically I need this for Selenium IDE **Edit** what I actually need is sth like : ``` |storeXpathCount | //input[@name='xyz' and @checked='checked'] | is_checked | ``` if checkbox 'xyz' is checked , is\_checked value should be 1 else 0 thanks
2012/08/01
[ "https://Stackoverflow.com/questions/11758616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416100/" ]
However, there are solution without using css classes and selectors. Use ``` //input[@type='checkbox' and @checked] ``` or ``` //input[@type='checkbox' and not(@checked)] ``` instead of ``` //input[@type='checkbox' and @checked='xyz'] ```
something like this may works: ```xml //input[@checked='checked']/following-sibling::*[1][not(@checked='checked')] ```
151,917
I've been hired to teach two courses as an adjunct professor in the US (my first time teaching). I would like to review syllabi previously used for these courses, simply to inform my thinking on these courses. Is this an inappropriate request? It is likely I would ask the department head's administrative assistant for these documents. (As far as I can tell, they are not available online.)
2020/07/19
[ "https://academia.stackexchange.com/questions/151917", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/125706/" ]
The first thing I did when asked to teach already existing courses was to ask the previous lecturers for copies of syllabi, teaching materials, exams, tutorials.... Probably depends a little on office politics, but I was just handed everything in a nice manner and took over from there.
In the one department I have taught in, it was stated that you have to run the course along similar lines to previous/other instructors (some courses run w/ multiple sections so they need consistency). So absolutely, ask for the existing syllabi. And good luck with your first teaches!
91,116
> > **Possible Duplicate:** > > [How to configure a shortcut for an SSH connection through a SSH tunnel](https://serverfault.com/questions/48808/how-to-configure-a-shortcut-for-an-ssh-connection-through-a-ssh-tunnel) > > > I have a situation where I would like to have SSH/SFTP access from my workstation to a server that is not directly accessable from my workstation. I do have ssh access to a computer that is on the network which can then ssh to the server in question. How can I accomplish this?
2009/12/04
[ "https://serverfault.com/questions/91116", "https://serverfault.com", "https://serverfault.com/users/28212/" ]
Use the ProxyCommand [ssh config](http://www.openbsd.org/cgi-bin/man.cgi?query=ssh_config&sektion=5) variable. ``` Host inaccessible ProxyCommand ssh accessible nc -w1 %h %p ``` [This post](http://glandium.org/blog/?p=303) even explains a way to use a generic config so `ssh host1/host2` automatically jumps hosts for you. **Update**: Fixed the hostnames in the config snippet as per toppledwagon's comment.
WinSCP directly supports connection through an ssh tunnel. Perhaps one of the MacOS clients also provide such functionality?
9,384,227
I have the following enum ``` enum Animal implements Mammal { CAT, DOG; public static Mammal findMammal(final String type) { for (Animal a : Animal.values()) { if (a.name().equals(type)) { return a; } } } } ``` I had originally used the `Enum.valueOf(Animal.class, "DOG");` to find a particular Animal. However, I was unaware that if a match is not found, an `IllegalArgumentException` is thrown. I thought that maybe a null was returned. So this gives me a problem. I don't want to catch this `IllegalArgumentException` if a match is not found. I want to be able to search all enums of type `Mammal` and I don't want to have to implement this static '`findMammal`' for each enum of type `Mammal`. So my question is, what would be the most auspicious design decision to implement this behaviour? I will have calling code like this: ``` public class Foo { public Mammal bar(final String arg) { Mammal m = null; if (arg.equals("SomeValue")) { m = Animal.findMammal("CAT"); } else if (arg.equals("AnotherValue") { m = Human.findMammal("BILL"); } // ... etc } } ``` As you can see, I have different types of Mammal - 'Animal', 'Human', which are enums. I don't want to have to implement 'findMammal' for each Mammal enum. I suppose the best bet is just create a utility class which takes a Mammal argument and searches that? Maybe there's a neater solution.
2012/02/21
[ "https://Stackoverflow.com/questions/9384227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543220/" ]
How about creating a `HashMap<String, Mammal>`? You only need to do it once... ``` public class Foo { private static final Map<String, Mammal> NAME_TO_MAMMAL_MAP; static { NAME_TO_MAMMAL_MAP = new HashMap<String, Mammal>(); for (Human human : EnumSet.allOf(Human.class)) { NAME_TO_MAMMAL_MAP.put(human.name(), human); } for (Animal animal : EnumSet.allOf(Animal.class)) { NAME_TO_MAMMAL_MAP.put(animal.name(), animal); } } public static Mammal bar(final String arg) { return NAME_TO_MAMMAL_MAP.get(arg); } } ``` Notes: * This will return `null` if the name doesn't exist * This won't detect a name collision * You may want to use an immutable map of some description (e.g. via [Guava](http://guava-libraries.googlecode.com)) * You may wish to write a utility method to create an immutable name-to-value map for a general enum, then just merge the maps :)
You have an error in your code. If you need your function to return null when it doesn't find something, simply return it: ``` enum Animal implements Mammal { CAT, DOG; public static Mammal findMammal(final String type) { for (Animal a : Animal.values()) { if (a.name().equals(type)) { return a; } } return null; // this line works if nothing is found. } } ``` No technology will help if you would do the same error and forget to create some return value for every possible case. Your choose : Enum - EnumMaps - HashMap depends on the dynamics of your data. Enums constants can't be created in runtime. On the other hand, you don't need to check many things in runtime - compiler will do it. And you very probably will forget to check something. What Jon Skeet manages easily could give you a headache.
30,656,752
Struggling with some regex here. I'll be looping through several urls but I cannot get the regex to how to recognize revenue or cost and grab the them both. Essentially the output would look something like this: ``` import re url = ['GET /ca.gif?rb=1631&ca=20564929&ra=%n&pid=&revenue=224.00&cost=', 'GET /ca.gif?rb=1631&ca=20564929&ra=%n&pid=&revenue=224.00', 'GET /ca.gif?rb=1631&ca=20564929&ra=%n&pid=&revenue=224.00&cost=13'] values = [] for i in urls: values.append(re.search(r'(?<=revenue=)(.*?)(?=&|;)',url).group(0)) print values [[224.00, ''], '224.00', [224.00, 13]] ```
2015/06/05
[ "https://Stackoverflow.com/questions/30656752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089468/" ]
Here's how I'd go about it - using sets ``` all_words = re.findall(r'\w+', open('test.txt').read().lower()) f = open('test2.txt', 'rb') stop_words = [line.strip() for line in f] set_all = set(all_words) set_stop = set(stop_words) all_only = set_all - set_stop print Counter(filter(lambda w:w in all_only, all_words)).most_common(1) ``` This should be slightly faster as well as you do a counter on only 'all\_only' words
``` import re from collections import Counter with open('test.txt') as testfile, open('test2.txt') as stopfile: stopwords = set(line.strip() for line in stopfile) words = Counter(re.findall(r'\w+', open('test.txt').read().lower())) for word in stopwords: if word in words: words.pop(word) print("the most frequent word is", words.most_common(1)) ```
3,727,718
Compute which element $[0],[1],\ldots,[2014]$ in $\Bbb{Z}/2015\Bbb{Z}$ under the map of the Chinese remainder theorem is mapped to $([12],[5])\in\Bbb{Z}/31\Bbb{Z} \times \Bbb{Z}/65\Bbb{Z}$. $$ x=12 \pmod{31} \\ x=5 \pmod{65} $$ I used the Euclidean algorithm to find $\gcd(31,65)= 31n+65m=1$ for $n= 21$ and $m= -10$. Now $x=12 \cdot 65 \cdot (-10) + 5 \cdot 31 \cdot 21 = -7800 +3255 =-4545 = [1500]$. My question is: how do I find that $-4545= [1500]$?
2020/06/20
[ "https://math.stackexchange.com/questions/3727718", "https://math.stackexchange.com", "https://math.stackexchange.com/users/800159/" ]
$-4545=((-3)\times2015)+1500$ $ \Rightarrow -4545\equiv 1500 ($mod $2015)$
To find the equivalence class of $-4545$ in $\mathbb{Z}/2015\mathbb{Z}$, we must find $x \in \left\{0, 1, ..., 2014\right\}$ for which $k \cdot 2015 = x - 4545$ holds for some $k \in \mathbb{Z}$. By this definition, we have $-4545 \in [x]$. Clearly, this holds for $k = -3$ and $x = 1500$, so we have $-4545 \in [1500]$.
893,724
I cannot get the system to use the wireless card. As far as I can tell, it acknowledges that the thing is plugged in, and even what it is. [![](https://cdn.discordapp.com/attachments/291740981508964353/291973322537697281/IMG_20170316_123711586.jpg)](https://cdn.discordapp.com/attachments/291740981508964353/291973322537697281/IMG_20170316_123711586.jpg) However, it apparently says disabled. The only driver I could get to install without failing was this one: <https://github.com/kuttor/Asus-N53-PCU-RT5592STA-Driver-for-Linux-Kernel-4.6-Ubuntu-16.10> And I'm assuming it's installed correctly, but it's not working
2017/03/16
[ "https://askubuntu.com/questions/893724", "https://askubuntu.com", "https://askubuntu.com/users/666209/" ]
The core issue is that without an `index.html` file to serve (or a corresponding `try_files` and `index` directive) that NGINX will try and do a directory listing, which is forbidden in your config (`autoindex off;`). To override this, you should be doing at least one of ***two things***: 1. Use a `try_files $uri /index.html` directive in your specialized location block. This makes sure to not try a directory listing, but if there's a failure to find the correct URI, it will default to the root site's index page. 2. Make sure you have an `index.htm` OR `index.html` OR `index.php` file in each location (this does not apply for `proxy_pass` or `fastcgi_pass` requests which pass requests to a backend server for handling). Each directory should have an index file that is of a name that is listed in the `index` directive in your config. (You've discovered #2 yourself, however this is a more comprehensive reply)
I figured it out, I made the mistake of not putting an index.html file in the directory, once I did that everything was working.
60,191
If my iPhone gets stolen and I try to use Find my iPhone while it's off, I am given the option to be notified by email when my iPhone is found. I believe this sends an email to my iCloud account. I see 2 problems with this: 1. Since my iCloud address was automatically set up to receive email on my iPhone, the person who currently has possession of the phone will also be notified when my phone was located. They could then take measures in order to make it harder to find the phone. Ideally they wouldn't get a notification message when my phone is found. 2. My iPhone was the only place that I used to get my iCloud messages. Right now I would need to manually login to iCloud.com and check the email every so often to see if it's been located. I realize that I could use an application such as Apple's Mail app to check this account automatically, but I am not using Mail right now. I'm using Gmail instead, and would prefer to get the message at my Gmail address. Is there any way to send the email to a different address and/or bypass these 2 issues *after* the phone is stolen?
2012/08/09
[ "https://apple.stackexchange.com/questions/60191", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/218/" ]
You can setup your gmail account as default iCloud account. To do this : 1. Go to settings 2. Mail Contacts, Calenders option 3. Add new Email Account 4. Choose iCloud Account 5. Choose Get a Free Apple ID 6. When it asks for Email provide your Gmail Address 7. It will then pair your email with iCloud account so that you can use it as primary iCloud account 8. Once setup is done go to iCloud in Settings and change the account from iCloud me address to your newly setup Gmail iCloud Account Hope it helps :)
You can go to your email's settings and forward all your emails to a different email address. --- Elaborating on this further, you can set up your existing email to forward your emails to another email address which is **not** synced to your phone. You can set up the forwarding from any browser & the thief will not have access to the account.
626,105
I installed Play On Linux, because I want to install World of Tanks game. But when this game installation process starts appears this error which is in print screen. ![](https://photos-1.dropbox.com/t/2/AABZMNJh7HFXlLShaur8t7tVH6EvQVxu53Qwq8gdHrzlFw/12/269710243/png/1024x768/3/1432137600/0/2/Ekr%C4%81natt%C4%93ls%202015-05-20%2015%3A30%3A55.png/CKPnzYABIAEgAigBKAI/fuvqJGrskapmZULxqtc8knb-m-MNm_sT54t2xK7nMJE) What should I do in this situation?
2015/05/20
[ "https://askubuntu.com/questions/626105", "https://askubuntu.com", "https://askubuntu.com/users/411993/" ]
Open `wotlauncher.cfg` with gedit and change number 3 in this line with number 2 ``` <launcher_transport>3</launcher_transport> ``` and then it downloads via HTTP. Check wineHQ for other problems.
I have try playonlinux too, but it fails. There are another solution: PortWoT - <http://portwine-linux.ru/world-of-tanks-linux/> WoT have gold status in wine db, but I had unable to install it, launcher crashes. Port WoT is a solution. It keep updated for years and work fine. > > PortWoT - is the port for the client World Of Tanks 1.x (SD and HD > customers) under Linux through WINE . With a convenient and simple > graphical installer, maximum performance and native WoTtweaker `th. > > > Here are full explanation in my answer: [Will "World Of Tanks" run on Ubuntu?](https://askubuntu.com/questions/295866/will-world-of-tanks-run-on-ubuntu)
1,422,812
For a few different reasons one of my projects is hosted on a shared hosting server and developed in asp.Net/C# with **access** databases (Not a choice so don't laugh at this limitation, it's not from me). Most of my queries are on the last few records of the databases they are querying. My question is in 2 parts: 1- Is the order of the records in the database only visual or is there an actual difference internally. More specifically, the reason I ask is that the way it is currently designed all records (for all databases in this project) are ordered by a row identifying key (which is an auto number field) ascending but since over 80% of my queries will be querying fields that should be towards the end of the table would it increase the query performance if I set the table to showing the most recent record at the top instead of at the end? 2- Are there any other performance tuning that can be done to help with access tables? "Access" and "performance" is an euphemism but the database type wasn't a choice and so far it hasn't proven to be a big problem but if I can help the performance I would sure like to do whatever I can. Thanks. Edit: * No, I'm not currently experiencing issues with my current setup, just trying to look forward and optimize everything. * Yes, I do have indexes and have a primary key (automatically indexes) on the unique record identifier for each of my tables. I definitely should have mentioned that. * You're all saying the same thing, I'm already doing all that can be done for access performance. I'll give the question "accepted answer" to the one that was the fastest to answer. Thanks everyone.
2009/09/14
[ "https://Stackoverflow.com/questions/1422812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116708/" ]
As far as I know... 1 - That change would just be visual. There'd be no impact. 2 - Make sure your fields are indexed. If the fields you are querying on are unique, then make sure you make the fields a unique key.
To understand the answers here it is useful to consider how access works, in an un-indexed table there is unlikely to be any value in organising the data so that recently accessed records are at the end. Indeed by the virtue of the fact that Access / the JET engine is an ISAM database it's the other way around. (<http://en.wikipedia.org/wiki/ISAM>) That's rather moot however as I would never suggest putting frequently accessed values at the top of a table, it is best as others have said to rely on useful indexes.
13,647,481
I want to use case statement in where clause but getting error in the query below. ``` where (r.WeekId=@WeekId or @WeekId is null) and (ShiftId=@ShiftId or @ShiftId is null) and (placeid=@PlaceId or @PlaceId is null) and (r.StatusId=3) AND CASE WHEN @day = 1 THEN ((firstday=@time and (allocateddays is null or NOT (AllocatedDays LIKE '%1%')))) WHEN @day = 2 THEN ((secondday=@time and (allocateddays is null or NOT (AllocatedDays LIKE '%2%')))) WHEN @day = 3 THEN ((thirdday=@time and (allocateddays is null or NOT (AllocatedDays LIKE '%3%')))) ELSE AND (1 = 1) END ``` I am getting error at Case statement at line `CASE WHEN @day = 1`. What is going wrong with my query. Please help.
2012/11/30
[ "https://Stackoverflow.com/questions/13647481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857475/" ]
In a `WHERE` clause, the `CASE` statement can be used only to specify alternative values for a comparison like this: ``` where @day = case @SomeCondition when 1 then @Sunday when 2 then @Monday ... end ```
The line: ELSE AND (1 = 1) looks mighty suspicious. Take that out and try.
3,219
When a Non Jew does something it would work according to Halacha, however when a Jew does the same thing it is useless.
2010/10/05
[ "https://judaism.stackexchange.com/questions/3219", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/200/" ]
Negating an *avoda zara*. If a non-Jew takes an idol and says "I reject this!" and damages it, the idol is no longer prohibited from benefit. A Jew can't do that.
A non-Jew can run a kosher establishment without the certifiers worrying (as much) about him owning chametz over pesach, toveling all the kelim, etc..
5,192,785
How to get touch on a particular view. I am using ``` CGPoint Location = [[touches anyObject] locationInView:self.view ]; ``` but want to trigger the action only if an particular subView is clicked. How to do this.
2011/03/04
[ "https://Stackoverflow.com/questions/5192785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/554865/" ]
Try this ``` //here enable the touch - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // get touch event UITouch *touch = [[event allTouches] anyObject]; CGPoint touchLocation = [touch locationInView:self.view]; if (CGRectContainsPoint(yoursubview_Name.frame, touchLocation)) { //Your logic NSLog(@" touched"); } } ```
Did u try ``` CGPoint Location = [[touches anyObject] locationInView:necessarySubView ]; ```
17,740
Could you please tell me that what is the maximum length for meta keywords?
2011/08/03
[ "https://webmasters.stackexchange.com/questions/17740", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/9365/" ]
The question asked no longer makes any sense in the current environment. Google and all other major search engines like Yahoo, Bing have disqualified the Meta keyword tag long before. So even if you're adding the meta keyword tag in your webpages, Google and all other search engines are never going to take a look at that meta and you are never going to get any SEO benefit out of it. So it's better to concentrate on Title, Description, Body content of the webpage to make SEO work for you.
7 to 8 general keywords with comma separated is good to put on all pages of your site. Some peoples put huge list which is over optimization. Keywords must be related to your content or meta description.
1,145,880
Mobile safari supports an attribute on input elements called [`autocapitalize`](https://developer.apple.com/documentation/webkitjs/htmlelement/2871133-autocapitalize) [[documented here](https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/DesigningForms/DesigningForms.html)], which when set to 'off' will stop the iPhone capitalizing the text input into that field, which is useful for url or email fields. ``` <input type="text" class="email" autocapitalize="off" /> ``` But this attribute is not valid in html 5 (or another spec as far as I know) so including it in the html will produce an invalid html page, what I would like to do is be able to add this attribute to particular fields onload with javascript with something like this: ``` $(document).ready(function(){ jQuery('input.email, input.url').attr('autocapitalize', 'off'); }); ``` which adds the correct attribute in firefox and desktop safari, but doesn't seem to do anything in mobile safari, why?
2009/07/17
[ "https://Stackoverflow.com/questions/1145880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/120434/" ]
This should be fixed in iPhone OS 3.0. What version of iPhone OS are you trying this on? ``` Email: <input id="email" type="text"><br> URL: <input id="url" type="text"><br> <script> //document.getElementById("email").autocapitalize = 'off'; //document.getElementById("url").autocapitalize = 'on'; document.getElementById("email").setAttribute('autocapitalize', 'off'); document.getElementById("url").setAttribute('autocapitalize', 'on'); alert(document.body.innerHTML); </script> ```
It's just as invalid if you add it via script or if you add it in the markup. It's just that the validator isn't able to notice it if you add it via script. Just put it in the markup and put a comment next to it, like `<!-- the "autocapitalize" attribute is an Apple proprietary extension for the iPhone to change its IME behaviour -->`, that way people who look at the code in the validator will know what's up.
9,952,273
After downloading Eclipse Indigo on a clean pc, when I try to download from <http://dl.google.com/eclipse/plugin/3.7> and download SDKs and Google Plugin , at about 35% of the way through I start getting errors. ``` Install download1 An internal error occurred during: "Install download1". Comparison method violates its general contract! Install download2 An internal error occurred during: "Install download1". Comparison method violates its general contract! Install download3 An internal error occurred during: "Install download1". Comparison method violates its general contract! Installing Software An error occurred while collecting items to be installed session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=). Multiple problems occurred while downloading. Unable to write to repository: file:/C:/Users/erice/Downloads/eclipse-jee-indigo-win32-x86_64/eclipse/. C:\Users\erice\Downloads\eclipse-jee-indigo-win32-x86_64\eclipse\plugins\com.ning.async-http-client_1.6.3.201112281337.jar (Access is denied) Unable to write to repository: file:/C:/Users/erice/Downloads/eclipse-jee-indigo-win32-x86_64/eclipse/. C:\Users\erice\Downloads\eclipse-jee-indigo-win32-x86_64\eclipse\plugins\com.ning.async-http-client_1.6.3.201112281337.jar (Access is denied) No repository found containing: osgi.bundle,org.eclipse.m2e.archetype.common,1.0.200.20111228-1245 No repository found containing: osgi.bundle,org.eclipse.m2e.maven.indexer,1.0.200.20111228-1245 No repository found containing: osgi.bundle,org.eclipse.m2e.maven.runtime,1.0.200.20111228-1245 No repository found containing: osgi.bundle,org.jboss.netty,3.2.4.Final-201112281337 ``` Any clues?
2012/03/31
[ "https://Stackoverflow.com/questions/9952273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/963070/" ]
Try to run eclipse with older java version. Start Eclipse from command line with: > > D:\Eclipse\eclipse j2ee indigo>eclipse -vm C:\Java\jdk1.6.0\_31\bin\javaw.exe > > > It worked for me. (-vm is pointing to your jre instalation. Remember: Eclipse does not use JAVA\_HOME variable. it uses its own Java.)
I had a similar issue. Could not install Android Native Development Tools. Was getting this error - "An internal error occurred during: "Install download3".Comparison method violates its general contract! " I ended up installing CDT (C/C++ Development Tools) from the Helios update site. Then I could install Android Native Development Tools. Hope this helps someone
23,670,607
``` MS = 'M-SEARCH * HTTP/1.1\r\nHOST: %s:%d\r\nMAN: "ssdp:discover"\r\nMX: 2\r\nST: ssdp:all\r\n\r\n' % (SSDP_ADDR, SSDP_PORT) ``` On checking this line with [PEP8](http://pep8online.com/), it says "line too long" So I break it like this: ``` MS = 'M-SEARCH * HTTP/1.1\r\n HOST: %s:%d\r\n MAN: "ssdp:discover"\r\n MX: 2\r\n ST: ssdp:all\r\n\r\n ' % (SSDP_ADDR, SSDP_PORT) ``` But I am still getting so many errors. Please review this.
2014/05/15
[ "https://Stackoverflow.com/questions/23670607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291873/" ]
Use python's implicit string concatenation and implicit line concatenation inside unterminated brackets/parenthesis...: ``` MS = ('M-SEARCH * ' 'HTTP/1.1\r\n' 'HOST: %s:%d\r\n' 'MAN: "ssdp:discover"\r\n' 'MX: 2\r\n' 'ST: ssdp:all\r\n\r\n') % (SSDP_ADDR, SSDP_PORT) ``` Note that some ([including Guido](https://mail.python.org/pipermail/python-ideas/2013-May/020527.html)) seem to dislike implicit string concatenation. If you fall into that category, you can use *explicit* concatenation (just add a `+`'s where necessary). There's no real harm in doing this -- the bytecode optimizer will optimize the concatenation away just the same as it does with implicit concatenation.
This is the solution I think would work for now. Splitting the lines into strings. ``` MS = 'M-SEARCH *' + \ 'HTTP/1.1\r\n' + \ 'HOST: %s:%d\r\n' + \ 'MAN: "ssdp:discover"\r\n' + \ 'MX: 2\r\n' + \ 'ST: ssdp:all\r\n\r\n' % (SSDP_ADDR, SSDP_PORT) ```
22,106,766
I've googled it for hours but I can't find a solution. I use raspian, on a raspberry pi and I want to have colorscheems work on it. Default terminal in raspian seems to be set at 8 colors as when I enter ``` tput colors ``` I get 8. I'm sure there must be a way to have the term work with 256 colors but I don't know how. Anyway I set tmux in the config file to support 256 colors, so I created a .tmux.conf file in my home directory and have ``` set -g default-terminal "screen-256color" ``` now if I check with tput within tmux I get 256. Anyway I know you can set VIM to force think you support 256 color by adding ``` set t_Co=256 ``` but this seems to make no actual change. If I run this color test ``` :runtime syntax/colortest.vim ``` in normal terminal from raspian I get only 8 different colors. If I do this on tmux I get more but not all of them because some of them (red and lightred for example) still look the same.
2014/02/28
[ "https://Stackoverflow.com/questions/22106766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3366709/" ]
did you add `set t_Co=256` *after* the line `colorscheme <yourColourScheme>`? That was a problem I had early on. Let me know if you're still having trouble, because I managed to solve a similar problem (only I'm using MobaXterm and GNU screen), and wouldn't mind the excuse to dig into this a bit more.
I was having a similar problem and have solved it with the following setup. .zshrc on my OSX laptop contains: `TERM=xterm-256color` after I ssh into raspbian, `tput colors` returns 256. On raspbian, I don't have TERM explicitly set (which means it pulls it from ssh), and have the following in .tmux.conf: `set -g default-terminal "xterm-256color"` Then after I do `tmux` (and I don't even need the -2), `tputs colors` still reports 256 colors and vim looks right. I am using vanilla solarized with no edits in .vimrc or elsewhere in the vim configs.
370,793
In [the most recent welcoming blog](https://stackoverflow.blog/2018/07/10/welcome-wagon-classifying-comments-on-stack-overflow/) about comment evaluation, something caught my eye. In the sample unwelcoming comments, 3 out of 5 comments are seemingly posted by users who (almost surely, judging by the content) have already made a previous comment trying to get the OP to improve their code, but haven't got a positive response on that. A 4th is borderline that. Of course, without the actual posts, I can't judge what exactly was going on, but it seems to me these users started out sincerely trying to improve, got ignored, and then went on to use a more serious/unwelcoming tone in their comments to get their point across. I can imagine that users spotting a serious flaw, pointing it out, and getting ignored post such comments. It's obviously important to them getting their point across, and they've failed at it once. What should we recommend users do in such a situation instead of posting an unwelcoming comment? --- [Related discussion](https://meta.stackoverflow.com/q/370792/7296893) about if these comments were rightfully judged to be unwelcoming. --- Apparently, SE has chosen to change the blog post without a version history. The relevant comments from the previous version: > > * “No. As it stands the C# marshaler is going to call CoTaskMemFree to deallocate the memory. This is now rather a waste of time. You won’t listen to my advice. If you won’t work find out how the string is allocated you can’t make progress.” > * “And this is tagged Javascript why?” > * “Also, any time you have enumerated columns, you can be sure that something’s gone very, very wrong with your design. That said, you’re probably after LEAST(). But don’t do that. Fix your design.” > * “For the last time, use the serial number code and replace kIOPlatformSerialNumberKey with kIOPlatformUUIDKey“ > * “Please provide a full compilable sample if you want anyone to be able to help you: <https://stackoverflow.com/help/mcve>. I have already told how you can bind to the property. If you can’t make it work, you are doing something wrong.” > > >
2018/07/10
[ "https://meta.stackoverflow.com/questions/370793", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/7296893/" ]
> > What should we do if users don't listen to our comments pointing out severe flaws? > > > Nothing. If your comment is correct and holds true in the context of the OP your job is done. The OP will find out sooner or later that there was merit in your comment. There is no need to put users through virtual medieval interrogation techniques to make them *confess* their sins. Just make sure future visitors can understand why some practices are bad. Instead of > > **DON'T DO FOO!!** > > > explain > > It might look like that Foo() will work but that will give you a Baz{} which behaves like a Bar{} until you FuBar it. > > > Just stick to the facts and if you find your self repeating yourself and/or yelling at your screen press CTRL+W as a stress reliever.
So the scenario is: * OP posted a question which is unclear, incomplete, or otherwise not up to standard * I commented saying "X" (hopefully in a constructive and engaging way) * OP replies either ignoring "X" or saying it's not relevant or impossible or similar (At this point, FWIW, in many cases I won't have downvoted [yet], but probably have close-voted.) In that situation, I do one of two things depending on how the OP is reacting: 1. Walk away: If they're rude, or seem to be unwilling to listen, etc., I just walk away (and if they were rude, flag the rude comment). Nothing I do having said "X" to start with is going to improve the situation. 2. Engage a second time: If they seem to have genuinely misunderstood what I said, I might try explaining it a different way. If they say that it's incorrect or irrelevant, I might ask them why. Striving in both cases to be constructive and friendly. * Sometimes, when they say something isn't relevant or I'm mistaken and I ask why, I learn that *they're right*. Which is useful to both of us. * If that's not it, and they still aren't getting it, it's really situation-dependent. If I think there's someone acting in good-faith at the other end and really trying to understand, I'll stick with it, again striving to be constructive and friendly. If the person seems to be acting in bad faith, be unwilling to try things, be unwilling to accept something is true, or (bluntly) seems not up to the task of handling what they're trying to do, I'll give up, walk away, and hope that they figure it out or someone else can find a way to help where I didn't. Whenever walking away, if the question as it stands then, having given the OP a chance to bring it up to standard, is "not useful," I'll downvote it. I used to do that earlier and then reverse it if the question improved, and I totally respect people choosing to do it that way. I just decided that I wanted to take that beat first. Similarly, if the OP brings the question up to standard, I'll upvote it if appropriate and try to answer it if I know the answer and have time. When I say "constructive and friendly," that doesn't mean kid gloves. It just means I make a conscious effort *not* to be sarky, dismissive, belittling, etc. (This has not always been the case.) That way I can at least lower the odds of what I write being *read* that way. And I'm mindful that written communication lacks the **huge** amount of non-verbal information (tone, facial expression, body language) that live communication has, and so the exact same words spoken can be fine, but written can be...not fine. What I don't do (anymore): I don't say "For the last time, use the serial number code and replace `kIOPlatformSerialNumberKey` with `kIOPlatformUUIDKey`" or even a more neutrally-worded version (maybe?) like "Look, if you're not going to listen to what the people trying to help you are telling you, we can't help you." I used to say something like that when giving up. It was useful maybe 1 in 20 times, tops, and led to escalating unpleasantness the other 19 times. (And all 20 times it was stressful and unpleasant *for me*.) Eventually, I learned that and stopped doing it. Everyone's going to have their own take on it, and I respect that; this is where I currently am.
11,755,112
Its a very silly problem but somehow it is not working I have a function to create a file, if it goes through with it i want it to redirect the user to X page.. in this case 1.php.... but somehow is not working :S why? ``` //Creates File, populates it and redirects the user. if (createfile($dbFile)) { header('Location: 1.php'); } ```
2012/08/01
[ "https://Stackoverflow.com/questions/11755112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1535747/" ]
You need to [`exit()`](http://php.net/exit) after sending a redirect header: ``` if (createfile($dbFile)) { header('Location: http://yoursite.com/path/to/1.php', true, 302); exit(); } ``` Otherwise, PHP continues to execute. If you `exit()`, the client receives the header right after you make the call to `header()`. You should also heed this warning on the [PHP docs page for `header()`](http://php.net/header): > > HTTP/1.1 requires an absolute URI as argument to [Location:](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30) including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use `$_SERVER['HTTP_HOST']`, `$_SERVER['PHP_SELF']` and `dirname()` to make an absolute URI from a relative one yourself: > > > ``` <?php /* Redirect to a different page in the current directory that was requested */ $host = $_SERVER['HTTP_HOST']; $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); $extra = 'mypage.php'; header("Location: http://$host$uri/$extra"); exit; ?> ```
I had a similar sounding problem where code was still being executed after the header location. That's why I always do exit(); afterwards