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
53,675,806
I'm working on accessibility and thought "I'll just make `alt` a required attribute in my project." My aim is for all `img` tags in my react app to complain if an `alt` attribute has not been provided. So, I created a `.d.ts` file where I have added the following: ``` import { HTMLAttributes } from 'react'; declare module 'react' { export interface ImgHTMLAttributes<T> extends HTMLAttributes<T> { alt: string; } } ``` I'm getting these errors: > > All declarations of 'alt' must have identical modifiers. > > > Subsequent property declarations must have the same type. Property 'alt' must be of type 'string | undefined', but here has type 'string'. > > > Is there a way to indicate that I'm trying to *override*, and not *extend*? Or is there a better way to go about this?
2018/12/07
[ "https://Stackoverflow.com/questions/53675806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/967405/" ]
There was an issue for this in the babel-eslint repo: <https://github.com/babel/babel-eslint/pull/523> It's recently been resolved and the fix is released in `babel-eslint@11.0.0-beta.0` [source](https://github.com/babel/babel-eslint/pull/711#issuecomment-456203896) Once `babel-eslint@11.0.0` is available, you can upgrade and plugins will be loaded from your Babel configuration file. ```js // babel.config.js module.exports = { plugins: [ "@babel/plugin-proposal-private-methods" ] }; ```
It is October now but `babel-eslint@11.0.0` still not released yet. In the meantime, you can apply the solution below, which currently working for me 1. Install theses packages * `@babel/plugin-proposal-class-properties` * `@babel/plugin-proposal-private-methods` * `@babel/eslint-parser` 2. Enable `classPrivateProperties` and `classPrivateMethods` in your `.eslintrc.json` or your `package.json` (eslintConfig) [![enter image description here](https://i.stack.imgur.com/yiJve.png)](https://i.stack.imgur.com/yiJve.png) 3. Change the parser in your `.eslintrc.js` [![enter image description here](https://i.stack.imgur.com/gCqr5.png)](https://i.stack.imgur.com/gCqr5.png) **Result:** ***I am now able to use private methods in my code without eslint error*** [![enter image description here](https://i.stack.imgur.com/7Qb3p.png)](https://i.stack.imgur.com/7Qb3p.png) ***husky pre-commit hook also work*** [![enter image description here](https://i.stack.imgur.com/4HaxW.png)](https://i.stack.imgur.com/4HaxW.png) Feel free to comment if you get any problem implementing this solution. Peace!
23,818,538
I have several files with this pattern: `prefix.1.*`, `prefix.2.*`, `prefix.3.*`, etc... and I want their name to be changed, respectively, to `prefix.01.*`, `prefix.02.*`, `prefix.03.*`, etc. With that, they will be properly sorted by name as there are filenames with already two digits (e.g. `prefix.27.*`) in the set. How can I do that using commands available in the bash shell? --- Note: Just after this issue, I had to cope with a list of files like `prefix.1.*`, `prefix.2.*`, `prefix.17.*`, `prefix.157.*` (arbitrary, not sequentially numbered), with the aim to convert to `prefix.001.*`, `prefix.002.*`, `prefix.017.*`, `prefix.157.*`, with a generic way of inserting the right number of leading zeros. If you face this situation, I strongly recommend you to follow the general solution provided by [mklement0 answer](https://stackoverflow.com/a/23940342/45375) (*More generic renaming solutions*) below.
2014/05/22
[ "https://Stackoverflow.com/questions/23818538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642012/" ]
Note a pure `bash` solution, but a little more concise(\*): ``` printf '%s\0' prefix.[0-9].* | xargs -0 -I % bash -c 'f="%"; mv "$f" "${f/\./.0}"' ``` This assumes that glob `prefix.[0-9].*` expands to at least 1 actual filename. If it's possible that NO files match, execute `shopt -s nullglob` first (and, if required, restore that shell option's value later). --- **Performance note**: While this is more *concise* than [@R Sahu's solution](https://stackoverflow.com/a/23818865/45375), it will *perform worse*, due to spawning an additional child shell (`bash -c`) for every input filename - so as to be able to assign the filename to a variable and use expansion on it. --- (\*) In terms of character count, [@R Sahu's solution](https://stackoverflow.com/a/23818865/45375) is actually shorter, but the absence of a *loop* (and fewer lines) may result in this answer being *perceived* as shorter. At the end of the day, **this solution doesn't add much in itself - except perhaps as an advanced example of using `xargs`**: * `printf '%s\0'` ensures that all matching filenames are passed through the pipeline with NUL chars. as separators. * `xargs -0` then ensures that the filenames are recognized individually, even if they contain embedded whitespace. * `-I %` ensures that *each* input filename results in its own invocation of the command that follows, with `%` instances replaced with the filename at hand. * `bash -c` then invokes a child shell (a child process that happens to be another `bash` instance) and evaluates the specified string.
Great answers so far. If the extension is same of all the files. Just use following. Here the extension is `.jpg` you can change `prefix_` to your choice of prefix. Also if you want more leading zeros just change %02 to %03 and so on. ``` rename -n -e 's/\d+/sprintf("prefix_%02d",$&)/e' -- *.jpg ```
22,252,491
I have a UIImageView, with scaling Center, so it's size changes according to the UIImage inside, however, by setting a nil UIImage, the constraints break, as no content size can be calculated **How to handle the autolayout with nil UIImage (the size should be changed to 0,0)?**
2014/03/07
[ "https://Stackoverflow.com/questions/22252491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/533422/" ]
The problem is that `UIImageView` returns {-1, -1} as intrinsicContentSize when no image is set. Use subclass of `UIImageView` with implementation like this: ``` @implementation MyImageView - (CGSize)intrinsicContentSize { if (self.image) { return [super intrinsicContentSize]; } return CGSizeZero; } @end ```
[@nikita-ivaniushchenko's answer](https://stackoverflow.com/a/26122574) gave me an idea to add `Width` constraint with `Low (250)` priority equals to `0` to `UIImageView`, so it is applied when `UIImage` is set to `nil`. ![Storyboard UIImage Constraints Example](https://i.stack.imgur.com/lZmzS.png) > > Note: I added `Width` constraint only, because there was only issue with `UIImageView`'s width in my case. Should work for both, though. > > >
33,856
I'm using Drupal 7 and Clean theme. And when created a node, show date top on node. No problem. But i want remove only hour and min. tab. How can i solve this?
2012/06/12
[ "https://drupal.stackexchange.com/questions/33856", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/6822/" ]
I think you want to have your node show *June 12, 2012* If that is the case, you can do this: ``` function THEME_preprocess_node(&$variables) { if ($variables['submitted']) { $variables['submitted'] = t('Posted: !datetime', array( '!datetime' => format_date($variables['node']->created, 'custom', 'F j, Y'))); } } ``` Here's PHP documentation for date formats: <http://php.net/manual/function.date.php>
I would disable the created date display under the content type settings, and then just add a new [date](http://drupal.org/project/date) field whose display settings you can alter just like any other field. The other option would be to change it by overriding [hook\_tokens](http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_tokens/7) in your theme. Specifically, you would override `format_date($node->created, 'medium', '', NULL, $language_code);` with your custom date format.
43,817,737
I am calling two api call in single page. but if i use one api call its working fine. But if i use two api call in same page. I'm getting below error at Runtime. > > Error Uncaught (in promise): removeView was not found`. > > > And i have one doubt too. Where ever i go to any screens. If i want to come back to my home screen. I need to show the Api called Data to display always. So should i need to call my Api call method inside constructor or `ionViewDidEnter`. i did in `ionViewDidEnter` i don't things show this may be the causes for my error. ***Here is my code :*** ``` import { Component, ViewChild } from '@angular/core'; import { AlertController, App, FabContainer, ItemSliding, List, ModalController, NavController, ToastController, LoadingController, Refresher } from 'ionic-angular'; import { CategoryDetailPage } from '../categorydetail/categorydetail'; import { ConferenceData } from '../../providers/conference-data'; import { UserData } from '../../providers/user-data'; import { SessionDetailPage } from '../session-detail/session-detail'; import { ScheduleFilterPage } from '../schedule-filter/schedule-filter'; import {Http, Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { AuthService } from '../../providers/AuthService'; @Component({ selector: 'page-speaker-list', templateUrl: 'speaker-list.html' }) export class SpeakerListPage { loading: any; data: any; Catdata: any; Catdatanames: any; resdata: any; resCatdata: any; resCatdatanames: any; loginData: {username?: string} = {}; resloginData: {username?: string} = {}; constructor( public alertCtrl: AlertController, public app: App, public loadingCtrl: LoadingController, public modalCtrl: ModalController, public navCtrl: NavController, public toastCtrl: ToastController, public confData: ConferenceData, public user: UserData, public http:Http, public authService: AuthService) { } ionViewDidEnter() { this.show(); this.another(); } show() { this.showLoader(); this.authService.subs(this.loginData).then((result) => { this.loading.dismiss(); this.data = result; if(this.data.status == 1) { this.Catdata = this.data.SubjectList; for(let i=0; i<this.Catdata.length; i++) { console.log(this.Catdata[i].SubjectName); } } else if(this.data.status == 0) { let alert = this.alertCtrl.create({ title: 'Error', subTitle: 'Please Enter Valid Username & Password', buttons: ['OK'] }); alert.present(); } }, (err) => { this.loading.dismiss(); }); } another() { this.showLoader(); this.authService.allresources(this.resloginData).then((result) => { this.loading.dismiss(); this.resdata = result; if(this.resdata.status == 1) { this.resCatdata = this.resdata.SubjectList; for(let i=0; i<this.resCatdata.length; i++) { console.log(this.resCatdata[i].FileName); } } else if(this.resdata.status == 0) { let alert = this.alertCtrl.create({ title: 'Error', subTitle: 'Please Enter Valid Username & Password', buttons: ['OK'] }); alert.present(); } }, (err) => { this.loading.dismiss(); }); } showLoader(){ this.loading = this.loadingCtrl.create({ content: 'Authenticating...' }); this.loading.present(); } } ``` Please help me out. How can solve my issue? ***My ionic info***: ``` Cordova CLI: 6.5.0 Ionic Framework Version: 3.1.1 Ionic CLI Version: 2.2.1 Ionic App Lib Version: 2.2.0 Ionic App Scripts Version: 1.3.5 ios-deploy version: 1.9.0 ios-sim version: 5.0.13 OS: macOS Sierra Node Version: v7.3.0 Xcode version: Xcode 8.3.2 Build version 8E2002 ``` Help will be much useful.Thanks
2017/05/06
[ "https://Stackoverflow.com/questions/43817737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7967576/" ]
I know this question asked more than a month ago! I was going through the same scenario with same problem and i sorted out this issue. And i have posted the [answer](https://stackoverflow.com/questions/43828359/ionic-error-uncaught-in-promise-removeview-was-not-found/44515433#44515433) in another stackoverflow [Question](https://stackoverflow.com/questions/43828359/ionic-error-uncaught-in-promise-removeview-was-not-found). Some of the [discussion and reference](https://github.com/ionic-team/ionic/issues/11443) available to get know the issue. > > ***Note:*** If you call this.loading.dismiss() manually, I don't recommend to use dismissOnPageChange, you are probably dismissing the > same loading twice. > > > I think this.loading.present() is asynchronous method., So we can't > call this.loading.dismiss() manually when this.loading.present() is > still running. > > > So if we need to dismiss manually we need to make sure that loading is > presented and have a view to dismiss it, we should use other method > after present().then like my code in below. > > > ``` public searchClick() { this.createLoader(); this.loading.present().then(() => { this.searchService.submitRequest(params, data) .subscribe(response => { this.loading.dismiss(); // Dismissing the loader manually. //Call the other function //You can dismiss loader here //You can dismiss loader in other functions too by calling it from here, Since the scope will be available to that also. }, error => { this.loading.dismiss(); this.errorMessage = <any>error }); }); } createLoader(message: string = "Please wait...") { // Optional Parameter this.loading = this.loadingCtrl.create({ content: message }); } ``` I hope this helps you out/gives you idea about your problem, if you still have the issue. [Ionic Framework ***LoadingController*** Documentation for this](http://ionicframework.com/docs/api/components/loading/LoadingController/).
I had the same error which was caused by accidentally having two handlers firing. One was part of the form as an ngSubmit attribute, the other one was on a custom save button. Removing one of the two solved it.
37,771,387
Consider the following [plunker](http://plnkr.co/edit/rJyLj077H76PdqmdRfic?p=preview) [![enter image description here](https://i.stack.imgur.com/KyaNa.png)](https://i.stack.imgur.com/KyaNa.png) I have a list of tile that I want to fade in one by one using `ng-repeat` however the animation fade the entire tile set all together. Here is my `CSS` ``` .fade-up { animation: fadeUpIn 5s ease-in-out; } .fade-in { animation: fadeUpOut 5s ease-in-out; } @keyframes fadeUpIn { 0% { opacity: 0; transform: translate3d(0, 100%, 0); } 100% { opacity: 1; transform: none; } } ``` Here is my template: ``` <div ng-controller="baseController as bCtrl"> <button ng-click="bCtrl.toggleStuff()"> Toggle </button> <div ng-repeat="group in bCtrl.groupList"> <div class="tile-style" ng-repeat="tile in group" ng-class="{'fade-up': bCtrl.display, 'fade-in': !bCtrl.display}"> {{tile}} </div> </div> </div> ``` Here is my `JS` ``` function toggleStuff() { self.display = !self.display; } ``` Is there a way to fade in the tiles individually?
2016/06/12
[ "https://Stackoverflow.com/questions/37771387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5628302/" ]
here is my pragmatic solution to eliminate newlines in Google Docs, or, more exact, to eliminate newlines from Gmail message.getPlainBody(). It looks that Google uses '\r\n\r\n' as a plain EOL and '\r\n' as a manuell Linefeed (Shift-Enter). The code should be self explainable. It might help to get alone with the newline problem in Docs. A solution possibly not very elegant, but works like a charm :-) ``` function GetEmails2Doc() { var doc = DocumentApp.getActiveDocument(); var body = doc.getBody(); var pc = 0; // Paragraph Counter var label = GmailApp.getUserLabelByName("_Send2Sheet"); var threads = label.getThreads(); var i = threads.length; // LOOP Messages within a THREAT for (i=threads.length-1; i>=0; i--) { for (var j = 0; j < messages.length; j++) { var message = messages[j]; /* Here I do some ... body.insertParagraph(pc++, Utilities.formatDate(message.getDate(), "GMT", "dd.MM.yyyy (HH:mm)")).setHeading(DocumentApp.ParagraphHeading.HEADING4) str = message.getFrom() + ' to: ' + message.getTo(); if (message.getCc().length >0) str = str + ", Cc: " + message.getCc(); if (message.getBcc().length >0) str = str + ", Bcc: " + message.getBcc(); body.insertParagraph(pc++,str); */ // Body !! var str = processBody(message.getPlainBody()).split("pEOL"); Logger.log(str.length + " EOLs"); for (var k=0; k<str.length; k++) body.insertParagraph(pc++,str[k]); } } } function processBody(tx) { var s = tx.split(/\r\n\r\n/g); // it looks like message.getPlainBody() [of mail] uses \r\n\r\n as EOL // so, I first substitute the 'EOL's with the string pattern "pEOL" // to be replaced with body.insertParagraph in the main function tx = ''; for (k=0; k<s.length; k++) tx = tx + s[k] + "pEOL"; // then replace all remaining simple \r\n with a blank s = tx.split(/\r\n/g); tx = ''; for (k=0; k<s.length; k++) tx = tx + s[k] + " "; return tx; } ```
I have now found out through much trial and error -- **and some much needed help from Wiktor Stribiżew (see other answer)** -- that there is a solution to this, but it relies on the fact that Google Script does not recognise `\n` or `\r` in regex searches. The solution is as follows: ``` function removeLineBreaks() { var selection = DocumentApp.getActiveDocument() .getSelection(); if (selection) { var elements = selection.getRangeElements(); for (var i = 0; i < elements.length; i++) { var element = elements[i]; // Only deal with text elements if (element.getElement() .editAsText) { var text = element.getElement() .editAsText(); if (element.isPartial()) { var start = element.getStartOffset(); var finish = element.getEndOffsetInclusive(); var oldText = text.getText() .slice(start, finish); if (oldText.match(/\r/)) { var number = oldText.match(/\r/g) .length; for (var j = 0; j < number; j++) { var location = oldText.search(/\r/); text.deleteText(start + location, start + location); text.insertText(start + location, ' '); var oldText = oldText.replace(/\r/, ' '); } } } // Deal with fully selected text else { text.replaceText("\\v+", " "); } } } } // No text selected else { DocumentApp.getUi() .alert('No text selected. Please select some text and try again.'); } } ``` **Explanation** Google Docs allows searching for vertical tabs (`\v`), which match newlines. Partial text is a whole other problem. The solution to dealing with partially selected text above finds the location of newlines by extracting a text string from the text element and searching in that string. It then uses these locations to delete the relevant characters. This is repeated until the number of newlines in the selected text has been reached.
52,833,259
In the folowing list: ``` tab1 = [['D001', None, None, None, 'Donald Duck', 'Organise a meeting with Scrooge McDuck', 'todo', None], ['D002', None, None, None, 'Mickey Mouse','Organise a meeting with Minerva Mouse', 'done', None], ['D003', None, None, None, 'Mickey Mouse', 'Organise a meeting with Daisy Duck', 'todo', None], [None, None, None, None, None, None, None, None]] ``` I would like to replace the None value by "..." for each sublist that is not empty I tried: ``` foo =[] for row in tab1: if row[0] is not None: for cell in row: if cell is None: cell = "..." foo.append(cell) ``` But foo gives me: ``` ['D001', '...', '...', '...', 'Donald Duck', 'Organise a meeting with Scrooge McDuck', 'todo', '...', 'D002', ... ``` Instead of: ``` [['D001', '...', '...', '...', 'Donald Duck', 'Organise a meeting with Scrooge McDuck', 'todo', '...',] ['D002', ... ```
2018/10/16
[ "https://Stackoverflow.com/questions/52833259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6239557/" ]
You were creating just one list, instead of a list of lists: ``` bar = [] for row in tab1: foo = [] if row[0] is not None: for cell in row: if cell is None: cell = "..." foo.append(cell) bar.append(foo) print(bar) ```
Traverse the list based on index values. ``` foo = tab1[:] for row in range(0,len(tab1)): if tab1[row][0] is not None: for cell in range(0,len(tab1[row])): if tab1[row][cell] is None: foo[row][cell] = "..." ```
35,000,687
I have a binary file ([link](https://drive.google.com/file/d/0BwwhEMUIYGyTWW9ndF9MNWxOQWs/view?usp=sharing)) that I would like to open and read contents of with Python. How are such binary files opened and read with Python? Any specific modules to use for such an operation.
2016/01/25
[ "https://Stackoverflow.com/questions/35000687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4576447/" ]
Here is an Example: ``` with open('somefile.bin', 'rb') as f: #the second parameter "rb" is used only when reading binary files. Term "rb" stands for "read binary". data = f.read() #we are assigning a variable which will read whatever in the file and it will be stored in the variable called data. print(data) ```
Reading a file in python is trivial (as mentioned above); however, it turns out that if you want to read a binary file and decode it correctly you need to know how it was encoded in the first place. I found a helpful example that provided some insight at <https://www.devdungeon.com/content/working-binary-data-python>, ``` # Binary to Text binary_data = b'I am text.' text = binary_data.decode('utf-8') #Trans form back into human-readable ASCII print(text) binary_data = bytes([65, 66, 67]) # ASCII values for A, B, C text = binary_data.decode('utf-8') print(text) ``` but I was still unable to decode some files that my work created because they used an unknown encoding method. Once you know how it is encoded you can read the file bit by bit and perform the decoding with a function of three.
3,927,936
Suppose I have a class like ``` class A { int x; int y; public: getSum1() const { return getx() + y; } getSum2() const { return y + getx(); } getx() const { return x; } } ``` And then I have ``` int main(int argc, char **argv) { A *a = 0; switch(argc) { case 0: a->getsum1(); break; default: a->getsum2(); break; } return 1; } ``` This program will segfault. I noticed that on my machine, when getsum1 executes, the core dump says the segfault was caused in getx, and when getsum2 executes it says the fault happened in getsum2. This makes sense. I have 2 questions: 1. is this behaviour specified, or is it implementation dependent? And most importantly: 2. Could the core dump say that the segfault happened in main, when a was dereferenced? (i.e. at a->getsum\*) Thanks.
2010/10/13
[ "https://Stackoverflow.com/questions/3927936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/371623/" ]
When you called those functions on a null pointer, you got [undefined behavior](https://stackoverflow.com/questions/2474018/when-does-invoking-a-member-function-on-a-null-instance-result-in-undefined-behav). That's really all that should be said; anything can happen, don't do it. The reason it segfaults is because there is no `A` at null. Attempting to access those members is attempting to access an invalid address. (This happens in `getx` and `getSum2`, hence the segfault report.) No, it cannot say the segfault happened in `main` because null wasn't accessed in main. (You still entered undefined behavior in main, no doubt, but in practice it just called a function with `this` set to null.) You accessed it in those functions. In practice, if a function never uses `this`, it won't crash with a null pointer. But don't.
"When is the segfault thrown?" Sometimes is **never** thrown, when should be thrown. Base of **most implementation** is Operation System with **protection of memory**. When OS is absent (embedded), or is very simply (CP/M, DOS), or has "low profile" goal (embedded), or CPU haven't such functionality (<80186) problem is hidden or delayed. It is very bad news. *Houston, we have BIG invisible problem.* Note: C++ in protected environment can realise scenarios when problem is hidden too (pointer is bad but in valid area) General rule how to understand C/C++ is key **"undefined behaviour"** (like many answers say), sometimes such exception
12,628,315
I have a 202 byte key and that is used to decrypt a binary file. ``` StringSource keyStr( key, Z3_KEY_LENGTH, true ); AutoSeededRandomPool rng; ECIES<ECP>::Decryptor ellipticalEnc( keyStr ); unsigned char *tmpBuffer( new unsigned char[ src.Size() ] ); DecodingResult dr = ellipticalEnc.Decrypt( rng, src.Data(), src.Size(), tmpBuffer ); ``` I tried to use jsafejce for this: ``` PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(key); KeyFactory factory = KeyFactory.getInstance("EC", "JsafeJCE"); PrivateKey privateKey = factory.generatePrivate(privKeySpec); Cipher eciesDecrypter = Cipher.getInstance("ECIES/SHA1/HMACSHA1", "JsafeJCE"); ``` and ``` Cipher eciesDecrypter = Cipher.getInstance("ECIESwithXOR/SHA1/HMACSHA1", "JsafeJCE"); ``` But with the first I get a block error, must be divided by 16, and with the second I get a mac check error. Does anyone have any suggestions?
2012/09/27
[ "https://Stackoverflow.com/questions/12628315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1704330/" ]
Well, I don't really know what you are trying to do in your code. I'll try and answer some of the questions. --- > > Convert ECIES ECP CryptoPP to JAVA > > > To get the point out of Crypto++, its about as hard as: ``` // Assuming your key was DER Encoded byte key[Z3_KEY_LENGTH] = ...; ECIES<ECP>::Decryptor decryptor; decryptor.BERDecodePublicKey(ArraySource(key, sizeof(key)).Ref(), false, sizeof(key)); const ECPPoint& point = decryptor.GetPublicElement(); const Integer& x = point.x; const Integer& y = point.y; ``` If your key was not DER Encoded, refer to [Keys and Formats](http://www.cryptopp.com/wiki/Keys_and_Formats) from the Crypto++ wiki. You also have the wiki page on [Elliptic Curve Integrated Encryption Scheme](http://www.cryptopp.com/wiki/Elliptic_Curve_Integrated_Encryption_Scheme). Java 7 provides and [ECPoint class](http://docs.oracle.com/javase/7/docs/api/java/security/spec/ECPoint.html), and it takes an X and Y coordinate. --- ``` > ECIES<ECP>::Decryptor ellipticalEnc( keyStr ); > unsigned char *tmpBuffer( new unsigned char[ src.Size() ] ); > DecodingResult dr = ellipticalEnc.Decrypt( rng, src.Data(), src.Size(), tmpBuffer ); ``` This does not look quite right, but you have not showed enough code. ``` size_t maxLength = decryptor.MaxPlaintextLength( src.Size() ); unsigned char *tmpBuffer = new unsigned char[ maxLength ]; DecodingResult dr = ellipticalEnc.Decrypt( rng, src.Data(), src.Size(), tmpBuffer ); if( !result.isValidCoding ) throw runtime_error("failed to decrypt cipher text"); unsigned char *buffer = new unsigned char[ result.messageLength ]; std::cpy(tmpBuffer, buffer, result.messageLength); ```
Have you tried adding some empty bytes to the end of your key so that it is 208 bytes long? That might fix your block size error.
18,130,548
i'd like to store into a mailbox table the folder, the message should be inside as an int. Like 0 is inbox, 1 is outbox, ... Is there a way to make the result of the query give me back a result like 'INBOX' for the stored value of 0? Greetings
2013/08/08
[ "https://Stackoverflow.com/questions/18130548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You may store them as `ENUM('INBOX', 'OUTBOX')`. They will be stored as integers. It'll be possible to write them as strings and as integer representation. They will be read as text by default.
You can use a nested IF statement: ``` select if(folder=0, 'Outbox', if(folder=1, 'Inbox', 'Sent')) as folder, msg_id,... from messages; ```
23,283,853
I am unable to figure out reason for NullPointer exception in my Spring project. Sometime project works fine but some time its throwing null pointer Exception here is full stacktrace. ``` org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NullPointerException org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:585) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:322) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:184) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:155) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) root cause javax.servlet.ServletException: java.lang.NullPointerException org.apache.jsp.redirect_jsp._jspService(index_jsp.java:72) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:322) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:184) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:155) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) root cause java.lang.NullPointerException org.apache.catalina.session.ManagerBase.generateSessionId(ManagerBase.java:807) org.apache.catalina.session.ManagerBase.createSession(ManagerBase.java:653) org.apache.catalina.connector.Request.doGetSession(Request.java:2892) org.apache.catalina.connector.Request.getSession(Request.java:2315) org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:898) org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:910) javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238) javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238) org.apache.jasper.runtime.PageContextImpl._initialize(PageContextImpl.java:146) org.apache.jasper.runtime.PageContextImpl.initialize(PageContextImpl.java:125) org.apache.jasper.runtime.JspFactoryImpl.internalGetPageContext(JspFactoryImpl.java:112) org.apache.jasper.runtime.JspFactoryImpl.getPageContext(JspFactoryImpl.java:65) org.apache.jsp.redirect_jsp._jspService(redirect_jsp.java:53) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:322) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:184) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:155) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) ``` I am also getting permgenspace error very often. is it related to this? I changed my project and tomcat VM option (Using NetBean IDE) to: ``` -XX:MaxPermSize=512m ``` I am using Netbeans IDE 7.3.1 , Apache Tomcat 7.0.37, Spring 3.1.1, Hibernate 3. Its showing DelegatingFilterProxy in Exception. May be its because of security setting. ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <!-- This is where we configure Spring-Security --> <security:http auto-config="true" use-expressions="true" access-denied-page="/auth/denied" > <security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/> <security:intercept-url pattern="/auth/**" access="hasRole('ROLE_USER')"/> <security:form-login login-page="/index" authentication-failure-url="/index" default-target-url="/welcome" /> <security:logout invalidate-session="true" logout-success-url="/index" /> </security:http> <!-- A custom service where Spring will retrieve users and their corresponding access levels --> <bean id="loginService" class="com.tcs.ignite.ih.spring.service.LoginService"/> <!--A service where spring will redirect to proper view after successfull login--> <!--<bean id="loginSuccessHandler" class="com.tcs.ignite.ih.spring.controller.LoginSuccessHandler" />--> <!-- Declare an authentication-manager to use a custom userDetailsService --> <security:authentication-manager> <security:authentication-provider user-service-ref="loginService"> </security:authentication-provider> </security:authentication-manager> </beans> ``` **UPDATE :** When I am trying to access index file,welcome file for application defined in web.xml, with following URL ``` localhost:8080/xxxx/index ``` I recieve following on browser: ``` HTTP Status 500 - Could not get RequestDispatcher for [/WEB-INF/jsp/index.jsp]: Check that the corresponding file exists within your web application archive! ``` index.jsp in present in my directory. Do i need to define mapping in spring security intercept url tag for /index?
2014/04/25
[ "https://Stackoverflow.com/questions/23283853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3413684/" ]
The exception actually comes when the redirect page requires session and the page context setup machanism (PageContextImpl.java:146) tries to create a session. However the session id generator is somehow null this time ``` ManagerBase.java:807..... protected String generateSessionId() { String result = null; do { if (result != null) { duplicates++; } result = sessionIdGenerator.generateSessionId(); //There is issue in the above line - sessionIdGenerator is null this time } while (sessions.containsKey(result)); return result; } ``` Issue like this which occurs intermittently have been reported [here](https://issues.apache.org/bugzilla/show_bug.cgi?id=54315) and there is lots of comment on the issue. See if there is some hint which can help you out.
Have you configured the view resolver in application context for the jsp? like below ``` <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/pages/" /> <property name="suffix" value=".jsp" /> <property name="exposeContextBeansAsAttributes" value="true"/> </bean> ``` if it is configured then check whether the controller has the correct definition. if above are performed correctly, then it should be with the spring security configuration.
51,544
This may seem like a weird question, but something got me thinking about it just recently. The Sun's core is composed of mainly hydrogen and helium, and is present in the form of a extremely hot supercrushed plasma. The Sun's core is mind-bogglingly dense, about 150,000 kg/m3 (about 15x denser than lead, 7x denser than uranium, 6x denser than osmium). The density can get extremely high at the center of stars. This leads me to think that the solar core, due to the immense amount of atoms packed together would behave like a extremely hard solid, as per my understanding, most dense metals (excluding gold) are extremely hard, like tungsten. I decided to dig into it a bit on the Internet, but whatever information I got were merely about the pressure at the center of the Sun, and not about the hardness of the solar core. By hardness, I mean having stiffness/rigidity, an ability to retain a certain shape when subjected to anisotropic stress. To clarify things a bit: Supposing we submerged an "indestructible" observer really deep into the Sun, just inside the solar core. Supposing we got the indestructible observer to throw a punch randomly inside the Sun, what would this observer feel? More specifically, would the observer perceive the solar core material as being extremely hard, like a solid, or would it act like an extremely viscous fluid? TL;DR **Would the solar core be extremely stiff and hard? Or would it simply behave like a dense and viscous gas?**
2023/01/08
[ "https://astronomy.stackexchange.com/questions/51544", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/47665/" ]
It is not solid. But it is hard. Its Young's modulus is about $10^{16.5}\text{ Pa}$. It is thousands or millions of times more than the Young's modulus of any ordinary solid matter. For comparison, the largest Young's modulus is approximately $10^{12}\text{ Pa}$ for diamond.
> > The Sun's core is mind-bogglingly dense, about 150,000 kg/m3 (about > 15x denser than lead, 7x denser than uranium, 6x denser than osmium). > > > Such a high pressure would compress matter into a [wigner crystal](https://en.wikipedia.org/wiki/Wigner_crystal) (but with nuclei against an electron background instead of the other way around). But the core of the sun is also mind-bogglingly *hot*. The thermal energy prevents this from happening. > > By hardness, I mean having stiffness/rigidity, an ability to retain a > certain shape when subjected to anisotropic stress. > > > No. The core of the sun is a gas and has a low viscosity. Ideal gas viscosity increases with the square root of temperature *and doesn't depend on pressure*, so a naïve ideal gas formula predicts a viscosity about 225 times more viscous than air. This is somewhere between water and cooking oil. > > Supposing we got the indestructible observer to throw a punch randomly > inside the Sun, what would this observer feel? > > > The trouble would be the *density*. Swimming would be hard, much worse than in mercury, and you could only swim or punch at the center. Each *g* of gravity gives you up to 140 *gs* of buoyant forces. And gravity rises to over a hundred *gs* (compared to "only" 27*g* at the surface) at the right distance from the center. Your *unobtanium* body would survive these extreme forces but fluid dynamics alone would dictate your posture.
10,713
I'm interested in running a promotion ... I'd like to make a product free if the customer's cart total is $10. I was able to do that with this module: <http://drupal.org/project/uc_discounts_alt> Everything is working great, but I don't want my customer to be able to add the product to their cart unless they are buying $10 worth of regular products. The products I'm giving away could be placed in another ubercart class, but I can't find a module that will allow me to prevent the node from being sold unless the cart total is $10 or more. Any ideas or help would be greatly appreciated. I've already explored the "free" checkout options; I'm really simply looking how to make a product not sellable unless the cart total has a minimum of $10.
2011/09/06
[ "https://drupal.stackexchange.com/questions/10713", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/1813/" ]
To prevent your customers to add the product to their cart if it's $10 with regular products, You can use ubercart [hook\_add\_to\_cart](http://drupalcontrib.org/api/drupal/contributions!ubercart!docs!hooks.php/function/hook_add_to_cart/6) . for example: ``` function MODULENAME_add_to_cart($nid, $qty, $data) { $contents= uc_cart_get_contents(); //check your condition such as total, and product type based on cart contents if (condition true) { $result[] = array( 'success' => FALSE, 'message' => t('Sorry, you can not add this product now!.'), ); } return $result; } ```
Learning the Rules framework could really help you here. there is an excellent tutorial [here](http://nodeone.se/en/learn-the-rules-framework) by Johan Falk just follow along and you will be able to do the above in no time.
2,389,735
The variance is defined as $$\sigma^2 = \frac{\sum\_{i=1}^n (x\_i - \bar x)^2}{n}$$ where, $\bar x = \frac{\sum\_{i=1}^n x\_i}{n}$ If someone wants to estimate this parameter from a sample (s)he must do $$s^2 = \frac{\sum\_{i=1}^n (x\_i - \bar x)^2}{n-1}$$ as the variance (as would be calculated by $\sigma^2$) of a sample decreases with the size of the sample. $s^2$ is an unbiased estimator of $\sigma^2$ only if sampling is with replacement (which is not the case in the model of interest here) or if the population is infinite. Let's call $N$ the size of the population ($n$ being the size of the sample). To the extreme, if $n=N$ (so that every individual is sampled), then $s^2$ will definitely be a biased estimator of the variance in the population. **What is an unbiased estimator of the variance of the population from a sample knowing the population size $N$?**
2017/08/11
[ "https://math.stackexchange.com/questions/2389735", "https://math.stackexchange.com", "https://math.stackexchange.com/users/87728/" ]
$\newcommand{\v}{\operatorname{var}} \newcommand{\e}{\operatorname{E}} \newcommand{\c}{\operatorname{cov}}$ The linear nature of expectation tells us that $$ \e\left( \sum\_{i=1}^n (X\_i - \bar X)^2 \right) = \sum\_{i=1}^n \e \left( (X\_i-\bar X)^2 \right) = n\e\left( (X\_1- \bar X)^2 \right) \tag 0 $$ where the second equality follows from the fact that by symmetry, all of the expectations are equal. So let us examine the expectation on the right side of the equality above. \begin{align} & \e\left( (X\_i - \bar X)^2\right) = \e(X\_i^2 - 2X\_i \bar X + \bar X^2) = \e(X\_i^2) -2\e(X\_i\bar X) + \e(\bar X^2) \\[10pt] = {} & \e(X\_i^2) - \frac 2 n \e(X\_i(X\_1 + \cdots + X\_n)) + \frac 1 {n^2} \e\left( (X\_1+\cdots+X\_n) (X\_1+\cdots+X\_n) \right). \qquad \tag 1 \end{align} So we need to know $\e(X\_i^2)$ and $\e(X\_i X\_j)$ for $i\ne j.$ We have $\e(X\_i^2) = \mu^2+\sigma^2.$ Next: $$ \e(X\_i X\_j) = \e(\e(X\_i X\_j \mid X\_j)) = \e(X\_j \e(X\_i\mid X\_j)), $$ so let us find $\e(X\_i\mid X\_j).$ \begin{align} \e(X\_i\mid X\_j=x) & = \frac{\text{sum of possible values except } x}{N-1} \\[10pt] & = \frac{\text{sum of all possible values}}{N-1} - \frac x {N-1} \\[10pt] & = \frac N {N-1} \mu - \frac x {N-1}, \end{align} so $$ \e(X\_i\mid X\_j) = \frac {N\mu - X\_j} {N-1}. $$ Therefore $$ \e(X\_i X\_j) = \e(X\_j \e(X\_i \mid X\_j)) = \e\left( X\_j \frac{N\mu-X\_j}{N-1} \right) = \frac{N\mu^2}{N-1} - \frac{\mu^2+\sigma^2}{N-1} = \mu^2 - \frac{\sigma^2}{N-1}. $$ Now we have \begin{align} \e(X\_i^2) & = \mu^2+\sigma^2 \\[10pt] \e(X\_i(X\_1+\cdots+X\_n)) & = (n-1)\left( \mu^2 - \frac{\sigma^2}{N-1} \right) + (\mu^2+\sigma^2) \\[10pt] & = n\mu^2 + \frac{N-n}{N-1} \sigma^2 \\[10pt] \e((X\_1+\cdots+X\_n)(X\_1+\cdots+X\_n)) & = n^2\mu^2 + n \frac{N-n}{N-1} \sigma^2 \end{align} Hence line $(1)$ above becomes \begin{align} & \Big(\mu^2 + \sigma^2 \Big) - \frac 2 n \left( n\mu^2 + \frac{N-n}{N-1} \sigma^2 \right) + \frac 1 {n^2} \left( n^2\mu^2 + n \frac{N-n}{N-1} \sigma^2 \right) \\[10pt] = {} & \frac{N(n-1)}{n(N-1)} \sigma^2. \end{align} Then line $(0)$ becomes $$ \frac{N(n-1)}{N-1} \sigma^2. $$ The factor by which line $(0)$ must be multiplied to get $\sigma^2$ is therefore $\displaystyle \frac{N-1}{N(n-1)}.$
The statement that $\displaystyle\sigma^2 = \frac{\sum\_{i=1}^n (x\_i - \bar x)}{n}$ is true only if each value $x\_i$ has the same probability $1/n$ and $x\_1,\ldots,x\_n$ includes every member of the population exactly once. The usual argument for the proposition that $\displaystyle \frac{\sum\_{i=1}^n (x\_i-\bar x)^2 } {n-1}$ is an unbiased estimator of the population assumes $x\_1,\ldots,x\_n$ is an i.i.d. sample from the population, and does not require equal probability assigned to all elements. In effect you are using the letter $n$ to refer to two different things, and that confuses matters. "Infinite population" should not be taken too literally. People say that in order to indicate that it's an i.i.d. sample. The point is that as the population size grows, the distribution of an i.i.d. sample and that of a sample without replacement approach each other. Suppose the population has three equally probable members, and the values of the random variable for those three are $1,2,3.$ Then the population variance is $$ \sigma^2 = \frac{(1-2)^2 + (2-2)^2 + (3-2)^2} 3 = \frac 2 3. $$ Suppose a sample of size $n=2$ is taken. Then the following are the possible samples and the unbiased sample variances $\sum\_{i=1}^2 (x\_i-\bar x)^2/(2-1)$: $$ \begin{array} {c|l|l} \text{sample} & \bar x = \text{sample mean} & s^2 = \text{sample variance} \\ \hline 1, 1 & 1 & 0 \\ 1, 2 & 1.5 & 0.5 \\ 1, 3 & 2 & 2 \\ 2, 1 & 1.5 & 0.5 \\ 2, 2 & 2 & 0 \\ 2, 3 & 2.5 & 0.5 \\ 3, 1 & 2 & 2 \\ 3, 2 & 2.5 & 0.5 \\ 3, 3 & 3 & 0 \\ \hline \end{array} $$ Observe that the average of the nine possible sample variances is $2/3,$ thus the sample variance is an unbiased estimator of the population variance. This population may be an infinite one in which $1/3$ of the members have the value $1$ for this random variable, and $1/3$ of them have $2$ and $1/3$ of them have $3$, or it may be a population with only three members. Either way, all of the above holds. One question I've answered a few times here is: Why divide by $n-1$? I won't go through that again here, but this concrete example gives us an opportunity to look at one aspect of that. First, suppose in computing the sample variances, we had looked at deviations from the population mean rather than from the sample mean. Then dividing by $n=2$ rather than $n-1=1$ would make the average of the estimates of variance equal to the population variance. Second, observe that some simple arithmetic applied to the nine cases will show you why use of the sample mean rather than the population mean makes the average estimate of variance smaller, unless you compensate by reducing the denominator from $n$ to $n-1$.
11,220,121
I basically need a way of guaranteed O(log n) deletion. Can this be done with a binary tree, or is it always worst case O(n)? What if I balance the tree everytime? please help
2012/06/27
[ "https://Stackoverflow.com/questions/11220121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/809240/" ]
If you are looking for a balanced binary tree, you could use the "heap" <http://en.wikipedia.org/wiki/Heap_(data_structure>)
You need a [Binary Search Tree](http://en.wikipedia.org/wiki/Binary_search_tree#Deletion) As the wiki page above said: *thus in the worst case it requires time proportional to the height of the tree* which means if you can make it always balanced, you can get O(logN) for deletion
386,297
$$\frac{12}{15} = 0.8\\ \frac{15}{12} = 1.25$$ If $15$ divided by $12 = 1.25$ shouldn't $12$ divided by $15$ be the same as $\frac{15}{12}$ and have the same result? Can someone please explain this step by step thank you.
2013/05/09
[ "https://math.stackexchange.com/questions/386297", "https://math.stackexchange.com", "https://math.stackexchange.com/users/76951/" ]
Are you using division as the operation? If so, then this example may help: (1) I have 12 cookies, but there are 15 people in the room. I don't have enough cookies, but if I still want to share evenly, how many cookies should each person get? (2) Now reverse, I have 15 cookies, but there are only 12 people in the room. I have more than enough cookies now. Should these people get more cookies to eat than the people in (1)?
$\frac{12}{15}$ has 15 as the divisor and thus is less than 1 and is in fact the same as $\frac{4}{5}=.8$ while the flip of this is $\frac{5}{4}=1.25$ which is the same as $1+\frac{1}{4} = 1 + 0.25$ where 12 is the divisor in this case.
33,887,289
I am working on a windows form application where i have some textboxes values and two buttons, one is **SAVE** and the other is **EDIT**. The buttons code for saving record upon **CLICK** is working very fine. But now i want to add the **keyboard shortcut** keys to SAVE and EDIT record by **pressing CTRL+S for SAVE** and **CTRL+E for EDIT**. Please help me with this. I am very new to this programming field so please be **precise** and **very clear** where to write my code in the program. Thanks
2015/11/24
[ "https://Stackoverflow.com/questions/33887289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4623453/" ]
At first, you should set the `Form.KeyPreview` property of your `Form` to `true`. Cause `Form.KeyPreview` property([as MSDN says](https://msdn.microsoft.com/en-us/library/system.windows.forms.form_properties(v=vs.110).aspx)): > > Gets or sets a value indicating whether the form will receive key > events before the event is passed to the control that has focus. > > > Then it is necessary to create an event handler for `KeyDown` event of the `Form`: ``` private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.Modifiers == Keys.Control && e.KeyCode == Keys.S) { buttonSave_Click(null, null); } if (e.Modifiers == Keys.Control && e.KeyCode == Keys.S) { buttonEdit_Click(null, null); } } ```
Add a `MenuStrip` to your form. Add two `ToolStripMenuItem` Save and Edit, attach them your EventHandler button clicks. Assign the desired values (Ctrl+S, Ctrl+E) to the `ShortcutKeys` property. If your application does not require main menu then you can hide it (`Visible` = false).
41,016,861
I need your advice on the best way to traverse through and return values from a database (as shown below). The structure of the database is set by another application. How the system currently returns the value of a user with ID=6 in this case: Look for item instance and item module (1 and training) and return the row ID. Using this row ID, look for the corresponding itemid and userid in table 2. grade\_grades [![Table1](https://i.stack.imgur.com/k3GWN.png)](https://i.stack.imgur.com/k3GWN.png) grade\_items [![Table2](https://i.stack.imgur.com/QhxMe.png)](https://i.stack.imgur.com/QhxMe.png) Current SQL / functions : function 1 { SELECT ID FROM grade\_items WHERE itemmodule = 'training' and iteminstance = '1' } (returns ID) function 2 { using returned ID, run the following: SELECT \* FROM grade\_grades WHERE itemid = '4' AND userid = '6'} (returns finalgrade) Is there an easier way of getting all of this in one MYSQL statement rather than running two queries? (The reason I am asking is because there is a potential each of these queries will run from 100 to 10000 times - depending on the number of users in the list. Currently - the server grinds to a halt for about 15 minutes if I run the query for all records (without pagenation to calculate totals)
2016/12/07
[ "https://Stackoverflow.com/questions/41016861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2381087/" ]
Just join them together : ``` SELECT g.* FROM grade_items g JOIN grade_grades g2 ON(g2.id = g.itemid) WHERE g2.itemmodule = 'training' and g2.iteminstance = '1' ``` Or alternatively , use `IN()` : ``` SELECT g.* FROM grade_items g WHERE g.itemid IN(SELECT g2.id FROM grade_grades g2 WHERE g2.itemmodule = 'training' and g2.iteminstance = '1') ```
Use **JOIN** which is combine rows from two or more tables ``` SELECT * FROM grade_grades JOIN grade_items ON grade_grades.id = grade_items.itemid WHERE itemid = 4 ```
976,754
I am having a frustrating time trying to do something with Perl that would take a couple of lines of code in C#, namely to call a web service on a Windows server that requires Integrated Windows Authentication. The most likely candidate I've found for success is a module called LWP::Authen::Ntlm, but all the examples I've googled require you to explicitly supply username, password and domain. I don't want to do that - I just want the request to use the credentials of the currently logged in user, a la CredentialCache.DefaultCredentials in .NET. Have any of you Perl gurus out there ever had to do this? Thanks.
2009/06/10
[ "https://Stackoverflow.com/questions/976754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Here's an idea: start an iexplore process to call a script on a server, since Internet Explorer uses the logged on user as a default logon when accessing servers on the same domain. Maybe you can achieve something using OLE with the Win32 Modules listed [here](http://win32.perl.org/wiki/index.php?title=Win32_Perl_Modules). Maybe the Win32::API module might be of help.
I think heeen is on a good path with Win32::API, and I suspect that you'll need to roll your own user agent to manage the NTLM handshake with the IIS server. That's not all that bad, the interaction is well understood. This smells a little like something that Samba could help you with, too. Searching around, there's a lot of buzz about using Samba + !IIS to support integrated authentication, you just need the other direction.
756
Here at Japanese SE, we see many questions along the lines of "Do you know any books/programs/websites that would help me learn XYZ in Japanese?", even though [we](https://japanese.meta.stackexchange.com/a/797/29) (and the stack exchange network [in general](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/)), are specifically not set up to handle those questions well. Inspired by [Chinese Language and Usage](https://chinese.stackexchange.com/questions/1120/resources-for-learning-mandarin-chinese)'s method for handling resource information, we decided to try it here. The idea is to provide a go-to list for those interested in resources while the discussion about whether to allow resource questions is ongoing. **Please do not create resource questions on the main site** asking for websites, books, courses, word-lists, or other "shopping recommendations", the question will be downvoted, closed and possibly deleted. [Resource related questions are off-topic](https://japanese.meta.stackexchange.com/a/797/29) for Japanese SE. **If you are looking for a particular resource** that you do not see on this list, the appropriate place to ask is almost certainly the [Japanese SE Chatroom](http://chat.stackexchange.com/rooms/511/japanese-language-and-usage). Feel free to ask in the chatroom **if you have a resource you would like to add to the list**, or if you have other questions. The small group that maintains this list overlaps quite a bit with those you will likely find in there. ### Organization * Each answer covers a particular category. * Include a short summary with each link, describing how it is useful or who it is useful to * Keep your entries as succinct as possible to maintain a easy-to-follow list format. * Don't include links to any illegal/copyright violating content, or sites that host such content. * If you are a developer/provider of the resource you are adding, follow our community [rules](https://japanese.stackexchange.com/faq#promotion) on self-promotion by including text similar to "developed/maintained by [your user account link](https://japanese.stackexchange.com/users/29/jkerian)" to the resource description. * Comments here will be fairly aggressively moderated to preserve the presentation of the list. If you have a larger comment or complaint, either talk to a moderator in the chatroom or open a meta question. ### Index * [Add-ons (browser)](https://japanese.meta.stackexchange.com/a/757/1272) * [Audio pronunciation](https://japanese.meta.stackexchange.com/a/1381/29) * [Audio resources (podcasts, audiobooks)](https://japanese.meta.stackexchange.com/a/764/29) * [Books](https://japanese.meta.stackexchange.com/a/759/1272) * [Classical/Medieval Japanese](https://japanese.meta.stackexchange.com/a/1076/29) * [Corpora](https://japanese.meta.stackexchange.com/a/1074/1478) * [Data and Japanese Analysis](https://japanese.meta.stackexchange.com/a/773/796) * [Dedicated JLPT preparation materials](https://japanese.meta.stackexchange.com/a/760/1272) * [Dictionaries (online)](https://japanese.meta.stackexchange.com/a/761/1272) * [Dictionaries (paper)](https://japanese.meta.stackexchange.com/a/1298/1478) * [Newspapers](https://japanese.meta.stackexchange.com/a/762/1272) * [Online courses](https://japanese.meta.stackexchange.com/a/763/1272) * [Pronunciation and pitch accent](https://japanese.meta.stackexchange.com/a/1496/1478) * [Software](https://japanese.meta.stackexchange.com/a/768/1272) * [Tablet & mobile apps](https://japanese.meta.stackexchange.com/a/769/1272) * [Television](https://japanese.meta.stackexchange.com/a/765/1272) * [Textbooks](https://japanese.meta.stackexchange.com/a/766/1272) * [Unreliable sites, apps, and tools](https://japanese.meta.stackexchange.com/a/2196/30454) * [Websites](https://japanese.meta.stackexchange.com/a/767/1272)
2012/04/19
[ "https://japanese.meta.stackexchange.com/questions/756", "https://japanese.meta.stackexchange.com", "https://japanese.meta.stackexchange.com/users/1272/" ]
Online Dictionaries =================== --- ### Monolingual Dictionaries * 三省堂 大辞林 第三版 *Sanseidō Daijirin, 3rd ed.* - [kotobank.jp](https://kotobank.jp/) - [weblio.jp](http://www.weblio.jp/) * 小学館 大辞泉 第二版 *Shōgakukan Daijisen, 2nd ed.* - [goo.ne.jp](http://dictionary.goo.ne.jp/jn/) - [kotobank.jp](https://kotobank.jp/) * 小学館 類語例解辞典 *Shōgakukan Ruigo Reikai Jiten* (thesaurus) - [goo.ne.jp](http://dictionary.goo.ne.jp/thsrs/) * 学研 全訳古語辞典 *Gakken Zen'yaku Kogo Jiten* (Classical Japanese) - [weblio.jp](http://kobun.weblio.jp/) * ものの数え方 *Mono no Kazoekata* (counters) - [benricho.org](http://www.benricho.org/kazu/) * 数え方単位辞典 *Kazoekata Tan'i Jiten* (counters) - [sanabo.com](http://www.sanabo.com/kazoekata/) * ニコニコ大百科 *Nico Nico Pedia* (slang) - [nicovideo.jp](http://dic.nicovideo.jp/) * はてなキーワード *Hatena Keyword* (encyclopedia) - [hatena.ne.jp](http://d.hatena.ne.jp/keyword/) * 日本辞典 *Japan Dictionary* (various) - [nihonjiten.com](http://www.nihonjiten.com) * 日本語俗語辞書 *Nihongo Zokugo Jisho* (colloquialisms) - [zokugo-dict.com](http://zokugo-dict.com/) * 故事ことわざ辞典 *Koji Kotowaza Jiten* (sayings) - [kotowaza-allguide.com](http://kotowaza-allguide.com/) * 平明四字熟語辞典 *Heimei Yoji-jukugo Jiten* (four-character idioms) - [yojijyukugo.com](http://yojijyukugo.com/) * 語源由来辞典 *Gogen Yurai Jiten* (etymology) - [gogen-allguide.com](http://gogen-allguide.com/) * 地名由来辞典 *Chimei Yurai Jiten* (place name origins) - [chimei-allguide.com](http://chimei-allguide.com/) * 類語同義語辞典 *Ruigo Dōgigo Jiten* (thesaurus) - [ruigo-tamatebako.jp](http://ruigo-tamatebako.jp/) * 違いがわかる事典 *Chigai ga Wakaru Jiten* (differences) - [chigai-allguide.com](http://chigai-allguide.com/) ### Bilingual Dictionaries * 研究社 新和英中辞典 第4版 *Kenkyūsha's New College Japanese-English Dictionary, 4th Ed.* - [excite.co.jp](http://www.excite.co.jp/dictionary/japanese_english/) - [weblio.jp](http://ejje.weblio.jp/) * 研究社 新英和中辞典 第6版 *Kenkyūsha's New College English-Japanese Dictionary, 6th Ed.* - [excite.co.jp](http://www.excite.co.jp/dictionary/english_japanese/) - [weblio.jp](http://ejje.weblio.jp/) * 小学館 プログレッシブ和英中辞典 第三版 *Shōgakukan Progressive J-E Dictionary, 3rd ed.* - [goo.ne.jp](http://dictionary.goo.ne.jp/je) - [kotobank](http://kotobank.jp/) * 小学館 プログレッシブ英和中辞典 第四版 *Shōgakukan Progressive E-J Dictionary, 4th ed.* - [goo.ne.jp](http://dictionary.goo.ne.jp/ej) - [kotobank](http://kotobank.jp/) * Jim Breen's EDICT Project - [wwwjdic](http://www.csse.monash.edu.au/%7Ejwb/cgi-bin/wwwjdic.cgi?1C) - [jisho.org](http://jisho.org) * ~~三省堂 デイリーコンサイス和英辞典 *Sanseidō Daily Concise J-E Dictionary* - [sanseido.net](http://www.sanseido.net/index.aspx)~~ (expired) * ~~三省堂 デイリーコンサイス英和辞典 *Sanseidō Daily Concise E-J Dictionary* - [sanseido.net](http://www.sanseido.net/index.aspx)~~ (expired) ### Bilingual Example Dictionaries * 英辞郎(アルク) *Eijirō at Space ALC* - [alc.co.jp](http://www.alc.co.jp/) * Weblio英語例文 *Weblio Example Sentences* - [weblio.jp](http://ejje.weblio.jp/sentence/) * 翻訳訳語辞典 *Hon'yaku Yakugo Jiten* - [dictjuggler.net](http://www.dictjuggler.net/yakugo/) * Tatoeba Project - [tatoeba.org](http://tatoeba.org/eng/) - [tangorin.com](http://tangorin.com/examples/) ### Accent Dictionaries * Online Japanese Accent Dictionary (OJAD) - [Japanese](http://www.gavo.t.u-tokyo.ac.jp/ojad/jpn/search/index/word) - [English](http://www.gavo.t.u-tokyo.ac.jp/ojad/eng/search/index/word) * Japanese Accent Study Website - [Japanese](http://accent.u-biq.org/) - [English](http://accent.u-biq.org/english.html) ### Other Dictionaries and Tools * Wiktionary - [Japanese](http://ja.wiktionary.org/w/index.php?search=&title=Special%3ASearch) - [English](http://en.wiktionary.org/w/index.php?search=&title=Special%3ASearch) * Kanjigen Character Etymology Tool - [namakajiri.net](http://namakajiri.net/kanjigen)
Learning Classical and Medieval Japanese ======================================== * [Getting started with Edo literature](http://no-sword.jp/blog/2011/01/reading.html) * [文語 Bungo](http://kafkafuura.wordpress.com/classical-japanese/) * [Reading kuzushiji, kanbun, and other premodern Japanese](http://avery.morrow.name/blog/2013/09/reading-kuzushiji-kanbun-and-other-premodern-japanese/) * [Introduction to kuzushiji 崩し字](http://naruhodo.weebly.com/1/post/2012/01/introduction-to-kuzushiji.html) * くずし字学習支援アプリ KuLA (Kuzushiji Learning Application) for [iPhone](https://itunes.apple.com/jp/app/kuzushi-zi-xue-xi-zhi-yuanapurikula/id1076911000) or [Android](https://play.google.com/store/apps/details?id=yuta.hashimoto.kula) * 変体仮名あぷり/The Hentaigana App for [iPhone](https://itunes.apple.com/jp/app/bian-ti-jia-mingapuri/id1053735914) or [Android](https://play.google.com/store/apps/details?id=edu.waseda.hentaigana) * [木簡庫 Wooden Tablet Database](http://r-jiten.nabunken.go.jp/) * [漢字字体規範史データセット](http://hng-data.org/) + ~~[漢字字体規範史データベース](http://www.joao-roiz.jp/HNG/search/start)~~ (offline) * [Weblio古語辞典](http://kobun.weblio.jp/)
36,908,161
I'm trying to print a char array after a for loop to see the output to make sure it's correct. However, it won't print the string. Why won't it print the string? Am I missing something? It prints the index println string but not the Tag bit won't print. What am I missing? Here is my code ``` char *getTag(char *address){ char *binary, *resultsIndex, *resultsTag, *resultsOffset; char* tags; int i, j, t; printf("Get Tag function\n"); binary = hexToBin(address); printf("Binary : %s\n", binary); printf("Tag : %i\n", TAG); printf("Offset : %i\n", OFFSET); /*Seperate index, tag and offset*/ i = 0; resultsIndex = (char * )malloc(sizeof(char) * INDEX); for(i = 0; i < INDEX; i++){ resultsIndex[i] = binary[i]; } resultsTag = (char * )malloc(sizeof(char) * TAG); //resultsTag = '\0'; for(t = INDEX; t < TAG + 1; t++){ resultsTag[t] = binary[t]; printf("binary[i] %c\n", binary[t]); printf("resultsTag[i] %c\n", resultsTag[t]); //<----prints individual character } printf("Index bit: %s\n", resultsIndex); printf("Tag Bit %s", resultsTag); //<-----Won't print the string return resultsTag; } ``` I tried googling the problem and have tried some of the methods. One to make resultsTag[t] = '\0'. I tried that and it won't print still. Is something wrong with my for loop that can cause that? It prints the individual character inside the loop, so I can see that it is storing it but it won't print it outside the loop. Any advice that could be helpful?
2016/04/28
[ "https://Stackoverflow.com/questions/36908161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5386926/" ]
You write to`resultTag` starting from an offset `INDEX`, but attempt to print it from the initialised start. If the start happens to contain zero, it will print nothing. Moreover, the final print does not end in a *newline* and the output stream is not flushed so will not be displayed immediately on some systems.
You need to flush stdout, or add a \n (stdout autoflush on new-line) ``` printf("Tag Bit %s\n", resultsTag); //<-----Won't print the string fflush (stdout); ```
16,193,499
I need a select statement which always returns at least one record. Something like this ``` SELECT id, date FROM mytable WHERE id = <INPUT_ID> AND date = <INPUT_DATE> UNION ALL SELECT VALUE_FROM_FILTER(id), VALUE_FROM_FILTER(date) WHERE NOT EXISTS (SELECT * FROM mytable WHERE id = <INPUT_ID> AND date = <INPUT_DATE>) ``` So should the query return 0 rows, it returns at least one row with the input values. Is this possible in SQL? I'm using Oracle 10.2 `<INPUT_ID>` and `<INPUT_DATE>` is just a replacement for any unknown values (based on answers and comments I modified the question to be more obvious)
2013/04/24
[ "https://Stackoverflow.com/questions/16193499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970707/" ]
> > Do I have to iterate "manually" through all rows to find these max and > min values? > > > Define *manually*. Yes, you have to calculate the `Min` and `Max` values by enumerating all `DataRows`. But that can be done either with the old `DataTable.Compute` method or with [**Linq**](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.min.aspx): ``` int minVal = table.AsEnumerable().Min(r => r.Field<int>("ColName")); int maxVal = table.AsEnumerable().Max(r => r.Field<int>("ColName")); ``` [`DataTable.Compute`](http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx): ``` int maxVal = (int)table.Compute("Max(ColName)", ""); ```
Try this: ``` var min = myTable.AsEnumerable().Min(x => (int)x["column"]); var max = myTable.AsEnumerable().Max(x => (int)x["column"]); ``` You'll need to make sure you have a reference to `System.Data.DataSetExtensions`, which is not added to new projects by default.
7,253,217
I'm making a WP7 app, which is consuming an ASMX which I can't touch, nor adapt, since I'm not the creator, nor the provider, I'm just consuming it. When I add the service reference to my WP7 solution (not mango - but it's the same behaviour in mango), I'll uncheck the "Reuse types in referenced assemblies" because I don't care about those. Side Note: Even when I leave that checkbox checked it doesn't work either. Then I add the following code to the constructor of a new WP7 page : ``` MobileWS.WebServiceSoapClient ws = new MobileWS.WebServiceSoapClient("WebServiceSoap", "http://www.somewhere.com/MobileService.asmx"); ws.getCountriesCompleted += new EventHandler<MobileWS.getCountriesCompletedEventArgs>(OnGetCountriesCompleted); ws.getCountriesAsync("fr"); ``` This goes out and fetches an array of Country objects ("fr" stands for "french", so it'll be "Etas Unis" instead of "United States")... at least that's the idea. I even checked with Fiddler2 if it returned anything, and indeed, the ASMX responds with some XML that contains the countries. Then my handler goes like this : ``` private void OnGetCountriesCompleted(object sender, MobileWS.getCountriesCompletedEventArgs e) { if (e.Cancelled == false && e.Error == null && e.Result != null) { List<MobileWS.Country> countries = e.Result.ToList<MobileWS.Country>(); CountriesListBox.ItemsSource = countries; } } ``` Unfortunatly the e.Result always returns an empty array of country objects (so non at all, but he knows there should be country objects in there, but there are 0 items in the array) ! Though, if I browse to : <http://www.somewhere.com/MobileService.asmx> I get the list when I invoke the getCountries function. Even more strange, when I copy and past the exact same code in a WPF application it works like a charm, I get a filled array with 7 country objects in. What's wrong ? I'm refusing to parse the returned XML myself so far, but I'm feeling I will need to sooner or later because of this fail. --- I'm pretty sure that the XML that is send back is correct, else the WPF application would have similar problems, no ? So, looks like I'm doomed to parse it myself, then ? I see a lot of examples on the web where they do that (parsing the XML result themselfs), so there must be a reason for that, and that reason is the one I describe above :).
2011/08/31
[ "https://Stackoverflow.com/questions/7253217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/921042/" ]
What's happening here is that the sum is being evaluated from left to right and this is causing a different type of addition to be performed than what you would expect. In C#, you can add two strings. If you add `"foo"` to `"bar"` then this will give you the string `"foobar"`. If you add a string and a number together, then it will convert the number to a string and add the two strings together. So `"foo"+13` yields `"foo13"`. So what's happening in your example is quite complicated. Starting from the inside, you have: `int.Parse(textBox3.Text)`. This takes `textBox3.Text` which is `"2"` and converts it to the number `2`. Next you do `textBox2.Text + (int.Parse(textBox3.Text)` which gets the string `"1"` and then adds the number 2 to it. This causes the number `2` to be converted to the string `"2"` and then adds `"1"+"2"`, giving the string `"12"` as the answer since strings are added by joining them. Next you do `int.Parse(textBox2.Text + (int.Parse(textBox3.Text))` which converts the string `"12"` to the number `12`. You also do `int.Parse(textBox1.Text)` which gives the number `0`. So at this point you're adding `"" + 0 + 12`. It does this from left to right, first adding `""` to `0`. This causes `0` to be converted to `"0"` and `"" + "0"` gives `"0"`. Then we are adding `"0" + 12`. When we do this, `12` gets converted to `"12"` and `"0"+"12"` gives `"012"`. Without making big changes, you could get the correct result just by changing your parentheses. If the numbers were all added together before any of them are added to strings, then you'll get the correct result. We can accomplish this with parentheses. ``` textBox4 = "" + (int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text)); ``` In short, it's really important to pay attention to what's happening in what order and what the types are because adding two strings is completely different from adding two numbers.
You have 2 problems here. The first one is the "" at the beginning. When you do the first +, textBox1.Text is first parsed, then converted to string again by the string concatenating operator. I'd prefer something like this: ``` textBox4.Text = (int.Parse(textBox1.Text) + int.Parse(textBox2.Text) + int.Parse(textBox3.Text)).ToString(); ``` The second problem (the real one) is the fact that you miss a closing parenthesis after textBox2.Text. In this way you are first concatenating textBox1.Text ("1") and int.Parse(textBox2.Text).ToString() ("2"), and only at this point you parse the result. If the parenthesis were not missing your code would give "3" and not "012"
77,817
Why are the names of these letters so different from how they are actually used in words ? 1. **F** - there are no words that start with an "F" that use the pronunciation "ɛf". 2. **L** - there are no words that start with an "L" that use the pronunciation " ɛl" Similarly, **M** (ɛm), **N** (ɛn), **H** (etʃ), **R** (ɑr), **S** (ɛs), **W** (dəbəlju), **x** (ɛks), **Y** (waj) and **Z** (zɛd). Apart from **Z**, which can be pronounced as 'zi', why are the names so different from how it is pronounced in words ? Examples for other alphabets with words that have the same (almost) pronunciation as its name : Ace, Beware, Cease, Deep, Eagle, Genes, Ice, Jail, Keratin, Oath, Piece, Queue, Tea, Unisex, Veal, X-ray.
2016/01/04
[ "https://ell.stackexchange.com/questions/77817", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/27122/" ]
The names of most consonants in English contain a common sound of the consonant, plus enough of a vowel sound that the name is a syllable. In some consonant names, the vowel sound precedes the consonant sound. In other consonant names, the vowel sound follows the consonant sound. There are three exceptions. "H"'s name has drifted away from its pronunciation. The names of "W" and "Y" match how they are written. Consonant sounds at the start of the consonant name: `. B C D G J K P Q T V Z` Consonant sounds at the end of the consonant name: `. F L M N R S X` Vowels: `. A E I O U` There are only three exceptions: `. H W Y` * H: Spanish pronounces its "j" as "[hota](http://www.spanishdict.com/guide/spanish-alphabet-pronunciation)", so it would be possible to pronounce "H" using its consonant sound + a vowel sound. According to <https://infogalactic.com/info/H>, the name has mutated over time. In Latin, "k" and "h" used to have similar sounds. The name of "H" picked up the "k" sound. The "k" sound in the name of "H" then mutated to be a "ch" sound in Old French. Various English speakers use a similar variety of pronunciations when pronouncing the "c" in the Latin word *[pace](https://ell.stackexchange.com/questions/43593)*. * W: This letter is named for how it is written -- as a doubled "U" or "V". * Y: This letter is also named for how it is written -- as a combination of "V" and "I". According to <https://infogalactic.com/info/Y>, the Romans borrowed the letter "Upsilon" from Greek twice -- once as the letter "v", and once as a "Greek i".
This answer might complement the previous ones. Names of letters should be taught with less strenght than sounds, we may say. Which is important is to know how a sound correspond with a particular symbol, and the inverse in order for the language to be complete. In any alphabet we write some symbols: > > a, b, c, d, e, f, g... > > > and assign each symbol a sound. **But** in our alphabetic system we can't pronounce consonants, so in order to speak about them we combine it with a vowel, and this gives birth to 'names'. We can define a name as: consonant (sound) + vowel (sound). (I think this answers part of the question) **Example** So although *c* has a sound (and really this is not an unique sound), we name it differently to speak about it, and we say c(name)= c(sound) + e(sound). **Curiosity** There is a strange case. When we speak about Greek alphabet even vowels have names, but this, I believe, is a different story. So when we want to speak about letters we use names, but they aren't completely related to the sound, as was pointed out.
16,171,223
I have an issue with [the site](http://jsfiddle.net/Jxrw7/2) I am working on. The top logo seems to have some kind of margin to the top, even though I have specifically set it to have no margin and its parents' have no padding. ``` body{ margin: 0; padding: 0; min-width: 320px; background-image: url('../images/templates/background.png'); font-family: 'Open Sans'; font-size: 12px; color: #303030; } ``` Here's an image with different browsers I tested: ![odd margins](https://i.imgur.com/bnbf8aj.png) As you can see, only Opera seems to work properly. Now is there anything wrong in it? Or is it an issue of browsers? If this is an issue with browsers, what would be the easiest way to solve the issue?
2013/04/23
[ "https://Stackoverflow.com/questions/16171223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It's line 98 in main.css thats causing your issue. ``` .menuAvatar { vertical-align: middle; // THIS LINE margin: 0 5px 0 -15px; } ``` When vertical align is removed the image aligns correctly. You can either find a different way to accomplish what you are using the `vertical-align` for, or you can use the following ways to compensate. ``` .menuAvatar { vertical-align: middle; margin: -3px 5px 0 -15px; } ``` I added -3px to margin-top to force it to align back in Chrome. (not tested in firefox and others). OR use this to avoid negative margins. ``` .menuAvatar { vertical-align: top; margin: 0 5px 0 -15px; } ```
On line 98 of `main.css`, you have the following rule: ``` .menuAvatar{ vertical-align: middle; margin: 0 5px 0 -15px;; } ``` I would recommend setting `vertical-align` to `top`, resulting in: ``` .menuAvatar{ vertical-align: top; margin: 0 5px 0 -15px; } ```
779,642
We had a file in our repository that we deleted several revisions ago. How do we get it back using TortoiseSVN without reverting our entire repository?
2009/04/22
[ "https://Stackoverflow.com/questions/779642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72631/" ]
Go to the Show Log screen, and search for the revision when the file was deleted, then right click the file and select **Save revision to...** ![tortoiseundelete.jpg](https://dl.getdropbox.com/u/35146/stackoverflow/tortoiseundelete.jpg)
In the repo browser, there is a menu that says some to the effect of goto version. From here you can browse the field that was available in that revision and drag and drop the file out. i would check the actual program bur I'm currently on my phone. Hope this helps
19,316,178
Database: Oracle 11g I am working on a greenfield project and designing a database schema. I have an audit table which, as the name suggests, will grow to hold huge number of records eventually. Following is the table definition (after pruning the extraneous columns). ``` create table ClientAudit ( id number(19,0) primary key, clientId number(19,0) not null, createdOn timestamp with time zone default systimestamp not null ); ``` id is a natural number to be populated by oracle sequence. clientId is a unique client identifier. For ease of query by reporting, I am creating a following view as well, which gives the latest record for each client, based on createdOn: ``` create or replace view ClientAuditView as select * from ( select ca.*,max(ca.createdOn) keep (dense_rank last order by ca.createdOn) over (partition by ca.clientId) maxCreatedOn from ClientAudit ca ) where createdOn=maxCreatedOn; / ``` I am not sure what should be the partitioning key here if I were to partition ClientAudit table. Should it be ClientId, or CreatedOn? What should be the partitioning strategy?
2013/10/11
[ "https://Stackoverflow.com/questions/19316178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/846051/" ]
The key is to let your MVC application (consumer) impersonate the calling user and then issue the HTTP requests synchronously (i.e. without spawning a new thread). You should not have to concern yourself with low-level implementation details, such as NTLM vs Kerberos. Consumer ======== Configure your MVC application like so: 1. Start IIS Manager 2. Select your MVC web application 3. Double click on 'Authentication' 4. **Enable** 'ASP.NET Impersonation' 5. **Enable** 'Windows Authentication' 6. **Disable** other forms of authentication (unless perhaps Digest if you need it) 7. Open the Web.config file in the root of your MVC application and ensure that `<authentication mode="Windows" />` To issue the HTTP request, I recommend you use the excellent [RestSharp](http://restsharp.org/) library. Example: ``` var client = new RestClient("<your base url here>"); client.Authenticator = new NtlmAuthenticator(); var request = new RestRequest("Modules/5/Permissions", Method.GET); var response = client.Execute<ModulePermissionsDTO>(request); ``` Service ======= Configure your Web API service like so: 1. Start IIS Manager 2. Select your Web API service 3. Double click on 'Authentication' 4. **Disable** 'ASP.NET Impersonation'. 5. **Enable** 'Windows Authentication' 6. If only a subset of your Web API methods requires users to be authenticated, leave 'Anonymous Authentication' enabled. 7. Open the Web.config file in the root of your Web API service and ensure that `<authentication mode="Windows" />` I can see that you've already decorated your method with a `[Authorize]` attribute which should trigger an authentication challenge (HTTP 401) when the method is accessed. Now you should be able to access the identity of your end user through the `User.Identity` property of your ApiController class.
The key issue with double hop is delegation of user credential to second call. I want to elaborate a little bit about it. C1 = client browser , S1 = First Server , S2 = Second Server. Suppose our complete system support window authentication. When user access S1 from browser , its default window credential pass to server S1, but when S1 make a call to S2 , by default it don't pass credential to S2. Resolution : 1. We must enable window authentication/ impersonation on both machines. 2. WE need to enable delegation between server so that S1 can trust to S2 and will pass credential to S2. You can find some useful details at below links : http://blogs.msdn.com/b/farukcelik/archive/2008/01/02/how-to-set-up-a-kerberos-authentication-scenario-with-sql-server-linked-servers.aspx https://sqlbadboy.wordpress.com/2013/10/11/the-kerberos-double-hop-problem/
85,947
I have some questions about the Hill cipher. 1. There is a rule for key K: `Determinant of matrix and number of characters of the alphabet must be coprime.` What does this rule say? Why it must be like this? So If I had determinant 5 and characters 30, it would not work? 2. Let's assume I have key K which should be 3x3. I would get the key: ENCRYPT. I would create trigrams like ENC RYP T?? - now the last trigraph is missing two characters. Should this input key be REFUSED by application for example or should I fill it with some values like #?(# alphabet must contain this char). Or how should the application behave when this happens? 3. Let's assume I have plain text T which is: textabcd - again the same question (as 2.). I have TEX TAB CD? - (should I again insert something in that empty space (?) (for instance #) ? 4. Should HILL cipher accept MATRICES (input as matrices) or as alphabet key like ABCD?
2020/11/02
[ "https://crypto.stackexchange.com/questions/85947", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/84613/" ]
The Hill Cipher as one of the classical cipher is [invented by Lester S. Hill in 1929](https://web.archive.org/web/20110719235517/http://w08.middlebury.edu/INTD1065A/Lectures/Hill%20Cipher%20Folder/Hill1.pdf). It is the first polygraphic cipher that can operate more than one letter at a time. > > 1. There is a rule for key K: `Determinant of matrix and number of characters of the alphabet must be coprime.` What does this rule say? Why > it must be like this? So If I had determinant 5 and characters 30, it > would not work? > > > In the Hill cipher, there is an invertible matrix for the key $K$ of size $n\times n$, and the plaintexts $m\_i$'s are row vectors of size $n$. The encryption of a block $m$ is performed by $c = m K$ and the encryption of the message can be considered mathematically take $c = m K$. For decryption, multiply both sides with $K^{-1}$ and get $cK^{-1} = m K K^{-1}$ and $cK^{-1} = m I$. That is the inverse of a matrix and it is a well-known property that to be invertible a matrix must have of square size and have a non-zero determinant. If the determinant has common factors with the alphabet size then it will not have inverse since invertible matrixes must have invertible determinants. This is due to fact that we are in the composite modulus. In this case, choose a new uniform random key or choose a prime alphabet. > > 2. Let's assume I have key K which should be 3x3. I would get the key: ENCRYPT. I would create trigrams like ENC RYP T?? - now the last > trigraph is missing two characters. Should this input key be REFUSED > by application for example or should I fill it with some values like > #?(# alphabet must contain this char). Or how should the application behave when this happens? > 3. Let's assume I have plain text T which is: textabcd - again the same question (as 2.). I have TEX TAB CD? - (should I again insert > something in that empty space (?) (for instance #) ? > > > In modern Cryptography, we call it padding and the classical era has [padding also](https://en.wikipedia.org/wiki/Padding_(cryptography)#Classical_cryptography). I'm not aware that Hill proposed any padding. Fixed padding can cause serious problems with the Hill cipher since [it hasn't got known-plaintext attack security](https://crypto.stackexchange.com/q/66933/18298). Putting X or any fixed character can cause information leak about the key. Wikipedia states it very well. The messages are starting end ending with predictable ways, like `my dear ambassador, Weather report, Sincerely your` `From .. To` in the military, etc. Context can change according to the target. Therefore we need randomized padding in the beginning and at the end. This can cause confusion, too. The better one may use nonsense letters for this aim. > > 4. Should HILL cipher accept MATRICES (input as matrices) or as alphabet key like ABCD? > > > If I've understood this part correctly; first, the messages are encoded into row vectors of numbers by using the alphabet then multiplied with the key matrix $K$. The key matrix is also a number matrix, not a character. We operate on the numbers then decode the information back to character. --- **Little proof of the claim** that the determinant must have relatively prime to $n$. When $n$ is a prime it is clear that we are in a field and the determinant must be non-zero by the [Invertible Matrix Theorem](https://en.wikipedia.org/wiki/Invertible_matrix#The_invertible_matrix_theorem) The theorem also gives the general case for this as; > > In general, a square matrix over a commutative ring is invertible if and only if its determinant is a unit in that ring. > > > The units are invertible elements. For a given $u$, if $\gcd(u,n)=1$ then it has an inverse, therefore it is a unit. The converse is also true that for a given unit the $\gcd(u,n)=1$ must hold. We can see it form that $u x \equiv 1 \pmod n$ then we can form the [bezout's identity](http://B%C3%A9zout%27s%20identity) $ux+bn=1$ then we can conclude that they are relatively prime. Or directly; if $ax\equiv 1 \pmod n$, then there is a $k$ such that $ax=bk+1$, equivalently $ax−bz=1.$ If $d=\gcd(a,b)$, then $d|a$ and $d|b$, so $d|ax−bz=1$. We can conclude that $d=1$.
when you are encrypting a five letter word using a 3x3 matrix key, you are supposed to add letters X and Y to the lonely character for instance the word ENCRYPT will be ENC RYP TXY.
57,160,634
I have an issue with my site; I cannot find a way to make my content stop overlapping when the actual display size is smaller than the original display size - `1920x1080`. I would like to know how I could either scale down the whole page or just make my content not overlap. Thanks in advance for any help provided! ```js var i = 0; var txt1 ="foqjpcqkcqèckqècqq." var txt2 ="iqj0pqcjqp'cjqpjciq'pcjqi'cjqic." var txt3 ="jqopjfgoqpkfpqovmqpvqvkqpoèvkqp" var prevScrollpos = window.pageYOffset; var speed = 100; /* The speed/duration of the effect in milliseconds */ window.onload = function typeWriter() { if (i < txt2.length) { document.getElementById("about_l1").innerHTML += txt1.charAt(i); document.getElementById("about_l2").innerHTML += txt2.charAt(i); document.getElementById("about_l4").innerHTML += txt3.charAt(i); i++; setTimeout(typeWriter, speed); } if (i == 0){ } } const scrollToTop =() => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } }; scrollToTop(); ``` ```css @import url('https://fonts.googleapis.com/css?family=Oswald:500'); .wrapper{ position: relative; width: auto; margin: 0 auto; overflow-y: visible; margin:0px; } .back{ position: fixed; left: 0; top: 0; width: 100%; height: 100%; background-image: url("../media/backgif2.gif"); background-size: cover; transform-origin: 50% 50%; color: white; } .thx{ position: fixed; left:50%; transform:translateX(-50%); bottom: 15px; } hr.style-one { position: relative; bottom: 0px; border: 0; height: 1px; width: 110%:; background: #333; background-image: -webkit-linear-gradient(left, #ccc, #333, #ccc); background-image: -moz-linear-gradient(left, #ccc, #333, #ccc); background-image: -ms-linear-gradient(left, #ccc, #333, #ccc); background-image: -o-linear-gradient(left, #ccc, #333, #ccc); } .visuallyhidden{ opacity: 0; animation: fade-in-right ease 0.8s forwards; animation-delay: 0.1s; } .visuallyhidden2{ opacity: 0; animation: fade-in-right ease 0.8s forwards; animation-delay: 0.8s; } .visuallyhidden3{ opacity: 0; animation: fade-in-right ease 2s forwards; animation-delay: 1.5s; } .Lvisuallyhidden{ opacity: 0; animation: fade-in-left ease 0.8s forwards; animation-delay: 0.1s; } .Lvisuallyhidden2{ opacity: 0; animation: fade-in-left ease 0.8s forwards; animation-delay: 0.8s; } .Lvisuallyhidden3{ opacity: 0; animation: fade-in-left ease 2s forwards; animation-delay: 1.5s; } nav{ width: 100%; position: absolute; top:50px; text-align:center; } nav a{ font-family: 'Oswald', sans-serif; font-weight:500; text-transform:uppercase; text-decoration:none; color:#16151b; margin:0 15px; font-size:16px; letter-spacing:1px; position:relative; display:inline-block; } nav a:before{ content:''; position: absolute; width: 100%; height: 3px; background:#16151b; top:47%; animation:out 0.2s cubic-bezier(1, 0, 0.58, 0.97) 1 both; } nav a:hover:before{ animation:in 0.2s cubic-bezier(1, 0, 0.58, 0.97) 1 both; } iframe{ height: 250px; width: 400px; border: 2px solid #FFFFFF; } input:focus {outline:0;} p{ width: 45%; font-family: 'Oswald', sans-serif; font-size:21px;letter-spacing:1px; font-weight:500;text-transform:uppercase;text-align: left; color:#16151b; position: absolute; } @keyframes in{ 0%{ width: 0; left:0; right:auto; } 100%{ left:0; right:auto; width: 100%; } } @keyframes out{ 0%{ width:100%; left: auto; right: 0; } 100%{ width: 0; left: auto; right: 0; } } @keyframes show{ 0%{ opacity:0; transform:translateY(-10px); } 100%{ opacity:1; transform:translateY(0); } } @keyframes fade-in-right { from { opacity: 0; transform: translateX(-25px); } to { opacity: 1; transform: translateX(0); } } @keyframes fade-in-left { from { opacity: 0; transform: translateX(25px); } to { opacity: 1; transform: translateX(0); } } #div1{ height: 1200px; } #div2{ height: 500px; } #div3{ height: 500px; } #about_p{ position: absolute; text-align: center; height: 5%; width: 70%; left: 15%; top: 30%; } #about_p2{ position: absolute; left: 50%; top: 95%; } #bar1{ position: absolute; width: 45%; max-width: 50%; height: auto; top: 39%; left :28%; border-bottom: 4px solid black; } #bar2{ position: relative; height: 135px; top: 715px; left :9%; border-left: 4px solid black; } #vid1{ position: absolute; left: 25%; top: 95%; } #vid2{ position: absolute; left: 55%; top: 150%; } #vid3{ position: absolute; left: 25%; top: 205%; } #title1{ position: absolute; font-family: 'Oswald', sans-serif; font-size:50px;letter-spacing:1px; font-weight:500;text-transform:uppercase;text-align: left; left: 5%; bottom: -10%; } #title2{ position: absolute; font-family: 'Oswald', sans-serif; font-size:50px;letter-spacing:1px; font-weight:500;text-transform:uppercase;text-align: left; left: 80%; bottom: -70%; } #title3{ position: absolute; font-family: 'Oswald', sans-serif; font-size:50px;letter-spacing:1px; font-weight:500;text-transform:uppercase;text-align: left; left: 5%; bottom: -120%; } #arrow{ position: absolute; height: 10%; left: 90%; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0"> <title>TEST</title> <link rel="stylesheet" type="text/css" href="css/inspiration.css" /> <script src="javascript/jquery-3.4.1.min.js" type="text/javascript"></script> <script src="javascript/inspiration.js" type="text/javascript"></script> </head> <body> <div id="wrapper"> <div class="back"></div> <header> <nav id="navbar"> <a href="about.html">About</a> <a href="works.html">Works</a> <a href="inspiration.html">Inspiration</a> <a href="price.html">Price</a> <a href="contacts.html">Contacts</a> </nav> </header> <div id="bar1" class="visuallyhidden2"></div> <div id="div1"> <p id="about_p" class="Lvisuallyhidden3"> <span id="about_l1">Music inspires people and I've been in</span> <span id="about_l2"><br>If those artists can inspire you too then may</span> </p> </div> <div id="div2"> <label id="title1" class="Lvisuallyhidden2">A$AP Rocky</label> <iframe id="vid1" class="Lvisuallyhidden" src="https://www.youtube.com/embed/tgbNymZ7vqY"> </iframe> <p id="about_p2" class="visuallyhidden2"> <span id="about_l3"><br>fdcjqiojqoicmqiojcopipcjqpèèpq qpoi jcqip jqè qè kq èjq èpjq q jqè jqpj pq c</span> <span id="about_l4"><br>fdcjqiojqoicmqiojcopipcjqpèèpq qpoi jcqip jqè qè kq èjq èpjq q jqè jqpj pq c </span> </p> </div> <div id="div3"> <label id="title2" class="visuallyhidden2">kzmzmzmzmzmz</label> <iframe id="vid2" class="visuallyhidden" src="https://www.youtube.com/embed/tgbNymZ7vqY"> </iframe> </div> <div id="div4"> <label id="title3" class="visuallyhidden2">Kendrick Lamar</label> <iframe id="vid3" class="visuallyhidden" src="https://www.youtube.com/embed/tgbNymZ7vqY"> </iframe> </div> <footer> <input id="arrow" type="image" src="media/arrow.png" onclick="scrollToTop()" /> </footer> </div> <a class="thx" style="background-color:black;color:white;text-decoration:none;padding:4px 6px;font-family:-apple-system, BlinkMacSystemFont, &quot;San Francisco&quot;, &quot;Helvetica Neue&quot;, Helvetica, Ubuntu, Roboto, Noto, &quot;Segoe UI&quot;, Arial, sans-serif;left: 51%;font-size:12px;font-weight:bold;line-height:1.2;display:inline-block;border-radius:3px;" href="https://www.instagram.com/manu.fma/?hl=fr" target="_blank" rel="noopener noreferrer" title="Magnolia's instagram"><span style="display:inline-block;padding:2px 3px;"><svg xmlns="http://www.w3.org/2000/svg" style="height:12px;width:auto;position:relative;vertical-align:middle;top:-1px;fill:white;" viewBox="0 0 32 32"><title></title><path d="M20.8 18.1c0 2.7-2.2 4.8-4.8 4.8s-4.8-2.1-4.8-4.8c0-2.7 2.2-4.8 4.8-4.8 2.7.1 4.8 2.2 4.8 4.8zm11.2-7.4v14.9c0 2.3-1.9 4.3-4.3 4.3h-23.4c-2.4 0-4.3-1.9-4.3-4.3v-15c0-2.3 1.9-4.3 4.3-4.3h3.7l.8-2.3c.4-1.1 1.7-2 2.9-2h8.6c1.2 0 2.5.9 2.9 2l.8 2.4h3.7c2.4 0 4.3 1.9 4.3 4.3zm-8.6 7.5c0-4.1-3.3-7.5-7.5-7.5-4.1 0-7.5 3.4-7.5 7.5s3.3 7.5 7.5 7.5c4.2-.1 7.5-3.4 7.5-7.5z"></path></svg></span><span style="display:inline-block;padding:2px 3px;">Magnolia </body> </html> ``` <https://jsfiddle.net/e6w5aLp7/>
2019/07/23
[ "https://Stackoverflow.com/questions/57160634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10647155/" ]
I'd use this more efficient version using [`String.Substring`](https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8#System_String_Substring_System_Int32_) and the [string constructor](https://learn.microsoft.com/en-us/dotnet/api/system.string.-ctor?view=netframework-4.8#System_String__ctor_System_Char_System_Int32_): ``` public static string ToCencoredString(this string str, int length = 10) { if (String.IsNullOrEmpty(str)) return str; string censored = new string('*', length); if (str.Length <= length) return censored; return censored + str.Substring(length); } ```
I suggest you use the original array for iterating so that you can make use of its index to create the mask. A `String.Join()` may help you to produce the masked output. The code would be something like this: ``` string maskedInput = String.Join("", str.Select((c, index) => index < 10? '*' : c)); ``` Here is a [working example](https://dotnetfiddle.net/1ZiWSr) for your reference
50,765,848
When I make a get request to get all tournaments I have paginated, I receive this kind of json. ``` { "data": [...], "links": {...}, "meta": {...} } ``` Now My Component, I get all the tournaments ``` getTournaments(): void { this.tournamentService.all() .subscribe(tournaments => this.tournaments = tournaments); } ``` My Service ``` all(): Observable<Tournament[]> { return this.http.get<Tournament[]>(this.listUrl) .pipe( tap(tournaments => console.log(`fetched tournaments`)), catchError(this.handleError('all', [])) ); } ``` and in my view, I fetch it like that: I can access the data in the html like that: {{ tourna`enter code here`ments['meta'].total }} it displays well on screen, but it also send me 2 errors in console: ``` TournamentsComponent.html:13 ERROR TypeError: Cannot read property 'meta' of undefined at Object.eval [as updateRenderer] (TournamentsComponent.html:13) at Object.debugUpdateRenderer [as updateRenderer] (core.js:11940) at checkAndUpdateView (core.js:11312) at callViewAction (core.js:11548) at execComponentViewsAction (core.js:11490) at checkAndUpdateView (core.js:11313) at callViewAction (core.js:11548) at execEmbeddedViewsAction (core.js:11511) at checkAndUpdateView (core.js:11308) at callViewAction (core.js:11548) View_TournamentsComponent_0 @ TournamentsComponent.html:13 proxyClass @ compiler.js:10058 push../node_modules/@angular/core/fesm5/core.js.DebugContext_.logError @ core.js:12166 push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:1647 (anonymous) @ core.js:5093 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388 push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138 push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:4021 push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:5093 (anonymous) @ core.js:4929 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388 onInvoke @ core.js:4062 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387 push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138 push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3918 next @ core.js:4929 schedulerFn @ core.js:3712 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:253 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:191 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:129 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:93 push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:53 push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3704 checkStable @ core.js:4031 onHasTask @ core.js:4075 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:441 push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:461 push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:285 push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:205 drainMicroTaskQueue @ zone.js:595 Promise.then (async) scheduleMicroTask @ zone.js:578 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:410 push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232 push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:252 scheduleResolveOrReject @ zone.js:862 ZoneAwarePromise.then @ zone.js:962 push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js:4791 ./src/main.ts @ main.ts:11 __webpack_require__ @ bootstrap:76 0 @ main.ts:12 __webpack_require__ @ bootstrap:76 checkDeferredModules @ bootstrap:43 webpackJsonpCallback @ bootstrap:30 (anonymous) @ main.js:1 TournamentsComponent.html:13 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 18, nodeDef: {…}, elDef: {…}, elView: {…}} View_TournamentsComponent_0 @ TournamentsComponent.html:13 proxyClass @ compiler.js:10058 push../node_modules/@angular/core/fesm5/core.js.DebugContext_.logError @ core.js:12166 push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:1652 (anonymous) @ core.js:5093 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388 push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138 push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:4021 push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:5093 (anonymous) @ core.js:4929 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388 onInvoke @ core.js:4062 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387 push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138 push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3918 next @ core.js:4929 schedulerFn @ core.js:3712 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:253 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:191 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:129 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:93 push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:53 push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3704 checkStable @ core.js:4031 onHasTask @ core.js:4075 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:441 push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:461 push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:285 push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:205 drainMicroTaskQueue @ zone.js:595 Promise.then (async) scheduleMicroTask @ zone.js:578 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:410 push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232 push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:252 scheduleResolveOrReject @ zone.js:862 ZoneAwarePromise.then @ zone.js:962 push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js:4791 ./src/main.ts @ main.ts:11 __webpack_require__ @ bootstrap:76 0 @ main.ts:12 __webpack_require__ @ bootstrap:76 checkDeferredModules @ bootstrap:43 webpackJsonpCallback @ bootstrap:30 (anonymous) @ main.js:1 TournamentsComponent.html:13 ERROR TypeError: Cannot read property 'meta' of undefined at Object.eval [as updateRenderer] (TournamentsComponent.html:13) at Object.debugUpdateRenderer [as updateRenderer] (core.js:11940) at checkAndUpdateView (core.js:11312) at callViewAction (core.js:11548) at execComponentViewsAction (core.js:11490) at checkAndUpdateView (core.js:11313) at callViewAction (core.js:11548) at execEmbeddedViewsAction (core.js:11511) at checkAndUpdateView (core.js:11308) at callViewAction (core.js:11548) View_TournamentsComponent_0 @ TournamentsComponent.html:13 proxyClass @ compiler.js:10058 push../node_modules/@angular/core/fesm5/core.js.DebugContext_.logError @ core.js:12166 push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:1647 (anonymous) @ core.js:5093 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388 push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138 push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:4021 push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:5093 (anonymous) @ core.js:4929 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388 onInvoke @ core.js:4062 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387 push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138 push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3918 next @ core.js:4929 schedulerFn @ core.js:3712 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:253 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:191 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:129 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:93 push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:53 push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3704 checkStable @ core.js:4031 onLeave @ core.js:4098 onInvokeTask @ core.js:4056 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:420 push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188 push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496 ZoneTask.invoke @ zone.js:485 target.(anonymous function) @ zone.js:2960 XMLHttpRequest.send (async) scheduleTask @ zone.js:2969 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407 onScheduleTask @ zone.js:297 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:401 push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232 push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:255 scheduleMacroTaskWithCurrentZone @ zone.js:1114 (anonymous) @ zone.js:3001 proto.(anonymous function) @ zone.js:1394 (anonymous) @ http.js:1932 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:161 (anonymous) @ subscribeTo.js:21 subscribeToResult @ subscribeToResult.js:6 push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub @ mergeMap.js:127 push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext @ mergeMap.js:124 push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next @ mergeMap.js:107 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:93 (anonymous) @ scalar.js:5 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe @ Observable.js:176 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:161 push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call @ mergeMap.js:80 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:158 push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterOperator.call @ filter.js:55 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:158 push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call @ map.js:51 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:158 push../node_modules/rxjs/_esm5/internal/operators/tap.js.DoOperator.call @ tap.js:60 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:158 push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchOperator.call @ catchError.js:17 push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:158 push../src/app/components/tournaments/tournaments-index/tournaments.component.ts.TournamentsComponent.all @ tournaments.component.ts:24 push../src/app/components/tournaments/tournaments-index/tournaments.component.ts.TournamentsComponent.ngOnInit @ tournaments.component.ts:36 checkAndUpdateDirectiveInline @ core.js:10097 checkAndUpdateNodeInline @ core.js:11363 checkAndUpdateNode @ core.js:11325 debugCheckAndUpdateNode @ core.js:11962 debugCheckDirectivesFn @ core.js:11922 (anonymous) @ TournamentsComponent_Host.ngfactory.js? [sm]:1 debugUpdateDirectives @ core.js:11914 checkAndUpdateView @ core.js:11307 callViewAction @ core.js:11548 execEmbeddedViewsAction @ core.js:11511 checkAndUpdateView @ core.js:11308 callViewAction @ core.js:11548 execComponentViewsAction @ core.js:11490 checkAndUpdateView @ core.js:11313 callWithDebugContext @ core.js:12204 debugCheckAndUpdateView @ core.js:11882 push../node_modules/@angular/core/fesm5/core.js.ViewRef_.detectChanges @ core.js:9692 (anonymous) @ core.js:5086 push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:5086 (anonymous) @ core.js:4929 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388 onInvoke @ core.js:4062 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387 push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138 push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3918 next @ core.js:4929 schedulerFn @ core.js:3712 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:253 push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:191 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:129 push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:93 push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:53 push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3704 checkStable @ core.js:4031 onHasTask @ core.js:4075 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:441 push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:461 push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:285 push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:205 drainMicroTaskQueue @ zone.js:595 Promise.then (async) scheduleMicroTask @ zone.js:578 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:410 push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232 push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:252 scheduleResolveOrReject @ zone.js:862 ZoneAwarePromise.then @ zone.js:962 push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js:4791 ./src/main.ts @ main.ts:11 __webpack_require__ @ bootstrap:76 0 @ main.ts:12 __webpack_require__ @ bootstrap:76 checkDeferredModules @ bootstrap:43 webpackJsonpCallback @ bootstrap:30 (anonymous) @ main.js:1 TournamentsComponent.html:13 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 18, nodeDef: {…}, elDef: {…}, elView: {…} ``` Can anyone explain me this behaviour ?
2018/06/08
[ "https://Stackoverflow.com/questions/50765848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956558/" ]
If you look at the error, it is from the component.html, You need to use safe navigation operator or \*ngIf inorder to handle the delay of response from your asynchronous request, Also since youw want to count the number of eleemnts in the arrya, change your template as, ``` {{ tournaments?.meta?.total }} ```
I cant see your html but it sounds like you need to make sure the data exists before you use it. using `*ngIf`... here are a few examples ``` <div *ngIf="tournaments"> <div *ngFor="let item of tournaments;"> <div *ngIf="item?.meta"> {{item.meta}} </div> </div> </div> ```
24,355,976
I was wondering how I can change the line length in IntelliJ. Since I use a pretty high resolution, I get that line that shows 120 characters straight through the middle of the screen. Can I change it from 120 to, say, 250?
2014/06/22
[ "https://Stackoverflow.com/questions/24355976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3685412/" ]
It seems like Jetbrains made some renaming and moved settings around so the accepted answer is no longer 100% valid anymore. **Intellij 2018.3**: `hard wrap` - idea will automatically wrap the line as you type, this is not what the OP was asking for `visual guide` - just a vertical line indicating a characters limit, default is `120` --- If you just want to change the `visual guide` from the default `120` to lets say `80` in my example: [![enter image description here](https://i.stack.imgur.com/LODn6.png)](https://i.stack.imgur.com/LODn6.png) Also you can change the color or the `visual guide` by clicking on the `Foreground`: [![enter image description here](https://i.stack.imgur.com/FUmPU.png)](https://i.stack.imgur.com/FUmPU.png) Lastly, you can also set the `visual guide` for all file types (unless specified) here: [![enter image description here](https://i.stack.imgur.com/45hqD.png)](https://i.stack.imgur.com/45hqD.png)
Open `.editorconfig` in the root of your project (or create one if you don't have any) and add: ``` max_line_length = 80 ``` The IDE should pick it up immediately (works in phpStorm, developed by the same company). As a bonus, it can be committed to GIT and will stay consistent across different editors you may be using in the future. [More info on `.editorconfig`](http://editorconfig.org).
1,370,163
Studying forcing I came across different definitions of the forcing relation $\Vdash$: * the *outer* forcing relation $\Vdash^M$ where we define $p \Vdash^M \varphi(\tau\_0,\dotsc,\tau\_n)$ to hold if for every generic $G$ with $p \in G$ we have $\varphi^{M[G]}(\tau\_0^G,\dotsc,\tau\_n^G)$. * the *inner* forcing relation $\Vdash^\*$ defined recursively using dense sets. I understand that the latter allows to speak about generic extensions within the ground model $M$ without having to deal with generic filters etc. This seems to be important because working in $M$ we don't know if there even exists a generic extension. However, I don't see the advantage of using the inner forcing relation. In our lecture, for proving statements we almost always used the inner forcing relation which seemed to make the proofs more complicated. In particular, we have proven the forcing theorems and know that both definitions are "equivalent" in some sense. So my question is, why is the inner forcing relation necessary? Why do we work with it? Is it just to avoid working in countable models before doing the actual consistency proofs?
2015/07/22
[ "https://math.stackexchange.com/questions/1370163", "https://math.stackexchange.com", "https://math.stackexchange.com/users/111080/" ]
The recursive definition is the common way of proving that the forcing relation is definable in the ground model, which is not at all clear from the generic filter definition. When one wants to analyze both the ground model and some generic extension, the definability of the forcing relation is used. For instance, if you wanted to prove that $\aleph\_1$-closed forcings do not add any new reals, you may go about it as follow: Let $\tau$ be a $\mathbb{P}$-name such that there some $p \in G$ with $p \Vdash \tau$ is a real. Let $q \leq p$ be arbitrary. Let $q\_0 < q$ and $a\_0 \in \{0,1\}$ such that $q\_0 \Vdash \tau(\check 0) = a\_0$. Suppose $q\_n$ has been defined, let $q\_{n + 1} \leq q\_n$ and $a\_{n + 1} \in \{0,1\}$ be such that $q\_{n + 1} \Vdash \tau(\check{n + 1}) = a\_{n + 1}$. By $\aleph\_1$-closed, let $t\leq q\_n$ for all $n$. Then using the definability of the the forcing in $M$, you apply the separation axiom in $M$, to conclude there is a real $r \in M$ such that for all $n$, $r(n) = a\_n$. By a genericity argument, $M[G] \models \tau = \check r$. So the definability of the forcing relation was essential to the above. However, I did not ever explicitly use the recursive definition of the forcing relation. This is generally how forcing arguments go. I am not exactly sure what you mean by "for proving statements we almost always used the inner forcing relation". Certainly, if you prove abstract theorems about forcing and names, you may find that knowing explicitly how the forcing relation evaluates may be useful. For example, if you are trying to the prove fullness or the maximality principle.
Try avoiding internal forcing while showing the following: In every Cohen real extension, every $\omega$-sequence of ordinals equals a ground model $\omega$-sequence infintely often. Let me know if this seems boring and I will give you harder ZFC facts.
553,362
For some reason, my root crontab does not seem to be running. Trying to reboot the device every night at midnight. Should be the following as root: ``` crontab -e ``` Then add: ``` 0 0 * * * /sbin/shutdown -r now ``` When I test using some values close current time, nothing happens. I installed NTP and made sure the time zone is correct. I am also specifying using the 24-hour clock. For example, to test this line right now (5:35 PM) I try entering the following: ``` 36 17 * * * /sbin/shutdown -r now ``` I have checked the time with date -R. The time for the crontab to run comes and goes and the system does not reboot. What am I missing here?
2014/11/24
[ "https://askubuntu.com/questions/553362", "https://askubuntu.com", "https://askubuntu.com/users/177227/" ]
I have three solution suggestions for you. 1. Invoke the crontab with `crontab -e -u root` 2. Make sure that you have an empty line at the end of the cronjob file, meaning that every line ends with a newline. 3. You might need to redirect the output to devnull: `shutdown -r now > /dev/null` Here are two helpful webpages for cronjobs: [CRON Tester](http://cron.schlitt.info/) [CRON Generator](http://cron.nmonitoring.com/cron-generator.html) You can also handle the cronjobs neatly with [webmin](http://www.webmin.com/). Other than that, you have at least two more ways for restarting your computer at midnight. One is to run the shutdown command as a script automatically at login but with specific time as a parameter instead of "now": `shutdown -r 00:00` However, this will yield a broadcast message of upcoming shutdown at every login (might not be a bad thing at all). Well you can also make this be run at boot time by adding the script in init.d, still yielding the message, though. Another is to use `at`command: `at 0am` Enter command `shutdown -r now` and save it with ctrl+d or do a script for the command and do: `at -f restart_script.sh 0am` Hope these help you to get the result you wanted.
36 17 \* \* \* etc .. 36 17 is not a way to specify the right time in your cron. check via date command to see if your system is working in US time or Europ time use 17 36 if europ time and if your system use 24 H time or 5 36 if your system use US TIME and 12 H time
55,173,819
**Update : I re-worded and re-thought through this, and I think the question is better asked like this.** So I've been hacking at this forever with no luck. Here is an example of what I am looking to do. I am starting off with a dataframe: ``` df = data.frame("one" = c(1,11), "two" = c(2,22), "three" = c(3,33)) one two three 1 2 3 11 22 33 ``` I am attempting to turn the above, into this: ``` one new 1 c(2,3) 11 c(22,33) ``` I have tried a few things like nesting the 2 columns and trying to map over them, etc. Maybe there is something simple I am not seeing here. I'd preferably like to do this in R via the tidyverse, but at this point I'm open to whatever. It has to be this way because when it gets converted to JSON the values under 'new' need to be in the form [1,2,3] & [11,22,33]. Maybe its easier in Python? I'm using the *jsonlite* package in R for converting to/from JSON. Thanks for the help.
2019/03/15
[ "https://Stackoverflow.com/questions/55173819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8355471/" ]
I think this should just be a `Map` exercise: ``` df$new <- Map(c, df$two, df$three) df # one two three new #1 1 2 3 2, 3 #2 11 22 33 22, 33 library(jsonlite) toJSON(df[c("one","new")]) #[{"one":1,"new":[2,3]},{"one":11,"new":[22,33]}] ``` If you've got many variables, you can wrap it in `do.call` to get it done too: ``` df$new <- do.call(Map, c(c,df[2:3])) ``` If *tidyverse* is your preference, you can *purrr* it like: ``` map2(df$two, df$three, c) ```
In python, using `pandas`: ``` import pandas as pd df = pd.DataFrame([[1,2,3],[11,22,33]], columns=["one", "two","three"]) one two three 0 1 2 3 1 11 22 33 df['new'] = list(zip(df.two, df.three)) df[['one','new']].to_json(orient='records') # '[{"one":1,"new":[2,3]},{"one":11,"new":[22,33]}]' ```
586,175
I am more in mechanics then in electrical engineering so sorry if this question sounds silly for you. I have a little CNC machine with NEMA 17 stepper motors but their power is not enough for me, so I decided to change them for NEMA 23 stepper motors. I am not sure if my current adapter of **12V and 5A** is enough to run **3x NEMA 23 motors of 3A each**? How could I calculate that?
2021/09/10
[ "https://electronics.stackexchange.com/questions/586175", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/295586/" ]
This question highlights the need to understand the problem space and shows that leaving out information makes providing accurate answers very difficult. To summarize the question with most of the necessary information: **I have a little CNC machine with NEMA 17 stepper motors and a 12V/5A power supply but their power is** **insufficient. I want to change to NEMA 23 stepper motors rated at 3A RMS and continue** **to use my current controller (using A4988 drivers) and power supply. Will this work?** Short answer: Yes Long answer: * The drivers you have ([A4988](https://www.allegromicro.com/%7E/media/Files/Datasheets/A4988-Datasheet.ashx)) are limited to 2A PEAK per phase. In reality for typical designs you will not get more than about 1.2 - 1.3A PEAK, set by the small potentiometer on the module. * Given the limitation in #1, you will get slightly improved torque because you moved from a NEMA 17 magnetic stack to a NEMA 23 magnetic stack. You would also get a gain in torque if you moved to a NEMA 17 stepper with a longer magnetic stack. If you compare steppers [here](https://www.applied-motion.com/products/stepper-motors) you will see that a longer stack can get you more torque for the same frame size. * Changing to larger NEMA 23 steppers will give you a boost in torque, and the motors will operate at less than their rated current, but the gains you achieve will be marginal. I'd suggest you simply get longer (larger magnetic stack NEMA 17 steppers). * Given the above, the power supply you have will be adequate as it's sized for the A4988 driver and you won't get to move to 3A. If you really want to increase the power to the stepper motor you will need to change both the power supply and the controllers driving the steppers. Something like a TB6600 driver will work up to 4A, and you'd need a power supply rated at 300W or more and a voltage of 30V or above. **Defining the real problem:** Your question is still incomplete of course. What is the reason that you think you have insufficient power (torque?) in the stepper motors you have?? * Do you lose steps when running a job? * Do you have poor surface finish? A common problem for small CNC (subtractive not 3D printer) machines is that the unit is run with too high a microstep count. As you increase the microstep count the torque to move each step reduces markedly. This results in poor surface finish and poor repeatability for jobs. Keeping the same stepper motors and putting a belt reduction (3 or 4:1) and reducing to Half step (MS1,2,3 on the A4988) drive may help you achieve better results with less re-engineering effort. It is incumbent on you to accurately define your problem/question so you can get worthwhile answers. Note: [This answer](https://electronics.stackexchange.com/questions/453954/is-a4988-and-drv8825-current-limit-setting-rms-or-peak) on PEAK vs RMS current may also help you understand some of the complexity in defining power usage. The rules for power usage change when comparing a CNC (subtractive) machine to a 3D printer. The worst case power for CNC is a spline (all three axis move at once). For a 3D printer the Z axis typically moves on its own (layer height setting) and only the X,Y axis move in tandem.
You can calculate that 3 motors requiring 3 A each require 3x3 = 9 amps. Even two motors would require 2x3 = 6 amps. Your power supply is therefore only adequate to run one motor, making no other assumptions. Sometimes stepper motor drivers are set up to use a lower holding current than their stepping current, so would use less when stationary. So the next step is to estimate, or simulate the operation of the machine, to see whether more than one motor is required to move at the same time. If I was investing in replacing all three motors, I would replace the power supply as well, so that I could use all three motors at the same time. Of course, being retired, I'm way behind the times. As Jack points out in comments, the drivers are probably switchers rather than the old fashioned linear types. With linear drivers, supply current is motor current. With switchers, supply power is motor power, and, as the motor voltage is usually a fraction of the supply voltage, supply current can be a fraction of the motor current. So, find out what your drivers are, you may be pleasantly surprised.
1,361,946
I must verify if the real part of the following expression $$z = \frac{1 + i}{\sigma \delta \left[ 1 - e^{-(1 + i)t/\delta} \right] }$$ is $$\Re(z) = \frac{1}{\sigma \delta} \frac{1}{1 - e^{-t/\delta}}$$ where $t, \sigma, \delta$ are real, positive quantities and $i$ is the imaginary unit. 1) First of all, I think that $$\frac{i}{\sigma \delta \left[ 1 - e^{-(1 + i)t/\delta} \right] }$$ is not purely imaginary, due to the complex exponential in the denominator, so it is anyway to be considered when trying to obtain $\Re(z)$. 2) Moreover $\Re(z)$ does not contain any $\cos$ or $\sin$ terms and this is confusing to me, because in the denominator I must consider $e^{iw} = \cos(w) + i\sin(w)$ and even [Wolfram](http://www.wolframalpha.com/input/?i=real%20part%20of%20%281%20%2B%20i%29%2F%281-e%5E%28-%281%20%2B%20i%29x%29%29) gives a result with those quantities. Is there a way to simplify the $\cos$ and $\sin$ terms from $z$ and obtain the $\Re(z)$ I wrote? If yes, what can I observe in order to cancel them?
2015/07/15
[ "https://math.stackexchange.com/questions/1361946", "https://math.stackexchange.com", "https://math.stackexchange.com/users/132192/" ]
I've checked my answer with Mathematica and it gives me the same, it's much more complicated as you thought, so your answer isn't good! --- $$z = \frac{1 + i}{\sigma \delta \left(1 - e^{-(1 + i)t/\delta} \right)}= \frac{1 + i}{\sigma \delta \left(1 - e^{-\frac{(1+i)t}{\delta}} \right)}$$ Assuming $\sigma,\delta,t\in \mathbb{R}$: $$\Re\left(\frac{1 + i}{\sigma \delta \left(1 - e^{-\frac{(1+i)t}{\delta}} \right)}\right)=$$ $$\Re\left(\frac{1 + i}{\sigma \delta - \sigma \delta e^{-\frac{(1+i)t}{\delta}} }\right)=$$ $$\Re\left(\frac{1+i}{\sigma \delta}\right)+\Re\left(\frac{1+i}{\sigma \delta\left(-1+e^{-\frac{(1+i)t}{\delta}}\right)}\right)=$$ $$\frac{1}{\sigma \delta}+\Re\left(\frac{1+i}{\sigma \delta\left(-1+e^{-\frac{(1+i)t}{\delta}}\right)}\right)=$$ $$\frac{1}{\sigma \delta}+\frac{\Re\left(\frac{1+i}{-1+e^{-\frac{(1+i)t}{\delta}}}\right)}{\sigma \delta}=$$ $$\frac{1}{\sigma \delta}+\frac{\Re\left(\frac{1}{-1+e^{-\frac{(1+i)t}{\delta}}}\right)-\Im\left(\frac{1}{-1+e^{-\frac{(1+i)t}{\delta}}}\right)}{\sigma \delta}=$$ $$\frac{1}{\sigma \delta}+\frac{\frac{1-e^{\frac{t}{\delta}}\cos\left(\frac{t}{\delta}\right)}{-e^{\frac{2t}{\delta}}+2e^{\frac{t}{b}}\cos\left(\frac{t}{\delta}\right)-1}-\left(-\frac{e^{\frac{t}{\delta}}\sin\left(\frac{t}{\delta}\right)}{e^{\frac{2t}{\delta}}\sin^2\left(\frac{t}{\delta}\right)+\left(e^{\frac{t}{\delta}}\cos\left(\frac{t}{\delta}\right)-1\right)^2}\right)}{\sigma \delta}=$$ $$\frac{1}{\sigma \delta}+\frac{\frac{1-e^{\frac{t}{\delta}}\cos\left(\frac{t}{\delta}\right)}{-e^{\frac{2t}{\delta}}+2e^{\frac{t}{\delta}}\cos\left(\frac{t}{\delta}\right)-1}+\frac{e^{\frac{t}{\delta}}\sin\left(\frac{t}{\delta}\right)}{e^{\frac{2t}{\delta}}\sin^2\left(\frac{t}{\delta}\right)+\left(e^{\frac{t}{\delta}}\cos\left(\frac{t}{\delta}\right)-1\right)^2}}{\sigma \delta}=$$ $$\frac{1}{\sigma \delta}+\frac{e^{\frac{t}{\delta}}\sin\left(\frac{t}{\delta}\right)+e^{\frac{t}{\delta}}\cos\left(\frac{t}{\delta}\right)-1}{\sigma \delta\left(e^{\frac{2t}{\delta}}-2e^{\frac{t}{\delta}}\cos\left(\frac{t}{\delta}\right)+1\right)}$$ So: $$\Re\left(\frac{1 + i}{\sigma \delta \left(1 - e^{-\frac{(1+i)t}{\delta}} \right)}\right)=\frac{1}{\sigma \delta}+\frac{e^{\frac{t}{\delta}}\sin\left(\frac{t}{\delta}\right)+e^{\frac{t}{\delta}}\cos\left(\frac{t}{\delta}\right)-1}{\sigma \delta\left(e^{\frac{2t}{\delta}}-2e^{\frac{t}{\delta}}\cos\left(\frac{t}{\delta}\right)+1\right)}$$
**Without computing**: The denominator of $z$ has non-trivial roots (when the argument of the exponential is $i2k\pi$); not the denominator of $\Re(z)$.
1,755,124
How can I add a Button column to a Datagrid programmatically? I want to do this through code in the code-behind file. Also i want to selectively enable or disable this button based on record (If status is Open then Enable it else disable this button). Here Status is a Column in the DataSource. Thanks, Abhi
2009/11/18
[ "https://Stackoverflow.com/questions/1755124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/213658/" ]
Xaml : ``` <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Click="Details">Details</Button> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> ``` Code Behind ``` private IEnumerable<DataGridRow> GetDataGridRowsForButtons(DataGrid grid) { //IQueryable var itemsSource = grid.ItemsSource as IEnumerable; if (null == itemsSource) yield return null; foreach (var item in itemsSource) { var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow; if (null != row & row.IsSelected) yield return row; } } void Details(object sender, RoutedEventArgs e) { for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual) if (vis is DataGridRow) { // var row = (DataGrid)vis; var rows = GetDataGridRowsForButtons(dgv_Students); string id; foreach (DataGridRow dr in rows) { id = (dr.Item as tbl_student).Identification_code; MessageBox.Show(id); } break; } } ``` After clicking on the Button, the ID of that row is returned to you and you can use it for your Button name.
XAML: ``` <DataGrid.Columns> <DataGridTemplateColumn Header="Check"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox x:Name="chkName" IsChecked="{Binding IsChecked , UpdateSourceTrigger=PropertyChanged}" Click="chkName_Click"> </CheckBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="as"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Click="OnAddQuantityClicked">hello</Button> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> ``` Code Behind: ``` private async void OnAddQuantityClicked(object sender, RoutedEventArgs e) { if (sender is Button) { var temps = (Models.TempV)mainDatagrid.SelectedItem; //Button button = (Button)e.OriginalSource; if (temps.IsChecked is true) { MessageBox.Show("Do something when it is True"); } else { MessageBox.Show("Do something when it is False"); } } } ```
5,016,181
I am wondering about the following code: ``` <html> <head> <title>Test HTML</title> <link rel="stylesheet" type="text/css" href="test.css"> </head> <body> <table class=foo cellpadding="2" cellspacing="2"> <tr> <td><b>Contingency Table:</b></td> <td><table class=bar border="2" align="left"> <tr><td>blaa</td><td>blaa</td><td>blaa</td></tr> <tr><td>blaa</td><td>blaa</td><td>blaa</td></tr> <tr><td>blaa</td><td>blaa</td><td>blaa</td></tr> </table> </td> </tr> </table> </body> </html> ``` with the following CSS: ``` table { border-width: 2px; border-spacing: 2px; border-style: solid; } table.bar { border-color: red; background-color: white; } table.bar td { background-color: green; } table.bar tr { background-color: black; } table.foo { border-color: blue; background-color: white; } table.foo td { border-color: black; background-color: yellow; } table.foo tr { background-color: yellow; } ``` The problem is, when interchanging the classes "foo" and "bar" in the table and its nested table, the style of the td-tags is not correctly set, or at least as not as expected by me. When changing from outer "bar" and inner "foo" to outer "foo" and inner "bar" the colors change as expected, except for the colors of the td-element. What am I doing wrong here, since the other elements of a table change correctly? I know that using `table table.foo {...}` would work, but this requires to know which style should be used for the inner/nested table and I don't really like this idea. I want to be able to interchange the styles when desired and not include the "inheritance" in the style-sheet... Also dictating the order of the foo or bar styles in the style-sheet is not desirable for me. Please correct me, if this is actually common HTML/CSS practice.
2011/02/16
[ "https://Stackoverflow.com/questions/5016181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271775/" ]
xzyfer's reasoning is right. A simple workaround could be to *add* ``` table table.bar td { background-color: green !important; } ``` Assuming your nesting is at most 2 levels, this works fine, because it overrides the cascading effect described (i.e. the rule applied is no longer dependant on the order the rules are defined). Working example: <http://jsfiddle.net/RQCQS/>
If you only want yto effect the direct children of table foo you need some child selectors. You might need to look thees up as I know they can be used as a work around for older browsers. Additionally I'd advise adding tbody to your table as firefox does this automatically and it messed up my testing of the child selectors: ``` table.foo > tbody > tr > td { border-color: black; background-color: yellow; } table.bar > tbody > tr > td { background-color: green; } ``` Should work in firefox, you would have to test other browsers. The issue you were having has been explained in other posts but is the nature of cascading style sheets as your code was originally any td inside table.foo was effected by the style table.foo td. Alternatively you will have to switch the order of the styles so the nested styles are always overidding the outer table styles.
1,448,858
How can I color Java output? For example in C and other languages I can use ANSI-escape like `\033[0m` to do this. But in Java it doesn't work. ``` public static void main(String[] x) { System.out.println("\033[0m BLABLA \033[0m\n"); } ```
2009/09/19
[ "https://Stackoverflow.com/questions/1448858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173787/" ]
Check This Out: i used ANSI values with escape code and it probably not work in windows command prompt but in IDEs and Unix shell. you can also check 'Jansi' library [here](https://github.com/fusesource/jansi) for windows support. ``` System.out.println("\u001B[35m" + "This text is PURPLE!" + "\u001B[0m"); ```
I've written a library called [AnsiScape](https://github.com/nomemory/ansiscape) that allows you to write coloured output in a more structured way: Example: ``` AnsiScape ansiScape = new AnsiScape(); String colors = ansiScape.format("{red {blueBg Red text with blue background}} {b Bold text}"); System.out.println(colors); ``` The library it also allows you to define your own "escape classes" akin to css classes. Example: ``` AnsiScapeContext context = new AnsiScapeContext(); // Defines a "class" for text AnsiClass text = AnsiClass.withName("text").add(RED); // Defines a "class" for the title used AnsiClass title = AnsiClass.withName("title").add(BOLD, BLUE_BG, YELLOW); // Defines a "class" to render urls AnsiClass url = AnsiClass.withName("url").add(BLUE, UNDERLINE); // Registering the classes to the context context.add(text).add(title).add(url); // Creating an AnsiScape instance with the custom context AnsiScape ansiScape = new AnsiScape(context); String fmt = "{title Chapter 1}\n" + "{text So it begins:}\n" + "- {text Option 1}\n" + "- {text Url: {url www.someurl.xyz}}"; System.out.println(ansiScape.format(fmt)); ```
19,779,139
I need to be able to dynamically retrieve the current action and controller name of whatever page you're on, and actually use them to create a new HTML.ActionLink that links to the same action and controller name, but in a different area. So I guess I need to retrieve the current action and controller name as variables to use in building a new HTML.ActionLink. So, if I'm on the www.site.com/about page, I need to have a link dynamically generated to the www.site.com/es/about page. I've basically built a spanish translated version of my site in a separate area folder (with the same named controllers and actions and views, just content is all in spanish). I need the user to be able to toggle back and forth between the english version of the page (which is the default, and resides in the root site views) and the spanish version (whose views resides in the area folder "es") of whichever page they're currently on. I can't "hardcode" these links because I need this in a shared partial view which is the \_topNavigation in my \_Layout used on every page. Please let me know if I need to clarify. I'm sure using "areas" wasn't really the way to go when localizing an application, but I'm still trying hard to teach myself asp.net MVC. I read many MANY tutorials and examples on localization, and I could just not get them to work or make sense. I should also add that I already know how to use HTML.ActionLink to go back and forth between the areas. I've managed to create the correct HTML.ActionLinks to any of the views in the spanish (es) area, and to any of the views in the default site. So that is not my question. Any help is greatly appreciated! Thanks!
2013/11/04
[ "https://Stackoverflow.com/questions/19779139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1637341/" ]
Use `ViewContext.RouteData` to determine current Controller and Action: ``` @Html.ActionLink("Spanish Version", ViewContext.RouteData.Values["action"] as String, ViewContext.RouteData.Values["controller"] as String, new { Area = "es" }) ```
If the actionName is only for `@Html.ActionLink()`, you can simply pass `"null"` as the actionName. The current actionName will be used.
10,010,604
I have defined a sencha List as below ``` Ext.List({ itemTpl: '<div class={filterClass}></div>{filterType}', id: 'sFilter', width: 200, cls: 'sFilter', grouped: false, indexBar: false, store: store, listeners: { itemtap: function (me, index, item, e) { var selectedRecord = me.store.getAt(index); var filterTag = selectedRecord.data.filterTag; if (filterTag !== searchResultTag.Everything) { var filteredResults = filterResults(filterTag, allResults); //some more code } else { //some more code } } } }); ``` Items of the list are dynamically added and they dont have an "id". I would like to fire (first item) itemtap event on the above list. How can I do that?
2012/04/04
[ "https://Stackoverflow.com/questions/10010604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214647/" ]
You can split that into 3 lines for understanding ``` StringBuffer reverseBuffer = new StringBuffer(name); // Creating new StringBuffer object reverseBuffer = reverseBuffer.reverse(); //Reversing the content using StringBuffer String reverse = reverseBuffer.toString(); // Converting StringBuffer to String and saving in reverse ```
From the JAVA API public StringBuffer reverse() Causes this character sequence to be replaced by the reverse of the sequence. If there are any surrogate pairs included in the sequence, these are treated as single characters for the reverse operation. Thus, the order of the high-low surrogates is never reversed. Let n be the character length of this character sequence (not the length in char values) just prior to execution of the reverse method. Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence. Note that the reverse operation may result in producing surrogate pairs that were unpaired low-surrogates and high-surrogates before the operation. For example, reversing "\uDC00\uD800" produces "\uD800\uDC00" which is a valid surrogate pair. Returns: a reference to this object. Since: JDK1.0.2 <http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html#reverse%28%29>
31,335,601
In the following expression, what conversion happens? ``` long long a; long long b; double c; b=a*c; ``` suppose the `long long` type is 8-byte. If `a` and `b` are both `int`, then in the expression `b = a * c`, `a` will be converted to `double` and does multiplication with `c`, and the result will be converted to `int` and assigned to `b`. Is my assumption correct?
2015/07/10
[ "https://Stackoverflow.com/questions/31335601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/668249/" ]
``` b=a*c; ``` is equivalent to: ``` b=(long long) ( (double)a * c ); ``` So there are two conversions involved, first from `long long` to `double` and second from `double` result to `long long` For more details check [this page from Joachim Pileborg's](https://stackoverflow.com/questions/31335601/what-conversion-happens-in-the-flowing-expression#comment50655882_31335601) comment
As per `C11` standard, chapter §6.3.1.8, *Usual arithmetic conversions* > > ....Otherwise, if the corresponding real type of either operand is double, the other > operand is converted, without change of type domain, to a type whose > corresponding real type is `double`. > > > So, your statement is essentially, ``` b= (long long)( (double)a * c ); ``` that is, for the `*` operand, `c` is `double`, so value of `a` is converted to a `double` value, the multiplication is performed, the result is of type `double` and finally, that value is being converted to `long long`, when assigned to `b`, as per the type of `b` itself.
34,436,146
Guys i have an html div and here is the code ``` <div id="mainBody"></div> ``` I gave it a background image in css and here is the code ``` #mainBody{background : url(../images/index/optimizedBackground.jpg) repeat 0 0;} ``` I want to add a color on it but this color is opacity and view the background image. so i used this html code and adding a div inside the first one: ``` <div id="mainDiv"><div id="layoutDiv"></div></div> ``` I gave the **layout** div a background color in css: ``` #layoutDiv{ background-color : #1a1a1a; opacity : 0.9;} ``` And it works perfectly but the problem here is anything inside the **layout** div has **0.9 opacity** and i want **layout** div only has 0.9 opacity not the divs inside it
2015/12/23
[ "https://Stackoverflow.com/questions/34436146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5683473/" ]
Add `clear: left;` on the `.navbar hr` and it works. When using floats, you always want to 'clear' the floats after that to stop bad things happening to your design. Take a look at <https://css-tricks.com/the-how-and-why-of-clearing-floats/> ```css li { list-style-type: none; margin: 0; padding: 0; float: left; overflow: auto; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } .navbar hr { border-color: #cc9900; float: none; clear: left; } ``` ```html <body bgcolor="#000000"> <title>Terraria Extras</title> <link rel="stylesheet" type="text/css" href="style.css"> <div id="section"> <div class="logo"> <h2>Terraria</h2> <h3>extras</h3> </div> <div class="navbar"> <hr> <a href="#" id="menu-icon"></a> <li><b><a href="#" class="active">Home</a></b></li> <li><b><a href="download">Download</a></b></li> <li><b><a href="about">About us</a></b></li> <li><b><a href="twitter">Twitter</a></b></li> <hr> </div> </div> </body> ```
Change the css according to the code and it will work ``` .navbar hr { border-color: #cc9900; float: left; display: block; width: 100%; } ```
14,113,788
It is known that Metacello first or main target was Pharo, but it seems now that [Squeak 4 is supported](https://github.com/dalehenrich/metacello-work/blob/master/docs/MetacelloScriptingAPI.md). I've tried but fails due a missing method. From the Transcript: ``` Starting atomic load Loaded -> OSProcess-dtl.65 --- http://www.squeaksource.com/OSProcess --- cache Finished atomic load BaselineOf>>projectClass (MetacelloMCBaselineProject is Undeclared) ConfigurationOf>>versionNumberClass (MetacelloSemanticVersionNumber is Undeclared) Loaded -> Metacello-Base-dkh.103 --- http://seaside.gemstone.com/ss/metacello --- cache MetacelloProjectRegistration>>version (MetacelloMCBaselineProject is Undeclared) MetacelloBaselineSpecGenerator>>projectSpecCreationBlock (MetacelloMCBaselineProject is Undeclared) Loaded -> Metacello-Core-dkh.667 --- http://seaside.gemstone.com/ss/metacello --- cache Loaded -> Metacello-MC-dkh.666 --- http://seaside.gemstone.com/ss/metacello --- cache Loaded -> Metacello-ToolBox-dkh.131 --- http://seaside.gemstone.com/ss/metacello --- cache Loaded -> Metacello-FileTree-dkh.29 --- http://seaside.gemstone.com/ss/metacello --- cache Loaded -> Metacello-GitHub-dkh.22 --- http://seaside.gemstone.com/ss/metacello --- cache Evaluated -> 1.0-beta.32 [ConfigurationOfMetacello] >> metacelloPrimeRegistry ...finished 1.0-beta.32 ...RETRY->ConfigurationOfMetacelloPreview ...RETRY->ConfigurationOfMetacelloPreview gofer repository error: 'GoferRepositoryError: My subclass should have overridden #downloadFile:to:'...ignoring ...FAILED->ConfigurationOfMetacelloPreview ``` I am using Squeak 4.4-12327 image. Any help on this?
2013/01/01
[ "https://Stackoverflow.com/questions/14113788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000565/" ]
The above solution is no longer valid u need to get it using this below code ``` (Installer monticello http:'http://seaside.gemtalksystems.com/ss') project: 'metacello'; install: 'ConfigurationOfMetacello'. ((Smalltalk at: #ConfigurationOfMetacello) project latestVersion) load. ```
I just ran this (as proposed by the install doc on Github) in 4.4 and had no problems whatsoever: ``` Installer gemsource project: 'metacello'; install: 'ConfigurationOfMetacello'. ((Smalltalk at: #ConfigurationOfMetacello) project version: '1.0-beta.32') load. ``` What code are you using?
2,702,017
Jquery - How do I change the parent of an element from an H1 to a P? I have `<h1>heading</h1>`, how do I change it to `<p>heading</p>` I think I could `$.unwrap` then `$.wrap`, but is there a better way?
2010/04/23
[ "https://Stackoverflow.com/questions/2702017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243494/" ]
This question is pretty close (I would consider it a duplicate) of [How do I change an element (e.g. h1 -> h2) using jQuery / plain old javascript?](https://stackoverflow.com/questions/240467/how-do-i-change-an-element-e-g-h1-h2-using-jquery-plain-old-javascript) Using this solution, your answer would resemble ``` var p = $('h4'); var a = $('<p/>'). append(p.contents()); p.replaceWith(a); ``` Test it here: <http://jsbin.com/abaja/edit>
HTML: ``` <h1 id="a">heading</h1> ``` jQuery: ``` var $a = $('#a'); var contents = $a.contents(); $a.remove(); $('body').append('<p>' + contents + '</p>'); ``` `$.unwrap` would remove the parent of the matched element. In other words, if `#a` were the child of a `div`, the `div` would be removed and not the `h1`.
59,990,814
I've followed the instructions here [gatsby tutorial:3](https://www.gatsbyjs.org/tutorial/part-three/) under the "Using Gatsby Plugins" section. But I can't get the fairy theme to appear. The `<style>` element never gets added to the `<head>` element. My only guess is this warning I get within the typography.js: Could not find a declaration file for module 'typography-theme-fairy-gates'. 'c:/Users/jghof/tutorial-part-three/node\_modules/typography-theme-fairy-gates/dist/index.js' implicitly has an 'any' type. Try `npm install @types/typography-theme-fairy-gates` if it exists or add a new declaration (.d.ts) file containing `declare module 'typography-theme-fairy-gates';`ts(7016) I don't understand what this means or how to fix it as I'm very new to this stuff, and the tutorial has not said anything about this issue. I tried the npm install suggestion just for the heck of it but I just got a bunch of errors in the terminal. Could anyone help? **Edit:** I found 4 problems within VSCode related to this file: tutorial-part-three\node\_modules\typography-theme-fairy-gates\src\index.js these are the problems it lists: 'import ... =' can only be used in a .ts file. '=' expected. ';' expected. 'types' can only be used in a .ts file. they occur on line 3 and 7 of the file. I can't figure out how to fix any of this, but here's the file below. ```js // @flow import gray from "gray-percentage" import type { OptionsType } from "Types" import { MOBILE_MEDIA_QUERY } from "typography-breakpoint-constants" import verticalRhythm from "compass-vertical-rhythm" const theme: OptionsType = { title: "Fairy Gates", baseFontSize: "20px", baseLineHeight: 1.45, googleFonts: [ { name: "Work Sans", styles: ["600"], }, { name: "Quattrocento Sans", styles: ["400", "400i", "700"], }, ], headerFontFamily: ["Work Sans", "sans-serif"], bodyFontFamily: ["Quattrocento Sans", "sans-serif"], headerColor: "hsla(0,0%,0%,0.9)", bodyColor: "hsla(0,0%,0%,0.8)", headerWeight: "600", bodyWeight: 400, boldWeight: 700, overrideStyles: ({ adjustFontSizeTo, scale, rhythm }, options) => { const linkColor = "#1ca086" const vr = verticalRhythm({ baseFontSize: "17px", baseLineHeight: "24.65px", }) return { a: { color: linkColor, textDecoration: "none", textShadow: ".03em 0 #fff,-.03em 0 #fff,0 .03em #fff,0 -.03em #fff,.06em 0 #fff,-.06em 0 #fff,.09em 0 #fff,-.09em 0 #fff,.12em 0 #fff,-.12em 0 #fff,.15em 0 #fff,-.15em 0 #fff", // eslint-disable-line backgroundImage: `linear-gradient(to top, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0) 1px, ${linkColor} 1px, ${linkColor} 2px, rgba(0, 0, 0, 0) 2px)`, // eslint-disable-line }, "a:hover,a:active": { textShadow: "none", backgroundImage: "none", }, "h1,h2,h3,h4,h5,h6": { marginTop: rhythm(1.5), marginBottom: rhythm(0.5), }, // Blockquote styles. blockquote: { ...scale(1 / 5), borderLeft: `${rhythm(6 / 16)} solid ${linkColor}`, color: gray(35), paddingLeft: rhythm(10 / 16), fontStyle: "italic", marginLeft: 0, marginRight: 0, }, "blockquote > :last-child": { marginBottom: 0, }, "blockquote cite": { ...adjustFontSizeTo(options.baseFontSize), color: options.bodyColor, fontStyle: "normal", fontWeight: options.bodyWeight, }, "blockquote cite:before": { content: '"— "', }, [MOBILE_MEDIA_QUERY]: { html: { ...vr.establishBaseline(), }, blockquote: { borderLeft: `${rhythm(3 / 16)} solid ${linkColor}`, color: gray(41), paddingLeft: rhythm(9 / 16), fontStyle: "italic", marginLeft: rhythm(-3 / 4), marginRight: 0, }, }, } }, } export default theme ```
2020/01/30
[ "https://Stackoverflow.com/questions/59990814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1352833/" ]
You have become a victim of [operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence). First dereference to get a `Point*`, then use `->` ``` (*ptrPtrPoint)->displayCoord(); ``` The compiler reads the original code as ``` *(ptrPtrPoint->displayCoord()); ```
The problem is the ***operator precedence***. You need first to dereference the pointer to pointer and then call the function with the `->`. The right line of code is this: ``` (*ptrPtrPoint)->displayCoord(); ``` pay attention to the operator precedence because in this case the compiler give you an error, but this isn't ever true. **Sometimes these errors can generate Undefined Behaviour or Unexepcted Behaviour.**
43,344,912
Hi i'm new in React Native. I am trying to create two columns layout with space beetween using react native component called flatList. Here is my view Code: ``` <View style={styles.container}> <FlatList data={db} keyExtractor={ (item, index) => item.id } numColumns={2} renderItem={ ({item}) => ( <TouchableWithoutFeedback onPress ={() => showItemDetails(item.id)}> <View style={styles.listItem}> <Text style={styles.title}>{item.name}</Text> <Image style={styles.image} source={{uri: item.image}} /> <Text style={styles.price}>{item.price} zł</Text> </View> </TouchableWithoutFeedback> ) } /> </View> ``` Here is styles: ``` container: { flex: 1, flexDirection: 'row', justifyContent: 'space-between', padding: 10, marginBottom: 40 }, listItem: { maxWidth: Dimensions.get('window').width /2, flex:0.5, backgroundColor: '#fff', marginBottom: 10, borderRadius: 4, }, ``` And result is two columns but without space between. Could you help me resolve this problem ?
2017/04/11
[ "https://Stackoverflow.com/questions/43344912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1559599/" ]
Just add some margin to the style of the list Item. ```js listItem: { margin: 10, } ```
How to create two columns with equal spacing between items: ``` <FlatList data={DATA} renderItem={renderItem} keyExtractor={(item) => item.id} horizontal={false} // you must include this line when using numColumns [per the documentation][1] numColumns={2} // creates two columns key={2} // add key to prevent error from being thrown columnWrapperStyle={{justifyContent: 'space-between'}} // causes items to be equally spaced > ``` Also, this will set each column to 1/2 the screen width: ``` const styles = StyleSheet.create({ item: { flex: 1/2, }}) ```
220,274
**The task** is taken from [leetcode](https://leetcode.com/problems/reverse-integer/) > > Given a 32-bit signed integer, reverse digits of an integer. > > > **Example 1:** > > > > ``` > Input: 123 > > Output: 321 > > ``` > > **Example 2:** > > > > ``` > Input: -123 > > Output: -321 > > ``` > > **Example 3:** > > > > ``` > Input: 120 > > Output: 21 > > ``` > > **Note:** > > > Assume we are dealing with an environment which could only store > integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For > the purpose of this problem, assume that your function returns 0 when > the reversed integer overflows. > > > **My solution** ``` /** * @param {number} x * @return {number} */ const reverse = x => { if (x === undefined || x === null) { return; } if (x < 10 && x >= 0) { return x; } const num = []; const dissectNum = n => { if (n <= 0) { return; } const y = n % 10; num.push(y); return dissectNum(Math.floor(n / 10)); }; dissectNum(Math.abs(x)); let tmp = 0; const maxPow = num.length - 1; for (let i = 0; i < num.length; i++) { tmp += num[i] * Math.pow(10, maxPow - i); } const result = (x < 0 ? -1 : 1 ) * tmp; return result > Math.pow(-2, 31) && result < (Math.pow(2, 31) - 1) ? result : 0; }; ```
2019/05/15
[ "https://codereview.stackexchange.com/questions/220274", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/54442/" ]
* The question states that the input is a number 32 signed int so checking for `undefined` or `null` is a waste of time. The solution is a little long. Some of it due to not being familiar with some old school short cuts. * To get the sign of a number use [`Math.sign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign) -JavaScript numbers are doubles but when you use bitwise operations on them they are converted to 32 bit signed integers. This gives you a very easy way to check if the result has overflowed. ``` const signedInt = value => (value | 0) === value; // returns true if int32 ``` * A 32 bit int can store 9 full decimal digits, with an extra digit `1` or `2`, and a sign. you dont need to use an array to hold the reversed digits you can store them in the reversed number as you go. * JavaScript can handle hex `0x10 === 16`, decimal `10 === 10`, octal `010 === 8` and binary `0b10 === 2` (oh and BIG ints `10n === 10`) Hex makes realy easy to remember the lowest and highest int for a given size. Not that you need them to solve the problem, just some handy info. Some common ways of writing min max 32Ints ``` const MIN = Math.pow(-2, 31), MAX = Math.pow(2, 31) - 1; // negative -0x80000000 === MIN; // true (0x80000000 | 0) === MIN; // true. Coerce from double to int32 1 << 31 === MIN; // true. Shift 1 to the highest (MSB) bit for negative //positive 0x7FFFFFFF === MAX; // true ~(1 << 31) === MAX; // true Flips bits of min int32 ``` Rewrite ------- With that info you can rewrite the solution as ``` function reverseDigits(int) { var res = 0, val = Math.abs(int); while (val > 0) { res = res * 10 + (val % 10); val = val / 10 | 0; } res *= Math.sign(int); return (res | 0) === res ? res : 0; } ```
Both answers require you to use `Math.sign`. To avoid compatibility issues with some browsers, you could add the following script in your solution. ``` if (Math.sign === undefined) { Math.sign = function ( x ) { return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : +x; }; } ```
22,849,037
I'm not sure how to add the target=\_blank to my code below. I am using Codeigniter and my image below contains an external link and works like a charm. I would love to have it open in a new window or tab but I'm unsure how to do it. I haven't found anything so far of anyone else using this method. Any suggestions are appreciated. Thanks ``` <?php echo anchor( 'http://www.facebook.com', img(array( 'src'=>base_url().'images/facebook.png', 'width'=>'32', 'height'=>'32', 'id'=>'facebook', 'alt'=>'Facebook Logo' )) );?> ```
2014/04/03
[ "https://Stackoverflow.com/questions/22849037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2434412/" ]
Err, pass the attribute as the third argument to `anchor()` ``` <?php echo anchor( 'http://www.facebook.com/artisticconcretegroup', img(array( 'src'=>base_url().'images/facebook.png', 'width'=>'32', 'height'=>'32', 'id'=>'facebook', 'alt'=>'Facebook Logo' )), ['target' => '_blank'] // or array('target' => '_blank') if PHP < 5.4 );?> ``` Or even more simply, use the code you have but with the `anchor_popup()` function. It's all in the docs - <http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html>
simply add `'target="_blank"'` eg. `echo anchor("url",'click here','target="_blank"')`
22,668,047
I have a button that is pressed after user enters email information. I have an alert view that is displayed when there is no email entered but if there is I want the button to segue to another view controller. The following code causes my app to crash. I have no idea why. Please help. (note: I have tried "sender:self]" "sender:nil]" and "sender:sender]" and they all make my app crash.) ``` - (IBAction)nextButtonPushed:(id)sender { if ([self.emailTextField.text isEqual: @""]) { emailAlertView = [[UIAlertView alloc] initWithTitle:@"Missing Email" message:@"A destination email is required to send." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [emailAlertView show]; self.nextButton.enabled = NO; } else { eString = self.eTextField.text; hString = self.hField.text; emailAddress = self.emailTextField.text; [userDefaults setObject:eString forKey:@"e"]; [userDefaults setObject:hString forKey:@"h"]; [userDefaults setObject:emailAddress forKey:@"email"]; [self performSegueWithIdentifier:@"next" sender:self]; } } ```
2014/03/26
[ "https://Stackoverflow.com/questions/22668047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3460321/" ]
There are three overwhelmingly likely possibilities: * Perhaps the storyboard really has no segue named "next" emerging from the FirstViewController scene. Be careful: spaces and capitalization and things like that matter. * Perhaps the storyboard has a segue named "next" but it emerges from a different scene (a different view controller). * Perhaps the FirstViewController instance represented by `self` in your code is not the same as the FirstViewController instance in the storyboard, i.e. maybe it came into existence in some other way and not by instantiation from the storyboard. You might even have two FirstViewController objects in the storyboard, and the segue comes from the other one.
Crashing can also occur if the view controller cannot load from the NIB. For example if there is an incorrectly named User Defined Runtime Attribute. For example `QBFlatButton` changed their API today and my app started crashing. This is why we use semantic versioning :-)
2,276
So I am looking into upgrading the gear I use to do a boil. Currently I have a 5 gallon stainless steal pot, I use an electric range to heat the water, and my kitchen sink to cool down the wort. It works, but I have had problems with my wort boiling over lately. I have tried putting less water in for the boil, then top up in the fermenter later, but this has lead to some scorching. Not to mention that fact it takes quite a while to get the wort to a boil and even longer to cool it off. The obvious answer is to upgrade my gear. I know very little about boiling setups. It seems propane is a popular choice, but anything that can boil water quickly and keep an even, controllable temperate I will consider. Also, what should I look for in a brew pot? Are cooling coils for the wort worth it? Amazon has some good deals, but I wouldn't mind giving a specialty home brew site my business either. I would like to keep it under $150. **Update** Thanks for all of the feedback. Amazon had a great combo deal with a propane burner, 8 gallon stainless pot, and wort chiller for $150. However, the shipping put it over $225. So I went with a 10 gal pot (same brand just bigger and no shipping fee for the same price) and a Bayou burner. I will get the wort chiller some other time. I decided it was better to get some good quality gear, rather than go for lesser quality pieces that I know I will replace in short order.
2010/06/25
[ "https://homebrew.stackexchange.com/questions/2276", "https://homebrew.stackexchange.com", "https://homebrew.stackexchange.com/users/573/" ]
I've been contemplating this myself recently. I've looked into induction hotplates, but I've found that they're too expensive for my blood. Here's what's on my list right now: Just grab a [turkey fryer from Walmart](http://www.walmart.com/ip/King-Kooker-30-Quart-Turkey-Fryer-and-Outdoor-Cooker/10661034) that comes with a 7 gallon kettle ($60). Sure it's aluminum, but that makes it significantly cheaper. I've been using aluminum so far with no ill affects (but that's a topic for another thread :) ). If the fryer doesn't heat evenly enough, just put a cast iron griddle or something similar under the pot to distribute the heat. Then I would make a insulating jacket for the pot using some [foil insulation from Lowes](http://www.lowes.com/pd_13353-56291-ST16025_4294858104_4294937087?productId=1014123&pl=1&currentURL=/pl_Foil%2BInsulation_4294858104_4294937087_) ($15). Those aluminum pots lose heat almost as quick as they get it. Just be sure to keep the insulation an inch or two above the bottom, we wouldn't want it to catch on fire. Lastly, I would make my own cheap-and-dirty wort chiller (which I've done before). You can grab 20' of 3/8" [copper tubing from Lowes](http://www.lowes.com/pd_311863-69305-CU06020N_4294822005_4294937087?productId=3142375&pl=1&currentURL=/pl_Copper%2BPipes%2B_4294822005_4294937087_) ($25) to start off. You're also going to need a connector on one end to thread a hose onto. You can solder one on or just find the right combo of connectors to screw one on (that's how I did mine, just remember to use Teflon tape). On the "exit end" of the chiller I just make sure the tube is clear of the water and have it spray out on the deck/driveway/wherever you're chilling. If you're chilling indoors you could just fit some plastic tubing over the end and return the water to your sink. I think all-in-all mine cost around $30-$35 to make. That comes in at around $110 (plus the cost of propane) and should definitely be an improvement on your setup.
Bad news: I doubt you can do the whole shebang for under 150. According to [Northern Brewer](http://www.northernbrewer.com/brewing), burners range between 50 and 140 bucks, chillers range between 60 and 200 bucks. Kettles are going to be a problem. I don't see anything (in the 8-10 gallon range) for less than 150. I'd suggest going the route I decided on: First, get a chiller. You can use it for your current setup. Second, get a burner. You can use your current pot and chilling system on the new burner. Third, get the bigger pot. Space it out over a couple of months/batches between buys, and you should be able to get it all and not have to cut corners just to match the budget.
20,207,199
I have an array in Matlab, let say of (256, 256). Now i need to build a new array of dimensions (3, 256\*256) containing in each row the value, and the index of the value in the original array. I.e: ``` test = [1,2,3;4,5,6;7,8,9] test = 1 2 3 4 5 6 7 8 9 ``` I need as result: ``` [1, 1, 1; 2, 1, 2; 3, 1, 3; 4, 2, 1; 5, 2, 2; and so on] ``` Any ideas? Thanks in advance!
2013/11/26
[ "https://Stackoverflow.com/questions/20207199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/950379/" ]
What you want is the output of `meshgrid` ``` [C,B]=meshgrid(1:size(test,1),1:size(test,2)) M=test; M(:,:,2)=B; M(:,:,3)=C; ```
here's what i came up with ``` test = [1,2,3;4,5,6;7,8,9]; % orig matrix [m, n] = size(test); % example 1, breaks with value zero elems o = find(test); test1 = [o, reshape(test, m*n, 1), o] ``` Elapsed time is 0.004104 seconds. ``` % one liner from above % (depending on data size might want to avoid dual find calls) test2=[ find(test) reshape(test, size(test,1)*size(test,2), 1 ) find(test)] ``` Elapsed time is 0.008121 seconds. ``` [r, c, v] = find(test); % just another way to write above, still breaks on zeros test3 = [r, v, c] ``` Elapsed time is 0.009516 seconds. ``` [i, j] =ind2sub([m n],[1:m*n]); % use ind2sub to build tables of indicies % and reshape to build col vector test4 = [i', reshape(test, m*n, 1), j'] ``` Elapsed time is 0.011579 seconds. ``` test0 = [1,2,3;0,5,6;0,8,9]; % testing find with zeros.....breaks % test5=[ find(test0) reshape(test0, size(test0,1)*size(test0,2), 1 ) find(test0)] % error in horzcat [i, j] =ind2sub([m n],[1:m*n]); % testing ind2sub with zeros.... winner test6 = [i', reshape(test0, m*n, 1), j'] ``` Elapsed time is 0.014166 seconds. Using meshgrid from above: Elapsed time is 0.048007 seconds.
9,731,928
Not sure if I'm being too clear with the title. Sorry, it's late and I don't think I have a cleared mind. Anyway what I want this to do is.. 1. When the div(manager) is clicked, the div(managerp) appears. 2. The div(manager) moves to the area the same time managerp moves there. Almost as though they move as one div element. 3. On the next click managerp Fades out, and manager moves back to its original position. I'm able to do all of that, but it won't return to it's original position. I am a novice when it comes to jQuery, so this is where I ask for your help. EDIT: The div manager doesn't seem to return to the old position. I've tried editing the css through jQuery to get it to, but it doesn't seem to work. HTML : ``` <div id="manager"> <span>&raquo;</span> </div> <div id="managerp" style=""> </div> ``` No, I can't put managerp within manager, it doesn't seem to position itself as good as it should. jQuery : ``` $(document).ready(function() { $("#manager").click(function() { $("#manager").css({'margin-left' : '270px', 'border-left' : '0'}); $("#managerp").toggle("slow", function() { if ($("#managerp").is(':visible')) $("span").html("&laquo;"); else $("span").html("&raquo;"); }); }); }); ``` This should help you get the picture of what it's supposed to look like. (Sorry if I am giving way too much information) ![One](https://i.stack.imgur.com/TZeEh.png) ![Two](https://i.stack.imgur.com/1WVyA.png) Thank you for your help. If you need me to be more specific as to what it should be doing, just ask. ![This is how it looks when it doesn't return correctly.](https://i.stack.imgur.com/8gOlP.png)
2012/03/16
[ "https://Stackoverflow.com/questions/9731928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1267786/" ]
How about this: ``` $(document).ready(function() { $("#manager").click(function() { $("#managerp").toggle("slow", function() { if($("#managerp").is(':visible')){ $("span").html("&laquo;"); $("#manager").css({'margin-left' : '0px', 'border-left' : '0'}); }else{ $("span").html("&raquo;"); $("#manager").css({'margin-left' : '270px', 'border-left' : '0'}); } }); }); }); ``` You have to reset the margin to `0px`.
Hope this helps ... You need to reset Margin-Left to 0. Also hide the div ManagerP at the start. ``` <html> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script> $(document).ready(function() { $("#managerp").hide(); $("#manager").click(function() { $("#managerp").toggle("slow", function() { if ($("#managerp").is(':visible')){ $("span").html("&laquo;"); $("#manager").css({'margin-left' : '270px', 'border-left' : '01'}); } else { $("span").html("&raquo;"); $("#manager").css({'margin-left' : '0px', 'border-left' : '01'});} }); }); }); </script> <body> <div id="manager"> <span>&raquo;</span> </div> <div id="managerp" style=""> This is a test for sliding control <br> This is Manager P DIV </div> </body> </html> ``` Apologies for bad formatting... working with notepad isn't fun
38,781,189
i am windows user and trying to update firebase version using **npm install -g firebase-tools** but when i run **firebase --version** it shows the same version. I also run npm uninstall **firebase --save** and check **firebase --version** it shows same. what should i do to update my firebase version?
2016/08/05
[ "https://Stackoverflow.com/questions/38781189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6349039/" ]
`npm update -g firebase-tools` or `npm install -g firebase-tools@3.12.0` to install a specific version And make sure to restart your **terminal/IDE** otherwise, it won't take effect.
it works to me... standalone binary: Download the new version, then replace it on your system if you are using the standalone.[Download the new version](https://firebase.google.com/docs/cli#windows)
21,759,423
I have a variable containing the list of selects, then I'd need to filter and find only those that has dependsOn attribute with the value of 'EventType'. I tried the below but it doesn't find the select and returns 0: ``` var selects = $("select"); var count = selects.find("[dependsOn='EventType']").length alert(count); ``` I wrote the below which works but isn't there an easier way? ``` var dependents = []; selectLists.each(function() { var dep = $(this).attr('dependsOn'); if (dep === undefined) return; dependents.push(dep.val()); }); ```
2014/02/13
[ "https://Stackoverflow.com/questions/21759423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133212/" ]
If that attribute is on the actual `select` tag, just do: ``` var selects = $("select[dependsOn='EventType']"); ``` Although, `dependsOn` doesn't seem like a valid attribute. Check out custom `data-*` attributes to have completely valid HTML.
try with you'r browser's console (I'm using chrome) and use this: ``` selects = $("select[dependsOn='EventType']"); ``` It worked just fine for me. Hope it helps!!
18,983,071
1. I know you shouldn't, in general, use Regex with HTML. I am using it as a one time tool to strip some data quickly out of a file that has a constant pattern and it will never be used again. I want to use Regex for this task. **I understand that you should not parse HTML with Regex.** 2. No I do not want to use an XMl Parser, BeautifulSoup, lxml, etc. Thank you. :) 3. I only want to get this one time use out of this, and be done with it forever. That being said, the regular expression I wrote only matches the last "match" out of the file. I'm not sure why. The file has a fairly constant pattern: ``` <p someAttribute="yes"><b someOtherAttribute="no">My Title - </b> My Description</p> <p someAttribute="yes"><b someOtherAttribute="no">My 2nd Title - </b> My 2nd Description</p> <p someAttribute="yes"><b someOtherAttribute="no">My 3rd Title - </b> My 3rd Description</p> <p class="normal" style="margin-left:1"><b style="font-weight:400">Another one </b>The cake is a lie</p> ``` I don't care about the attributes. I'm trying to group what is in the `<b>` tags and what follows. Title and description. ``` def parseData(html): pattern = re.compile('.*<p.*><b.*>(.+)</b>(.+)</p>.*') matches = re.findall(pattern, str(html)) for match in matches: print(match) def main(): htmlFile = "myFile.htm" browser = UrlBrowser() parseData(browser.getHTML(htmlFile)) ``` This pattern is only matching the last available "match" - I tried adding a `.*` before to see if that would be the issue, but it didn't make a difference. What am I missing on the regex?
2013/09/24
[ "https://Stackoverflow.com/questions/18983071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/783284/" ]
This should do it. See this [working demo](https://eval.in/50433) ``` matches = re.findall(r'<b[^>]+>(.*?)</b>(.*?)</p>', str) ``` Regular expression: ``` <b match start of tag '<b' [^>]+ any character except: '>' (1 or more times) > match enclosed '>' ( group and capture to \1: .*? any character except \n (0 or more times) ) end of \1 </b> match '</b>' ( group and capture to \2: .*? any character except \n (0 or more times) ) end of \2 </p> match '</p>' ``` You are using `.*` which is greedy (matching the most amount possible). You want to add `?` to the end of that making it a non greedy (matching the least amount possible) Taking the explanation from the `re` documentation discussing the following quantifiers `?`, `+?`, `??` > > The \*, '+', and '?' qualifiers are all greedy; they match as much > text as possible. Sometimes this behaviour isn’t desired; if the RE > <.*> is matched against '<H1>title</H1>', it will match the entire > string, and not just '<H1>'. Adding '?' after the qualifier makes it > perform the match in non-greedy or minimal fashion; as few characters > as possible will be matched. Using .*? in the previous expression will > match only '<H1>'. > > >
It's your leading .\* that's causing the last-match. The \* and + qualifiers will match as many as possible of the preceding item while still producing a match Use the "non-greedy" \*? in place of each \*, and +? in place of each + to get the shortest possible sequence that produces a match. See: <http://docs.python.org/3.3/library/re.html#regular-expression-syntax>
11,777,921
I have a Facebook app that I want to use to post on my customer's Facebook Page Walls on their behalf. I have it setup now so that when they authenticate my app I get the Access token, but when I go to post to the wall I am getting the following error: "OAuthException: Error validating access token: The session is invalid because the user logged out." How can I post from my script without being logged in? Here is my code: ``` include_once('fb-php-sdk/src/facebook.php'); $facebook = new Facebook(array( 'appId' => 'XXX', 'secret' => 'XXX', )); try { $page_id = '215133535279290'; //page id of the customer's facebook page $args = array( 'access_token' => 'XXX', //access token received when user authenticated app 'message' => 'A test message' ); $post_id = $facebook->api("/$page_id/feed","post",$args); } catch (FacebookApiException $e) { echo "Error:" . $e; } ```
2012/08/02
[ "https://Stackoverflow.com/questions/11777921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892221/" ]
I don't any `@Equal` contraint in other Java framework neither in the JSR 303. To check for password, it's not difficult: in your form object, just write a `public String validate()` method: ``` public class SignupForm { @Min(6) public String password; @Min(6) public String confirmPassword; public String validate() { if(!password.equals(confirmPassword)) { return "Password mismatch"; } return null; } } ``` Take a look at the [zentask sample](https://github.com/playframework/Play20/blob/master/samples/java/zentasks/), in this [class](https://github.com/playframework/Play20/blob/master/samples/java/zentasks/app/controllers/Application.java#L14).
The below code returns global error. ``` public String validate() { if(!password.equals(confirmPassword)) { return "Password mismatch"; } return null; } ``` But the snippet below more specifically returns error specific to confirmPassword field. ``` public List<ValidationError> validate(){ List<ValidationError> errors = new ArrayList<ValidationError>(); if(!this.password.equals(this.confirmPassword)){ errors.add(new ValidationError("confirmPassword", "Password should be same.")); } return errors.isEmpty() ? null : errors; } ``` [Here](https://www.playframework.com/documentation/2.4.x/JavaForms) is the official documentation that describes more on this.
6,246,108
Im having a issue with my code i am working on. I am trying to get a include loaded depending on the status of the user (if they paid and if they have a invalid email. The NULL value is being pulled form the database however it only sends to the entermail.php Here is my code does anyone see whats wrong? ``` function is_premium() { $premium_query = mysql_query("SELECT 'authLevel' FROM 'users' WHERE 'fbID' ='".$userId."'"); $premium = mysql_query($premium_query); if ($premium=='1') { return true; } else { return false; } } function valid_email() { $validemail_query = mysql_query("SELECT 'parentEmailOne' FROM 'users' WHERE 'fbID' ='".$userId."'"); $validemail = mysql_query($validemail_query); if ($validemail != 'NULL') { return true; } else { return false; } } if (!empty($session) && is_premium() && valid_email()) { include 'indexPremium'; } else if (!empty($session) && valid_email()) { include 'entermail.php'; } else if (!empty($session)) { include 'indexLoggedIn.php'; }else{ include 'indexNotLogged.php'; } ```
2011/06/05
[ "https://Stackoverflow.com/questions/6246108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try this in the `validemail` function: ``` if (!is_null($validemail)) { return true; } else { return false; } ```
Your functions are not using any parameters. And please use parametrized queries or escaping.
28,721,877
Im trying to write a Batch script that will log onto a bunch of xp computers (from a supplied list) and get the file modifed info for a particular file. (Same file and location on each Pc) When the script runs it completes and logs onto each PC ok, but for some reason it passes a null value to `%filename%` and in the results file im getting an echo on message where the file modified info should be. The problem seems to lie in the section of my code below (full script is at bottom): ``` set filename="G:\Documents and settings\user\desktop\samplefile.txt" for %%C in (%filename%) DO (SET "bodytext=%bodytext%samplefile for %%A updated at %%~tC") echo %bodytext% > results.txt ``` When I run just the above section of code by itself it works, so im assuming that when I map to the G drive and try to asssign the filename variable its not working. Any ideas or help is appreciated. Thanks Full Script ``` for /F "tokens=1,2 delims=," %%A in (list_of_machines.txt) do ( net use G: \\%%A\c$ /User:domain\user password echo processing IP_Address=%%A Hostname=%%B >> results.txt set filename="G:\Documents and settings\user\desktop\samplefile.txt" for %%C in (%filename%) DO (SET "bodytext=%bodytext%samplefile for %%A updated at %%~tC") echo %bodytext% > results.txt net use G: / delete ) ```
2015/02/25
[ "https://Stackoverflow.com/questions/28721877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4601062/" ]
I solved it by using the load callback function in steead of the when/done structure. ``` $('.lightbox').after('<div id="insertnationalcontent"></div>') $('#insertnationalcontent').load(loadlink, function() { $('#insertnationalcontent .lightbox').remove(); }); ```
`remove` should end properly with a `semi-colon` as it's a statement inside an anonymous function in `done` unlike the arguments you pass to `when` ``` $('#eucontentpage #country-choice .lang-ico').click(function(){ $.when( $('.lightbox').after('<div id="insertnationalcontent"></div>') ).done(function() { $.when( $("#insertnationalcontent").load(loadlink) ).done(function() { $('#insertnationalcontent .lightbox').remove(); }); }); return false; }); ```
15,080,557
I have a ListView with a onListItemListener, I have it so if you tap a ListView Item it removes it, but for some reason if I remove the last item form the list, the app crashes and gives me this error `(java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3)` Does anyone have any idea what that means? This is my code: ``` @Override protected void onListItemClick(ListView l, View v, int pos, long id) { super.onListItemClick(l, v, pos, id); adapter.remove(adapter.getItem(pos)); adapter.notifyDataSetChanged(); } ```
2013/02/26
[ "https://Stackoverflow.com/questions/15080557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1262576/" ]
I believe I've figured it out, all the answers that said that the `pos` variable was one number too high seemed logical, but I tried them all and they didn't work. It seems what was wrong was, when I would remove the last item from the list, it would try to refresh the ListView but there wouldn't be anything in it to refresh, so therefore the app would crash, I changed my code a little bit and it works great now! :) I dont fully understand why it works, but it does! Thanks for all the answers guys! ``` @Override protected void onListItemClick(ListView l, View v, int pos, long id) { super.onListItemClick(l, v, pos, id); if (adapter.getCount() != adapter.getItemId(pos)) { adapter.remove(adapter.getItem(pos)); adapter.notifyDataSetChanged(); } } ```
According to the [documentation](http://developer.android.com/reference/android/app/ListActivity.html#onListItemClick%28android.widget.ListView,%20android.view.View,%20int,%20long%29) you should have been using id as the value to remove the item. like this: ``` adapter.remove(adapter.getItem(id)); ```
44,105,427
I want to display my date as day/month/year. example 31st October 2011 ``` echo '<h4>Date Of Birth: '.$row['dob'].'</br></h4>'; ```
2017/05/22
[ "https://Stackoverflow.com/questions/44105427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7425144/" ]
You can try below code ::- ``` echo '<h4>Date Of Birth: '.date('dS F Y', strtotime($row['dob'])).'</br></h4>'; // ^^^^^^^ Here the is format of date, in which format you want. ``` **Output will be ::-** > > 31st October 2011 > > > For more you can refer [click here](http://php.net/manual/en/function.date.php)
So if you have that data stored as or you can convert it to 3 variables representing DD MM YYYY then I'd suggest creating array of months and an array of *post-fixes*(don't know how to call it, but in your example it's 31**st**) and getting DD % 10 to use reminder for *post-fix* array ``` $month = ['January','February',....,'December']; //remember it's $month[MM-1]; $post = ['th','st','nd',...,'th'] //not sure if this on is correct but hope you get the idea ```
26,471,239
How do I place a constant in an Interface in typescript. Like in java it is: ``` interface OlympicMedal { static final String GOLD = "Gold"; static final String SILVER = "Silver"; static final String BRONZE = "Bronze"; } ```
2014/10/20
[ "https://Stackoverflow.com/questions/26471239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2658276/" ]
You cannot declare values in an interface. You can declare values in a module: ``` module OlympicMedal { export var GOLD = "Gold"; export var SILVER = "Silver"; } ``` In an upcoming release of TypeScript, you will be able to use `const`: ``` module OlympicMedal { export const GOLD = "Gold"; export const SILVER = "Silver"; } OlympicMedal.GOLD = 'Bronze'; // Error ```
Since nobody gave the actual answer of how to do it with an `interface` (to be used in interface/class merging for example). ``` interface Medals { GOLD: 'gold'; SILVER: 'silver'; BRONZE: 'bronze'; } ``` This will make ``` const a: Medals = { ... } // type of a.GOLD is the literal 'gold' ``` Although you should consider using an `enum` or `const medals = { ...definition } as const` or even a `class`. #### Appendix: Objects, Arrays and Classes Const arrays and const objects can be done like this. ``` const constArray = ['array', 'of', 'emperor', 'Constantine'] as const; const constObj = { gold: 'GOLD', silver: 'SILVER', bronze: 'BRONZE' } as const; interface Constants { constArray: typeof constArray; constObj: typeof constObj; } const obj: Constants = {} as any; const str = obj.constArray[3]; // str has type 'Constantine' const gold = obj.constObj.gold; // gold has type 'gold' ``` For a class-based approach ``` class Medals { static readonly GOLD = 'gold'; static readonly SILVER = 'silver'; static readonly BRONZE = 'bronze'; } // Medals.GOLD has literal type 'gold' ```
71,725,758
[MDN says](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/marker-end) you can use CSS to define a `marker-end` value for an SVG `<path>`, but all the examples use a `url(#...)` syntax which refers to an existing element in the drawing. Is it possible to define a marker completely inside the CSS, such that by changing a stylesheet it can change the marker style to a completely different shape? As in, one that wasn't already defined in the image? Or would I have to include all these options inside the image itself, and the CSS can only choose which one it uses? (I tried a few `data:` URL solutions, didn't work for me.)
2022/04/03
[ "https://Stackoverflow.com/questions/71725758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/472388/" ]
It's not completely impossible, but there are some obstacles. You can style the marker shape with CSS, but not by changing the style of the path that uses the marker. You need to change the style of the marker definition itself. Consequently, you would need a unique marker for every path you want to decorate, otherwise all elements referencing the same `<marker>` would change at once. Also you can only change the presentation attributes of the **content** of the `<marker>` element. Its own attributes (`markerWidth`, `markerHeight`, `refX`, `refY`, `orient`) are all XML, not presentation attributes. But you **can** change the marker shape. One strategy might be to define multiple shapes, and set all of them to `display: none` save the one you currently want to show. Or, since now Chrome and Firefox have implemented the `d` property in CSS, you can also redefine a shape like this: ```css svg { width: 200px; display: block; } input ~ svg #marker { --shape: path('M2,2 H8 V8 H2 z'); --color: green; } input:checked ~ svg #marker { --shape: path('M5,0 10,5 5,10 0,5 z'); --color: red; } #marker path { d: var(--shape); fill: var(--color); } #usage { stroke: black; marker-end: url(#marker); } ``` ```html <input id="switch" type="checkbox"> <label for="switch">Switch marker</label> <svg viewBox="0 0 30 30"> <marker id="marker" viewBox="0 0 10 10" orient="auto" markerWidth="6" markerHeight="6" refX="5" refY="5"> <path /> </marker> <path id="usage" d="M5,18 25,12" /> </svg> ``` Lokking at this pattern, you might be tempted to compare it to the way you can inherit CSS custom properties inside the shadow DOM by setting them on `<use>` elements. Alas, this does not work for referenced markers: ```css svg { width: 200px; display: block; } input ~ svg #usage { --shape: path('M2,2 H8 V8 H2 z'); --color: green; } input:checked ~ svg #usage { --shape: path('M5,0 10,5 5,10 0,5 z'); --color: red; } #marker path { d: var(--shape); fill: var(--color); } #usage { stroke: black; marker-end: url(#marker); } ``` ```html <input id="switch" type="checkbox"> <label for="switch">Switch marker</label> <svg viewBox="0 0 30 30"> <marker id="marker" viewBox="0 0 10 10" orient="auto" markerWidth="6" markerHeight="6" refX="5" refY="5"> <path /> </marker> <path id="usage" d="M5,18 25,12" /> </svg> ```
Here's a marker encoded as a data URL. It works on Firefox but it seems [Chrome still doesn't support external markers](https://bugs.chromium.org/p/chromium/issues/detail?id=109212). ```html <svg viewBox="0 50 120 120" xmlns="http://www.w3.org/2000/svg"> <polyline fill="none" stroke="black" points="40,60 70,80" marker-end='url(data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%20120%20120%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cdefs%3E%3Cmarker%20id%3D%22triangle%22%20viewBox%3D%220%200%2010%2010%22%20refX%3D%221%22%20refY%3D%225%22%20markerUnits%3D%22strokeWidth%22%20markerWidth%3D%2210%22%20markerHeight%3D%2210%22%20orient%3D%22auto%22%3E%3Cpath%20d%3D%22M%200%200%20L%2010%205%20L%200%2010%20z%22%20fill%3D%22%23f00%22%2F%3E%3C%2Fmarker%3E%3C%2Fdefs%3E%3C%2Fsvg%3E#triangle)'/> </svg> ```
17,965,626
I have two class, `User` and `Status`, while a user will have a number of status, this is naturally `Many-to-One` relation and can be easily mapped to DB Tables. However, the requirement also need User to maintain its “current” status, i.e., in the `User` Table, it need to have a foreign-key to the `Status` table. The result of this is having two foreign-keys between two tables in the opposite direction. One obvious problem of this is once the records are inserted into the two tables, I can delete neither of them cause deleting from one table will violate the other table's foreign-key. What is the best Design for this situation?
2013/07/31
[ "https://Stackoverflow.com/questions/17965626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/185668/" ]
you should use model without inheriting from `ActiveRecord::Base` class. ``` class ContactPageMessage include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :whatever validates :whatever, :presence => true def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end def persisted? false end end ``` Through this you will able to initialize new object and able to call validations on that object. I think you have a different class name with same name, in your controller code, I can see this : ``` if ContactPageMessage.received(params).deliver redirect_to contacts_path, :notice => "Success" else ``` if this is your mailer class change its name to `ContactPageMessageMailer`. you will no loger get that error. Hope it will help. Thanks
In your model you can add the below which will just set getter and setter method for message and you can have validation on message without having a column in the db ``` attr_accessor :message validates :message, presence: true ```
37,811,034
I have an HTML `<table>` with many columns, so when my web page is displayed on a mobile browser, it's too small. So I'm creating a media query and I want to remove some columns (That are not important). So how to remove an html column using only css ? For example, how to remove the column "B" in the middle of the table on the next example : ```css table, th, td, tr{ border:1px solid black; } table{ width:100%; } ``` ```html <table> <th>A</th> <th>B</th> <th>C</th> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> ```
2016/06/14
[ "https://Stackoverflow.com/questions/37811034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5456540/" ]
The proper way is using `col` elements with `visibility: collapse`. ```html <colgroup> <col /> <col /> <col /> </colgroup> ``` ```css col:nth-child(2) { visibility: collapse; } ``` ```css table, th, td, tr { border: 1px solid black; } table { width: 100%; } col:nth-child(2) { visibility: collapse; } ``` ```html <table> <colgroup> <col /> <col /> <col /> </colgroup> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </tbody> </table> ``` This way will work properly even if you use `colspan`. However, note the layout of the table will be calculated before hiding the columns. And at the end, the remaining columns won't grow to make the table respect `width: 100%`. As described in [Dynamic effects](https://www.w3.org/TR/CSS21/tables.html#dynamic-effects), this avoids expensive re-layout operations. To compensate this, you can increase the width of the table beyond `100%`. ```css div { overflow: hidden; margin: 20px 0; } table, th, td, tr { border: 1px solid black; } table { width: 100%; table-layout: fixed; } table.grow { width: 150%; } col.hidden { visibility: collapse; } ``` ```html <div> Full table <table> <colgroup> <col /> <col /> <col /> </colgroup> <thead> <tr> <th colspan="2">A B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td colspan="2">Eve Jackson</td> <td>94</td> </tr> </tbody> </table> </div> <div> Hiding last column <table> <colgroup> <col /> <col /> <col class="hidden" /> </colgroup> <thead> <tr> <th colspan="2">A B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td colspan="2">Eve Jackson</td> <td>94</td> </tr> </tbody> </table> </div> <div> Hiding last column and enlarging table <table class="grow"> <colgroup> <col /> <col /> <col class="hidden" /> </colgroup> <thead> <tr> <th colspan="2">A B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td colspan="2">Eve Jackson</td> <td>94</td> </tr> </tbody> </table> </div> ```
To remove the second column: ``` table tr>th:nth-of-type(2), table tr>td:nth-of-type(2){ display: none; } ``` ```css table, th, td, tr { border: 1px solid black; } table { width: 100%; } @media (max-width: 900px){ /* use your media breakpoint */ table tr>th:nth-of-type(2), table tr>td:nth-of-type(2){ display: none; } } ``` ```html <table> <tr> <th>A</th> <th id="foo">B</th> <th>C</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> ``` [JSFiddle](https://jsfiddle.net/4k81rumy/) **Note**: your HTML is not valid - `th` must also be inside the `tr` element.
37,579,134
Need help with splitting the below. ``` 100GB@sdb,100GB@sdc ``` Into this ``` sdb sdc ``` Everything I've tried keeps giving me ``` sdb 100GB ```
2016/06/01
[ "https://Stackoverflow.com/questions/37579134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5849019/" ]
**Update** This is not relevant anymore in the new V3-beta.2 router. **Original** Change ``` @Routes([ {path: '', component: SchoolyearsHomeComponent}, {path: '/create', component: CreateSchoolyearComponent} ]) ``` to ``` @Routes([ {path: '/create', component: CreateSchoolyearComponent}, {path: '', component: SchoolyearsHomeComponent}, ]) ``` The order of routes is currently significant. The most specific routes should come first, the least specific routes last. This is a known issue and should be fixed soon.
You need to inject the router into the app component, something like this: ``` export class AppComponent { constructor(private router: Router) {} } ``` This is normally needed when the template associated with this component does not use the `<router-link>` directive. A recent change to Angular does not load the router component when only using the `<router-outlet>`
45,914,596
How to make primary key of one table, the foreign key of the same table? I have table `vendors` with these attributes: ``` vendor_id, company_name rep_first rep_last referredby ``` Do I want to make `vendor_id` as the foreign key of that table? Here is what I have tried: ``` create table vendors( vendor_id char(5) Not Null primary key, company_name varchar(255), rep_first varchar(255), rep_last varchar(255), referredby char(5) ); constraint vendors_REF_FK foreign key (referredby) references vendors(referredby) ```
2017/08/28
[ "https://Stackoverflow.com/questions/45914596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8445781/" ]
Constraints is also part of the table and thus have to go along with table definition like ``` vendor_id char(5) Not Null primary key, company_name varchar(255), rep_first varchar(255), rep_last varchar(255), refferedby char(5), constraint vendors_REF_FK foreign key (refferedby) references vendors(vendor_id )); ```
You may use `ALTER TABLE` as well ``` ALTER TABLE Vendors ADD CONSTRAINT vendors_REF_FK FOREIGN KEY (refferedby) REFERENCES Vendors(vendor_id ); ```
26,782,235
We have an application that uses Azure SQL for the database backend. Under normal load/conditions this database can successfully run on a Premium 1 plan. However, during the early morning hours we have jobs that run that increase database load. During these few hours we need to move to a Premium 3 plan. The cost of a Premium 3 is about 8 times more, so obviously we do not want to pay the costs of running on this plan 24/7. Is it possible to autoscale the database up and down? Cloud services offer an easy way to scale the number of instances in the Azure Portal, however, nothing like this exists for Azure SQL databases. Can this be done programmatically with the Azure SDK? I have been unable to locate any documentation on this subject.
2014/11/06
[ "https://Stackoverflow.com/questions/26782235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090359/" ]
After digging through the articles in @ErikEJ's answer (Thanks!) I was able to find the following, which appears to be newly published with the release of the Elastic Scale preview: [Changing Database Service Tiers and Performance Levels](http://msdn.microsoft.com/library/azure/dn369872.aspx) The following REST APIs are now newly available as well, which let you do pretty much whatever you want to your databases: [REST API Operations for Azure SQL Databases](http://msdn.microsoft.com/en-us/library/azure/dn505719.aspx) And for my original question of scaling service tiers (ex. P1 -> P3 -> P1): [Update Database REST API](http://msdn.microsoft.com/en-us/library/azure/dn505718.aspx) With these new developments I am going to assume it's only a matter of time before autoscaling is also available as a simple configuration in the Azure Portal, much like cloud services.
Another way to do it is using Azure automation and using run book below: ``` param ( # Desired Azure SQL Database edition {Basic, Standard, Premium} [parameter(Mandatory=$true)] [string] $Edition, # Desired performance level {Basic, S0, S1, S2, P1, P2, P3} [parameter(Mandatory=$true)] [string] $PerfLevel ) inlinescript { # I only care about 1 DB so, I put it into variable asset and access from here $SqlServerName = Get-AutomationVariable -Name 'SqlServerName' $DatabaseName = Get-AutomationVariable -Name 'DatabaseName' Write-Output "Begin vertical scaling script..." # Establish credentials for Azure SQL Database server $Servercredential = new-object System.Management.Automation.PSCredential("yourDBadmin", ("YourPassword" | ConvertTo-SecureString -asPlainText -Force)) # Create connection context for Azure SQL Database server $CTX = New-AzureSqlDatabaseServerContext -ManageUrl “https://$SqlServerName.database.windows.net” -Credential $ServerCredential # Get Azure SQL Database context $Db = Get-AzureSqlDatabase $CTX –DatabaseName $DatabaseName # Specify the specific performance level for the target $DatabaseName $ServiceObjective = Get-AzureSqlDatabaseServiceObjective $CTX -ServiceObjectiveName "$Using:PerfLevel" # Set the new edition/performance level Set-AzureSqlDatabase $CTX –Database $Db –ServiceObjective $ServiceObjective –Edition $Using:Edition -Force # Output final status message Write-Output "Scaled the performance level of $DatabaseName to $Using:Edition - $Using:PerfLevel" Write-Output "Completed vertical scale" } ``` Ref: [Azure Vertically Scale Runbook](https://gallery.technet.microsoft.com/scriptcenter/Azure-SQL-Database-e957354f) Setting schedule when u want to scale up/down. For me, I used 2 schedules with input parameters, 1 for scaling up and another one for scaling down. Hope that help.
35,739,975
I have two apps, App1 and App2. I,m saving some data in App2 and accessing in App1. So when i,m coming back to App1 from App2 using backpress, shared pref data will not refresh that i,m accessing from App2. On removing App1 from background and coming back to same page will do the work. So, what should I do such that, Shared Pref Data in App1 will fetch the latest data I,ve stored in App2 ?
2016/03/02
[ "https://Stackoverflow.com/questions/35739975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5986048/" ]
You can assign an IAM role to your instance using the following workaround: * Create an AMI for your instance; * Terminate your old instance; * Re-deploy it again from previously created AMI and assing an IAM role during the process.
Assigning an IAM (Identity and Access Management) **Role** to an Amazon EC2 instance is a way of securely providing rotating credentials to applications running on an EC2 instance. Such roles must be assigned **when the instance is first launched**. If the instance you would like to use has already been launched, either: * Launch a new instance ("Launch More Like This") with a Role, or * Create a User in IAM: You will receive an Access Key and Secret Key that can be configured in the instance by using the `aws configure` command. This is part of the [AWS Command-Line Interface (CLI)](http://aws.amazon.com/cli/). See documentation: [Using an IAM Role to Grant Permissions to Applications Running on Amazon EC2 Instances](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html)
19,664,273
I have the method below writen in Delphi: `function acceptPutNF(const aJSONObject: TJSONObject; const aJSONArray: TJSONArray): TJSONObject;` I'm trying to send a PUT request, but I don't know how to specify the second parameter/object data `aJSONArray` with python. I tried this: ``` nfe = {'CodigoUsuario':1,'CodigoEmpresa':1,'Originario':'1','CodigoCliente':1,'CodigoTransportador':1,'NaturezaOperacao':'1', 'IndicadorPagamento':'1','ValorFrete':1,'ValorSeguro':1,'ValorOutrasDespesas':1,'ValorProdutosServicos':1,'ValorDescontoGlobal':1,'nformacoesContr':None} nfe_itens = [{'CodigoProduto':1,'CodigoGradeProduto':1,'Quantidade':1,'ValorUnitario':1,'DescontoUnitario':1}] nfe_encoded = json.dumps(nfe) nfe_itens_encoded = json.dumps(nfe_itens) print nfe_encoded url = 'http://localhost:88/datasnap/rest/TServerMethods/PutNF' r = requests.put(url, data={nfe_encoded, nfe_itens_encoded}) ``` I get an error message in the last instruction...
2013/10/29
[ "https://Stackoverflow.com/questions/19664273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995464/" ]
What you pass to data should be encoded. You are encoding the two structures then building an unencoded structure around it. Try this ``` r = requests.put(url, data=json.dumps([nfe, nfe_itens]) ```
I ended up using just one object data parameter with a "sub-object", and then I manage it on my server. I think it is the better way to use more of available features that JSON provides.
1,327,951
In the course of my study of metric spaces I've come across some terminology which I can't seem to understand completely. So, assuming $X=\mathbb{R}$, and $\mathbb{Q}\subset X$ is the set of the rational numbers, what exactly are: * $\mathbb{Q}^\circ$ * int $\mathbb{Q}$ * $\partial\mathbb{Q}$ * $\bar{\mathbb{Q}}$ Everywhere I looked, there is always a quite confusing explanation.
2015/06/16
[ "https://math.stackexchange.com/questions/1327951", "https://math.stackexchange.com", "https://math.stackexchange.com/users/212451/" ]
I believe the first two denote interior, the third boundary, and the fourth closure. The *interior* of a set is the largest open set included in it. Equivalently, it is the union of all open sets included in it: $$\operatorname{int} S\equiv\bigcup\{U\,|\,U\text{ is open and }U\subseteq S\}.$$ Analogously, the *closure* of a set is the smallest closed set that includes it. Equivalently, it is the intersection of all closed sets including it: $$\overline S\equiv\bigcap\{C\,|\,C\text{ is closed and }S\subseteq C\}.$$ The *boundary* of a set is simply the set of points in the closure but not in the interior: $$\partial S\equiv \overline S\setminus\operatorname{int} S.$$ --- In the case of the rationals, one has that \begin{align\*} \operatorname{int}\mathbb Q=&\,\varnothing,\\ \overline{\mathbb Q}=&\,\mathbb R,\\ \partial{\mathbb Q}=&\,\mathbb R. \end{align\*} Why? Note that every non-empty open subset of $\mathbb R$ contains a non-empty open interval and every non-empty interval, in turn, contains irrational numbers. Hence, $\mathbb Q$ cannot have any non-empty open set as its subset, so the largest open set included in it is the empty set. On the other hand, if $C\subseteq\mathbb R$ is a closed set containing $\mathbb Q$, then $C$ must contain all irrationals, too, because every irrational is a limit of some sequence of rational numbers and the set $C$ is closed. Hence, it must be the case that $C=\mathbb R$. It follows that the smallest closed set containing $\mathbb Q$ is, in fact, $\mathbb R$.
Int $\mathbb{Q} = \emptyset$, since, if you have an arbitrary $x \in \mathbb{Q}$, no matter how you choose an $r>0$, the x-centered ball($B(x,r)$), with $r$ radius will always contain an irrational number, therefore it is not an internal point. Since our $x$ was arbitrary, the set of interal points must be empty. $\rightarrow Int \mathbb{Q} = \emptyset$ Let us discuss $\bar{\mathbb{Q}}$ next. $\bar{\mathbb{Q}} = \mathbb{Q} \cup \mathbb{Q'}$. Let us have an arbitrary $x \in \mathbb{R}$, no matter how you choose an $r>0$, the x-centered ball($B(x,r)$), with $r$ radius will always contain a rational number, therefore, every $x$ will be element of $\mathbb{Q'}$, so $\bar{\mathbb{Q}}= \mathbb{Q} \cup \mathbb{Q'}= \mathbb{Q} \cup \mathbb{R}=\mathbb{R}$. For that, we tend to say, that rational numbers are dense. $\partial\mathbb{Q}=\bar{\mathbb{Q}}$ \ $Int(\mathbb{Q})$. Since we discussed, that $Int(\mathbb{Q}) = \emptyset$, that will be $\mathbb{R}$ too. By the way, $\mathbb{Q}^\circ$ and int $\mathbb{Q}$ are equivalent.
5,372,680
Im trying to send keystrokes and mouse movements to a Java program but once the applicaton has focus nothing is sent. It's as if the Java application takes focus of everything because Autohotkey stops responding. Everything works fine in a regular Windows app (e.g. Notepad). I've tried using various send methods (Send, SendInput, and SendEvent) but nothing works. Does anyone have any suggestions? The program in particular is ThinkOrSwim's ThinkDesktop.
2011/03/21
[ "https://Stackoverflow.com/questions/5372680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322772/" ]
Some playing around I've discovered that TOS on Mac OSX can be controlled via scripting with [Keyboard Maestro](http://www.keyboardmaestro.com). It's a ugly, hacked solution, but it works. You can edit text boxes and click stuff if you know the X,Y position of elements. Keyboard Maestro can be run via scripts (AppleScript, Python, etc.) so maybe you can build some elaborate rube goldberg.
I suggest you use Easy Macro Recorder <http://download.cnet.com/Easy-Macro-Recorder/3000-2094_4-10414139.html> Its a great tool to automate keystrokes and mouse movements. Hope this helps :)
2,179,263
I would like to learn a functional programming language to see a different programming paradigm. My background in programming: Java (I have just passed the SCJP exam), some ruby and very limited Rails. I use bash for basic sysadmin tasks. I use Ubuntu 9.04. As a second goal I would like to use fp to show kids (14-18 years olds) how math and cs interrelated. The guys are very good at programing (they are learning Python and Java at politechnical high school from the first year). However as tests show, they have difficulties with math esp. basic concepts of discrete math. I think we can develop their math skills by using programming (and I possibly that can be the topic of my teacher training thesis). I think a language with very basic vocabulary would serve this project best.
2010/02/01
[ "https://Stackoverflow.com/questions/2179263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260145/" ]
If your primary goal is to work with teens, it makes sense to use the functional-language pedagogy and technology that is proven to work with teens, and that is [PLT Scheme](http://plt-scheme.org/) (aka DrScheme) with the [How To Design Programs](http://htdp.org/) book (also free online). These guys have got great results from middle school through 3rd semester university. They have [resources for teachers](http://teach-scheme.org/) as well. Many respondents like SICP. It is a wonderful book—but not to *learn* from. If you already know Scheme, it is a good book to *admire*, but SICP is less about functional programming and more about how to implement all known interesting computer-science ideas in Scheme. If your primary goal is to learn a really new programming paradigm, then Scheme lacks some features that are very important to many functional programmers: * Programming with pattern matching * Partial application of curried functions * A polymorphic static type system * Pure functional computation If you want exciting ideas, try [Haskell](http://www.haskell.org/); Haskell makes it a lot harder for you to program your old thoughts in the new language. Instead, Haskell forces you to think new thoughts. In addition to many other resources, [Real World Haskell](http://www.realworldhaskell.org/) is free online. Final note: SO has had many [similar questions](https://stackoverflow.com/questions/779800) on learning functional programming.
My question is what approach is likely to be best for the teens you're working with. If they're willing to learn something new and different, Scheme is an excellent choice as a functional language. It's as basic as they come. If you want to keep to a more familiar syntax, Haskell might be your answer.
20,475
I'm trying to prove that ${n \choose r}$ is equal to ${{n-1} \choose {r-1}}+{{n-1} \choose r}$ when $1\leq r\leq n$. I suppose I could use the counting rules in probability, perhaps combination= ${{n} \choose {r}}=\frac{n!}{r!(n-r!)}$. I want to see an actual proof behind this equation. Does anyone have any ideas?
2011/02/04
[ "https://math.stackexchange.com/questions/20475", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
See this Wikipedia page: * <http://en.wikipedia.org/wiki/Binomial_coefficient> Under the subsection **Recursion formula**, *HINT* for proving this formula is given. Hope you can do it from there. > > The formula follows either from tracing the contributions to $X^{k}$ in $(1 + X)^{n−1}(1 + X)$, or by counting k-combinations of {1, 2, ..., n} that contain n and that do not contain n separately > > >
Consider, $$ (1+x)(1+x)(1+x)(1+x).. \text{n times}$$ Notice that sequence of each factor is given as: $$ \{a\_i \} = \{ 1,1, 0, 0... \}$$ By $b\_i^j$ denote the coefficents of $x^i$ term in the product of $j$ factors, from cauchy product rule: $$ b\_0^0 =1$$ $$ b\_k^1= \sum\_{i=0}^k b\_i^0 a\_{k-i}$$ $$ b\_k^2 = \sum\_{i=0}^k b\_k^1 a\_{k-i} $$ $$ \vdots$$ by induction, $$ b\_k^n = \sum\_{i=0}^k b\_k^{n-1} a\_{k-i}= \sum\_{i=0}^k b\_k^{n-1} a\_{k-i}= \sum\_{i=0}^k b\_{k-i}^{n-1} a\_i = b\_k^{n-1} + b\_{k-1}^{n-1}$$ Hence, $$ b\_k^n =b\_k^{n-1} + b\_{k-1}^{n-1}$$ Now use the fact that coefficent of binomial product is just the binomial coefficent: $$ \binom{n}{k} = \binom{n-1}{k} + \binom{n-1}{k-1}$$
8,985,869
I'm trying to get camera preview data, but I don't want to show the preview. Unfortunatelly ``` setPreviewCallback( PreviewCallback ) ``` doesn't work unless you call ``` setPreviewDisplay(SurfaceHolder) ``` Is it possible to pass this in any way - start callbacks without setting the preview display, or any way of hiding the display?
2012/01/24
[ "https://Stackoverflow.com/questions/8985869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972896/" ]
**Update** As noted in the comments, versions of the SDK after Windows 7's do not include the build tools. If you want to use Microsoft's most recent tools you have to install Visual Studio. Once installed, you can use the tools from the command-line. At the moment the free versions are the "Community" versions, e.g. [Microsoft Visual Studio Community 2015](https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx). You can continue to develop apps for Windows 7 and earlier (and they will run on later versions of Windows) using the old SDK tools as I described before: **Original Answer** If you desperately want to avoid Visual Studio, download and install the [Windows SDK](http://www.microsoft.com/download/en/details.aspx?id=8279). This contains (more or less) the same build tools as Visual Studio. Then run the Windows SDK Command Prompt (which you'll find on the start menu under Microsoft Windows SDK) to set the path to point to the tools, and you are set. Or just use Visual C++ Express.
You have to figure out where NVIDIA GPU Computing Toolkit is installed. In my system it's in "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\bin\nvcc.exe" Then 1. "Edit Environment Variables" on Windows. 2. Click on New... 3. Variable name: NVCC Variable Value: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\bin\nvcc.exe 4. Click on OK.
23,781,034
I'm trying to load a JavaScript array with an array from my model. Its seems to me that this should be possible. Neither of the below ways work. Cannot create a JavaScript loop and increment through Model Array with JavaScript variable ``` for(var j=0; j<255; j++) { jsArray = (@(Model.data[j]))); } ``` Cannot create a Razor loop, JavaScript is out of scope ``` @foreach(var d in Model.data) { jsArray = d; } ``` I can get it to work with ``` var jsdata = @Html.Raw(Json.Encode(Model.data)); ``` But I don't know why I should have to use JSON. Also while at the moment I'm restricting this to 255 bytes. In the future it could run into many MBs.
2014/05/21
[ "https://Stackoverflow.com/questions/23781034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3660362/" ]
I was integrating a slider and needed to get all the files in the folder and was having same situationof C# array to javascript array.This solution by @heymega worked perfectly except my javascript parser was annoyed on `var` use in `foreach` loop. So i did a little work around avoiding the loop. ``` var allowedExtensions = new string[] { ".jpg", ".jpeg", ".bmp", ".png", ".gif" }; var bannerImages = string.Join(",", Directory.GetFiles(Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "Images", "banners"), "*.*", SearchOption.TopDirectoryOnly) .Where(d => allowedExtensions.Contains(Path.GetExtension(d).ToLower())) .Select(d => string.Format("'{0}'", Path.GetFileName(d))) .ToArray()); ``` And the javascript code is ``` var imagesArray = new Array(@Html.Raw(bannerImages)); ``` Hope it helps
``` @functions { string GetStringArray() { var stringArray = "["; for (int i = 0; i < Model.List.Count; i++) { if (i != Model.List.Count - 1) { stringArray += $"'{Model.List[i]}', "; } else { stringArray += $"'{Model.List[i]}']"; } } return stringArray; } } <script> var list = @Html.Raw(GetStringArray()); </script> ```
13,118,418
I set the background color of the outer div to blue but it is not displayed. Why? A demo of it: ```css .question-template { width: auto; height: auto; background-color: blue; } .question { float: left; margin: 10px; } .participants { background-color: green; float: left; margin: 10px; } ``` ```html <body> <div class="question-template"> <div class="participants">234</div> <div class="question">Some lorem ipsum text</div> </div> </body> ``` [jsFiddle](http://jsfiddle.net/4zjtp/)
2012/10/29
[ "https://Stackoverflow.com/questions/13118418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337934/" ]
Try like this.. ``` .question-template { width: auto; height: auto; background-color: blue; overflow:auto; } ```
***[Live demo](http://jsfiddle.net/4zjtp/1/)***........... Hi now define your **parent div** `.question-template overflow:hidden;` ``` .question-template{ overflow:hidden; } ``` --- **Method two** now clear your parent **Css** ``` .clr{ clear:both; } ``` **HTML** ``` <div class="question-template"> <div class="participants">234</div> <div class="question">Some lorem ipsum text</div> <div class="clr"></div> </div> ``` ***[Live demo](http://jsfiddle.net/4zjtp/6/)***
38,634,766
I am using IntelliJ IDEA, learning Java. All went well until yesterday, when the mentioned error occurred. I didn't make any changes. I was looking for the solution the following ways: 1. reboot the pc 2. restart IntelliJ. 3. delete the project directory and use another one (both on desktop) nothing helps. buy running simple hello world method. It keeps showing this error: [![screenshot](https://i.stack.imgur.com/yyvkp.jpg)](https://i.stack.imgur.com/yyvkp.jpg) Is there someone able to help me?
2016/07/28
[ "https://Stackoverflow.com/questions/38634766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6479494/" ]
One reason for this to happen is if you have print statement somewhere on the body of the class, and not inside a method. Here is an example: [![enter image description here](https://i.stack.imgur.com/WRl4X.png)](https://i.stack.imgur.com/WRl4X.png) But if the print is inside a method, it should work fine. Here is an example: [![enter image description here](https://i.stack.imgur.com/Q1203.png)](https://i.stack.imgur.com/Q1203.png)
case 1: if all sdk setup is complete and perfect then file -> invalidated caches / Restart this could work case 2 : if something missing in sdk setup of intelij then goto 1.file->project structure->libraries 2.click on + button 3. add location of lib folder of tomcat directory C:\xampp\tomcat\lib [to add lib directory to tomcat](https://i.stack.imgur.com/S1paI.jpg)
1,538,801
Also part of the problem: Show that: $$\int\_0^{n\pi} f(\cos^2 x)dx=n\int\_0^{\pi} f(\cos^2 x)dx$$ It may be important to note that I have taken a few semester of calculus prior to this, and that this problem was brought up in my math analysis course. Additionally, my class has only taught as far as Riemannian integrals. My work: A) For the first part of this problem ($\int\_0^\frac\pi 2 f(\sin x)dx=\int\_0^\frac\pi 2 f(\cos x)= \frac12\int\_0^\pi f(\sin x)$ ), I intuitively know that the areas under the curve will be equal to each other because the values at the endpoints will be the same, provided that $f(\sin x)=\sin x$ and $f(\cos x)=\cos x$. However, I have two dilemmas: 1) The fact that the situation deals with a function of $\sin x$, not $\sin x$ itself. To give an example, $f(a)$ could be equal to $a^2 + 8a^{-1} + \csc a^3$ and I feel like this completely flaws my logic (note that the above function was just an example to show how arbitrary the function is). In the grand scheme of things, I don't believe this will prove to be too much of an issue, I just don't know how I can prove that it won't be an issue 2) I am unaware of how to definitively prove that the area under each curve will be the same. Suppose $f(a)= a$ for the sake of argument, then the value $f(x)$ at each of the endpoints will be the same, but this does not tell anything about the areas under the curve B) I believe that I understand the second part of the problem. Because $x^2$ will never be negative, the graph of $f(x)$ will either always be negative or always be positive. Therefore, the value of the integral is entirely dependent on $n$. I am primarily concerned with the two dilemmas in the first part of the problem, but any additional assistance is always welcome!
2015/11/20
[ "https://math.stackexchange.com/questions/1538801", "https://math.stackexchange.com", "https://math.stackexchange.com/users/274111/" ]
\begin{align\*}\int\_0^{n\pi}f(\cos^2(x))\mathrm{d}x &= \sum\_{i=0}^{n-1}\int\_{i\pi}^{(i+1)\pi}f(\cos^2(x))\mathrm{d}x \\ &= \sum\_{i=0}^{n-1}\int\_0^\pi f(\cos^2(x))\mathrm{d}x \\ &=n\int\_0^\pi f(\cos^2(x))\mathrm{d}x \end{align\*} You should ask yourself why the third equality is true.
First: $\int\_0^{\pi/2}f(\sin x) dx = \int\_0^{\pi/2}f(\cos y)dy$. (Note the change of the name of the variable. That is only for convenience.) This is solved by doing the substitution $x \mapsto \frac{\pi}{2} - y$. We get $$ \int\_0^{\pi/2}f(\sin x)dx = \int\_{\pi/2}^0-f\big(\sin(\pi/2 - y)\big)dy\\ = \int\_0^{\pi/2}f\big(\sin(\pi/2 - y)\big)dy\\ = \int\_0^{\pi/2}f(\cos y)dy $$ where the steps I've done are, in order, the afformented substitution, then changing the order of the integration limits, then applying the identity $\sin\left(\frac{\pi}{2} - y\right) = \cos y$. As for showing $\int\_0^{\pi/2}f(\sin x)dx = \frac12\int\_0^{\pi}f(\sin x)dx$, we first note that $$\int\_0^{\pi}f(\sin x)dx = \int\_0^{\pi/2}f(\sin x)dx + \int\_{\pi/2}^{\pi}f(\sin x)dx$$ which means that we can subtract $\frac12\int\_0^{\pi/2}f(\sin x)dx$ from each side: $$ \int\_0^{\pi/2}f(\sin x)dx = \frac12\int\_0^{\pi}f(\sin x)dx$$ $$ \frac12 \int\_0^{\pi/2}f(\sin x)dx = \frac12\int\_{\pi/2}^{\pi}f(\sin x)dx\tag{\*} $$ Now, on the right-hand side do the substitution $x \mapsto \pi - y$. This makes the right-hand side into $$ \frac12\int\_{\pi/2}^{0}-f\big(\sin (\pi - y)\big)dy = \frac12\int\_0^{\pi/2}f\big(\sin (\pi - y)\big)dy\\ = \frac12\int\_0^{\pi/2}f(\sin y)dy $$ where in the last line I've applied the identity $\sin (\pi - y) = \sin y$. We now see that it is equal to the left-hand side of $(\text{\*})$ above.
62,727,314
How to convert a camelcased string to sentence cased without excluding any special characters? Suggest a regex for converting camelcased string with special characters and numbers to sentence case?: ``` const string = `includes:SummaryFromDetailHistory1990-AsAbstract` ``` Expected outcome: ``` Includes : Summary From Detail History 1990 - As Abstract ``` Currently I'm using lodash startCase to convert camelCased to sentenceCase. But the issue with this approach is that it is removing special characters like brackets, numbers, parenthesis, hyphens, colons, etc... (most of the special characters) So the idea is to convert camelcased strings to sentence cased while preserve the string identity For example: ``` const anotherString = `thisIsA100CharactersLong:SampleStringContaining-SpecialChar(s)10&20*` const expectedReturn = `This Is A 100 Characters : Long Sample String Containing - Special Char(s) 10 & 20 *` ``` Is that possible with regex?
2020/07/04
[ "https://Stackoverflow.com/questions/62727314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13324968/" ]
The wanted result doesn't seem to be regular, some special characters are supposed to be preceeded with a space and some are not. Treating the parenthesis like you want is a bit tricky. You can use function to handle the parenthesis, like this: ```js let parenth = 0; const str = `thisIsA100CharactersLong:SampleStringContaining-SpecialChar(s)10&20*`, spaced = str.replace(/[A-Z]|\d+|\W/g, (m) => { if (m === '(') { parenth = 1; return m; } if (parenth || m === ')') { parenth = 0; return m; } return ` ${m}`; }); console.log(spaced); ``` If the data can contain other brackets, instead of just checking parentheses, use a RexExp to test any opening bracket: `if (/[({[]/.test(m)) ...`, and test for closing brackets: `if (/[)}\]]/.test(m)) ...`. You can test the snippet with different data at [jsFiddle](https://jsfiddle.net/uLx5zrnp/).
This is impossible. You cannot do this in regex. You will have to consider exceptions...
69,882,148
I'm trying to execute a LINQ query within a plugin, using the OrganizationServiceContext, to retrieve some quotes. On these quotes, I'm using .Select() to only select the value for the field cgk\_totalnetprice, as shown below: ```cs quotes = OrganizationServiceContext.QuoteSet .Where(_ => _.OpportunityId != null && _.OpportunityId.Id == opportunityId && _.QuoteId != currentQuote.Id && (_.StatusCode.Value == (int)Quote_StatusCode.Won || _.StatusCode.Value == (int)Quote_StatusCode.WonOrder) && _.cgk_quotetypecode != null && (_.cgk_quotetypecode.Value == (int)QuoteTypeCode.Regular || _.cgk_quotetypecode.Value == (int)QuoteTypeCode.ServiceUnderWarranty)) .Select(x => new Quote() { Id = x.Id, cgk_totalnetprice = x.cgk_totalnetprice}) .ToList(); ``` However, when retrieving those quotes, the context does not return a value for all except one quote (and it is not the quote that triggered the update in the first place, but just a random one that was not updated at all) Weird part: when I rewrite the query to a QueryExpression, everything works perfectly: ```cs QueryExpression qe = new QueryExpression("quote"); //Exclude current quote qe.Criteria.AddCondition("quoteid", ConditionOperator.NotEqual, currentQuote.Id); //Opportunity qe.Criteria.AddCondition("opportunityid", ConditionOperator.NotNull); qe.Criteria.AddCondition("opportunityid", ConditionOperator.Equal, opportunityId); //State-Status FilterExpression statusFilter = new FilterExpression(LogicalOperator.Or); statusFilter.AddCondition("statuscode", ConditionOperator.Equal, (int)Quote_StatusCode.Won); statusFilter.AddCondition("statuscode", ConditionOperator.Equal, (int)Quote_StatusCode.WonOrder); qe.Criteria.AddFilter(statusFilter); //QuoteType qe.Criteria.AddCondition("cgk_quotetypecode", ConditionOperator.NotNull); FilterExpression typeFilter = new FilterExpression(LogicalOperator.Or); typeFilter.AddCondition("cgk_quotetypecode", ConditionOperator.Equal, (int)QuoteTypeCode.Regular); typeFilter.AddCondition("cgk_quotetypecode", ConditionOperator.Equal, (int)QuoteTypeCode.ServiceUnderWarranty); qe.Criteria.AddFilter(typeFilter); qe.ColumnSet = new ColumnSet("quoteid", "cgk_totalnetprice"); quotes = this.OrganizationService.RetrieveMultiple(qe).Entities.Cast<Quote>().ToList(); ``` What could cause this difference between OrganizationServiceContext and OrganizationService + QueryExpression??
2021/11/08
[ "https://Stackoverflow.com/questions/69882148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9396654/" ]
Queries on `OrganizationServiceContext` rely on LINQ for CRM, which in turn translates LINQ expressions into `QueryExpression` objects. LINQ for CRM comes with a few weaknesses: * it does not implement all capabilities of the underlying `QueryExpression`, * it only supports a limited set of LINQ constructs (see [MS Docs](https://learn.microsoft.com/en-us/powerapps/developer/data-platform/org-service/use-linq-construct-query)), * in some cases it creates incorrect queries, * query processing is approx. 10% slower. Your query looks pretty straightforward, yet it fails. Maybe you can leave the line `_.cgk_quotetypecode != null &&` out. I guess it is not needed and combined with the subsequent filtering on the same attribute it may trick the LINQ parser into constructing the wrong filter and/or conditions. Another option is to materialize the LINQ query first and then select the columns needed. Of course this will lead to a `select *`, but it's often worth trying while troubleshooting. E.g. you could write: ```cs .ToArray() .Select(x => new Quote() { Id = x.Id, cgk_totalnetprice = x.cgk_totalnetprice}); ``` Working with Dynamics CRM/365 CE I learned to avoid LINQ for CRM. Instead I use a bunch of extension methods allowing me to create `QueryExpression` queries in a much less verbose way. Final suggestion: in some cases a filter's `LogicalOperator.Or` can be replaced by `ConditionOperator.In` or `ConditionOperator.Between`. Doing so the construct ```cs //State-Status FilterExpression statusFilter = new FilterExpression(LogicalOperator.Or); statusFilter.AddCondition("statuscode", ConditionOperator.Equal, (int)Quote_StatusCode.Won); statusFilter.AddCondition("statuscode", ConditionOperator.Equal, (int)Quote_StatusCode.WonOrder); qe.Criteria.AddFilter(statusFilter); ``` can simply be replaced by this oneliner: ```cs qe.Criteria.AddCondition("statuscode", ConditionOperator.In, (int)Quote_StatusCode.Won, (int)Quote_StatusCode.WonOrder); ```
I generally use the query syntax for Dynamics LINQ queries. I'd suggest standard query troubleshooting - start with no conditions and add them one-by-one. Below is an idea of how my query would look. I'd keep adding / modifying the `where` clauses until the query returned what I expected. We could use `&&` operators instead of multiple `where` clauses, but I find that having the multiple `where` clauses often makes commenting and uncommenting easier. ``` using(var ctx = new OrganizationServiceContext(ctx)) { var x = from q in ctx.CreateQuery<Quote>() where q.QuoteId ! = currentQuote.Id where q.OpportunityId != null where q.cgk_quotetypecode != null where q.cgk_quotetypecode == QuoteTypeCode.Regular || QuoteTypeCode.ServiceUnderWarranty select new Quote { Id = q.Id, cgk_totalnetprice = x.cgk_totalnetprice }; var quotes = x.ToList(); } ```
435,810
I am in the process of implementing onion / clean architecture, and would like to understand better how and when to map to my domain entities. So if we take a specific example where we have a `Post` and we would like to update a `status` on this object. Am I correct in thinking that when I receive data in the controller I would pass this over to the service, at this point the service should first fetch that data from the repository and then map it into a domain entity. It is the domain entity, that will house rules for update, once the operation is performed we would pass this back to the repository. What since entities !== what we get via the API and what get saved in the DB, what layers should perform that transformation?
2022/01/07
[ "https://softwareengineering.stackexchange.com/questions/435810", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/261048/" ]
It depends on where you draw the line. (Von Neumann) Computers are by definition finite state machines in an infinite loop. Most programs aren’t modeled this way because, well, it’s hella tedious and impractical to list all of the states of an integer to make math work. But *parsers* very often are implemented this way, because their grammars are almost always in BNF (or some variant) which can be trivially generated into this finite state machine style code. They do it because it is very important to cover all of the possible permutations of input in an unambiguous way. Protocols have similar sort of needs, so also tend to be state machines even if they are (usually) less rigorously defined.
Your example of a scanner is not a program, it would be a tiny subroutine in a much larger program. If you use it as a co-routine, it would have internal state, but likely not enough to call it a “state-machine”. Many applications have the goal of not being modal. At any point, the user should be able to take any action, so having a state machine would be avoided. What *is* extremely common is an event processing loop, where some code that you wrote gets executed every time some event happens. You will likely not have that loop in your application code, but hidden in the GUI frameworks.
62,760,670
I'm working on the following user table, where role = 2 means the user is an instructor, and role = 3 means that the user is a student. ``` +--------+------+---------------+ | name | role | creation_date | +--------+------+---------------+ | Tom | 2 | 2020-07-01 | | Diana | 3 | 2020-07-01 | | Rachel | 3 | 2020-07-01 | | Michel | 3 | 2020-08-01 | +--------+------+---------------+ ``` My goal is to select the sum value of all instructors and students, grouped by date. The result should look like this: ``` +------------------+---------------+---------------+ | totalInstructors | totalStudents | creation_date | +------------------+---------------+---------------+ | 1 | 2 | 2020-07-01 | | 0 | 1 | 2020-08-01 | +------------------+---------------+---------------+ ``` In this case, on 2020-07-01, I had 1 instructor and 2 students registered and on 2020-08-01, I had no instructors and I had 1 student registered. My problem is that I am having difficulties in setting up this query, if someone can help me thank you very much!
2020/07/06
[ "https://Stackoverflow.com/questions/62760670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11380315/" ]
Use conditional aggregation: ``` SELECT creation_date, COUNT(CASE WHEN role = 2 THEN 1 END) AS totalInstructors, COUNT(CASE WHEN role = 3 THEN 1 END) AS totalStudents FROM yourTable GROUP BY creation_date; ``` [![screen capture from demo link below](https://i.stack.imgur.com/hewYo.png)](https://i.stack.imgur.com/hewYo.png) [Demo ----](https://dbfiddle.uk/?rdbms=mariadb_10.5&fiddle=29c2f7aba6c82b2c0da9a7ecc58070fe)
Please use below query, ``` select case when role = 2 then count(1) end as totalInstructors, case when role = 3 then count(1) end as totalStudents, creation_date from table_name group by creation_date; ``` You can use `COALESCE()` to replace null with 0 ``` select COALESCE(totalInstructors, 0) as totalInstructors, COALESCE(totalStudents, 0) as totalStudents,creation_date from (select case when role = 2 then count(1) end as totalInstructors, case when role = 3 then count(1) end as totalStudents, creation_date from table_name group by creation_date) qry; ```
31,433,579
I store my session id Redis, my session id is global unique, every time login will generate a new session id, so even same user will still have different session id. So I have no way to destroy the user's session because I have no way to locate it. So how can I design, so as to satisfy my need?
2015/07/15
[ "https://Stackoverflow.com/questions/31433579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1063434/" ]
You could specifically test for null and undefined ``` var b = { items: ('undefined' === typeof a || null === a) ? null : +a }; ```
This should work as well: ``` var b = { items: a != null? +a : null }; ``` Based on <https://stackoverflow.com/a/15992131/1494833>
783,536
Here's the question: Prove that $\lim\_{n \to \infty} (\sqrt{n^2+n}-n) = \frac{1}{2}.$ Here's my attempt at a solution, but for some reason, the $N$ that I arrive at is incorrect (I ran a computer program to test my solution against some test cases, and it spits out an error). Can anyone spot the error for me? $\left|\sqrt{n^2+n}-n-\frac{1}{2}\right| < \epsilon$ $\Rightarrow \left|\frac{n}{\sqrt{n^2+n}+n} - \frac{1}{2}\right| < \epsilon$ $\Rightarrow \frac{1}{2}-\frac{1}{\sqrt{1+\frac{1}{n}}+1} < \epsilon$ $\Rightarrow \frac{1}{\sqrt{1+\frac{1}{n}}+1} > \frac{1}{2} - \epsilon = \frac{1-2 \epsilon}{2}$ $\Rightarrow \frac{1}{\sqrt{1+\frac{1}{n}}} > \frac{1-2 \epsilon}{2}$ $\Rightarrow \frac{1}{\sqrt{\frac{1}{n}}} > \frac{1-2 \epsilon}{2}$ $\Rightarrow \sqrt{n} > \frac{1-2 \epsilon}{2}$ $\Rightarrow n > \frac{4 {\epsilon}^2-4 \epsilon +1}{4}$
2014/05/06
[ "https://math.stackexchange.com/questions/783536", "https://math.stackexchange.com", "https://math.stackexchange.com/users/140755/" ]
From $a^2-b^2=(a+b)(a-b)$ we have $$\sqrt{n^2+n}-n=\frac{n^2+n-n^2}{\sqrt{n^2+n}+n}=\frac{n}{\sqrt{n^2+n}+n}= \frac{1}{\sqrt{1+\frac{1}{n}}+1}$$ from which the result follows immediately.
Using the [fractional binomial theorem](https://brilliant.org/wiki/fractional-binomial-theorem/) we have $$ \Bigl(1+\frac{1}{n}\Bigr)^{1/2}=1+\frac{1}{2n}+o\Bigl(\frac{1}{n}\Bigr) $$ where $o(1/n)$ denotes a quantity that grows asymptotically slower than $1/n$ as $n\to\infty$. Multiplying through by $n$ yields $$ \sqrt{n^2+n}=n+\frac{1}{2}+o(1), $$ which is equivalent to the limit $$ \lim\_{n\to\infty}\sqrt{n^2+n}-n=\frac{1}{2}. $$
62,621,788
I am working on a Blazor server-side project for which I am currently creating a customized sign in page. Since I don't know that much about web apps (which is why I'm using blazor) possible solutions posted on the stackoverflow/github have not worked for me so far. To the point: I want the built-in `SignInManager` to handle the validation of the credentials provided by the user. These credentials are set as properties of a `FormLoginUser` class instance. ``` public class FormLoginUser { [Required, DataType(DataType.EmailAddress)] public string Email { get; set; } [Required] public string Password { get; set; } } ``` The code behind for the login page is as follows: ``` public class LoginBase : ComponentBase { [Inject] private UserManager<ApplicationUser> userManager { get; set; } [Inject] private SignInManager<ApplicationUser> signInManager { get; set; } [Inject] private NavigationManager NavigationManager { get; set; } protected FormLoginUser User { get; set; } protected bool IsLoginFailed { get; set; } protected override void OnInitialized() { base.OnInitialized(); IsLoginFailed = false; User = new FormLoginUser(); } protected async Task ValidateUser() { SignInResult result = await signInManager.PasswordSignInAsync( userName: User.Email, password: User.Password, isPersistent: true, lockoutOnFailure: false); if (result.Succeeded) NavigationManager.NavigateTo("/"); else IsLoginFailed = true; ShouldRender(); } } ``` When the user submits the login form the method `ValidateUser()` is called, by which time the `User` property will have been filled with data from the form. Things go wrong of right away on the first line of the `ValidateUser()` method. This is the the exception that is thrown: ``` Microsoft.AspNetCore.Components.Server.Circuits.RemoteRenderer: Warning: Unhandled exception rendering component: The response headers cannot be modified because the response has already started. System.InvalidOperationException: The response headers cannot be modified because the response has already started. at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.ThrowIfReadOnly() at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.set_Item(String key, StringValues value) at Microsoft.AspNetCore.Http.ResponseCookies.Append(String key, String value, CookieOptions options) at Microsoft.AspNetCore.Authentication.Cookies.ChunkingCookieManager.AppendResponseCookie(HttpContext context, String key, String value, CookieOptions options) at Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties) at Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext context, String scheme, ClaimsPrincipal principal, AuthenticationProperties properties) at Microsoft.AspNetCore.Identity.SignInManager`1.SignInWithClaimsAsync(TUser user, AuthenticationProperties authenticationProperties, IEnumerable`1 additionalClaims) at Microsoft.AspNetCore.Identity.SignInManager`1.SignInOrTwoFactorAsync(TUser user, Boolean isPersistent, String loginProvider, Boolean bypassTwoFactor) at Microsoft.AspNetCore.Identity.SignInManager`1.PasswordSignInAsync(TUser user, String password, Boolean isPersistent, Boolean lockoutOnFailure) at Microsoft.AspNetCore.Identity.SignInManager`1.PasswordSignInAsync(String userName, String password, Boolean isPersistent, Boolean lockoutOnFailure) at EvaluationPortal.Pages.Authentication.LoginBase.ValidateUser() in C:\dev\EvaluationPortal\Src\EvaluationPortal\Pages\Authentication\Login.razor.cs:line 33 at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync() at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle) Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost: Error: Unhandled exception in circuit 'j2FiQ7xmyQgNWl9lQDS5yHURzyFSUDlJyCeOu33qd-8'. System.InvalidOperationException: The response headers cannot be modified because the response has already started. at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.ThrowIfReadOnly() at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.set_Item(String key, StringValues value) at Microsoft.AspNetCore.Http.ResponseCookies.Append(String key, String value, CookieOptions options) at Microsoft.AspNetCore.Authentication.Cookies.ChunkingCookieManager.AppendResponseCookie(HttpContext context, String key, String value, CookieOptions options) at Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties) at Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext context, String scheme, ClaimsPrincipal principal, AuthenticationProperties properties) at Microsoft.AspNetCore.Identity.SignInManager`1.SignInWithClaimsAsync(TUser user, AuthenticationProperties authenticationProperties, IEnumerable`1 additionalClaims) at Microsoft.AspNetCore.Identity.SignInManager`1.SignInOrTwoFactorAsync(TUser user, Boolean isPersistent, String loginProvider, Boolean bypassTwoFactor) at Microsoft.AspNetCore.Identity.SignInManager`1.PasswordSignInAsync(TUser user, String password, Boolean isPersistent, Boolean lockoutOnFailure) at Microsoft.AspNetCore.Identity.SignInManager`1.PasswordSignInAsync(String userName, String password, Boolean isPersistent, Boolean lockoutOnFailure) at EvaluationPortal.Pages.Authentication.LoginBase.ValidateUser() in C:\dev\EvaluationPortal\Src\EvaluationPortal\Pages\Authentication\Login.razor.cs:line 33 at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync() at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task) at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle) ``` Has anyone got any clue as to what might cause this, I've been looking all over the internet but cannot seem to find anyting that solves this issue for me. Please help.
2020/06/28
[ "https://Stackoverflow.com/questions/62621788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9172408/" ]
As you noted, strings are immutable. All of the instance methods on the `string` type (at least those related to "modifying" it) return a new string. This means that calling something like the following returns a new string which is immediately discarded: ``` // value is discarded searchQuery.Substring(0, searchQuery.Length - 1); ``` The solution is to *reassign* the variable with the new value. For example: ``` searchQuery = searchQuery.Substring(0, searchQuery.Length - 1); ``` [SharpLab example](https://sharplab.io/#v2:C4LgTgrgdgPgAgJgIwFgBQiAM7EGYAEA3uvqfogkSWTQG4CGY+AzgKaMDGAFgIoStgAnvgC8pAEQBZYQGVgYAJZQA5uIDc1GqTade/IaJbsw3PgMEA6GRABGcJJgAUmADRHdZoRYAyrFcC58AFp8JABKDTQtMnsATkcdEz1zCPwAejT8AAdFKGBmfClZeSVxfE18AF90SqA=) If you are using C# 8 you can make use of the *range operator* via the [`Index`/`Range`](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges) classes. This provides a bit cleaner version: ``` // backspace one character searchQuery = searchQuery[..^1]; ``` [SharpLab example](https://sharplab.io/#v2:C4LgTgrgdgPgAgJgIwFgBQiAM7EGYAEA3uvqfogkSWTQG4CGY+AzgKaMDGAFgIoStgAnvgC8+AEQBBAEIBhcQG5qNUm069+QkWrDc+AwQG0AdMYB6SALpK0KsnCQBOABQ69mwQEobNAL7pfIA===) I will also note that `TrimEnd` is most likely *not* what you want. It will trim more than one character at a time which isn't what a *single* press of the Backspace key would do. For example consider the following: ``` var str = "Abcdeee"; var result = str.TrimEnd('e'); Console.WriteLine(result); // prints "Abcd" ``` [SharpLab example](https://sharplab.io/#v2:C4LgTgrgdgPgAgJgIwFgBQiAM7EGYAEA3uvqfogkSWTQG4CGY+AzsEwLykBEAggEYBjACYBTMVwDc1GqQZMwI5hAA2wfJ1ZgAdABUwASwC2AUShCAFAHIRlgJRS0MsnCQBOcwqWr7+APS/8AAcDKGBmfF5BIS58aXwAX3R4oA===)
Any method you use to manipulate the string will return the new string so you need to capture that. `string newString = searchQuery.Substring(0, searchQuery.Length -1);`
220,773
Has anybody who administers email servers or spam filtering noticed that in last couple of weeks the spam volume has dropped significantly? Is there a chart provided by one of the major spam filtering companies? **Edit:** Based on our internal stats, although it varies, on the two weeks starting the day after Christmas (Sunday), spam seems to be coming in about half as much as it did before Christmas.
2011/01/10
[ "https://serverfault.com/questions/220773", "https://serverfault.com", "https://serverfault.com/users/58001/" ]
You are trying to forward emails from a domain that has SPF records, but that domain does not list your server as a valid source of email for that domain. Your choices are: 1. Contact somedomain.co.uk and tell them you're forwarding their mail and want to be added to their SPF record. 2. Contact the "external mailbox at another domain" and tell them you're forwarding email to one of their users and to whitelist you in their SPF checking. 3. Use [Sender Rewriting Scheme](http://www.openspf.org/SRS) on your server to reflect that you are resending this mail from the original sender.
Your mail server is not a fault here, but there is a conceptual fault in SPF, that breaks email forwarding. Explanation: In this case your mail server is a standard non sender rewriting forwarding service, that is in the mail delivery path. This is completely valid according to [RFC\_822 (page 18)](http://www.ietf.org/rfc/rfc0822.txt "RFC_822 (page 18)"). The SPF Council prescribes that the ESP that is receiving the email must consider possible Forwarding Services and not reject emails delivered via forwarding services only because of an SPF fail. It states: "For non-sender-rewriting forwarders, accept all mail without checking SPF (any SPF results are meaningless)". See the official SPF website at: [SPF: Best Practices/Forwarding](http://www.openspf.org/Best_Practices/Forwarding "SPF: Best Practices/Forwarding")
6,581,162
I suppress a few warnings, 1591 is the XML comments warning. It's not that I don't use the comments, there are some false positives. Now to find the fact that XML comments warning is 1591 took a whole load of googling. Is there a list somewhere? Or a way to display the error number in Visual Studio itself? Thanks
2011/07/05
[ "https://Stackoverflow.com/questions/6581162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518551/" ]
You can find a whole list of them here: [Compiler and Warning messages for C/C++](http://msdn.microsoft.com/en-us/library/8x5x43k7%28v=VS.80%29.aspx) [Compiler and Warning messages for C#](http://msdn.microsoft.com/en-us/library/ms228296.aspx)
I stumbled on this thread while trying to sort out how to find these in VS2015 with Beckhoff TwinCAT and found the Beckhoff-specific ones under Project->Properties, in the Compiler Warnings tab (as below in [1](https://i.stack.imgur.com/ALa5r.png)). [screencap of TwinCAT project properties' compiler warning list](https://i.stack.imgur.com/ALa5r.png)
55,871,387
I have a question for my assignment. I have a database with sqlite in my android app and the location updates come and writes to the sql db, but there is some same data with the coming updates. I want to check if there is same location in my db, the system skips or overwrites the existing location info in db as x,y I have some code I post it below but my code always adds or always overwrites if I change it as Update Replace or something like that also I have the id in my databases. How to change and organize my code for the job? ``` public void DBCreate(){ SQLITEDATABASE = openOrCreateDatabase("LatLongDatabase3", Context.MODE_PRIVATE, null); SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS myTable74(id INTEGER PRIMARY KEY AUTOINCREMENT, FAVCurrentLocationLAT VARCHAR,FAVCurrentLocationLONG VARCHAR);"); } public void SubmitData2SQLiteDB(){ SQLiteQuery = "INSERT OR REPLACE INTO myTable74(id, FAVCurrentLocationLAT, FAVCurrentLocationLONG) VALUES(NULL,'"+mCurrentLocation.getLatitude()+"','"+mCurrentLocation.getLongitude()+"');"; SQLITEDATABASE.execSQL(SQLiteQuery); Toast.makeText(CampaignActivity.this,"OK", Toast.LENGTH_LONG).show(); } ```
2019/04/26
[ "https://Stackoverflow.com/questions/55871387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When `var b = a;` is executed, `b` does not "refer" to `a`. It becomes a number whose value is `a`'s value at this moment. --- However, if you use an **Object**, the attribution will use the **reference** of `a`, and not its value: ``` a = { value: 23 }; b = a; a.value = 46; console.log(b); ``` ``` // console Object { value: 46 } ```
Look at this [answer](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language/51523031#51523031). Primitives are passed by values and objects are passed by reference. As a and b are primitives, they are passed by values. And when a is changed that will not be reflected in b.
653,106
I was watching this video by Ben Eater on building an 8-bit computer: [Youtube Video](https://www.youtube.com/watch?v=CiMaWbz_6E8&list=PLowKtXNTBypGqImE405J2565dvjafglHU&index=12) time: 1:51. He has this circuit: [![enter image description here](https://i.stack.imgur.com/UgIUk.jpg)](https://i.stack.imgur.com/UgIUk.jpg) Right before the 74LS245 he has 8 LEDs in parallel with the 74lS245 IC. I am a little confused on what this does to the circuit exactly. How can he just put 8 LEDs in parallel without affecting the 5 V going into the 74LS245? As far as I am aware, putting an LED in parallel with a load would lower the voltage of both the LED and load to be equivalent to Vf of the LED. How does this not affect the voltage of the 74LS245 IC?
2023/02/07
[ "https://electronics.stackexchange.com/questions/653106", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/314255/" ]
You should maybe ask Ben Eater about his circuits. We have not checked if the circuit matches the schematic or if that is just a block diagram and not the actual schematics. We also don't know the LED color which plays an important part here. So first thing is to be absolutely sure that there are no resistors in the video you watched. There are no bypass capacitors drawn either, which should generally be a part of any sane logic chip design. So if you are not sure, there might be resistors after all. Having said that, there are LEDs that have a forward voltage higher that logic level input threshold for a valid logic high level. And the output high current drive of LS logic is so weak that there is not much current through the LEDs anyway and the LEDs don't burn if there are no resistors. So maybe a red LED might not work, but a yellow, green, white or blue could indeed work. The diagram does convey they basics what the circuit is about with block level. It may even work enough with no resistors or capacitors for the purpose of making an educational Youtube video.
Do not do that! Always use a resistor in series with an LED to limit the current. (Anything between 330 Ohm to 2.2 kOhm will work there.) Once you do, your question becomes moot.
33,877,915
I want two lists inside one list: ``` x = [1,2] y = [3,4] ``` I need them to turn out like: ``` z = [[1,2][3,4]] ``` But I have no idea how to do that. Thanks so much for your consideration and help.
2015/11/23
[ "https://Stackoverflow.com/questions/33877915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3958253/" ]
Make a new list which contains the first two lists. ``` z = [x, y] ``` This will make each element of `z` a reference to the original list. If you don't want that to happen you can do the following. ``` from copy import copy z = [copy(x), copy(y)] print z ```
If you don't want references to the original list objects: ``` z = [x[:], y[:]] ```
62,826,678
Everything is working except the button. The submit button is not being clicked. Can anyone help me out? I believe it may have to do with the fact that I changed the frame to "top". But, I am unsure how to change it back. Code: ``` from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time url = 'https://protonmail.com/' driver = webdriver.Chrome('/Users/edenhikri/Desktop/chromedriver') driver.get(url) WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.btn.btn-default.btn-short'))).click() WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.panel-heading'))).click() WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#freePlan'))).click() WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.ID,'password'))).send_keys('test123') WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.ID,'passwordc'))).send_keys('test123') WebDriverWait(driver,20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,".top"))) WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.ID,'username'))).send_keys('myUsername') driver.find_element_by_class_name('btn.btn-submit').click() ``` error: ``` no such element: Unable to locate element: {"method":"class name","selector":"btn.btn-submit"} ``` button code: ``` <button type="submit" class="btn btn-submit" name="submitBtn">Create Account</button> ``` I have also tried using xpath but I get the same error that it cannot find this: ``` driver.find_element_by_xpath("//button[@class=“btn btn-submit”]").click() ```
2020/07/10
[ "https://Stackoverflow.com/questions/62826678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12585735/" ]
above your activity class you must add annotation @AndroidEntryPoint as below: @AndroidEntryPoint class MainActivity : AppCompatActivity() {
``` class MainViewModel @ViewModelInject constructor(private val repository: HomePageRepository, @Assisted private val savedStateHandle: SavedStateHandle) : ViewModel(){} ``` and intead of initializing the viewmodel like this : private lateinit var viewModel: MainViewModel viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java) Use this directly : private val mainViewModel:MainViewModel by activityViewModels() EXplanation : **assisted saved state handle** : will make sure that if activity / fragment is annotated with @Android entry point combined with view model inject , it will automatically inject all required constructor dependencies available from corresonding component activity / application so that we won't have to pass these parameters while initializing viewmodel in fragment / activity
8,731,426
I'm writing a userscript for a page which has this HTML code block.. ``` <span id="mediaSetUfiLikeLink"> <button class="like_link stat_elem as_link" title="Like this item" type="submit" name="like"> <span class="default_message">Like</span> <span class="saving_message">Unlike</span> </button> </span> <span> <a href="/ajax/sharer/?s=3&appid=2305272732&p[]=1012781954&p[]=2063763" rel="dialog">Share</a> </span> ``` I need to add an `id` tag to the **last** `span` block. (below one) ``` <span> <a href="/ajax/sharer/?s=3&appid=2305272732&p[]=1012781954&p[]=2063763" rel="dialog">Share</a> </span> ``` I'm got to this point using this, ``` document.getElementById("mediaSetUfiLikeLink").getElementsByTagName("span")[1]; ``` I tried getting the last `span` using `nextSibling` like this, which returned `null` ``` document.getElementById("mediaSetUfiLikeLink").getElementsByTagName("span")[1].nextSibling; ``` Can someone please help me out with this? Just to be clear once again, I want to 'gain access' to the last `span` block so that I can add an `id` attribute to it.. **P.S** - I need to do this **without** using jQuery or any other external library. Pure JavaScript only. Thank you
2012/01/04
[ "https://Stackoverflow.com/questions/8731426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077789/" ]
As far as I know this is not possible without changing the Jenkins code, but I think you could achieve the same goal with minimal maintenance using [build slaves.](https://wiki.jenkins-ci.org/display/JENKINS/Distributed+builds) Different builds can run concurrently on the slaves, or even on the same slave if you define multiple executors (if the slave machine has >1 CPU). You can label the slaves to control which jobs get executed on each one, so you could have a separate set of slaves for each of your pipelines. Apart from the overhead of making sure the basic slave machines stay running, the Jenkins specific overhead for running a slave is minimal. You can use a process on the master to keep the slave JAR file and the build tools you need updated; at my shop we use a simple rsync script that runs every time the master or slave is restarted to copy the latest tools from the master to the slave and restart the slave process. This approach also reduces the extent to which the Jenkins master is a single point of failure.
What you want can only be accomplished by running a separate Jenkins master for each project. Usually people think a Jenkins master has more administrative overhead than a slave, but if that does not hold for you, you can run multiple masters on a server, just assign them different ports. If this isn't good for you, then maybe Jenkins isn't the right tool for you. It is not the only CI server out there. Jenkins is very easy to set up but on the other hand it is not possible to do deep customization, like multiple build queues.
178,154
I'm a senior developer on a project. Because I'm the most senior, I was given the role of an informal dev lead to control and guide the dev team when needed. Apart from that we are doing scrum. The Product Owner - who's the only person responsible for backlog selection and prioritisation - now told me that I'm burning the dev team down. The problem is I have 0 impact on what we are working on. Actually, we (meaning the whole team) have already had several discussions with him about him assigning too many points per sprint. I do occasionally point to possible problems with the designed solutions during the review and I do, when needed, point to the need to test when the code that is demoed has not tested - this type of things. But good coding practices is something we agreed to follow at the beginning of the project and I leave it for him to decide what to do with the situation. What do you do in such situations? I'm not ok with him directing such accusations towards me. He already accused me of something else in the past, which resulted in a not very pleasant discussion with my boss, although I don't think I had done anything wrong. I could among others: * contact my boss directly, tell them about the accusations and why I don't agree with them and that I find it worrying to receive such "feedback" to preempt the colleague escalating that to my boss * tell the colleague verbally or in writing that I don't accept such accusations * write to the colleague with my boss in cc quoting the accusations and stessing that it's his and only his role to prioritize the backlog * shut up and pretend I didn't hear it I work in a culture in which escalations happen a lot.
2021/09/06
[ "https://workplace.stackexchange.com/questions/178154", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/120073/" ]
Well that's unfortunate. Let's break this down. You the tech lead do not get to say what are you working on. The way you influence that is that you take in the spec and draft a sensible way to go about it. Managers want feature Z before feature X, which is a totally ridiculous thing to do architecturally? Instead of hard turn down, come up with the ways to do it: make a tech demo or mockup separate from the rest of the project or quote them two months worth of tech debt down the line spent on refactoring. You are not a marketing professional and, quite possibly, not even an expert in the project subject area. You are a tech expert. If the owner starts arguing with you about tech things or how long features should be taking, there's not much to be done, really. No trust in people you hire => no good work could be done. Micromanaging owners are terrible and they might as well just keep hurting themselves, don't waste time on it. But very, very importantly - don't cross the line from your side, either: ridiculous as management requests might be, push back on them in a cooperative way, offering solutions instead of critique. Worst case scenario here is owner driving the project to the ground with creeping tech debt and overworking the team, not much to be done here. IMO, if you say "this will take 2 weeks" and the owner straight away says "you must do it in one or else" one should consider quitting. Maybe there is someone else who can finish it within a week who's not you - but if your expectations for the work don't match with your employer's, it's a long downwards spiral with no real benefit to either. I've seen people who'd hire team after team only to come to the conclusion "huh those programmers suck, charging way too high and quoting ridiculous deadlines for simple features", and there's just no real reconciling with those.
The push / pushback dynamic between product owners ("the business") and development is not a new one, and agile techniques were in part an attempt to defuse it and turn it into something more productive. I agree with some of the other answers that you should keep the dialogue going with the Product Owner. You should clearly and politely state that they set priority, not tasks. In a crude way, the somewhat unprofessional comment about "burning the team" indicates you are successfully pushing back, such that the team see a dilemma of choosing who to please. Of course when talking to the product owner they are going to complain about the other guy (you). In addition, it's clear that the product owner wants to go faster. Maybe there's a good reason for that? Maybe there's even things about the system that slow delivery down ... like not have good automated test coverage? Maybe you only get one decent release out every two months? It's better if you sort it out with the product owner directly. If you have not talked to them one-to-one, face-to-face (or video), you should do so. It's not unreasonable to ask for backup from your own manager, though, especially once direct discussion has been tried. I would definitely not do it by email and cc. Reach out to your manager and explain the situation. Suggest the product owner needs to understand the boundaries better. Then after listening to feedback from your manager, if they agree with your analysis and will back you up, setup a face to face or video meeting with the product owner, yourself, and your manager. Reiterate that "burning the team down" is not fixed by "burning the product down". Secondly, and in the same meeting, present your concrete plan for making the development go faster. This will have the usual "to go fast, go well" dynamic, but it foregrounds that goal of faster higher quality delivery, rather than something that can come across as esoteric technical concerns or nice-to-haves.
4,978,640
I would like to create my logout view for many reasons but the main reason is avoid the `request.session.flush()` the logout is automatically calling. That's not good for my application since I would like to keep alive some of the session variables even if the user logs out. What session variable(s) do I have to delete in order to logout the user?
2011/02/12
[ "https://Stackoverflow.com/questions/4978640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509807/" ]
Besides `request.session.flush()` it seems django sets the `request.user` object to an `AnonymousUser():` ``` from django.contrib.auth.models import AnonymousUser request.user = AnonymousUser() ```
you can also do it by using `delete_test_cookie()` within your view. [check more here](http://www.djangobook.com/en/beta/chapter12/)
161,700
I have an HTC One M8 running Marshmallow 6.0, kernel 3.4.0-perf-gd7aafa47 and build MRA58K.H15, unlocked bootloader but non-rooted device. The device is a tab over 2 years old now, and the system has been shutting down on its own when the battery charge gets closer to 10%. Yesterday, after charging up and powering on, I've noticed no more notifications are shown. The sounds are played, but no icons are displayed at the top left. Further, when I try to draw down to see more information, nothing other than 'No notifications' message displays. Also noticed that the gear icon on the top right has disappeared, I actually have to go the long route to access settings now. Another thing I've noticed is that the 'developer options', which were always enabled, now display '...not available for this user'. I've tried wiping the cache partition, but that made not difference. Any ideas?
2016/11/07
[ "https://android.stackexchange.com/questions/161700", "https://android.stackexchange.com", "https://android.stackexchange.com/users/195423/" ]
yeah there's [Google Handwriting Input](https://play.google.com/store/apps/details?id=com.google.android.apps.handwriting.ime&hl=en) available on PlayStore. get it.
Tried Google Translate App? It can do such things[![enter image description here](https://i.stack.imgur.com/9ofAg.jpg)](https://i.stack.imgur.com/9ofAg.jpg)
19,016,924
I have read through various Stackover flow Questions and contents on the web on similar problem. However, I couldnt find useful hints that would allow me to narrow down on my problem. Here is my usecase which results in this error. > > 2 entities Campus and Programs --> One-to-many relation from Campus to > Program and One-to-one from Program to Campus. > > > i am trying to create multiple programs associated with campuses. Each > insert will create a new program with same details and attach it to a > different(unique) campus. eg. Java 101 Course offered at New York, > San Francisco, Dallas, Chicago will create a new program for each > campus. > > > There is no problem persisting single program. also there is no issue > persisting a program for upto 46 campuses but this error shows up for > the 47th campus. > > > Here is the config for my application: Properties file: ``` datasource.classname=com.mysql.jdbc.Driver datasource.url=jdbc:mysql://localhost:3306/edu datasource.username=xxx datasource.password=xxx123 datasource.initialsize=15 datasource.maxactive=50 datasource.maxidle=15 datasource.minidle=5 datasource.maxwait=10000 datasource.dialect=org.hibernate.dialect.MySQLDialect datasource.validationquery =select 1 datasource.minEvictableIdleTimeMillis = 180000 datasource.timeBetweenEvictionRunsMillis = 180000 hibernate.batchsize=30 ``` Here's how my **spring-hibernate** config looks like ``` <context:property-placeholder location="classpath:database.properties" order="1" ignore-unresolvable="true" /> <context:property-placeholder location="classpath:app.properties" order="2" ignore-unresolvable="true" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${datasource.classname}" /> <property name="url" value="${datasource.url}" /> <property name="username" value="${datasource.username}" /> <property name="password" value="${datasource.password}" /> <property name="initialSize" value="${datasource.initialsize}" /> <property name="maxActive" value="${datasource.maxactive}" /> <property name="maxIdle" value="${datasource.maxidle}" /> <property name="minIdle" value="${datasource.minidle}" /> <property name="maxWait" value="${datasource.maxwait}" /> <property name="minEvictableIdleTimeMillis" value="${datasource.minEvictableIdleTimeMillis}" /> <property name="timeBetweenEvictionRunsMillis" value="${datasource.timeBetweenEvictionRunsMillis}" /> <property name="validationQuery" value="${datasource.validationquery}" /> <property name="testOnBorrow" value="true" /> <property name="removeAbandoned" value="true"/> <property name="removeAbandonedTimeout" value="60"/> <property name="logAbandoned" value="true"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${datasource.dialect}</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.batch_size">${hibernate.batchsize}</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.provider_configuration_file_resource_path">/WEB-INF/ehcache-entity.xml</prop> <prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop> <prop key="hibernate.generate_statistics">false</prop> <!-- <prop key="hibernate.connection.release_mode">auto</prop> --> </props> </property> <property name="packagesToScan"> <list> <value>com.edapp.core</value> <value>com.edapp.data.engine</value> <value>com.edapp.service.engine</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <aop:config proxy-target-class="true"/> <!-- necessary to call methods on classes than proxies --> <context:annotation-config /> <context:component-scan base-package="com.edapp" /> <!-- transaction settings --> <tx:annotation-driven transaction-manager="transactionManager" /> ``` --- Here's how my application flow looks like ProgramController -> ProgramService -> ProgramDAO **Service class is annotated with:** `@Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.READ_COMMITTED)` **DAO class is annotated with:** `@Transactional(propagation=Propagation.MANDATORY, isolation=Isolation.READ_COMMITTED)` Here's the piece from Controller ``` List<String> campuses = Arrays.asList(gson.fromJson(campusesJSArray, String[].class)); if(campuses.size() > 0){ List<Program> programList = new ArrayList<Program>(); AreaOfStudy aos = this.areaOfStudyService.getById(areaOfStudyId); Concentration con = this.concentrationService.getById(concentrationId); for(String c : campuses){ Long campusid = Long.parseLong(c); Program p = new Program(); Campus campus = this.campusService.getById(campusid); if(campus != null){ System.out.println(campus.toString()); p.setName(name); p.setCampus(campus); p.setCode(code); p.setLevel(level); p.getCampus().getPrograms().add(p); p.setAreaOfStudy(aos); p.setConcentration(con); p.setActive(true); } programList.add(p); } ((ProgramServiceImpl)programService).saveOrUpdate(programList); ``` --- Here's a snippet from Service ``` if(programList == null){ log.error("ProgramList cannot be null"); return null; } Map<Integer, String> errors = new HashMap<Integer, String>(); log.info("Saving program list of size:"+programList.size()); for(int i=0; i<programList.size();i++){ try{ this.saveOrUpdate(programList.get(i)); }catch(HibernateException e){ errors.put(i, "error"); } } return errors; ``` --- Here's a snippet from the DAO: ``` @Transactional(isolation=Isolation.REPEATABLE_READ) public void create(final T entity) { if(entity == null){ IllegalArgumentException e = new IllegalArgumentException(); throw(e); } Session session = this.sessionFactory.getCurrentSession(); try{ session.persist(entity); session.flush(); }catch(ConstraintViolationException cve){ log.error("School with same code already exists "+ this.clazz.getName(),cve); throw cve; }catch(HibernateException e){ log.error("Error persisting entity of type "+ this.clazz.getName(),e); throw new HibernateException(e); }finally{ session.clear(); } } ``` Batchsize = 30 ``` @Transactional(isolation=Isolation.REPEATABLE_READ) public void create(List<T> entityList){ if(entityList == null){ IllegalArgumentException e = new IllegalArgumentException(); throw(e); } Session session = this.sessionFactory.getCurrentSession(); try{ for(int i=0;i<entityList.size();i++){ T entity = entityList.get(i); if(entity == null){ log.error("List "+ this.clazz.getName() + " of cannot contain null"); throw new NullPointerException("List "+ this.clazz.getName() + " of cannot contain null"); } session.persist(entity); if(i% this.batchSize == 0){ session.flush(); session.clear(); } } }catch(HibernateException e){ log.error("Error persisting entity of type "+ this.clazz.getName(),e); throw new HibernateException(e); }finally{ session.flush(); session.clear(); } } ``` tried using both methods to persist but same outcome. --- Here is the full stack trace ``` org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:932) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:233) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) root cause org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:597) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:329) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631) com.tr.leadgen.service.engine.CampusServiceImpl$$EnhancerByCGLIB$$68d579ad.getById(<generated>) com.tr.leadgen.web.edu.controllers.ProgramController.add(ProgramController.java:74) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:233) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) root cause org.hibernate.exception.GenericJDBCException: Cannot open connection org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140) org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128) org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52) org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449) org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167) org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:160) org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:81) org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473) org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:556) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:329) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631) com.tr.leadgen.service.engine.CampusServiceImpl$$EnhancerByCGLIB$$68d579ad.getById(<generated>) com.tr.leadgen.web.edu.controllers.ProgramController.add(ProgramController.java:74) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:233) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) root cause org.apache.commons.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle object org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:114) org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:83) org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446) org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167) org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:160) org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:81) org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473) org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:556) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:329) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631) com.tr.leadgen.service.engine.CampusServiceImpl$$EnhancerByCGLIB$$68d579ad.getById(<generated>) com.tr.leadgen.web.edu.controllers.ProgramController.add(ProgramController.java:74) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:233) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) root cause java.util.NoSuchElementException: Timeout waiting for idle object org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1174) org.apache.commons.dbcp.AbandonedObjectPool.borrowObject(AbandonedObjectPool.java:79) org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106) org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:83) org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446) org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167) org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:160) org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:81) org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473) org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:556) org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:372) org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:329) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631) com.tr.leadgen.service.engine.CampusServiceImpl$$EnhancerByCGLIB$$68d579ad.getById(<generated>) com.tr.leadgen.web.edu.controllers.ProgramController.add(ProgramController.java:74) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:233) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ``` --- This is the only way I get session from hibernate: ``` @Transactional(propagation=Propagation.NOT_SUPPORTED) protected Session getCurrentSession(){ if(this.sessionFactory == null){ log.error("SessionFactory is null"); } return this.sessionFactory.getCurrentSession(); ``` } -- Also per my app logs, code execution does not make it to service layer. It throws an error while looping in the controller to populate the list of program entites (refer controller snippet) I would be thankful if anyone can point me in the right direction.
2013/09/25
[ "https://Stackoverflow.com/questions/19016924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425575/" ]
I see you had a pool setting which validates connection on borrow, and from the stack trace I can see this validation failed (seem to timeout). There are 2 possible causes I can think of: 1. Network connection between your app and db server was broken. This could be due to connection lost, firewall setting change, stale DNS entries, db server suddenly dies, or even router had a setting to kill suspicious tcp socket (happened to us once) 2. The pool run out of available connection. This is rather unlikely because I'd assume the stack trace would give more hint, but it's worth monitoring your pool and check the number of available conn at the time when problem occur
I ran into a similar error today. I have a similar setting: "datasource.maxactive=50", which means no more than 50 connections at a time. I have n threads, each uses a connection. When n is 50 or close, this exception happens a lot. There are a few things that can be done; 2 that I found helpful: * Adjust n to be smaller * Retry with proper back-off From what I see, both of these give the pool time to recollect connections and reduces the timeout.
22,594,093
I am creating a website that will demonstrate the dangers of XSS. Users will attempt to get JavaScript to execute using an XSS vulnerability. However, I am running into problems in determining if JavaScript is actually being executed so that I can record that the user was successful. I will be running these checks on a node.js server. I originally planned to run `eval` on the parts which would contain JavaScript if the user was successful, but thought that this would be too dangerous as it would be running on the server-side and could get the server exploited. Are there any ways to using JavaScript to validate if a string is valid JavaScript other than running eval? Or is there a way to run `eval` without putting my server at risk?
2014/03/23
[ "https://Stackoverflow.com/questions/22594093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516476/" ]
You could use the [esprima](http://esprima.org/) javascript parser to see if the string is valid javascript syntax. Install using `npm install esprima`. To use: ``` var esprima = require('esprima'); var userStringToTest = 'var a = 10;'; var isValid = isValidJs(userStringToTest); if(isValid) { console.log('its valid!'); } else { console.log('its NOT valid!'); } function isValidJs(testString) { var isValid = true; try { esprima.parse(testString); } catch(e) { isValid = false; } return isValid; } ``` As @FelixKing pointed out in his comment, this of course won't detect runtime errors. For your use case though, it sounds like you should be testing for syntax errors as opposed to runtime errors since that is both more strict and there really shouldn't be valid javascript syntax to begin with.
What you need is a JavaScript sandbox, which will isolate their code from the code running it. There are several to choose from. I've used "Sandbox" before: <http://gf3.github.io/sandbox/> Execute their code in the sandbox, see if there were errors, return the output.
60,136,235
Sorry, my understanding of how packaging works in `Angular` is terrible!! I want to use a `WYSIWYG` editor in my `Angular6` application. I have zeroed down to `quill.js`. <https://quilljs.com/docs/quickstart/> But I am confused how I can include it in my project. I have added it as a dependency in my `package.json`. ``` "dependencies": { ... "quill": "1.3.6" } ``` and then I tried to use for the following `textarea` ``` <textarea id="question-description" type="text" class="form-control" formControlName="questionDescription" [ngClass]="validateField('questionDescription')" rows="4"></textarea> ``` and initialize `Quill` like following in `ngAfterViewInit` ``` var quill = new Quill('#question-description', { theme: 'snow' }); ``` But I get error ``` ReferenceError: Quill is not defined at NewPracticeQuestionComponent.push../s ``` I have also added `declare var Quill:any;` at the top of the Component's `.ts` file I can see in `node_modules` that there is a `quill` folder and it has `dist/quill.js` where I suppose `Quill` object must be defined and exported (haven't checked it though). What am I doing wrong?
2020/02/09
[ "https://Stackoverflow.com/questions/60136235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6703783/" ]
Try using the [ngx-quill](https://www.npmjs.com/package/ngx-quill) wrapper.
Thanks the answer from Sathiamoorthy. That helps me a lot. I want to add more comments here during my quill setup. Since my Angular CLI version is 12.0. I have to identify the specific version to make it work. (I spent 6 hours to figure this out) Like: npm install quill@**1.3.7** npm install ngx-quill@**13.0.1** npm install @types/quill@**1.3.10** Hope this helps the people still in frustration.