Search is not available for this dataset
qid
int64
1.35k
73.7M
question
stringlengths
83
22.1k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
32
15.5k
response_k
stringlengths
32
9.22k
836,058
If $0\le\alpha\le\frac{\pi}{2}$, then which of the following is true? A) $\sin(\cos(\alpha))<\cos(\sin(\alpha))$ B) $\sin(\cos(\alpha))\le \cos(\sin(\alpha))$ and equality holds for some $\alpha\in[0,\frac{\pi}{2}]$ C) $\sin(\cos(\alpha))>\cos(\sin(\alpha))$ D) $\sin(\cos(\alpha))\ge \cos(\sin(\alpha))$ and equality holds for some $\alpha\in[0,\frac{\pi}{2}]$ Testing for $\alpha=0$, I can say that the last two options will be incorrect. However which option among the first two will hold ?
2014/06/16
[ "https://math.stackexchange.com/questions/836058", "https://math.stackexchange.com", "https://math.stackexchange.com/users/155795/" ]
![plot of sin(cos(x)) and cos(sin(x))](https://i.stack.imgur.com/TONvu.png) [peterwhy](https://math.stackexchange.com/users/89922/peterwhy) has proved what the plot shows.
Let $a=\cos{x}$, $b=\sin{x}$, and $a,b \in[0,1]$. We are now going to see which one ($\sin{a}$ or $\cos{b}$) is larger? Noticg that $a$ and $b$ satisfy $a^2+b^2=1$, and if we regard the value $a$ and $b$ as a pair $(a,b)$ on the $(a,b)$-plane, it should be a circle with radius $1$ in the first quadrant. If $\sin{a}=\cos{b}=\sin{(\frac{\pi}{2}-b)}, \forall a,b \in [0,1]$ holds, then $a=\frac{\pi}{2}-b$, (i.e. the line $a+b=\frac{\pi}{2}$), but $a+b=\frac{\pi}{2}$ does not touch the circle $a^2+b^2=1$, so the equality does not hold. Moreover, the region $a^2+b^2=1$ locates below the line $a+b=\frac{\pi}{2}$, that is, $a+b < \frac{\pi}{2}$. And, $\sin{\theta}$ is an increasing function for $\theta \in [0,1]$, we have $\sin{a} < \sin{(\frac{\pi}{2}-b)}=\cos{b}$. The answer is A).
15,209,574
Given the following HTML... ``` <div class="tester"> <div>a</div> <div>abcd efgh ijkl mnop qrst abcd efgh ijkl mnop qrst abcd efgh ijkl mnop qrst abcd efgh ijkl mnop qrst </div> <div>c</div> </div> ``` How would I change this css to make the 3 divs above appear in a single row? The middle div I wish to clip if it overflows its boundary. ``` .tester { width: 300px; overflow: auto; background-color: #c5c5c5; } .tester > div { float: left; overflow: hidden; } .tester > div:last-child { float: right; width: 50px; } ``` [Fiddle](http://jsfiddle.net/jeljeljel/B9ttJ/) **\* UPDATE \*** **Clarification** I want to keep the width at 300px, and the middle element should clip if it exceeds it's bounding box. The bounding box of the first element is determined by it's size. The bounding box of the last element is set at 50px. So the middle element should clip.
2013/03/04
[ "https://Stackoverflow.com/questions/15209574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131270/" ]
Use display inline, here's a little demo: [Demo](http://jsfiddle.net/B9ttJ/6/) HTML: ``` <div class="tester"> <div>a</div> <div>abcd efgh ijkl mnop qrst abcd efgh ijkl mnop qrst abcd efgh ijkl mnop qrst abcd efgh ijkl mnop qrst <div>c</div> </div> ``` CSS: ``` .tester div { display:inline; } ``` And the result: > > a abcd efgh ijkl mnop qrst abcd efgh ijkl mnop qrst abcd efgh ijkl > mnop qrst abcd efgh ijkl mnop qrst c > > >
use the display property ``` display: inline-block; ```
11,795,498
I'm having this situation and I'm wondering if i could do it with regex: I have a string in this format: ``` {{We all}} love {{stackoverflow}}. ``` My question is how can I use regex replace to get: ``` match1 love match2 ```
2012/08/03
[ "https://Stackoverflow.com/questions/11795498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715283/" ]
You do need to add `/socket.io/socket.io.js` anywhere. If you have installed socket.io via `npm install socket.io` your application knows how to handle it. I played around with socket.io myself a few months back and this is a very simple "chat" that I came up with and it worked. So it might help you out! (I am using ExpressJS. A very helpful Node.JS framework btw) This is you server side application: ``` var app = require('express').createServer(); var io = require('socket.io').listen(app); app.listen(3000); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); io.sockets.on('connection', function (socket) { socket.on('news', function (data) { socket.emit('news', { content: data.text }); socket.broadcast.emit('news', { content: data.text}); }); }); ``` This is your index.html ``` <!DOCTYPE html> <html> <head> <title>socket test</title> </head> <body> <input type="text" id="Username"> <input type="text" id="Content"><input type="button" value="send" onclick="sendMessage()"><br /> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost:3000/pathtoproject'); socket.on('news', function (data) { document.body.innerHTML += data.content + "<br />"; }); function sendMessage() { socket.emit('news', { text: document.getElementById('Username').value + ": " + document.getElementById('Content').value }); } </script> </body> </html> ```
**I finally resolved this** The socket.io script doesn't exists as flat file. It is **generated by node.js server** and served to browser. So. including it by: `<script src="/socket.io/socket.io.js"></script>` Works only if node.js server is started on the same port as the web server with web application. If you try to load this script from for example apache on port 80, you need to put whole path to node.js server listen host: `<script src="http://localhost:8080/socket.io/socket.io.js"></script>`
445,910
i write program that parse text with regular expression. Regular expression should be obtained from user. I deside to use glob syntax for user input, and convert glob string to the regular expression internally. For example: ``` "foo.? bar*" ``` should be converted to ``` "^.*foo\.\w\bar\w+.*" ``` Somehow, i need to escape all meaningful characters from the string, then i need to replace glob \* and ? characters with apropriate regexp syntax. What is the most convinient way to do this?
2009/01/15
[ "https://Stackoverflow.com/questions/445910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42371/" ]
no need for incomplete or unreliable hacks. there's a function included with python for this ``` >>> import fnmatch >>> fnmatch.translate( '*.foo' ) '.*\\.foo$' >>> fnmatch.translate( '[a-z]*.txt' ) '[a-z].*\\.txt$' ```
In R, there's the `glob2rx` function included in the base distribution: <http://stat.ethz.ch/R-manual/R-devel/library/utils/html/glob2rx.html>
59,505,221
I'm trying to send a uint8\_t and two floats as bytes (not as the actual characters in the numbers) from a Python program over a serial connection to an Arduino (ATtiny1614 using megaTinyCore). Currently, on the Python side, I have this: ```py Serial.write(b"\x01" + struct.pack("<ff", float1, float2)) ``` On the Arduino, I have this: ```cpp struct DATA_W { float f1; float f2; } wStruct if (Serial.available() >= (sizeof(uint8_t)+(sizeof(float)*2))) { uint8_t cmd = (uint8_t) Serial.read(); Serial.readBytes((char *) &wStruct.f1, sizeof(float)); Serial.readBytes((char *) &wStruct.f2, sizeof(float)); } ``` The uint8\_t would be in the `cmd` variable, and the two floats would be in the `wStruct` struct. I can read the `cmd` just fine, but when I read the two floats, I get very different values than what I should be getting. Most of the time, I just read -0.00 and 0.00, but sometimes, I get very large numbers. An example would be me sending 100 and 94.1999, but getting -14336 and 20608 (those values are after I converted the float to an int, but the issue still shows up before the conversion). What am I doing wrong, and how can I fix it?
2019/12/27
[ "https://Stackoverflow.com/questions/59505221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5282060/" ]
It seems that my serial port connection was unreliable. I was using the built-in connection on a Jetson Nano (/dev/ttyTHS1). When I switched to a USB to Serial adapter, the code worked perfectly.
Another approach is to use an existing protocol library like Firmata (which is supported for Arduino, Python, and many other platforms) to transfer your data. It takes care of synchronization, encoding, parsing, and decoding for you, so you don't have to worry about representation, packing, endedness, etc.
46,096,941
This line: ``` using (FileStream fs = File.Open(src, FileMode.Open, FileAccess.Read, FileShare.Read)) ``` throws: > > System.IO.IOException: The process cannot access the file 'X' because > it is being used by another process. > > > When I replace the line with: ``` File.Copy(src, dst, true); using (FileStream fs = File.Open(dst, FileMode.Open, FileAccess.Read, FileShare.Read)) ``` it works. But why I can copy, which surely reads the whole content of file, while being restricted from directly reading the file? Is there a workaround?
2017/09/07
[ "https://Stackoverflow.com/questions/46096941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2224701/" ]
When you open a file there is a check for access modes and sharing modes. The access modes of any process must be compatible with the sharing modes of others. So if A wants access to read, others must have allowed reading in sharing mode. Same for writing. If process A has opened a file for writing and you say `SharingMode.Read` the call will fail. You are in this case saying "others may only read from the file, not write." If you specify `ShareMode.ReadWrite` you're saying "others can read or write, I don't care" and if no other process has specified `ShareMode.Write` you are allowed to read from the file.
> > But why I can copy, which surely reads the whole content of file > > > Well, conceptually it reads the whole file, though it can happen at a lower level than copying streams. On Windows it's a call to the [`CopyFileEx`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363852(v=vs.85).aspx) system function, passing in the paths. On \*nix systems it also uses a system call, but does open the source file with `FileAccess.Read, FileShare.Read` for that call, so you would have the same issue. > > while being restricted from directly reading the file? > > > If a file may be written to then you cannot open it `FileShare.Read` because at some point between the various operations you are doing the file could be changed and your operations will give the wrong results. `CopyFileEx` can succeed by preventing any writes that happen to it during the short period it was operating from affecting the results. There would be no way to offer a more general form of this, because there's no way to know you are going to close the stream of it again quickly. > > Is there a workaround? > > > A workaround for what? That you can't open a stream, or that you can copy the file? For the former the latter provides just such a workaround: Copy the file to get a snapshot of how it was, though note that it isn't guaranteed.
13,432,941
I want to ask is there a way to get information from JCheckBox without actionListener. In my code I scan a file of strings and each line has data which, if selected, should be added to an array in my program. Problem is that i will never know how many JCheckBoxes I will have, it depends from file. So, my question is how to put selected strings to an array (or list) with a press of a button (ok) so i could do something else with them (in my case i need to get data from file or from hand input and put it in a red-black tree, so I will need to push selected strings to my putDataInTheTree method). EDIT: Also, is it possible not to show those JCheckBoxes that already has been added to the program? I.E. if i choose fluids, next time I call input method fluids wont show in my panel? Thanks in advance! How it looks: ![enter image description here](https://i.stack.imgur.com/wFuAl.png) My code is so far: ``` public void input() { try { mainWindow.setEnabled(false); fromFile = new JFrame("Input from file"); fromFile.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); fromFile.setLayout(new BorderLayout()); fromFile.setSize(300,200); panelFromFile = new JPanel(); panelFromFile.setLayout(new java.awt.GridLayout(0,1)); JScrollPane scrollPane2 = new JScrollPane(panelFromFile); scrollPane2.setMaximumSize(new Dimension(300, 180)); FileReader File = new FileReader(data); BufferedReader Buffer = new BufferedReader(File); while ((info = Buffer.readLine()) != null) { if (info != null) { JCheckBox check = new JCheckBox(info); panelFromFile.add(check); } } ok = new JButton("ok"); ok.addActionListener(this); fromFile.add(scrollPane2, BorderLayout.CENTER); fromFile.add(ok, BorderLayout.SOUTH); fromFile.setLocationRelativeTo(null); fromFile.setResizable(false); fromFile.setVisible(true); } catch(Exception e) { text.append("Error in INPUT method"); text.append(System.getProperty("line.separator")); } } ```
2012/11/17
[ "https://Stackoverflow.com/questions/13432941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1832175/" ]
Add your checkboxes to a collection, and when the button is pressed, iterate through the checkboxes and get the text associated with each checked checkbox: ``` private List<JCheckBox> checkBoxes = new ArrayList<JCheckBox>(); ... while ((info = Buffer.readLine()) != null) { if (info != null) { JCheckBox check = new JCheckBox(info); panelFromFile.add(check); this.checkBoxes.add(check); } } ... public void actionPerformed(ActionEvent e) { List<String> infos = new ArrayList<String>(); for (JCheckBox checkBox : checkBoxes) { if (checkBox.isSelected() { infos.add(checkBox.getText()); } } // TODO do something with infos } ```
If you store the checkboxes (e.g. in a `List`) you can loop over them and query their selected state when the OK button is pressed. To obtain the `String` from the checkbox, you could opt to use the `putClientProperty` and `getClientProperty` methods, as explained in the class javadoc of `JComponent`
3,510,059
Series $$\sum\_{n=1}^{\infty}\left(\frac{1}{3}\right)^n\cdot\left(\frac{n+1}{n}\right)^{n^2}$$ I tried Abel, Dirichlet theorems and it seems like divergent series but I don’t know the series a can compare to (for proving of divergence) //i’m sorry that I can’t post images cuz due to reputation, this is my first question :>
2020/01/15
[ "https://math.stackexchange.com/questions/3510059", "https://math.stackexchange.com", "https://math.stackexchange.com/users/742144/" ]
Use <https://en.m.wikipedia.org/wiki/Root_test> to find $$\dfrac13\cdot \lim\_{n\to\infty}\left(1+\dfrac1n\right)^n=\dfrac e3<1$$
$0 < (1/3)^n[(1+1/n)^n]^n <$ $(1/3)^ne^n=(e/3)^n=:a^n$, where $a<1$. $\sum a^n$ is convergent, now use comparison test. Used: $(1+1/n)^n$ is increasing, bounded from above by $e$. Recall: $\lim\_{n\rightarrow \infty}(1+1/n)^n=e.$ [Show that $\left(1+\dfrac{1}{n}\right)^n$ is monotonically increasing](https://math.stackexchange.com/questions/167843/show-that-left1-dfrac1n-rightn-is-monotonically-increasing)
52,322,314
How to verify if the invisible web page is loaded or not . Because of problems in Internet connection or loading the page from the website i get error in display like "the web page can't display" in Internet Explorer for XP or windows 7 or 10 . Need for way to tell me if web page loaded successfully or have problem so i can decide what is the next step.
2018/09/13
[ "https://Stackoverflow.com/questions/52322314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5399258/" ]
A bit clueless here, it works for me in this reproduction: ```js import { ComponentFixture, TestBed, } from '@angular/core/testing'; import { Component, Injectable, OnInit } from '@angular/core'; import { of, forkJoin } from 'rxjs'; @Injectable({providedIn: 'root'}) export class Service { // service to be mocked response = ['hello', 'world']; // this is mocked anyway someCall() { return of(this.response); } someCall1() { return of(this.response); } someCall2() { return of(this.response); } someCall3() { return of(this.response); } someCall4() { return of(this.response); } someCall5() { throw new Error('oups!') } } @Component({ selector: 'app-testee', template: `<h1>hi</h1>` }) export class TesteeComponent implements OnInit { // main comp constructor(private service: Service) {} result: string; // aggregated property ngOnInit() { } loadData() { forkJoin([ this.service.someCall(), this.service.someCall1(), this.service.someCall2(), this.service.someCall3(), this.service.someCall4(), this.service.someCall5(), ]).subscribe( rse => this.result = [].concat(...rse).join('-'), // aggregation err => this.result = `ERR ${err}` ); } } describe('TesteeComponent', () => { let fixture: ComponentFixture<TesteeComponent>; let component: TesteeComponent; beforeEach(async () => { TestBed.configureTestingModule({ declarations: [ TesteeComponent ], providers: [ Service ] }).compileComponents(); fixture = TestBed.createComponent(TesteeComponent); component = fixture.componentInstance; }); it('should load data', () => { const testee = component; // why not use TestBed.get(Service) here? const service = fixture.debugElement.injector.get(Service); spyOn(service, 'someCall').and.returnValue(of(['test', 'values', '0'])); spyOn(service, 'someCall1').and.returnValue(of(['test', 'values', '1'])); spyOn(service, 'someCall2').and.returnValue(of(['test', 'values', '2'])); spyOn(service, 'someCall3').and.returnValue(of(['test', 'values', '3'])); spyOn(service, 'someCall4').and.returnValue(of(['test', 'values', '4'])); spyOn(service, 'someCall5').and.returnValue(of(['test', 'values', '5'])); expect(testee).toBeTruthy(); fixture.detectChanges(); testee.loadData(); expect(testee.result).toEqual('test-values-0-test-values-1-test-values-2-test-values-3-test-values-4-test-values-5'); expect(service.someCall).toHaveBeenCalled(); }); }); ```
It's from a bit that this question was did but i'll hope that in any case it will help. This should works fine: ``` import { ComponentFixture, TestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestComponent } from 'someLocation'; import { ServiceTest1 } from 'someLocation'; import { ServiceTest2 } from 'someLocation'; describe('TestComponent', () => { let fixture: ComponentFixture<TestComponent>; let component: TestComponent; let service1: ServiceTest1; let service2: ServiceTest2; let httpMock: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ TestComponent ], imports: [ HttpClientTestingModule ], providers: [ ServiceTest1, ServiceTest2 ] }).compileComponents(); service1 = TestBed.inject(ServiceTest1); service2 = TestBed.inject(ServiceTest2); httpMock = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(TestComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('TestComponent should be created', () => { expect(component).toBeTruthy(); }); it('should load data', done => { const response0 = ['test', 'values', '0']; const response1 = ['test', 'values', '1']; const response2 = ['test', 'values', '2']; const response3 = ['test', 'values', '3']; const response4 = ['test', 'values', '4']; const response5 = ['test', 'values', '5']; const response6 = ['test', 'values', '6']; component.loadData().subscribe({ next: (responses) => { expect(responses[0]).toEqual(response0); expect(responses[1]).toEqual(response1); expect(responses[2]).toEqual(response2); expect(responses[3]).toEqual(response3); expect(responses[4]).toEqual(response4); expect(responses[5]).toEqual(response5); expect(responses[6]).toEqual(response6); done(); } }); httpMock.expectOne('urlSomeCall0').flush(response0); httpMock.expectOne('urlSomeCall1').flush(response1); httpMock.expectOne('urlSomeCall2').flush(response2); httpMock.expectOne('urlSomeCall3').flush(response3); httpMock.expectOne('urlSomeCall4').flush(response4); httpMock.expectOne('urlSomeCall5').flush(response5); httpMock.expectOne('urlSomeCall6').flush(response6); httpMock.verify(); }); }); ``` With the loadData() function like this: ``` loadData(): Observable<any> { return new Observable(observable => { this.someOtherMethod(); this.someProperty = false; this.someOtherMethod2(); if (this.isNew) { this.noData = true; } else if (this.key) { Observable.forkJoin([ /*00*/ this.service1$.someCall(this.key), /*01*/ this.service2$.someCall(this.key), /*02*/ this.service2$.someCall1(this.key), /*03*/ this.service2$.someCall2(this.key), /*04*/ this.service2$.someCall3(this.key), /*05*/ this.service2$.someCall4(this.key), /*06*/ this.service2$.someCall5(this.key), ]) .takeWhile(() => this.alive) .subscribe({ next: responses => { observable.next(responses); observable.complete(); ... // join all the data together }, error: error => { observable.error(error); observable.complete(); this.handleError(error); } }); } this.changeDetector$.markForCheck(); }); }; ``` Also remember that with the forkJoin all your observables should return the complete event.
3,764,858
What is the difference in these two statements in python? ``` var = foo.bar ``` and ``` var = [foo.bar] ``` I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case? For example: if foo.bar = [1, 2] would I get this? ``` var = foo.bar #[1, 2] ``` and ``` var = [foo.bar] #[[1,2]] where [1,2] is the first element in a multidimensional list ```
2010/09/21
[ "https://Stackoverflow.com/questions/3764858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330013/" ]
`[]` is an empty list. `[foo.bar]` is creating a new list (`[]`) with `foo.bar` as the first item in the list, which can then be referenced by its index: ``` var = [foo.bar] var[0] == foo.bar # returns True ``` So your guess that your assignment of `foo.bar = [1,2]` is exactly right. If you haven't already, I recommend playing around with this kind of thing in the Python interactive interpreter. It makes it pretty easy: ``` >>> [] [] >>> foobar = [1,2] >>> foobar [1, 2] >>> [foobar] [[1, 2]] ```
> > I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case? > > > * Yes, it creates a new list. * If `foo.bar` is already a list, it will simply become a list, containing one list. ``` h[1] >>> l = [1, 2] h[1] >>> [l] [[1, 2]] h[3] >>> l[l][0] [1, 2] ```
1,418
I currently have a tomato plant planted in a pot on my porch. It is doing quite nicely and is tied to a 6' bamboo cane. Unfortunately my cane has started to lean a bit and I am afraid that as the plant continues to grow and eventually starts bearing fruit that the cane will not be able to do its job, or that the pot may fall over. I am wondering what the best way to support the cane that is supporting the tomato plant? Or am I better off choosing a different support method for my potted tomato plants?
2011/07/22
[ "https://gardening.stackexchange.com/questions/1418", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/36/" ]
Add another cane =) (or stick) Adding a cane inside the pot should reinforce the first one and prevent mechanical failure. This doesn't address the issue of the pot becoming top heavy and unstable. If it looks like it might fall over, add another cane (or two) so that the cane(s) rest on the ground outside the pot and counteract the instability.
For tomato plants, a conical cage that looks like this is the best way to go. This way, you provide support at each stage of the plant's growth and there are multiple points (on each circle) for you to tie the fruits to. ![enter image description here](https://i.stack.imgur.com/jGQxG.jpg) However, this requires that you plan in advance and set up the cage before the plant gets too big. There is no way you're going to be able to fit that onto a full grown plant. ### Supporting your cane Now coming to supporting your 6' cane, here's one cheap way using some twine and some turnbuckles. You'll need: 1. Some mason's line or strong twine (costs around $3-4 for a 100-feet roll. You'll need a lot less!) 2. 3 small [turnbuckles](http://en.wikipedia.org/wiki/Turnbuckle) (costs around $1.50 each for the small ones) 3. 3 6" nails (costs around 10¢ each) Now I'm not at home and don't have a picture of how it looks like, but here's a hand drawn drawing that shouldn't be too hard to follow (also not too clear because of the scanner, but it's readable). ![enter image description here](https://i.stack.imgur.com/JKhTj.png) 1. Drive in the three nails at the points marked X. Make sure that you drive it in at an angle so that the head is tilting outward as in the second figure. 2. Tie some twine from the cane (probably around less than half way down from the top) to the loop of the turnbuckle. 3. Next tie a smaller piece of twine from the nail head and through the hook of the turnbuckle. Pull it till it is tight and then make a knot. 4. Make sure that the turnbuckle is screwed out most of the way so that later if and when you need to adjust tension, you can (last figure). 5. Repeat for all three nails and adjust tension till the cane is as vertical as you'd like it to be. 6. Check periodically (every week?) to see if it is leaning and increase tension in the string(s) opposite to the direction in which it is leaning. This is a neat way to keep it vertical without having to build additional supports/structures and is my preferred method of training young trees to grow vertically.
29,357,327
I have the following Ruby script which is supposed to insert the names of the files into the *contents* array: ``` filelist = Dir.glob('C:\Users\abc\Desktop\drg\*.*') print filelist filelist.each do |filepathname| contents = IO.read(filepathname) puts contents end ``` For the above code, I get no output for *filelist* or *contents*. Why is that?
2015/03/30
[ "https://Stackoverflow.com/questions/29357327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/588855/" ]
Use File#join ------------- In your current string, the backslash acts as an escape character, not a path separator. A more verbose, but potentially more canonical, approach is to use [File#join](http://ruby-doc.org/core-2.2.0/File.html#method-c-join) to join the parts of your path using File::SEPARATOR. For example: ``` path = File.join "C:", "Users", "abc", "Desktop", "drg", "*.*" Dir.glob path ``` A side-benefit of this approach is that you can inspect the *path* variable to ensure that it's valid, which is much more testable and debuggable than globbing directly.
[Dir.glob](http://ruby-doc.org/core-2.2.1/Dir.html#method-c-glob) uses the backslash as an escape character, so the path will not be what you think it is. To quote: > > Escapes the next metacharacter. > > > Note that this means you cannot use backslash on windows as part of a glob, i.e. Dir["c:\foo\*"] will not work, use Dir["c:/foo\*"] instead. > > >
364,139
Here is a version of differential pair: [![enter image description here](https://i.stack.imgur.com/UoHAG.png)](https://i.stack.imgur.com/UoHAG.png) I can understand the working principle of differential pair above. When Ic1 increases Ic2 decreases that's the thing. And for that to happen the tail current must be constant. And the above differential pair example is using current source at the tail which makes this idea work. But have a look at below: [![enter image description here](https://i.stack.imgur.com/4UF35.png)](https://i.stack.imgur.com/4UF35.png) In the above version there's no current source but just a resistor at the tail. How is the tail current kept constant by that resistor Re? Or am I misunderstanding something here? **Edit:** Finally after reading τεκ's answer I started to understand. Below is an example how we can replace a "voltage source in series with a resistor" with a "current source in parallel with the same resistor". I added disturbance to see how much the current is regulated. I and II shows that **source transformation** which was the keyword to make things sense. Black plot of the current for I and II is identical which proves this. In III I've increased the source impedance of that equivalent current source and that shows us that moving to an ideal current source makes the current variation much smaller as shown in the red plot. [![enter image description here](https://i.stack.imgur.com/aHXIn.png)](https://i.stack.imgur.com/aHXIn.png) [![enter image description here](https://i.stack.imgur.com/dNJhN.png)](https://i.stack.imgur.com/dNJhN.png)
2018/03/23
[ "https://electronics.stackexchange.com/questions/364139", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/125197/" ]
An ideal current source has infinite output impedance (i.e. \$dV/dI = \infty\$). A real current source is equivalent to an ideal current source in parallel with some finite output impedance Ro. A current source in parallel with a resistor is equivalent to a voltage source in series with a resistor ([source transformation](https://en.wikipedia.org/wiki/Source_transformation)). ![schematic](https://i.stack.imgur.com/p8Ern.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fp8Ern.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) So the long-tail resistor in your circuit is just a non-ideal current source. ![schematic](https://i.stack.imgur.com/izUxp.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fizUxp.png) In the traditional vacuum tube version, V- would be a very large voltage and Re would be a very large resistance, so that the resulting current was correct but it was closer to the ideal of infinite resistance.
The resistor keeps the tail current fairly constant, constant enough. If the magnitude of V- is much more than the of Vin range, then the current is fairly constant indeed. There is a common mode gain, RC/2RE, but it's much smaller than the differential gain, RC/2(Qx intrinsic Re), and for many purposes, this degree of CMRR is sufficient. You'll notice there's no resistor used between Q1/2 emitters to reduce the differential gain, so this gain stays very high. Where this degeneration is used, the CMRR is much less, and a current source may be used in the tail to increase it again.
142,609
A player of mine had an interesting concept where two parties who are opposed to each other would play at the same time in the same session. In essence the plot would be a group of thieves have been hired to steal some kind of magical artefact from a castle, and the first part of the session would be this group infiltrating the castle and getting to the artefact. Once they remove it however, of course alarms will go off, or a pair of patrolling guards will see it's missing on their next rotation. This would then introduce the second party who are a group of elite guards. I was thinking the easiest way to run it would be to give each group 30 seconds to decide their course of action, and then act upon it. The guards will have a map so they can point out to the DM where they want to move next, and the thieves will have a map revealed to them as they travel along that they can point at to try and avoid metagaming as well as other punishments for metagaming. Naturally the two parties will be at opposite ends of the room. **How can I run a session like this where there are two opposing parties in the same session?** All the players have shown a lot of interest in trying this idea out for a one-shot. I am hoping to use some online resources to help run it; any specific ideas are welcome, but should be supported by experience (per [Good Subjective, Bad Subjective](https://stackoverflow.blog/2010/09/29/good-subjective-bad-subjective/)).
2019/03/06
[ "https://rpg.stackexchange.com/questions/142609", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/52858/" ]
Sounds like [Epic Adventures](http://dndadventurersleague.org/start-here/conventions) from Adventurers League. > > D&D Epics are exciting multi-table events where participants cooperate in a “mass raid” of truly EPIC proportions; as every table works toward the same goal, individual tables act as squads that might take on different tasks, possibly affecting other tables or unlocking side quests needed to progress the event. > > > An Epic Adventure has a structure consisting of 1-hour missions, each played by a different table. Every mission has a different objective and grants different bonuses when completed. There are also events that, when triggered, grant *immediate* bonuses or penalties to all tables. You need another DM ------------------- Each table has their DM, so they can play simultaneously. **You need to have another DM** to take care the other party and communicate if the other party affect your party ("The guards successfully turned on the emergency light, your stealth rolls now has -2 penalty"). However, if you are planning to solo DM, I suggest to convert the "hide-and-seek" showdown to a **combat showdown**, ended with either the capture of the thieves or their escape. It is more manageable, without losing the narrative conclusion. If your group is not into combat, you can change it to a **skill showdown**. 1. Gives each party 3 objectives that are solved by skill checks against DC or other party's opposing check. 2. Each party takes turn to complete objectives. 3. Each successful objective grant bonus or penalty to subsequent checks, to you and your opponent, respectively. This mimics "events" in the Epic Adventure. 4. Each successful objective also grant bonus or penalty to the final skill contest. 5. Final skill contest is whoever wins three times first, win the game. Using this method, you as the DM have to adequately interpret and narrate the result of their checks to build the tension toward the final skill contest. Last note, "hide-and-seek" with traversing the map round by round will be tedious and takes a lot of time, even with two DMs. That's why I suggest you to ditch the hide and seek and use alternative.
With two opposing parties the game will go painfully slowly for both. ===================================================================== The Basic [loop](https://www.dndbeyond.com/compendium/rules/basic-rules/introduction#HowtoPlay) of D&D is: 1. The DM describes the environment. 2. The players describe what they want to do. 3. The DM narrates the results of the adventurers’ actions. One party is going to be on hold while you're narrating for the other as the game can't proceed without a DM. This means both sessions will proceed haltingly. The style of play you've described does not seem well suited for D&D. This style may be easier to execute under a different gaming system.
52,695
In a vlog made by a Chinese vlogger about the possibility of working and earning money in Germany, he said, “德国的社会制度就象一个熨斗,当你刚开始想卷的时候,它一下子就把你烫平了。” What does the sentence mean? What does the word 卷 here mean?
2022/10/09
[ "https://chinese.stackexchange.com/questions/52695", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/17398/" ]
I would say both EEQ and Tang Ho are correct. 卷 originally means curling up. This sentence uses the iron as a metaphor, so the society prevents people from "curling up". But what does the author mean when they says a person curls up? That's related to EEQ's explanation of 卷 as a Internet shorthand for 内卷 (involution, involute). So there is a little Chinese wordplay here. In sum, it means "when the involution is about to emerge, the society immediately prevents it from happening". But it depends on the vlog content... Probably a people "curling up" follows Tang Ho's explanation instead of EEQ's. But if it is a recent vlog, then 内卷 is a common topic among Chinese Gen Z. So I assume EEQ's explanation is correct.
"德国的社会制度就象一个熨斗,当你刚开始想卷的时候,它一下子就把你烫平了。" German's social system is like a smoothing iron, when the society(you) starts to **roll up/curl(卷)**, it will immediately iron/smooth it(you) down. The sentence means, in Germany, when a new societal trend/wave **goes against the norm (卷)**, it is likely will be put down/straightened(烫平) by the value carried by its social system.
3,200,050
I was thinking $f(n)=|n|$, but realized that would be a surjection. I'm not sure of how to solve this. Thank you.
2019/04/24
[ "https://math.stackexchange.com/questions/3200050", "https://math.stackexchange.com", "https://math.stackexchange.com/users/638602/" ]
Let $f(n)=2(n+1)$ if $n\ge0$ and $-2n-1$ if $n<0$. This maps {$0,1,2,...$} to {$2,4,6,...$} and {$-1,-2,-3,...$} to {$1, 3, 5, ...$}; i.e., {$..., -3, -2, -1, 0, 1, 2, ...$} to {$1,2,3,4,5,6,...$}. The inverse map is $f^{-1}(m)=\dfrac m 2 -1 $ if $m$ is even and $-\dfrac{m+1}2$ if $m$ is odd.
Here's another solution: let $f(n)=2^n $ if $n>0, 2^{-n}-1$ otherwise.
61,441
Suppose S is a genus g surface with n punctures satisfying the hyperbolicity condition 2g + n - 2 > 0. If n > 0 the fundamental group of the surface is a free group on 2g + n - 1 := m generators. If we look the universal covers of different punctured surfaces with the same m (e.g., thrice-punctured sphere and once-punctured torus for m = 2) in, say the hyperbolic plane or the Poincare disc model, how do they differ? The "only" apparent difference is in the number of punctures which should give rise to a difference in the lifts of the punctures to the boundary of the disc. The fundamental groups are isomorphic, but they must act differently to produce quotient surfaces of different genera. How? How does the set of lifts of punctures on the boundary relate to the standard Farey set? Thanks a lot in advance!
2011/04/12
[ "https://mathoverflow.net/questions/61441", "https://mathoverflow.net", "https://mathoverflow.net/users/14314/" ]
The simplest case, where $g=0, n=3$ and $g = n = 1$ yield isomorphic groups (free of rank 2), can be written explicitly using a little $2 \times 2$ matrix calculation. We choose a fundamental domain in the upper half-plane made out of two vertical lines with real parts $-1$ and $1$, and two semicircles whose diameters are the real intervals $[-1,0]$ and $[0,1]$. Since the boundaries are geodesics, it suffices to find Möbius transformations that transform the endpoints appropriately. For $g=0, n=3$, we choose generators $\begin{pmatrix}1& 2 \\ 0 & 1 \end{pmatrix}$ to glue the vertical lines together, and $\begin{pmatrix}1& 0 \\ 2 & 1 \end{pmatrix}$ to glue the semi-circles. If you like modular curves, this quotient is called $Y(2)$, and classifies isomorphism classes of elliptic curves equipped with an ordered list of all 2-torsion points. For $g=1, n=1$, we choose $\begin{pmatrix}1& 1 \\ 1 & 2 \end{pmatrix}$ to glue the left vertical line to the right semicircle, and $\begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}$ to glue the left semicircle to the right vertical line. This quotient is a leaky torus. The above results form a special case of a general phenomenon (mentioned by Sam Nead), where the loops around punctures give unipotent (aka parabolic) generators of $\pi\_1$, and handles give a pair of hyperbolic generators. I don't have a good answer concerning the set of lifts of the boundary points - it will always be a disjoint union of $n$ orbits under the transformation group, but it can vary widely, since the transformation group has a continuous family of representations in $PSL\_2(\mathbb{R}$.
For the thrice-punctured sphere, there is a generating set where both generators are parabolic. For the once-punctured torus only the commutator (and its conjugates) is parabolic. Hence any element that can be part of a generating set is hyperbolic. Thinking in the upper half-plane model of $\mathbb H$, the Farey set is the rational points of the real line (plus the point at infinity). If $X$ is a punctured hyperbolic surface then the lifts of the ideal points of $X$ likewise form a dense set in the real line. If $X$ is a thrice-punctured sphere then, after possibly conjugating the deck group by an isometry of $\mathbb H$ the lifts of the punctures are the Farey set. However, for any other surface $X$ this only happens if the *modulus* of $X$ is carefully chosen.
56,092,725
I need help writing this next() method in this class. I've tried several stuff, but I keep getting that I'm not returning the next value, but rather null. The instructions for this class reads: This class should be public, non-static, and should implement java.util.Iterator. It's index instance variable should be initialized with an appropriate value. It's hasNext() method should return true if any elements in the queue have yet to be returned by its next() method. It's next() method should return queue values in the same order as in the underlying array. Therefore I'm going to write the code that I have, but will cut it short so only the important elements that are relatable to my problem shows. ``` public class MaxHeapPriorityQueue<E extends Comparable<E>> { private E[] elementData; private int size; @SuppressWarnings("unchecked") public MaxHeapPriorityQueue() { elementData = (E[]) new Comparable[10]; size = 0; } public Iterator<E> iterator() { return new MHPQIterator(); } ``` and the other class takes place here, which has ties with the Iterator method. ``` public class MHPQIterator implements java.util.Iterator<E> { private int index; public boolean hasNext() { if(size == 0) { return false; } else { return (index < size); } } public E next() { return elementData[index]; } } ``` I'm not sure if I'm elementData would work, but I don't know what else I could return with.
2019/05/11
[ "https://Stackoverflow.com/questions/56092725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10572727/" ]
First of all, my understanding is, that your data is inside elementData and size gives the number of elements stored inside. iterator() gives you an iterator. Your Iterator implementation has index as a point to the current element. What do you plan to store inside index? I see 2 possibilities: a) it is giving you the current data location. The first element inside the array is element 0, so to be before that, I would initialize it as -1. b) It could be visual. So it is initialized as 0 first and then 1 means: first element, which would be the elementData[0]. ==> It is just an internal variable so it is completely up to you, what you want to store inside of it. Now let us look at your hasNext method. If the sizer is 0, then there cannot be a next element. Ok. But then you check if iterator() is null? iterator always returns a new instance of your inner iterator class. So it will always be non null! So this seems wrong. You have index and size. So you just have to check if the index is already pointing to the last element. So depending on the choice a/b above, you simply have to check if index+1 < size or index And then the next function: - It has to validate that there is another element. (=> hasNext) - you increase index - you return the element, index is pointing to (elementData[index] or elementData[index-1] (depends again on your decision what to store inside index) My hint is, to play around with it with paper and pen. Just write an instance of your class with e.g. 3 elements (so elementData[0], elementData[1], elementData[2] hs some value, size = 3. You create a new instance of your iterator, index is initialized and then see what must happen. A possible class that shows an implementation is: import java.util.Iterator; ``` public class MaxHeapPriorityQueue<E extends Comparable<E>> { private E[] elementData; private int size; @SuppressWarnings("unchecked") public MaxHeapPriorityQueue() { elementData = (E[]) new Comparable[10]; size = 0; } public void add(E data) { if (size == 10) throw new IllegalStateException("Queue full"); elementData[size] = data; size++; } public Iterator<E> iterator() { return new MHPQIterator(); } public class MHPQIterator implements java.util.Iterator<E> { private int index=-1; public boolean hasNext() { return (index+1)<size; } public E next() { index++; return elementData[index]; } } public static void main (String[] args) { MaxHeapPriorityQueue<Integer> queue = new MaxHeapPriorityQueue<>(); Iterator<Integer> iterator = queue.iterator(); System.out.println("Empty queue:"); while (iterator.hasNext()) System.out.println(iterator.next()); queue.add(1); System.out.println("Queue with 1 element (1):"); iterator = queue.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); queue.add(2); queue.add(3); queue.add(4); System.out.println("Queue with 4 elementa (1,2,3,4):"); iterator = queue.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } } ```
Like this: ``` public class MHPQIterator implements java.util.Iterator<E> { private int index=0; public boolean hasNext() { return (index < size); } public E next() { return elementData[index++]; } } ```
37,319,736
I have the below hibernate native query as shown below the idea is not to use the native query and switch to hibernate criteria api ``` <![CDATA[select count(iilnmp.INV_LINE_NOTE_ID) from IOA_INV_LINE_NOTE_MAP iilnmp , IOA_INVOICE_LINE_NOTES iiln , IOA_INVOICE_LINE iil where iilnmp.INV_LINE_NOTE_ID = iiln.ID and iiln.INLI_ID =iil.id and iil.ID = ?]]> ``` which i am calling from a method as shown below now my query is that instead of having native query can i use criteria also to achieve the same result ``` public int findAttachementsCount(long id) { Query query = session.getNamedQuery("attachmentQuery"); query.setParameter(0, id); int attachCount = query.list().size(); return attachCount; } ``` Folks please advise for this. Can somebody please look this into priority..!!
2016/05/19
[ "https://Stackoverflow.com/questions/37319736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6355442/" ]
You shouldn't use `commandLine` + `args` together in a Gradle `Exec` task. Either use `commandLine` with executable and all arguments as the value, or `executable` + `args` which is the better alternative usually.
My gradle file contained a snippet to get the aws auth token and I was getting the same failure - `Caused by: java.io.IOException: error=2, No such file or directory` In my case, the issue was not caused due to caching. It was due to gradle not being able to find the aws binary. What worked for me - Use the `which aws` command to find the absolute path to aws binary and use it for the binary as shown below. Hope this helps someone with similar issue. [![enter image description here](https://i.stack.imgur.com/AKxKg.png)](https://i.stack.imgur.com/AKxKg.png)
29,991,407
I want to run `x` function for `n` seconds. What I tried: ``` var stop = false; setTimeout(function(){stop = true}, n); while(!stop) x(); ``` but this didn't work... As I understood the reason is that setTimeout waiting until no task is running and then executes the function. Is that right? Another way to do this is like this: ``` var stop = false, started = Date.now(); while(!stop) { if((Date.now() - started) > n) stop = true; else x(); } ``` Is there any other better way?
2015/05/01
[ "https://Stackoverflow.com/questions/29991407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3546760/" ]
``` var stop = false; setTimeout(function(){stop = true}, n); var interval = setInterval(function(){ if(!stop){x();}else{clearInterval(interval);} }, 0); ``` the while statement will block the timeout function, if you don't mind using setInterval, you can do it like this.
You can schedule it repeatedly while time's not up: ``` var runRepeatedly = function(f, secs) { var start = Date.now(); var reschedule = function() { var now = Date.now(); if (now - start < secs * 1000) { setTimeout(repeat, 0) } } var repeat = function() { f(); reschedule(); }; repeat(); } ... runRepeatedly(x, n); ``` Note that `x` should not take too long to return.
48,737,886
With ES5 constructor and prototype approach I can add public (prototype) properties as below: ``` function Utils(){} Utils.prototype.data = {}; var utils = new Utils(); console.log(utils.data); //{} ``` The ES6 `class` allows me to define only public methods in the class. I build an app with a class-approach and I don't want to mix constructors and classes features. The working code that I figured out is: ``` class Utils(){ get _data(){ const proto = Object.getPrototypeOf(this); if(!proto._status) proto._data = {}; return proto._data; } } const utils = new Utils(); console.log(utils._data); //{} ``` When I call `_data` getter method, it checkes whether the `_data` property exists in the prototype object. If so, it returns it, otherwise it initiates the `_data` property. Is it a good practice? Is there any other way to do it better?
2018/02/12
[ "https://Stackoverflow.com/questions/48737886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5388390/" ]
You can use AJAX to fetch content from the server and display that content in the second column. Below is a sample application illustrating this concept: **app.py** ``` from flask import Flask, render_template app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' app.config['DEBUG'] = True @app.route('/') def page_view(): return render_template('view.html') @app.route('/plot') def plot(): return render_template('plot.html') if __name__ == '__main__': app.run() ``` **templates/view.html** ``` <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("a.loadPlot").click(function() { args = $(this).data('args'); $.ajax({ type: "GET", data: args, url: "{{ url_for('plot') }}", success: function(data) { $('#targetColumn').html(data) } }); }); }); </script> <style> .column { float: left; width: 33.33%; padding: 10px; height: 300px; /* Should be removed. Only for demonstration */ } </style> </head> <body> <div class="column" style="background-color:#aaa;"> <a href="#" class="loadPlot" data-args='{"par1": 1, "par2": 4, "par3": 10}'>Plot 1</a><br /> <a href="#" class="loadPlot" data-args='{"par1": 5, "par2": 3, "par3": 5}'>Plot 2</a><br /> <a href="#" class="loadPlot" data-args='{"par1": 10, "par2": 9, "par3": 1}'>Plot 3</a><br /> </div> <div class="column" style="background-color:#bbb;" id="targetColumn"> </div> </body> </html> ``` **templates/plot.html** ``` Plot with args: <br /><br/ > <ul> {% for a in request.args %} <li>{{ a }} - {{ request.args[a] }}</li> {% endfor %} </ul> ```
Answer is not short, and I cannot accomplish it fully with just parts of code that you've provided, but I can give you some guidance so you can continue. Change your /PLOT route to return json instead of rendering template. ``` @app.route('/plot') def plot(): ... return flask.jsonify(jsongraph) ``` Then you need to add all needed libraries to your first html, so include `plotly` js. After that you need to add ajax calls instead of links to button: ``` <div class="column" style="background-color:#aaa;"> <span id="link">link text</span> </div> <div class="column" style="background-color:#bbb;" id="target"> <!-- DISPLAY SOMETHING HERE --> </div> ``` and add something like (example in jQuery) ``` <script> $(document).ready(function(){ $.get('/ploty', function(data){ ... Plotly.plot(..., graph.data, graph.layout); ... }); }); </script> ``` Idk how plotly works exactly, but you need to provide to it id of `target` div somehow. Also maybe you need to clear previous content of div.
47,270
I thought about posting this in English.SE, but since it occurs in a university setting, I decided to post here - hopefully it's on-topic. I have been working on a project that is being transitioned to another group member so she could take over the project. The project involves the design, development, and application of "Model X". I have done some useful work on it, but some work still needs to be done to complete it. I'm putting together a documentation package to describe what I've done so far, the design of "Model X", and how to use the code I've written thus far. This report is internal to the group (whether this will be part of something that is published in the future, I do not know). I hesitate to title the report "Model X" because it's not, and might not be close to, being the final model. How should I title the transition report? Some options I have thought of: "Current status of Model X" - but this seems like an email subject "Incomplete Model X: Design and Usage" - this sounds a bit degrading What would you suggest? And are there in fact accepted titles for this kind of report?
2015/06/16
[ "https://academia.stackexchange.com/questions/47270", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/35916/" ]
I have typically seen the word "Draft" used, as in: > > Draft Model of X (Date) > > > If you want to track multiple drafts over time, then you can give a version number as well: > > Draft Model of X (Version N, Date) > > >
I suggest using term *"intermediate"*, as it IMHO most accurately reflects the incomplete status of the project. Therefore, the title of the corresponding report might be formulated like the following: > > "[Topic of the report]: Intermediate technical report by [group name]. > Version x.y.z from [date]" > > >
58,039,133
i'm using GPS NEO 6m with esp8266(NODEMCU) and uploading data to firebase Using " Serial.print(gps.location.lat(), 6);" shows "Latitude= 34.200271" But How to save **Latitude as local variable with 6 decimal degits ?** using " float latitude=(gps.location.lat()); only saves 34.20 " and " float latitude=(gps.location.lat(),6); only saves 6" Thanks
2019/09/21
[ "https://Stackoverflow.com/questions/58039133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12098976/" ]
When using a Trusted Web Activity with the recommended [android-browser-helper library](https://github.com/GoogleChrome/android-browser-helper/), the application will check for an installed browser that supports Trusted Web Activity, giving preference to the user's preferred browser. If there's no browser that supports the protocol available, it will fall back to using a [Custom Tab](https://developers.google.com/web/android/custom-tabs) and, if Custom Tabs is not available, open the browser. The library also contains a [WebView fallback](https://github.com/GoogleChrome/android-browser-helper/blob/master/androidbrowserhelper/src/main/java/com/google/androidbrowserhelper/trusted/WebViewFallbackActivity.java) for developers who prefer that to the Custom Tab / browser. A demo on how to use the WebView fallback is available [here](https://github.com/GoogleChrome/android-browser-helper/tree/master/demos/twa-webview-fallback). Regarding the Samsung Internet browsers, it added support for Trusted Web Activity in November 2020 (version 13.0.2.9). Currently, Chrome, Samsung Internet, Firefox, Edge and others support Trusted Web Activity, covering the vast majority of users. An updated list of browser support is maintained [here](https://github.com/GoogleChrome/android-browser-helper/blob/master/docs/trusted-web-activity-browser-support.md).
I just checked my TWA and it is working for particular browsers as follows: * Chrome without any problem * Edge on first launch shows message running in edge, later works as expected * Opera working as expected * Samsung browser - asks to open in browser, but works fine in browser. hides address bar if opened in browser * Firefox(once a best browser around ...) asks to open in browser, if opened it still shows address bar
69,299,586
I suddenly get this error and not sure why.I did not change the `"react-router-dom": "^6.0.0-beta.4"` version. But the `"react-dom": "^16.8.4"`" had changed to `"react-dom": "^16.13.1"`, Dunno if that had anything to do with I don't know but the `useRoutes` comes from `"react-router-dom"` and that's where the error originate ya. Anyone have a clue? [![enter image description here](https://i.stack.imgur.com/Lk2gb.png)](https://i.stack.imgur.com/Lk2gb.png) Here is my App.jsx where i use the `useRoutes(routes)` and it's giving me the error: ``` import React, { useEffect } from 'react'; import { AnimatePresence } from 'framer-motion'; import { connect } from 'react-redux'; import { compose } from 'recompose'; import { useRoutes } from 'react-router-dom'; import { ThemeContextProvider } from './theme/ThemeProvider'; import { getAlbumData } from './redux/albumData/albumData.actions'; import { getMetaData } from './redux/albumMetaData/albumMetaData.actions'; import { startTagsListener, startTagsCategoryListener, } from './redux/global/global.actions';1111 import { withAuthentication } from './session'; import './styles/index.css'; import routes from './routes'; require('react-dom'); const AnimatedSwitch = () => { const routing = useRoutes(routes); return ( <AnimatePresence exitBeforeEnter initial={false}> <div>{routing}</div> </AnimatePresence> ); }; const App = props => { const { getMeta, getAlbum, startTagListener, startTagCategoryListener } = props; useEffect(() => { getMeta(); getAlbum(); startTagListener(); startTagCategoryListener(); }, [getMeta, getAlbum, startTagListener, startTagCategoryListener]); return ( <ThemeContextProvider> {AnimatedSwitch()} </ThemeContextProvider> ); }; const mapDispatchToProps = dispatch => ({ getMeta: () => dispatch(getMetaData()), getAlbum: () => dispatch(getAlbumData()), startTagListener: () => dispatch(startTagsListener()), startTagCategoryListener: () => dispatch(startTagsCategoryListener()), }); export default compose(connect(null, mapDispatchToProps), withAuthentication)(App); ``` Here are the routes and I have not changed them in the last month: ``` import React from 'react'; import ContentLayout from './components/structure/ContentLayout'; import DashboardLayout from './components/DashboardLayout'; import AccountView from './components/DashboardLayout/views/account/AccountView'; import SearchListView from './components/DashboardLayout/views/search/SearchListView'; import DashboardView from './components/DashboardLayout/views/dashboard/DashboardView'; import NotFoundView from './components/DashboardLayout/views/errors/NotFoundView'; import CreateContentView from './components/DashboardLayout/views/creator/CreateContentView'; import SettingsView from './components/DashboardLayout/views/settings/SettingsView'; import LoginView from './components/DashboardLayout/views/auth/LoginView'; import RegisterView from './components/DashboardLayout/views/auth/RegisterView'; import SubmissionsView from './components/DashboardLayout/views/submissions/SubmissionsView'; import InboxView from './components/DashboardLayout/views/inbox/InboxView'; const routes = [ { path: 'app', element: <DashboardLayout />, children: [ { path: 'account', element: <AccountView /> }, { path: 'search', element: <SearchListView /> }, { path: 'dashboard', element: <DashboardView /> }, { path: 'create', element: <CreateContentView /> }, { path: 'submissions', element: <SubmissionsView /> }, { path: 'inbox', element: <InboxView /> }, { path: 'settings', element: <SettingsView /> }, { path: 'login', element: <LoginView /> }, { path: 'register', element: <RegisterView /> }, { path: '*', element: <NotFoundView /> }, { path: '/', element: <DashboardView /> }, ], }, { path: '/', element: <ContentLayout />, children: [ { path: '404', element: <NotFoundView /> }, { path: '*', element: <NotFoundView /> }, ], }, ]; export default routes; ```
2021/09/23
[ "https://Stackoverflow.com/questions/69299586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11749004/" ]
I have had a similar issue with material kit ui, and i fixed it simply just write `path:""`. leaving the path empty will fix the problem
I have seen the error message and it clearly explains that path "/" should not be given under route "app".So try changing the path to some other valid name or remove it.
12,483
> > (As for women past child-bearing, who have no hope of marriage) and do > not need to get married, (it is no sin for them) for such women (if > they discard their (outer) clothing) in front of strange people (in > such a way as not to show adornment) without adorning themselves or > showing their adornment to strangers. (But to refrain) to keep their > outer garment on (is better for them) than discarding it. (Allah is > Hearer) He hears what they say, (Knower) He knows their deeds. > **[24:60](http://www.altafsir.com/Tafasir.asp?tMadhNo=2&tTafsirNo=73&tSoraNo=24&tAyahNo=60&tDisplay=yes&UserProfile=0&LanguageId=2)** > > > --- [What is Adornment?](https://www.google.com.pk/search?q=vb6+and+dir+and+directory+check&oq=vb6+and+dir+and+directory+check&aqs=chrome..69i57.8781j0j7&sourceid=chrome&es_sm=93&ie=UTF-8#q=adornment) > > a thing which adorns or decorates; an ornament. > > > An adornment is generally an accessory or ornament worn to enhance the > beauty or status of the wearer. > > > the act or process of making someone or something attractive by > decorating : the act or process of adorning someone or something. > > > something that adds attractiveness > > > --- **Point 1:** These explanations are in English and the word `adornment` is in English as well so, there is a high probability that the word has been explained well. If `adornment` = `ornament`(non-body parts) If `adornment` = Regular\_Cloths/Jewelry/Perfume/ then by referring to the following part of 24:60 > > without adorning themselves or showing their adornment to strangers > > > **i.e. Outer cloths can be put off but adornment or Regular\_Cloths/Jewelry/Perfume should still be kept hidden**, So **Q 1.1** Which *things* get exposed after removing outer cloths while `Regular_Cloths/Jewelry/Perfume` are still hidden? **Q 1.2** What is the logic in hiding `Regular_Cloths/Jewelry/Perfume` even for an old woman? **Q 1.3** What benefit/relief will an old woman get by exposing *that thing* (answer of Q 1.1)? --- **Point 2:** Since `زينة` is an Arabic word so there is a high possibility that the `adornment` is not the right word for `زينة` or there is no 100% accurate translation possible. Now if `زينة` = `outer-body-parts`(hair, neck, feet, face, hands) and not Regular\_Cloths/Jewelry/Perfume then by referring to the following part of 24:60 > > without adorning themselves or showing their adornment to strangers > > > **i.e. Outer cloths can be put off but adornment or hair, neck, feet, face, hands should still be kept hidden**, So **Q 2.1** Which *things* get exposed after removing outer cloths while `hair, neck, feet, face, hands` are still hidden? **Q 2.2** What is *that cloth* which is allowed to put off while keeping `hair, neck, feet, face, hands` hidden from strangers? **Q 2.3** What benefit/relief will an old woman get by exposing *that thing* (answer of Q 2.1)? --- **One would answer all questions of either Point 1 or 2 but not both. It would be interesting if one proves both points valid.**
2014/04/16
[ "https://islam.stackexchange.com/questions/12483", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/3775/" ]
God wants women to hide from strangers anything that might be attractive for them, but he says it's no blame if an old woman doesn't put on outer garment. but not to the extent that they also show anything attractive. `زینه` = anything attractive! **Q\*.1** Anything that might be attractive! **Q1.2** The logic is that no one would probably fall into a sin. **Q2.2** The outer garment is Chador(the usual garment of Muslim women in public places). An old woman can still be unattractive and hiding her `anything attractive` by not wearing Chador. **Q\*.3** The issue is not what gain might be in this for the old woman, The Problem is about society not to lose its order and modesty.
Here is the translation: > > And women of post-menstrual age who have no desire for marriage - > there is no blame upon them for putting aside their **outer garments** > [but] not displaying adornment. But to modestly refrain [from that] is > better for them. And Allah is Hearing and Knowing. > > > Please note the word OUTER garment. it does not says that completely remove all clothes, but it means outer garment, like Complete Hjiab or Jilbab, that women wear to fully cover their body. In front of their brothers and mahrams, they can remove the Hijab(outer garment). Adornment, here means that beauty,that is visible to her mahrams, like her hair , neck, feet, face and hands are all visible to them. And Allah knows the best
29,056
We already have a large list of the [Best book ever on Number Theory](https://math.stackexchange.com/questions/329/best-ever-book-on-number-theory), but I'm looking for a more targeted response for analytic number theory. Specifically, I'm taking a trip on which I may or may not have access to internet resources, nor my University's library. I'm starting to work through Montgomery and Vaughan's [*Multiplicative Number Theory*](http://books.google.com/books?id=nGb1NADRWgcC&printsec=frontcover&dq=multiplicative+number+theory+montgomery&source=bl&ots=AwKlmhPkvu&sig=p0z-AdItbjwjjnlqmQWULUSEelA&hl=en&ei=_e6MTZObJ7C10QGomYmfCw&sa=X&oi=book_result&ct=result&resnum=2&ved=0CCEQ6AEwAQ#v=onepage&q&f=false). What would be the one book you recommend bringing as a supplement?
2011/03/25
[ "https://math.stackexchange.com/questions/29056", "https://math.stackexchange.com", "https://math.stackexchange.com/users/7346/" ]
Of course, the second book in their sequence: [Montgomery and Vaughn Chapters 16-27 draft version](http://www-personal.umich.edu/%7Ehlm/math775/handouts.html) (online only) Here are some other well known titles (in no particular order): > > H. Iwaniec and E. Kowalski, Analytic Number Theory > > > H. Davenport, Multiplicative Number Theory > > > A. E. Ingham, The Distribution of Prime Numbers > > > T. M. Apostol, Introduction to Analytic Number Theory > > > P. T. Bateman and H. G. Diamond, Analytic Number Theory: An introductory course > > > E. C. Titchmarsh (revised by D. R. Heath-Brown), The Theory of the Riemann Zeta-Function > > > Hope that helps, **Remark:** These books were all suggested readings from one of my courses. The books by Davenport, Bateman, Apostol and Ingham were suggested reading for the basics of analytic number theory, while Titchmarsh and Iwaniec and the online chapters of M&V were more related to the course material.
I would also add to Eric's answer that Tenenbaum's "Introduction to Analytic and Probabilistic Number" is a great resource if one is limited to the number of books you can carry.
3,699,154
I have a demo server where I put samples of my apps, I send potential customers links to those apps. Is it possible to use htaccess to track visitors, *without* adding tracking capability to the apps themselves? The data I'm interested in are: 1. date and time of page visit 2. ip of visitor 3. url of the page visited 4. referrer 5. post and get (query string) data if any
2010/09/13
[ "https://Stackoverflow.com/questions/3699154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66580/" ]
That entirely depends on your webserver, what options it provides for htaccess overrides. For Apache, the access log logs what you are looking for <http://httpd.apache.org/docs/current/logs.html#accesslog> but is **not configurable via htaccess**.
I know this thread has been quiet for a while, but i it not possible to use the ***prepend***?? directive that prepends a script to all visits to track site/page visits ? I have not got the code (tried something similarthough was not successfull) but I used the prepend directive to prepend a script that "switches" on gzip for all site visits. I am sure the same can be implemented for logs (for those of us with cheap shared servers!) Come on coders, do us all a favour and reveal the secret!
16,383,242
I'm very new to Android development (have some Obj-C experience with Cocoa Touch though). I was testing my first Android app as I encountered these syntax errors: > > Syntax error on token "100000", invalid VariableDeclaratorId > > > Syntax error on token "11", delete this token > > > Syntax error on token "2", delete this token > > > Syntax error on token "5000", invalid VariableDeclaratorId > > > Syntax error on token "61", invalid VariableDeclaratorId > > > Syntax error on token "69", invalid VariableDeclaratorId > > > When I double clicked them, they appeared to be in the file `R.java` and I have no idea how they are caused. ``` public static final class drawable { public static final int 100000=0x7f020000; public static final int 11ba=0x7f020001; public static final int 2values=0x7f020002; public static final int 5000=0x7f020003; public static final int 61=0x7f020004; public static final int 69=0x7f020005; ..... ``` It would be great if someone can tell how this is caused. [updates] [MarsAtomic](https://stackoverflow.com/users/2305826/marsatomic) suggested that it is caused by not following the naming conventions for Android resources and perhaps having rawables named "5000", "69", which is, as a matter of fact, true in this case. After changing the names, these exceptions didn't occur anymore. But I would still like to know why having images in numeral names would trigger this. Thanks.
2013/05/05
[ "https://Stackoverflow.com/questions/16383242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2024727/" ]
You cannot declare variable names starting with numbers.
Take a look at the RES directories. You might have a file with the numerical sequence mentioned above, eg 00000002. To solve the problem, simply remove it from the folder.
2,938,969
I would like to know how to translate the following code to codebehind instead of XAML: ``` <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> ``` The part I can't figure out is the Path portion. I have the following but it doesn't work: ``` new Trigger { Property = Validation.HasErrorProperty, Value = true, Setters = { new Setter { Property = Control.ToolTipProperty, // This part doesn't seem to work Value = new Binding("(Validation.Errors)[0].ErrorContent"){RelativeSource = RelativeSource.Self} } } } ``` Help?
2010/05/30
[ "https://Stackoverflow.com/questions/2938969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99367/" ]
I think I finally found a solution: First, in a header file, declare `memset()` with a pragma, like so: ``` extern "C" void * __cdecl memset(void *, int, size_t); #pragma intrinsic(memset) ``` That allows your code to call `memset()`. In most cases, the compiler will inline the intrinsic version. Second, in a separate implementation file, provide an implementation. The trick to preventing the compiler from complaining about re-defining an intrinsic function is to use another pragma first. Like this: ``` #pragma function(memset) void * __cdecl memset(void *pTarget, int value, size_t cbTarget) { unsigned char *p = static_cast<unsigned char *>(pTarget); while (cbTarget-- > 0) { *p++ = static_cast<unsigned char>(value); } return pTarget; } ``` This provides an implementation for those cases where the optimizer decides not to use the intrinsic version. The outstanding drawback is that you have to disable whole-program optimization (/GL and /LTCG). I'm not sure why. If someone finds a way to do this without disabling global optimization, please chime in.
Just name the function something slightly different.
37,319,736
I have the below hibernate native query as shown below the idea is not to use the native query and switch to hibernate criteria api ``` <![CDATA[select count(iilnmp.INV_LINE_NOTE_ID) from IOA_INV_LINE_NOTE_MAP iilnmp , IOA_INVOICE_LINE_NOTES iiln , IOA_INVOICE_LINE iil where iilnmp.INV_LINE_NOTE_ID = iiln.ID and iiln.INLI_ID =iil.id and iil.ID = ?]]> ``` which i am calling from a method as shown below now my query is that instead of having native query can i use criteria also to achieve the same result ``` public int findAttachementsCount(long id) { Query query = session.getNamedQuery("attachmentQuery"); query.setParameter(0, id); int attachCount = query.list().size(); return attachCount; } ``` Folks please advise for this. Can somebody please look this into priority..!!
2016/05/19
[ "https://Stackoverflow.com/questions/37319736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6355442/" ]
You shouldn't use `commandLine` + `args` together in a Gradle `Exec` task. Either use `commandLine` with executable and all arguments as the value, or `executable` + `args` which is the better alternative usually.
I had similar issue.. With Vampire's solution, I was able to step up.. However the issue seems to be the sh file not able to point to the exact file location. Meaning, even with workingDir (wherein actual sh file resides) set properly, still was getting the following exception. ``` Caused by: java.io.IOException: error=2, No such file or directory ``` Finally, this [post](https://discuss.gradle.org/t/a-problem-occurred-starting-process-ioexception-no-such-file-or-directory/1960) resolved the issue.. Though the original issue of this post's question is already resolved, thought of sharing this solution of adding the absolute file path to actual sh file would resolve the `"No such file or directory"` issue to someone in the future.. I ran into similar issue and got it resolved with absolute path reference to sh file. Mine was, ``` workingDir = "path_to_the_actual_sh_file_to_be_executed" executable = new File(workingDir, 'actual.sh') args = ['configure', 'manageRepo', '-tenant', 'etc...'] ```
85,127
According to <https://www.google.com/design/spec/style/icons.html#icons-system-icons>, icon size should be 24dp. This size is pretty elegant looking, yet doesn't make icon recognition difficult, as material styled icons are minimalist design. There isn't much detail inside the icon body. But, is this rule applicable, if our used icon (like country flags) has significant detail inside the icon body? Will this make icon recognition difficult? Does user need to stretch his eye ball, in order to know what does the icon represent? I post the following examples. **Is 24dp icon more difficult to be read/seen/recognized compared with 32dp?** 24dp ---- [![enter image description here](https://i.stack.imgur.com/ja7P4.png)](https://i.stack.imgur.com/ja7P4.png) 32dp ---- [![enter image description here](https://i.stack.imgur.com/TPVg2.png)](https://i.stack.imgur.com/TPVg2.png)
2015/09/28
[ "https://ux.stackexchange.com/questions/85127", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/27708/" ]
I think the issue you're having is because you're sticking to guidelines as laws on one side, and you're misunderstanding things a little bit (I admit Google Material is not clear about this, it's more like inference after viewing, studying and working on lots of Material design apps). A clue is given on the [same page you're linking](https://www.google.com/design/spec/style/icons.html#icons-system-icons): > > A system icon, or UI icon, symbolizes a command, file, device, or > directory. System icons are also used to represent common actions like > trash, print, and save. > > > The design of system icons is simple, modern, friendly, and sometimes > quirky. Each icon is reduced to its minimal form, with every idea > edited to its essence. The designs ensure readability and clarity even > at small sizes. > > > As you can see, Material Design only considers System Icons (which your flags are not). **So this leaves us with the question: what to do then?** For small illustrations with details (like flags), you should take a look to **[UI Integration chapter](https://www.google.com/design/spec/style/imagery.html#imagery-ui-integration)** and scroll to **Thumbnails and Avatars**. From that page: > > Avatars and thumbnails represent entities or content, either literally > through photography or conceptually through illustration. Generally, > they are tap targets that lead to a primary view of the entity or > content. > > > Avatars can be used to represent people. For personal avatars, offer > personalization options. As users may choose not to personalize an > avatar, provide delightful defaults. When used with a specific logo, > avatars can also be used to represent brand. > > > Thumbnails allude to more information—letting the user peek into > content—and assist navigation. Thumbnails let you include imagery in > tight spaces. > > > See? We got out of System Icons and dive straight into entities or taxonomies (which your flags actually stand for!) See an example below: [![enter image description here](https://i.stack.imgur.com/V9ouC.png)](https://i.stack.imgur.com/V9ouC.png) it's easy to see you can replace those avatars with flags. Now see the recommended metrics on the above elements: [![enter image description here](https://i.stack.imgur.com/T83G7.png)](https://i.stack.imgur.com/T83G7.png) As you can see by the metrics the avatar is 40dp `(72-16-16)`, which is **bigger than 24dp, and even bigger than 32**! Conclusion ========== To answer your specific question: not at all, but be careful because Material Design elements are quite unorganized so you need to read everything to find out which element to use on every case (in your case, **avatars or thumbnails**)
I think the thing to remember here is that the material design guidelines are just that, guidelines - and good design and common sense should always override them. In your example - whilst most flag designs are recognisable when small, the 32dp clearly flows better and the larger size does not obstruct your design. The only other suggestion i have is to ensure all of the flags are the same shape. Whilst they may all be 32dp wide, the square belgian flag is clearly taller than the rectangular canadian flag. Consistency here would improve the design.
3,377,464
I have a Chipmunk shape, with a body, in a space. I am removing the body from the space so that I can position it and not have it fall due to gravity etc. I need to be able to make this body move, so I am not making it static. I need the body to update it's position according to the position of a Cocos2D sprite in the scene + an offset. I'm setting the bodies position with: collShape->body->p = collSprite.position; - this seems to not work, not compile errors, it runs, but the collision shape doesn't move. Is it possible to move a collision body based upon the position of a sprite in my tick method?
2010/07/31
[ "https://Stackoverflow.com/questions/3377464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407371/" ]
That depends on what environment the JS is running in. If you are in a browser which supports mp3 and the HTML5 audio API, then you can load the mp3 in an `<audio>` element and access the [duration property](http://www.w3.org/TR/html5/media-elements.html#dom-media-duration) via the DOM. If you are using some sort of Flash player, then it might expose that information using ExternalInterface. There are other environments, but they aren't in such common usage.
There is actually a library that can run client-side, attempting to fetch just enough of the MP3 to read the ID3 tags: <http://github.com/aadsm/JavaScript-ID3-Reader> Since you are using server-side JavaScript, you can directly read files from the server and do pretty much anything you want. If you can't find any libraries specifically for server-side use, I expect you can grab just the bits out of the above project that relate to parsing the ID3, and leave out the AJAX fetching stuff. Other libraries are available with a Web search for *Javascript ID3*.
316,352
In Java, you can qualify local variables and method parameters with the final keyword. ``` public static void foo(final int x) { final String qwerty = "bar"; } ``` Doing so results in not being able to reassign x and qwerty in the body of the method. This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?
2008/11/25
[ "https://Stackoverflow.com/questions/316352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32174/" ]
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it. I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error. But, of course, it's all personal preference ;-)
Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work. The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier. *Edit* In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.
6,758,706
It just appears like this in Google Chrome: ``` <html> <head> <title>Hello World!</title> </head> <body> <h1 align="center">Hello World!<br/>Welcome to My Web Server.</h1> </body> </html> ``` Why isn't it transforming as expected? Edit: Yes the file does have an .html filename. I'm not sure it should need a header yet according to a tutorial I'm using which says that it should render correctly without one? All new to this so I'm unsure. Edit: When I open it with textedit, I get this: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <title></title> <meta name="Generator" content="Cocoa HTML Writer"> <meta name="CocoaVersion" content="1038.35"> <style type="text/css"> p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica} </style> </head> <body> <p class="p1">&lt;html&gt;</p> <p class="p1">&lt;head&gt;</p> <p class="p1">&lt;title&gt;Hello World!&lt;/title&gt;</p> <p class="p1">&lt;/head&gt;</p> <p class="p1">&lt;body&gt;</p> <p class="p1">&lt;h1 align="center"&gt;Hello World!&lt;br/&gt;Welcome to My Web Server.&lt;/h1&gt;</p> <p class="p1">&lt;/body&gt;</p> <p class="p1">&lt;/html&gt;</p> </body> </html> ``` I don't remember saving it like this at all.
2011/07/20
[ "https://Stackoverflow.com/questions/6758706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/812013/" ]
It should be rendered by the browser, not the webserver. Check the HTTP headers "Content-Type". It should read something like "Content-Type: text/html; charset=utf-8". Given your using Chrome, load up developer tools using the following steps; 1. Right click the page -> Choose "Inspect Element" 2. Go to the network tab 3. Load the page your trying to inspect 4. Pick the URL of the page for which you want to inspect headers etc
From the file content you posted contains the explanation: ``` <meta name="Generator" content="Cocoa HTML Writer"> ``` Basically, your text editor thought you wanted to *convert* the "text" you had entered to a webpage. So it saved it as a webpage that displays exactly what you have entered. How did you save the file? If you used anything that says "convert" or "export" to HTML, that's the culprit. Just use the regular "save" option. And if that doesn't work: get a better editor, one that doesn't try to be smarter than you.
3,200,050
I was thinking $f(n)=|n|$, but realized that would be a surjection. I'm not sure of how to solve this. Thank you.
2019/04/24
[ "https://math.stackexchange.com/questions/3200050", "https://math.stackexchange.com", "https://math.stackexchange.com/users/638602/" ]
Let $f(n)=2(n+1)$ if $n\ge0$ and $-2n-1$ if $n<0$. This maps {$0,1,2,...$} to {$2,4,6,...$} and {$-1,-2,-3,...$} to {$1, 3, 5, ...$}; i.e., {$..., -3, -2, -1, 0, 1, 2, ...$} to {$1,2,3,4,5,6,...$}. The inverse map is $f^{-1}(m)=\dfrac m 2 -1 $ if $m$ is even and $-\dfrac{m+1}2$ if $m$ is odd.
Define $f$ as follows: $$ f(n) = \left\{\begin{array}{lr} 2^n , & \text{when } n \ge 0 \\ 3^{|n|} , & \text{when } n \lt 0 \end{array}\right\} $$
3,020,746
> > [![enter image description here](https://i.stack.imgur.com/wacyF.gif)](https://i.stack.imgur.com/wacyF.gif) > > > Given that ABC is an isosceles triangle, $[BD]$ is angle bisector, $\angle BDA = 120^\circ$. Evaluate the degree of $\angle A $ > > > Could you help me approach this problem using sine law? Here's my attempt: From the angle bisector theorem, we know that $$\dfrac{|AB|}{|BC|} = \dfrac{|AD|}{|DC|} $$ In $\triangle ADB$, let's call same angles $\alpha$ and we have that $$\dfrac{|AB|}{\sin (120)} = \dfrac{|AD|}{\sin(\alpha )} \implies \dfrac{|AB|}{|AD|} = \dfrac{\sin (120)}{\sin (\alpha )} $$ This also equals $$\dfrac{|AB|}{|AD|} = \dfrac{\sin (120)}{\sin (\alpha )} = \dfrac{|BC|}{|DC|}$$ Now $\angle A 180-120-\alpha = 60-\alpha $, then $$\dfrac{|DB|}{\sin (x)} = \dfrac{|AB|}{\sin (120)} \implies \dfrac{|DB|}{|AB|} = \dfrac{\sin(60-\alpha )}{\sin (120)} $$
2018/11/30
[ "https://math.stackexchange.com/questions/3020746", "https://math.stackexchange.com", "https://math.stackexchange.com/users/533847/" ]
Let $x$ be the measure of $\angle ABD$ and $y$ be the measure of $\angle BAC$ $x+y+ 120 = 180\\ 4x + y = 180$ And solve the system of equations. Regrading law of sines.. that might be useful you knew more side lengths. Right now all you know is that the triangle is isosceles.
We have that since $\angle BDC=60° \implies \angle ACB=\angle ABC=80\*$ and $\angle BAC=20°$. To find the result by law of sine let * $BC=a $ * $AB=AC=b$ * $BD=x$ * $DC=y$ * $\angle BAC=\alpha$ then we have to solve the following systems of $5$ equations in $5$ unknowns * $\frac{a}{\sin \alpha}=\frac{b}{\sin 80}$ * $\frac{a}{\sin 60}=\frac{x}{\sin 80}=\frac{y}{\sin 40}$ * $\frac{x}{\sin \alpha}=\frac{b}{\sin 120}=\frac{b-y}{\sin 40}$
66,884,049
Is it possible somehow to preform logical functions on arrays like eg. ``` a= [1,2,3,4,5,6] b= [1,3,5,7] c= a and b resulting in c=[1,3,5] ``` so only the values that are present in both the arrays. The same with or eg: ``` d = a OR b resulting in b=[1,2,3,4,5,6,7] ``` Is this possible somehow in python or are there short functions for this? Thanks for your response
2021/03/31
[ "https://Stackoverflow.com/questions/66884049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3851151/" ]
Lists do not support logical operations , but you can do it in sets: ``` a= [1,2,3,4,5,6] b= [1,3,5,7] c = list(set(a) | set(b)) d = list(set(a) & set(b)) print(c) # OUTPUT: [1, 2, 3, 4, 5, 6, 7] print(d) # OUTPUT: [1, 3, 5] ```
Here is your snippet: ``` def and_array(a, b): return [a[i] for i in range(min(len(a), len(b))) if a[i] in b or b[i] in a] def or_array(a, b): return a + [element for element in b if not element in a] a= [1,2,3,4,5,6] b= [1,3,5,7] c = and_array(a, b) d = or_array(a, b) print(c) print(d) ``` Result: ``` [1, 2, 3] [1, 2, 3, 4, 5, 6, 7] ``` It is not that fast, avoid this for very large lists and use numpy or build-in functions!
39,130,015
Following simplified table ``` CustNr OrderNr Date Price Curry 1 555 030316 2,4 EUR 1 666 030316 2,5 EUR 1 777 030316 2,3 EUR 1 777 030316 1,9 USD 1 888 030316 2,3 EUR 1 888 030316 2,4 EUR ``` Desired output: ``` CustNr OrderNr Date Price Curry CustNr OrderNr Date Price Curry 1 555 030316 2,4 EUR 1 666 030316 2,5 EUR 1 777 030316 2.3 EUR 1 777 030316 1,9 USD 1 888 030316 2,3 EUR 1 888 030316 2,4 EUR ``` I tried following self join: ``` SELECT * FROM TEST T1 INNER JOIN TEST T2 ON T1.OrderNr = T2.OrderNr ``` But then i get duplicate records and a `GROUP BY` only works when grouping by OrderNr but I also need the other columns aswell.
2016/08/24
[ "https://Stackoverflow.com/questions/39130015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977744/" ]
You should use left join instead of inner join and filter by Curry ``` SELECT * FROM TEST T1 LEFT JOIN TEST T2 ON (T1.OrderNr = T2.OrderNr AND T1.Curry <> T2.Curry ) ```
You need a top-level query that represents unique order numbers: ``` select t.OrderNr, t1.*, t2.* from (select distinct OrderNr from test) t cross apply (select top 1 * from test t1 where t1.OrderNr = t.OrderNr order by Curry) t1 outer apply (select top 1 * from test t2 where t2.OrderNr = t.OrderNr and t2.Curry <> t1.Curry order by Curry) t2 ``` I think this answers the question, but I think it raises more questions about the design of the desired output.
9,694,863
I'm attempting to learn XML in order to parse GChats downloaded from GMail via IMAP. To do so I am using lxml. Each line of the chat messages is formatted like so: ``` <cli:message to="email@gmail.com" iconset="square" from="email@gmail.com" int:cid="insertid" int:sequence-no="1" int:time-stamp="1236608405935" xmlns:int="google:internal" xmlns:cli="jabber:client"> <cli:body>Nikko</cli:body> <met:google-mail-signature xmlns:met="google:metadata">0c7ef6e618e9876b</met:google-mail- signature> <x stamp="20090309T14:20:05" xmlns="jabber:x:delay"/> <time ms="1236608405975" xmlns="google:timestamp"/> </cli:message> ``` When I try to build the XML tree like so: ``` root = etree.Element("cli:message") ``` I get this error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "lxml.etree.pyx", line 2568, in lxml.etree.Element (src/lxml/lxml.etree.c:52878) File "apihelpers.pxi", line 126, in lxml.etree._makeElement (src/lxml/lxml.etree.c:11497) File "apihelpers.pxi", line 1542, in lxml.etree._tagValidOrRaise (src/lxml/lxml.etree.c:23956) ValueError: Invalid tag name u'cli:message' ``` When I try to escape it like so: ``` root = etree.Element("cli\:message") ``` I get the exact same error. The header of the chats also gives this information, which seems relevant: ``` Content-Type: text/xml; charset=utf-8 Content-Transfer-Encoding: 7bit ``` Does anyone know what's going on here?
2012/03/14
[ "https://Stackoverflow.com/questions/9694863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/723212/" ]
You can also do it without AVFoundation and it is in my opinion an easier way to implement it using only the UIImagePickerController. There are 3 conditions: 1. Obviously the device needs to have a camera 2. You must hide the camera controls 3. Then simply use the takePicture method from UIImagePickerController Below is a simple example that you woul typically trigger after a button push ``` - (IBAction)takePhoto:(id)sender { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; picker.sourceType = UIImagePickerControllerSourceTypeCamera; picker.cameraDevice = UIImagePickerControllerCameraDeviceFront; picker.showsCameraControls = NO; [self presentViewController:picker animated:YES completion:^ { [picker takePicture]; }]; } ```
[VLBCameraView](https://github.com/verylargebox/VLBCameraView) is a library that uses AVFoundation to take photo. A preview is shown in the view, which you can then call the method VLBCameraView#takePicture programmatically to take a photo. Comes with CocoaPods.
7,230,820
I'm looking at a Git hook which looks for print statements in Python code. If a print statement is found, it prevents the Git commit. I want to override this hook and I was told that there is a command to do so. I haven't been able to find it. Any thoughts?
2011/08/29
[ "https://Stackoverflow.com/questions/7230820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558699/" ]
Maybe (from [`git commit` man page](https://git-scm.com/docs/git-commit)): ``` git commit --no-verify -m "commit message" ^^^^^^^^^^^ -n --no-verify ``` > > This option bypasses the pre-commit and commit-msg hooks. See also [githooks(5)](http://git-scm.com/docs/githooks). > > > As commented by [Blaise](https://stackoverflow.com/users/451480/blaise), `-n` can have a different role for certain commands. For instance, [`git push -n`](http://git-scm.com/docs/git-push) is actually a dry-run push. Only `git push --no-verify` would skip the hook. --- Note: Git 2.14.x/2.15 improves the `--no-verify` behavior: See [commit 680ee55](https://github.com/git/git/commit/680ee550d72150f27cdb3235462eee355a20038b) (14 Aug 2017) by [Kevin Willford (``)](https://github.com/). (Merged by [Junio C Hamano -- `gitster` --](https://github.com/gitster) in [commit c3e034f](https://github.com/git/git/commit/c3e034f0f0753126494285d1098e1084ec05d2c4), 23 Aug 2017) > > `commit`: skip discarding the index if there is no `pre-commit` hook > -------------------------------------------------------------------- > > > > > "`git commit`" used to discard the index and re-read from the filesystem > just in case the `pre-commit` hook has updated it in the middle; this > has been optimized out when we know we do not run the `pre-commit` hook. > > > --- [Davi Lima](https://stackoverflow.com/users/462849/davi-lima) points out [in the comments](https://stackoverflow.com/questions/7230820/skip-git-commit-hooks/7230886?noredirect=1#comment101929781_7230886) the [`git cherry-pick`](https://git-scm.com/docs/git-cherry-pick) does *not* support --no-verify. So if a cherry-pick triggers a pre-commit hook, you might, as in [this blog post](http://web-dev.wirt.us/info/git-drupal/git-continue-vs-no-verify), have to comment/disable somehow that hook in order for your git cherry-pick to proceed. The same process would be necessary in case of a `git rebase --continue`, after a merge conflict resolution. --- With Git 2.36 (Q2 2022), the callers of `run_commit_hook()` to learn if it got "success" because the hook succeeded or because there wasn't any hook. See [commit a8cc594](https://github.com/git/git/commit/a8cc594333848713b8e772cccf8159196ea85ede) (fixed with [commit 4369e3a1](https://github.com/git/git/commit/4369e3a1a39895ab51c2bef2985255ad05957a20)), [commit 9f6e63b](https://github.com/git/git/commit/9f6e63b966e9876ca6f990819fabafc473a3c9b0) (07 Mar 2022) by [Ævar Arnfjörð Bjarmason (`avar`)](https://github.com/avar). (Merged by [Junio C Hamano -- `gitster` --](https://github.com/gitster) in [commit 7431379](https://github.com/git/git/commit/7431379a9c5ed4006603114b1991c6c6e98d5dca), 16 Mar 2022) > > [`hooks`](https://github.com/git/git/commit/a8cc594333848713b8e772cccf8159196ea85ede): fix an obscure **[TOCTOU](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use)** "did we just run a hook?" race > ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > > > Signed-off-by: Ævar Arnfjörð Bjarmason > > > > > Fix a [**Time-of-check to time-of-use** (**TOCTOU**)](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use) race in code added in [680ee55](https://github.com/git/git/commit/680ee550d72150f27cdb3235462eee355a20038b) ("`commit`: skip discarding the index if there is no pre-commit hook", 2017-08-14, Git v2.15.0-rc0 -- [merge](https://github.com/git/git/commit/c3e034f0f0753126494285d1098e1084ec05d2c4) listed in [batch #3](https://github.com/git/git/commit/ab86f93d680618f62ad6e3c2f37db76029cfce5e)). > > > This obscure race condition can occur if we e.g. ran the "`pre-commit`" hook and it modified the index, but `hook_exists()` returns false later on (e.g., because the hook itself went away, the directory became unreadable, etc.). > > Then we won't call `discard_cache()` when we should have. > > > The race condition itself probably doesn't matter, and users would have been unlikely to run into it in practice. > > This problem has been noted on-list when [680ee55](https://github.com/git/git/commit/680ee550d72150f27cdb3235462eee355a20038b) [was discussed](https://lore.kernel.org/git/20170810191613.kpmhzg4seyxy3cpq@sigill.intra.peff.net/), but had not been fixed. > > > Let's also change this for the push-to-checkout hook. > > Now instead of checking if the hook exists and either doing a push to checkout or a push to deploy we'll always attempt a push to checkout. > > If the hook doesn't exist we'll fall back on push to deploy. > > The same behavior as before, without the TOCTOU race. > > See [0855331](https://github.com/git/git/commit/0855331941b723b227e93b33955bbe0b45025659) ("`receive-pack`: support push-to-checkout hook", 2014-12-01, Git v2.4.0-rc0 -- [merge](https://github.com/git/git/commit/cba07bb6ff58da5aa4538c4a2bbf70b717b172b3)) for the introduction of the previous behavior. > > > This leaves uses of `hook_exists()` in two places that matter. > > The "reference-transaction" check in [`refs.c`](https://github.com/git/git/blob/a8cc594333848713b8e772cccf8159196ea85ede/refs.c), see [6754159](https://github.com/git/git/commit/675415976704459edaf8fb39a176be2be0f403d8) ("`refs`: implement reference transaction hook", 2020-06-19, Git v2.28.0-rc0 -- [merge](https://github.com/git/git/commit/33a22c1a88d8e8cddd41ea0aa264ee213ce9c1d7) listed in [batch #7](https://github.com/git/git/commit/4a0fcf9f760c9774be77f51e1e88a7499b53d2e2)), and the "prepare-commit-msg" hook, see [66618a5](https://github.com/git/git/commit/66618a50f9c9f008d7aef751418f12ba9bfc6b85) ("`sequencer`: run 'prepare-commit-msg' hook", 2018-01-24, Git v2.17.0-rc0 -- [merge](https://github.com/git/git/commit/1772ad1125a6f8a5473d73bbd17162bb20ebd825) listed in [batch #2](https://github.com/git/git/commit/b2e45c695d09f6a31ce09347ae0a5d2cdfe9dd4e)). > > > In both of those cases we're saving ourselves CPU time by not preparing data for the hook that we'll then do nothing with if we don't have the hook. > > So using this `"invoked_hook"` pattern doesn't make sense in those cases. > > > The "`reference-transaction`" and "`prepare-commit-msg`" hook also aren't racy. > > In those cases we'll skip the hook runs if we race with a new hook being added, whereas in the TOCTOU races being fixed here we were incorrectly skipping the required post-hook logic. > > >
For some reason, `--no-verify` does not work for me with this particular hook: `prepare-commit-msg` If you too are running into this issue, try: ```bash SKIP=prepare-commit-msg git commit ```
27,891,646
I am converting date to day, but if I just println() the current selected date in the datepicker, I get wrong time and wrong date. ``` @IBOutlet weak var datepicker: UIDatePicker! @IBAction func displayDay(sender: AnyObject) { var chosenDate = self.datepicker.date println(chosenDate) ``` I've following date selected date. ![enter image description here](https://i.stack.imgur.com/EAXaJ.png) And click on the button underneath datepicker. I get following line in output ``` 2015-01-11 20:17:37 +0000 ``` Can somebody tell me.what's wrong with output?
2015/01/11
[ "https://Stackoverflow.com/questions/27891646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/682321/" ]
Use this method to get correct date: ``` func getDateStamp(date:String)-> String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +SSSS" dateFormatter.timeZone = TimeZone(abbreviation: "UTC") guard let date = dateFormatter.date(from: date) else { // assert(false, "no date from string") return "" } dateFormatter.dateFormat = "dd MMMM,yyyy" //"yyyy-MM-dd" dateFormatter.timeZone = TimeZone.current let st = dateFormatter.string(from: date) return st } ```
Swift 5 ``` let yourLocalDate = Date().description(with: .current) ```
8,615,265
I want to change the background color of Days in my [FullCalendar](http://arshaw.com/fullcalendar) How can i do this..?
2011/12/23
[ "https://Stackoverflow.com/questions/8615265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875214/" ]
OPTION 1 there is class in each cell ``` .fc-past .fc-today .fc-future ``` You can use them in your css and make some colors for past, today and future. OPTION 2 You can loop for each day cell and do some check's Here is example with month view ``` $('.fc-day').each(function(){ if($(this).is('.fc-today')) return false; $(this).addClass('fc-before-today'); }) ``` CSS ``` .fc-before-today{background-color:red} ```
Do it in css, as simple as ``` .fc-past { background-color: #F5F5F6 } ```
7,660,328
I can't understand why I'm not able to use an additional local in my partial. In my parent view: ``` <%= render :partial => 'content', :locals => { :post => post, :summary => true } %> ``` And in my partial: ``` <%= summary ? post_content(post, 220) : post_content(post) %> ``` Results in an error, where the variable summary can't found: ``` undefined method `summary?' for #<#<Class:0x007ff425e773b0>:0x007ff425e67a50> ``` Any ideas? I'm potentially being really stupid here...!!
2011/10/05
[ "https://Stackoverflow.com/questions/7660328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/608171/" ]
I think you have to make the test expression more explicit, because the system is trying to find a method called summary? instead of using ? as ternary operator. Try changing it to: ``` <%= summary == true ? post_content(post, 220) : post_content(post) %> ```
Can you please confirm that in your partial you indeed have `summary <space> ?` instead of `summary?`
39,869,571
So I have this Team Services shared project which I've pulled locally. I am connecting to a remote DB which requires credentials in order to do anything with it. Everything works fine, and my `connectionString` is as follows: ``` <add name="PluginSchedulerContext" connectionString="metadata=res://*/PluginSchedulerDataModel.csdl|res://*/PluginSchedulerDataModel.ssdl|res://*/PluginSchedulerDataModel.msl;provider=System.Data.SqlClient; provider connection string=&quot; data source=xxx.xxx.xxx.xxx; initial catalog=TestDB; persist security info=True; user id=xxx; password=xxx; MultipleActiveResultSets=True; App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> ``` I was wondering if there is a smarter way to do this and to omit the password field in the string since `app.config` as I see is not part of the `.gitignore`. (I am migrating from Laravel PHP)
2016/10/05
[ "https://Stackoverflow.com/questions/39869571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841351/" ]
The better way is that, you can change connectionstring to connect to another database (test database), then you can replace connectionstring through [Replace Token task](https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens) to connect to actual database when you deploy app to the server through [build](https://www.visualstudio.com/en-us/docs/build/define/create) or [release](https://www.visualstudio.com/en-us/docs/release/overview). If you just want to use an database, can specify connectionstring programmatically. (Encrypt password, then store the encrypted password to your app, then decrypt password and combine connectionstring with actual password and specify it to entity context. The decrypt local could be in additional assembly.) ``` var encryptedPassword="xxx"; var actualPassword=[decrypt password]; var connstring = [combine connectionstring with actual password]; var estringnew = new EntityConnectionStringBuilder(connstring); estringnew.Metadata = XXX var context = new BAEntities(estringnew.ToString()); var query = from con in context.Contacts where con.Addresses.Any((a) => a.City == "Seattle") select con; ``` More information, you can refer to [this](https://msdn.microsoft.com/en-us/library/orm-9780596520281-01-16.aspx) article. For this way, developers can debug application to know actual password. If you don't want to let developers to know the actual password, you can [encrypt connectionstring](https://msdn.microsoft.com/en-us/library/zhhddkxy.aspx)
If you use Windows Authentication (client and database access using same Windows login) you don't need the username and password in your source code. Or you'll need to edit the configuration when you deploy. Otherwise the credentials are in your project's configuration in your VCS.
50,507,235
How to access nested dictionary in python. I want to access '**type**' of both card and card1. ``` data = { '1': { 'type': 'card', 'card[number]': 12345, }, '2': { 'type': 'wechat', 'name': 'paras' }} ``` I want only type from both the dictionary. how can i get. I use the following code but getting error: ``` >>> for item in data: ... for i in item['type']: ... print(i) ... Traceback (most recent call last): File "<stdin>", line 2, in <module> TypeError: string indices must be integers ```
2018/05/24
[ "https://Stackoverflow.com/questions/50507235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8211382/" ]
You can use: ``` In [120]: for item in data.values(): ...: print(item['type']) card wechat ``` Or list comprehension: ``` In [122]: [item['type'] for item in data.values()] Out[122]: ['card', 'wechat'] ```
[![nested dict](https://i.stack.imgur.com/SvAMJ.png)](https://i.stack.imgur.com/SvAMJ.png) from a nested python dictionary like this, if I want to access lets, say article\_url, so I have to program like this ``` [item['article_url'] for item in obj.values()] ```
46,105,620
I have this dataframe: ``` df: id . city . state . person1 . P1phone1 . P1phone2 . person2 . P2phone1 . P2phone2 1 . Ghut . TY . Jeff . 32131 . 4324 . Bill . 213123 . 31231 2 . Ffhs . TY . Ron . 32131 . 4324 . Bill . 213123 . 31231 3 . Tyuf . TY . Jeff . 32131 . 4324 . Tyler . 213123 . 31231 ``` I want it to look like this: ``` df: id . city . state . person . phone1 . phone2 1 . Ghut . TY . Jeff . 32131 . 4324 2 . Ghut . TY . Bill . 213123 . 31231 3 . Ffhs . TY . Ron . 32131 . 4324 4 . Ffhs . TY . Bill . 213123 . 31231 5 . Tyuf . TY . Jeff . 32131 . 4324 6 . Tyuf . TY . Tyler . 213123 . 31231 ``` I'm having quite a hard time trying to do that. Can someone help?
2017/09/07
[ "https://Stackoverflow.com/questions/46105620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5606352/" ]
You can just slice the dataframe into two: ``` In [20]: df1 = df[['city','state','person1','P1phone1','P1phone2']] In [21]: df2 = df[['city','state','person2','P2phone1','P2phone2']] ``` and then make sure they have the same columns: ``` In [27]: df1.columns = ['city','state','person','phone1','phone2'] In [28]: df2.columns = ['city','state','person','phone1','phone2'] ``` And then append one onto the other: ``` In [29]: df1.append(df2) Out[29]: city state person phone1 phone2 0 Ghut TY Jeff 32131 4324 1 Ffhs TY Ron 32131 4324 2 Tyuf TY Jeff 32131 4324 0 Ghut TY Bill 213123 31231 1 Ffhs TY Bill 213123 31231 2 Tyuf TY Tyler 213123 31231 ```
This is a typically `pd.wide_to_long` question Try this ``` df=df.rename(columns={'P1phone1':'phone1P1','P1phone2':'phone2P1','P2phone1':'phone1P2','P2phone2':'phone2P2'}) pd.wide_to_long(df,['person','phone1P','phone2P'],i=['id','city','state'],j='age').reset_index().drop('age',1) Out[364]: id city state person phone1P phone2P 0 1 Ghut TY Jeff 32131 4324 1 1 Ghut TY Bill 213123 31231 2 2 Ffhs TY Ron 32131 4324 3 2 Ffhs TY Bill 213123 31231 4 3 Tyuf TY Jeff 32131 4324 5 3 Tyuf TY Tyler 213123 31231 ```
68,194,716
I made a HTML email layout using table, the design is working fine in my machine but when I put the code to test in **putsmail** the footer moves to the left when I view the mail in the dekstop. It should come like this: [![enter image description here](https://i.stack.imgur.com/II3w8.jpg)](https://i.stack.imgur.com/II3w8.jpg) Its coming like this: [![enter image description here](https://i.stack.imgur.com/Orq6b.jpg)](https://i.stack.imgur.com/Orq6b.jpg) My HTML code: ``` <!--Footer--> <table class="footer"> <tr> <td style="padding: 50px;background-color: #f7f7f7"> <table width="100%"> <p style="text-align: center; font-size: 12px; line-height: 1.5;"> Having Trouble with something? <br> Reach out to us <a href="#">support@vantagecircle.com</a> </p> <img style="display: block; margin-right: auto;margin-left: auto; padding-bottom: 25px;" src="https://i.ibb.co/1Z05xTH/vc-footer-logo.png" width="120px" /> </table> </td> </tr> </table> ``` My CSS code: ``` .footer{ align-content: center; width: max-content; position: relative; } ``` Thank You in advance
2021/06/30
[ "https://Stackoverflow.com/questions/68194716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It’s safer to use inline CSS for email templates, I also don’t think any email clients supports the `align-content` property or even `max-content` on `width`. Maybe try it like this: ```html <table width="100%"> <tr width="100%"> <td style="padding: 50px;background-color:#f7f7f7"> <div style="margin-left:auto;margin-right:auto;"> <p style="text-align: center; font-size: 12px; line-height: 1.5;"> Having Trouble with something? <br> Reach out to us <a href="#">support@vantagecircle.com</a> </p> <img style="display: block; margin-right: auto;margin-left: auto; padding-bottom: 25px;" src="https://i.ibb.co/1Z05xTH/vc-footer-logo.png" width="120px" /> </div> </td> </tr> </table> ``` Note that I'm using `width` inline there, and added a `div` in the inner `td` to align to the center.
Use `width: 100%` for the table.
40,772,620
i need your help with some regex. I have a .csv file with fields separated with pipes and i want a regex that starts working from the n occurrence of that pipe and delete the element after including the next '|' . For Example, start from the third pipe: ``` elem1 | elem2 | elem3 | elem4 | elem5 | elem6 ^ ``` delete result: ``` elem1 | elem2 | elem3 | elem5 | elem6 ``` Hope you understand my problem. Thanks
2016/11/23
[ "https://Stackoverflow.com/questions/40772620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4350639/" ]
Below is the short working example with handling for 3 types of errors: 1) passed to `next()` handler, 2) throw-ed inside route handler, 3) unhandled error inside callback of some function called from route handler. (1) and (2) are captured using custom error middleware handler (A) and (3) is captured by `uncaughtException` handler (B). Express has own error handler which outputs error if it gets the control using the chain of `next()` calls (i.e. if there is no custom error handler or if it passes the control further using `next(err, req, res, next)`). That's why you still getting an error message in console even if youyr handler is not triggers. If you try to run the example for cases (1) and (2), you'll see the error outputs twice - by custom handler (A) and by default Express error handler. ``` 'use strict'; var express = require('express'); var app = express(); var server = app.listen(8080, function() { console.log('* Server listening at ' + server.address().address + ':' + server.address().port); }); // Example 1: Pass error in route handler to next() handler app.use('/1', function(req, res, next) { console.log('* route 1'); next(new Error('* route 1 error')); }); // Example 2: throw the error in route handler app.use('/2', function(req, res, next) { console.log('* route 2'); throw new Error('route 2 error'); }); // Example 3: unhandled error inside some callback function app.use('/3', function(req, res, next) { console.log('* route 3'); setTimeout(function(){ throw new Error('route 3 error'); }, 500); }); // Error handler A: Express Error middleware app.use(function(err, req, res, next) { console.log('**************************'); console.log('* [Error middleware]: err:', err); console.log('**************************'); next(err); }); // Error handler B: Node's uncaughtException handler process.on('uncaughtException', function (err) { console.log('**************************'); console.log('* [process.on(uncaughtException)]: err:', err); console.log('**************************'); }); ``` Node version: `v7.2.0` Typical error is to place error handlers before route definitions, but according to your description that's not the case. To locate the issue you can try to reduce your own code to same size as mine and I think, the problem will become obvious. --- UPDATE Moreover, if I try to run the code you provided (with trivial modifications), it works for me: ``` 'use strict'; var express = require('express'); var app = express(); var server = app.listen(8080, function() { console.log('* Server listening at ' + server.address().address + ':' + server.address().port); }); //process.on('uncaughtException', function (err: Error) { process.on('uncaughtException', function (err) { try { console.log('*** uncaughtException:', err); //mongoDal.log(err.message, err); } catch (err) { } }); //app.get('/test_feature', function (req: Request, res: Response) { app.get('/test_feature', function (req, res) { makeError(); res.send("Done"); }); function makeError(){ throw new Error("asdasdad"); } app.use(logErrors); //function logErrors (err: Error, req: Request, res: Response, next: NextFunction) { function logErrors (err, req, res, next) { console.log('*** logErrors:', err); //mongoDal.log(err.message, err); next(err); } ``` The result is (stack traces are truncated): ``` * Server listening at :::8080 *** logErrors: Error: asdasdad at makeError (/home/alykoshin/sync/al-projects/dev/nmotw/400-express-error-handling/main-stackoverflow.js:32:9) ........... Error: asdasdad at makeError (/home/alykoshin/sync/al-projects/dev/nmotw/400-express-error-handling/main-stackoverflow.js:32:9) ........... ``` You may see at the beginning the ouput of `logErrors` handler and then the output of default Express error handler.
I think the problem is on the routing definitions As you said you are using this ``` app.get('/test_feature', function (req, res) { throw new Error("asdasdad"); res.send("Done"); }); ``` Try using this: ``` app.get('/test_feature', function (req, res, next) { next(new Error("asdasdad")); }); ``` And then put res.send on the error handler... **Why?** I think throwing a Error inside the function stops the request chain... So it doesn't reach the very ending and then your error handler. If you write as the second way... you move the error forward ... and then reaches your handler...
975,995
I have this problem with Cocoa, I am calling a function and passing an Array to it: Some where I call the function: ``` [self processLabels:labels]; ``` And the function is as follow: ``` - (void)processLabels:(NSMutableArray*)labs{ labs = [[NSMutableArray alloc] init]; [labs addObject:@"Random"]; .... } ``` When debugging, I notice that no new object are being added to labels when they are added to labs. Is it because I am re-initializing labs? how could I re-initialize labels inside the function then? I tried using byref by didn't succeed, any help is appreciated.. thanks
2009/06/10
[ "https://Stackoverflow.com/questions/975995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
'labs' should be initialized before you pass it to processLabels, and then it shouldn't be re-initialized. If you can't initialize the array beforehand for whatever reason and you want processLabels to create it, you need to pass a pointer to a pointer: ``` [self processLabels:&labels]; ``` and the method would change to: ``` - (void)processLabels:(NSMutableArray**)labs{ *labs = [[NSMutableArray alloc] init]; [*labs addObject:@"Random"]; .... } ```
Will is correct, both about correcting the existing method, and about it being a bad idea. Storing back to a by-reference parameter is certainly valid, and it's used frequently in plain C programs, but in this case it adds needless complexity. In Objective-C, the preferred idiom is to return objects using the return value first, and only store back to a pointer if the return value is already being used to return something else. Not only will this make calls to a method easier to read and write, but it conforms to standard idioms that are commonly used in other languages (such as Java and C#). It becomes quite obvious if you overwrite an array pointer by assigning to it, a potential bug that is more likely to be picked up by tools like the [Clang Static Analyzer](http://clang-analyzer.llvm.org/). On a related note, you should probably also consider better method and parameter naming. (I realize this is likely a somewhat contrived example.) If you're processing "labels", and they come from some source other than the mutable array you're creating, I wouldn't name the local variable "labs" or "labels" — use a more descriptive name. Method names that are less vague about what they do can vastly improve code readability. In Objective-C, long descriptive method names are preferred. Since Xcode does code completion and the method names are less ambiguous, the end result is usually *less* typing.
18,984
What are your opinions on developing for the command line first, then adding a GUI on after the fact by simply calling the command line methods? eg. > > W:\ todo AddTask "meeting with John, re: login peer review" "John's office" "2008-08-22" "14:00" > > > loads `todo.exe` and calls a function called `AddTask` that does some validation and throws the meeting in a database. Eventually you add in a screen for this: ``` ============================================================ Event: [meeting with John, re: login peer review] Location: [John's office] Date: [Fri. Aug. 22, 2008] Time: [ 2:00 PM] [Clear] [Submit] ============================================================ ``` When you click submit, it calls the same AddTask function. Is this considered: * a good way to code * just for the newbies * horrendous!. **Addendum:** I'm noticing a trend here for "shared library called by both the GUI and CLI executables." Is there some compelling reason why they would have to be separated, other than maybe the size of the binaries themselves? Why not just call the same executable in different ways: * `"todo /G"` when you want the full-on graphical interface * `"todo /I"` for an interactive prompt *within* `todo.exe` (scripting, etc) * plain old `"todo <function>"` when you just want to do one thing and be done with it. **Addendum 2:** It was mentioned that "the way [I've] described things, you [would] need to spawn an executable every time the GUI needs to do something." Again, this wasn't my intent. When I mentioned that the example GUI called "the same `AddTask` function," I didn't mean the GUI called the command line program each time. I agree that would be totally nasty. I had intended (see first addendum) that this all be held in a single executable, since it was a tiny example, but I don't think my phrasing necessarily precluded a shared library. Also, I'd like to thank all of you for your input. This is something that keeps popping back in my mind and I appreciate the wisdom of your experience.
2008/08/20
[ "https://Stackoverflow.com/questions/18984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1588/" ]
If you do your development right, then it should be relatively easy to switch to a GUI later on in the project. The problem is that it's kinda difficult to get it right.
In addition to what [Stu](https://stackoverflow.com/questions/18984/what-do-you-think-of-developing-for-the-command-line-first#18990) said, having a shared library will allow you to use it from web applications as well. Or even from an IDE plugin.
16,214,133
Is it ever best practise or recommended to use a table of the following? ``` id, uid, fieldname, fieldvalue 4, 12, gender, male 5, 12, age, 21-30 6, 12, location, 5 7, 13, gender, female 8, 13, age, 31-40 9, 13, location, 5 10, 14, gender, female 11, 14, age, 31-40 12, 14, location, 6 13, 15, gender, male 14, 15, age, 21-30 15, 15, location, 7 ``` It is not normalised and you cannot specify the data type of the field. Would the following not be better ``` id, uid, gender, age, location 4, 12, male, 21-30, 5 5, 13, female, 31-40, 5 6, 14, female, 31-40, 6 7, 15, male, 21-30, 7 ``` I want to know if you can ever justify having such a table in a database, I know that the first method may be easier to add more fields (instead of altering the database) and will probably remove all null values. However one cannot specify the datatype and you will have to convert from string every time you want to use the data. So is there ever a scenario where the first table is considered the best practice or solution?
2013/04/25
[ "https://Stackoverflow.com/questions/16214133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2118666/" ]
Thanks for the very thorough answers above! None of the responses, quite did what I was looking for though. I followed up on DarkOtter's suggestion in the comment the question, and used `unsafeCoerce` avoid the type checker. The basic idea is that we create a GADT that packages up Haskell functions with their types; the type system I use follows pretty closely Mark P. Jones' ["Typing Haskell in Haskell."](http://web.cecs.pdx.edu/~mpj/thih/) Whenever I want a collection of Haskell functions, I first coerce them into `Any` types, then I do what I need to do, stitching them together randomly. When I go to evaluate the new functions, first I coerce them back to the type I wanted. Of course, this isn't safe; if my type checker is wrong or I annotate the haskell functions with incorrect types, then I end up with nonsense. I've pasted the code I tested this with below. Note that there are two local modules being imported `Strappy.Type` and `Strappy.Utils`. The first is the type system mentioned above. The second brings in helpers for the stochastic programs. Note: in the code below I'm using the combinatory logic as the basic language. That's why my expression language only has application and no variables or lambda abstraction. ``` {-# Language GADTs, ScopedTypeVariables #-} import Prelude hiding (flip) import qualified Data.List as List import Unsafe.Coerce (unsafeCoerce) import GHC.Prim import Control.Monad import Control.Monad.State import Control.Monad.Trans import Control.Monad.Identity import Control.Monad.Random import Strappy.Type import Strappy.Utils (flip) -- | Helper for turning a Haskell type to Any. mkAny :: a -> Any mkAny x = unsafeCoerce x -- | Main data type. Holds primitive functions (Term), their -- application (App) and annotations. data Expr a where Term :: {eName :: String, eType :: Type, eThing :: a} -> Expr a App :: {eLeft :: (Expr (b -> a)), eRight :: (Expr b), eType :: Type} -> Expr a -- | smart constructor for applications a <> b = App a b (fst . runIdentity . runTI $ typeOfApp a b) instance Show (Expr a) where show Term{eName=s} = s show App{eLeft=el, eRight=er} = "(" ++ show el ++ " " ++ show er ++ ")" -- | Return the resulting type of an application. Run's type -- unification. typeOfApp :: Monad m => Expr a -> Expr b -> TypeInference m Type typeOfApp e_left e_right = do t <- newTVar Star case mgu (eType e_left) (eType e_right ->- t) of (Just sub) -> return $ toType (apply sub (eType e_left)) Nothing -> error $ "typeOfApp: cannot unify " ++ show e_left ++ ":: " ++ show (eType e_left) ++ " with " ++ show e_right ++ ":: " ++ show (eType e_right ->- t) eval :: Expr a -> a eval Term{eThing=f} = f eval App{eLeft=el, eRight=er} = (eval el) (eval er) filterExprsByType :: [Any] -> Type -> TypeInference [] Any filterExprsByType (e:es) t = do et <- freshInst (eType (unsafeCoerce e :: Expr a)) let e' = unsafeCoerce e :: Expr a case mgu et t of Just sub -> do let eOut = unsafeCoerce e'{eType = apply sub et} :: Any return eOut `mplus` rest Nothing -> rest where rest = filterExprsByType es t filterExprsByType [] t = lift [] ---------------------------------------------------------------------- -- Library of functions data Library = Library { probOfApp :: Double, -- ^ probability of an expansion libFunctions :: [Any] } cInt2Expr :: Int -> Expr Int -- | Convert numbers to expressions. cInt2Expr i = Term (show i) tInt i -- Some basic library entires. t = mkTVar 0 t1 = mkTVar 1 t2 = mkTVar 2 t3 = mkTVar 3 cI = Term "I" (t ->- t) id cS = Term "S" (((t2 ->- t1 ->- t) ->- (t2 ->- t1) ->- t2 ->- t)) $ \f g x -> (f x) (g x) cB = Term "B" ((t1 ->- t) ->- (t2 ->- t1) ->- t2 ->- t) $ \f g x -> f (g x) cC = Term "C" ((t2 ->- t1 ->- t2 ->- t) ->- t1 ->- t2 ->- t) $ \f g x -> (f x) g x cTimes :: Expr (Int -> Int -> Int) cTimes = Term "*" (tInt ->- tInt ->- tInt) (*) cPlus :: Expr (Int -> Int -> Int) cPlus = Term "+" (tInt ->- tInt ->- tInt) (+) cCons = Term ":" (t ->- TAp tList t ->- TAp tList t) (:) cAppend = Term "++" (TAp tList t ->- TAp tList t ->- TAp tList t) (++) cHead = Term "head" (TAp tList t ->- t) head cMap = Term "map" ((t ->- t1) ->- TAp tList t ->- TAp tList t1) map cEmpty = Term "[]" (TAp tList t) [] cSingle = Term "single" (t ->- TAp tList t) $ \x -> [x] cRep = Term "rep" (tInt ->- t ->- TAp tList t) $ \n x -> take n (repeat x) cFoldl = Term "foldl" ((t ->- t1 ->- t) ->- t ->- (TAp tList t1) ->- t) $ List.foldl' cNums = [cInt2Expr i | i <- [1..10]] -- A basic library exprs :: [Any] exprs = [mkAny cI, mkAny cS, mkAny cB, mkAny cC, mkAny cTimes, mkAny cCons, mkAny cEmpty, mkAny cAppend, -- mkAny cHead, mkAny cMap, mkAny cFoldl, mkAny cSingle, mkAny cRep ] ++ map mkAny cNums library = Library 0.3 exprs -- | Initializing a TypeInference monad with a Library. We need to -- grab all type variables in the library and make sure that the type -- variable counter in the state of the TypeInference monad is greater -- that that counter. initializeTI :: Monad m => Library -> TypeInference m () initializeTI Library{libFunctions=es} = do put (i + 1) return () where go n (expr:rest) = let tvs = getTVars (unsafeCoerce expr :: Expr a) getTVars expr = tv . eType $ expr m = maximum $ map (readId . tyVarId) tvs in if null tvs then 0 else go (max n m) rest go n [] = n i = go 0 es ---------------------------------------------------------------------- ---------------------------------------------------------------------- -- Main functions. sampleFromExprs :: (MonadPlus m, MonadRandom m) => Library -> Type -> TypeInference m (Expr a) -- | Samples a combinator of type t from a stochastic grammar G. sampleFromExprs lib@Library{probOfApp=prApp, libFunctions=exprs} tp = do initializeTI lib tp' <- freshInst tp sample tp' where sample tp = do shouldExpand <- flip prApp case shouldExpand of True -> do t <- newTVar Star (e_left :: Expr (b -> a)) <- unsafeCoerce $ sample (t ->- tp) (e_right :: Expr b) <- unsafeCoerce $ sample (fromType (eType e_left)) return $ e_left <> e_right -- return application False -> do let cs = map fst . runTI $ filterExprsByType exprs tp guard (not . null $ cs) i <- getRandomR (0, length cs - 1) return $ unsafeCoerce (cs !! i) ---------------------------------------------------------------------- ---------------------------------------------------------------------- main = replicateM 100 $ do let out = runTI $ do sampleFromExprs library (TAp tList tInt) x <- catch (liftM (Just . fst) out) (\_ -> putStrLn "error" >> return Nothing) case x of Just y -> putStrLn $ show x ++ " " ++ show (unsafeCoerce (eval y) :: [Int]) Nothing -> putStrLn "" ```
Would something along these lines meet your needs? ``` import Control.Monad.Random randomFunction :: (RandomGen r, Random a, Num a, Floating a) => Rand r (a -> a) randomFunction = do (a:b:c:d:_) <- getRandoms fromList [(\x -> a + b*x, 1), (\x -> a - c*x, 1), (\x -> sin (a*x), 1)] -- Add more functions as needed main = do let f = evalRand randomFunction (mkStdGen 1) :: Double -> Double putStrLn . show $ f 7.3 ``` --- **EDIT:** Building on that idea, we could incorporate functions that have different numbers and types of parameters... as long as we partially apply them so that they all have the same result type. ``` import Control.Monad.Random type Value = (Int, Double, String) -- add more as needed type Function = Value -> String -- or whatever the result type is f1 :: Int -> Int -> (Int, a, b) -> Int f1 a b (x, _, _) = a*x + b f2 :: String -> (a, b, String) -> String f2 s (_, _, t) = s ++ t f3 :: Double -> (a, Double, b) -> Double f3 a (_, x, _) = sin (a*x) randomFunction :: RandomGen r => Rand r Function randomFunction = do (a:b:c:d:_) <- getRandoms -- some integers (w:x:y:z:_) <- getRandoms -- some floats n <- getRandomR (0,100) cs <- getRandoms -- some characters let s = take n cs fromList [(show . f1 a b, 1), (show . f2 s, 1), (show . f3 w, 1)] -- Add more functions as needed main = do f <- evalRandIO randomFunction :: IO Function g <- evalRandIO randomFunction :: IO Function h <- evalRandIO randomFunction :: IO Function putStrLn . show $ f (3, 7.3, "hello") putStrLn . show $ g (3, 7.3, "hello") putStrLn . show $ h (3, 7.3, "hello") ```
40,712,574
I have 2 dataframes `df_1` and `df_2`. Both have an index `datetimecode`which is a `pd.datetime64` object, and a `temp` column. I want to iterate through `df_1` and replace all the NaN temperature values with the corresponding temp from `'df_2'`. Something like this: ``` for index, row in df_1.iterows(): row['temp'] = df_2[index]['temp'] if row['temp'] ==np.nan ``` but this is invalid sytax
2016/11/21
[ "https://Stackoverflow.com/questions/40712574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6567949/" ]
This will give you the file name and full name. The difference is full name includes the complete path and name is just the file name. ``` Get-ChildItem c:\users\somefolder -Recurse -filter "*.pem" | foreach{ $name = $_.Name $fullName = $_.FullName Write-Output $name Write-Output $fullName } ``` If you run this you will understand. So you can get the name like this and then run any other command inside the foreach loop with the $name variable.
try Something like this ``` $msbuild = "C:\pathofexefile\WinSCP.com" $formatstring="/keygen {0} /output={1}.ppk" Set-Location "c:\temp" gci -file -Filter "*.txt" | %{$arguments=($formatstring -f $_.FullName, $_.BaseName);start-process $msbuild $arguments } ```
3,641,737
can I get description of an exception caught by ``` catch(...) ``` block? something like **.what()** of std::exception.
2010/09/04
[ "https://Stackoverflow.com/questions/3641737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/395573/" ]
If you know you only throw std::exception or subclasses, try ``` catch(std::exception& e) {...e.what()... } ``` Otherwise, as DeadMG wrote, since you can throw (almost) everything, you cannot assume anything about what you caught. Normally catch(...) should only be used as the last defense when using badly written or documented external libraries. So you would use an hierarchy ``` catch(my::specialException& e) { // I know what happened and can handle it ... handle special case } catch(my::otherSpecialException& e) { // I know what happened and can handle it ... handle other special case } catch(std::exception& e) { //I can at least do something with it logger.out(e.what()); } catch(...) { // something happened that should not have logger.out("oops"); } ```
Quoting [bobah](https://stackoverflow.com/questions/315948/c-catching-all-exceptions) ``` #include <iostream> #include <exception> #include <typeinfo> #include <stdexcept> int main() { try { throw ...; // throw something } catch(...) { std::exception_ptr p = std::current_exception(); std::clog <<(p ? p.__cxa_exception_type()->name() : "null") << std::endl; } return 1; } ```
43,793,622
How can I remove this square from tooltip? [![enter image description here](https://i.stack.imgur.com/whK6l.jpg)](https://i.stack.imgur.com/whK6l.jpg) I would prefer if I could manage to just have it one line like this: February - 2 ``` var data = { labels: ['January', 'February', 'March'], datasets: [ { data: [1,2,3] } ] }; var myLineChart = new Chart(document.getElementById('chart'), { type: 'line', data: data, options: { legend: { display: false } } }); ```
2017/05/04
[ "https://Stackoverflow.com/questions/43793622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2769517/" ]
Add this in your `options` object ``` tooltips: { displayColors: false } ``` **Update for version 3 or greater** (from @hanumanDev below): Remove 's' from tooltips ``` tooltip: { displayColors: false } ```
In version 3.8.0 of the chart.js plugin the tooltip config needs to go in the plugins config object, like this: ```js options: { plugins: { tooltip: { displayColors: false } } } ```
12,438
I have the following issue with accent insensitive search in Czech language. My database is set to `Czech_CI_AI` collation. For some diacritics system works correctly (ie. `I`), but for some does not (ie. `R`). In my database there are several `'DVORA*'` records: ``` SELECT contact_name FROM CONTCTSM1 WHERE CONTACT_NAME LIKE 'DVO%' ``` Results: > > DVOŘÁČKOVÁ, > > IVETA DVOŘÁČKOVÁ, > > JIŘINA DVOŘÁK > > >
2012/02/08
[ "https://dba.stackexchange.com/questions/12438", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/2899/" ]
R and Ř are different letters, as opposed to modified base letters(?) like German umlauts with ö vs o From [Czech language on Wikipedia](http://en.wikipedia.org/wiki/Czech_alphabet) (my bold) > > The acute accent (čárka) letters (Á, É, Í, Ó, Ú, Ý) and the kroužek letter Ů all indicate long vowels. They have the **same** alphabetical ordering as their non-diacritic counterparts. ...The háček (ˇ) indicates historical palatalization of the base letter. The letters Č, Ř, Š, and Ž currently represent postalveolar consonants and are ordered **behind** their corresponding base letters; while Ď, Ň, Ť represent palatal consonants and have the same alphabetical ordering as their non-diacritic counterparts. > > > A test with Ö and O in Swedish (different letters) and German (modified) ``` SELECT 'Finnish_Swedish_100_CI_AI' WHERE N'Ö' COLLATE Finnish_Swedish_100_CI_AI = N'O' UNION ALL SELECT 'Latin1_General_CI_AI' WHERE N'Ö' COLLATE Latin1_General_CI_AI = N'O' ```
SQL collation seems not very useful accent insensitive search. The best solution seems to be to convert the string to varchar with collation SQL\_Latin1\_General\_CP1251\_CI\_AS. Either as a persistent column holding varchar value with the 1251 collation or cast the value directly in query (if you don't care that it will go through whole table since there won't be an index). ``` WHERE (cast([name] as varchar(255))) COLLATE SQL_Latin1_General_CP1251_CI_AS like (cast(N'dvoř%' as varchar(255))) COLLATE SQL_Latin1_General_CP1251_CI_AS ```
69,299,586
I suddenly get this error and not sure why.I did not change the `"react-router-dom": "^6.0.0-beta.4"` version. But the `"react-dom": "^16.8.4"`" had changed to `"react-dom": "^16.13.1"`, Dunno if that had anything to do with I don't know but the `useRoutes` comes from `"react-router-dom"` and that's where the error originate ya. Anyone have a clue? [![enter image description here](https://i.stack.imgur.com/Lk2gb.png)](https://i.stack.imgur.com/Lk2gb.png) Here is my App.jsx where i use the `useRoutes(routes)` and it's giving me the error: ``` import React, { useEffect } from 'react'; import { AnimatePresence } from 'framer-motion'; import { connect } from 'react-redux'; import { compose } from 'recompose'; import { useRoutes } from 'react-router-dom'; import { ThemeContextProvider } from './theme/ThemeProvider'; import { getAlbumData } from './redux/albumData/albumData.actions'; import { getMetaData } from './redux/albumMetaData/albumMetaData.actions'; import { startTagsListener, startTagsCategoryListener, } from './redux/global/global.actions';1111 import { withAuthentication } from './session'; import './styles/index.css'; import routes from './routes'; require('react-dom'); const AnimatedSwitch = () => { const routing = useRoutes(routes); return ( <AnimatePresence exitBeforeEnter initial={false}> <div>{routing}</div> </AnimatePresence> ); }; const App = props => { const { getMeta, getAlbum, startTagListener, startTagCategoryListener } = props; useEffect(() => { getMeta(); getAlbum(); startTagListener(); startTagCategoryListener(); }, [getMeta, getAlbum, startTagListener, startTagCategoryListener]); return ( <ThemeContextProvider> {AnimatedSwitch()} </ThemeContextProvider> ); }; const mapDispatchToProps = dispatch => ({ getMeta: () => dispatch(getMetaData()), getAlbum: () => dispatch(getAlbumData()), startTagListener: () => dispatch(startTagsListener()), startTagCategoryListener: () => dispatch(startTagsCategoryListener()), }); export default compose(connect(null, mapDispatchToProps), withAuthentication)(App); ``` Here are the routes and I have not changed them in the last month: ``` import React from 'react'; import ContentLayout from './components/structure/ContentLayout'; import DashboardLayout from './components/DashboardLayout'; import AccountView from './components/DashboardLayout/views/account/AccountView'; import SearchListView from './components/DashboardLayout/views/search/SearchListView'; import DashboardView from './components/DashboardLayout/views/dashboard/DashboardView'; import NotFoundView from './components/DashboardLayout/views/errors/NotFoundView'; import CreateContentView from './components/DashboardLayout/views/creator/CreateContentView'; import SettingsView from './components/DashboardLayout/views/settings/SettingsView'; import LoginView from './components/DashboardLayout/views/auth/LoginView'; import RegisterView from './components/DashboardLayout/views/auth/RegisterView'; import SubmissionsView from './components/DashboardLayout/views/submissions/SubmissionsView'; import InboxView from './components/DashboardLayout/views/inbox/InboxView'; const routes = [ { path: 'app', element: <DashboardLayout />, children: [ { path: 'account', element: <AccountView /> }, { path: 'search', element: <SearchListView /> }, { path: 'dashboard', element: <DashboardView /> }, { path: 'create', element: <CreateContentView /> }, { path: 'submissions', element: <SubmissionsView /> }, { path: 'inbox', element: <InboxView /> }, { path: 'settings', element: <SettingsView /> }, { path: 'login', element: <LoginView /> }, { path: 'register', element: <RegisterView /> }, { path: '*', element: <NotFoundView /> }, { path: '/', element: <DashboardView /> }, ], }, { path: '/', element: <ContentLayout />, children: [ { path: '404', element: <NotFoundView /> }, { path: '*', element: <NotFoundView /> }, ], }, ]; export default routes; ```
2021/09/23
[ "https://Stackoverflow.com/questions/69299586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11749004/" ]
I have had a similar issue with material kit ui, and i fixed it simply just write `path:""`. leaving the path empty will fix the problem
In the case you are nesting `Routes`, one workaround is to group them together: From ``` <BrowserRouter> <Routes> <Route path="/" element={<LandingPage />} /> <Route path="products" element={<Foo/>} <Route path="/" element={<Bar/>}/> <Route path=":id" element={<FooBar/>}/> </Route> </Routes> </BrowserRouter> ``` To ``` <BrowserRouter> <Routes> <Route path="/" element={<LandingPage />} /> <Route path="products/:id" element={<Product />}/> </Routes> </BrowserRouter> ```
61,441
Suppose S is a genus g surface with n punctures satisfying the hyperbolicity condition 2g + n - 2 > 0. If n > 0 the fundamental group of the surface is a free group on 2g + n - 1 := m generators. If we look the universal covers of different punctured surfaces with the same m (e.g., thrice-punctured sphere and once-punctured torus for m = 2) in, say the hyperbolic plane or the Poincare disc model, how do they differ? The "only" apparent difference is in the number of punctures which should give rise to a difference in the lifts of the punctures to the boundary of the disc. The fundamental groups are isomorphic, but they must act differently to produce quotient surfaces of different genera. How? How does the set of lifts of punctures on the boundary relate to the standard Farey set? Thanks a lot in advance!
2011/04/12
[ "https://mathoverflow.net/questions/61441", "https://mathoverflow.net", "https://mathoverflow.net/users/14314/" ]
For the thrice-punctured sphere, there is a generating set where both generators are parabolic. For the once-punctured torus only the commutator (and its conjugates) is parabolic. Hence any element that can be part of a generating set is hyperbolic. Thinking in the upper half-plane model of $\mathbb H$, the Farey set is the rational points of the real line (plus the point at infinity). If $X$ is a punctured hyperbolic surface then the lifts of the ideal points of $X$ likewise form a dense set in the real line. If $X$ is a thrice-punctured sphere then, after possibly conjugating the deck group by an isometry of $\mathbb H$ the lifts of the punctures are the Farey set. However, for any other surface $X$ this only happens if the *modulus* of $X$ is carefully chosen.
I strongly recommend you look at: MR0795536 (86j:11069) Series, Caroline(F-IHES) The geometry of Markoff numbers. Math. Intelligencer 7 (1985), no. 3, 20–29. 11J06 (11J13 11J70)
490,387
I've been using TortoiseSVN with Subversion for a while now. Its pretty easy to use and most of the time I just use the Update and Commit functions....and occasionally if I need to track down the author of a particular line of code I use Blame or Show Log. Recently though, I made the mistake of directly copying folders and files from a different branch into the one I was working in...and on checking it in found that it broke things because it checked it in as coming from the branch I had copied them from. At that point I found out that what needs to be done is to use the commands made available by TortoiseSVN to copy and export the folders across so their references remain correct. So it's left me wondering....What other power commands exist that are important for a developer using Subversion to know that help you from breaking things or reduce the amount of effort of performing various version control tasks?
2009/01/29
[ "https://Stackoverflow.com/questions/490387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
* [the most forgotten feature](http://tortoisesvn.net/most-forgotten-feature) (right-drag) * [unversion a working copy](http://tortoisesvn.net/unversion.html) * [extended context menu](http://tortoisesvn.net/extendedcontextmenu.html) * [repair moves/renames](http://tortoisesvn.net/repairmoves.html)
I've found the [export](http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-cli-main.html#tsvn-cli-export) command to be invaluable several times. It gives you a clean (no .svn directories) copy of whatever directory you want.
37,547,951
I'm trying to increment my counter every time but when the html is clicked the counter grows exponentially like +1, +2, +3, +4. ![Gif of it happening](https://dl.dropboxusercontent.com/s/tyiw0e1lhrrcb60/E559DFA9-EE89-4B7F-A2DF-2C6A5F99DAFB-78418-000239B4942AD234.gif?dl=0) ``` $('.dates').click(function(){ $('#output').html(function(i, val) { return val*1+1 }); }); ``` HTML: ``` <div id="output">0</div> ``` Heart Animation Code: ``` var rand = Math.floor(Math.random() * 100 + 1); var flows = ["flowOne", "flowTwo", "flowThree"]; var colors = ["colOne", "colTwo", "colThree", "colFour", "colFive", "colSix"]; var timing = (Math.random() * (1.3 - 0.3) + 1.6).toFixed(1); // Animate Particle $('<div class="particle part-' + rand + ' ' + colors[Math.floor(Math.random() * 6)] + '" style="font-size:' + Math.floor(Math.random() * (30 - 22) + 22) + 'px;"><i class="fa fa-heart-o"></i><i class="fa fa-heart"></i></div>').appendTo('.particle-box').css({ animation: "" + flows[Math.floor(Math.random() * 3)] + " " + timing + "s linear" }); $('.part-' + rand).show(); // Remove Particle setTimeout(function () { $('.part-' + rand).remove(); }, timing * 1000 - 100); ``` 1. Why is it incrementing exponentially? 2. How do I make it increment by 1 every time? Like 0, 1, 2, 3, 4
2016/05/31
[ "https://Stackoverflow.com/questions/37547951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4256605/" ]
Most likely, you are registering a new click event listener every time you click. Please check and post the code that surrounds the line `$('.dates').click(...)`. Make sure this line is called only once in your code, and not again later.
May be it is considering it as string. Use `parseInt` to parse the value as an integer instead of using String Concatenation: ``` $('.dates').click(function() { $('#output').html(function(i, val) { return parseInt(val, 10) + 1; }); }); ``` Working snippet: ```js $('.dates').click(function() { $('#output').html(function(i, val) { return parseInt(val, 10) + 1; }); return false; }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" class="dates">Click</a> <div id="output">0</div> ```
19,187,457
Please look at the following: <http://jsfiddle.net/ran5000/uZ7dD/> the `header` div has a fixed height of 40px, I want that the `content` div will use the remaining height of the screen without scroll and regardless of the screen height. any ideas?
2013/10/04
[ "https://Stackoverflow.com/questions/19187457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/553823/" ]
I generally use `position:absolute` for this, and then set the top value to start at the bottom of the header. <http://jsfiddle.net/uZ7dD/4/> ``` .content { background-color: yellow; position:absolute; top:40px; bottom:0; left:0; right:0; } ```
For css3 browsers just use: ``` .content { width: 100%; background-color: yellow; height: -moz-calc(100% - 40px); height: -webkit-calc(100% - 40px); height: -o-calc(100% - 40px); height: calc(100% - 40px); } ``` for non-css3 browsers use this workaround, HTML: ``` <div class="container"> <div class="header">i am the header</div>i am the <content></content> </div> ``` CSS ``` .header { width: 100%; height 40px; line-height: 40px; background-color: blue; } .container{ height: 100%; background-color: yellow; } ``` Hope I could help :)
37,319,736
I have the below hibernate native query as shown below the idea is not to use the native query and switch to hibernate criteria api ``` <![CDATA[select count(iilnmp.INV_LINE_NOTE_ID) from IOA_INV_LINE_NOTE_MAP iilnmp , IOA_INVOICE_LINE_NOTES iiln , IOA_INVOICE_LINE iil where iilnmp.INV_LINE_NOTE_ID = iiln.ID and iiln.INLI_ID =iil.id and iil.ID = ?]]> ``` which i am calling from a method as shown below now my query is that instead of having native query can i use criteria also to achieve the same result ``` public int findAttachementsCount(long id) { Query query = session.getNamedQuery("attachmentQuery"); query.setParameter(0, id); int attachCount = query.list().size(); return attachCount; } ``` Folks please advise for this. Can somebody please look this into priority..!!
2016/05/19
[ "https://Stackoverflow.com/questions/37319736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6355442/" ]
Try stopping the gradle daemon with `./gradlew --stop` I had the same problem with something as simple as: ``` commandLine = [ "node", "--version"] ``` It came down to the gradle daemon having a cached location of node which no longer existed (I had updated node sometime before).
My gradle file contained a snippet to get the aws auth token and I was getting the same failure - `Caused by: java.io.IOException: error=2, No such file or directory` In my case, the issue was not caused due to caching. It was due to gradle not being able to find the aws binary. What worked for me - Use the `which aws` command to find the absolute path to aws binary and use it for the binary as shown below. Hope this helps someone with similar issue. [![enter image description here](https://i.stack.imgur.com/AKxKg.png)](https://i.stack.imgur.com/AKxKg.png)
29,761,871
I am working with an existing application that I would like to add angular to. The application is using a custom proprietary SPA framework + dojo. The application is built with mainly dojo modules and heavily utilizes AMD modules. I have imported angular in the head with ``` <script type="text/javascript" src="lib/angular/angular.js"></script> ``` I have also added ``` <html ng-app="myApp"> <script> angular.module('myApp', []) </script> ``` to my index.html. I have also tried manually bootstrapping via ``` var app = angular.module('myApp', []); angular.element(document).ready(function() { angular.bootstrap(document, ['myApp']); }); ``` but still ``` {{1+1}} ``` Does not evaluate. It remains as {{1+1}} The only way I get get it to (sort of) work is in my partial view (rendered inside body of index.html) and I manually bootstrap the application via ``` var app = angular.module('myApp', []); angular.element(document).ready(function() { angular.bootstrap(document, ['myApp']); }); ``` But as soon as I leave the page and come back, the bootstrapping is gone. {{1+1}} shows as {{1+1}} not 2. If I run the above code again, I get an error saying document is already bootstrapped. No errors are thrown in console.. I am not sure what to try next. Any help? Thanks
2015/04/21
[ "https://Stackoverflow.com/questions/29761871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2141336/" ]
Update this css class or override it to: ``` .bootstrap-switch.bootstrap-switch-focused { outline: none; box-shadow: none; } ```
css: ``` .bootstrap-switch:focus { outline: none; } ```
4,105,042
im a newbie here and would like some advice on C# programming i would like to store values from a textbox into a database. so far, i have the following: ``` string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Customers.mdf;Integrated Security=True;User Instance=True"; SqlConnection connection = new SqlConnection(connectionString); connection.Open(); string query = "INSERT INTO ProjectList (ProjectName, BiddingDueDate, Status, ProjectStartDate, ProjectEndDate, AssignedTo, PointsWorth, StaffCredits) VALUES ('"+projName+"', '"+bidDueDate+"', '"+status+"', '"+projectStartDate+"', '"+projectEndDate+"', '"+assignedTo+"', '"+pointsWorth+"', '"+aStaffCredits+"')"; SqlCommand command = new SqlCommand(query, connection); command.ExecuteNonQuery(); connection.Close(); ``` There are no errors in the code, but i cannot seem to figure out why nothing is being stored in the database.
2010/11/05
[ "https://Stackoverflow.com/questions/4105042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/498209/" ]
Do you have 'Copy to Output Directory' property set to 'Copy Always' for the database file? Because this would overwrite your database file everytime you build.
if your **ProjectStartDate** and dates in general are datetime values in the DB, then you will get an error when inserting data with the '. It should be like: ``` String thisQuery = "INSERT INTO ProjectList (ProjectName, BiddingDueDate, Status, ProjectStartDate, ProjectEndDate, AssignedTo, PointsWorth, StaffCredits) VALUES ('"+projName+"', "+bidDueDate+", '"+status+"', "+projectStartDate+", "+projectEndDate+", '"+assignedTo+"', '"+pointsWorth+"', '"+aStaffCredits+"')"; ```
44,625,081
I want to create update procedure and I get the following error; Msg 102, Level 15, State 1, Procedure sp\_name, Line 30 [Batch Start Line 9] Incorrect syntax near 'update '. How can write proper procedure please help me? I can not solve the problem My procedure as follows; ``` @tablo nvarchar(100), @kayit nvarchar(50), @inceleme nvarchar(50), @icevap nvarchar(50), @tespit nvarchar(MAX), @scevap nvarchar(MAX), @aksiyon nvarchar(50), @mutalaa nvarchar(MAX), @tamamlanma nvarchar(100), @not nvarchar(MAX), @izleme nvarchar(50), @kaydeden nvarchar(50), @idd int, @kullanici nvarchar(50), @yil int, @donem int as DECLARE @sql as varchar(max) SET @sql = 'select ID into #a from ' + @tablo + ' where yil='+ cast(@yil as varchar(100)) +' and donem='+ cast(@donem as varchar(100)) +' and (ilkkaydeden is null or ilkkaydeden='') and (kull='+ cast(@kullanici as varchar(100)) +' or kull1='+ cast(@kullanici as varchar(100)) +' or kull2='+ cast(@kullanici as varchar(100)) +')' exec(@sql) IF EXISTS(SELECT * FROM #a WHERE ID=@idd) BEGIN 'update '+@tablo+' set kayitzamani='+@kayit+', incelendimi='+@inceleme+', cevap='+@icevap+', ites='+@tespit+', icevabi='+@scevap+', iaksiyon='+@aksiyon+', ison='+@mutalaa+', ieksiklik='+@tamamlanma+', inotlar='+@not+', izleme='+@izleme+', ilkkaydeden='+@kaydeden+' where ID='+@idd END ELSE BEGIN 'update '+@tablo+' set kayitzamani='+@kayit+', incelendimi='+@inceleme+', cevap='+@icevap+', ites='+@tespit+', icevabi='+@scevap+', iaksiyon='+@aksiyon+', ison='+@mutalaa+', ieksiklik='+@tamamlanma+', inotlar='+@not+', izleme='+@izleme+', sonkaydeden='+@kaydeden+' where ID='+@idd END; go ```
2017/06/19
[ "https://Stackoverflow.com/questions/44625081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
you can leave it blank but imho It's better this: ``` if(!in_array($productName, array_keys($_SESSION["cart_item"]))) { $_SESSION['cart_item'] = array_merge($_SESSION['cart_item'],$itemArray); } ``` You can add `!` to specifiy a `NOT` operation so you can delete else condition and you don't need to leave an `if` statement blank
If you have blank code block after `IF`, then simply use negation `!`. ``` if (!in_array($productName, array_keys($_SESSION["cart_item"]))) { ``` Then code should be more easily to read by other developers.
40,772,620
i need your help with some regex. I have a .csv file with fields separated with pipes and i want a regex that starts working from the n occurrence of that pipe and delete the element after including the next '|' . For Example, start from the third pipe: ``` elem1 | elem2 | elem3 | elem4 | elem5 | elem6 ^ ``` delete result: ``` elem1 | elem2 | elem3 | elem5 | elem6 ``` Hope you understand my problem. Thanks
2016/11/23
[ "https://Stackoverflow.com/questions/40772620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4350639/" ]
Note: your error handler middleware MUST have 4 parameters: error, req, res, next. Otherwise your handler won't fire. I was fighting this problem until I've discovered this.
I think the problem is on the routing definitions As you said you are using this ``` app.get('/test_feature', function (req, res) { throw new Error("asdasdad"); res.send("Done"); }); ``` Try using this: ``` app.get('/test_feature', function (req, res, next) { next(new Error("asdasdad")); }); ``` And then put res.send on the error handler... **Why?** I think throwing a Error inside the function stops the request chain... So it doesn't reach the very ending and then your error handler. If you write as the second way... you move the error forward ... and then reaches your handler...
57,574,910
So I am working on a simple CRUD. I organize my form in a separate page view so I can just insert it on my create and edit views. Here's how my field view: ``` <div class="form-group row"> <label class="col-sm-2 col-form-label"for="room_id">Room</label> <div class="col-sm-10"> <select name="room_id" class="form-control" id="room_id" required> @foreach($rooms as $id => $display) <option value="{{ $id }}" {{ (isset($booking->room_id) && $id === $booking->room_id) ? 'selected' : '' }}>{{ $display }}</option> @endforeach </select> <small class="form-text text-muted">The room number being booked.</small> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label"for="user_id">User</label> <div class="col-sm-10"> <select name="user_id" class="form-control" id="user_id" required> @foreach($users as $id => $display) <option value="{{ $id }}" {{ (isset($bookingsUser->user_id) && $id === $bookingsUser->user_id) ? 'selected' : '' }}>{{ $display }}</option> @endforeach </select> <small class="form-text text-muted">The user booking the room.</small> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="start">Start Date</label> <div class="col-sm-10"> <input name="start" type="date" class="form-control" required placeholder="yyyy-mm-dd" value="{{ $booking->start ?? '' }}"/> <small class="form-text text-muted">The start date for the booking.</small> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="start">End Date</label> <div class="col-sm-10"> <input name="end" type="date" class="form-control" required placeholder="yyyy-mm-dd" value="{{ $booking->end ?? '' }}"/> <small class="form-text text-muted">The end date for the booking.</small> </div> </div> <div class="form-group row"> <div class="col-sm-2">Paid Options</div> <div class="col-sm-10"> <div class="form-check"> <input name="is_paid" type="checkbox" class="form-check-input" value="1" {{ $booking->is_paid ? 'checked' : '' }}/> <label class="form-check-label" for="start">Pre-Paid</label> <small class="form-text text-muted">If the booking is being pre-paid.</small> </div> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label" for="notes">Notes</label> <div class="col-sm-10"> <input name="notes" type="text" class="form-control" placeholder="Notes" value="{{ $booking->notes ?? '' }}"/> <small class="form-text text-muted">Any notes for the booking.</small> </div> </div> ``` Now this line gets the attention: ``` <input name="is_paid" type="checkbox" class="form-check-input" value="1" {{ $booking->is_paid ? 'checked' : '' }}/> ``` When I access my create view it says: ``` Undefined variable: booking (View: /home/vagrant/code/resources/views/bookings/fields.blade.php) (View: /home/vagrant/code/resources/views/bookings/fields.blade.php) ``` Looking at the code the $booking variable is working on other form field items but on this particular item it doesnt. Any idea what I am missing? EDIT: Here's the controller: ``` <?php namespace App\Http\Controllers; use App\Booking; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class BookingController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // // \DB::table('bookings')->get()->dd(); $bookings = DB::table('bookings')->get(); return view('bookings.index') ->with('bookings', $bookings); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // // $users = DB::table('users')->get()->pluck('name', 'id')->dd(); $users = DB::table('users')->get()->pluck('name', 'id')->prepend('none'); $rooms = DB::table('rooms')->get()->pluck('number', 'id'); return view('bookings.create') ->with('users', $users) ->with('rooms', $rooms); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // // dd($request->all()); $id = DB::table('bookings')->insertGetId([ 'room_id' => $request->input('room_id'), 'start' => $request->input('start'), 'end' => $request->input('end'), 'is_reservation' => $request->input('is_reservation', false), 'is_paid' => $request->input('is_paid', false), 'notes' => $request->input('notes'), ]); DB::table('bookings_users')->insert([ 'booking_id' => $id, 'user_id' => $request->input('user_id'), ]); return redirect()->action('BookingController@index'); } /** * Display the specified resource. * * @param \App\Booking $booking * @return \Illuminate\Http\Response */ public function show(Booking $booking) { // // dd($booking); return view('bookings.show', ['booking' => $booking]); } /** * Show the form for editing the specified resource. * * @param \App\Booking $booking * @return \Illuminate\Http\Response */ public function edit(Booking $booking) { // $users = DB::table('users')->get()->pluck('name', 'id')->prepend('none'); $rooms = DB::table('rooms')->get()->pluck('number', 'id'); $bookingsUser = DB::table('bookings_users')->where('booking_id', $booking->id)->first(); return view('bookings.edit') ->with('bookingsUser', $bookingsUser) ->with('users', $users) ->with('rooms', $rooms) ->with('booking', $booking); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Booking $booking * @return \Illuminate\Http\Response */ public function update(Request $request, Booking $booking) { // } /** * Remove the specified resource from storage. * * @param \App\Booking $booking * @return \Illuminate\Http\Response */ public function destroy(Booking $booking) { // } } ```
2019/08/20
[ "https://Stackoverflow.com/questions/57574910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can add `isset` to check for the ternary operation, ``` {{ isset($booking->is_paid) ? 'checked' : '' }} ```
Change the input line for the checkbox to read: ```html <input type="checkbox" class="form-check-input" name="is_paid" value="1" {{(isset($booking->is_paid)) && $booking->is_paid == 1 ? 'checked ' : ' '}}/> ``` Create, show, and edit should all work.
50,859,498
``` SqlDataAdapter sda = new SqlDataAdapter("Select * from salestable where empid='" + txtsid.Text + "'between'" + datepick1.Value.ToString("MM/dd/yyyy") + "'And'" + datepick2.Value.ToString("MM/dd/yyyy") + "'", con); DataTable dt = new DataTable(); sda.Fill(dt); ```
2018/06/14
[ "https://Stackoverflow.com/questions/50859498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9932627/" ]
try use parameters on sqlDataAdapter: ``` string SQLsentence = @" SELECT * FROM salestable WHERE empid=@Employe AND [datesale(your column with date)] between @fDate And @lDate "; SqlDataAdapter sda = new SqlDataAdapter ( SQLsentence , con ); sda.SelectCommand.Parameters.Add ( new SqlParameter ( "@Employe" , txtsid.Text ) ); sda.SelectCommand.Parameters.Add ( new SqlParameter ( "@fDate" , new DateTime ( 2018 , 06 , 1 ) ) ); sda.SelectCommand.Parameters.Add ( new SqlParameter ( "@lDate" , new DateTime ( 2018 , 06 , 14 ) ) ); ``` whe you use parameters you prevent the SQL injection.
You don't seem to be testing a field for the between. It looks like the sql rendored will be something like: ``` Select * from salestable where empid='x'between'mm/dd/yy'and'mm/dd/yyyy' ``` you aren't testing anything as being between those two date values. Plus your spacing makes the sql hard to read
495,352
Hey I recently got interested in number theory and proved the following inequality: \begin{align} x^m-y^m > p\_n^2 + 4p\_n + 3 > 1\ \text{(corrected again)} \end{align} where $x-y\neq1$ and m in an integer >1 and \begin{align} \gcd(x,y)&=1 \\ xy&= 2\*3\*5\*..\*p\_n \end{align} So my question is ... Does this formula already exist? And is it useful or slightly interesting?
2013/09/16
[ "https://math.stackexchange.com/questions/495352", "https://math.stackexchange.com", "https://math.stackexchange.com/users/43620/" ]
The inequality deals with the primorial function $$ p\_n\#=2\cdot3\cdot5\cdots p\_n=\prod\_{p\le p\_n,\ p\in \mathbb{P}}p, $$ where $p\_n$ is the $n$th prime. [Asymptotically we have the result](http://mathworld.wolfram.com/ChebyshevFunctions.html) that $$ \lim\_{n\to\infty}\frac{\ln p\_n\#}{p\_n}=1. $$ Early on the primorials are bit smaller though. For example $\ln(59\#)\approx49$. Consider the following problem. Assume that $xy=p\_n\#$ and that $x-y\ge3$ (in OP $x,y$ were constrained to be integers of opposite parity such that $x-y>1$ implying that $x-y\ge 3$). Therefore $$x^m-y^m\ge x^2-y^2=(x-y)(x+y)\ge3(x+y).$$ Here by the AM-GM inequality $x+y\ge2\sqrt{xy}=2\sqrt{p\_n\#}.$ Therefore asymptotically we get a lower bound $$ x^m-y^m\ge 6\sqrt{p\_n\#}\ge6e^{\frac n2(1+o(1))}. $$ Asymptotically we also have have $p\_n\approx n\ln n.$ This suggests that $$ \frac{\ln(x^m-y^m)}{\ln p\_n}\ge \frac n{2\ln n} K(n), $$ where $K(n)$ is some correction factor (bounded away from zero) that I won't calculate. Your result says (using only the main term $p\_n^2$) that $$ \frac{\ln(x^m-y^m)}{\ln p\_n}\ge 2. $$ So asymptotically it is weaker. But it would not be fair to call your result trivial because of this. I'm not a number theorist, but I have seen simpler estimates being derived in many number theory books, and in addition to being fun, they pave the road to stronger results. Please share details of your argument with us, so that we can comment and give you other kind of feedback!
Modulo small values of $n,$ you do not need to assume that $x-y\ne 1$ as well as asymptotic on the primorial function. Instead, you can get away with Bertrand's postulate stating that $p\_{n}<2p\_{n-1}$ or $p\_{n-1}\ge p\_n/2.$ Indeed, if $m\ge 2,$ then $$x^m-y^m=(x-y)(x^{m-1}+...+y^{m-1})\ge (x-y)(x+y)\ge x+y\ge 2\sqrt{xy}.$$ Note, $$2\sqrt{xy}=2\sqrt{p\_1...p\_{n-3}p\_{n-2}p\_{n-1}p\_n}$$ and using the fact that $p\_{n-2}\ge p\_n/4,$ $p\_{n-3}\ge p\_n/8$ and $p\_{n-1}\ge p\_n/2$ we can estimate $2\sqrt{xy}\ge 2\sqrt{p\_1p\_2\cdot...\frac{p\_n^4}{64}}=\frac{p\_n^2}{8}\sqrt{p\_1p\_2...}.$ So we are left to check the result for small values of $p\_n.$
34,361
Abraham is said to have arrived at the existence of Gd in [Gen Rabah 39:](http://www.tsel.org/torah/midrashraba/lechlecha.html) > > אמר רבי יצחק משל לאחד שהיה עובר ממקום למקום וראה בירה אחת דולקת אמר > תאמר שהבירה זו בלא מנהיג הציץ עליו בעל הבירה אמר לו אני הוא בעל הבירה > כך לפי שהיה אבינו אברהם אומר תאמר שהעולם הזה בלא מנהיג הציץ עליו הקב"ה > ואמר לו אני הוא בעל העולם > > > Rabbi Isaac said: A parable for one who was going from place to place and he saw a tower alight. He said, *"could it be that this tower is without a caretaker?"* The caretaker appeared to him. He said *"I am the master of this tower."* So to because Abraham was saying *"could it be that this world has no caretaker?"*, Gd appeared to him and said *"I am the Master of the world".* > > > How did Abraham arrive at this conclusion? What was the "light in the tower" that lead him to reason that the must be a caretaker of the world? I have yet to come across any absolute logical proof of Gd's existence. Even the compelling evidence for His existence is found in the words of the Torah, which wasn't around in Abraham's lifetime. In the end, it boils down to belief... right? **Are there any sources that describe Abraham's process in detail?**
2014/01/02
[ "https://judaism.stackexchange.com/questions/34361", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/4682/" ]
This answer is taken mostly from this shiur by [R. Ezra Bick](http://vbm-torah.org/archive/midrash/01bira.doc) from VBM I just want to point out that this Midrash is not saying what Mideval logicians used to argue about Gd's existence. While the argument here is similar to the [watchmaker argument](http://en.wikipedia.org/wiki/Watchmaker_analogy) it is also very different. But first, we need to quote the entire Midrash, not just a small part of it: > > ויאמר ה' אל אברם לך לך מארצך וגו' ר' יצחק פתח (תהלים מה) שמעי בת וראי > והטי אזנך ושכחי עמך ובית אביך אמר רבי יצחק משל לאחד שהיה עובר ממקום > למקום וראה בירה אחת דולקת אמר תאמר שהבירה זו בלא מנהיג הציץ עליו בעל > הבירה אמר לו אני הוא בעל הבירה כך לפי שהיה אבינו אברהם אומר תאמר > שהעולם הזה בלא מנהיג הציץ עליו הקב"ה ואמר לו אני הוא בעל העולם (שם) > ויתאו המלך יפיך כי הוא אדוניך ויתאו המלך יפיך ליפותיך בעולם והשתחוי לו > הוי ויאמר ה' אל אברם:‏ > > > The Full Translation is as follows: ([taken from here](http://adderabbi.blogspot.co.il/2008/11/burning-house-reading-of-bereishit.html)) > > (Midrash Rabba 39,1) God spoke to Avraham: Go you from your land …. > > > R. Yitzchak began: > > > “Listen, O daughter, and look, and incline your ear; and forget you > nation and your father's house” (Tehillim 45:11) > > > R. Yitzchak said: > > > This may be compared to one who was traveling from place to place, and > he saw a burning mansion. He said: Is it possible that this mansion is > without someone responsible? The owner of the mansion looked out at > him and said: I am the owner of the mansion. > > > So, too, our father Avraham said: Is it possible that the world is > without someone responsible? God looked out at him and said: I am the > master of the world. > > > So the king shall desire your beauty, for he is your lord… (Ibid 12) > > > So the king shall desire your beauty – to beautify you in the world. > > > …and bow to him – that is, “and God spoke to Avraham”. > > > Firstly a note about the translation. The word "דולקת" can mean either "burning" or "illuminated", so depending on how you translate this word the midrash can mean two opposite things. The proper translation is "burning", but that doesn't make sense to people who view this as the watchmaker argument, and so they try to translate it as "illuminated" instead. I believe this is an incorrect translation, because of the references to Tehilim, but perhaps the writers of the Midrash did intend for both readings. Avraham traveled "the world", moving from place to place. In every place he went he found the world "burning". He saw disorder, injustice, a dissaray of purposes and goals manifested in idolatry. The response of avraham to a burning world was a cry out, searching for the owner. Surely there is an owner of the "building"(world) who will put out the fire, who cares that the world is on fire, and is the master of the world. The Midrash tells us that indeed, Gd called out to Avraham and said "I am the master of the master of the world." And So Gd calls out to Avraham, and tells him to leave his past, his place , his family, and to strike out to Cannan (an immoral place) and to build a new society which is Just, and build on good moral principles, and to stop the World from burning. The Alternative meaning is that he saw a well built world, after traveling from place to place, and saw that "someone was home", (the lights were on) and assumed there must be an owner. The argument from design, or the watchmaker analogy. (My rest is my own reading, not from R. Bick) However, this interpretation does not explain the quotes from Tehilim, which ask the Daughter of king to leave her home for the right king to be annointed. If the world was built well and not burning, there would be no need to leave. She could stay where she is, but if her home is on fire, and the false kings reign, then it would be best for her to leave and find the true king. The last reference to Tehilim tells us that Gd told Avraham to go out to the world and beautify it. Gd is the master of the world, but it is our responsibility to fix it, based on Gd's instruction. I highly recommend reading R. Bick's article, as it goes on many other tangents and makes many good explanations about Midrash and how to read midrash, including the midrash about Abraham and Nimrod regarding the power of the elements. (but is not in the scope of this question) So to sum up. The process that Avraham took was the opposite of the "question of evil". Avraham saw what was wrong with the world, and recognized that such a world must have an owner. For a well built tower that is burning, means there is an owner to that building. The obvious question to all this however, is that perhaps the world/tower is burning precisely because it has no owner? But this does not hold up to scrutiny. If a tower has no owner, then it might be left to rot or decay. But why would someone burn it? Why go through the effort to destroy the tower by fire, unless it is owned by someone?
Abraham realized that everything has a cause, and complex systems don't arise out of nothingness; Someone has to create them.
4,146,234
**Problem** I am not able to refresh the page with **window.location.reload()** which is used inside the success call made to yahoo. Any hints how it can be fixed. The whole of the code is working fine it is making call to cse server getting contents from there saving on yahoo. but i have to manually refresh the page to bring the contents. I want it to be automatic so I used **window.location.reload()** but thats not working. Any suggestions how it can be done. The function below is actually a function for a button.
2010/11/10
[ "https://Stackoverflow.com/questions/4146234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1272852/" ]
You have to use `DeviceInfo.getDeviceId();` as shown [here](http://supportforums.blackberry.com/t5/Java-Development/Method-to-get-device-ID/m-p/205656)
Have you read [this article](http://www.blackberryforums.com/developer-forum/1620-retrieve-model-info-java.html) and read the [DeviceInfo.getDeviceName() and DeviceInfo.getDeviceId() documentation](http://www.blackberry.com/developers/docs/4.0.2api/net/rim/device/api/system/DeviceInfo.html)?
35,296,907
I have a generic class that looks something like this: ``` template <class T> class Example { private: T data; public: Example(): data(T()) Example(T typeData): data(typeData) ~Example() // ... }; ``` I'm a bit confused about how to implement a deconstructor for something like this. Specifically, since `T` is of any type, it could be memory allocated on the stack (which is always the case for `Example`'s created via the no-argument constructor) or on the heap. For instance, if the client makes the type for `T` an `int*` and provides a pointer to dynamic memory, how do I know to call `delete` on `data` as opposed to if the client set the type to `int`?
2016/02/09
[ "https://Stackoverflow.com/questions/35296907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/996249/" ]
The simplest answer is: don't. Don't try to second-guess the user and do something they might not expect. Adopt the same policy as standard containers do: assume `T` cleans up after itself correctly. If the client code is written correctly, it will use RAII classes (such as smart pointers) for automatic and correct management of memory and other resources. If it's not, you cannot hope to fix that in your provider code. Make your class work with `std::unique_ptr` and `std::shared_ptr`, as well as any other custom RAII class, and let your clients do the management themselves. What if they want to store non-owning pointers, after all?
You can use Template Specialization. ``` template <class T> class Example { private: T data; public: Example() : data(T()) {} Example(T typeData): data(typeData) {} }; template <class T> class Example<T*> { private: T* data; public: Example() : data(nullptr){} Example(T* typeData): data(typeData) {} ~Example() { delete data; } }; int main() { Example<int> e; Example<int*> e2; return 0; } ```
606,514
First off: please don't flag this question as being for Stack Overflow (yes, Python is a major part of the context but my question is ultimately about Systemd) I am currently writing a Python program that will sit on a server and be controlled through Systemd (enabled so it restarts if the server goes down, etc.). My concern is that the "Tasks" section of the `systemctl status` is continually increasing. ``` ... Active: active (running) since Wed 2020-08-26 18:31:12 UTC; 14min ago Main PID: 1657 (python3) Tasks: 178 (limit: 637) <-- ... ``` Extrapolating this information, it will take a little over 50mins (from service start) before the limit is reached. My question is not "why is my code broken", "how do I raise this limit" or the like. Instead my question is: what does Systemd consider a task and what will happen when the limit is reached (is a signal sent to kill the service, etc.)? With this information, I hope to understand why my Python script has (what appears to be) a linear increase in the number of tasks (and subsequently fix this).
2020/08/26
[ "https://unix.stackexchange.com/questions/606514", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/368878/" ]
[systemd.resource-control(5)](https://www.freedesktop.org/software/systemd/man/systemd.resource-control.html#TasksMax=N) gives us a hint: > > > ``` > TasksMax=N > Specify the maximum number of tasks that may be created in the unit. This > ensures that the number of tasks accounted for the unit (see above) stays > below a specific limit. This either takes an absolute number of tasks or a > percentage value that is taken relative to the configured maximum number of > tasks on the system. If assigned the special value "infinity", no tasks > limit is applied. This controls the "pids.max" control group attribute. For > details about this control group attribute, see Process Number Controller[7]. > > The system default for this setting may be controlled with DefaultTasksMax= > in systemd-system.conf(5). > > ``` > > So this limit is based on "pids.max". PIDs are generated whenever your process calls [`fork()`](https://www.man7.org/linux/man-pages/man2/fork.2.html) or [`clone()`](https://www.man7.org/linux/man-pages/man2/clone.2.html). In the context of python, there is a [`os.fork()`](https://docs.python.org/3/library/os.html#os.fork) which probably calls the system-call of the same name. I'm not sure in which other situations `python` would make those system calls, but if you're not spawning hundreds of processes, then I expect it to be related to the number of spawned threads. The man page references some good literature: [[7] Process Number Controller](https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v1/pids.html)
Simply add this command to your scripts with: `systemctl restart yourproject.service` Explanation: With `systemctl restart`, your project always has a fresh task.
4,282
I have several Micro SD Cards for my Raspberry Pi. However, they often get mixed up because they are so small: [![MicroSD Card](https://i.stack.imgur.com/CgScwm.jpg)](https://i.stack.imgur.com/CgScw.jpg) [image source](http://www.mikroe.com/products/view/966/microsd-card-2gb-with-adapter/) Unlike regular SD Cards and Flash Drives, I cannot label them. How can I organize them?
2015/02/12
[ "https://lifehacks.stackexchange.com/questions/4282", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/15/" ]
SD/SDHC Memory Card Hard Plastic Cases [https://www.amazon.com/Slots-Memory-Plastic-Tronixpro-Microfiber/dp/B00UNQT714](https://rads.stackoverflow.com/amzn/click/B00UNQT714) Each unit has twelve containers for SD cards. I use a label maker to add a label to the door.
I don't think that labelling them is impossible and I made my own attempts with tiny, usually two-line labels printed with a Brother P-Touch series label printer. Such labels printed are small enough to fit onto a microSD card and thin enough to work with most (normal-size) SD card slots or readers, so that method is fine for older Raspberry Pis. But those labels already too thick for most microSD card slots, at least for those on the Raspberry Pi 2 and 3. They either shave off when putting the microSD card into the slot, or, if I managed that, they're much harder to get out again, especially with the Raspberry Pi 3 which has no more counter spring inside the slot. I recently discovered that [there are also non-laminated label cassettes for Brother P-Touch label printers and they're said to be much thinner](https://www.brother.co.uk/supplies/p-touch/tapes/tze). Will probably try these. Those fitting for my label printer all seem to have the product number prefix "TZe-N" with "N" standing for "Non-Laminated". Will probably try the [3.5mm](https://www.brother.co.uk/supplies/p-touch/tapes/tze/tzen201) and [9mm](https://www.brother.co.uk/supplies/p-touch/tapes/tze/tzen221) widths. I also found a thread somewhere else where the same topic has been discussed. [Someone found thin enough labels and made a Microsoft Word template for printing them in the proper size](https://gbatemp.net/threads/how-to-label-micro-sd-cards.490582/#post-7956459). You still need scissors to cut the labels into that small size alongside a dotted line printed from the template.
31,964,025
So we use Sidekiq as our queue managing system in our Rails application. We also use Sidetiq to manage scheduled and recurring tasks. At the moment there is around 200-300 scheduled tasks that will run anytime from couple of minutes to 30 days. I would transfer just Redis database rdb file but due to some configuration changes, Rails project path has changed (hence tasks will not be able to run anymore) What would be a preferred way to transfer whole scheduled tasks queue to work with new project path and manually is not the case. * Ruby 2.1.6 * Rails 3.2.22 * Sidekiq 3.4.2 * Redis 2.8.4
2015/08/12
[ "https://Stackoverflow.com/questions/31964025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/904430/" ]
Use DUMP and RESTORE: ``` redis-cli -h source_host dump schedule | head -c-1 | redis-cli -h dest_host restore 0 schedule ``` <http://redis.io/commands/restore>
You can copy your redis dump file as you said. It's not clear for me why you are excluding that option. Doing it manually (just create a ruby script for it), moving the scheduled tasks should be pretty easy. The only thing you have to do is moving the redis sets `retry` and `schedule`
8,151
We all know that deserts are the hottest places on Earth, but what makes them different from other parts of the world?
2016/06/10
[ "https://earthscience.stackexchange.com/questions/8151", "https://earthscience.stackexchange.com", "https://earthscience.stackexchange.com/users/5395/" ]
> > We all know that deserts are the hottest places on Earth. > > > That is not necessarily true. What is true is that the hottest places on Earth are in deserts. Note the reversal. Much of the Arctic and Antarctic are technically deserts due to extremely low precipitation. Excluding these polar deserts, some deserts are quite cool, even if they are close to the equator. For example, Arica, Chile (the driest inhabited locale in the world), has a rather mild climate temperature-wise, despite being at 18°29′ south latitude. This is the case for much of the Atacama desert. > > What makes them different from other parts of the world? > > > I'm assuming you are asking about those deserts that are hot in the summertime rather than deserts in general. A key ingredient for extremely high temperatures is a desert, but not a high latitude desert, high altitude desert, or coastal desert. Very low precipitation is what distinguishes desert from non-desert biomes. Lack of precipitation is not sufficient for very high temperatures, as exhibited by the very cold polar deserts and the rather cool deserts that are well outside polar areas. Much of the Atacama is at a high altitude, as are the Gobi in China and Mongolia, the Taklamakan in China, and the high desert in the Mexico and the US. While some of these deserts can be hot during summer, they aren't ridiculously hot. Areas along the coast of the previously mentioned Atacama desert and the Namib in Africa are kept somewhat cool by ocean breezes. These coastal deserts can be uniformly mild year-round. What is needed to create the possibility for extremely high temperatures is a desert that is not at extreme latitudes, that is well removed from coastal cooling, and that is at low altitudes. A desert is needed so as to receive the full brunt of solar radiation. Equatorial regions don't work because they tend to be cloudy and rainy. High latitude areas don't work because they don't receive very much insolation. High altitude areas don't work because temperature tends to decrease with increased altitude. A low altitude desert in the horse latitudes is exactly what is needed, and this is why Furnace Creek in Death Valley, California (supposedly the hottest place in the world) and Tirat Zvi, Isreal (supposedly the hottest place in Asia) can be very, very hot. The horse latitudes are where the Hadley cell and mid latitude cell converge, creating long-lived high pressure areas where rain is highly unlikely. Most of the world's non-polar deserts are in or near the horse latitudes. Even better than Furnace Creek are those areas that are so ridiculously hot that nobody sane would live there and hence there are no weather stations. We don't know, for example, how hot it gets in the Lut desert in Iran. It's too hot there for people to fathom, and is almost certainly hotter than is Furnace Creek.
The first thing to note is that not all deserts are hot - think Tibet. But there is no doubt that most deserts are distributed adjacent to the hot and wet climatic equator. This is no coincidence. Because the sun is at or close to being overhead in the equatorial zone, this belt receives the most solar energy per square metre. Hot air rises, dumping a lot of the moisture as it cools (hence tropical rain forests), then the air spreads out polewards in both north and south directions, flowing in the upper troposphere. Pressure distribution is such that this part of the global circulation is balanced by a return air flow close to ground level. Together this convective air circulation occurs in 'Hadley Cells' which constitutes the world's biggest heat re-distribution mechanism. The downflow part of the cells is where hot dry air descends under clear skies, and hence is where deserts occur.
47,270
I thought about posting this in English.SE, but since it occurs in a university setting, I decided to post here - hopefully it's on-topic. I have been working on a project that is being transitioned to another group member so she could take over the project. The project involves the design, development, and application of "Model X". I have done some useful work on it, but some work still needs to be done to complete it. I'm putting together a documentation package to describe what I've done so far, the design of "Model X", and how to use the code I've written thus far. This report is internal to the group (whether this will be part of something that is published in the future, I do not know). I hesitate to title the report "Model X" because it's not, and might not be close to, being the final model. How should I title the transition report? Some options I have thought of: "Current status of Model X" - but this seems like an email subject "Incomplete Model X: Design and Usage" - this sounds a bit degrading What would you suggest? And are there in fact accepted titles for this kind of report?
2015/06/16
[ "https://academia.stackexchange.com/questions/47270", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/35916/" ]
I have typically seen the word "Draft" used, as in: > > Draft Model of X (Date) > > > If you want to track multiple drafts over time, then you can give a version number as well: > > Draft Model of X (Version N, Date) > > >
How about calling it a [Working Paper](https://en.wikipedia.org/wiki/Working_paper) or a [Technical Report](https://en.wikipedia.org/wiki/Technical_report)? (These are considered forms of [grey literature](https://en.wikipedia.org/wiki/Grey_literature).)
33,647,249
This is question is about the general architecture, I do not require anyone to solve this little hack for me, although I won't be angry if someone does ;). Suppose I have a web app that spawns standard unix processes (like Travis CI). While it seems simple enough to pick the stdout of such a process, I'd rather like to make the whole thing asynchronous (like e.g. Travis). So I thought of passing the whole output through a websocket and into some web-based terminal emulator. However, the only emulators I could find were fully interactive (i.e. they allow for user input and thus have some custom server-side component). My goal would be to have a piece of client side code and just stuff the output into it. So what is necessary to create a websocket, attach it to the stdout of a server-side process (preferably emulating a tty for colors and fancyness) and display a terminal client-side? I recon there are control codes to distinguish a tty from a text file and these control codes need to be encoded on the websocket somehow, but is there some documentation on this?
2015/11/11
[ "https://Stackoverflow.com/questions/33647249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3031069/" ]
If you're trying to get the actual index values for some reason (and/or need to control the inner loop separate from the outer), you'd do: ``` for i in range(len(mylist)): for j in range(i+1, len(mylist)): # Or for indices and elements: for i, x in enumerate(mylist): for j, y in enumerate(mylist[i+1:], start=i+1): ``` But if what you really want is unique non-repeating pairings of the elements, there is a better way, [`itertools.combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations): ``` import itertools for x, y in itertools.combinations(mylist, 2): ``` That gets the values, not the indices, but usually, that what you really wanted. If you really need indices too, you can mix with `enumerate`: ``` for (i, x), (j, y) in itertools.combinations(enumerate(mylist), 2): ``` Which gets the exact index pattern you're looking for, as well as the values. You can also use it to efficiently produce the indices alone as a single loop with: ``` for i, j in itertools.combinations(range(len(mylist)), 2): ``` Short answer: `itertools` is magical for stuff like this.
If you're really just interested in the indexes, you can use `range` rather than `enumerate`. ``` for i in range(5): for j in range(i+1, 5): print i, j ```
24,938,301
Newbie java question, I am sure this has been answered but cannot find a solution anywhere :( I want to use this java program contained here <http://sourceforge.net/projects/ant-tibco/files/> wich consists of a ant-tibco.jar file and many .java files contained here .\ant-tibco\src\org\apache\tools\ant\taskdefs\optional\tibco I want to edit a line in one of these .java files, but after that I am not sure how to compile to commit these changes, I have tried javac but keep getting "cannot find symbol" exceptions. What do I need to commit and compile changes made in these .java files to the ant-tibco.jar file? Any help is greatly appreciatted! Thank you!
2014/07/24
[ "https://Stackoverflow.com/questions/24938301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2796332/" ]
``` var http = require('http') var through = require('through') var server = http.createServer(function(req, res) { console.error("Been called") if (req.method != 'POST') return res.end('send me a POST\n'); var tr = through(function(buf){ this.queue(buf.toString().toUpperCase()) }) req.pipe(tr).pipe(res) }) server.listen(parseInt(process.argv[2])); ``` Run this example. Note the console.error call. The createServer requestListener is being called twice, so two instances of 'tr' are being created. If 'tr' is created outside the callback there is only one. This results in unexpected behavior when the requests and writes don't happen in the order we get oddness. I suspect this is not intended behavior for the through module.
The comments in the problem are correct that it's an asynchronous issue (the biggest pitfall for somebody new to Node in my own experience). PSB's solution is correct, but I wanted to be able to break the through instance out into a separate function rather than have to define it inside the createServer callback function. The through instance needs to be wrapped in a closure so this.queue keeps the intended context. ``` var http = require('http'); var through = require('through'); var server = http.createServer(function(req,res){ if(req.method==='POST'){ req.pipe(tr()). pipe(res); } }); server.listen(process.argv[2]); var tr = function(){ return(through( function(buf){ this.queue(buf.toString().toUpperCase()); }) ); }; ```
4,136,588
I have a multidimensional array which I would like to sort by two factors: First the state and then the city alphabetically. ``` var locations = [ ['Baltimore', 'Maryland', 'MD'], ['Germantown', 'Maryland', 'MD'], ['Rockville', 'Maryland', 'MD'], ['San Francisco', 'California', 'CA'], ['San Diego', 'California', 'CA'] ]; ``` How can I sort them alphabetically based on these two factors? First State, then City? I know how to do it just be one factor, but not two..
2010/11/09
[ "https://Stackoverflow.com/questions/4136588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90871/" ]
``` locations.sort(function(x, y) { if (x[1] > y[1]) // if you want to sort by abbreviation, return 1; // use [2] instead of [1]. else if (x[1] < y[1]) return -1; else if (x[0] > y[0]) return 1; else if (x[0] < y[0]) return -1; else return 0; }); ```
Try this: ``` locations.sort(function(a, b){ var cmp = function(x, y){ //generic for any sort return x > y? -1 : x < y ? 1 : 0; }; return [cmp(a[1], b[1]), cmp(a[0], b[0])] < [cmp(b[1], a[1]), cmp(b[0], a[0])] ? 1 : -1; }); ``` If you want to sor descending on city for instance you can use `-cmp(...)` instead of `cmp(...)`
2,117,623
(I think this question is platform independent, but I happen to be coding for a Nexus One). About "current speed": I'm getting a callback every second or so telling me what my current latitude and longitude are. I can calc the distance between the current location and the previous location, so I can keep track of cumulative distance and cumulative time. With that I can say what the average speed has been for the ENTIRE trip. But how do I calc current speed? I suspect I need to use the most recent N samples, right? Am I thinking about this the right way? What's a good rule of thumb for N? How many samples, or how many seconds back? About "stop time": If I'm just standing still, I can still get slightly different latitudes and longitudes reported to me, right? So, deciding that I'm not really moving means saying something like, "the previous X locs have all been within Y meters of each other", right? Am I thinking about this the right way? What's a good rule of thumb for X and Y? Even about "distance": Will I be understating it because I'm literally cutting corners? Is there an algorithm or a rule of thumb, for determining when I'm "turning" and should I add in a little fudge? EDIT: I APOLOGIZE: I feel bad about wasting people's time and good will, but sadly, the device *IS* giving me speed. I thought it wasn't because in the emulator it wasn't, but on the real device it is. Thanks everybody. There's still some rule-of-thumb code I need to write, but speed was the biggest challenge. EDIT: I retract the apology. In my original question I wrote that distance too is a derived value. If I just use the raw GPS data, I will be overstating distance because of the inaccuracies. I might be walking a straight line, but the raw GPS lat/long will wobble, so if I calc total distance by measuring the distance between the points, I will be overstating it. Here's some links that are related to this problem. [Smooth GPS data](https://stackoverflow.com/questions/1134579/smooth-gps-data) <http://www.cs.unc.edu/~welch/kalman/Levy1997/index.html> [How to intelligently degrade or smooth GIS data (simplifying polygons)?](https://stackoverflow.com/questions/1849928/how-to-intelligently-degrade-or-smooth-gis-data-simplifying-polygons) [How to 'smooth' data and calculate line gradient?](https://stackoverflow.com/questions/204184/how-to-smooth-data-and-calculate-line-gradient)
2010/01/22
[ "https://Stackoverflow.com/questions/2117623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
Remember a short history of position, going back a few seconds. 5 seconds should give you a reasonably accurate result that updates fairly quickly... ``` // delay is the time difference between the 2 samples you have delay = 5; // 5 second delay // figure out how far along x and y we have moved since last time dx = newx - oldx; dy = newy - oldy; // distance travelled distance = sqrt(dx*dx + dy*dy); // find the speed. if the positions were measured in metres and the time in seconds // this will be the average speed in metres per second, over the last 5 seconds speed = distance / delay; ``` The longer you can wait between samples (eg, if you keep the last 30 position samples and use a 30 second delay), the more stable your answer will be (ie, the less noisy it will be), but the slower it will be to react to any changes in speed. Why do you need to add this delay stuff? well, the GPS unit in your phone probably isn't very accurate. If you are standing still, the position it returns each second might wobble about a fair bit. This wobble noise will make it look like you are sprinting randomly around the room and might cause you to report a moderately high speed, even though you're not moving at all. The solution I have listed will not really help when you are standing still, as the result from 30 seconds ago will be just as wrong as the position from 1 second ago. What you really need to do is average the position over a while, then compare that to the average position from a slightly earlier time. eg... Take 10 samples of position and average them. This is position 1. Take another 10 samples and average them. This is position 2. Use these 2 positions with the code above to get the speed. Again, the more samples you can take, the more accurate and stable your positions will become, but this will make your speed measurement less responsive.
The current speed is the difference between Position(now) and Position(previous) so to get the current speed you only need to compare the current and last position. BUT: As this is quite vulnerable to small inaccuracies in time/position tracking it is not reliable so you have to average it over the last Positions. How many depends on the use case, the longer the time frame the less "current" the speed is but the more precise it is.
26,390,165
I have regular navigation and mobile navigation that collapses. Whenever the navigation switches from mobile to regular, the regular navigation shifts down from where it was originally. I am befuddled as to why this is happening and how to fix it. Thanks so much for taking the time to look at this. It is only a problem in Chrome and Safari, but not Firefox. Example image: <http://wildmeasure.com/qualitymetalcraft.com/qmcnav.jpg>
2014/10/15
[ "https://Stackoverflow.com/questions/26390165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525923/" ]
You should avoid the use of `length` and write your function using `foldl` (or `foldl'`): ``` fromDigits :: [Int] -> Integer fromDigits ds = foldl (\s d -> s*10 + (fromIntegral d)) 0 ds ``` From this a generalization to any Foldable should be clear.
A better way to solve this is to build up a list of your powers of 10. This is quite simple using `iterate`: ``` powersOf :: Num a => a -> [a] powersOf n = iterate (*n) 1 ``` Then you just need to multiply these powers of 10 by their respective values in the list of digits. This is easily accomplished with `zipWith (*)`, but you have to make sure it's in the right order first. This basically just means that you should re-order your digits so that they're in descending order of magnitude instead of ascending: ``` zipWith (*) (powersOf 10) $ reverse xs ``` But we want it to return an `Integer`, not `Int`, so let's through a `map fromIntegral` in there ``` zipWith (*) (powersOf 10) $ map fromIntegral $ reverse xs ``` And all that's left is to sum them up ``` fromDigits :: [Int] -> Integer fromDigits xs = sum $ zipWith (*) (powersOf 10) $ map fromIntegral $ reverse xs ``` Or for the point-free fans ``` fromDigits = sum . zipWith (*) (powersOf 10) . map fromIntegral . reverse ``` Now, you can also use a fold, which is basically just a pure for loop where the function is your loop body, the initial value is, well, the initial state, and the list you provide it is the values you're looping over. In this case, your state is a sum and what power you're on. We could make our own data type to represent this, or we could just use a tuple with the first element being the current total and the second element being the current power: ``` fromDigits xs = fst $ foldr go (0, 1) xs where go digit (s, power) = (s + digit * power, power * 10) ``` This is roughly equivalent to the Python code ```py def fromDigits(digits): def go(digit, acc): s, power = acc return (s + digit * power, power * 10) state = (0, 1) for digit in digits: state = go(digit, state) return state[0] ```
56,092,725
I need help writing this next() method in this class. I've tried several stuff, but I keep getting that I'm not returning the next value, but rather null. The instructions for this class reads: This class should be public, non-static, and should implement java.util.Iterator. It's index instance variable should be initialized with an appropriate value. It's hasNext() method should return true if any elements in the queue have yet to be returned by its next() method. It's next() method should return queue values in the same order as in the underlying array. Therefore I'm going to write the code that I have, but will cut it short so only the important elements that are relatable to my problem shows. ``` public class MaxHeapPriorityQueue<E extends Comparable<E>> { private E[] elementData; private int size; @SuppressWarnings("unchecked") public MaxHeapPriorityQueue() { elementData = (E[]) new Comparable[10]; size = 0; } public Iterator<E> iterator() { return new MHPQIterator(); } ``` and the other class takes place here, which has ties with the Iterator method. ``` public class MHPQIterator implements java.util.Iterator<E> { private int index; public boolean hasNext() { if(size == 0) { return false; } else { return (index < size); } } public E next() { return elementData[index]; } } ``` I'm not sure if I'm elementData would work, but I don't know what else I could return with.
2019/05/11
[ "https://Stackoverflow.com/questions/56092725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10572727/" ]
First of all, my understanding is, that your data is inside elementData and size gives the number of elements stored inside. iterator() gives you an iterator. Your Iterator implementation has index as a point to the current element. What do you plan to store inside index? I see 2 possibilities: a) it is giving you the current data location. The first element inside the array is element 0, so to be before that, I would initialize it as -1. b) It could be visual. So it is initialized as 0 first and then 1 means: first element, which would be the elementData[0]. ==> It is just an internal variable so it is completely up to you, what you want to store inside of it. Now let us look at your hasNext method. If the sizer is 0, then there cannot be a next element. Ok. But then you check if iterator() is null? iterator always returns a new instance of your inner iterator class. So it will always be non null! So this seems wrong. You have index and size. So you just have to check if the index is already pointing to the last element. So depending on the choice a/b above, you simply have to check if index+1 < size or index And then the next function: - It has to validate that there is another element. (=> hasNext) - you increase index - you return the element, index is pointing to (elementData[index] or elementData[index-1] (depends again on your decision what to store inside index) My hint is, to play around with it with paper and pen. Just write an instance of your class with e.g. 3 elements (so elementData[0], elementData[1], elementData[2] hs some value, size = 3. You create a new instance of your iterator, index is initialized and then see what must happen. A possible class that shows an implementation is: import java.util.Iterator; ``` public class MaxHeapPriorityQueue<E extends Comparable<E>> { private E[] elementData; private int size; @SuppressWarnings("unchecked") public MaxHeapPriorityQueue() { elementData = (E[]) new Comparable[10]; size = 0; } public void add(E data) { if (size == 10) throw new IllegalStateException("Queue full"); elementData[size] = data; size++; } public Iterator<E> iterator() { return new MHPQIterator(); } public class MHPQIterator implements java.util.Iterator<E> { private int index=-1; public boolean hasNext() { return (index+1)<size; } public E next() { index++; return elementData[index]; } } public static void main (String[] args) { MaxHeapPriorityQueue<Integer> queue = new MaxHeapPriorityQueue<>(); Iterator<Integer> iterator = queue.iterator(); System.out.println("Empty queue:"); while (iterator.hasNext()) System.out.println(iterator.next()); queue.add(1); System.out.println("Queue with 1 element (1):"); iterator = queue.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); queue.add(2); queue.add(3); queue.add(4); System.out.println("Queue with 4 elementa (1,2,3,4):"); iterator = queue.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } } ```
Here is what worked for me, however the answer was posted here and I accepted it, but here's what worked with my code. ``` public class MHPQIterator implements java.util.Iterator<E> { private int index; public boolean hasNext() { if(size == 0) { return false; } else { return (index < size); } } public E next() { index++; return elementData[index]; } } ```
26,390,165
I have regular navigation and mobile navigation that collapses. Whenever the navigation switches from mobile to regular, the regular navigation shifts down from where it was originally. I am befuddled as to why this is happening and how to fix it. Thanks so much for taking the time to look at this. It is only a problem in Chrome and Safari, but not Firefox. Example image: <http://wildmeasure.com/qualitymetalcraft.com/qmcnav.jpg>
2014/10/15
[ "https://Stackoverflow.com/questions/26390165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525923/" ]
You should avoid the use of `length` and write your function using `foldl` (or `foldl'`): ``` fromDigits :: [Int] -> Integer fromDigits ds = foldl (\s d -> s*10 + (fromIntegral d)) 0 ds ``` From this a generalization to any Foldable should be clear.
If you're really determined to use a right fold for this, you can combine calculating `length xs` with the calculation like this (taking the liberty of defining `fromDigits [] = 0`): ``` fromDigits xn = let (x, _) = fromDigits' xn in x where fromDigits' [] = (0, 0) fromDigits' (x:xn) = (toInteger x * 10 ^ l + y, l + 1) where (y, l) = fromDigits' xn ``` Now it should be obvious that this is equivalent to ``` fromDigits xn = fst $ foldr (\ x (y, l) -> (toInteger x * 10^l + y, l + 1)) (0, 0) xn ``` The pattern of adding an extra component or result to your accumulator, and discarding it once the fold returns, is a very general one when you're re-writing recursive functions using folds. Having said that, a `foldr` with a function that is always strict in its second parameter is a really, really bad idea (excessive stack usage, maybe a stack overflow on long lists) and you really should write `fromDigits` as a `foldl` as some of the other answers have suggested.
2,938,969
I would like to know how to translate the following code to codebehind instead of XAML: ``` <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> ``` The part I can't figure out is the Path portion. I have the following but it doesn't work: ``` new Trigger { Property = Validation.HasErrorProperty, Value = true, Setters = { new Setter { Property = Control.ToolTipProperty, // This part doesn't seem to work Value = new Binding("(Validation.Errors)[0].ErrorContent"){RelativeSource = RelativeSource.Self} } } } ``` Help?
2010/05/30
[ "https://Stackoverflow.com/questions/2938969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99367/" ]
I think I finally found a solution: First, in a header file, declare `memset()` with a pragma, like so: ``` extern "C" void * __cdecl memset(void *, int, size_t); #pragma intrinsic(memset) ``` That allows your code to call `memset()`. In most cases, the compiler will inline the intrinsic version. Second, in a separate implementation file, provide an implementation. The trick to preventing the compiler from complaining about re-defining an intrinsic function is to use another pragma first. Like this: ``` #pragma function(memset) void * __cdecl memset(void *pTarget, int value, size_t cbTarget) { unsigned char *p = static_cast<unsigned char *>(pTarget); while (cbTarget-- > 0) { *p++ = static_cast<unsigned char>(value); } return pTarget; } ``` This provides an implementation for those cases where the optimizer decides not to use the intrinsic version. The outstanding drawback is that you have to disable whole-program optimization (/GL and /LTCG). I'm not sure why. If someone finds a way to do this without disabling global optimization, please chime in.
This definitely works with VS 2015: Add the command line option /Oi-. This works because "No" on Intrinsic functions isn't a switch, it's unspecified. /Oi- and all your problems go away (it should work with whole program optimization, but I haven't properly tested this).
16,526,646
Trying to improve a custom codeigniter route regex that I have created. Essentially the purpose of the custom route is to create a cleaner/shorter URL for client profile pages which have the format of `clients/client-slug`, for example: `clients/acme-inc`. I only want this route to match if their are no additional segments after the client-slug segment, and if they client-slug value does not match any of the 'reserved' values which correspond to actual methods/routes in the Clients controller. Currently, this is what I'm using: ``` $route['clients/(?!some_method|another_method|foo|bar)(.+)'] = 'clients/index/$1'; ``` This mostly works ok, except for when there is a client-slug that begins with one of the reserved methods text, i.e. `clients/food-co`, which since it has `clients/foo` in it, the custom route is not matched. So I need to basically conditionally allow the route to contain any of the reserved methods in that set ONLY IF it is followed by additional characters (that is not a `/`).
2013/05/13
[ "https://Stackoverflow.com/questions/16526646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192694/" ]
Do you try this? ``` $route['clients/(?!(?:some_method|another_method|foo|bar)(?:/|$))(.+)'] = 'clients/index/$1'; ```
You should consider the [`_remap()`](http://ellislab.com/codeigniter/user-guide/general/controllers.html#remapping) method in the future. It will allow you to update your controller and add new methods without needing to update your route (you actually wouldn't need a route at all, so long as your URI matches the controller name).
2,497,720
The following simple code reproduces the growth of `java.lang.ref.WeakReference` objects in the heap: ``` public static void main(String[] args) throws Exception { while (true) { java.util.logging.Logger.getAnonymousLogger(); Thread.sleep(1); } } ``` Here is the output of jmap command within a few seconds interval: ``` user@t1007:~> jmap -d64 -histo:live 29201|grep WeakReference 8: 22493 1079664 java.lang.ref.WeakReference 31: 1 32144 [Ljava.lang.ref.WeakReference; 106: 17 952 com.sun.jmx.mbeanserver.WeakIdentityHashMap$IdentityWeakReference user@t1007:~> jmap -d64 -histo:live 29201|grep WeakReference 8: 23191 1113168 java.lang.ref.WeakReference 31: 1 32144 [Ljava.lang.ref.WeakReference; 103: 17 952 com.sun.jmx.mbeanserver.WeakIdentityHashMap$IdentityWeakReference user@t1007:~> jmap -d64 -histo:live 29201|grep WeakReference 8: 23804 1142592 java.lang.ref.WeakReference 31: 1 32144 [Ljava.lang.ref.WeakReference; 103: 17 952 com.sun.jmx.mbeanserver.WeakIdentityHashMap$IdentityWeakReference ``` Note that jmap command forces FullGC. ``` JVM settings: export JVM_OPT="\ -d64 \ -Xms200m -Xmx200m \ -XX:MaxNewSize=64m \ -XX:NewSize=64m \ -XX:+UseParNewGC \ -XX:+UseConcMarkSweepGC \ -XX:MaxTenuringThreshold=10 \ -XX:SurvivorRatio=2 \ -XX:CMSInitiatingOccupancyFraction=60 \ -XX:+UseCMSInitiatingOccupancyOnly \ -XX:+CMSParallelRemarkEnabled \ -XX:+DisableExplicitGC \ -XX:+CMSClassUnloadingEnabled \ -XX:+PrintGCTimeStamps \ -XX:+PrintGCDetails \ -XX:+PrintTenuringDistribution \ -XX:+PrintGCApplicationConcurrentTime \ -XX:+PrintGCApplicationStoppedTime \ -XX:+PrintGCApplicationStoppedTime \ -XX:+PrintClassHistogram \ -XX:+ParallelRefProcEnabled \ -XX:SoftRefLRUPolicyMSPerMB=1 \ -verbose:gc \ -Xloggc:$GCLOGFILE" ``` --- ``` java version "1.6.0_18" Java(TM) SE Runtime Environment (build 1.6.0_18-b07) Java HotSpot(TM) Server VM (build 16.0-b13, mixed mode) Solaris 10/Sun Fire(TM) T1000 ```
2010/03/23
[ "https://Stackoverflow.com/questions/2497720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192275/" ]
Fixed in 1.6.0\_29: <http://www.oracle.com/technetwork/java/javase/6u29-relnotes-507960.html?ssSourceSiteId=ocomen> 1.6.0\_29 is not mentioned on the bug page itself ( <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6942989> ), so I thought it'd be useful to post the link there so the fact it's been fixed is discoverable.
I have reproduced this on 1.6.0\_19. If you run the sample application with these java arguments: -Xms8m -Xmx8m -XX:MaxPermSize=8m After 10 - 15 minutes it will produce an OutOfMemoryError. I have filed a bug report with Sun. They will let me know in due time if it has been accepted.
19,280,807
I'm looking to store some customer data in memory, and I figure the best way to do that would be to use an array of records. I'm not sure if that's what its called in C#, but basically I would be able to call `Customer(i).Name` and have the customers name returned as a string. In turing, its done like this: ``` type customers : record ID : string Name, Address, Phone, Cell, Email : string //Etc... end record ``` I've searched, but I can't seem to find an equivalent for C#. Could someone point me in the right direction? Thanks! :)
2013/10/09
[ "https://Stackoverflow.com/questions/19280807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2856410/" ]
Okay, well that would be defined in a `class` in C#, so it might look like this: ``` public class Customer { public string ID { get; set; } public string Name { get; set; } public string Address { get; set; } public string Phone { get; set; } public string Cell { get; set; } public string Email { get; set; } } ``` Then you could have a `List<T>` of those: ``` var customers = new List<Customer>(); customers.Add(new Customer { ID = "Some value", Name = "Some value", ... }); ``` and then you could access those by index if you wanted: ``` var name = customers[i].Name; ``` **UPDATE:** as stated by [`psibernetic`](https://stackoverflow.com/users/909954/psibernetic), the [`Record`](http://msdn.microsoft.com/en-us/library/dd233184.aspx) class in F# provides field level equality out of the gate rather than referential equality. This is a very important distinction. To get that same equality operation in C# you'd need to make this `class` a `struct` and then produce the operators necessary for equality; a great example is found as an answer on this question [What needs to be overridden in a struct to ensure equality operates properly?](https://stackoverflow.com/questions/1502451/what-needs-to-be-overriden-in-a-struct-to-ensure-equality-operates-properly).
Assuming you have a class which models your customers, you can simply use a List of customers. ``` var c = new List<Customers>() string name = c[i].Name ```
21,109,690
I am Currently Migrating from Dreamweaver to Sublime Text 3, Sublime has a very handy snippets feature. Could this work in a team workflow? Is it possible to synchronize everyone's snippets, Store all the snippets on a server and have every user synchronizes with that? After a Few hours of searching around, Any Help Greatly Appreciated.
2014/01/14
[ "https://Stackoverflow.com/questions/21109690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
### Sublime text uses files to store anything: configuration / plugins / snippets / ext. From the [docs](http://docs.sublimetext.info/en/latest/basic_concepts.html), the configuration folder: > > **Windows**: %APPDATA%\Sublime Text 3 > > **OS X**: ~/Library/Application Support/Sublime Text 3 > > **Linux**: ~/.Sublime Text 3 > > > So all you really need is to **synchronize that folder** with any sync tool you want. Examples with dropbox: * <http://www.alexconrad.org/2013/07/sync-sublime-text-3-settings-with.html> * <http://misfoc.us/post/18018400006/syncing-sublime-text-2-settings-via-dropbox> * <http://juhap.iki.fi/misc/using-dropbox-to-sync-sublime-text-settings-across-windows-computers/>
Try **[Syncrow](https://packagecontrol.io/packages/Syncrow/ "Syncrow")**, You can **create snippets** on the go and **sync them in all your systems**.
5,810,648
I'm trying to build a mobile web app and am intrigued by the "apple-mobile-web-app-capable" option, making the app feel a lot more native. The issue I'm having is that it's an app that lets a user browse through a bunch of content, some of which opens a new browser window outside the web app (on purpose). The problem is, when a user goes back to the web app, it re-launches and starts them from the home page. Has anyone found a way to avoid this complete reloading process?
2011/04/27
[ "https://Stackoverflow.com/questions/5810648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636064/" ]
ive got it working like this: ``` if(window.navigator.standalone === true) { var lastpage = localStorage.getItem('exitsatus'); if (lastpage==null){ lastpage = "index.html"; } if(document.referrer.length > 0 && document.referrer.indexOf("mysite.com") != -1){ var lastpageupdate = window.location; localStorage.setItem('exitsatus',lastpageupdate); } else { window.location = lastpage; } } ```
There is, but it's a bit of a hack and requires some JavaScript. What you want to do is at the end of each page load, save the current path in offline key-value storage. In your `head`, see if there's an entry for the URL and if so, load it up. What you want to ensure is that internal links disable this key so that you don't just jump to a link and then back again.
51,229,553
I am using simple html dom to get the contents of a table: ``` foreach($html->find('#maintable .table tr td') as $a) { $array[] = $a->plaintext; } print_r($array); ``` The array returned looks like this: ``` Array ( [0] => 1 [1] => 0xd35a2d8c651f3eba4f0a044db961b5b0ccf68a2d [2] => 309953166.54621424 [3] => 30.9953% [4] => 2 [5] => 0xe17c20292b2f1b0ff887dc32a73c259fae25f03b [6] => 200000001 [7] => 20.0000% [8] => 3 [9] => 0x0000000000000000000000000000000000000000 [10] => 129336426 [11] => 12.9336% ) ``` I would like to create a new multidimensional array from the array above that skips one row every three rows starting with the first row like this: ``` New Array ( [1] ['address'] => 0xd35a2d8c651f3eba4f0a044db961b5b0ccf68a2d ['amount'] => 309953166.54621424 ['percent'] => 30.9953% [2] ['address'] => 0xe17c20292b2f1b0ff887dc32a73c259fae25f03b ['amount'] => 200000001 ['percent'] => 20.0000% [3] ['address'] => 0x0000000000000000000000000000000000000000 ['amount'] => 129336426 ['percent'] => 12.9336% ``` ) In the new array, "address" represents [1] [5] and [9] from the original array. "amount" represents [2] [6] and [10], and "percent" represents [3] [7] and [11]. How can I accomplish this? Thank you
2018/07/08
[ "https://Stackoverflow.com/questions/51229553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9958157/" ]
You can use `array_chunk` to chunk the array. Use `array_reduce` to loop thru the chuncked array. Use `array_combine` to use the `$keys` array as the key. ``` $array = //Your array $keys = array( 'address', 'amount', 'percent' ); $result = array_reduce( array_chunk( $array, 4 ), function($c, $o) use ($keys) { $c[ array_shift($o) ] = array_combine( $keys, $o ); return $c; }, array() ); echo "<pre>"; print_r( $result ); echo "</pre>"; ``` This will result to: ``` Array ( [1] => Array ( [address] => 0xd35a2d8c651f3eba4f0a044db961b5b0ccf68a2d [amount] => 309953166.54621424 [percent] => 30.9953% ) [2] => Array ( [address] => 0xe17c20292b2f1b0ff887dc32a73c259fae25f03b [amount] => 200000001 [percent] => 20.0000% ) [3] => Array ( [address] => 0x0000000000000000000000000000000000000000 [amount] => 129336426 [percent] => 12.9336% ) ) ```
Given the input array in your example this should do what you have asked: ``` $newArray = []; for($i=1; $i<count($oldArray); $i=($i+4)){ $newArray[] = [ 'address' => (isset($oldArray[$i])) ? $oldArray[$i] : '', 'amount' => (isset($oldArray[($i+1)])) ? $oldArray[($i+1)] : '', 'percent' => (isset($oldArray[($i+2)])) ? $oldArray[($i+2)] : '', ]; } print_r($newArray); ``` Producing: ``` Array ( [0] => Array ( [address] => 0xd35a2d8c651f3eba4f0a044db961b5b0ccf68a2d [amount] => 309953166.54621424 [percent] => 30.9953% ) [1] => Array ( [address] => 0xe17c20292b2f1b0ff887dc32a73c259fae25f03b [amount] => 200000001 [percent] => 20.0000% ) [2] => Array ( [address] => 0x0000000000000000000000000000000000000000 [amount] => 129336426 [percent] => 12.9336% ) ) ```
15,030,723
I'd like to use [datatables](http://datatables.net/) in my rails application but I'd like to avoid prepraring JSON data by myself, so I'm looking for a gem that does it. Ideally I'd pass an ActiveRecored Relation and the gem generated JSON that could be consumed by datatables, for example: ``` class ItemsController < ApplicationController def index # I fetch data I need (taking into account authorization, search etc.) @items = Item.find_relevant_items respond_to do |format| # gem prepares JSON for datatables format.json { ItemDatatable.new(@items) } # ... end end end ``` I'm aware that there are several gems availabe. However, they don't suit me: [jquery-datatables-rails](https://github.com/rweng/jquery-datatables-rails) is just a wrapper for the JS and the others seem to be outdated or not maintained ([ajax-datatables-rails](https://github.com/JoelQ/ajax-datatables-rails), [rails\_datatables](https://github.com/phronos/rails_datatables), [simple\_datatables](https://github.com/gryphon/simple_datatables)). Do you know about any gem that would serve data for datatables?
2013/02/22
[ "https://Stackoverflow.com/questions/15030723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580346/" ]
Ruby's [JSON](http://www.ruby-doc.org/stdlib-1.9.3/libdoc/json/rdoc/JSON.html) module is built-in, just `require 'json'` at the top of a Ruby script to make it available. See "[How do I parse JSON with Ruby on Rails?](https://stackoverflow.com/questions/1826727/how-do-i-parse-json-with-ruby-on-rails)" for more information. Rails also includes JSON capability too. See "[Understanding Ruby and Rails: Serializing Ruby objects with JSON](http://www.simonecarletti.com/blog/2010/04/inside-ruby-on-rails-serializing-ruby-objects-with-json/)" for info using JSON and Rails. Rails is a fast-moving platform so that might be a bit out of date, but it should get you started. "[Lightning JSON in Rails](http://brainspec.com/blog/2012/09/28/lightning-json-in-rails/)" is a good read for things to pay attention to as you generate JSON. "[JSON implementation for Ruby](http://flori.github.com/json/)" is a great reference for Ruby and JSON also.
RABL and JBuilder both spring to mind. They are json template handlers and awesomely simple to use and both are equally powerfull enabling complete customisation of your json output. There are railscasts on them both <http://railscasts.com/episodes/320-jbuilder> <http://railscasts.com/episodes/322-rabl> and the sites <https://github.com/rails/jbuilder> <https://github.com/nesquena/rabl> Both are well maintained. Otherwise the datatables-rails gem is really the best option for you <http://railscasts.com/episodes/340-datatables?view=asciicast> **UPDATE 2** It's the gem you have already looked at As per railscast the gem is defined in the Gemfile ``` group :assets do gem 'jquery-datatables-rails', github: 'rweng/jquery-datatables-rails' gem 'jquery-ui-rails' end ``` I strongly urge you to watch that railscast (<http://railscasts.com/episodes/340-datatables?view=asciicast>) as there are other configurations needed.
855,747
I was wondering if anyone can point me in the right direction. I have an asp.net button with a click event (that runs some server side code). What i'd like to do is call this event via ajax and jquery. Is there any way to do this? If so, i would love some examples. Thanks in advance
2009/05/13
[ "https://Stackoverflow.com/questions/855747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56509/" ]
This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button: When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001\_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery. ``` $(document).ready(function() { $("input[id$='btnAwesome']").click(function() { // Do client side button click stuff here. }); }); ``` The id$= is doing a regex match for an id ENDING with btnAwesome. Edit: Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods. The gist of it is you create a **static** method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax. ``` $.ajax({ type: "POST", url: "PageName.aspx/MethodName", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Do something interesting here. } }); ``` I learned my WebMethod stuff from: <http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/> A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.
In the client side handle the click event of the button, use the ClientID property to get he id of the button: ``` $(document).ready(function() { $("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click( function() { $.get("/myPage.aspx",{id:$(this).attr('id')},function(data) { // do something with the data return false; } }); }); ``` In your page on the server: ``` protected void Page_Load(object sender,EventArgs e) { // check if it is an ajax request if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") { if (Request.QueryString["id"]==myButton.ClientID) { // call the click event handler of the myButton here Response.End(); } if (Request.QueryString["id"]==mySecondButton.ClientID) { // call the click event handler of the mySecondButton here Response.End(); } } } ```
29,386,116
I'm on Chrome Version 41.0.2272.101 m (newest), and this update is messed up. They put it, when you have inspector open, that any DOM change will flash with purple on the changed element (like in Firefox), but now I cannot inspect any hovered object (also like in FF, which is why I don't like to use it when doing front end developing). I'm talking about js triggered events, like superfish for instance. Before, I could hover the menu, and cover the menu with the inspector, and the menu would stay opened, and I could go in the inspector see what pseudoelements are created, change the paddings and such directly, and see the change. Now, when I hover the menu, and right click to inspect it, the menu closes, and I cannot inspect it! I tried dragging the inspector over, but nothing helped. This new 'feature' is annoying as hell. Is there a way to inspect js triggered events, without putting break points on elements (which works, but is kinda pain in the ass)?
2015/04/01
[ "https://Stackoverflow.com/questions/29386116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629127/" ]
In Chrome, press F12 to open the developer console, then click on Settings (cogwheel icon) or press F1: ![Dev tools Settings](https://i.stack.imgur.com/dPReZ.png) then find & check the "Emulate a focused page" option. ![Check Emulate a Focused Page Option](https://i.stack.imgur.com/12TxE.png) Update: as noted in comments, this option is now in another place. See [this](https://stackoverflow.com/a/64456947/1440076) answer.
You can set an interval that writes out the content of a given element in the JS console every second. Drop this in the console and open the dropdown. ``` setInterval(() => console.log(document.querySelector('.Select-menu-outer').outerHTML), 1000) ```
4,870
I'm writing a Telnet client of sorts in C# and part of what I have to parse are ANSI/VT100 escape sequences, specifically, just those used for colour and formatting (detailed [here](http://www.termsys.demon.co.uk/vtansi.htm#colors)). One method I have is one to find all the codes and remove them, so I can render the text without any formatting if needed: ``` public static string StripStringFormating(string formattedString) { if (rTest.IsMatch(formattedString)) return rTest.Replace(formattedString, string.Empty); else return formattedString; } ``` I'm new to regular expressions and I was suggested to use this: ``` static Regex rText = new Regex(@"\e\[[\d;]+m", RegexOptions.Compiled); ``` However, this failed if the escape code was incomplete due to an error on the server. So then this was suggested, but my friend warned it might be slower (this one also matches another condition (z) that I might come across later): ``` static Regex rTest = new Regex(@"(\e(\[([\d;]*[mz]?))?)?", RegexOptions.Compiled); ``` This not only worked, but was in fact faster to and reduced the impact on my text rendering. Can someone explain to a regexp newbie, why? :)
2008/08/07
[ "https://Stackoverflow.com/questions/4870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483/" ]
Do you really want to do run the regexp twice? Without having checked (bad me) I would have thought that this would work well: ``` public static string StripStringFormating(string formattedString) { return rTest.Replace(formattedString, string.Empty); } ``` If it does, you should see it run ~twice as fast...
I'm not sure if this will help with what you are working on, but long ago I wrote a regular expression to parse ANSI graphic files. ``` (?s)(?:\e\[(?:(\d+);?)*([A-Za-z])(.*?))(?=\e\[|\z) ``` It will return each code and the text associated with it. Input string: ``` <ESC>[1;32mThis is bright green.<ESC>[0m This is the default color. ``` Results: ``` [ [1, 32], m, This is bright green.] [0, m, This is the default color.] ```
24,678,856
I have a tableview controller class, a tableviewcell subclass and a uibutton subclass. I am creating an instance of the unbutton subclass in the tableviewcell subclass and initialize a button in a specific cell position. Then I am using this cell in the tableview controller class. Also I am trying to add an IBAction to the button. But it can't recognize the object of the uibutton subclass while everything else works fine. What am I doing wrong in the declaration? **tableviewcell.m** ``` #import "tableviewcell.h" #import "CustomCheckButton.h" CustomCheckButton *starbtn = [[CustomCheckButton alloc] init];; starbtn = [[CustomCheckButton alloc]initWithFrame:CGRectMake(243,0, 30, 30)]; ``` **tableviewcontroller.m** In the cellForRowAtIndexPath object startbtn won't be recognized: ``` #import "ScannedProductControllerViewController.h" #import "imageCellCell.h" tableviewcell*firstRowCell = (tableviewcell *)cell; [firstRowCell.prodimage setImage: [UIImage imageNamed:@"test1.jpg"]]; [firstRowCell.label1 setText:@"17.5"]; [firstRowCell.label2 setText:@"Score"]; [firstRowCell.basket setImage: [UIImage imageNamed:@"Basket.jpg"]]; // reference of the home button to the buttonclick method [firstRowCell.homebtn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside]; // reference of the favorites button to the buttonclick method [firstRowCell.starbtn addTarget:self action:@selector(clickFavButton:) forControlEvents:UIControlEventTouchUpInside]; ``` **CustomCheckButton.h** ``` #import <UIKit/UIKit.h> @interface CustomCheckButton : UIButton { BOOL _checked; } @property (nonatomic, setter = setChecked:) BOOL checked; -(void) setChecked:(BOOL) check; @end ```
2014/07/10
[ "https://Stackoverflow.com/questions/24678856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3211165/" ]
``` @interface TableViewCell : UITableViewCell @property (nonatomic, strong) CustomCheckButton *startButton; @end @implementation TableViewCell - (instancetype)init { self = [super init]; self.startButton = [[CustomCheckButton alloc]initWithFrame:CGRectMake(243,0, 30, 30)]; return self; } - (void)viewDidLoad { [super viewDidLoad]; [self.contentView addSubview:self.startButton]; } @end ```
First, why don't you create your cells in the storyboard as a prototype cell or inside of a XIB file. Then, create an IBAction to the button and respond to it in the cell. Finally, make a protocol for your cell that will inform the delegate when the button is tapped. You can then setup your table view controller as the delegate of the cells and respond to the button tapped. If you need to determine which cell you're working with, you can even pass the cell as a parameter of one of the protocol's methods you use.
23,268,176
I am trying to make login form using PHP and Mysql, my code is main\_login.html ``` <table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form name="form1" method="post" action="checklogin.php"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td colspan="3"><strong>Member Login </strong></td> </tr> <tr> <td width="78">Username</td> <td width="6">:</td> <td width="294"><input name="myusername" type="text" id="myusername"></td> </tr> <tr> <td>Password</td> <td>:</td> <td><input name="mypassword" type="text" id="mypassword"></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td><input type="submit" name="Submit" value="Login"></td> </tr> </table> </td> </form> </tr> </table> ``` checklogin.php ``` <?php $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name="test"; // Database name $tbl_name="members"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" //session_register('myusername'); $_SESSION['myusername'] = $myusername; //session_register('mypassword'); $_SESSION['mypassword'] = $mypassword; header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> ``` loginsucces.php ``` <?php session_start(); $myusername=''; if(isset($_SESSION[$myusername])){ header("location:main_login.html"); } ?> <html> <body> Login Successful<br> welcome <?php echo $_SESSION['myusername']?> </body> </html> ``` now on entering login credentials i want to display the welcome'user' but it is giving output as ===>Login Successful welcome ``` Notice: Undefined index: username in F:\xampp\htdocs\xampp\seesion\login_success.php on line 16 ```
2014/04/24
[ "https://Stackoverflow.com/questions/23268176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2372786/" ]
Add ``` session_start(); ``` in top of **checklogin.php**
You have not started session on checklogin.php page and you are using session here.. so start session here before using it.. ``` session_start(); $_SESSION['myusername'] = $myusername; //session_register('mypassword'); $_SESSION['mypassword'] = $mypassword; ``` It works well for me. also use `type="password" in password input field.`
26,390,165
I have regular navigation and mobile navigation that collapses. Whenever the navigation switches from mobile to regular, the regular navigation shifts down from where it was originally. I am befuddled as to why this is happening and how to fix it. Thanks so much for taking the time to look at this. It is only a problem in Chrome and Safari, but not Firefox. Example image: <http://wildmeasure.com/qualitymetalcraft.com/qmcnav.jpg>
2014/10/15
[ "https://Stackoverflow.com/questions/26390165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3525923/" ]
You should avoid the use of `length` and write your function using `foldl` (or `foldl'`): ``` fromDigits :: [Int] -> Integer fromDigits ds = foldl (\s d -> s*10 + (fromIntegral d)) 0 ds ``` From this a generalization to any Foldable should be clear.
If you want to "fold with state", probably Traversable is the abstraction you're looking for. One of the methods defined in Traversable class is ``` traverse :: Applicative f => (a -> f b) -> t a -> f (t b) ``` Basically, traverse takes a "stateful function" of type `a -> f b` and applies it to every function in the container `t a`, resulting in a container `f (t b)`. Here, `f` can be `State`, and you can use traverse with function of type `Int -> State Integer ()`. It would build an useless data structure (list of units in your case), but you can just discard it. Here's a solution to your problem using Traversable: ``` import Control.Monad.State import Data.Traversable sumDigits :: Traversable t => t Int -> Integer sumDigits cont = snd $ runState (traverse action cont) 0 where action x = modify ((+ (fromIntegral x)) . (* 10)) test1 = sumDigits [1, 4, 5, 6] ``` However, if you really don't like building discarded data structure, you can just use `Foldable` with somewhat tricky `Monoid` implementation: store not only computed result, but also `10^n`, where `n` is count of digits converted to this value. This additional information gives you an ability to combine two values: ``` import Data.Foldable import Data.Monoid data Digits = Digits { value :: Integer , power :: Integer } instance Monoid Digits where mempty = Digits 0 1 (Digits d1 p1) `mappend` (Digits d2 p2) = Digits (d1 * p2 + d2) (p1 * p2) sumDigitsF :: Foldable f => f Int -> Integer sumDigitsF cont = value $ foldMap (\x -> Digits (fromIntegral x) 10) cont test2 = sumDigitsF [0, 4, 5, 0, 3] ``` I'd stick with first implementation. Although it builds unnecessary data structure, it's shorter and simpler to understand (as far as a reader understands `Traversable`).
52,723,273
Now I have updated all the dependencies to the latest version then I have faced this issues. > > The library com.google.android.gms:play-services-basement is being > requested by various other libraries at [[15.0.1,15.0.1]], but > resolves to 16.0.1. Disable the plugin and check your dependencies > tree using ./gradlew :app:dependencies. > > > ``` classpath 'com.google.gms:google-services:4.0.2' ``` and ``` implementation 'com.google.firebase:firebase-messaging:17.3.3' implementation "com.google.android.gms:play-services-maps:16.0.1" implementation "com.google.android.gms:play-services-location:16.0.1" ``` Please help me to resolve this issue... Thanks in Advance...
2018/10/09
[ "https://Stackoverflow.com/questions/52723273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5230881/" ]
**Android (Project - level build.gradle)** ``` buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' classpath 'com.google.gms:google-services:4.0.0' } } allprojects { repositories { google() jcenter() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } subprojects { project.configurations.all { resolutionStrategy.eachDependency { details -> if (details.requested.group == 'com.android.support' && !details.requested.name.contains('multidex') ) { details.useVersion "26.1.0" } } } } task clean(type: Delete) { delete rootProject.buildDir } ``` **Android (App - level build.gradle)** ``` apply plugin: 'com.android.application' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion 28 lintOptions { disable 'InvalidPackage' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.chatflutterapp.fullterchat" minSdkVersion 16 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' compile 'com.google.firebase:firebase-core:16.0.4' } apply plugin: 'com.google.gms.google-services' com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true ```
I had same problem, in my case, following these steps made it run: > > 1) comment all firebase dependencies > > > 2) comment all firebase usages from classes > > > 3) clean and rebuild project > > > 4) uncomment all commented lines > > >
316,352
In Java, you can qualify local variables and method parameters with the final keyword. ``` public static void foo(final int x) { final String qwerty = "bar"; } ``` Doing so results in not being able to reassign x and qwerty in the body of the method. This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?
2008/11/25
[ "https://Stackoverflow.com/questions/316352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32174/" ]
In the case of local variables, I tend to avoid this. It causes visual clutter, and is generally unnecessary - a function should be short enough or focus on a single impact to let you quickly see that you are modify something that shouldn't be. In the case of magic numbers, I would put them as a constant private field anyway rather than in the code. I only use final in situations where it is necessary (e.g., passing values to anonymous classes).
Although it creates a little clutter, it is worth putting `final`. Ides e.g eclipse can automatically put the `final` if you configure it to do so.
39,571,231
How I would check internet connection in Angular2 at the time of API hitting, whenever in my app API is hit to server sometimes user is offline (i mean without internet connection) so how would i check the internet connectivity ? is there some special status code for internet connectivity ? or something else ? PS:- i found `navigator.onLine` in angularJs but seems not working in angular2. * Source - [How to check internet connection in AngularJs](https://stackoverflow.com/a/16242703/5043867) update ====== as sudheer suggested in answer below `navigator.onLine` in working with angular2 but still not working properly why ? `[working example here](http://plnkr.co/edit/3Mw5c9DAU6d0Gnl9CtKP?p=preview)`
2016/09/19
[ "https://Stackoverflow.com/questions/39571231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5043867/" ]
At first, j2L4e's answer didn't work for me (testing in Chrome). I tweaked slightly by surrounding my bool in brackets in the ngIf and this ended up working. `<md-icon class="connected" mdTooltip="No Connection" *ngIf="!(isConnected | async)">signal_wifi_off</md-icon>` ``` import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import 'rxjs/Rx'; @Component({ selector: 'toolbar', templateUrl: './toolbar.component.html', styleUrls: ['./toolbar.component.css'] }) export class ToolbarComponent implements OnInit { isConnected: Observable<boolean>; constructor() { this.isConnected = Observable.merge( Observable.of(navigator.onLine), Observable.fromEvent(window, 'online').map(() => true), Observable.fromEvent(window, 'offline').map(() => false)); } ngOnInit() { } } ```
Go with this simple Hack. Working in angular 5 or later ``` constructor(){ setInterval(()=>{ if(navigator.onLine){ //here if it is online }else{ //here if it is offline } }, 100) } ``` write this in constructor of app.component.ts or your app bootstrap No need of any external library ..