qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
21,734,677 | I have a code like this:
```js
<select id='chapter'>
<option onclick="return my_function('1')" value='1'>1</option>
<option onclick="return my_function('2')" value='2'>2</option>
<option onclick="return my_function('3')" value='3'>1</option>
</select>
```
When user click on select it trigger one of options `onclick` events.
I really don't know what to do.
Here is my code in work and see problem(check select tags):
<http://animup.net/manga/claymore/c127/#1> | 2014/02/12 | [
"https://Stackoverflow.com/questions/21734677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1489083/"
] | Here is a standard SQL way of doing this:
```
delete from t
where Id1 > Id2 and
exists (select 1
from t t2
where t2.Id1 = t.Id2 and
t2.Id2 = t.Id1 and
t2.Name1 = t.Name2 and
t2.Name2 = t.Name1 and
t2.DOB1 = t.DOB2 and
t2.DOB2 = t.DOB1
);
``` | You could use an `INNER JOIN` to pair up any rows with transposed `Id1` and `Id2` values, filter down to those that are actually duplicates, select all but one of the duplicate rows, and then send the results to a `DELETE`.
```
DELETE T1
FROM [TableName] T1
-- Pair up the duplicate rows
INNER JOIN [TableName] T2
ON T1.Id1 = T2.Id2
AND T1.Id2 = T2.Id1
WHERE T1.Id1 > T1.Id2 -- Only delete the row with the higher "Id1" value
-- Filter out any rows that are not actually duplicates
AND T1.Name1 = T2.Name1
AND T1.Name2 = T2.Name2
AND T1.Name2 = T2.Name2
AND T1.DOB1 = T2.DOB1
AND T1.DOB2 = T2.DOB2
``` |
10,552,446 | I am adding the following codes to add a footer with a button to perform an action. i am not able to re-size the button to the size of the cell. The change in the CGRectMake(0, 0, 300,44) value is not affecting the change of the footer appears can any one help me. I am using a table having more session. i don't want a footer for every session instead i need at the end of the table so i inserted the following code.
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
//...
footerView = [[UIView alloc] init];
UIButton* Logoutbutton = [UIButton buttonWithType:UIButtonTypeCustom];
[Logoutbutton setTitle:@"Logout" forState:UIControlStateNormal];
NSLog(@"cell width : %d",cell.contentView.frame.size.width);
[Logoutbutton setFrame:CGRectMake(0, 0, 300,44)];
[Logoutbutton setBackgroundImage:[UIImage imageNamed:@"LogoutBgImage.png"]
forState:UIControlStateNormal];
[Logoutbutton setBackgroundColor:[UIColor clearColor]];
[Logoutbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[Logoutbutton addTarget:self action:@selector(LogoutbuttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
Settingstable.tableFooterView = Logoutbutton;
return cell;
}
- (void)LogoutbuttonPressed: (UIButton*) button
{
//some action
}
```
Can any one help me to fix this issue | 2012/05/11 | [
"https://Stackoverflow.com/questions/10552446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063216/"
] | You Don't need to add a button to uitableview , instead add it to the footer of the tableview for which you will have to pass a view to the delegate method of tableview :-
```
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
```
You may read this [tutorial](http://blog.blackwhale.at/?p=104) as it has same requirement as yours. | use this way for footer of tableview
```
self.tableView.tableFooterView = myCustomFooterView
```
and for footer view of whole table,use
```
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
```
and read more about it here
<http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITableViewDelegate_Protocol/Reference/Reference.html>
and if you wan't footer of only one cell, then implement a custom cell, and use layoutsubviews to change the cell settings, for custom cell use this link
<http://www.e-string.com/content/custom-uitableviewcells-interface-builder>
<http://www.galloway.me.uk/tutorials/custom-uitableviewcell/>
<http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html> |
885,906 | I have a switch `D-Link DGS-1210` with 52 ports. There is a device connected to the switch that shall be updated. The update requires a TFTP transfer between my PC and the device.
Unfortunately the switch drops the UDP packet to port 69 that should initiate the transfer. All other UDP packets go through. I have monitored the traffic with Wireshark to verify this.
There are no VLANs configured.
Is there any option to detect, why UDP packets to the port 69 are not forwarded?
*The TFTP transfer is not intended to update the `D-Link DGS-1210` but a device connected to it.*
**Edit:**
I have connected a dumb hub (each packet is repeat at all ports, NO intelligence) at the switch. The hub connects
* the device
* the switch
* a PC with Wireshark, let's call it Wireshark B
At the PC I run the TFTP client and Wireshark, let's call ist Wireshark A. The device implements the TFTP server, even if there is often the other way round.
I can see the UDP packet to port 69 at "Wireshark A" to the correct IP address. I cannot see the same packet at "Wireshark B". All other packets to the same IP address are passed through.
**Edit:** The problem has been reproduced with a different PC at the same switch.
The TFTP communication from any PC is without a problem when I replace the `D-Link DGS-1210` with a different switch. Unfortunately this requires additional cables and can be only used as a temporary workaround. But we can exclude the doubt about PC based firewalls. | 2015/03/05 | [
"https://superuser.com/questions/885906",
"https://superuser.com",
"https://superuser.com/users/45542/"
] | If you'd like to consider alternatives, [Dropbox supports differential file sync](https://www.dropbox.com/en/help/8) on their desktop and web clients. Alternatively, if you are so inclined, you could achieve this yourself by using [xdelta](http://xdelta.org/).
`xdelta` creates binary diff files. You could upload the huge PST file to Google Drive and keep a copy of the version that you uploaded somewhere safe on your computer or backup disk.
Now whenever you feel like syncing the changes made to the PST file (say once every 24 hours) you create a [delta file](http://www.ehow.com/facts_7470315_delta-file_.html) by running [this command](https://code.google.com/p/xdelta/wiki/CommandLineSyntax) (assuming you use a Windows system):
```
xdelta -e -s %PATH_TO_BACKUP_PST_FILE% %PATH_TO_MODIFIED_PST_FILE% > deltafile.delta
```
A new file named `deltafile.delta` will be created that contains just the modifications made to the original 15 GB file. The delta file will hopefully be small enough to be uploaded easily. However, if encryption is enabled, the delta file sizes might end up being larger.
You can automate this process by using batch files and the Task Scheduler or just run it manually.
To re-create the modified file from the delta file and backup PST file, run this command:
```
xdelta -d -s %PATH_TO_BACKUP_PST_FILE% deltafile.delta > modified-file.pst
``` | As of [2012](https://superuser.com/questions/652483/cloud-backup-for-large-truecrypt-container), Google Drive apparently still did not support differential file sync. If that's still the case, Google would sync the entire 15 GB file every time it changes.
It sounds like you're using Outlook to back up your Google Apps Email, then you want to back up the Outlook PST file to Google Drive. You may want to take a step back and consider what you are trying to achieve.
For example:
1. Do you want access to your old email in the event that Google has a massive outage? If so, then syncing the PST file to Google Drive doesn't necessarily help in that scenario.
2. Are you trying to protect yourself in the event that your Google account is compromised? In that case, the PST file stored in the cloud would be worthless because someone may have tampered with it.
Using Google Drive to store your PST-file backup of Google Apps Email only seems reasonable to me if Google Drive is syncing the PST file to at least one other device that you own. But in that case, you could use some other backup system like CrashPlan, which lets you use your own machines as backup targets for free.
But let's suppose that either the email in your PST file is for a different email account than Google Apps Email, or you have a great reason for backing up Google Apps Email to Outlook PST, then uploading the PST file back to Google (Drive).
One solution to your file syncing problem is built into Outlook. If you turn on [AutoArchive](https://support.office.com/en-us/article/AutoArchive-settings-explained-444bd6aa-06d0-4d8f-9d84-903163439114), your old emails will periodically be "aged out" into a separate PST file. This will allow you to shrink the main PST file enough that it can be synced in a reasonably small amount of time, while the larger archive PST file--which is only modified during an AutoArchive operation--will be synced much less frequently.
Another solution is to manually create a new PST file every once in a while and move all your old messages to that PST file (for example, at the beginning of each year). Assuming the PST files are purely for archival purposes, you could then unmount the new PST file so Outlook will make no future modifications, compact your main PST file, and let the main PST file accumulate mail for another year. This may not be quite as convenient as the first solution, but it will still be better than trying to sync a 15 GB file several times a day. As a nice side effect, it also decreases the chances that your entire email backup may be lost in the event that a single very large PST file is somehow massively corrupted. |
3,227,870 | By "common script startup sequence", what I mean is that in the majority of pages on my site, the first order of business is to consult 3 specific files (via `include()`), which centrally define constants, certain functions used in many scripts, and a class or two, as well as providing the database credentials. I don't know if there's a more standard term for such a setup.
What I want to know is whether it's possible to have too many of these and make things slower as a result. I know that using `include()` has a certain amount of overhead because it's another file to look for in the filesystem, parse, and execute. If there is such a thing as too many `include`s, I want to know whether I am anywhere near that point. N.B. Some of my pages `include()` still more scripts that they specifically, individually need (for example, a script that defines a function used by only a few pages), and I do not count these occasional extra `include`s, which are used reasonably sparingly anyway. I'm only worrying about the 3 `include`s that occur on the majority of pages and set everything up.
What are the 3 `include`s?
Two of them are outside of webroot. `common.php` defines a bunch of functions, classes and other things that do not vary between the development and production sites. `config.php` defines various constants and paths that are different in the development and production sites (which database to connect to, among other things). Of course, it's desirable for this file in particular to be outside of webroot. `config.php` `include()`s `common.php` at the bottom.
The other one is inside webroot and contains a single line:
```
include [path to appropriate directory]/config.php
```
The directory differs between the development and production sites.
(Feel free to question the rationale behind setting up the `includes` this way, but I feel that this does provide a good, reliable system for preparing to execute each page, and my question is about whether it is bad to have that many `include`s as a baseline on each page.) | 2010/07/12 | [
"https://Stackoverflow.com/questions/3227870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340819/"
] | Use [`APC`](http://php.net/manual/en/book.apc.php) and your worries go away. The [**opcode**](http://en.wikipedia.org/wiki/Opcode) of your files will be **cached in the RAM** and everything will go **super fast**. :) [Facebook does this](http://www.scribd.com/doc/88689/ApcFacebook) so it'll definitely help you to **scale**.
Because you may not notice any difference between 1 include or 50 in terms of speed, but for an application with **high concurrency, I/O** can be a huge **bottleneck**. So the key is not speed, but scaling. | Or if you by any chance using Windows as OS, you can use [WinCache](http://www.iis.net/download/wincacheforphp).
<http://php.net/manual/en/book.wincache.php> |
37,377,310 | I have a node mongo app. Now I want to show audit trail for some specific crud events which are happening in the application.
What would be the best approach for solving this problem ?
I have considered of creating a new collection and service which would be called in each method in node app for logging the operations. | 2016/05/22 | [
"https://Stackoverflow.com/questions/37377310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646909/"
] | It's better to use a different schema having all the logs that you want to store for particular actions.
```
// schema
var schema = new Schema({
actionType: {type: String, require: true},
userId: { type: Schema.Types.ObjectId, required: true },
userType: { type: String, required: true },
message: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
}, options);
```
Here you can log your activity logs with
>
> What action have been taken.
> Which user.
> And the message that you want to store with that action etc.
>
>
> | you can add a middleware to you app which adds a [bunyan](https://github.com/trentm/node-bunyan) child logger to each request with some unique id (probably `uuid`)
here is some sample code to attach a logger to each request with unique id,
whenever you will print something using this logger, this uuid will also be printed automatically so you can trace each request using this id
```
var bunyan = require('bunyan');
var uuid = require('uuid');
var logger = bunyan.createLogger({name: 'some name'});
function loadlogger(req, res, next) {
req.log = logger.child({request_id: uuid.v4()});
next()
}
app.use(loadLogger);
```
and you can log when ever you want as follow
```
req.log.info({keys: values}, "message");
req.log.warn({keys: values}, "message");
req.log.error({keys: values}, "message");
```
You can refer to complete documentation [bunyan logger](https://github.com/trentm/node-bunyan) |
32,304,067 | I've been through the introductory tutorial for Django successfully using SQLite as per the instructions. However, for my real project I want to use MySQL, so I deleted the tutorial project files and started with a fresh setup. The trouble is that when I run "python manage.py migrate" I get the following MySQL error:
>
> \_mysql\_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
> version for the right syntax to use near '%s' at line 1").
>
>
>
I have the following in the site settings database section:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'vocabulator$database',
'USER': 'vocabulator',
'PASSWORD': '<password>',
'HOST': 'mysql.server',
}
}
```
I connected to this database successfully in Bash using, 'mysql --user=vocabulator --host=mysql.server --password=<password> "vocabulator\$database" ', so it appears I have entered these setting details correctly.
I also followed an instruction on setting up database bindings for Python 3, which also appeared to work successfully. It was on either the Django documentation pages or the PythonAnywhere equivalent, but unfortunately I cannot locate the page reference again.
I haven't written any MySQL queries myself yet, so any incorrect ones that are being made must be coming from manage.py, so what could be the cause? The complete error trace is quoted below:
```
Operations to perform: Synchronize unmigrated apps: staticfiles, messages Apply all migrations: contenttypes, sessions, admin, auth Synchronizing apps without migrations: Creating tables...
Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial...Traceback (most recent call last): File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 124, in execute
return self.cursor.execute(query, args) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/cursors.py", line 184, in execute
self.errorhandler(self, exc, value) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/connections.py", line 37, in defaulterrorhandler
raise errorvalue File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/cursors.py", line 171, in execute
r = self._query(query) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/cursors.py", line 330, in _query
rowcount = self._do_query(q) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/cursors.py", line 294, in _do_query
db.query(q)
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1")
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute() File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/core/management/base.py", line 393, in run_from_argv
self.execute(*args, **cmd_options) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/core/management/base.py", line 444, in execute
output = self.handle(*args, **options) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 222, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/migrations/executor.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/migrations/executor.py", line 148, in apply_migration
state = migration.apply(state, schema_editor) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/migrations/migration.py", line 115, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/migrations/operations/models.py", line 59, in database_forwards
schema_editor.create_model(model) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 289, in create_model
self.deferred_sql.extend(self._model_indexes_sql(model)) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/backends/mysql/schema.py", line 55, in _model_indexes_sql
self.connection.cursor(), model._meta.db_table File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/backends/mysql/introspection.py", line 142, in get_storage_engine
"WHERE table_name = %s", [table_name]) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/utils/six.py", line 658, in reraise
raise value.with_traceback(tb) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 124, in execute
return self.cursor.execute(query, args) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/cursors.py", line 184, in execute
self.errorhandler(self, exc, value) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/connections.py", line 37, in defaulterrorhandler
raise errorvalue File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/cursors.py", line 171, in execute
r = self._query(query) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/cursors.py", line 330, in _query
rowcount = self._do_query(q) File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-packages/MySQLdb/cursors.py", line 294, in _do_query
db.query(q) django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server v ersion for the right syntax to use near '%s' at line 1") Exception ignored in: <bound method Cursor.__del__ of <MySQLdb.curso rs.Cursor object at 0x7feec394b940>> Traceback (most recent call last): File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-p ackages/MySQLdb/cursors.py", line 67, in __del__ File "/home/vocabulator/.virtualenvs/django18/lib/python3.4/site-p ackages/MySQLdb/cursors.py", line 73, in close ReferenceError: weakly-referenced object no longer exists (django18)03:29 ~/mysite $ mysql --user=vocabulator --host=mysql.server --p mysql: ambiguous option '--p' (pager, plugin_dir)
``` | 2015/08/31 | [
"https://Stackoverflow.com/questions/32304067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/859023/"
] | As I said in my comment above, I found the page which had instructed me on how to install drivers. It is this one:
<https://www.pythonanywhere.com/wiki/UsingMySQL>
However, this Wiki page is a little dated now and it instructed me to install the MySQL connector version 2.0.1. The current version is now 2.0.4. The old version had a bug which meant it would not operate with Django 1.8, as stated here:
<http://bugs.mysql.com/bug.php?id=76752>
By version 2.0.4 this bug appears to have been corrected.
The line in the PythonAnywhere Wiki page referenced above should change to:
pip3.4 install <https://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-2.0.4.tar.gz>
Once I ran this, the migration appears to have worked successfully on my Django installation. | i have try this,and works...
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database',
'USER': 'vocabulator',
'PASSWORD': '<password>',
'HOST': 'mysql.server',
}
}
``` |
44,271,263 | I'm creating a layout for a newsletter. Usually this has to be pretty static but I'm using the Mailchimp guideline to achieve some responsiveness. It works well but the problem is that I would like the second image to come before the text (the problem is very obvious in the example link, it's hard to explain). Basically I would like to achieve something like you could do with Bootstrap using push and pull for example where an image that is placed second becomes first when resizing.
So image and then text when the layout is a single column.
Example: <https://codepen.io/SergiOca/pen/vmqMoZ?editors=1010>
```
@media only screen and (max-width: 480px){
#templateColumns{
width:100% !important;
}
.templateColumnContainer{
display:block !important;
width:100% !important;
}
.columnImage{
height:auto !important;
max-width:480px !important;
width:100% !important;
}
.leftColumnContent{
font-size:16px !important;
line-height:125% !important;
}
.rightColumnContent{
font-size:16px !important;
line-height:125% !important;
}
}
<table border="0" cellpadding="0" cellspacing="0" width="600" id="templateColumns">
<tr>
<td align="center" valign="top" width="50%" class="templateColumnContainer">
<table border="0" cellpadding="10" cellspacing="0" width="100%">
<tr>
<td class="leftColumnContent">
<img src="http://placekitten.com/g/480/300" width="280" style="max-width:280px;" class="columnImage" />
</td>
</tr>
</table>
</td>
<td align="center" valign="top" width="50%" class="templateColumnContainer">
<table border="0" cellpadding="10" cellspacing="0" width="100%">
<tr>
<td class="rightColumnContent">
<p style ="font-size:21px; color:#009DE0; width: 125px; line-height: 22px;";> Selección de profesionales en plantilla o freelance.</p>
<p style="font-size: 13px; line-height: 19px; width: 218px;"> A partir de un Job description acordado con el cliente, procedemos a entrevistar y a validar técnicamente a los candidatos que cumplan con los requisitos técnicos y personales, previamente establecidos.</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="600" id="templateColumns">
<tr>
<td align="center" valign="top" width="50%" class="templateColumnContainer">
<table border="0" cellpadding="10" cellspacing="0" width="100%">
<tr>
<td class="leftColumnContent">
<p style ="font-size:21px; color:#009DE0; width: 125px; line-height: 22px;";> Selección de profesionales en plantilla o freelance.</p>
<p style="font-size: 13px; line-height: 19px; width: 218px;"> A partir de un Job description acordado con el cliente, procedemos a entrevistar y a validar técnicamente a los candidatos que cumplan con los requisitos técnicos y personales, previamente establecidos.</p>
</td>
</tr>
</table>
</td>
<td align="center" valign="top" width="50%" class="templateColumnContainer">
<table border="0" cellpadding="10" cellspacing="0" width="100%">
<tr>
<td class="rightColumnContent">
<img src="http://placekitten.com/g/480/300" width="280" style="max-width:280px;" class="columnImage" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="600" id="templateColumns">
<tr>
<td align="center" valign="top" width="50%" class="templateColumnContainer">
<table border="0" cellpadding="10" cellspacing="0" width="100%">
<tr>
<td class="leftColumnContent">
<img src="http://placekitten.com/g/480/300" width="280" style="max-width:280px;" class="columnImage" />
</td>
</tr>
</table>
</td>
<td align="center" valign="top" width="50%" class="templateColumnContainer">
<table border="0" cellpadding="10" cellspacing="0" width="100%">
<tr>
<td class="rightColumnContent">
<p style ="font-size:21px; color:#009DE0; width: 125px; line-height: 22px;";> Selección de profesionales en plantilla o freelance.</p>
<p style="font-size: 13px; line-height: 19px; width: 218px;"> A partir de un Job description acordado con el cliente, procedemos a entrevistar y a validar técnicamente a los candidatos que cumplan con los requisitos técnicos y personales, previamente establecidos.</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
``` | 2017/05/30 | [
"https://Stackoverflow.com/questions/44271263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6738021/"
] | What you need my son is direction in life.
You can apply the css property `direction` to swap the order of the table cells. `Direction` can be applied to text or inline-block elements.
You can apply it different ways.
```
<row dir="rtl">
<td dir="rtl">
.main-content {direction: rtl; /* Right to Left */}
```
This is a sample of code how the row or td could be applied:
```
<!-- header -->
<container class="header">
<row dir="rtl">
<columns large="6" small="12" class="text-right" dir="rtl">
<p class="text-right" style="color: #432a6f; font-size: 12px; text-decoration: underline;"><a href="<%@ include view='MirrorPageUrl' %>" target="_blank">View this email on the web</a></p>
</columns>
<columns large="6" small="12" dir="rtl">
<a href="http://example.com" target="_blank"><img style="display: inline-block" border="0" alt="Image name" src="http://example.com/sample.png" width="184" height="45"></a>
</columns>
</row>
</container>
<!-- .header -->
```
You can try rtl ot ltr inherit from parent elements.
I would suggest placing direction on a class for the tables in a @media query so that you can swap them in mobile view. Something like this:
```
@media only screen and (max-width: 600px) {
.leftColumnContent {direction: rtl}
}
```
For more information on direction, check out:
<https://css-tricks.com/almanac/properties/d/direction/>
Good luck. | This is what you are after. I have taken one table of yours and given an example of how column swapping can be done. You will need to keep both the elements together for it to work.
The method used here is called hybrid. Both columns are created using div's which is encased in a td
```
<td valign="top" bgcolor="#FFFFFF" class="templateColumnContainer" style="padding:0px;text-align: center; vertical-align: top; font-size: 0px; direction:rtl;">
```
This td has direction which will tells everytrhing inside the div to be right to left (*direction:rtl*)
Next each columns are created using div's which are 50% width of the container td.
```
<div style="width:100%;max-width:280px;display: inline-block; vertical-align: top; direction:ltr;">
</div>
```
These div's have a max width of 280px, width of 100% and direction set to left to right (*direction:ltr*)
Everything inside the div can be coded as 100% width table.
I have added what people call ghost columns. This is Outlook conditional statement that tells outlook that this is a column.
```css
@media only screen and (max-width: 480px){
#templateColumns{
width:100% !important;
}
.templateColumnContainer{
display:block !important;
width:100% !important;
}
.columnImage{
height:auto !important;
max-width:480px !important;
width:100% !important;
}
.leftColumnContent{
font-size:16px !important;
line-height:125% !important;
}
.rightColumnContent{
font-size:16px !important;
line-height:125% !important;
}
.hundred{width:100% !important;}
}
```
```html
<table border="0" cellpadding="0" cellspacing="0" width="600" id="templateColumns">
<tr>
<td valign="top" bgcolor="#FFFFFF" class="templateColumnContainer" style="padding:0px;text-align: center; vertical-align: top; font-size: 0px; direction:rtl;">
<div style="width:100%;max-width:280px;display: inline-block; vertical-align: top; direction:ltr;">
<table border="0" cellpadding="10" cellspacing="0" width="100%">
<tr>
<td class="rightColumnContent">
<p style ="font-size:21px; color:#009DE0; line-height: 22px;"> Selección de profesionales en plantilla o freelance.</p>
<p style="font-size: 13px; line-height: 19px;"> A partir de un Job description acordado con el cliente, procedemos a entrevistar y a validar técnicamente a los candidatos que cumplan con los requisitos técnicos y personales, previamente establecidos.</p>
</td>
</tr>
</table>
</div>
<!--[if (gte mso 9)|(IE)]>
</td><td width="50%" align="left" valign="top">
<![endif]-->
<div style="width:100%;max-width:280px; display: inline-block; vertical-align: top; direction:ltr;">
<table border="0" cellpadding="10" cellspacing="0" width="100%">
<tr>
<td class="leftColumnContent">
<img src="http://placekitten.com/g/480/300" width="280" style="max-width:280px;" class="columnImage" />
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
```
For the second row of code you can swap the divs around to get the desired result.
Let me know if any of this didnt make sense or you want me to explain further.
Cheers |
52,473,299 | I'm trying add this transaction named `placeOrder` i want to add a `Customer` participant
before creating `Order` asset and map its relationship with the `Order` asset while processing this transaction. But I'm getting customer not defined error. Can anybody help? Thanks.
My models
```
namespace org.isn.customer
participant Customer identified by email {
o String firstName
o String lastName
o String email
o String password
}
enum Status{
o ACTIVE
o OFF_THE_ROAD
}
asset Vehicle identified by serial {
o String brand
o String model
o String color
o Status status
o Double price
o String serial
}
asset Order identified by orderId{
o String orderId
o Vehicle item
--> Customer customer
}
transaction PlaceOrder {
o String orderId
--> Vehicle item
o Customer customer
}
```
script.js
```
/**
* @param {org.isn.shop.PlaceOrder}orderRequest
* @transaction
*/
async function placeOrder(orderRequest){
const factory = getFactory();
const customerRegistry = await getParticipantRegistry("org.isn.customer.Customer");
const customerExists = await customerRegistry.exists(orderRequest.customer.email);
if(!customerExists){
const customer = factory.newResource("org.isn.customer","Customer",orderRequest.customer.email);
customer.firstName = orderRequest.customer.firstName;
customer.lastName = orderRequest.customer.lastName;
customer.email = orderRequest.customer.email;
customer.password = orderRequest.customer.password;
await customerRegistry.add(customer);
}else{
const customer = await customerRegistry.get(orderRequest.customer.email);
}
const order = await factory.newResource("org.isn.shop","Order",orderRequest.orderId);
order.customer = customer.getIdentifier();
order.item = orderRequest.item;
const orderRegistry = await getAssetRegistry("org.isn.shop.Order");
await orderRegistry.add(order);
const PlaceOrderEvent = factory.newEvent("org.isn.shop","PlaceOrderEvent");
placeOrderEvent.order = order;
emit(placeOrderEvent);
}
``` | 2018/09/24 | [
"https://Stackoverflow.com/questions/52473299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10341923/"
] | * Go to "->About This Mac".
* Click on "System Report" and select "USB".
* Find your phone and the "Serial Number" field is what you are after.
* Copy this value and paste it into the developer portal when you register a new device; you will need to insert a - after the 8th digit.
You can also get the "identifier" from the Xcode "devices" window or have Xcode update the portal directly.
[](https://i.stack.imgur.com/kf3gJ.png) | 1.Connect iPhone to Mac
2.Go to About This Mac
3.Click on "System Report" and select "USB" from left panel.
4.Find your iphone and look for the "Serial Number" field. This is what you need.
5.Copy this "Serial Number" and register the device in the developer portal. Make sure developer portal recognizes the device model. (As the developer portal recognizes the device model for a valid UDID when registering the device).
6. The serial number will be without hyphen. Make sure to add hyphen after first 8 characters. Example: XXXXXXXX-XXXXXXXXXXXXXXXX |
18,824,598 | I have a form in Struts 1.2 where I have text boxes (text box created using struts html tag) . I have retrieved the values for this text box from data base and then put in session attribute (`session.setAttribute("UserInfo",userinfoobj)`) now I wants to get values from session attribute and set this value as value of text box | 2013/09/16 | [
"https://Stackoverflow.com/questions/18824598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2572688/"
] | You didn't provide full information, but this is the most likely scenario:
By the time the store has loaded, `items` is no longer an array of configuration options, because the container has already processed them. Instead, you need to call `me.add()`, since items is now a MixedCollection and the configuration processing stage has passed. | You could try it like this:
```
var items = [];
var arrayVals = [];
var self = this;
me.getUserCompanyLogStore().load({
callback: function (records, operation, success) {
success: {
Ext.Array.each(records, function (record, index, array) {
arrayVals.push(record.get("company"));
});
Ext.Array.each(arrayVals, function (record, index, array) {
console.log(arrayVals)
self.items.push({ // Object [object Object] has no method 'push'
xtype: 'main-header-nav-FavoriteItem',
text: record
});
});
}
}
});
``` |
24,848,332 | I want to have a dictionary of events, so far I have
```
private Dictionary<T, event Action> dictionaryOfEvents;
```
is it possible to do something like this? | 2014/07/20 | [
"https://Stackoverflow.com/questions/24848332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/313586/"
] | You can't have dictionary of events, though you can have dictionary of delegates.
```
private Dictionary<int, YourDelegate> delegates = new Dictionary<int, YourDelegate>();
```
where `YourDelegate` can be any delegate type. | You can't directly define a dictionary of event types but you can define the event inside a class instead.
```
private Dictionary<string, MyEventManager> dictionaryOfEvents;
dictionaryOfEvents["key1"].CallMyEvent();
```
Example implementation of MyEventManager Class :
```
public class MyEventManager {
public event Action MyEvent;
public void CallMyEvent => MyEvent.Invoke()
}
``` |
8,559,904 | Is it possible to display complex HTML content inside TextView ? My HTML is going to have images and video tags. Is that possible or to use WebView component or there is some simpoler solution ? | 2011/12/19 | [
"https://Stackoverflow.com/questions/8559904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486578/"
] | If you want to use **HTML tags for TextViews, you have to use android.text.Html class, fromHtml()**..
From **Mark Murphy's** Technical Stuff...
**HTML Tags Supported By TextView**
More importantly, it means that you cannot rely on what it will support from release to release.
```
* <a href="...">
* <b>
* <big>
* <blockquote>
* <br>
* <cite>
* <dfn>
* <div align="...">
* <em>
* <font size="..." color="..." face="...">
* <h1>
* <h2>
* <h3>
* <h4>
* <h5>
* <h6>
* <i>
* <img src="...">
* <p>
* <small>
* <strike>
* <strong>
* <sub>
* <sup>
* <tt>
* <u>
```
For more complex HTML tags you have to use **WebView**... | The best way is to use `WebView` for complex `HTML` content, use `HTML` content in `TextView` only to give your text view a custom style |
38,892,806 | I have problem. I created a web page with upload files, I have database (MySQL) with correctly URL to file (file path) (in database is only url to the file, file is in folder on the server). And now I trying write/search php script to download this file what was uploaded. All at web works well, but this download scripts don't work. I read and I think best way for me will be download with 'header', but I was trying and nothing. File is download to our disk, name is correctly, file extension ok, file is open in correct program, but if file have in name chars (';',':' etc.) file is download without these chars and is incorrectly (lack of extension, bad name). And second problem: all downloaded files are empty (0 b size), all is ok but they are empty, some tips ? Thanks in advance for help
My bad download codes:
```
<?php
$data=date('Y-m-d_H:i:s');
$nazwa=$_POST['downtitle'];
$urlek=$_POST['downurl'];
$extrozsz=$_POST['downext'];
$filePath = $urlek;
$fileName = $nazwa.$data.".".$extrozsz;
//------------------------------------------------------------------------
// $fd = fopen($filePath,"r");
// $size = filesize($filePath);
// $contents = fread($fd, filesize($filePath));
// fclose($fd);
// header("Content-Type: application/octet-stream");
// header("Content-Length: $size;");
// header("Content-Disposition: attachment; filename=$fileName");
// echo $contents;
//----------------------------------------------------------------------
// set_time_limit(0);
// while( $urlek = $response->fetch() )
// {
// $my_pliki = file_get_contents("$urlek");
// $my_file = fopen("$urlek","w+");
// fwrite($my_file,$my_pliki);
// fclose($my_file);
// }
//----------------------------------------------------------------------------
$quoted = $filePath;
$size = filesize($file);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
```
?> | 2016/08/11 | [
"https://Stackoverflow.com/questions/38892806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6704007/"
] | Simple solution: In file *app.module.ts* -
### Example 1
```
import {FormsModule} from "@angular/forms";
// Add in imports
imports: [
BrowserModule,
FormsModule
],
```
### Example 2
If you want to use [(ngModel)] then you have to import FormsModule in *app.module.ts*:
```
import { FormsModule } from "@angular/forms";
@NgModule({
declarations: [
AppComponent, videoComponent, tagDirective,
],
imports: [
BrowserModule, FormsModule
],
providers: [ApiServices],
bootstrap: [AppComponent]
})
export class AppModule { }
``` | Sometimes you get this error when you try to use a component from a module, which is not shared, in a different module.
For example, you have 2 modules with module1.componentA.component.ts and module2.componentC.component.ts and you try to use the selector from module1.componentA.component.ts in a template inside module2 (e.g. `<module1-componentA [someInputVariableInModule1]="variableFromHTTPRequestInModule2">`), it will throw the error that the someInputVariableInModule1 is not available inside module1.componentA.component.ts - even though you have the `@Input() someInputVariableInModule1` in the module1.componentA.
If this happens, you want to share the module1.componentA to be accessible in other modules.
So if you share the module1.componentA inside a sharedModule, the module1.componentA will be usable inside other modules (outside from module1), and every module importing the sharedModule will be able to access the selector in their templates injecting the `@Input()` declared variable. |
42,440,860 | I have a User-Role Many-To-Many-Relationship in my MySQL database. Therefore I have a mapping-table which connects the IDs of both tables. The **mapping-table** looks like that:
```
ID of User | ID of Role
---------- | ----------
1 | 1
1 | 2
2 | 1
2 | 3
```
**user-table:**
```
Firstname of User | ID of User
----------------- | ----------
ExampleUser1 | 1
ExampleUser2 | 2
```
**role-table:**
```
Name of Role | ID of Role
----------------- | ----------------
ExampleRole1 | 1
ExampleRole2 | 2
ExampleRole3 | 3
```
and I want my **mapping-table** to look like this:
```
Firstname of User | Name of Role
----------------- | ------------
ExampleUser1 | ExampleRole1
ExampleUser1 | ExampleRole2
ExampleUser2 | ExampleRole1
ExampleUser2 | ExampleRole3
```
What is the SQL-Query to realize that? | 2017/02/24 | [
"https://Stackoverflow.com/questions/42440860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7593672/"
] | It's true that this question has many possible answers. This is probably the most lame one, but it works quite ok actually:
1. Add an additional column;
2. Then put random value in this column;
3. Sort by this column - that's exactly what you want!
4. Delete the additional column, so the trick is no visible!
5. Voila!
Just to give you some idea how this should look like:
```
Option Explicit
Public Sub Randomize()
Dim lCounter As Long
Application.ScreenUpdating = False
Columns("A:A").Insert Shift:=xlToRight
For lCounter = 1 To 5
Cells(lCounter, 1) = Rnd()
Next lCounter
With ActiveSheet.Sort
.SortFields.Add Key:=Range("A1:A5")
.SetRange Range("A1:E5")
.Apply
End With
Columns("A:A").Delete
Application.ScreenUpdating = False
End Sub
```
It would work on data like this one:
[](https://i.stack.imgur.com/fkSRh.png)
You can further update the code, by removing the magic numbers and improving the ranges. | This is my solution:
First I have created a function to generate random numbers between a and b without repeated values:
jlqmoreno@gmail.com
Julio Jesus Luna Moreno
```
Option Base 1
Public Function u(a As Variant, b As Variant) As Variant
Application.Volatile
Dim k%, p As Double, flag As Boolean, x() As Variant
k = 1
flag = False
ReDim x(1)
x(1) = Application.RandBetween(a, b)
Do Until k = b - a + 1
Do While flag = False
Randomize
p = Application.RandBetween(a, b)
'Debug.Assert p = 2
resultado = Application.Match(p, x, False)
If IsError(resultado) Then
k = k + 1
ReDim Preserve x(k)
x(k) = p
flag = True
Else
flag = False
End If
Loop
flag = False
Loop
u = x
End Function
```
this is nessesary since i needed a funtion to create random indices with no duplicates (This was the rough part)
Then i used this function using the logic i applied [here](https://stackoverflow.com/questions/152319/vba-array-sort-function/41886947#41886947)
with this function:
```
Public Function RNDORDER(rango As Range) As Variant
Dim z() As Variant, n%, m%, i%, j%, y() As Variant, k%
n = rango.Rows.count
m = rango.Columns.count
k = 1
ReDim x(n, m)
ReDim y(n)
y = u(1, n)
For i = 1 To n
For j = 1 To m
x(i, j) = rango(y(i), j)
Next j
Next i
RNDORDER = x
```
Just run this function as an array function.
Thanks! |
23,317 | I am still very new to learning guitar (specifically, Classical fingerstyle). While this is the first time I am doing this "seriously", I HAVE tried to learn guitar before, just very badly (and usually with crappy instruments that have been handed down and mistreated by family). I am currently using a tuner app on my phone, although I just ordered a nicer clip-on tuner (Snark SN-2). In the past I've used other mic'd chromatic tuners.
I'm just curious why it is, when tuning, that when you get a note "perfect" it's only exactly in tune for a moment after the string is struck. After that moment, the tuner starts to frequency wobbling sharp and flat around the ideal tuning.
What causes that to happen? I've read a bit about tuning now trying to find out, and everyone just seems to repeat that it's the note played originally that has to be as close to exactly in tune as possible, and not to worry about afterwards.
What confuses me is that the string length never changes, so the wavelength shouldn't change. The frequency may slow down as the string stops vibrating as fast... but why would it sometimes go up too? Maybe I'm thinking about it wrong?
Wouldn't this affect sustained long notes, or is it mostly imperceivable by the ear? | 2014/09/04 | [
"https://music.stackexchange.com/questions/23317",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/12067/"
] | Plucking a string increases its tension momentarily. This tension drops rapidly as the vibration dies out. This causes the pitch to drop slightly as the string vibrates. It's an inherent limitation of plucked string instruments but it's OK, it's part of the sound we know and love.
Also, unlike the ideal mathematical model, strings vibrate in two dimensions. Since the change in tension is more pronounced in one dimension than the other, we're actually hearing two sounds. This causes some harmonics to get cancelled while others become more pronounced. As the frequencies of these two vibrations shift relative to each other, the harmonics that get cancelled or become pronounced also change. This causes a slight chorusing or flanging effect. It's also an inherent limitation of plucked string instruments but it's also OK, it's also part of the sound we know and love.
Digital tuners are not perfect. These changes in harmonic distribution and drop in volume cause them to misread the exact pitch. This is probably the reason why you see some "wobbling" that follows the initial pitch drop. | The fact you have picked up on this shows you have a good ear, here are some tips to make your guitar ring like an angel :)
**Make sure you have a good tuner that is accurate**, (doesn't have to be expensive). Read plenty of reviews on it don't just go buy one.
**Always tune turning up**, if you overshoot go back and start again. This makes sure there is no tension unreleased, more so for older strings when they start to click when tuning.
**Tune at temperature**, tune it so you can play without irritation, then tune again once you have warmed up the guitar. (don't annoyingly tune in front of people, unless you have a muting tuner)
**Tune according to playing style**. If you are going to be picking really hard and quickly, the note that stands out the most is the one you want to tune for. If you need lots of resonance then its the ringing I tune for.
**How long after picking**, My favourite spot to tune to is about 1 second after picking it medium to gentle. No earlier as its to sharp, no later as it starts to go flat.
.
--Expert Level--
If your guitar is tuned well, keep tuning it and let the other strings resonate (i.e. don't mute them). You will hear a rise and fall (like a wobbling) in the volume of the harmonics (the high pitched ringing noise).
You can finer tune by aiming to reduce the speed it rises and falls. Sometimes I've re-tuned my guitar, with my tuner saying every string is in tune both before and after, and can still hear an improvement! Other times I have tuned a guitar so the tuner says its slightly out of tune, but it sounds better with my tuning because it is tailored to the guitar. Although this improves lots of open string and low down chords, it can make higher up notes slightly out of tune. (this is purely open string, not the harmonic tuning method). |
2,677,313 | I guess this is simple, but i couldnot figure it out.
i have a dropdown list with values
```
America
Asia
Europe
```
I need to the display the ddl as Select Type and when i click the dropdownlist to see the values in it, it should display the three values, but i should not use Select Type as a list item and it should not be displayed in the list. It should only be used as a default text in ddl.
Thanks, | 2010/04/20 | [
"https://Stackoverflow.com/questions/2677313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305196/"
] | Windows Forms?
If you populate your combobox like this:
```
this.comboBox1.Items.Add("Select...");
this.comboBox1.Items.Add("America");
this.comboBox1.Items.Add("Asia");
this.comboBox1.Items.Add("Yurrup");
```
Then, attach a DropDown event, to remove the first option on first drop down.
```
private void comboBox1_DropDown(object sender, EventArgs e)
{
if (comboBox1.Items[0].ToString() == "Select...")
{
comboBox1.Items.RemoveAt(0);
}
}
``` | I would add the ListItem to the list with its text set to "Select Type" and its value set to an empty string. In the code behind when you're handling the list, you would programmatically handle the possibility of an empty string selected value.
So given
```
ddl.Items.Add(new ListItem("Select Type", string.Empty));
ddl.Items.Add(new ListItem("America", "America"));
ddl.Items.Add(new ListItem("Asia", "Asia"));
ddl.Items.Add(new ListItem("Europe", "Europe"));
```
You'd handle it like
```
if (ddl.SelectedValue != string.Empty)
{
// do what you need to do
}
else
{
// OK to ignore? re-prompt user? etc.
}
``` |
65,557 | Is there a technical reason why Android phones general lag a lot behind the stable released version of Android?
This applies to both new phones, for example a recent trip to the phone shop everything was 4.0 to 4.2.1, KitKat could not be seen. And also old phones, my girlfriend's iPhone 4 had an OTA update to the latest OS, this is a July 2010 phone, whilst a July 2010 Android is basically a paperweight.
Presumably Android itself doesn't concern itself with the actual hardware, and thus talks to the OS via abstractions? I guess then the handset maker just provides the drivers for the specific hardware, thus I can't see the issue with pushing OTA updates if the ABI remains stable (my phone doesn't grow new hardware features). | 2014/03/16 | [
"https://android.stackexchange.com/questions/65557",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/56268/"
] | This is a 2-part question. Part 1 asks why Android phones do not get the newest update right away, and has been answered adequately by the other answers. Part 2 asks why older phones often never get the newest update, and has not been answered yet.
As LeBeau says, there are other corporate stakeholders besides Google. Google only creates the new versions, and, besides the phones it directly creates, like the Nexus line, it does not get much say over whether and when the others put them into the phones. Also like LeBeau says, all these other stakeholders have to learn the new version before they can implement it. This is why the phones get new versions later, and why certain phones, like the Nexuses, get the versions before anyone else, because Google has already learned the new version.
As for part 2, the hardware makers want us to keep buying new phones every couple months, right? Otherwise, how will they keep all that dough rolling in if we keep using our old phones? They'd be in the same position the computer companies are in: with storage and RAM enough for any purpose, why buy any new hardware? The answer is to stop updating old phones, so if we want the newest features, we have to get a new one. Google probably doesn't do this as much, as it is already selling you Android, so why does it need to sell you phones, but it probably does it a little bit. The network carriers, for their part, probably help with their draconian rules like preventing rooting (or else you void your warranty). This is why, as you say, "`a July 2010 android is basically a paperweight`".
As for your comment about improvements being "mainly userland", I don't know how all that works, but I'm sure it's not that simple. The upgrades may be in software, but not all software talks to the user. Plus, the hardware makers put "skins" on our phones, so we do not see the inner workings, and it's likely that when they finally upgrade to the newest version, they put some new stuff in themselves, so that an HTC One phone at Android 4.2 is different from a Samsung Galaxy SIV phone at Android 4.2. Probably either HTC or Samsung throws some new features out to put in 4.3, and you do not even notice they did it. Then, when let's say the HTC One does not upgrade to 4.3, but the HTC Two does (I'm making this up), you are forced to get HTC Two to get (some of) the new features of 4.3, as well as some features of 4.2 you didn't get with HTC One. I am not certain this happens, but it is normal business procedure, so I would not be surprised. | In addition to the incredibly long HTC infographic in [Mpeti's answer](https://android.stackexchange.com/a/65587/156), other manufacturers have come out and said why their updates lag behind official Google releases, and why they don't release updates for older models:
**Sony Mobile**: [Ice Cream Sandwich – from source code release to software upgrade](http://developer.sonymobile.com/2011/12/07/ice-cream-sandwich-from-source-code-release-to-software-upgrade/), selected excerpts and headers below:
>
> However, before we can roll out those software upgrades, there are a lot of activities to first of all get Ice Cream Sandwich to work and become stable on all Sony Ericsson phones. We call this the **Bring up phase.**
>
> Secondly, and perhaps most important, we must certify and approve the new software release with all the different technologies, networks, and hardware that a modern smartphone should work with. We call this the **Certification and approval phase.**
>
>
> * The Bring up phase: Getting Ice Cream Sandwich to work on our phones
> * Integrating Android patches
> * Getting the software stable and adding localisation
> * The Certification and approval phase: Making sure the software and hardware is compliant
> * Additional approvals might be needed
> * Many operators also want to customise the software according to their requirements
>
>
> When all of this is done, we are ready to roll out the software release variants as software upgrades to operators and consumers around the world.
>
>
>
**Motorola** used to have a good blog entry on this, but seem to have deleted all their older blog content in the last few months. However the Wayback machine has an archived copy of it: [Archive.org: Motorola Update on Ice Cream Sandwich](http://web.archive.org/web/20130219020436/http://www.motorola.com/blog/2011/12/07/motorola-update-on-ice-cream-sandwich), selected text and headings below:
>
> Once source code is released from Google, it doesn’t automatically update to your device.
>
>
> Each new version of Android launches with one device partner, in what is called the “Google Experience Device” or GED, the showcase device for a new Android release. The GED partner for each launch works with Google during the development of the OS so that the device and new Android version are ready for a coordinated simultaneous launch.
>
>
> Once that GED device ships, the rest of the Android community gains access to the Android source code as its made public shortly after – a critical milestone for device manufacturers and component suppliers, enabling us to start work on integrating the new release into our existing products.
>
>
> * Merge and adapt the new release for different device hardware architecture(s) and carrier customizations
> * Stabilize and ‘bake’ the result to drive out bugs
> * Submit the upgrade to the carriers for certification
> * Perform a Customer pre-release
> * Release the upgrade
>
>
> We are planning on upgrading as many of our phones as possible. The ability to offer the upgrade depends on a number of factors including the hardware/device capabilities, the underlying chipset software support, the ICS support and then the ability to support the Motorola value add software.
>
>
>
Also, PC Mag [Why It Will Take So Long to Upgrade Phones to 'Ice Cream Sandwich'](http://www.pcmag.com/article2/0,2817,2397349,00.asp) |
21,697,949 | ```
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at com.sun.javafx.scene.control.skin.NestedTableColum nHeader.dispose(NestedTableColumnHeader.java:323)
at com.sun.javafx.scene.control.skin.NestedTableColum nHeader.updateTableColumnHeaders(NestedTableColumn Header.java:265)
at com.sun.javafx.scene.control.skin.NestedTableColum nHeader.checkState(NestedTableColumnHeader.java:51 9)
at com.sun.javafx.scene.control.skin.NestedTableColum nHeader.computePrefHeight(NestedTableColumnHeader. java:401)
at javafx.scene.Parent.prefHeight(Parent.java:918)
at javafx.scene.layout.Region.prefHeight(Region.java: 1438)
at com.sun.javafx.scene.control.skin.TableHeaderRow.c omputePrefHeight(TableHeaderRow.java:344)
at com.sun.javafx.scene.control.skin.TableHeaderRow.c omputeMinHeight(TableHeaderRow.java:339)
at javafx.scene.Parent.minHeight(Parent.java:946)
at javafx.scene.layout.Region.minHeight(Region.java:1 404)
at javafx.scene.control.SkinBase.computeMinHeight(Ski nBase.java:254)
at javafx.scene.control.Control.computeMinHeight(Cont rol.java:485)
at javafx.scene.Parent.minHeight(Parent.java:946)
at javafx.scene.layout.Region.minHeight(Region.java:1 404)
at javafx.scene.layout.Region.computeChildMinAreaHeig ht(Region.java:1700)
at javafx.scene.layout.Region.getMaxAreaHeight(Region .java:1981)
at javafx.scene.layout.Region.computeMaxMinAreaHeight (Region.java:1850)
at javafx.scene.layout.HBox.computeMinHeight(HBox.jav a:419)
at javafx.scene.Parent.minHeight(Parent.java:946)
at javafx.scene.layout.Region.minHeight(Region.java:1 404)
at javafx.scene.layout.AnchorPane.computeHeight(Ancho rPane.java:297)
at javafx.scene.layout.AnchorPane.computeMinHeight(An chorPane.java:246)
at javafx.scene.Parent.minHeight(Parent.java:946)
at javafx.scene.layout.Region.minHeight(Region.java:1 404)
at javafx.scene.layout.Region.computeChildMinAreaHeig ht(Region.java:1700)
at javafx.scene.layout.Region.getMaxAreaHeight(Region .java:1981)
at javafx.scene.layout.Region.computeMaxMinAreaHeight (Region.java:1850)
at javafx.scene.layout.HBox.computeMinHeight(HBox.jav a:419)
at javafx.scene.Parent.minHeight(Parent.java:946)
at javafx.scene.layout.Region.minHeight(Region.java:1 404)
at javafx.scene.layout.Region.computeChildMinAreaHeig ht(Region.java:1700)
at javafx.scene.layout.VBox.getAreaHeights(VBox.java: 440)
at javafx.scene.layout.VBox.computeContentHeight(VBox .java:522)
at javafx.scene.layout.VBox.computeMinHeight(VBox.jav a:400)
at javafx.scene.Parent.minHeight(Parent.java:946)
at javafx.scene.layout.Region.minHeight(Region.java:1 404)
at javafx.scene.layout.Region.computeChildMinAreaHeig ht(Region.java:1700)
at javafx.scene.layout.VBox.getAreaHeights(VBox.java: 440)
at javafx.scene.layout.VBox.computeContentHeight(VBox .java:522)
at javafx.scene.layout.VBox.computeMinHeight(VBox.jav a:400)
at javafx.scene.Parent.minHeight(Parent.java:946)
at javafx.scene.layout.Region.minHeight(Region.java:1 404)
at javafx.scene.layout.Region.computeChildPrefAreaHei ght(Region.java:1765)
at javafx.scene.layout.VBox.getAreaHeights(VBox.java: 446)
at javafx.scene.layout.VBox.computeContentHeight(VBox .java:522)
at javafx.scene.layout.VBox.computePrefHeight(VBox.ja va:421)
at javafx.scene.Parent.prefHeight(Parent.java:918)
at javafx.scene.layout.Region.prefHeight(Region.java: 1438)
at javafx.scene.layout.AnchorPane.computeHeight(Ancho rPane.java:297)
at javafx.scene.layout.AnchorPane.computePrefHeight(A nchorPane.java:254)
at javafx.scene.Parent.prefHeight(Parent.java:918)
at javafx.scene.layout.Region.prefHeight(Region.java: 1438)
at javafx.scene.layout.Region.minHeight(Region.java:1 406)
at com.sun.javafx.scene.control.skin.ScrollPaneSkin.c omputeScrollNodeSize(ScrollPaneSkin.java:917)
at com.sun.javafx.scene.control.skin.ScrollPaneSkin.l ayoutChildren(ScrollPaneSkin.java:791)
at javafx.scene.control.Control.layoutChildren(Contro l.java:574)
at javafx.scene.Parent.layout(Parent.java:1076)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Parent.layout(Parent.java:1082)
at javafx.scene.Scene.doLayoutPass(Scene.java:576)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene. java:2386)
at com.sun.javafx.tk.Toolkit$3.run(Toolkit.java:322)
at com.sun.javafx.tk.Toolkit$3.run(Toolkit.java:320)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:32 0)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:3 49)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(Qua ntumToolkit.java:479)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(Qua ntumToolkit.java:460)
at com.sun.javafx.tk.quantum.QuantumToolkit$13.run(Qu antumToolkit.java:327)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run( InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Nativ e Method)
at com.sun.glass.ui.win.WinApplication.access$300(Win Application.java:39)
at com.sun.glass.ui.win.WinApplication$4$1.run(WinApp lication.java:112)
at java.lang.Thread.run(Thread.java:744)
``` | 2014/02/11 | [
"https://Stackoverflow.com/questions/21697949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3082679/"
] | I had misunderstood the problem and have changed the solution to fix it:
```
$(".dropdown-menu > li > a").click( function (e) {
e.preventDefault();
$(this).parent().parent().prev().text($(this).text());
})
```
You could use one of the button classes or even the button html tag to address the change but by using relative paths you will adress the right element without risking to change other buttons on your page.
[fiddle](http://fiddle.jshell.net/QfD5p/)
----------------------------------------- | Try this instead
**HTML**:
```
<div class="btn-group">
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
Content <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href=# onclick=javascript:xxxx>Speed 1</a></li>
<li><a href=#>Speed 2</a></li>
<li><a href=#>Speed 3</a></li>
<li><a href=#>Speed 4</a></li>
<li><a href=#>Speed 5</a></li>
</ul>
</div>
```
**Jquery:**
```
$('li a').click(function(){
$('button').text($(this).text());
});
```
[JsFiddle](http://jsfiddle.net/W3eba/) |
753,964 | I currently RDP to my home PC using a secure SSH tunnel. It works well but I would like to try to set up a VPN.
My understanding is that if I connect to the VPN from a remote PC, all the traffic of that PC will go through my home network (including Internet). Is that correct? If it is the case, is there a way to limit the VPN to RDP only? For instance, I wouldn't like all the traffic on my work PC to go through my home network.
Thanks! | 2014/05/15 | [
"https://superuser.com/questions/753964",
"https://superuser.com",
"https://superuser.com/users/59672/"
] | If you know in advance the commands you need to run, you can just do
```
cp file1 file2; cp file3 file4
```
If you have already started the first command, and you are in the same shell, you can hit `Ctrl`+`Z`, then [`bg`](http://www.gnu.org/software/bash/manual/html_node/Job-Control-Builtins.html#index-bg) to put the first command in the background, then call [`wait`](http://www.gnu.org/software/bash/manual/html_node/Job-Control-Builtins.html#index-wait) on the job number or PID to wait until it finishes. For example:
```
$ sleep 30
^Z
[1]+ Stopped sleep 30
$ bg
[1]+ sleep 30 &
$ wait %1; echo "next command"
[1]+ Done sleep 30
next command
``` | ```
cp largefile1 somedestination
```
...time...passes...
```
wait $(pidof cp)
cp largefile2 someplace
```
The bash builtin wait, will pause until the job/process specified (or all jobs if unspecified) has completed before continuing. |
27,498,681 | i have to read from the following format.
```
1
12
23
34
```
So, All inputs are separated by a line.
I have tried the following
```
br = new Scanner(System.in);
num = Integer.parseInt(br.next());
while(br.hasNextInt()) {
num = br.nextInt() ;
System.out.println(num);
}
```
But it is not working as i expected. If i enter first input, it started processing it and prints. it is not waiting for me to enter next line. In C, i can make use of sscanf. but in java i have no idea how to allow user to enter multiline input? plese suggest some ideas | 2014/12/16 | [
"https://Stackoverflow.com/questions/27498681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2694184/"
] | Try
``br = new Scanner(System.in);` while (true) {
int num = Integer.parseInt(br.nextLine());
System.out.println(num);
}` | ```
br = new BufferedReader(new InputStreamReader(System.in));
int ch;
while ((ch = br.read()) != -1) {
if (ch == 10) {
System.out.println();
}
}
``` |
14,425,063 | I'm trying to make a gridview because thats better for more devices. I already tried to add my buttons in the interface builder (as ImageViews because I've added them as ImageButtons the size wasn't good) and the result of that is in this screen: <http://i.imgur.com/pTJnKOv.png>
Can anyone help me by making this in a GridView, just exactly the same but compatible on all the devices.
Thanks in advance ;)!
This is the ImageAdapter:
```
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] buttonValues;
public ImageAdapter(Context context, String[] buttonValues) {
this.context = context;
this.buttonValues = buttonValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.mobile, null);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.grid_item_image);
String button = buttonValues[position];
if (button.equals("homework")) {
imageView.setImageResource(R.drawable.homework);
} else if (button.equals("schedule")) {
imageView.setImageResource(R.drawable.schedulebut);
} else if (button.equals("planner")) {
imageView.setImageResource(R.drawable.plannerbut);
} else {
imageView.setImageResource(R.drawable.settingsbut);
}
} else {
gridView = (View) convertView;
}
return gridView;
}
@Override
public int getCount() {
return buttonValues.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
```
}
and this is my method in the onCreate :
```
static final String[] MOBILE_OS = new String[] { "Homework", "Schedule",
"Planner", "Settings" };
private void setGridView() {
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(), "LOL!", Toast.LENGTH_SHORT).show();
}
});
}
``` | 2013/01/20 | [
"https://Stackoverflow.com/questions/14425063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1923618/"
] | Since you are trying to use a **2X2 Grid** and have only 4 elements, use **`android:numColumns="2"`** as an attribute of your GridView.
Additionally, there is this excellent [tutorial on GridViews](http://www.mkyong.com/android/android-gridview-example/)!
Code snippet to implement only Images in your Grid :
```
public class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context context) {
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.mobile, null);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.grid_item_image);
if (mobile.equals("Windows")) {
imageView.setImageResource(R.drawable.windows_logo);
} else if (mobile.equals("iOS")) {
imageView.setImageResource(R.drawable.ios_logo);
} else if (mobile.equals("Blackberry")) {
imageView.setImageResource(R.drawable.blackberry_logo);
} else {
imageView.setImageResource(R.drawable.android_logo);
}
} else {
gridView = (View) convertView;
}
return gridView;
}
@Override
public int getCount() {
return mobiles.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
```
**EDIT :** You are getting the same image in all the buttons because you are matching the strings which you have written in different cases. (You are using *"Homework"* in one place and *"homework"* in another)
So, use `static final String[] MOBILE_OS = new String[] { "homework", "schedule", "planner", "settings" };` and it would work fine. | To get fixed sizes you can add
android:layout\_height=""
android:layout\_width=""
example :
android:layout\_height="100dp"
android:layout\_width="200dp"
in your button tags |
9,780,792 | I have a `ListView` with `fastScrollAlwaysVisible` and `fastScrollEnabled` both set to `true`. After implementing `SectionIndexer` to my `Adapter` and an `AlphabetIndexer`, my `fast scroll thumb` will disappear while I scroll, then reappear once I reach the top or bottom of the list. I'm pretty clueless about why this happens. I haven't experienced it before.
Everything below works as far as `AlphabetIndexer` is concerned. My question is why does my fast scroll thumb disappear while I scroll and how can I stop it from disappearing?
Whether or not the `fast scroll` is *always* visible doesn't matter. Whenever the `fast scroll` is visible, the `fast scroll thumb` is not there, it's simply gone and that's my problem. Also, when I remove the `AlphabetIndexer` the `fast scroll thumb` works like I intend for it to. Everything works successfully in an `Activity`, but when I load my `ListView` in a `Fragment` things end up like I explain.
This is my `Adapter` for my `ListView`:
```
private class AlbumsAdapter extends SimpleCursorAdapter implements
SectionIndexer {
private AlphabetIndexer mIndexer;
// I have to override this because I'm using a `LoaderManager`
@Override
public Cursor swapCursor(Cursor cursor) {
if (cursor != null) {
mIndexer = new MusicAlphabetIndexer(cursor, mAlbumIdx,
getResources().getString(R.string.fast_scroll_alphabet));
}
return super.swapCursor(cursor);
}
@Override
public Object[] getSections() {
return mIndexer.getSections();
}
@Override
public int getPositionForSection(int section) {
return mIndexer.getPositionForSection(section);
}
@Override
public int getSectionForPosition(int position) {
return 0;
}
}
```
`MusicAlphabetIndexer` helps sort through music correctly:
```
class MusicAlphabetIndexer extends AlphabetIndexer {
public MusicAlphabetIndexer(Cursor cursor, int sortedColumnIndex,
CharSequence alphabet) {
super(cursor, sortedColumnIndex, alphabet);
}
@Override
protected int compare(String word, String letter) {
String wordKey = MediaStore.Audio.keyFor(word);
String letterKey = MediaStore.Audio.keyFor(letter);
if (wordKey.startsWith(letter)) {
return 0;
} else {
return wordKey.compareTo(letterKey);
}
}
}
``` | 2012/03/20 | [
"https://Stackoverflow.com/questions/9780792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420015/"
] | I had similar issue with fast scroller's thumb icon. I was investigating Android source code and found a commit which introduced this problem and other (ArrayIndexOutOfBoundsException). I built even Android system without this commit and it worked then.
I submitted the issue in June: <https://code.google.com/p/android/issues/detail?id=33293>
When I'm reading it know I see I could describe the issue better :)
This is the commit which is making problems: <https://github.com/android/platform_frameworks_base/commit/32c3a6929af9d63de3bf45a61be6e1a4bde136d3>
Unfortunately I haven't found any solution, except revert the commit, and I left it.
I hope someone will find how to fix it. | Do you have both `fastScrollEnabled` and [`fastScrollAlwaysVisible`](http://developer.android.com/reference/android/widget/AbsListView.html#setFastScrollAlwaysVisible%28boolean%29) set to `true`? There is no `fastScrollAlwaysEnabled` attribute of a `ListView`, so I'm thinking maybe you just have `fastScrollEnabled` set to true but `fastScrollAlwaysVisible` is set to its default value, which is `false`. |
147,175 | In Book V of *The Return of the King,* in "The Black Gate Opens," as the Captains approach the Gate, Tolkien makes this statement (phrase in question bolded by me):
>
> North amid their noisome pits lay the first of the great heaps and hills of slag and broken rock and blasted earth, the vomit of **the maggot-folk of Mordor**; but south and now near loomed the great rampart of Cirith Gorgor, and the Black Gate amidmost, and the two Towers of the Teeth tall and dark upon either side.
>
>
>
North of the Black Gate is actually *outside* Mordor, but obviously the landscape north of it was affected by these "maggot-folk of Mordor." The question I have specifically is if "maggot-folk" is merely a *general*, descriptive, collective term referring to all the various "peoples" of Mordor (orcs, trolls, evil men, etc.) or is there some evidence in other writing that Tolkien is here making an identification of a *specific* people group that were part of Mordor who terraformed the landscape in such a destructive way? | 2016/12/12 | [
"https://scifi.stackexchange.com/questions/147175",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/31437/"
] | Probably orcs
-------------
"Maggots" suggest creatures that are small, which would rule out Trolls and the large Uruks of Mordor.
The closest I can come to a quote that answers your question is when Frodo and Sam approach the Black Gate.
>
> Across the mouth of the pass, from cliff to cliff, the Dark Lord had built a rampart of stone. In it there was a single gate of iron, and upon its battlement sentinels paced unceasingly. Beneath the hills on either side the rock was bored into a hundred caves and maggot-holes; there a host of orcs lurked, ready at a signal to issue forth like black ants going to war.
>
>
> *The Lord of the Rings* Book 4, Chapter 3: *The Black Gate is Closed*
>
>
>
This could be said, by analogy, to equate orcs to maggots (as well as to ants).
There are also plenty of places where orcs refer to each other as "maggots". This includes during the arguments between Saruman's Uruk-Hai and the smaller orcs of the Misty Mountains.
>
> In the afternoon Uglúk’s troop overtook the Northerners.
> They were flagging in the rays of the bright sun, winter sun
> shining in a pale cool sky though it was; their heads were
> down and their tongues lolling out.
>
>
> ‘Maggots!’ jeered the Isengarders. ‘You’re cooked. The
> Whiteskins will catch you and eat you. They’re coming!’
>
>
> *The Lord of the Rings* Book 3, Chapter 3: *The Uruk-Hai*
>
>
>
On the whole, I think it most likely that Tolkien had orcs (the smaller breeds rather than the larger Uruks) in mind when he referred to the "maggot-folk of Mordor". | I would say maggot-folk of Mordor are Uruk-hai. As written on [LOTR wiki](http://lotr.wikia.com/wiki/Uruk-hai)
>
> The Uruks first appeared about the year TA 2475, when they conquered
> Ithilien and destroyed the city of Osgiliath. The Uruks in the service
> of Barad-dûr, **the folk of Mordor**, used the symbol of the red Eye of
> Sauron.
>
>
>
Also the is descripition
>
> Sauron's uruks, seen in The Return of the King, have noticeably
> rougher features than Saruman's. They are shown in the movie as being
> released from a kind of membrane in the mud deep under Isengard
> (special commentary on the DVD edition explained that they were trying
> to base the scene on an early description of Tolkien's that orcs "**worm**
> **their way out of the ground like maggots**")
>
>
> |
28,878,724 | I am developing a python module. My module needs getting data from database various times. I am writing a data-layer class with sole motive of writing all the functions which hits DB at same place and calling these data-layer class methods from different method of my module.
I tried below code:
```
class datalayer:
cur = None; #Cursor which would be used by all methods
def __init__(self):
conn=sqlite3.connect(DB_NAME);
cur=conn.cursor();
def getEmpData(self,flowId):
sql= "Select * from emp"
cur.execute(sql);
rows = cur.fetchall();
return rows;
def getManData(self,flowId):
sql= "Select * from manager"
cur.execute(sql);
rows = cur.fetchall();
return rows;
```
Once this is done I am creating instances of same class in classes where I want to hit DB, like:
```
class example1:
def ex1():
do_something()
datalayerInstance = datalayer();
datalayerInstance.getEmpData();
```
But even if a do above each time the instance of data-layer class is created a new cursor object would be created. I want to avoid this and create a cursor object just once and use the same through the class. How can this be achieved?
Also, I tried using static method, but that too is not solving my problem.
Please help as I am new to Python. | 2015/03/05 | [
"https://Stackoverflow.com/questions/28878724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1678247/"
] | datalayer.py
```
datalayerInstance = datalayer();
def get_datalayerinstance():
return datalayerInstance
```
example.py
```
import datalayer
datalayerInstance = get_datalayerinstance();
``` | What you want is a singleton. To do this you could override `__new__` so that everytime you have a new `datalayer` object created, it uses the same cursor.
```
class datalayer(object):
_cur = None; #Cursor which would be used by all methods
def __new__(cls, *args, **kwargs):
if not cls._cur:
conn=sqlite3.connect(DB_NAME);
cls._cur = conn.cursor();
return cls._cur
def getEmpData(self,flowId):
sql= "Select * from emp"
cls._cur.execute(sql);
rows = cls._cur.fetchall();
return rows;
def getManData(self,flowId):
sql= "Select * from manager"
cls._cur.execute(sql);
rows = cls._cur.fetchall();
return rows;
```
It should work although *it might not be the prettiest way of doing thigs*, there are others much more simple and elegant.
The only advantage is that this would not require you to change all your code.
>
> Answer adapted from this one : <https://stackoverflow.com/a/1810367/2549230>
>
>
> |
346,445 | I've been banging my head against for wall for a while with this one.
I want to SSH into a set of machines and check whether they are available (accepting connections and not being used). I have created a small script, tssh, which does just that:
```
#!/bin/bash
host=$1
timeout=${2:-1}
ssh -qo "ConnectTimeout $timeout" $host "[ \`who | cut -f1 | wc -l \` -eq 0 ] && exit 0 || exit 1"
```
This script works correctly. Returning 255 if there was a connection problem, 1 if the machine is busy and 0 if everything is good. If anyone knows a better way to do this please let me know.
So next I try and call tssh on my set of machines using a while read loop, and this is where it all goes wrong. The loop exits as soon as tssh returns 0 and never completes the full set.
```
while read nu ; do tssh "MYBOXES$nu" ; done < <(ruby -e '(0..20).each { |i| puts i }')
```
At first I thought this was a subshell problem but apparently not.
Any help, along with comments on style/content, would be much appreciated!
I know I'm going to kick myself when I find out why... | 2008/12/06 | [
"https://Stackoverflow.com/questions/346445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In the construct
```
something |
while read x; do
ssh ...
done
```
the standard input as seen by the while loop is the output of `something`.
The default behavior of `ssh` is to read standard input. This allows you to do things like
```
cat id_rsa.pub | ssh new_box "cat - >> ~/.ssh/authorized_keys"
```
Now, with that being said, when the first value is read, the first ssh command will read the entire input from `something`. Then, by the time ssh finishes, there is no output left, and `read` stops.
The fix is `ssh -n ...` e.g.
```
cat /etc/hosts | awk '{print $2}' | while read x; do
ssh -n $x "do_something_on_the_machine"
done
``` | Most of the answers are specific to ssh. Other commands also hijack stdin and do not have a -n option. This should address any other commands. This should also work for ssh.
```
while read x; do
# Make sure command does not hijack stdin
echo "" | command $x
done < /path/to/some/file
``` |
606,726 | I.e., if I flipped five non-absolute values, then averaged them, then got the absolute value as the result, and I did that infinite times, what would be the average value of the result?
What mathematical method would I use to calculate this? I've only taken up to precalculus and I anticipate that calculating this would involve something I haven't learned yet but I don't know what it is.
Edit: I am asking this to understand how I can quantify how much lower sample size rather than an actual shift in the average for which there is a tendency can be expected to cause a deviation. | 2023/02/26 | [
"https://stats.stackexchange.com/questions/606726",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/380919/"
] | There are 32 different equally probable outcomes of 5 throws, of which two have absolute value of sum of throws equal to 5, 10 have 3, and 20 have 1, so total sum of all these cases is $5\times2 + 3\times10 + 1\times20 = 60$. To get average, we need to devide 60 by number of total cases which is 32. $\frac{60}{32} = \frac{15}{8}$. That is expectation of sums, average is sum divided by 5, so if you want to get expectation of averages, then you divide expectation of sums by 5 and get $\frac{3}{8}$. | I get zero by two methods, a Mathematica simulation, and a counting argument.
Mathematica simulation:
```
results = {}; results2={};
Module[{n = 10000000, outer, inner},
AbsoluteTiming[
For[k = 1, k <= 5, ++k,
sum1 = 0;
For[outer = 1, outer <= n, ++outer,
sum2 = 0;
For[inner = 1, inner <= 5, ++inner,
sum2 += RandomChoice[{-1, 1}]
];
AppendTo[results,sum2];
sum1 += sum2/5.0;
];
Print["{n, sum2, sum1/n}", {n, sum2, sum1/N[n]}];
AppendTo[results, {n, sum2, sum1/N[n]}];
]
]
]
results:
n = # Flips Sum last Average of n flips
5 flips
10000, 1, 0.0006400000000000063
10000, -3, -0.007840000000000005
10000, -1, -0.004319999999999987
10000, -3, -0.0022799999999999947
10000, 1, 0.00899999999999997
100000, -1, 0.0005719999999999979
100000, 3, 0.0025119999999999774
100000, -1, -0.000683999999999993
100000, -3, -0.0034999999999999923
100000, -1, 0.0016439999999999894
1000000, -3, -0.00005719999999999856
1000000, 1, 0.0005504000000000307
1000000, 1, 0.000036799999999996686
1000000, -1, 0.00013999999999999622
1000000, 1, 0.0006572000000000153
10000000, -1, -0.00001588000000000591
10000000, 3, -2.8800000000038654e-6
10000000, 1, -0.00011363999999998875
10000000, 3, 0.00022167999999998797
10000000, -1, 0.000014039999999994434
```
The counting argument:
only six sums are possible
-5,-3,-1,+1,+3,+5 and the averages are those divided by 5.
The sums of equal absolute value have an equal number of terms.
Since the negative and positive values cancel each other out, the average is zero.
Here is a count of the number of sums of each kind:
Tally[results2] ->
{{-1, 312475}, {1, 312595}, {5, 31378}, {-3, 155964}, {3,
156121}, {-5, 31467}} |
11,373,083 | How can I change my C# code below to list all possible permutations without repetitions? For example: The result of 2 dice rolls would produce 1,1,2 so that means 2,1,1 should not appear.
Below is my code:
```
string[] Permutate(int input)
{
string[] dice;
int numberOfDice = input;
const int diceFace = 6;
dice = new string[(int)Math.Pow(diceFace, numberOfDice)];
int indexNumber = (int)Math.Pow(diceFace, numberOfDice);
int range = (int)Math.Pow(diceFace, numberOfDice) / 6;
int diceNumber = 1;
int counter = 0;
for (int i = 1; i <= indexNumber; i++)
{
if (range != 0)
{
dice[i - 1] += diceNumber + " ";
counter++;
if (counter == range)
{
counter = 0;
diceNumber++;
}
if (i == indexNumber)
{
range /= 6;
i = 0;
}
if (diceNumber == 7)
{
diceNumber = 1;
}
}
Thread.Sleep(1);
}
return dice;
}
``` | 2012/07/07 | [
"https://Stackoverflow.com/questions/11373083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1417178/"
] | I have written a class to handle common functions for working with the binomial coefficient, which is the type of problem that your problem falls under. It performs the following tasks:
1. Outputs all the K-indexes in a nice format for any N choose K to a file. The K-indexes can be substituted with more descriptive strings or letters. This method makes solving this type of problem quite trivial.
2. Converts the K-indexes to the proper index of an entry in the sorted binomial coefficient table. This technique is much faster than older published techniques that rely on iteration. It does this by using a mathematical property inherent in Pascal's Triangle. My paper talks about this. I believe I am the first to discover and publish this technique, but I could be wrong.
3. Converts the index in a sorted binomial coefficient table to the corresponding K-indexes.
4. Uses [Mark Dominus](http://blog.plover.com/math/choose.html) method to calculate the binomial coefficient, which is much less likely to overflow and works with larger numbers.
5. The class is written in .NET C# and provides a way to manage the objects related to the problem (if any) by using a generic list. The constructor of this class takes a bool value called InitTable that when true will create a generic list to hold the objects to be managed. If this value is false, then it will not create the table. The table does not need to be created in order to perform the 4 above methods. Accessor methods are provided to access the table.
6. There is an associated test class which shows how to use the class and its methods. It has been extensively tested with 2 cases and there are no known bugs.
To read about this class and download the code, see [Tablizing The Binomial Coeffieicent](http://tablizingthebinomialcoeff.wordpress.com/). | Here is generic c# version using recursion (basically the recursive method takes number of dices or number of times the dice has been tossed) and returns all the combinations strings ( for ex, for '3' as per the question - there will be 56 such combinations).
```
public string[] GetDiceCombinations(int noOfDicesOrnoOfTossesOfDice)
{
noOfDicesOrnoOfTossesOfDice.Throw("noOfDicesOrnoOfTossesOfDice",
n => n <= 0);
List<string> values = new List<string>();
this.GetDiceCombinations_Recursive(noOfDicesOrnoOfTossesOfDice, 1, "",
values);
return values.ToArray();
}
private void GetDiceCombinations_Recursive(int size, int index, string currentValue,
List<string> values)
{
if (currentValue.Length == size)
{
values.Add(currentValue);
return;
}
for (int i = index; i <= 6; i++)
{
this.GetDiceCombinations_Recursive(size, i, currentValue + i, values);
}
}
```
**Below are corresponding tests...**
```
[TestMethod]
public void Dice_Tests()
{
int[] cOut = new int[] { 6, 21, 56, 126 };
for(int i = 1; i<=4; i++)
{
var c = this.GetDiceCombinations(i);
Assert.AreEqual(cOut[i - 1], c.Length);
}
}
``` |
33,871 | If I recall correctly, karma is constituted of two parts - action and intention. Which means if one wishes to "gain" positive karma, one would have to conduct a positive action AND do so with a positive mind. With that being said, if I were to help an old lady to cross the street for the sole purpose of obtaining good karma, am I going to get good karma? | 2019/07/05 | [
"https://buddhism.stackexchange.com/questions/33871",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/15203/"
] | This is a triple win in term of accumulating and strengthening the effectiveness of the karmic action:
1. Being nice
2. Knowing being nice has consequences
3. Acting knowing there are consequences
When doing good, believing in Karma and knowing there are consequences, reinforce the good results. | Karma is how this world behaves. As an example in general how world behave is ; if we change the state of a weight (put a stone from the ground on the table) to a more unstable position (being on the table is more unstable than being on the ground) what would happen? Once its got a chance it comes to a stable position right? You can name this as gravity or any other concept in Science. The same model is happening in Karma too.
By helping a lady to cross the road you are changing the state, and once the nature got a chance it gives you similar thing back. But main thing to remember is that ‘chethana han bikkha wè kamman wadami’ means thought (intention) is the karma. So if you do this without the intention of really helping that lady, you will not get similar help in future. The intention you meant here may cause you to be used by someone else (as return karma) to get what they want while you will feel some easiness. |
65,429,426 | I'm trying to take the content of the `<p>` tag then change it to a number and multiply it by 2000 then returning it to the `<p>` (this works after I press a select tag that changes the currency from USD to LBP by multiplying the number with 2000)
ps: it's a project for my class
:
**HTML:**
```
<div class="card">
<img class="imgcar" src="cars/402088-2020-land-rover-range-rover-velar.jpg" alt="Avatar" style="width:16em">
<div class="container">
<h4><b>Range Rover Velar</b><br><b>4 Doors</b><br><b> 5 Passengers</b> </h4>
<p id="price">100</p><p>$/24hrs</p>
</div>
</div>
```
**JavaScript:**
```
var p = document.getElementById("price");
var text = p.textContent;
var number = parseInt(text) * 2000;
p.innerHTML = number;
``` | 2020/12/23 | [
"https://Stackoverflow.com/questions/65429426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14879696/"
] | First get the distinct combinations of `order_no` and `invoice_total` and then aggregate:
```
SELECT SUM(invoice_total) AS invoicetotal
FROM (
SELECT DISTINCT order_no, invoice_total
FROM p_orders
WHERE plain_date='2020-12-23' AND o_status='Delivered'
) t
``` | Your data is poorly structured; you really should have another table where order\_no is the primary key and keep invoice\_total in that. As is, you could have different invoice\_total values for the same order\_no; you need to decide which to use in that case. If you wanted to use the maximum, you would do:
```
SELECT SUM(invoicetotal) AS invoicetotal FROM (
SELECT MAX(invoice_total) AS invoicetotal FROM `p_orders` WHERE `plain_date`='2020-12-23' AND `o_status`='Delivered' GROUP BY `order_no`
) AS distinct_orders;
``` |
101,230 | I’m using a MacBook Pro and I broke it a while back. So, the keyboard doesn’t work on the laptop. I hooked up a keyboard to the USB port so I can still use it. I’m using a Dell keyboard.
Last night I wanted to listen to music without the brightness of the screen. So without thinking I turned the brightness off. Now I can't get the screen back so I was wondering if there's a way I can use the Dell keyboard to get the screen brightness back? | 2013/09/08 | [
"https://apple.stackexchange.com/questions/101230",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/56687/"
] | key: "**scroll lock**" to decrease brightness
key: "**pause**" to increase brightness | You can also use Apple Script - if you can ssh into your mac, you can then, in the ssh session, type the following:
```
osascript -e 'tell application "System Events"
key code 113
end tell'
```
Please note, that you actually need to press Enter at the end of each line. Also, be careful with the quote characters - there's a single quote after the `-e` option, and then a closing single quote at the end of line 3 above (following the `end tell`). Each execution of the script will increase the brightness by one notch. If you want it dimmer, change `113` to `107`.
If this is something you see yourself use more often, then it might be worth it to either define an alias or write a small shell script, eg:
```
MacBook:~ alias brightup="osascript -e 'tell application \"System Events\"
> key code 113
> end tell'"
```
and:
```
MacBook:~ alias brightdn="osascript -e 'tell application \"System Events\"
> key code 107
> end tell'"
```
Again, be careful with the quotes. When you put the above aliases into your `.bashrc`, all you'll need to type is `brightup` or `brightdn`.
**Additional info**
If you can't ssh into your box, you can blindly type the first `osascript` command. I would do it in the following way:
1. press `Command``Space`
2. type `terminal` and press `Enter`
3. blindly and slowly (and carefully) type the first `osascript...` command from the example above, exactly as it is there. This should bump the brightness up a bit, enough so that you should see what you're doing. If not, try a couple of times to press `Up Arrow``Enter` |
58,181,578 | Consider the following column vector:
```
vec <- rbind(c(0.5),c(0.6))
```
I want to convert it into the following 4x4 diagonal matrix:
```
0.5 0 0 0
0 0.6 0 0
0 0 0.5 0
0 0 0 0.6
```
I know I can do it by the following code:
```
dia <- diag(c(vec,vec))
```
But what if I want to convert it into a 1000x1000 diagonal matrix. Then the code above is so efficient. Maybe I can use `rep`, but I am not totally sure how to do it. How can I do it more efficient? | 2019/10/01 | [
"https://Stackoverflow.com/questions/58181578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12073743/"
] | Here is one other way using recycling:
```
diag(c(vec), length(vec)*2)
``` | I think your approach is already good enough, here is another way by initialising the matrix and using `rep` to fill diagonals.
```
n <- 4
mat <- matrix(0, ncol = n, nrow = n)
diag(mat) <- rep(vec, n/2)
mat
# [,1] [,2] [,3] [,4]
#[1,] 0.5 0.0 0.0 0.0
#[2,] 0.0 0.6 0.0 0.0
#[3,] 0.0 0.0 0.5 0.0
#[4,] 0.0 0.0 0.0 0.6
```
and following your approach you could do
```
diag(rep(vec, n/2))
``` |
256,274 | I'm a C noob and I'm learning about concurrency using C. I came across an exercise in a [book](https://rads.stackoverflow.com/amzn/click/com/B00EKZ123U) asking me to find the approximate value of Pi using the Monte Carlo technique with OpenMP. I came up with the following:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include <omp.h>
int in_circle = 0;
int total = 10000;
int thread_numb = 4;
void calculate_in_circle_random_count() {
srand((unsigned int)time(NULL));
for (int i = 0; i < total / thread_numb; i++) {
float x = (float)rand()/(float)(RAND_MAX);
float y = (float)rand()/(float)(RAND_MAX);
float val = (x * x) + (y * y);
if (val < 1.0) {
#pragma omp critical
{
in_circle++;
}
}
}
}
int main(int argc, char const *argv[]) {
#pragma omp parallel num_threads(thread_numb)
{
printf("Hello from process: %d\n", omp_get_thread_num());
calculate_in_circle_random_count();
}
float pi_approx = 4 * (float)in_circle / (float)total;
printf("In circle: %d\n", in_circle);
printf("Total: %d\n", total);
printf("Pi approximation: %.6f\n", pi_approx);
return 0;
}
```
I have the sample count of 10000 to calculate approximation and I want to dedicate 4 threads to be parallel for the calculation. So since I want 4 threads, I make sure the for loop is run until `total / 4` for each thread. And whenever `(val < 1.0)` is `true` I increase the `in_circle` variable in a critical section.
Does this approach make sense? If not, how could it be improved? | 2021/02/20 | [
"https://codereview.stackexchange.com/questions/256274",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/168876/"
] | This code has a serious problem due to (at least the typical implementation of) `rand()`. `rand()` normally has a (hidden) seed value, and each call to `rand()` modifies the seed. At least in most implementations, that means `rand` always forces serialization.
That means, calling `rand()` (a couple of times) in your inner loop will prevent code from scaling well at all. In fact, in most cases (as Toby Speight showed) a multi-threaded version will run substantially *slower* than a single-threaded version.
To fix this, you pretty much need to use some other random number generator. Your implementation may provide one (e.g., `erand48` is fairly common). If you really need your code to be portable, you could write your own, something on this order:
```c
#include <time.h>
typedef unsigned long long rand_state;
// multiplier/modulus taken from Knuth Volume 2, Table 1
static const int multiplier = 314159269;
static const int addend = 1;
static const int modulus = 0xffffffff;
// note that this works differently from srand, returning a seed rather than setting
// a hidden seed.
rand_state omp_srand() {
rand_state state = time(NULL);
state ^= (unsigned long long)omp_get_thread_num() << 32;
return state;
}
int omp_rand(rand_state *state) {
*state = *state * multiplier + addend;
return *state & modulus;
}
```
Note that since it's entirely likely that all the threads get started in the same second, this combines the current time with the thread ID to seed each thread's generator. Although it's not 100% guaranteed, this gives a pretty high likelihood that each thread's generator will start with a unique seed. On the other hand, it also means that we have to start the thread, and then seed the generator inside that thread.
To use this, our code would be something on this general order:
```c
double calculate_in_circle_random_count(void) {
static const unsigned total = 1000000000;
unsigned in_circle = 0;
#pragma omp parallel reduction(+:in_circle)
{
// do per-thread initialization
rand_state seed = omp_srand();
int count = total / omp_get_num_threads();
int i;
// then do this thread's portion of the computation:
for (i = 0; i < count; ++i) {
double x = (double)omp_rand(&seed) / OMP_RAND_MAX;
double y = (double)omp_rand(&seed) / OMP_RAND_MAX;
double val = x * x + y * y;
in_circle += val < 1.0;
}
}
return 4.0 * in_circle / total;
}
int main(int argc, char const *argv[])
{
int num_threads = 1;
if (argc > 1)
num_threads = atoi(argv[1]);
omp_set_num_threads(num_threads);
float pi_approx = calculate_in_circle_random_count();
printf("Pi approximation: %.6f\n", pi_approx);
return 0;
}
```
With this modification, the code is at least *capable* of scaling. To get it to scale very well, you'd need to change your `total` to a rather larger number though--with it as small as you've specified, it takes longer to start up multiple threads than it saves in calculation. But at least this code *can* scale well, so if we make `total` quite a bit larger, it really will run faster. For timing, I added a few more zeros to `total`, and rewrote `main` a bit, to create a loop to use 1, 2, 3, and 4 threads and print out the time each iteration. On my machine, this produced the following:
```
With 1 threads: Pi approximation: 3.140259, time: 3,652,683 microseconds
With 2 threads: Pi approximation: 3.139389, time: 1,892,415 microseconds
With 3 threads: Pi approximation: 3.138885, time: 1,268,917 microseconds
With 4 threads: Pi approximation: 3.138306, time: 935,579 microseconds
```
So with this, 4 threads is at least close to 4 times as fast as one thread. I'm pretty sure if you use `rand` inside the loop, you'll never get it to scale well at all.
For anybody who cares, the version of main that produces that output is written in C++, and looks like this:
```cpp
int main(int argc, char const* argv[]) {
using namespace std::chrono;
std::cout.imbue(std::locale(""));
int processors = omp_get_num_procs();
for (int num_threads = 1; num_threads <= processors; num_threads++) {
std::cout << "With " << std::setw(2) << num_threads << " threads: ";
omp_set_num_threads(num_threads);
auto start = high_resolution_clock::now();
float pi_approx = calculate_in_circle_random_count();
auto stop = high_resolution_clock::now();
printf(" %.6f, time: ", pi_approx);
std::cout << std::setw(9) << duration_cast<microseconds>(stop - start).count() << " microseconds\n";
}
return 0;
}
```
This remains pretty much the same, but with some timing code hacked in. In particular, it's *not* an attempt at rewriting the code in C++ in general. If I were doing that, I'd probably do a number of things rather differently (starting with the fact that the C++ `<random>` header already provides a clean way to handle per-thread random number generation, so I'd use that instead of rolling my own). | I think you're over-complicating this. You can let OpenMP divide the work between the threads for you, using `#pragma openmp parallel for`.
You can use a reduction for `in_circle` instead of a critical section - that allows OpenMP to sum into a per-thread variable, and add them all at the end, reducing contention for the variable.
Here's a simpler version (I've removed the unused includes, too, and made the function declaration a prototype):
```
#include <stdio.h>
#include <stdlib.h>
double calculate_in_circle_random_count(void)
{
static const unsigned total = 1000000;
unsigned in_circle = 0;
#pragma omp parallel for reduction(+:in_circle)
for (unsigned i = 0; i < total; ++i) {
double x = (double)rand() / RAND_MAX;
double y = (double)rand() / RAND_MAX;
double val = x * x + y * y;
in_circle += val < 1.0;
}
return 4.0 * in_circle / total;
}
int main(void)
{
const double pi_approx = calculate_in_circle_random_count();
printf("Pi approximation: %.6f\n", pi_approx);
}
```
Note that at this scale, the parallelisation overheads dominate, making the parallel version much slower than the serial. With more iterations, you'll get closer, but there's so little in the loop that the benefits are small. |
1,776,944 | I would like to create an interface for manipulating invoices in a transaction-like manner.
The database consists of an invoices table, which holds billing information, and an invoice\_lines table, which holds line items for the invoices. The website is a set of scripts which allow the addition, modification, and removal of invoices and their corresponding lines.
The problem I have is this, I would like the ACID properties of the database to be reflected in the web application.
* **Atomic**: When the user hits save, either the entire invoice is modified or the entire invoice is not changed at all.
* **Consistent**: The application code already ensures consistency, lines cannot be added to non-existent invoices. Invoice IDs cannot be duplicated.
* **Isolated**: If a user is in the middle of a set of changes to an invoice, I would like to hide those changes from other users until the user clicks save.
* **Durable**: If the web site dies, the data should be safe. This already works.
If I were writing a desktop application, it would maintain a connection to the MySQL database at all times, allowing me to simply use the BEGIN TRANSACTION and COMMIT at the beginning and end of the edit.
From what I understand you cannot BEGIN TRANSACTION on one PHP page and COMMIT on a different page because the connection is closed between pages.
Is there a way to make this possible without extensions? From what I have found, only [SQL Relay](http://sqlrelay.sourceforge.net/) does this (but it is an extension). | 2009/11/21 | [
"https://Stackoverflow.com/questions/1776944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] | you don't want to have long running transactions, because that'll limit concurrency. <http://en.wikipedia.org/wiki/Command_pattern> | The translation on the web for this type of processing is the use of session data or data stored in the page itself. Typically what is done is that after each web page is completed the data is stored in the session (or in the page itself) and at the point in which all of the pages have been completed (via data entry) and a "Process" (or "Save") button is hit, the data is converted into the database form and saved - even with the relational aspect of data like you mentioned. There are many ways to do this but I would say that most developers have an architecture similar to what I mentioned (using session data or state within the page) to satisfy what you are talking about.
You'll get much advice here on different architectures but I can say that the Zend Framework (<http://framework.zend.com>) and the use of Doctrine (<http://www.doctrine-project.org/>) make this fairy easy since Zend provides much of the MVC architecture and session management and Doctrine provides the basic CRUD (create, retrieve, update, delete) you are looking for - plus all of the other aspects (uniqueness, commit, rollback, etc). Keeping the connection open to mysql may cause timeouts and lack of available connections. |
6,475,815 | **UPDATE**
It seems to have magically corrected itself because now it works, but I emphasize that it wasn't a cache issue because even I was able to update with new images but they always appeared "below" rather than "next to"... I don't understand...but suddenly it worked now.
if you check [www.dodomainer.com](http://www.dodomainer.com) in Safari and Chrome, the two images in the header float, but not in Firefox. Any idea how to fix this? Note, it's definitely not this way in Firefox as a result of a cache
this is the code that I use. Any idea how to fix the problem?
```
<div class="header a"><a href="http://dodomainer.com/">
<img src="http://dodomainer.com/images/dodo4.jpg" width="400" height="50" padding-left="10px" alt="dodobird" />
</a></div>
<div class="header b">
<a href="http://dodomainer.com/">
<img src="http://dodomainer.com/images/dodotest.jpg" width="380" height="70" padding-left="10px" alt="dodobird" />
</a>
</div>
```
CSS
```
.header {
float: left;
width: 400px;
}
.a {
height: 50px;
}
.b {
height: 70px;
padding-left: 100px;
}
```
 | 2011/06/25 | [
"https://Stackoverflow.com/questions/6475815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577455/"
] | There is no problem to be fixed here.
Your code should work in all browsers. I checked in IE, FF, Opera (all latest though). All good.
There are just 2 child divs with float:left. | Michael, i feel like you may have an overflow issue here regarding your padding and the various methods browsers compute the box model. Header A has a width of 400 but an image within of 400+the padding. Remove the padding or resize it's container to actually contain it. Other option is to set overflow to hidden |
71,893,079 | I've been following a tutorial on youtube for flutter. <https://www.youtube.com/watch?v=Zv5T2C1oKus>. I'm new to flutter and dart btw. I don't understand this error message.
>
> lib/main.dart:91:36: Error: The value 'null' can't be assigned to the
> parameter type 'Offset' because 'Offset' is not nullable.
>
>
> * 'Offset' is from 'dart:ui'.
> points.add(null);
> ^
>
>
>
here is my code
[](https://i.stack.imgur.com/n7ars.png)
[](https://i.stack.imgur.com/Py3ld.png) | 2022/04/16 | [
"https://Stackoverflow.com/questions/71893079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14872021/"
] | In the video you linked, there is a check whether `points[x]` is `null`, so I assume the elements of `points` should be nullable. You can achieve this with
```
List<Offset?> points = [];
```
(instead of `List<Offset> points = [];`).
The added questionmark makes it possible for elements of the list to be either a instance of the class `Offset` or the value `null`. | The points is non-nullable list.
So this time, it can be solved with to remove **points.add(null);** inside onPanEnd. (Or add non-null Offset.) |
68,987,980 | I've written a problem for an algorithm problem. I'm new to C++, and I'm getting the following error message when I try to run my code: "array initializer must be an initializer list". Here's the code itself:
```
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main(){
int n;
cin>>n;
int a[n][2];
int b[n];
for(int i=0;i<n;i++){
cin>>a[i][0];a[i][1]=i;
b[i]=a[i][0];
}
sort(a,a+n);
for(int i=1;i<n;i++)
{
if(a[i][0]<=a[i-1][0]){
a[i][0]=a[i-1][i]+1;
b[i]=a[i-1][i]+1;
}
}
for(int i=0;i<n;i++)
cout<<b[i]<<" ";
}
```
I don't know why I'm getting this error message. I've Googled it and couldn't find anything useful. If someone could explain to me why I'm getting this message and how to solve it, I'd really appreciate it. Thanks in advance. | 2021/08/30 | [
"https://Stackoverflow.com/questions/68987980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15306169/"
] | >
>
> ```
> cin>>n;
> int a[n][2];
>
> ```
>
>
The size of an array variable must be compile time constant. `n` is not compile time constant. The program is ill-formed.
>
> What alternative do I have?
>
>
>
If you want a runtime size array, then you must create the array in dynamic storage. Simplest approach is to use `std::vector`. Elements of vector cannot be arrays, but you can use `std::array` as the element type instead. Example:
```
std::vector<std::array<int, 2>> a;
```
>
>
> ```
> sort(a,a+n);
>
> ```
>
>
`a` is an array of arrays. Elements of tha array are themselves arrays. The arguments decay to be pointers to arrays. Pointer to array does not satisfy the requirement of being "value swappable" that is required by `std::sort`. Iterators to `std::array` are "value swappable", so this issue is solved by using that as the inner array as suggested above. | If you want to create an array, the size must be **constant number** or you should use **vector** instead. In addition, compiler says you have to assign your array to 0 with curly brackets like that:
```
int a[5][2]={{0}};
int b[5]={0};
``` |
440,533 | I read that all you need to start an induction motor is to apply the AC voltage, and with time the slippage decreases. How does this happen magnetically?
If a rotor, connected to a moderate sized mass, is stationary at t=0, and you apply a quickly rotating magnetic field, then the stator will spend half of its AC cycle with its magnetic vector ahead of the rotor, and the other half it will be behind. To me that means it rotates the rotor in the +ve direction for 1/2 of the 1/60 cycle (assuming 60Hz), but it rotates it backwards for the other half.
What am I missing? | 2019/05/26 | [
"https://electronics.stackexchange.com/questions/440533",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/71001/"
] | You're absolutely right that a rotor inside a magnet on a single-phase circuit won't start moving on its own. The key to getting it started is having a **rotating magnetic field**. The field of a magnet in a single-phase circuit doesn't rotate; it just switches polarity. Once the rotor is turning that's all it needs, but when it's stationary it needs a push to get it moving.
There are several ways to create that push. Many motors have an additional winding, called a starter winding, that's offset from the main winding. The power to that winding goes through a capacitor (that's the thing inside that cylinder on the top of the motor), which shifts the phase of the power coming into the starter winding. So as the incoming voltage rises to its peak, the starter winding produces its full magnetic field, and then, a bit later, the main winding hits its peak. The net magnetic field changes its direction as the main winding kicks in. That pulls the rotor a bit. Then the voltage switches direction, the momentum of the rotor keeps it moving, and the pull in the opposite direction pulls it around. Again, the starter winding gives the magnetic field a bit of rotation, and that, again, pulls the rotor more.
Once the rotor is up to speed, a centrifugal switch shuts off the starter winding, and the main winding is left on its own to provide all the power.
As you put more load on the motor, the rotor slows down, and lags further behind the magnetic field. That produces a stronger pull, which produces more torque, which adjusts for the increased load on the motor. | You were right if you talked about single-phase induction motors with no additional provisions. Such induction motors are rare for that very reason. You can find them as electrical brakes for example, because that starting problem doesn't apply then.
If you insisted on single-phase and single-coil (well, sort of), you had to create an anisotropy in the magnetic field in the rotor. That's done in a [shaded pole motor](https://en.wikipedia.org/wiki/Shaded-pole_motor). Such a motor has more standstill torque in one direction than the other, so it starts by itself. |
2,960,515 | Is it possible to echo something while the script for example is still running in a loop?
my problem:
I ask the server with Ajax and then the server is fetching mails and store them in Database. This took around 15 sec. During that Time the Server should echo his progress so that the Javascript can update a loading bar.
This is working with a php script without CodeIgniter well.
Is there a way to skip the output class and all that stuff to get a direct echo?
Thanks | 2010/06/02 | [
"https://Stackoverflow.com/questions/2960515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/334501/"
] | On many processors address zero is the reset vector, wherein lies the bootrom (BIOS on a PC), so you are unlikely to be storing anything at that physical address. On a processor with an MMU and a supporting OS, the physical and logical address addresses need not be the same, and the address zero may not be a valid logical address in the executing process context. | You are correct in noting that the address space at 0 is not usable storate for your program. For a number of reasons a variety of systems do not consider this a valid address space for your program anyway.
Allowing any valid address to be used would require a null value flag for all pointers. This would exceed the overhead of the lost memory at address 0. It would also require additional code to check and see if the address were null or not, wasting memory and processor cycles.
Ideally, the address that NULL pointer is using (usually 0) should return an error on access. VAX/VMS never mapped a page to address 0 so following the NULL pointer would result in a failure. |
47,833,675 | I've created an android app that calculates the factorial of an input number.
My code is:
```
void factorial(int x){
if(x>=0){
BigInteger res= new BigInteger("1");
for(int i=x; i>1; i--){
res = res.multiply(BigInteger.valueOf(i));
}
TextView text = (TextView)findViewById(R.id.resultTextView);
text.setText(res.toString());
}
}
```
It works but when I try calculating factorial 80.000 and more the app stucks for a moment and then exits, reloading the graphical 'desktop' inteface of android.
The same piece of code run by a pc creates no problems.
How can I fix my app to calculate those values rather than terminate itself?
Thank's in advance. | 2017/12/15 | [
"https://Stackoverflow.com/questions/47833675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6906418/"
] | Try this:
```
private class FactCalculator extends AsyncTask<Void, Void, BigInteger> {
int number = 0;
public FactCalculator(int i) {
this.number =i;
}
@Override
protected BigInteger doInBackground(final Void... params){
try{
if(number>=0) {
BigInteger res = new BigInteger("1");
for (int i = number; i > 1; i--) {
res = res.multiply(BigInteger.valueOf(i));
}
return res;
}
} catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(final BigInteger result) {
if (result != null) {
TextView text = (TextView)findViewById(R.id.resultTextView);
text.setText(result.toString());
}
}
}
```
Call it like:
```
new FactCalculator(80000).execute();
```
**Note**:- As others have pointed out in the comments it may be because the value is too large, there may be memory issues or to hold in a `String` or in the `TextView`, | Calculating factorials lead to very big numbers very fast. The factorial of 100 is 9.332621544 E+157. Your factorial is 3.097722251 E+357506! Although BigInteger theoretically has no limitations, I will suggest you to read the answer in [this question](https://stackoverflow.com/questions/12088436/what-does-biginteger-having-no-limit-mean).
Also BigInteger is an immutable class, so creating new ones in every loop is really heavy on your memory. Your code seems correct, but when you deal with factorials most of the times you fall into memory problems. |
5,437,164 | I have an ArrayCollection derived from a httpService call where the XML looks like the following:
>
>
> ```
> <data>
> <label>John</label><height>5.5</height>
> <label>John</label><height>7.2</height>
> <label>John</label><height>3.2</height>
> </data>
>
> ```
>
>
I know how to use Math.min and Math.max on an array but how would I get the min and max of just the height in this example? Thanks! | 2011/03/25 | [
"https://Stackoverflow.com/questions/5437164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/677325/"
] | You can achieve this with [Apache Commons StringUtils](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#removeEnd-java.lang.String-java.lang.String-) as follows:
```
String s = "http://almaden.ibm.com/";
StringUtils.removeEnd(s, "/")
``` | ```
if (null != str && str.length > 0 )
{
int endIndex = str.lastIndexOf("/");
if (endIndex != -1)
{
String newstr = str.subString(0, endIndex); // not forgot to put check if(endIndex != -1)
}
}
``` |
25,806 | I posted earlier about how I was surprised that a typical Calculus 1 course that meets 3-4 hours each week for 15 weeks only barely manages to reach the fundamental theorem by the end of the course. If we consider James Stewart's *Calculus: Early Transcendentals*, then the fundamental theorem of calculus is towards the end of Chapter 5 (5.3-5.5). As a reference, Chapter 1 is a review of functions, Chapter 2 is limits and the notion of a derivative, Chapter 3 is methods of differentiation and basic applications (related rates; differentials), Chapter 4 is more applications of derivatives (optimization; curve sketching), and Chapter 5 is integrals (culminating in the fundamental theorem).
There are 5 chapters with a total of 38 sections. And given 3 lectures per week per 15 weeks, there are 45 class meetings in a semester. Taking into account days for exams and other holidays, that leaves still about 40 classes, which is two more lectures than I need. In other words, the rate is 0.3 chapters per week.
I mentioned in my previous post that I am able to, for the most part, end my Calculus 1 course at around Chapter 11.3, which covers the integral test for infinite sequences and series. This is usually the last chapter of a Calculus 2 course (Chapters 6 - 11; although some instructors skip Ch. 9). This ends up being an average of 0.73 chapters per week.
I have not had any negative effects due to teaching at such a fast pace, but I decided to draft a syllabus that goes at the common pace. In this syllabus, I basically ended up having one 50-minute lecture for every single section of the text, with room to spare for quizzes on certain days. This rate allows me to finish at the fundamental theorem of calculus. For example, in this new syllabus, I am dedicating an entire 50 minutes to Chapter 3.2 (Product and Quotient Rules).
In my "fast" version of the lectures, I typically cover all rules of differentiation and trigonometric derivatives all in about 50 minutes. As such, I do not know how to drag out **only** the product and quotient rule for 50 minutes. I do not see any point in providing the amateur proof of these rules, since I am not teaching for math majors.
If any of you are familiar with Professor Leonard's YouTube series, his lectures about the product and quotient rules is one hour long! Is his style the same way most instructors teach? The comments from students generally say positive things about his content, but my students also say positive comments about my teaching in the student evaluations. Most of the comments point out that I am quick to the point with the material and examples.
My students have had success, but the only issue I see is that since the exams are departmental, the material being tested is usually topics we covered weeks ago. But because calculus is cumulative, it ends up not being too much of a problem. For example by the time they are taking the final exam, my students have had a lot of experience taking derivatives when doing integration by parts and other integration methods. Similarly, they breeze through the exam questions that are about basic integration, since they have experience with more advanced methods of integration. They can also compute limits much faster with knowledge of L'Hopital's Rule and the problems they did with limits in the improper integral sections. I have even had a handful of students test out of Calculus 2 after taking my class, since I essentially covered 90% of the material of Calculus 2.
I am not at a selective college. It is a small liberal arts college in the midwest. My students are not in an honors section. Exams are departmental. I do weekly quizzes, and two semi-exams in the semester. Homework is assigned but not graded for credit. The entire grading scale is based on assessments only, there are no cushion points.
I will be teaching Calculus 1 again next semester, and I will also be teaching Calculus 3. One problem with this is that I have already created lectures for Calculus 3 (covering Chapters 12 - 16 of Stewart's). My current playlist has 21 lectures each that is 50-55 minutes long. That means that if I follow the pace of may already recorded lectures, I will end up covering all of Calculus 3 by Week 6, and that still leaves me with 9 more weeks of class with nothing to do. Should I just start them on differential equations after? I guess I am not sure how much the students will grasp the material, but even so, I think Calculus 3 is easier on students than Calculus 1 (I won't have to review functions or worry about the students understanding the actual notion of derivatives and integrals). I asked my colleague for a copy of his calendar for Calculus 3, and he spends about 3-4 lectures per a single section (about an entire week on **just** double integrals over general regions, whereas in my 50-minute lecture, I covered double integrals in rectangular and general regions, and in polar coordinates.)
All advice is appreciated. I am always seeking to be a better instructor. | 2022/11/14 | [
"https://matheducators.stackexchange.com/questions/25806",
"https://matheducators.stackexchange.com",
"https://matheducators.stackexchange.com/users/20591/"
] | IF you want to fill more time (and that is what the question asks), the clear answer is to spend more time on in-class drill. You are verging back to debating if you should spend more time, in responding to answers. But that's not this question (which is "how", not "if", as your other question was).
FWIW, if you're really crushing it like you say, I would say the answer to the "if" question is no. [And this is coming from someone who usually pushes in class drill...but if you're getting results, you're getting results.]
You could just cover 1st semester calc and give students half the periods back. Or stick with your original scheme and teach both semesters of calculus (at least there is some drill of first semester and of algebra buried within the work of second semester) in a normal semester. I mean...it worked, right. Just keep your head low and ignore colleagues (no bragging and just go your way on the sly). | Either the centralized tests do not properly assess your students' understanding, or your students are being inspired by your fast-paced style to spend more of their own time on reading and doing exercises - things that the lecturer or a TA would usually be doing in the settings I have been part of, as a student long ago and as an educator for the past few decades.
It is unlikely (not impossible, but improbable) that you have found a magic recipe for accelerated learning of the same skills, at the same level, that take twice as long to master for other groups of students. Comparisons between US and any other country can sometimes be misleading, because of the often huge differences in math curriculum and the level of skill retained from lower grades, but I assume you are comparing apples and apples here.
Some students can learn at an amazing speed. However, calculus is hard for most people, and they require time for repetition and rote practice of problem solving.
You might possibly be giving your students a false sense of accomplishment by preparing them to pass the tests but not for applying math to actual problem solving. Note that I say "possibly". Only you and the people near you can know. |
6,527,762 | I am using IBOutletCollections to group several Instances of similar UI Elements. In particular I group a number of UIButtons (which are similar to buzzers in a quiz game) and a group of UILabels (which display the score). I want to make sure that the label directly over the button updates the score. I figured that it is easiest to access them by index. Unfortunately even if I add them in the same order, they do not always have the same indexes. Is there a way in Interface Builder to set the correct ordering. | 2011/06/29 | [
"https://Stackoverflow.com/questions/6527762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/347445/"
] | EDIT: Several commenters have claimed that more recent versions of Xcode return `IBOutletCollections` in the order the connections are made. Others have claimed that this approach didn't work for them in storyboards. I haven't tested this myself, but if you're willing to rely on undocumented behavior, then you may find that the explicit sorting I've proposed below is no longer necessary.
---
Unfortunately there doesn't seem to be any way to control the order of an `IBOutletCollection` in IB, so you'll need to sort the array after it's been loaded based on some property of the views. You could sort the views based on their `tag` property, but manually setting tags in IB can be rather tedious.
Fortunately we tend to lay out our views in the order we want to access them, so it's often sufficient to sort the array based on x or y position like this:
```
- (void)viewDidLoad
{
[super viewDidLoad];
// Order the labels based on their y position
self.labelsArray = [self.labelsArray sortedArrayUsingComparator:^NSComparisonResult(UILabel *label1, UILabel *label2) {
CGFloat label1Top = CGRectGetMinY(label1.frame);
CGFloat label2Top = CGRectGetMinY(label2.frame);
return [@(label1Top) compare:@(label2Top)];
}];
}
``` | Not as far as I am aware.
As a workaround, you could assign each of them a tag, sequentially. Have the buttons range 100, 101, 102, etc. and the labels 200, 201, 202, etc. Then add 100 to the button's tag to get its corresponding label's tag. You can then get the label by using `viewForTag:`.
Alternatively, you could group the corresponding objects into their own `UIView`, so you only have one button and one label per view. |
62,857,126 | I have many big strings with many characters (about 1000-1500 characters) and I want to write the string to a text file using python. However, I need the strings to occupy only a single line in a text file.
For example, consider two strings:
```
string_1 = "Mary had a little lamb
which was as white
as snow"
string_2 = "Jack and jill
went up a hill
to fetch a pail of
water"
```
When I write them to a text file, I want the strings to occupy only one line and not multiple lines.
text file eg:
```
Mary had a little lamb which was as white as snow
Jack and Jill went up a hill to fetch a pail of water
```
How can this be done? | 2020/07/12 | [
"https://Stackoverflow.com/questions/62857126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9578785/"
] | If you want all the strings to be written out on one line in a file without a newline separator between them there are a number of ways as others here have shown.
The interesting issue is how you get them back into a program again if that is needed, and getting them back into appropriate variables.
I like to use json (docs [here](https://docs.python.org/2/library/json.html#basic-usage)) for this kind of thing and you can get it to output all onto one line. This:
```py
import json
string_1 = "Mary had a little lamb which was as white as snow"
string_2 = "Jack and jill went up a hill to fetch a pail of water"
strs_d = {"string_1": string_1, "string_2": string_2}
with open("foo.txt","w") as fh:
json.dump(strs_d, fh)
```
would write out the following into a file:
```
{"string_1": "Mary had a little lamb which was as white as snow", "string_2": "Jack and jill went up a hill to fetch a pail of water"}
```
This can be easily reloaded back into a dictionary and the oroginal strings pulled back out.
If you do not care about the names of the original string variable, then you can use a list like this:
```py
import json
string_1 = "Mary had a little lamb which was as white as snow"
string_2 = "Jack and jill went up a hill to fetch a pail of water"
strs_l = [string_1, string_2]
with open("foo.txt","w") as fh:
json.dump(strs_l, fh)
```
and it outputs this:
```
["Mary had a little lamb which was as white as snow", "Jack and jill went up a hill to fetch a pail of water"]
```
which when reloaded from the file will get the strings all back into a list which can then be split into individual strings.
This all assumes that you want to reload the strings (and so do not mind the extra json info in the output to allow for the reloading) as opposed to just wanting them output to a file for some other need and cannot have the extra json formatting in the output.
Your example output does not have this, but your example output also is on more than one line and the question wanted it all on one line, so your needs are not entirely clear. | You can split the string to lines using parenthesis:
```py
s = (
"First line "
"second line "
"third line"
)
```
You can also use triple quotes and remove the newline characters using `strip` and `replace`:
```py
s = """
First line
Second line
Third line
""".strip().replace("\n", " ")
``` |
52,708,565 | I'm working on a Help project that contains thousands of .htm topics. Each topic has a heading (inside a h1 tag). Each heading contains a span tag. I'm looking for a script that would allow me to insert a period (".") separator before the span tag in every h1 tag across all topics.
For example, I need to change...
```
<h1>Heading<span>Heading</span></h1>
```
to...
```
<h1>Heading.<span>Heading</span></h1>
```
I've tried the following, but it doesn't seem to work. (Note that I'm a relative newb when it comes to jquery/scripting.)
```
$(function(){
$("h1.span").before(".");
});
```
Thanks in advance. | 2018/10/08 | [
"https://Stackoverflow.com/questions/52708565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10474834/"
] | Just use CSS to add it using after and contents
```css
h1 span::after{
content: "."
}
```
```html
<h1><span>Hello</span></h1>
<h1><span>World</span></h1>
<h1><span>Foo</span></h1>
<h1><span>Bar</span></h1>
``` | You could try this.
```js
$("h1 span").prepend(".")
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><span>My brain</span> <span>Yo</span></h1>
<h1>Some test <span>Yo</span></h1>
<h1>Another test<span>Yo</span></h1>
``` |
72,476,708 | I have this request using a curl command and I want to translate it to python using the requests library
```
curl -X POST https://endpoint/prod/api/Translations/start \
-H 'Authorization: Bearer <accessToken>' \
-H 'Content-Type: application/json' \
-d '{ "text": ["first segment to translate.", "second segment to translate."], "sourceLanguageCode": "en", "targetLanguageCode": "de", "model": "general", "useCase": "testing"}'
``` | 2022/06/02 | [
"https://Stackoverflow.com/questions/72476708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14080363/"
] | You can use `requests` library.
The following curl:
```
curl -X POST "https://www.magical-website.com/api/v2/token/refresh/" \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"refresh": "$REFRESH_TOKEN"
}'
```
I wrote in python the following way:
```py
import requests
def get_new_token():
url = 'https://www.magical-website.com/api/v2/token/refresh/'
token = constants.THE_TOKEN
payload = f'{{ "refresh": "{token}" }}'
headers = {"accept": "application/json", "Content-Type": "application/json"}
print("Token handling ....")
r = requests.post(url, data=payload, headers=headers)
print(f"Token status: {r.status_code}")
return r.json()['access']
``` | You can try this one.
```
import requests
url = "https://endpoint/prod/api/Translations/start"
payload = {
"text": ...,
"sourceLanguageCode": ...,
...
}
headers = { "Authorization": "Bearer ...", "Content-Type": "application/json" }
res = requests.post(url, data = payload, headers = headers)
print(res.status_code)
print(res.text)
``` |
4,154,707 | I'm trying to delete records from one database based on a selection criteria of another. We have two tables, emailNotification which stores a list of jobs and emails. Then we have jobs. I want to clear out emailNotifications for jobs that have been closed. I found some earlier examples on Stackoverflow that lead me to this type of syntax (I was previously trying to do the join before the where).
```
DELETE FROM emailNotification
WHERE notificationId IN (
SELECT notificationId FROM emailNotification e
LEFT JOIN jobs j ON j.jobId = e.jobId
WHERE j.active = 1
)
```
I'm getting the error, you can't specify the target table 'emailNotication' for update in the FROM Clause. | 2010/11/11 | [
"https://Stackoverflow.com/questions/4154707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/158244/"
] | MySQL DELETE records with JOIN
Delete multiple records from multiple table using Single Query is As below:
You generally use INNER JOIN in the SELECT statement to select records from a table that have corresponding records in other tables. We can also use the INNER JOIN clause with the DELETE statement to delete records from a table and also the corresponding records in other tables e.g., to delete records from both T1 and T2 tables that meet a particular condition, you use the following statement:
```
DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition
```
Notice that you put table names T1 and T2 between DELETE and FROM. If you omit the T1 table, the DELETE statement only deletes records in the T2 table, and if you omit the T2 table, only records in the T1 table are deleted.
The join condition `T1.key = T2`.key specifies the corresponding records in the T2 table that need be deleted.
The condition in the WHERE clause specifies which records in the T1 and T2 that need to be deleted. | If the aim is deleting matching rows, like deleting rows in 1st table which have relations in 2nd, to avoid deleting whole 1st table you should put additional "where" condition for 2nd table
```
DELETE f FROM firsttable f
LEFT JOIN secondtable s ON f.related_id = .jobId
WHERE s.related_id
``` |
38,950,301 | I am trying to write a stored procedure in SQL Server 2008, which should generate ID number on the basis of another column's first letter like below:
[](https://i.stack.imgur.com/GMVFc.jpg)
I am using SQL Server 2008. Would be grateful on any help. Regards | 2016/08/15 | [
"https://Stackoverflow.com/questions/38950301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3909410/"
] | Not sure how your localhost:3003 is configured; With or without `https:`...
Say you are using http://localhost:3000 (not https:);
The `Secure` cookie attribute from your target might be the cause for your browser to omit the cookie.
>
> 4.1.2.5. The Secure Attribute
>
>
> The Secure attribute limits the scope of the cookie to "secure"
>
> channels (where "secure" is defined by the user agent). When a
>
> cookie has the Secure attribute, the user agent will include the
>
> cookie in an HTTP request only if the request is transmitted over a
>
> secure channel (typically HTTP over Transport Layer Security (TLS)
>
>
>
source: <https://www.rfc-editor.org/rfc/rfc6265#section-4.1.2.5>
Browsers may omit cookies based on the algorithm described in: <https://www.rfc-editor.org/rfc/rfc6265#section-5.4>
Try removing the `Secure Attribute` and see if that helps | B.Ma's answer give me a hint to solve my problem with the webpack-dev-server which probably uses the http-proxy-middleware under the hood to proxy the request. The problem comes with the httpOnly cookies and this approach solved it.
Here is my config that I used in the webpack.conf.js:
```
let myappSessionValidationCookie = '';
module.exports = {
...
devServer: {
publicPath: 'http://localhost:9000/',
...
proxy: {
'/api': {
target: 'http://localhost/myapp',
changeOrigin: true,
onProxyReq: function (proxyReq) {
if (myappSessionValidationCookie) {
proxyReq.setHeader('cookie', myappSessionValidationCookie);
}
},
onProxyRes: function (proxyRes) {
const proxyCookie = proxyRes.headers['set-cookie'];
if (proxyCookie) {
myappSessionValidationCookie = proxyCookie;
}
},
},
},
},
});
```
Some explanation for the configuration. I have a backend that is serving the app's api under the localhost/myapp/api/\* and sets a httpOnly cookie that is for authentication purposes. That header (set-cookie) was not transferred by the proxy to the new location (localhost:9000/myapp/api/\*) so the browser is not keeping it and all following requests were without this cookie and failed.
All the credits goes to B.Ma. Many thanks for the post!!! |
19,491,324 | I am trying to create a list of members against whom I would be running comparison operation with multiple values
Here's my code
```
HashSet<string> respCodeList = new HashSet<string> { "051", "052", "055", "056", "058", "059", "061", "063", "064" };
if (respCodeList.Contains(object.Property))
```
I am getting error in if statement :
>
> 'object' does not contain a definition for 'Property'
>
>
>
Found this way of doing comparison through google, but not sure why this error is coming up
Complete Code:
```
/* Microsoft SQL Server Integration Services Script Component
* Write scripts using Microsoft Visual C# 2008.
* ScriptMain is the entry point class of the script.*/
using System;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Collections.Generic;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public override void PreExecute()
{
base.PreExecute();
/*
Add your code here for preprocessing or remove if not needed
*/
}
public override void PostExecute()
{
base.PostExecute();
/*
Add your code here for postprocessing or remove if not needed
You can set read/write variables here, for example:
Variables.MyIntVar = 100
*/
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string TermnLn = Row.TermnLn;
string TransTypeCode = Row.TransTypeCode;
string ReversalReason = Row.ReversalReason;
string TransResponseCode = Row.TransResponseCode;
string CardIssuerLn = Row.CardIssuerLn;
string transType = Row.TransTypeCode;
int origTransAmount = (int)Row.origTransAmount;
int actualTransAmount = (int)Row.actualTransAmount;
HashSet<string> respCodeList = new HashSet<string> { "051", "052", "055", "056", "058", "059", "061", "063", "064" };
if (TransTypeCode == "10") // IF IT IS WITHDRAWAL
{
if (TermnLn== "PRO1") // CHECK FOR AXIS TERMINAL
{
if (ReversalReason == "00") //IT IS NOT A REVERSAL
{
if (respCodeList.Contains(Row.TransResponseCode))
{
Row.CashDispensed = origTransAmount/100; //cash dispense
}
}
else
{
if (respCodeList.Contains(Row.TransResponseCode))
{
Row.CashDispensed =(actualTransAmount/100 - origTransAmount/100); //cash dispense
}
}
}
if (TermnLn!= "PRO1" && CardIssuerLn == "PRO1") // CHECK FOR NON AXIS TERMINAL
{
if (ReversalReason == "00") //IT IS NOT A REVERSAL
{
if (respCodeList.Contains(Row.TransResponseCode))
{
Row.CashDispensed = origTransAmount / 100; //cash dispense non axis
}
}
else
{
if (respCodeList.Contains(Row.TransResponseCode))
{
Row.CashDispensed = (actualTransAmount / 100 - origTransAmount / 100); //cash dispense
}
}
}
}
if (ReversalReason == "00") //IT IS NOT A REVERSAL
{
if (respCodeList.Contains(Row.TransResponseCode))
{
Row.SuccessTransOrigAmt = origTransAmount / 100; //SuccessTransOrigAmt
}
}
if (ReversalReason != "00" && ReversalReason != " ")
{
if (transType == "0420" || transType == "0412" || transType == "0430")
{
if (origTransAmount == actualTransAmount)
{
Row.ReversalAmount = origTransAmount / 100; //ReversalAmount
}
else
{
Row.ReversalAmount = (actualTransAmount / 100 - origTransAmount / 100); //ReversalAmount
}
}
}
}
}
``` | 2013/10/21 | [
"https://Stackoverflow.com/questions/19491324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385057/"
] | If a save operation fails then the client side state will still be either "added", "modified" or "deleted". Changes are only accepted if a save succeeds. This allows you to "resave" the same entity or entities after you have "corrected" the issue without having to reassemble the changes.
You can also use Breeze *EntityAspect.rejectChanges* to return an entity to its state when it was last queried.
The simplest way to copy an entity is to use the Breeze *EntityManager.createEntity* method and pass in an object that contains just the data properties from the source entity. The reason this will work is that Breeze will automatically link up all of the navigation properties for you based on the foreign key data properties once the new entity is attached to the entityManager, which occurs internally as the last step of the createEntity call.
So you might try something like this ( I didn't actually test this code fragment but this approach definitely does work.
```
function cloneEntity(sourceEntity, keyName, newKeyValue) {
var sourceEntityType = sourceEntity.entityType;
var sourceDataProperties = sourceEntityType.dataProperties;
var configEntity = {};
sourceDataProperties.forEach(function(dp) {
configEntity[dp.name] = sourceEntity.getProperty(dp.name);
});
// you will need to give the entity a unique key before calling createEntity
// you could also get the keyName from metadata but I was too lazy to do that here.
configEntity[keyName] = newKeyValue;
var cloneEntity = myEntityManager.createEntity(fooEntityType, configEntity, breeze.EntityState.Added);
return cloneEntity;
}
``` | Have you tried using [EntityAspect.rejectChanges()](http://www.breezejs.com/sites/all/apidocs/classes/EntityAspect.html#method_rejectChanges) ?
>
> Returns the entity to an EntityState of 'Unchanged' by rejecting all changes made to it since the entity was last queried had 'rejectChanges' called on it.
>
>
> |
20,651,301 | I am trying to open another activity through Intent on Button press.
But the **app crashes every time** on launch.
**IntentTest.java:**
```
package com.example.intenttest;
public class IntentTest extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_test);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(IntentTest.this, IntentTest2.class);
startActivity(intent2);
}
});
}
}
```
**IntentTest2.java:**
```
package com.example.intenttest;
public class IntentTest2 extends Activity {
TextView textView1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_test2);
textView1=(TextView)findViewById(R.id.textView1);
}
}
```
**Manifest:**
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intenttest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.intenttest.IntentTest"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:label="@string/app_name" android:name="com.example.intenttest.IntentTest2" />
</application>
</manifest>
```
Here is the **LogCat** where the app crashes:
```
12-18 11:59:59.563: W/Trace(20985): error opening trace file: No such file or directory (2)
12-18 11:59:59.623: D/AndroidRuntime(20985): Shutting down VM
12-18 11:59:59.623: W/dalvikvm(20985): threadid=1: thread exiting with uncaught exception (group=0x40c8d930)
12-18 11:59:59.633: E/AndroidRuntime(20985): FATAL EXCEPTION: main
12-18 11:59:59.633: E/AndroidRuntime(20985): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.intenttest/com.example.intenttest.IntentTest}: java.lang.NullPointerException
```
I cant find out what is wrong. Please help. | 2013/12/18 | [
"https://Stackoverflow.com/questions/20651301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020956/"
] | Because you did not initialize `b1(Button)`
```
b1 = (Button)findViewById(R.id.button_id);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(IntentTest.this, IntentTest2.class);
startActivity(intent2);
}
});
``` | You did not initialize your button b1 in IntentTest class,
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_test);
b1=(Button)findViewById(R.id.your_btn_name);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(IntentTest.this, IntentTest2.class);
startActivity(intent2);
}
});
}
``` |
104,137 | Some time ago I saw the [Nikon's roadmap](https://www.nikon.com/news/2018/img/pic_180823_03_08.jpg) for new S-Line lenses and today I found an [update to this roadmap](https://petapixel.com/2019/01/08/this-is-nikons-updated-mirrorless-lens-roadmap/).
I am wondering why Nikon is building lenses with those apertures first, is it a market strategy or is there a reason behind of this?
Here is what I saw on the roadmap:
* 24-70mm f/4 comes first (2018) and then 24-70mm f/2.8 (2019)
* 50mm f/1.8 (2018) and then 50mm f/1.2 (2020)
* A lot of f/1.8 lenses annunced for the 3 first years (35mm, 50mm, 20mm, 85mm, 24mm) and probably we will se wider apertures for those lenses on the future.
Of course there are some exceptions to this behavior, like the 70-200mm f/2.8 and the astonishing 58mm f/0.95 (sadly this last one will be only manual focus). | 2019/01/09 | [
"https://photo.stackexchange.com/questions/104137",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/79309/"
] | Everyone *talks* a lot more about the premium, widest aperture lenses.
But a lot more folks *buy* the lower priced, narrower aperture lenses.
I think that is the primary strategy: To sell as many lenses in as short a time as is possible to get users anchored in the new system.
Those who tend to buy more expensive premium lenses also tend to use more than one body, so they're probably going to be straddling the fence for a while longer. They likely already have premium lenses in the old mount that they can adapt to their new mirrorless body. So it will take a greater performance boost to convince those buyers that the new expensive lenses that don't work on their older, DSLR backup bodies are worth the price. | It is more difficult to make highly corrected wide aperture lenses. Perhaps it is additionally complicated by the shorter flange distance of the Z-mount. |
18,768 | I am moving from creating maps with Illustrator to making them with QGIS and actual data. One of the things I haven't been able to re-create in QGIS are the smooth curved lines I can get in Illustrator. I am not talking about Join and Cap Styles, but how an entire line is rendered.
I am looking for an answer that doesn't include exporting as SVG to Illustrator and finishing the map there.
Also, I realize they could be considered an inaccurate representation but, for the most part, these maps are for giving riders an idea of where they are and don't necessarily have to be an exact representation.
Here is an example of what I mean:
 | 2012/01/12 | [
"https://gis.stackexchange.com/questions/18768",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/584/"
] | Check out the Generalizer plugin, it should do what you want. The plugin has smoothing options which work quite well.
It doesn't change how your lines are rendered but instead makes a new shapefile with smoothing (or simplification/generalization) applied.

 | There is a **Smooth** geoalghoritm under `Processing Toolbox -> Vector geometry -> Smooth`.
[](https://i.stack.imgur.com/nhWqQ.png)
>
> This algorithm smooths the geometries in a line or polygon layer. It
> creates a new layer with the same features as the ones in the input
> layer, but with geometries containing a higher number of vertices and
> corners in the geometries smoothed out.
>
>
> The iterations parameter dictates how many smoothing iterations will be applied to each geometry. A higher number of iterations
> results in smoother geometries with the cost of greater number of
> nodes in the geometries.
>
>
> The offset parameter controls how "tightly" the smoothed geometries follow the original geometries. Smaller values results in a
> tighter fit, and larger values will create a looser fit.
>
>
> The maximum angle parameter can be used to prevent smoothing of nodes with large angles. Any node where the angle of the segments to
> either side is larger than this will not be smoothed. For example,
> setting the maximum angle to 90 degrees or lower would preserve right
> angles in the geometry.
>
>
> If input geometries contain Z or M values, these will also be smoothed and the output geometry will retain the same dimensionality
> as the input geometry.
>
>
> |
3,870,808 | is there a way to stop execution and return a different value in a before do block in sinatra ?
```
before do
# code is here
# I would like to 'return "Message"'
# I would like "/home" to not get called.
end
// rest of the code
get '/home' do
end
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3870808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127511/"
] | ```
before do
halt 401, {'Content-Type' => 'text/plain'}, 'Message!'
end
```
You can specify only status if you want, here's example with status, headers and body | On <http://www.sinatrarb.com/intro> Filters section
>
> Before filters are evaluated before
> each request within the context of the
> request and can modify the request and
> response. Instance variables set in
> filters are accessible by routes and
> templates:
>
>
>
```
before do
@note = 'Hi!'
request.path_info = '/foo/bar/baz'
end
get '/foo/*' do
@note #=> 'Hi!'
params[:splat] #=> 'bar/baz'
end
``` |
21,982,619 | i am storing logged in user name in arraylist and than putting the arraylist in session .Whenever the user logged in for the first time it is printing the user name but when refreshing the page the same name is printing twice but i only want to print the username only one time no matter how many times the user refresh the page please help
```
String username = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session = request.getSession(true);
session.setAttribute("username", username);
session.setAttribute("password", password);
response.setContentType("text/html");
ArrayList<user> users = (ArrayList<user>) sc
.getAttribute("users");
if (users == null) {
System.out.println("loggedInUsers creates");
users = new ArrayList<user>();
}
users.add(new user(Name, U_ID, Pass));
sc.setAttribute("users", users);
users = (ArrayList<user>) sc.getAttribute("users");
for (int i = 0; i <= users.size() - 1; i++) {
user user = users.get(i);
out.println(user.getUserName()+ "<br>");
//out.println("<br/>" + user.get(i));
}
``` | 2014/02/24 | [
"https://Stackoverflow.com/questions/21982619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2920839/"
] | Use a Hashmap, as it does not allow duplicates and will replace the original key with the new one.
```
HashMap hm = new HashMap();
hm.put (U_ID, new user(Name, U_ID, Pass));
``` | I am not sure what you are asking for but as far as i understood your code following changes can be done to your programme.Let me know if it helps.
```
String username = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session = request.getSession(true);
session.setAttribute("username", username);
session.setAttribute("password", password);
response.setContentType("text/html");
ArrayList<user> users = (ArrayList<user>) sc
.getAttribute("users");
boolean shouldPrint = false; //declare this variable to check if printing of username is required
if (users == null) {
shouldPrint = true; //set this value to true to print username
System.out.println("loggedInUsers creates");
users = new ArrayList<user>();
}
users.add(new user(Name, U_ID, Pass));
sc.setAttribute("users", users);
users = (ArrayList<user>) sc.getAttribute("users");
/**********As far as i understood your code.You need to set condition here to prevent twice printing of user name***********************************************/
if(shouldPrint)
{
for (int i = 0; i <= users.size() - 1; i++) {
user user = users.get(i);
out.println(user.getUserName()+ "<br>");
//out.println("<br/>" + user.get(i));
}
}
``` |
8,055,889 | In our web application, we have print functionality for a couple of our pages and the approach we take is to put the current page's content in a globally available iframe's document and print the iframe (using Javascript). This works totally fine in Firefox but in IE it prints the iframe in a very small font, almost unreadable.
All the CSS's applied in both the browsers are same, I ensured that the HTML being printed is not overflowing in any way (making IE to fit the content or something)...and still IE print is very small. Interestingly, if I change the printing logic to write to a new window and then do window.print(), everything works fine in IE as well and the font is as big as required/specified by CSS.
Has anyone faced a similar problem with iframe.print() in IE?
Thanks for the help.
Nitin | 2011/11/08 | [
"https://Stackoverflow.com/questions/8055889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/757483/"
] | Was having the small print on IE issue today, and to fix I simply adjusted my print function as so:
```
$(document).ready(function(){
$("#printFrame").click(function(){
if (document.queryCommandSupported('print'))
{
$("#iframe").get(0).contentWindow.document.execCommand('print', false, null);
}
else
{
$("#iframe").get(0).contentWindow.focus();
$("#iframe").get(0).contentWindow.print();
}
});
});
```
Now it seems to print out the same on IE, Chrome and Firefox. Posted here because this solution was hard for me to find, so hopefully this will help someone. | Yes, we're seeing the same thing. If we open the same page directly it prints as you would expect. When it is loaded in an iframe and printed it makes everything smaller; not just the font.
This is using IE9 on Windows 7. |
359,820 | Is there a single adjective that means "does not use much energy" / "not using much energy"?
**I do not mean "efficient"**.
Efficient means something that does not waste much energy - something efficient could use a lot of energy for a specific purpose, yet not waste much energy on actions that do not achieve that purpose/not waste energy as heat or sound or whatever.
However, something \*word I seek\* may or may not be efficient, i.e may waste very little, or very much energy, in trying to perform a task, but does not/will not **use** or **consume** much energy in trying to perform the task - whether some of this energy is wasted or not. | 2016/11/23 | [
"https://english.stackexchange.com/questions/359820",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/207229/"
] | *low-power* or maybe *low-powered*
From a physics standpoint Power = Work / Time. A low-power device does not take in much (electrical) energy. (In the end, all that energy comes out one way or the other. Often much of it as heat.) | Try "unvigorous". Since vigorous means "Characterized by forceful and energetic action or activity" and you're after the opposite of that, just invert the meaning by prefixing it with "un".
"Unvigorous" might not presently be in the dictionary, but perhaps it ought to be...
Other suggestions: unenergetic, lethargic, economical, thrifty |
2,383,554 | In C/C++, there is a 'write() function which let me write to either file or a socket, I just pass in the file descriptor accordingly). And there is a fprintf() which allow me to do fprintf (myFile, "hello %d", name); but it only works for file.
Is there any api which allows me to do both?
i.e. able to let me do print formatting and able to switch between writing to file or socket?
Thank you. | 2010/03/04 | [
"https://Stackoverflow.com/questions/2383554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/114970/"
] | In C, on POSIX-ish machines (which you must have to be using 'write()'), you can use:
* `fdopen()` to create a file stream from a file descriptor.
* `fileno()` to obtain a file descriptor from a file stream.
You need to be careful about flushing the file stream at appropriate times before using the matching file descriptor. | generalizing tusbar answer, and to make it work with visual studio you can try the following codes:
`
```
int fdprintf(int fd, const char* fmt, ...) {
int cc;
va_list args;
va_start(args, fmt);
int len = _vscprintf(fmt,args) + 1;
char* buffer = new char[len];
buffer[len] = 0;
if ((cc = vsprintf_s(buffer, len-1, fmt, args)) > 0) {
write(fd, buffer, cc);
}
va_end(args);
delete[] buffer;
return cc;
}
```
` |
48,269,698 | I am trying to return a vector of structs from one object to another. My first idea is to return a reference to the vector. Both object files include the struct in question (the listener struct) and the function doing the returning looks as such:
```
vector<Listener>* Component::GetListeners() {
vector<Listener> listeners;
for (int i = 0; i < listenerSize; i++) {
Listener listener = { id, static_cast<EventType>(Component::listensFor[i]) };
listeners.push_back(listener);
}
return &listeners;
}
```
A vector of listeners is constructed and then the address of the vector is returned
The problem arises when I receive the pointer in my next function:
```
void Entity::AddComponent(Component c) {
components.push_back(c);
vector<Listener> *listeners = c.GetListeners();
for (int i = 0; i < listeners->size; i++) {
}
}
```
The error occurs at the line:
```
vector<Listener> *listeners = c.GetListeners();
```
The error states that
```
A value of type "std::vector<<error-type>, std::allocator<<error-type>>>*" cannot be used to initialize entity of type "std::vector<<Listener>, std::allocator<<Listener>>>*"
```
I've tried to research this error but have come across nothing to indicate why exactly it assumes the returned vector is defined as error-type. any help would be greatly appreciated, thanks in advance.
**Edit**
I was informed that when I passed the address of listeners, which was a local variable it did not circumvent the destruction of the local variable when the function was finished (actually quite obvious when it was brought to my attention thank you all). Unfortunately even though I have made the adjustments to return the vector by itself rather than its address I am still receiving the exact same error message (minus the pointers of course). My code is now as such:
```
vector<Listener> Component::GetListeners() {
vector<Listener> listeners;
for (int i = 0; i < listenerSize; i++) {
Listener listener = { this, static_cast<EventType>(Component::listensFor[i]) };
listeners.push_back(listener);
}
return listeners;
}
void Entity::AddComponent(Component c) {
components.push_back(c);
vector<Listener> listeners = c.GetListeners();
for (int i = 0; i < listeners.size; i++) {
}
}
```
**More Code**
Event.h
```
struct Listener {
Component *component;
EventType type;
};
enum EventType {
PhysCol = 0,
WheelRayCol = 1,
Accelerate = 2,
Turn = 3,
Fire = 4,
Damage = 5
};
class Event {
public:
static EventType type;
Entity *actor;
};
```
Component.h
```
#include "Event.h"
class Component {
private:
void Invoke(Event *e);
//int entityID;
Entity *entity;
int id;
public:
static int listensFor[0];
//static vector<int> listensFor;
static int listenerSize;
static ComponentType type;
bool enabled = true;
//Component();
void HandleEvent(Event *event);
//static Component CreateComponent(ComponentType type);
vector<Listener> GetListeners();
int GetID();
void RegisterEntity(Entity *e);
};
int Component::listenerSize = 0;
```
Component.cpp
```
#include "Component.h"
vector<Listener> Component::GetListeners() {
vector<Listener> listeners;
for (int i = 0; i < listenerSize; i++) {
Listener listener = { this, static_cast<EventType>(Component::listensFor[i]) };
listeners.push_back(listener);
}
return listeners;
}
```
Entity.h
```
#include "Event.h"
class Entity {
public:
Transform transform;
Component GetComponent(ComponentType type);
void HandleEvent(Event *event);
void AddComponent(Component component);
int GetId();
std::string GetTag();
bool MatchesTag(std::string tag);
private:
int id;
std::string tag;
std::vector<Component> components;
std::vector<Listener> listeners;
};
```
Entity.cpp
```
#include "Entity.h"
void Entity::AddComponent(Component c) {
components.push_back(c);
vector<Listener> l = c.GetListeners();
for (int i = 0; i < l.size; i++) {
listeners.push_back(l[i]);
}
}
``` | 2018/01/15 | [
"https://Stackoverflow.com/questions/48269698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9211144/"
] | In the below code the button cycles through the decimal numerals except for 0, which are basically sudoku numbers, for a `widget`'s text:
```
import tkinter as tk
def cycle(widget):
widget['text'] = (widget['text'] % 9) + 1
root = tk.Tk()
btn = tk.Button(root, text=1)
btn['command'] = lambda widget=btn: cycle(widget)
btn.pack()
root.mainloop()
``` | You have to fix your lambda values in the button callback, this is the main change that I added to your code. All other edits are mainly to make the code clearer and remove all unnecessary parts.
Take home message ist here, that you are basically always using the last iterator value for the callback function of `Button(command=...)`, if you're not fixing the values you pass to you lambda function. This addition of `row=rowindex,...` forces Python to look back/save the values while create the buttons.
```
import numpy as np
hardUnsolved=np.array([[8,0,0,0,0,0,0,0,0],...])
def btnCommand(row, col, x):
x += 1
hardUnsolved[row][col] = x
createGrid()
#-----------------------------MAIN CODE------------------
def createGrid():
for rowindex in range (9):
for colindex in range (9):
if ((rowindex in (0,1,2,6,7,8) and colindex in (3,4,5)) or \
rowindex in (3,4,5) and colindex in (0,1,2,6,7,8))):
colour='blue'
else:
colour='white'
x=hardUnsolved[rowindex][colindex]
if x==0:
colourTxt='red'
else:
colourTxt='black'
btn=Button(frame, width=4, height=3, bg=colour, text=x, fg=colourTxt,
command=lambda row=rowindex, col=colindex, x=x: btnCommand(row, col, x))
btn.grid(row=rowindex, column=colindex, sticky=N+S+E+W)
btn.grid(row=rowindex, column=colindex, sticky=N+S+E+W)
mainloop()
createGrid()
```
*Edit: I also imported `numpy` so that the assignment of values to your grid is a little bit more intuitive and clean.* |
70,135,719 | I need to write a function that receives an non-negative integer and returns:
```
[] for n=0
[[]] for n=1
[[],[[]]] for n=2
[[],[[]],[[],[[]]]] for n=3
```
And so on. For `n`, we will receive an `n` sized list, so that in index `i` there will be all the `i-1` elements from the list. I don't know how to explain that better, English isn't my first language.
**I'm not allowed to use list slicing or loops** and I'm supposed to create deep copies of each list, without the `copy` module. I'm not allowed to let 2 different lists or indexes point to the same list in memory.
This is what I tried:
```
def list_seq(x, outer_list=[]):
if x == 0:
return []
outer_list.append(list_seq(x-1,outer_list))
return outer_list
```
And the output for `print(list_seq(2))` is `[[], [...]]`. | 2021/11/27 | [
"https://Stackoverflow.com/questions/70135719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17499674/"
] | If you can't use loops, you can use the following:
```
def recursive_list(n):
if n == 0:
return []
else:
return recursive_list(n-1) + [recursive_list(n-1)]
```
EDIT
----
You can do the following if you want to use `append`:
```
def recursive_list(n: int) -> list:
if n:
result = recursive_list(n-1)
result.append(recursive_list(n-1))
return result
return []
```
**NOTE** as pointed out in the comments, `caching` introduces some reference issues, so I have removed the cached versions. | You can write this down as a recursive function using a simple list comprehension:
```
def f(n):
return [f(i) for i in range(n)]
```
Or instead of the list comprehension, you could also use `map`:
```
def f(n):
return list(map(f, range(n)))
```
Note, though, that without [caching](https://docs.python.org/3/library/functools.html#functools.lru_cache) this is going to get rather slow rather quickly. |
637,505 | I have an array of dates in a one week range stored in an unusual way.
The Dates are stored in this numeric format: 12150
From left to right:
1st digit represents day: 1 = sunday, 2 = monday, 3 = tuesday, ...., 7 = saturday
next two digits represent hour in a 24 hour system: 00 = midnight, 23 = 11pm
next two digits represent minutes: 00-59
Given an input date and a start date and end date I need to know if the input date is between the start and end date.
I have an algorithm right now that I *think* works 100% of the time, but I am not sure.
In any case, I think there is probably a better and simpler way to do this and I was wondering if anybody knew what that algorithm was.
If not it would be cool if someone could double check my work and verify that it does actually work for 100% of valid cases.
What I have right now is:
```
if (startDate < inputDate &&
endDate > inputDate) {
inRange = yes;
}
else if (endDate < startDate) {
if((inputDate + 72359) > startDate &&
(inputDate + 72359) < endDate) {
inRange = yes;
}
else if((inputDate + 72359) > startDate &&
(inputDate + 72359) < (endDate + 72359)) {
inRange = yes;
}
}
``` | 2009/03/12 | [
"https://Stackoverflow.com/questions/637505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20895/"
] | How about
```
const int MAX = 72460; // Or anything more than the highest legal value
inRange = (MAX + inputDate - startDate) % MAX <
(MAX + endDate - startDate) % MAX;
```
This assumes of course that all the dates are well formed (according to your specs).
This addresses the case where the start is "after" the end. (e.g. Friday is in range if start is Wednesday and end is Monday)
It may take a second to see (which probably isn't good, because readability is usually the most important) but I think it does work.
Here's the basic trick:
```
Legend:
0: Minimum time
M: Maximum time
S: Start time
1,2,3: Input Time test points
E: End Time
The S E => Not in range
2 In range
3 > E => Not in range
The S > E case
0 M
Original -1--E----2---S--3--
Add Max -------------------1--E----2---S--3--
Subtract StartDate ------1--E----2---S--3--
% Max S--3--1--E----2----
1 In range
2 > E => Not in range
3 In range
```
If you really want to go nuts (and be even more difficult to decipher)
```
const int MAX = 0x20000;
const int MASK = 0x1FFFF;
int maxMinusStart = MAX - startDate;
inRange = (maxMinusStart + inputDate) & MASK <
(maxMinusStart + endDate) & MASK;
```
which ought to be slightly faster (trading modulus for a bitwise and) which we can do since the value of MAX doesn't really matter (as long as it exceeds the maximum well-formed value) and we're free to choose one that makes our computations easy.
(And of course you can replace the `<` with a `<=` if that's what you really need) | The simplest solution i found is this:
said x your generic time and S, E the start and end time respectively (with 0 < S,E < T):
```
f(x) = [(x-S) * (x-E) * (E-S) < 0]
```
This function returns TRUE if x is in between the start and end time, and FALSE otherwise.
It will also take care of start time bigger than end time (i.e. you start working at 20:00 and finish at 04:00, 23:13 will return TRUE)
i must say, considering the multiplications, it could not be the most efficient in terms of speed, but it is definitely the most compact (and pretty IMHO)
EDIT:
i found a much more elegant and efficient solution:
```
f(x) = (x<S) XOR (x<E) XOR (E<S)
```
you can substitute XOR with the "different" operator ( != )
I explain it:
The first formula comes from the considering the relation inequality study:
if S < E:
```
...............S.....E..........
(x-S)----------+++++++++++++++++
(x-E)----------------+++++++++++
(E-S)+++++++++++++++++++++++++++
total++++++++++------+++++++++++
```
so, the total is negative if x is in between S and E
if S > E:
```
...............E.....S..........
(x-S)----------------+++++++++++
(x-E)----------+++++++++++++++++
(E-S)---------------------------
total----------++++++-----------
```
so, the total is negative if x is bigger than S or smaller than E
To reach the final equation, you decompose the first formula in 3 terms:
```
(x-S)<0 => x<S
(x-E)<0 => x<E
(E-S)<0 => E<S
```
the product of these terms is negative only if they are all negative (true, true, true) or only one is negative and the other are positive (true, false, false, but the order does not matter)
Therefore the problem can be solved via
```
f(x) = (x<S) != (x<E) != (E<S)
```
These solution can be applied to any similar problem with periodic system, such as checking if the angle x is inside the arc formed by the two angles S and E.
Just make sure that all the variable are between 0 and the period of your system (2PI for arcs in a circle, 24h for hours, 24\*60\*60 for the seconds count of a day.....and so on) |
7,999,240 | I have a feeling this is going to be really simple. I don't know if I'm just missing a trick here, or searching for the wrong phrases.
I'm looking for a profiling or code coverage (don't really know which category this falls in) that can monitor an application (preferably let me start and stop the monitoring) and count the number of times a method has been called. I've been tasked with optimising some old code and whilst doing so, I've found a few methods that are being called twice or even 3 times, where they only need to be called once.
I have a feeling there could be more of these..
On a side note: *I'm actually a big fan of the JetBrains .NET tools. I'm using ReSharper, dotPeek and dotTrace at the moment (but can't find a way to do this). Is it worth looking into dotCover?* | 2011/11/03 | [
"https://Stackoverflow.com/questions/7999240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369247/"
] | [Visual Studio 2010 Premium](http://msdn.microsoft.com/en-us/library/z9z62c29.aspx) and above have performance profiling tools built in that can do exactly what you're asking.
[Here's](http://blogs.msdn.com/b/profiler/archive/2009/12/22/which-profiling-mode-should-i-use.aspx) a blog about the performance tools available in VS2010 Premium/Ultimate. | I don't have any touch or knowledge of dotcover that you are talking about. But regarding number of times a method called, a dumb method to calculate this is create a static integer and increment it in the method. I am not sure what "profiling or code coverage" means. This may sound really stupid if you are asking something else. |
85,910 | I do a lot of Java programming at my work (I'm an intern) and I was wondering if it is generally a rule to create javadoc to accompany my code. I usually document every method and class anyways, but I find it hard to adhere to Javadoc's syntax (writing down the variables and the output so that the parser can generate html).
I've looked at a lot of C programming and even C++ and I like the way they are commented. Is it wrong not to supply javadoc with my code? | 2011/06/21 | [
"https://softwareengineering.stackexchange.com/questions/85910",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/22067/"
] | I would say it's wrong not to make certain that the code you develop is clearly and understandably documented for the situation at hand. What that means is situational.
As an intern, consider that all the code you write is going to be someone else's responsibility. That ups the ante for what constitutes understandable documentation.
As far as javadoc in particular, that is up to you and your employer, but you should definitely be sure that something gets left behind for another person to use. | JavaDoc makes your code easier to use. I doubt it helps better than normal comments when it comes to bugfixing or modifying the code, but using your classes in other projects is by far easier and therefore more likely when JavaDoc comments allow other programmers to find and use your classes and methods. Since code reuse is generally better than reinventing the wheel, the omission of JavaDoc is hardly acceptable unless your code is so bad that reuse is not an option anyway. |
46,516,868 | I've created a new WPF App in Visual Studio 2017 for Windows Classic Desktop on Windows 10.
I add the ribbon to new application in following way.
The xaml code:
```
<r:RibbonWindow x:Class="AKnowledgeBase.MainWindow"
xmlns:r1="http://schemas.microsoft.com/winfx/2006/xaml/presentation/ribbon"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:AKnowledgeBase"
mc:Ignorable="d"
xmlns:r="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
xmlns:r2="clr-namespace:Microsoft.Windows.Controls.Ribbon.Primitives;assembly=RibbonControlsLibrary"
Title="AKnowledgeBase" Height="350" Width="525">
<DockPanel>
<r:Ribbon>
<r2:RibbonTabsPanel></r2:RibbonTabsPanel>
</r:Ribbon>
</DockPanel>
</r:RibbonWindow>
```
And change the base class:
```
public partial class MainWindow : RibbonWindow
{
public MainWindow()
{
InitializeComponent();
}
}
```
But the result application window looks ugly:
[](https://i.stack.imgur.com/nCse6.png)
On the image above you can see the Explorer caption (it have standard view in Windows10) and the created application caption (it looks like Windows98-styled view).
Why it happens and how it could be fixed?
**UPD1**:
When I use suggested below reference to the System.Windows.Controls.Ribbon.dll the main window have blue artifacts on left and righ sides:
[](https://i.stack.imgur.com/0D4bb.png)
Also when I maximize this window - there are appears bug with caption:
[](https://i.stack.imgur.com/E1XNw.png)
The text partitially cut. | 2017/10/01 | [
"https://Stackoverflow.com/questions/46516868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3260229/"
] | Add a reference to `System.Windows.Controls.Ribbon.dll` and try this XAML markup:
```
<RibbonWindow x:Class="AKnowledgeBase.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:r2="clr-namespace:System.Windows.Controls.Ribbon.Primitives;assembly=System.Windows.Controls.Ribbon"
mc:Ignorable="d"
Title="Window14" Height="300" Width="300">
<Grid>
<DockPanel>
<Ribbon>
<r2:RibbonTabsPanel></r2:RibbonTabsPanel>
</Ribbon>
</DockPanel>
</Grid>
</RibbonWindow>
```
You probably don't need the `RibbonWindow`:
```
<Window x:Class="AKnowledgeBase.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication7"
xmlns:r2="clr-namespace:System.Windows.Controls.Ribbon.Primitives;assembly=System.Windows.Controls.Ribbon"
mc:Ignorable="d"
Title="Window14" Height="300" Width="300">
<Grid>
<DockPanel>
<Ribbon>
<r2:RibbonTabsPanel></r2:RibbonTabsPanel>
</Ribbon>
</DockPanel>
</Grid>
</Window>
``` | You have probably added some theme based styling along with your r, r1 and r2 references. I'd suggest you look for a way to build Ribbon without overriding default styling. |
32,047,544 | I'm trying to change a text inside a canvas circle only once a week in wordpress
The increment will always be the same.
How can I do it automatically?
I suppose it has to do with server side javascript?
Thank you, | 2015/08/17 | [
"https://Stackoverflow.com/questions/32047544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4090776/"
] | Your use case doesn’t seem to be a critical security issue, so it might be okay to store the information date client-side. You can save a timestamp in [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) and just do a integer comparison with something along the lines of:
```
var weekInMilliseconds = 7*24*60*60*1000; // == 604800000 ms
var lastInfo = parseInt(localStorage.getItem('info'), 10); // either NaN or timestamp
if(isNaN(lastInfo))
lastInfo = 0; // 1970, mind you
// if last info showed earlier than one week ago:
if(lastInfo < (Date.now() - weekInMilliseconds)){
localStorage.setItem('info',Date.now()); // set info date now
alert('Information or action (once a week)'); // display your information
}
``` | You can store the first time a page is loaded in your cookie or localstorage and then each time the page os loaded do a check with the current date.
With that said you should probably do this kind of things on the server side and retrive it on the client because if you're doing it in browser you have no control or replication on multiple devices |
72,430,741 | This is not the usual problem with a missing `super()` call. Instead I have a special construct where I need to call `super()` differently. Check this code:
```js
class A {
public constructor() {
console.log("c-tor A");
}
}
class B extends A {
public constructor(s: string);
public constructor(i: number, s: string);
public constructor(_i: string | number, s?: string) {
const x = () => {
s = "";
super();
};
x();
console.log("c-tor B");
}
}
const b = new B("");
```
It runs fine and prints:
>
> c-tor A
> c-tor B
>
>
>
However, tsc reports the error mentioned in the title:
[](https://i.stack.imgur.com/iIBFX.png)
and I cannot suppress it by using `// @ts-ignore`. What other option do I have to silence the compiler? | 2022/05/30 | [
"https://Stackoverflow.com/questions/72430741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137174/"
] | [`JsonSerializer.Deserialize()`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer.deserialize?view=net-6.0) is a static method. You don't need to create instance for `JsonSerializer`.
Meanwhile `JToken` is from `Newtonsoft.Json`. I think would be great not to mix up with `System.Text.Json` and `Newtonsoft.Json`.
And deserialize as `Dictionary<string, List<Dictionary<string, string>>>` type.
```cs
Dictionary<string, List<Dictionary<string, string>>> dictionary = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(JTR);
// Iterate for first item in RandonName dictionary
foreach (KeyValuePair<string, string> kvp in dictionary["RandonName"][0])
{
Console.WriteLine(kvp.Key);
Console.WriteLine(kvp.Value);
}
// Iterate for all items in RandonName dictionary
foreach (var items in dictionary["RandonName"])
{
foreach (KeyValuePair<string, string> kvp in items)
{
Console.WriteLine(kvp.Key);
Console.WriteLine(kvp.Value);
}
}
```
[Sample .NET Fiddle](https://dotnetfiddle.net/8INoyn)
To get all Keys (from the first item):
```cs
dictionary["RandonName"][0].Keys
```
To get all keys from every item in the list:
```cs
using System.Linq;
dictionary["RandonName"].SelectMany(x => x.Keys).ToList();
``` | If you need only just the property names from the first object then you can take advantage of [Json.NET's Linq](https://www.newtonsoft.com/json/help/html/queryinglinqtojson.htm)
```
var semiParsedJson = JObject.Parse(json);
var collection = (JArray)semiParsedJson["RandonName"];
var firstObject = (JObject)collection.First();
foreach (var property in firstObject.Properties())
{
Console.WriteLine(property.Name);
}
``` |
21,451,622 | Hive Metastore is not creating MYSQL or Derby Connection.
For Derby
```
schematool -dbType derby -initSchema
Metastore connection URL: jdbc:mysql://localhost/metastore
Metastore Connection Driver : com.mysql.jdbc.Driver
Metastore connection User: hive
schematool -dbType derby -info
Metastore connection URL: jdbc:mysql://localhost/metastore
Metastore Connection Driver : com.mysql.jdbc.Driver
Metastore connection User: hive
org.apache.hadoop.hive.metastore.HiveMetaException: Failed to load driver
*** schemaTool failed ***
```
For mysql
```
schematool -dbType mysql -initSchema
Metastore connection URL: jdbc:mysql://localhost/metastore
Metastore Connection Driver : com.mysql.jdbc.Driver
Metastore connection User: hive
org.apache.hadoop.hive.metastore.HiveMetaException: Failed to load driver
*** schemaTool failed ***
schematool -dbType mysql -info
Metastore connection URL: jdbc:mysql://localhost/metastore
Metastore Connection Driver : com.mysql.jdbc.Driver
Metastore connection User: hive
org.apache.hadoop.hive.metastore.HiveMetaException: Failed to load driver
*** schemaTool failed ***
```
What is the issue .
I am running Hive 0.12.0 | 2014/01/30 | [
"https://Stackoverflow.com/questions/21451622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2028043/"
] | I think the problem is with your URL. Modify the URL as follows. Put the mysql port no.
Metastore connection URL: `jdbc:mysql://localhost:3306/metastore` | For this specific error "Failed to load driver", you should check if you have the mysql connector copied or has a link in Hive lib folder.
ln -s /usr/share/java/mysql-connector-java.jar $HIVE\_HOME/lib/mysql-connector-java.jar
(Download it if you don't have it within the Java libs)
Similarly get the lib for Derby too. |
3,167,494 | 1. How often does Python flush to a file?
2. How often does Python flush to stdout?
I'm unsure about (1).
As for (2), I believe Python flushes to stdout after every new line. But, if you overload stdout to be to a file, does it flush as often? | 2010/07/02 | [
"https://Stackoverflow.com/questions/3167494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329344/"
] | For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
<http://docs.python.org/library/functions.html#open>
"The optional buffering argument specifies the file’s desired buffer size:"
* 0 means unbuffered,
* 1 means line buffered,
* any other positive value means use a buffer of (approximately) that size.
* A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files.
* If omitted, the system default is used.
code:
```
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
``` | You can also check the default buffer size by calling the read only DEFAULT\_BUFFER\_SIZE attribute from io module.
```
import io
print (io.DEFAULT_BUFFER_SIZE)
``` |
8,444,087 | **Goal**
I've got a DOM with about 70 elements on it (divs with some content) . I need to move and toggle the display of those divs quite a lot and also quite fast. The speed is one of the most important things. The trigger for moving and toggling these divs is a search query, kind of like [Google Instant](http://www.google.com/insidesearch/instant-about.html), except that all the DOM elements I move around and toggle are loaded the first time (so no more calls to the server).
**Implementation**
I've implemented this in the following way: alongside the DOM I pass in a JavaScript array of objects representing the divs along with their attributes like position, contents etcetera. This array acts like a mirror to the DOM. When the user starts typing I start looping through the array and calculating, per div/object, what needs to be done to it. I actually loop over this array a couple of times: I first check if I need to look at a div/object, then I look at the object, then whether I need to look at the contents, then I look at the contents.
One of the things I do in these loops is the setting of flags for DOM-manipulation. As I understand it, reading and manipulating and the DOM is one of the slower operations in JavaScript, as compared to the other stuff I'm doing (looping, reading and writing object attributes etc.). I also did some profiling, confirming this assumption. So at every corner I've tried to prevent "touching" the DOM to increase performance. At the end of my algorithm I loop once more, execute all the necessary DOM actions and reset the flags to signal they've been read. For cross-browser compatibility I use jQuery to actually do the DOM actions (selecting, moving, toggling). I do *not* use jQuery to loop over my array.
**Problem**
My problem now is that I *think* my code and data structure is a bit ugly. I have this rather
large multidimensional array with lots of attributes and flags. I repeatedly loop over it with functions calling functions calling functions. When running into problems I can (still) somewhat easily debug stuff, but it doesn't *feel* right.
**Question**
Is there a design pattern or common solution to this kind of problem? I suspect I could implement some sort of smart coupling between the array and the DOM where I would not have to explicitly set flags and execute DOM actions, but I've no idea how such a coupling should work or if it's even a good idea or just complicating things.
Are there any other data-structure or algorithmic principles I've overlooked when solving this problem?
Thanks!
**Update**
As requested I've added my code, it's about 700 lines. Note: I'm not polluting the global namespace, these functions are defined and used inside a closure.
```
/**
* Applies the filter (defined by the currentQuery and to the cats array)
*
* -checks whether matching is needed
* -if needed does the matching
* -checks whether DOM action is needed
* -if needed executes DOM action
*
* cats is an array of objects representing categories
* which themselves contain an array of objects representing links
* with some attributes
*
* cats = (array) array of categories through which to search
* currentQuery = (string) with which to find matches within the cats
* previousQuery = (string) with previously-typed-in query
*
* no return values, results in DOM action and manipulation of cats array
*/
function applyFilter(cats,currentQuery, previousQuery) {
cats = flagIfMatchingIsNeededForCats(cats,currentQuery,previousQuery);
cats = matchCats(cats,currentQuery);
cats = flagIfMatchingIsNeededForLinks(cats,currentQuery,previousQuery);
cats = matchLinks(cats,currentQuery);
cats = flagIfDisplayToggleNeeded(cats);
if ( currentQuery.length > 0 ) {
cats = flagIfMoveNeeded(cats);
} else {
// move everything back to its original position
cats = flagMoveToOriginalPosition(cats);
}
// take action on the items that need a DOM action
cats = executeDomActions(cats);
}
/**
* Sets a flag on a category if it needs matching, parses and returns cats
*
* Loops through all categories and sets a boolean to signal whether they
* need matching.
*
* cats = (array) an array with all the category-objects in it
* currentQuery = (string) the currently typed-in query
* previousQuery = (string) the query that was previously typed in
*
* returns (array) cats, possibly in a different state
*/
function flagIfMatchingIsNeededForCats(cats,currentQuery,previousQuery) {
var newQueryIsLonger = isNewQueryLonger(currentQuery, previousQuery);
// check if matching is necessary for categories
for (var i = 0; i < cats.length; i++) {
cats[i].matchingNeeded = isMatchingNeededForCat(
cats[i].matches
,newQueryIsLonger
,currentQuery.length
,cats[i].noMatchFoundAtNumChars
);
}
return cats;
}
/**
* Whether the new query is longer than the previous one
*
* currentQuery = (string) the currently typed-in query
* previousQuery = (string) the query that was previously typed in
*
* returns (boolean) true/false
*/
function isNewQueryLonger(currentQuery, previousQuery) {
if (previousQuery == false) {
return true;
}
return currentQuery.length > previousQuery.length
}
/**
* Deduces if a category needs to be matched to the current query
*
* This function helps in improving performance. Matching is done using
* indexOf() which isn't slow of itself but preventing even fast processes
* is a good thing (most of the time). The function looks at the category,
* the current and previous query, then decides whether
* matching is needed.
*
* currentlyMatched = (boolean) on whether the boolean was matched to the previous query
* newQueryIsLonger = (boolean) whether the new query is longer
* queryLength = (int) the length of the current query
* noMatchFoundAtNumChars = (int) this variable gets set (to an int) for a
* category when it switches from being matched to being not-matched. The
* number indicates the number of characters in the first query that did
* not match the category. This helps in performance because we don't need
* to recheck the categoryname if it doesn't match now and the new query is
* even longer.
*
* returns (boolean) true/false
*/
function isMatchingNeededForCat(currentlyMatched, newQueryIsLonger ,queryLength ,noMatchFoundAtNumChars) {
if (typeof(currentlyMatched) == 'undefined') {
// this happens the first time we look at a category, for all
// categories this happens with an empty query and that matches with
// everything
currentlyMatched = true;
}
if (currentlyMatched && newQueryIsLonger) {
return true;
}
if (!currentlyMatched && !newQueryIsLonger) {
// if currentlyMatched == false, we always have a value for
// noMatchFoundAtNumChars
// matching is needed if the first "no-match" state was found
// at a number of characters equal to or bigger than
// queryLength
if ( queryLength < noMatchFoundAtNumChars ) {
return true;
}
}
return false;
}
/**
* Does matching on categories for all categories that need it.
*
* Sets noMatchFoundAtNumChars to a number if the category does not match.
* Sets noMatchFoundAtNumChars to false if the category matches once again.
*
* cats = (array) an array with all the category-objects in it
* currentQuery = (string) the currently typed-in query
*
* returns (array) cats, possibly in a different state
*/
function matchCats(cats,currentQuery) {
for (var i = 0; i < cats.length; i++) {
if (cats[i].matchingNeeded) {
cats[i].matches = categoryMatches(cats[i],currentQuery);
// set noMatchFoundAtNumChars
if (cats[i].matches) {
cats[i].noMatchFoundAtNumChars = false;
} else {
cats[i].noMatchFoundAtNumChars = currentQuery.length;
}
}
}
return cats;
}
/**
* Check if the category name matches the query
*
* A simple indexOf call to the string category_name
*
* category = (object) a category object
* query = (string) the query
*
* return (boolean) true/false
*/
function categoryMatches(category,query) {
catName = category.category_name.toLowerCase();
if (catName.indexOf(query) !== -1 ) {
return true;
}
return false;
}
/**
* Checks links to see whether they need matching
*
* Loops through all cats, selects the non-matching, for every link decides
* whether it needs matching
*
* cats = (array) an array with all the category-objects in it
* currentQuery = the currently typed-in query
* previousQuery = the query that was previously typed in
*
* returns (array) cats, possibly in a different state
*/
function flagIfMatchingIsNeededForLinks(cats,currentQuery,previousQuery) {
var newQueryIsLonger = isNewQueryLonger(currentQuery, previousQuery);
for (var i = 0; i < cats.length; i++) {
if (!cats[i].matches) { // only necessary when cat does not match
for (var k = 0; k < cats[i].links.length; k++) {
cats[i].links[k].matchingNeeded = isMatchingNeededForLink(
cats[i].links[k].matches
,newQueryIsLonger
,currentQuery.length
,cats[i].links[k].noMatchFoundAtNumChars
);
}
}
}
return cats;
}
/**
* Checks whether matching is needed for a specific link
*
* This function helps in improving performance. Matching is done using
* indexOf() for every (relevant) link property, this function helps decide
* whether that *needs* to be done. The function looks at some link
* properties, the current and previous query, then decides whether
* matching is needed for the link.
*
* currentlyMatched = (boolean) on whether the boolean was matched to the previous query
* newQueryIsLonger = (boolean) whether the new query is longer
* queryLength = (int) the length of the current query
* noMatchFoundAtNumChars = (int) this variable gets set (to an int) for a
* link when it switches from being matched to being not-matched. The
* number indicates the number of characters in the first query that did
* not match the link. This helps in performance because we don't need
* to recheck the link properties in certain circumstances.
*
* return (boolean) true/false
*/
function isMatchingNeededForLink(currentlyMatched, newQueryIsLonger ,queryLength ,noMatchFoundAtNumChars) {
if (typeof(currentlyMatched) == 'undefined') {
// this happens to a link the first time a cat does not match and
// we want to scan the links for matching
return true;
}
if (currentlyMatched && newQueryIsLonger) {
return true;
}
if (!currentlyMatched && !newQueryIsLonger) {
// if currentlyMatched == false, we always have a value for
// noMatchFoundAtNumChars
// matching is needed if the first "no-match" state was found
// at a number of characters equal to or bigger than
// queryLength
if ( queryLength < noMatchFoundAtNumChars ) {
return true;
}
}
return false;
}
/**
* Does matching on links for all links that need it.
*
* Sets noMatchFoundAtNumChars to a number if the link does not match.
* Sets noMatchFoundAtNumChars to false if the link matches once again.
*
* cats = (array) an array with all the category-objects in it
* currentQuery = (string) the currently typed-in query
*
* returns (array) cats, possibly in a different state
*/
function matchLinks(cats,currentQuery) {
for (var i = 0; i < cats.length; i++) {
// category does not match, check if links in the category match
if (!cats[i].matches) {
for (var k = 0; k < cats[i].links.length; k++) {
if (cats[i].links[k].matchingNeeded) {
cats[i].links[k].matches = linkMatches(cats[i].links[k],currentQuery);
}
// set noMatchFoundAtNumChars
if (cats[i].links[k].matches) {
cats[i].links[k].noMatchFoundAtNumChars = false;
} else {
cats[i].links[k].noMatchFoundAtNumChars = currentQuery.length;
}
}
}
}
return cats;
}
/**
* Check if any of the link attributes match the query
*
* Loops through all link properties, skips the irrelevant ones we use for filtering
*
* category = (object) a category object
* query = (string) the query
*
* return (boolean) true/false
*/
function linkMatches(link,query) {
for (var property in link) {
// just try to match certain properties
if (
!( // if it's *not* one of the following
property == 'title'
|| property == 'label'
|| property == 'url'
|| property == 'keywords'
|| property == 'col'
|| property == 'row'
)
){
continue;
}
// if it's an empty string there's no match
if( !link[property] ) {
continue;
}
var linkProperty = link[property].toLowerCase();
if (linkProperty.indexOf(query) !== -1){
return true;
}
}
return false;
}
/**
* Flags if toggling of display is needed for a category.
*
* Loops through all categories. If a category needs some DOM
* action (hiding/showing) it is flagged for action. This helps in
* performance because we prevent unnecessary calls to the DOM (which are
* slow).
*
* cats = (array) an array with all the category-objects in it
*
* returns (array) cats, possibly in a different state
*/
function flagIfDisplayToggleNeeded(cats) {
for (var i = 0; i < cats.length; i++) {
// this happens the first time we look at a category
if (typeof(cats[i].currentlyDisplayed) == 'undefined') {
cats[i].currentlyDisplayed = true;
}
var visibleLinks = 0;
// a cat that matches, all links need to be shown
if (cats[i].matches) {
visibleLinks = cats[i].links.length;
} else {
// a cat that does not match
for (var k = 0; k < cats[i].links.length; k++) {
if (cats[i].links[k].matches) {
visibleLinks++;
}
}
}
// hide/show categories if they have any visible links
if (!cats[i].currentlyDisplayed && visibleLinks > 0 ) {
cats[i].domActionNeeded = 'show';
} else if( cats[i].currentlyDisplayed && visibleLinks == 0 ){
cats[i].domActionNeeded = 'hide';
}
}
return cats;
}
/**
* Flags categories to be moved to other position.
*
* Loops through all categories and looks if they are distributed properly.
* If not it moves them to another position. It remembers the old position so
* it can get the categories back in their original position.
*
* cats = (array) an array with all the category-objects in it
*
* returns (array) cats, possibly in a different state
*/
function flagIfMoveNeeded(cats) {
var numCats, numColumns, displayedCats, i, moveToColumn, tmp;
numColumns = getNumColumns(cats);
numDisplayedCats = getNumDisplayedCats(cats);
columnDistribution = divideInPiles(numDisplayedCats, numColumns);
// optional performance gain: only move stuff when necessary
// think about this some more
// we convert the distribution in columns to a table so we get columns
// and positions
catDistributionTable = convertColumnToTableDistribution(columnDistribution);
// sort the categories, highest positions first
// catPositionComparison is a function to do the sorting with
// we could improve performance by doing this only once
cats = cats.sort(catPositionComparison);
for (i = 0; i < cats.length; i += 1) {
if( categoryWillBeDisplayed(cats[i]) ){
tmp = getNewPosition(catDistributionTable); // returns multiple variables
catDistributionTable = tmp.catDistributionTable;
cats[i].moveToColumn = tmp.moveToColumn;
cats[i].moveToPosition = tmp.moveToPosition;
} else {
cats[i].moveToColumn = false;
cats[i].moveToPosition = false;
}
}
return cats;
}
/**
* A comparison function to help the sorting in flagIfMoveNeeded()
*
* This function compares two categories and returns an integer value
* enabling the sort function to work.
*
* cat1 = (obj) a category
* cat2 = (obj) another category
*
* returns (int) signaling which category should come before the other
*/
function catPositionComparison(cat1, cat2) {
if (cat1.category_position > cat2.category_position) {
return 1; // cat1 > cat2
} else if (cat1.category_position < cat2.category_position) {
return -1; // cat1 < cat2
}
// the positions are equal, so now compare on column, if we need the
// performance we could skip this
if (cat1.category_column > cat2.category_column) {
return 1; // cat1 > cat2
} else if (cat1.category_column < cat2.category_column) {
return -1; // cat1 < cat2
}
return 0; // position and column are equal
}
/**
* Checks if a category will be displayed for the currentQuery
*
* cat = category (object)
*
* returns (boolean) true/false
*/
function categoryWillBeDisplayed(cat) {
if( (cat.currentlyDisplayed === true && cat.domActionNeeded !== 'hide')
||
(cat.currentlyDisplayed === false && cat.domActionNeeded === 'show')
){
return true;
} else {
return false;
}
}
/**
* Gets the number of unique columns in all categories
*
* Loops through all cats and saves the columnnumbers as keys, insuring
* uniqueness. Returns the number of
*
* cats = (array) of category objects
*
* returns (int) number of unique columns of all categories
*/
function getNumColumns(cats) {
var columnNumber, uniqueColumns, numUniqueColumns, i;
uniqueColumns = [];
for (i = 0; i < cats.length; i += 1) {
columnNumber = cats[i].category_column;
uniqueColumns[columnNumber] = true;
}
numUniqueColumns = 0;
for (i = 0; i < uniqueColumns.length; i += 1) {
if( uniqueColumns[i] === true ){
numUniqueColumns += 1
}
}
return numUniqueColumns;
}
/**
* Gets the number of categories that will be displayed for the current query
*
* cats = (array) of category objects
*
* returns (int) number of categories that will be displayed
*/
function getNumDisplayedCats(cats) {
var numDisplayedCats, i;
numDisplayedCats = 0;
for (i = 0; i < cats.length; i += 1) {
if( categoryWillBeDisplayed(cats[i]) ){
numDisplayedCats += 1;
}
}
return numDisplayedCats;
}
/**
* Evenly divides a number of items into piles
*
* Uses a recursive algorithm to divide x items as evenly as possible over
* y piles.
*
* items = (int) a number of items to be divided
* piles = (int) the number of piles to divide items into
*
* return an array with numbers representing the number of items in each pile
*/
function divideInPiles(items, piles) {
var averagePerPileRoundedUp, rest, pilesDivided;
pilesDivided = [];
if (piles === 0) {
return false;
}
averagePerPileRoundedUp = Math.ceil(items / piles);
pilesDivided.push(averagePerPileRoundedUp);
rest = items - averagePerPileRoundedUp;
if (piles > 1) {
pilesDivided = pilesDivided.concat(divideInPiles(rest, piles - 1)); // recursion
}
return pilesDivided;
}
/**
* Converts a column distribution to a table
*
* Receives a one-dimensional distribution array and converts it to a two-
* dimensional distribution array.
*
* columnDist (array) an array of ints, example [3,3,2]
*
* returns (array) two dimensional array, rows with "cells"
* example: [[true,true,true],[true,true,true],[true,true,false]]
* returns false on failure
*/
function convertColumnToTableDistribution(columnDist) {
'use strict';
var numRows, row, numCols, col, tableDist;
if (columnDist[0] === 'undefined') {
return false;
}
// the greatest number of items are always in the first column
numRows = columnDist[0];
numCols = columnDist.length;
tableDist = []; // we
for (row = 0; row < numRows; row += 1) {
tableDist.push([]); // add a row
// add "cells"
for (col = 0; col < numCols; col += 1) {
if (columnDist[col] > 0) {
// the column still contains items
tableDist[row].push(true);
columnDist[col] -= 1;
} else {
tableDist[row][col] = false;
}
}
}
return tableDist;
}
/**
* Returns the next column and position to place a category in.
*
* Loops through the table to find the first position that can be used. Rows
* and positions have indexes that start at zero, we add 1 in the return
* object.
*
* catDistributionTable = (array) of rows, with positions in them
*
* returns (object) with the mutated catDistributionTable, a column and a
* position
*/
function getNewPosition(catDistributionTable) {
var numRows, row, col, numCols, moveToColumn, moveToPosition;
numRows = catDistributionTable.length;
findposition:
for (row = 0; row < numRows; row += 1) {
numCols = catDistributionTable[row].length;
for ( col = 0; col < numCols; col += 1) {
if (catDistributionTable[row][col] === true) {
moveToColumn = col;
moveToPosition = row;
catDistributionTable[row][col] = false;
break findposition;
}
}
}
// zero-indexed to how it is in the DOM, starting with 1
moveToColumn += 1;
moveToPosition += 1;
return {
'catDistributionTable' : catDistributionTable
,'moveToColumn' : moveToColumn
,'moveToPosition' : moveToPosition
};
}
/**
* Sets the target position of a category to its original location
*
* Each category in the DOM has attributes defining their original position.
* After moving them around we might want to move them back to their original
* position, this function flags all categories to do just that.
*
* cats = (array) of category objects
*
* All of the possible return values
*/
function flagMoveToOriginalPosition(cats) {
for (i = 0; i < cats.length; i += 1) {
cats[i].moveToColumn = cats.category_column;
cats[i].moveToPosition = cats.category_position;
}
return cats;
}
/**
* Execute DOM actions for the items that need DOM actions
*
* Parses all categories, executes DOM actions on the categories that
* require a DOM action.
*
* cats = (array) an array with all the category-objects in it
*
* no return values
*/
function executeDomActions(cats) {
for (var i = 0; i < cats.length; i++) {
var category_id = cats[i].category_id;
// toggle display of columns
if (cats[i].domActionNeeded == 'show') {
showCategory(category_id);
cats[i].currentlyDisplayed = true;
}
if (cats[i].domActionNeeded == 'hide') {
hideCategory(category_id);
cats[i].currentlyDisplayed = false;
}
cats[i].domActionNeeded = false;
// for every currentlyDisplayed category move it to new location
// if necessary
if (cats[i].currentlyDisplayed && cats[i].moveToColumn !== false) {
cats[i] = moveCat(cats[i]);
}
}
return cats;
}
/**
* Show a certain category
*
* category_id = (int) the id of the category that needs to be shown
*
* no return values
*/
function showCategory(category_id) {
$('#' + category_id).show();
}
/**
* Hide a certain category
*
* category_id = (int) the id of the category that needs to be hidden
*
* no return values
*/
function hideCategory(category_id) {
$('#' + category_id).hide();
}
/**
* Moves a category to the position set in its attributes
*
* A category can have attributes defining the column and position (or row)
* this function moves the category to the correct column and position.
*
* cat = (object) category
*
* returns (object) category
*/
function moveCat(cat) {
var columnSelector, catSelector;
columnSelector = '#column' + cat.moveToColumn + ' .column_inner' + ' .hiddenblocks';
catSelector = '#' + cat.category_id;
$(columnSelector).prepend($(catSelector));
// reset target coordinates
cat.moveToColumn = false;
cat.moveToPosition = false;
return cat;
}
``` | 2011/12/09 | [
"https://Stackoverflow.com/questions/8444087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61109/"
] | Well commented and formatted JavaScript, kudos sir!
First off, it seams like your use-case would be perfect for a SQL database query. Sending your query to a DB and getting the category IDs and locations back would be much simpler than your current implementation. I assume you do it all client side because you don't have access to a DB, your data is fairly static, or you're not confident in the real-time speed of your database.
To speed up your current implementation lower case and concatenate all your Link data properties into one property before hand.
```
function linkMatches(link,query) {
if (link["ConcatenatedLCasedProperties"].indexOf(query) !== -1){
return true;
}
return false;
}
```
*EDIT* Here's a faster/more efficient version of your divideInPiles function.
```
function divideInPiles(items, piles) {
var result = [];
var perPile = Math.floor(items/piles);
var leftOver = items % piles;
if(piles == 0)
return false;
for(var x=0; x<piles; x++)
result.push(perPile + (--leftOver >= 0 ? 1: 0));
return result;
}
``` | I think that it really possible to use tree structure there. Also you can try to implement manipulate some graph algorithms. Also, think it could be reasonable to have some hidden div on each level of the tree, when you store most popular information, and you can just display it if necessary instead of manipulation with div content.
But, think that it needs to specify you task with more details. Some real cases could be really helpfull. |
43,739,658 | I get a iterable list which I iterate using following code
```
for (IssueField issueObj : issue.getFields())
{
System.out.println(issueObj.getId());
}
```
the list is of following structure
```
[IssueField{id=customfield_13061, name=Dev Team Updates, type=null, value=null},
IssueField{id=customfield_13060, name=Development, type=null, value={}},
IssueField{id=customfield_11160, name=Rank, type=null, value=1|i0065r:},
IssueField{id=customfield_13100, name=TM Product, type=null, value=IntelliGlance},
IssueField{id=customfield_11560, name=Release Notes, type=null, value=null},
IssueField{id=customfield_13500, name=Request Type, type=null, value=null},
IssueField{id=customfield_13900, name=Category, type=null, value=null},
IssueField{id=environment, name=Environment, type=null, value=null}]
```
there are more then 100 of such objects in the list. is there a way I can directly get the desired objects value without iterating all the values. currently using something like this which I think is not efficient.
```
for (IssueField issueObj : issue.getFields())
{
if(issueObj.getId().equalIgnoreCase(someId)){
//Object Found
}
}
``` | 2017/05/02 | [
"https://Stackoverflow.com/questions/43739658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7925298/"
] | If you want to be able to do frequent searching over a large dataset like you said then you should use a HashMap where the string is the value in your getId(). The big O time complexity for search of a HashMap is O(1) where for a list it is O(n). This would net you the desired efficiency. | If you are using java 8, You can try this
```
<your-object> result1 = <your-list>.stream()
.filter(x -> "jack".equals(x.getId()))
.findAny()
.orElse(null);
```
First of all it Convert list to Streams, then you want id like "jack", If 'findAny' then return object otherwise return null |
2,195,953 | >
> Show that ${n\choose r}={{n-1}\choose{r-1}}+{{n-1}\choose {r}}$.
>
>
>
My try:
$$\dfrac{n!}{(n-r)!\;r!}=\dfrac{(n-1)!}{(n-r)!(r-1)!}+\dfrac{(n-1)!}{(n-1-r)!\;r!}$$
Multiplying all terms by $r!(n-r)!$
$$n!=r(n-1)!+(n-1)!(n-r)$$
Dividing everything by $(n-1)!$
$$n=r+(n-r)$$
$$n=n$$
Is this correct? | 2017/03/21 | [
"https://math.stackexchange.com/questions/2195953",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/167548/"
] | Combinatorial Proof:
Let $A= \big\{1,2, \ldots,n\big\} $. there are $\binom{n}{r}$ ways to form r-combinations $S$ of $A$.
we can count the number of r-combinations $S$ of $A$ in a different way.
Every r-combination $S$ of $A$ either contains the element $1$ or not. if $1 \in S$, the number of ways to form S is $\binom{n-1}{r-1}$. if $1\notin S$, the number of ways to form $S$ is $\binom{n-1}{r}$. thus we have:
$$\binom{n-1}{r-1}+\binom{n-1}{r}=\binom{n}{r}$$
---
source:Principles and Techniques in Combinatorics | Not quite. Following your method:
$$\dfrac{n!}{(n-r)!\;r!}=\dfrac{(n-1)!}{(n-r)!(r-1)!}+\dfrac{(n-1)!}{(n-1-r)!\;r!}$$
Multiplying all terms by $r!(n-r)!$ (rather than $(r-1)!(n-r)!$)
$$n!=r(n-1)!+(n-1)!(n-r) = r(n-1)!+(n-1)!n - r(n-1)! = n!$$
But it's usually better to start with one side and ending up at the other side. So:
$${{n-1}\choose{r-1}}+{{n-1}\choose {r}} =$$
$$\dfrac{(n-1)!}{(n-r)!(r-1)!}+\dfrac{(n-1)!}{(n-1-r)!\;r!} =$$
$$ \dfrac{r(n-1)!}{(n-r)!r!}+\dfrac{(n-r)(n-1)!}{(n-r)!\;r!} =$$
$$\dfrac{r(n-1)!+n(n-1)!-r(n-1)!}{(n-r)!\;r!} =$$
$$ \frac{n!}{(n-r)!r!} =$$
$${{n}\choose {r}} $$ |
1,844,603 | Is the *NSSearchPathForDirectoriesInDomain*s function still the best way to get the path of the iPhone Documents directory? I ask because most topics I see on this are dated last year, and it still seems like a pretty cumbersome way of getting to a directory that is used commonly on iPhones. You'd think that there'd be a convenience method for this by now, similar to NSBundle's *bundlePath*, *executablePath*, etc.
Just to be clear, this means calling "NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)" and getting back an array with the Documents path at index 0. | 2009/12/04 | [
"https://Stackoverflow.com/questions/1844603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/162491/"
] | The Core Data-based application template in Xcode provides this method:
```
- (NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
```
So it would seem that Apple continues to endorse getting the documents directory that way. You could put it into a category, I suppose, but I have found it is enough to include that method in the small handful of classes in a given app that need to do work in the documents directory. If you're doing a lot of file stuff all over the place, you might consider refactoring your code a bit to confine those tasks to one or two manager classes.
For me, at least, the third or fourth time I said "Hey, getting the docs directory is a pain in the neck" was the point where I realized some opportunities to shift the file juggling into a dedicated class. | This works for me, pretty short and sweet
```
#define kDOCSFOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
```
Cheers! |
5,070,328 | Can anybody help me with this?
Here's the problem...
When I have to code let's say, a registration form, I add the new form and start coding it. But sometimes the form is a bit complex and I find myself duplicating code and making the same verifications over and over again making the code messy.
I was wondering is there is some sort of tool that allows me to create a flow of this form before coding it, like a flow chart... where I can find such places where I'm duplicating code and then avoid that.
thanks! | 2011/02/21 | [
"https://Stackoverflow.com/questions/5070328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/555089/"
] | Well real tool/language designed for this is [UML](http://en.wikipedia.org/wiki/Unified_Modeling_Language). You can read up on it.
But its very strict. Altough you don't have to follow all specs and conventions. There are several types of diagram that cover pretty much everything. But AFAIK only 4 are practically in use.
Most people I know tend to draw [Control flow diagrams](http://en.wikipedia.org/wiki/Control_flow_diagram)
Google Docs drawing is perfectly fine for that.
But it depends on the type of application. I pesonally think more in data and like [data flow diagrams](http://en.wikipedia.org/wiki/Data_flow_diagram).
I also like to design top-down. Other people do it differently. I mostly start with a sheet of paper and a pen and draw some stuff i could not tell what it means half an hour later. But I start very basic with application/database/user or something and when a picture arises i go into specifics using modeling tools.
I cannot design anything without knowing the greater picture, altough i know it is a software developers quality to just that.
ps: designing a form sounds very trivial at first, altough it might be not. but a great help
I think a great help is sticking to some programming patterns and paradigms you like. A good base is the [MVC](http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller) concept. I like to extend it with a "resource model" that does all the database stuff. | 1) The best place to start is the white board. If your company doesn't have white boards, tell them to order some. Seriously. You will wonder how you lived without it.
2) Build a paper prototype with the stakeholders, or have them build one. They take maybe 30 minutes to make and solve a ton of UI arguments that otherwise would be "defects"
3) Code. That's the easy part.
4) Refactor as you fix defects. You'll notice better things you could have done, shortcuts, duplicate code. Take time to fix the defect correctly and code quality will improve. It's an iterative process.
5) Visio if you hand the process off (to support or whatever). This could be step 4 as kind of a state machine, but the paper prototypes should be enough of a process to get you started with enabling, disabling, etc.
If you're on the computer designing and writing code before you have a prototype and have white boarded everything out, you will have to invest a lot more time in the Refactor step. Visio and other state design applications will show you what happens, but the white board marker is the excalibur of the development world.
I know this doesn't answer the question you asked, verbatim; however, solid processes are infinitely more valuable than tools. |
9,215,063 | How can an object replace itself in ASNI C++ ? I want a function like foo->replaceBy(bar)
which will cause object foo to delete itself and replace pointer by bar
```
if (foo->isFoo())
{
foo->replaceBy(bar);
}
ASSERT(foo->isFoo(), false);
ASSERT(foo->isBar(), true);
``` | 2012/02/09 | [
"https://Stackoverflow.com/questions/9215063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298023/"
] | You cannot do this unless you pass a pointer to the pointer or a reference to the pointer ([example here](http://ideone.com/lwV9u)):
```
void replaceBy(Foo*& foo, Foo* bar) {
delete foo;
foo = bar;
}
//...
foo->replaceBy(foo, bar);
```
Which would defeat the purpose of `replaceBy` being a non-static member function.
---
There is also the überevil macro way to do this (**don't**):
```
#define FOO_REPLACE_BY(foo, bar) do {delete foo; foo = bar;} while(0)
```
---
I recommend that you overload `operator=` and stay away from pointers when possible, or at least use smart pointers (which allow for pointer assignment without memory leaks). | With the `PIMPL` idiom it's easy to *effectively* let objects take each others place: [The Pimpl Idiom in practice](https://stackoverflow.com/questions/843389/the-pimpl-idiom-in-practice)
Perhaps you also want a `swap` method to swap the contents of two objects. <https://stackoverflow.com/a/843418/1149664> |
10,152,650 | Is there a way in JavaScript to get Boolean value for a match of the string against the array of regular expressions?
The example would be (where the 'if' statement is representing what I'm trying to achieve):
```
var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = 'else';
if (matchInArray(thisString, thisExpressions)) {
}
``` | 2012/04/14 | [
"https://Stackoverflow.com/questions/10152650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/398341/"
] | Using a more functional approach, you can implement the match with a one-liner using an [array function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some):
ECMAScript 6:
```
const regexList = [/apple/, /pear/];
const text = "banana pear";
const isMatch = regexList.some(rx => rx.test(text));
```
ECMAScript 5:
```
var regexList = [/apple/, /pear/];
var text = "banana pear";
var isMatch = regexList.some(function(rx) { return rx.test(text); });
``` | You could use [.test()](http://www.w3schools.com/jsref/jsref_regexp_test.asp) which returns a boolean value when is find what your looking for in another string:
```
var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = new RegExp('\\b' + 'else' + '\\b', 'i');
var FoundIt = thisString.test(thisExpressions);
if (FoundIt) { /* DO STUFF */ }
``` |
59,178,418 | I am little confused with the caching mechanism of Spark.
Let's say I have a Spark application with only one action at the end of multiple transformations. In which suppose I have a dataframe A and I applied 2-3 transformation on it, creating multiple dataframes which eventually helps creating a last dataframe which is going to be saved to disk.
example :
```
val A=spark.read() // large size
val B=A.map()
val C=A.map()
.
.
.
val D=B.join(C)
D.save()
```
So do I need to cache dataframe A for performance enhancement?
Thanks in advance. | 2019/12/04 | [
"https://Stackoverflow.com/questions/59178418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3762708/"
] | Yes, you are correct.
You should cache A as it used for B & C as input. The DAG visualization would show the extent of reuse or going back to source (in this case). If you have a noisy cluster, some spilling to disk could occur.
See also top answer here [(Why) do we need to call cache or persist on a RDD](https://stackoverflow.com/questions/28981359/why-do-we-need-to-call-cache-or-persist-on-a-rdd)
However, I was looking for skipped stages, silly me. But something else shows as per below.
The following code akin to your own code:
```
val aa = spark.sparkContext.textFile("/FileStore/tables/filter_words.txt")//.cache
val a = aa.flatMap(x => x.split(" ")).map(_.trim)
val b=a.map(x => (x,1))
val c=a.map(x => (x,2))
val d=b.join(c)
d.count
```
Looking at UI with .cache
[](https://i.stack.imgur.com/vTO5A.png)
and without .cache
[](https://i.stack.imgur.com/qsxjX.png)
QED: SO, .cache has benefit. It would not make sense otherwise. Also, 2 reads could lead to different results in some cases. | I think thebluephantom's answer is right.
I had faced same situation with you until today, and i also found answers only saying Spark `cache()` does not work on single query.
And also my spark job executing single query seems not caching.
Because of them, i was also doubted for he's answer.
But he showed evidences for cache is working with a green box even he execute single query.
So, i tested 3 cases with dataframe(not RDD) like below and the results seems he is right.
And execution plan is also changed (more simple and use InMemoryRelation, please see the below).
1. without cache
2. using cache
3. using cache with calling unpersist before action
without cache
-------------
**example**
```scala
val A = spark.read.format().load()
val B = A.where(cond1).select(columns1)
val C = A.where(cond2).select(columns2)
val D = B.join(C)
D.save()
```
**DAG for my case**
[](https://i.stack.imgur.com/mUKq0.png)
>
> This is a bit more complicated than example.
>
>
>
This DAG is messy even though there is no complicated execution.
And you can see the scan is occured 4 times.
[](https://i.stack.imgur.com/1Fuw4.png)
with cache
----------
**example**
```scala
val A = spark.read.format().load().cache() // cache will be working
val B = A.where(cond1).select(columns1)
val C = A.where(cond2).select(columns2)
val D = B.join(C)
D.save()
```
This will cache A, even single query.
You can see DAG that read `InMemoryTableScan` twice.
**DAG for my case**
[](https://i.stack.imgur.com/cQ0Nu.png)
with cache and unpersist before action
--------------------------------------
```scala
val A = spark.read.format().load().cache()
val B = A.where(cond1).select(columns1)
val C = A.where(cond2).select(columns2)
/* I thought A will not be needed anymore */
A.unpersist()
val D = B.join(C)
D.save()
```
This code will not cache A dataframe, because it was unset cache flag before starting action. (`D.save()`)
So, this will result in exactly same with first case (without cache).
Important thing is `unpersist()` must be written after action(after `D.save()`).
But when i ask some people in my company, many of them used like case 3 and didn't know about this.
I think that's why many people misunderstand `cache` is not working on single query.
`cache` and `unpersist` should be like below
--------------------------------------------
```scala
val A = spark.read.format().load().cache()
val B = A.where(cond1).select(columns1)
val C = A.where(cond2).select(columns2)
val D = B.join(C)
D.save()
/* unpersist must be after action */
A.unpersist()
```
This result exactly same with case 2 (with cache, but unpersist after `D.save()`).
So. I suggest try cache like thebluephantom's answer.
If i present any incorrection. please note that.
Thanks to thebluephantom's for solving my problem. |
182,606 | You are given four numbers. The first three are \$a\$, \$b\$, and \$c\$ respectively, for the sequence:
$$T\_n=an^2+bn+c$$
You may take input of these four numbers in any way. The output should be one of two distinct outputs mentioned in your answer, one means that the fourth number is a term in the sequence (the above equation has at least one solution for \$n\$ which is an integer when \$a\$, \$b\$, \$c\$ and \$T\_n\$ are substituted for the given values), the other means the opposite.
This is code golf, so the shortest answer in bytes wins. Your program should work for any input of \$a, b, c, T\_n\$ where the numbers are negative or positive (or 0), decimal or integer. To avoid problems but keep some complexity, non-integers will always just end in \$.5\$. Standard loop-holes disallowed.
Test cases
----------
```
a |b |c |T_n |Y/N
------------------------
1 |1 |1 |1 |Y #n=0
2 |3 |5 |2 |N
0.5 |1 |-2 |-0.5|Y #n=1
0.5 |1 |-2 |15.5|Y #n=5
0.5 |1 |-2 |3 |N
-3.5|2 |-6 |-934|Y #n=-16
0 |1 |4 |7 |Y #n=3
0 |3 |-1 |7 |N
0 |0 |0 |1 |N
0 |0 |6 |6 |Y #n=<anything>
4 |8 |5 |2 |N
``` | 2019/04/03 | [
"https://codegolf.stackexchange.com/questions/182606",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/80756/"
] | [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
============================================================================================================================
```
Æ©²Āi²4P³n+tÐdi(‚³-IJ·Ä%P}뮳Āi³%]_
```
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/182609/52210), so make sure to upvote him!
Takes the input in the format \$[t,c], a, b\$.
[Try it online](https://tio.run/##AVAAr/9vc2FiaWX//8OGwqnCssSAacKyNFDCs24rdMOQZGko4oCawrMtw4TCssK3w4QlUH3Dq8KuwrPEgGnCsyVdX///Wy05MzQsLTZdCi0zLjUKMg)
**Explanation:**
```python
Æ # Reduce the (implicit) input-list by subtraction (`t-c`)
© # Store this value in the register (without popping)
²Āi # If the second input `a` is not 0:
²4P # Calculate `(t-c)*a*4`
³n+ # Add the third input `b` squared to it: `(t-c)*a*4+b*b`
t # Take the square-root of that
# (NOTE: 05AB1E and JS behave differently for square-roots of
# negative integers; JS produces NaN, whereas 05AB1E leaves the
# integer unchanged, which is why we have the `di...}` here)
Ð # Triplicate this square
di # If the square is non-negative (>= 0):
(‚ # Pair it with its negative
³- # Subtract the third input `b` from each
Ä # Take the absolute value of both
²·Ä% # Modulo the absolute value of `a` doubled
# (NOTE: 05AB1E and JS behave differently for negative modulos,
# which is why we have the two `Ä` here)
P # Then multiply both by taking the product
} # And close the inner if-statement
ë # Else (`a` is 0):
® # Push the `t-c` from the register
³Āi # If the third input `b` is not 0:
³% # Take modulo `b`
] # Close both if-else statements
_ # And check if the result is 0
# (which is output implicitly)
``` | [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
==========================================================
```
_3¦UÆr=Ḟ$;3ị=ɗẸ
```
[Try it online!](https://tio.run/##y0rNyan8/z/e@NCy0MNtRbYPd8xTsTZ@uLvb9uT0h7t2/D866eHOGTqPGuYo6NopPGqYq3N4uT5Q9lHjvki/Y11ch9sfNa2J/P8/OtpQBwhjQSg62kjHWMcUyjbQMwXK6BrF6ugCmagihqboIsYgrq4xkG@ko2sG1GNpbAJWAZQHMswhbGMdXUM4BwhhVgHZQD1msQA "Jelly – Try It Online")
Built-in helps here but doesn’t handle a=b=0 so this is handled specially. |
13,020,103 | I'm working with ASP.NET MVC 4 WebApi and am having a lot of fun with it running it on my local computer on IIS Express. I've configured IIS Express to serve remote machines too, and so other's in my company are using my computer as our webserver.
After deciding this was a less-than-optimal solution, we decided to put the WebApi on a remote server after installing .NET 4.5. When I use fiddler and sent a POST to a controller on my local machine it returns the correct response, yet when I change the domain to the webserver running IIS7 the same POST returns a cryptic
>
> {"message":"an error has occurred"}
>
>
>
message. Anyone have any idea what could be going on? | 2012/10/22 | [
"https://Stackoverflow.com/questions/13020103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087161/"
] | I always come to this question when I hit an error in the test environment and remember, "I've done this before, but I can do it straight in the web.config without having to modify code and re-deploy to the test environment, but it takes 2 changes... what was it again?"
For future reference
```
<system.web>
<customErrors mode="Off"></customErrors>
</system.web>
```
AND
```
<system.webServer>
<httpErrors errorMode="Detailed" existingResponse="PassThrough"></httpErrors>
</system.webServer>
``` | So i tried all the suggested solutions to no avail.
All i did was to set run the app from the server and it displayed the error in full, this should have worked when i set customErrors mode to false but it didn't. The moment i browsed the API form the server i was able to see the problem. |
73,249,019 | let's say I have the following data frame table:
df
```
Users Data_Type
User1 String
User2 Integer
User3 String
```
I have the following sample list which dictionary elements inside it.
my\_dicts
```
[{'name': 'User4', 'dtype': 'StringType'},
{'name': 'User3', 'dtype': 'String'},
{'name': 'User1', 'dtype': 'Boolean'},
{'name': 'User2', 'dtype': 'String'}]
```
Based on the above table, I would like to update the above existing list of dictionary`my_dicts`. I would like to get the following result.
```
[{'name': 'User1', 'dtype': 'String'},
{'name': 'User2', 'dtype': 'Integer'},
{'name': 'User3', 'dtype': 'String'}]
```
I was trying with this:
```
list_= df['Users'].tolist()
my_new_list= dict(zip((*my_dicts ,), list_))
```
Can anyone help me with this? | 2022/08/05 | [
"https://Stackoverflow.com/questions/73249019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14882883/"
] | You did not provide how the table is formatted, so I'm assuming this data structure:
```py
updates = [
("User1", "String"),
("User2", "Integer"),
("User3", "String")
]
```
You can update `my_dicts` by going over each element and checking if the `name` key corresponds. If so, overwrite `dtype`.
```py
for (name, dtype) in updates:
for d in my_dicts:
if d["name"] == name:
d["dtype"] = dtype
```
I'm not entirely sure what the behavior should be for deleting rows. If any row in `my_dict` that is not in the new table should automatically be deleted, then what is the point of updating `my_dict`? It sounds like you want to *convert the table to your dict datastructure*. | ```
newlist = sorted(my_dicts, key=lambda d: d['name'])
``` |
6,477,318 | Given a jar runs within a JVM would it be possible to unload the current running Jar and remove it from the system. Download a new version and rename it with the same name of the last Jar and then initialise the new Jar, creating a seamless update of the Jar within the JVM. Is it even possible to instruct the JVM to perform this action? Is it even possible to update a Jar whilst its running? | 2011/06/25 | [
"https://Stackoverflow.com/questions/6477318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/450321/"
] | Generally you cannot do this as this behaviour to my knowledge is not officially defined.
You CAN however create a classloader using a jar file *outside* your official classpath and then load classes from that as you need. By discarding all instances of classes loaded by the classloader you can remove the current resources and then instantiate a new classloader on the new jar file and then load the new classes and create new objects.
This is quite complicated so perhaps you would instead make the jar an OSGi module and invoke your program through an OSGi-loader? | Please pay attention to Tom Hubbard's comment.
If a class was not used yet in Runtime (and therefore not loaded), if you remove the class in the new JAR - you will have some issues.
For example, if you will execute the following code:
```
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
while (true) {
long now = System.currentTimeMillis();
long delta = (now - startTime);
System.out.println("Running... delta is " + delta);
if (TimeUnit.MILLISECONDS.toSeconds(delta) > 30) {
Me1 m1 = new M1();
me1.method1(); // ###
}
Thread.sleep(1000);
}
}
```
If you put the above in a Jar and execute it, and before 30 seconds will pass, you will change the Jar such that the class "Me1" will not contain "method1" at all (and of course you will remove the line marked with "###"), after 30 seconds of execution you will get an exception:
```
Exception in thread "main" java.lang.NoClassDefFoundError: Me1
at Me.main(Me.java:16)
Caused by: java.lang.ClassNotFoundException: Me1
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
``` |
4,290,230 | I have a page `action.php` on which I run an SQL query through the code, so that whenever the page is viewed the query runs like **its like counting page views**
```
<?php
mysqli_query("UPDATE ****");
?>
```
The problem is when the page is refreshed, the query is run & PAGE REFRESH is counted as a PAGE VIEW which I want to avoid.
**Question:** How to avoid it ?
What I am looking for is a simple solution so that I can check
```
if( page was refresh ) //some condition
{
do
}
``` | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/158455/"
] | You can't directly detect a page refresh, but you can use a cookie to simulate what you want:
```
if (isset($_COOKIE['action'])) {
// action already done
} else {
setcookie('action');
// run query
}
```
Depending on your requirements, you also need to decide when to remove the cookie and/or perform the action again. | ```
//here you get the url behind the domain.
$currentPage = $_SERVER['REQUEST_URI'];
//if the session current page is not set.
if(!isset($_SESSION['currentPage'])){
//set the session to the current page.
$_SESSION['currentPage'] = $currentPage;
}
//check if the session is not equal to the current page
if($_SESSION['currentPage'] != $currentPage){
// if it's not equal you set the session again to the current page.
$_SESSION['currentPage'] = $currentPage;
//set the query you want to use
}
``` |
71,849,087 | I am new to Flutter. Why Do I need a Mac OS to develop IOS Applications in Flutter? | 2022/04/12 | [
"https://Stackoverflow.com/questions/71849087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18730456/"
] | change the `PASSWORD_HASHERS` in your `settings.py`
```
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
]
``` | Django rest framework doesn't encrypt the passwords automatically. You 'll have to explicitly do that. Use make\_password function from django contrib or if the insance is available you can simply do `instance.set_password(<password here>)`
Override the create/Update method of the serializer:
```
from django.contrib.auth.hashers import make_password
class UserSerializer(serializers.ModelSerializer):
....
def create(self, validated_data):
validated_data['password'] = make_password(validated_data['password'])
return super().create(validated_data)
```
Similarly for update
```
class UserSerializer(serializers.ModelSerializer):
....
def update(self, instance, validated_data):
if 'password' in validated_data:
validated_data['password'] = make_password(validated_data['password'])
return super().update(instance,validated_data)
``` |
44,344,624 | I'm trying to make a function in my service class, that render a twig page. I've tried to do like this:
**service.yml:**
```
********
parameters:
error.class: AppBundle\Utils\Error
services:
app.error:
class: '%error.class%'
arguments: [@templating]
```
**Error.php (service class):**
```
****
class Error
{
public function __construct($templating)
{
$this->templating = $templating;
}
public function redirectToError($condition,$message)
{
if($condition){
return $this->templating->render('default/error.html.twig',array(
'error_message' => $message,
));
}
}
}
```
and **error.html.twig** that have some random text to see if it gets there.
After that I get this answer from browser:
[](https://i.stack.imgur.com/Z1JH2.png)
Can somebody to tell me what is the problem? | 2017/06/03 | [
"https://Stackoverflow.com/questions/44344624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3628180/"
] | YAML can be a bit iffy when it comes to syntax, make sure your using all spaces (no tab chars). And makes sure every indentation is the same amount of space characters. Like 2/4/6/8 for each level or 4/8/12 etc if you prefer 4 wide.
The code you posted should be fine, but its probably something silly as described above. If it was actually a wrong section/ parameter in the file symfony should tell you what is unexpected as it actually validates YAML files on its content.
---
Allright so `['@templating']` takes care of the YAML parse error, the next part is how to use a service. Which is done using the [service container](http://symfony.com/doc/current/service_container.html).
In a controller there is an alias for it and you can do something like:
```
// required at the top to use the response class we use to return
use Symfony\Component\HttpFoundation\Response;
// in the action we use the service container alias
// short for $this->container->get('app.error');
$content = $this->get('app.error')->redirectToError(true, 'Hello world');
// as your redirectToError function returns a templating->render, which only returns a
// string containing the the rendered template, however symfony
// requires a Response class as its return argument.
// so we create a response object and add the content to it using its constructor
return new Response($content);
```
---
A few small things:
`$condition`, is probably likely to change if not it seems it should not be in the function but around the function call, as it seems weird to call an redirectToError but there is no error, instead we just call it when we do have an error.
And its recommended to if you are setting a class variable to define it ([details on visibility](http://php.net/manual/language.oop5.visibility.php)):
```
class Error {
// visibility public, private, protected
protected $templating;
``` | You should put `'` around `@templating`
```
services:
app.error:
class: AppBundle\Utils\Error
arguments: ['@templating']
``` |
2,221,806 | There are lots of PE file browsers. Here is a list of good ones if you are interested:
>
> PE File format viewers:
>
>
> * PE Explorer <http://www.pe-explorer.com/>
> * PE VIew: <http://www.magma.ca/~wjr/>
> * PEBrowse Professional <http://www.smidgeonsoft.prohosting.com/pebrowse-pro-file-viewer.html>
> * PE Browse Professional Interactive - <http://www.smidgeonsoft.prohosting.com/pebrowse-pro-interactive-debugger.html>
>
>
>
I'm still working on windows & I want to view the ELF files. Are there any tools? I'm googling but couldn't find any till now. | 2010/02/08 | [
"https://Stackoverflow.com/questions/2221806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268241/"
] | `readelf` and `objdump` are both excellent utilities if you are on a Unix box.
Both are provided by Cygwin.
`readelf` will give you a good overview of the ELF header information, section headers. You can also use it to get relocation and symbol information. Overall, `readelf` can give greater detail on the contents of an ELF file.
`objdump` has some similar features to `readelf`, but also includes the ability to disassemble sections. | I like objdump. I think it comes with the Mingw and/or cygwin distributions. |
1,399,336 | I have about one hundred of XML file (with the same structure) and I want to import them in SAS. Unfortunately in doing that I have some issues relatated to the MAP file of the XML files (I have not the MAP file for these files). So I though to convert these files in CSV through Excel. But if I use this path, I need something that is able to convert massively all my XML files in CSV, because clearly I can't convert by hands every file individually.
Anyone knows how can I solve?
Thanks. | 2019/01/28 | [
"https://superuser.com/questions/1399336",
"https://superuser.com",
"https://superuser.com/users/991047/"
] | I've solve my issue with this VBA script:
```
Public Sub ConvertXmlToXlsx()
Application.DisplayAlerts = False
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
xmlFolder = "C:\Users\xxx\xxx\xxx\xxx\"
convFolder = "C:\Users\xxx\xxx\xxx\xxx\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(xmlFolder)
For Each objFile In objFolder.Files
If UCase(Right(objFile.Name, Len(XML))) = UCase(XML) Then
NewFileName = convFolder & objFile.Name & ".xlsx"
Workbooks.OpenXML (objFolder & "\" & objFile.Name), LoadOption:=xlXmlLoadImportToList
ActiveWorkbook.SaveAs Filename:=NewFileName
ActiveWorkbook.Close
End If
Next objFile
End Sub
``` | Since you seem to be familiar with SAS, or you'll have to be soon, I'd use R to read out the Excel files and then write them again as CSV.
The code below allows you to set the working directory, read the contents onto a list and iterate through the list to conver the files in a few lines.
```
library(readxl)
setwd("The directory containing your files")
list <- list.files()
for(i in 1:length(list)) {
Intermediate <- read_excel(list[i])
write.csv(Intermediate, paste0(list[i],".csv"))
}
``` |
38,689,254 | Just launched mule studio 6.0.3 and trying to use Data Weaver. When I double click the transform message,only blank space coming up.
Whenever I drag and drop any components from palette, i am getting the error as :-
An internal error has occurred.
org/mule/tooling/apikit/common/metadata/resolver/APIkitRouterInvokerMetadataResolver$1$1
Any helps. | 2016/07/31 | [
"https://Stackoverflow.com/questions/38689254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767265/"
] | Maybe you have to write the entire url when you are setting the header:
```
header("Location: http://www.google.com");
``` | I wonder why you have set form method="get", but used $\_POST variable under php code. Here's another version using POST method, try if it helps.
```
<?php
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
if (isset($_POST['email'])) {
$email = $_POST['email'];
$address= $_POST['address'];
$subject = "Message from: ".$email;
$content = "Email: " . $email."\n"
. "Address: " . $address;
$headers ='Reply-To: ' . $email . "\r\n";
mail('example@gmail.com', $subject ,$content, $headers );
header("location: https://google.com");
exit;
}
?>
<form role="form" id="contact-form" method="post">
<div class="form-group row">
<input type="email" id="email" name="email" placeholder="Enter your email" required="required" class="form-control input-lg" />
<input type="text" id="address" name="address" placeholder="Enter your address" required="required" class="form-control input-lg" />
<button type="submit" class="btn btn-t-primary">Show Me Now!</button>
</div>
</form>
``` |
34,777,595 | I have a single .json file that contains configuration stuff that I would like to reference from another script file using the typical import/require syntax. Currently I'm using webpack to resolve these dependencies and bundle them for me. This file however I want to be loaded at runtime and was hoping that there might be some type of loader that could resolve and load this file for me at runtime. So far I haven't found anything that matches my needs exactly.
Example:
```
var jQuery = require('jQuery');
var sol = require('some-other-lib');
var myConfig = require('/real/production/url/myconfig.json');
console.log(myConfig.myFavoriteSetting);
```
In the example above I'd like to have `myconfig.json` resolved and loaded at runtime.
Possibly related questions:
* [how to use webpack to load CDN or external vendor javascript lib in js file, not in html file](https://stackoverflow.com/questions/33250174/how-to-use-webpack-to-load-cdn-or-external-vendor-javascript-lib-in-js-file-not)
* [Webpack - dynamic require and paths](https://stackoverflow.com/questions/31884135/webpack-dynamic-require-and-paths)
* [Require JS files dynamically on runtime using webpack](https://stackoverflow.com/questions/30575060/require-js-files-dynamically-on-runtime-using-webpack) | 2016/01/13 | [
"https://Stackoverflow.com/questions/34777595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83658/"
] | I think what you want is [require.ensure](https://webpack.github.io/docs/code-splitting.html), webpack's code splitting. The modules that you 'ensure' are put into a separate bundle, and when your 'ensure' executes at runtime, the webpack runtime automatically fetches the bundle via ajax. Note the callback syntax for ensure -- your callback runs when the bundle has finished loading. You still need to require the desired modules at that point; .ensure just makes sure they're available.
Code splitting is one of webpack's major features, it lets you load only what you need at any given time. There's plugins etc. to optimize the multiple bundles as well. | I had the same case with a file (config.json).
I decided to copy it with [Copy-Webpack-Plugin](https://github.com/kevlened/copy-webpack-plugin)
```
new CopyWebpackPlugin([
// Copy directory contents to {output}/
{ from: 'config.json' }
])
```
After that, my file was in the output build directory. I used 'externals' property to reference my file in my webpack.config file :
```
externals: {
'config': "require('./config.json')"
}
```
In my js file which load the config.json :
```
import config from 'config'
```
'config' load require('./config.json) which is the one in the output build directory.
I know it's tricky but I didn't find another solution to my problem. Maybe it will help someone.
**EDIT**
I had to use webpack in order to build because `import config from 'config'` wasn't understandable without it. That's why I replace :
```
externals: {
'./config.json': "require('./config.json')"
}
```
and
```
var config = require('./config.json') //replace import config from 'config'
```
Without webpack, Javascript understand `var config = require('./config.json')` because it's the right path.
And when I build with webpack, it change by `require('./config.json')` when it sees './config.json', so it works |
21,423,697 | I have class A and class B. And I have two functions:
`B FromAToB(A)`
and
`A FromBToA(B)`
The question is: In which class should I implement these functions? Or they should belong in another class? Or it doesn't matter? | 2014/01/29 | [
"https://Stackoverflow.com/questions/21423697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2708741/"
] | You can provide mutual conversion operators. This will require you to forward declare one class and defer the implementation of the conversion operator to after the implementation of the other class. For example:
```
#include <iostream>
struct Seconds;
struct Minutes
{
int value;
operator Seconds() const;
};
struct Seconds
{
int value;
operator Minutes() const
{
return Minutes{value / 60};
}
};
Minutes::operator Seconds() const
{
return Seconds{value * 60};
}
int main()
{
Minutes m{1};
Seconds s{60};
std::cout << static_cast<Seconds>(m).value << " "
<< static_cast<Minutes>(s).value;
return 0;
}
```
If you don't want implicit conversions (to avoid mistakes) you can add `explicit` to the operators. | Simply you may redefine cast operators to your type in each class you need.
For example, instead of calling functions (FromAToB etc) in A class you can do this:
```
operator B() {
// Creating B b_object
return b_object;
}
```
And then use it in the code
```
main() {
// Creating A a_object
B b_object = (B)a_object;
}
```
And vice-versa. So, there is no need to define special method for that, you may simply use type casts.
Some useful link: [Overloading typecasts](http://www.learncpp.com/cpp-tutorial/910-overloading-typecasts/) |
38,032,105 | I'm trying to use the EOF function but it doesn't work as I expect it. In the debugger mode it doesn't detect the second "scanf" function and just carries on. It keeps on missing out the "scanf" function now and then. Code is posted below
```
int main() {
char tempString;
int i = 0;
printf("Enter your letter\n");
scanf_s("%c", &tempString);
while (tempString != EOF) {
printf("You entered:%c\n", tempString);
scanf_s("%c", &tempString);
}
}
```
I have also tried it using the getchar() function but the same thing occurs, code is posted below:
```
int main() {
char tempString;
int i = 0;
printf("Enter your letter\n");
while ((tempString = getchar()) != EOF) {
printf("You entered:%c\n", tempString);
}
}
```
Thanks for reading | 2016/06/25 | [
"https://Stackoverflow.com/questions/38032105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6513225/"
] | EDIT:
Firstly you omitted the length argument required by `scanf_s` for `%c` and `%s` formats.
Second, the `%c` format takes the *next character from the input buffer*. At the second (and subsequent) entries there was a `newline` left in the input buffer from the first input. Adding a `space` before the `%c` format specifier cleans off that leading whitespace.
Other formats, such as `%s` and `%d` **do** ignore leading whitespace, but not `%c`.
Thirdly, with `scanf` the use of `EOF` is not the way to go, you should control the loop with the return value from `scanf` which tells you the number of items successfully read.
This program starts by using `scanf_s`. The second entry ignores the `newline` after the first entry.
Then it moves to using `getchar`. In this test the function return value is `int`, so that's my data type here. That way `EOF` (-1) won't conflict with any required character data. Note that `getchar` starts by reading the `newline` left after the previous `scanf_s` (which only ignores *leading* whitespace.
```
#include <stdio.h>
int main(void)
{
char ch_scanf; // char type
int ch_getchar; // int type
printf("Using scanf_s\n");
if (scanf_s(" %c", &ch_scanf, 1) == 1) { // consumes any leading whitespace
printf("scanf_s value: %d\n", ch_scanf);
}
if (scanf_s(" %c", &ch_scanf, 1) == 1) { // consumes any leading whitespace
printf("scanf_s value: %d\n", ch_scanf);
}
printf("\nUsing getchar\n");
while ((ch_getchar = getchar()) != EOF) {
printf("getchar value: %d\n", ch_getchar);
}
return 0;
}
```
Sample session:
```
Using scanf_s
A
scanf_s value: 65
B
scanf_s value: 66
Using getchar
getchar value: 10
C
getchar value: 67
getchar value: 10
^Z
```
Finally if you want to use the standard library function `scanf` without MSVC ticking you off, you can do it like this
```
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
``` | try this
```
#include <stdio.h>
int main(void) {
char tempString;
printf("Enter your letter\n");
while (scanf_s("%c%*c", &tempString, 1) != EOF) {//%*c for consume newline, 1 is buffer size
printf("You entered:%c\n", tempString);
}
return 0;
}
```
---
```
int tempString;//int for check EOF
printf("Enter your letter\n");
while ((tempString = getchar()) != EOF) {
printf("You entered:%c\n", tempString);
getchar();//consume newline
}
``` |
1,411,854 | I have a collection of static libraries (.lib) files one of which may have been built with a different version of Visual Studio. This is causing the code generation of a project that links against all of them to fail. Is there any way to determine which version of Visual Studio was used to compile a static library? | 2009/09/11 | [
"https://Stackoverflow.com/questions/1411854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118815/"
] | If you have the corresponding .PDB files then you can see the version of the compiler from there with a tool like [Pdb Inspector](http://www.codeproject.com/Articles/37456/How-To-Inspect-the-Content-of-a-Program-Database-P).
Or open the PDB in a hex viewer and search for the string "Microsoft (R) Optimizing Compiler". The version will be in four 2-byte hex values just before that string, like in this example:
```
000000A060: .. .. .. .. .. .. . ... .. .. .. .. .. .. 13 00 ..
000000A070: 00 00 6E 5D 00 00 4D 69 63 72 6F 73 6F 66 74 20 ......Microsoft
000000A080: 28 52 29 20 4F 70 74 69 6D 69 7A 69 6E 67 20 43 (R) Optimizing C
000000A090: 6F 6D 70 69 6C 65 72 00 .. .. .. .. .. .. .. .. ompiler ........
```
The version is thus HEX 13 00, 00 00, 6E 5D, 00 00, or 19.0.23918.0. | You didn't specify the language, but in C# the answer for knowing the OS and .NET version (in your code at runtime) is:
```
System.Version osVersion = System.Environment.OSVersion;
System.Version cliVersion = System.Environment.Version;
```
There would be an equivalent in Managed C++/CLI
That won't tell you the verison of the **compiler** or of the **IDE**, but will tell you the verison of the .NET runtimes. You may or may not need to know the OS version.
-Jesse |
1,469,854 | I have an asp Label control used for displaying error messages to the user. My client
would like certain words in these messages to be underlined. How would this be accomplished?
Thank you,
James | 2009/09/24 | [
"https://Stackoverflow.com/questions/1469854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/167027/"
] | Though a bit hacky, you can assign HTML markup to the Label's Text property. Something like this should suffice:
```
Label.Text = "this is an <span class='underlineIt'>underlined expression</span>";
```
The would assign class `underlineIt` to the words "underlined expression." Within the underlineIt CSS class, you can set the rule `text-decoration: underline`. | I total misunderstood the question blah.
Embed the HTML into the label's text property. |
29,991,578 | I'm developing an app that uses GPS position. For knowing position I get latitude and longitude.
I don't get position at regular intervals, but I want to know if user has moved. For that I store last position and current position (both latitude and longitude)
I was doing this:
```
if (latitudNew != latitudOld && longitudNew != longitudNew)
{
float R = 6378.137;
double dLat = ((latitudNew - latitudOld) * M_PI) / 180;
double dLong = ((longitudNew - longitudOld) * M_PI) / 180;
double a = sin(dLat/2) * sin(dLat/2) + cos((latitudOld*M_PI)/180) * cos((latitudNew*M_PI)/180) * sin(dLong/2) * sin(dLong/2);
double c = 2 * atan2(sqrt(a), sqrt(1-a));
double d = R * c;
}
```
Where distance is stored in d.
My problem is that it never get past the if condition, so I know I'm not comparing it correctly.
I can't use [this solution](https://stackoverflow.com/questions/4732645/iphone-objective-c-comparing-doubles-not-working), as I can have negative numbers (one or both or none).
Any ideas?? | 2015/05/01 | [
"https://Stackoverflow.com/questions/29991578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1520085/"
] | You have the line:
```
if (latitudNew != latitudOld && longitudNew != longitudNew)
```
This is doing `longitudNew != longitudNew`. You have a typo there, you're testing to see if a variable is not equal to itself. It'll always be false. You meant to put `longitudOld` for one of them. Though you probably want to replace the `&&` with `||`, because you want to execute the code in the if block if either of these conditions is true.
Also, this is a bit of a nit... The proper spellings are longitude and latitude. You left the e off of both. | That looks correct to me, you'd compare `double`s in Objective-C just as you would in C. The datasource you're getting the information from might be rounding the values so that they appear as equal or the data isn't updating often enough.
Also, you'd probably want to change the logic to have an `||` in the `if` instead of an `&&`. You'd still consider an update in location to be an update, even if it was just in one of the two. |
1,483,278 | I know that $A-S-S$$(Angle-Side-Side)$ congruence does not exist.But I cannot disprove it. Every time I draw a figure,I get two congruent triangles.
**My Attempt**-[](https://i.stack.imgur.com/08uqQ.jpg)
So,we draw two lines such that $AB=DE$.Now we draw angles $\angle CAB=\angle FDB.$Now,By compass we take measurements such that $CB=FE.$By Cutting arcs on lines $A$ and $B$ we see that $AC=DF$ always.So,Now the two triangles are congruent by $SAS.$
Someone please help me out of this,with a diagram to disprove it.
Thanks a lot in advance. | 2015/10/16 | [
"https://math.stackexchange.com/questions/1483278",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242402/"
] | Here is a counterexample that should be what you are looking for:
[](https://i.stack.imgur.com/PLF9b.png) | Did you see that your example is a **right** triangle? Look at your method but imagine that last side being done by setting the point of compasses, set to the given length, at E and striking an arc. There are **three** possible results. In might happen that the arc is simply NOT long enough to reach side AC. In that case, there is NO such triangle, It might happen that the arc cuts side AC in two different places. In that case there are **two** such triangles (this is the case that aras is giving). It might happen that the arc strikes side AC in exactly one place. In that case, side AC is **tangent** to the arc so the triangle is a **right** triangle. |
803,921 | I'm trying to use the navigation command framework in WPF to navigate between Pages within a WPF application (desktop; not XBAP or Silverlight).
I believe I have everything configured correctly, yet its not working. I build and run without errors, I'm not getting any binding errors in the Output window, but my navigation button is disabled.
Here's the app.xaml for a sample app:
```
<Application x:Class="Navigation.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="First.xaml">
</Application>
```
Note the StartupUri points to First.xaml. First.xaml is a Page. WPF automatically hosts my page in a NavigationWindow. Here's First.xaml:
```
<Page x:Class="Navigation.First"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="First">
<Grid>
<Button
CommandParameter="/Second.xaml"
CommandTarget="{Binding RelativeSource=
{RelativeSource
FindAncestor,
AncestorType={x:Type NavigationWindow}}}"
Command="NavigationCommands.GoToPage"
Content="Go!"/>
</Grid>
</Page>
```
The button's CommandTarget is set to the NavigationWindow. The command is GoToPage, and the page is /Second.xaml. I've tried setting the CommandTarget to the containing Page, the CommandParameter to "Second.xaml" (First.xaml and Second.xaml are both in the root of the solution), and I've tried leaving the CommandTarget empty. I've also tried setting the Path to the Binding to various navigational-related public properties on the NavigationWindow. Nothing has worked so far.
What am I missing here? I *really* don't want to do my navigation in code.
---
Clarification.
If, instead of using a button, I use a Hyperlink:
```
<Grid>
<TextBlock>
<Hyperlink
NavigateUri="Second.xaml">Go!
</Hyperlink>
</TextBlock>
</Grid>
```
everything works as expected. However, my UI requirements means that using a Hyperlink is right out. I need a big fatty button for people to press. That's why I want to use the button to navigate. I just want to know how I can get the Button to provide the same ability that the Hyperlink does in this case. | 2009/04/29 | [
"https://Stackoverflow.com/questions/803921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | According to the [documentation](http://msdn.microsoft.com/en-us/library/system.windows.input.navigationcommands.gotopage.aspx), only `DocumentViewer` and `FlowDocumentViewer` implement this command specifically. You'll need to either find a command for navigation that `NavigationWindow` implements, or set up a `CommandBinding` for this command and handle it yourself. | In XAML:
```
<Button Command="{x:Static Views:Commands.NavigateHelp}" Content="Help"/>
```
In Views (We have a `Commands.cs` file that contains all of these):
```
public static RoutedCommand NavigateHelp = new RoutedCommand();
```
In the Page contstructor, you can connect the two:
```
CommandBindings.Add(new CommandBinding(Commands.NavigateHelp, NavigateHelpExecute));
```
NavigateHelpExecute can be in the code behind (which is what we do), hook into a ViewModel event handler, or whatever. The beauty of this is that you can disable other navigation like so:
```
CommandBindings.Add(new CommandBinding(NavigationCommands.Refresh, null));
```
Hope this helps. |
8,232,608 | How to fit an image of random size to an `ImageView`?
When:
* Initially `ImageView` dimensions are 250dp \* 250dp
* The image's larger dimension should be scaled up/down to 250dp
* The image should keep its aspect ratio
* The `ImageView` dimensions should match scaled image's dimensions after scaling
E.g. for an image of 100\*150, the image and the `ImageView` should be 166\*250.
E.g. for an image of 150\*100, the image and the `ImageView` should be 250\*166.
If I set the bounds as
```
<ImageView
android:id="@+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true" />
```
images fit properly in the `ImageView`, but the `ImageView` is always 250dp \* 250dp. | 2011/11/22 | [
"https://Stackoverflow.com/questions/8232608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326849/"
] | After searching for a day, I think this is the easiest solution:
```
imageView.getLayoutParams().width = 250;
imageView.getLayoutParams().height = 250;
imageView.setAdjustViewBounds(true);
``` | Use Simple math to resize the image . either you can resize `ImageView` or you can resize drawable image than set on `ImageView` . find the width and height of your bitmap which you want to set on `ImageView` and call the desired method. suppose your width 500 is greater than height than call method
```
//250 is the width you want after resize bitmap
Bitmat bmp = BitmapScaler.scaleToFitWidth(bitmap, 250) ;
ImageView image = (ImageView) findViewById(R.id.picture);
image.setImageBitmap(bmp);
```
**You use this class for resize bitmap.**
```
public class BitmapScaler{
// Scale and maintain aspect ratio given a desired width
// BitmapScaler.scaleToFitWidth(bitmap, 100);
public static Bitmap scaleToFitWidth(Bitmap b, int width)
{
float factor = width / (float) b.getWidth();
return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
}
// Scale and maintain aspect ratio given a desired height
// BitmapScaler.scaleToFitHeight(bitmap, 100);
public static Bitmap scaleToFitHeight(Bitmap b, int height)
{
float factor = height / (float) b.getHeight();
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
}
}
```
**xml code is**
```
<ImageView
android:id="@+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true"
android:scaleType="fitcenter" />
``` |
21,615,687 | I'm trying to sort my users in my controller, and I wanted to sort them by id number. My question is, does rails automatically assign orders an id when they are created, or do I need to add that to the create function in my create action in my controller? For example, can I say this:
```
def index
@users = User.all.order(:WHAT TO PUT HERE???????)
end
```
Would I put :id in the space? If I did so, would I need to define id somewhere else or is this something ruby does on the back end? | 2014/02/06 | [
"https://Stackoverflow.com/questions/21615687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2253215/"
] | In most cases Rails would return you records sorted by id. But you should not rely on Rails as sorting is database-specific.
To explicitly add sorting by id you should use:
```
def index
@users = User.order(:id)
end
```
Id is automatically added, you don't need to declare it anywhere. | If you want to sort User by ID
```
@users = User.order(:id) #ASC default
@users = User.order('id ASC') #ASC explicit
@users = User.order('id DESC') #DESC explicit
``` |
49,871,582 | I wanted to circle my UIImageView and added this code :
```
profileImage.layer.cornerRadius = profileImage.frame.size.height/2
profileImage.clipsToBounds = true
```
and it work perfectly, but when images are horizontal, I get this picture:
[](https://i.stack.imgur.com/20Sn5.png)
as you can see, there is white space at the bottom and top of my circle image view. but what I really wanted was a circle filled with my image!
I've tried changing "content Mode" from attribute inspector, but I didn't get any answer! how can I fix this issue? | 2018/04/17 | [
"https://Stackoverflow.com/questions/49871582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646999/"
] | You have already set the `clipsToBound` property. So just update the `contentMode`.
**I you don't want to distort image's scale:**
```
profileImage.contentMode = .scaleAspectFill
```
**If image's scale does not matter, you also can use:**
```
profileImage.contentMode = .scaleToFill
```
>
> Follow the link for more details: <https://useyourloaf.com/blog/stretching-redrawing-and-positioning-with-contentmode/>
>
>
>
[](https://i.stack.imgur.com/lan7M.png) | Set the `contentMode` of your UIImageView to `scaleAspectFill`
```
profileImage.contentMode = .scaleAspectFill
```
Keep in mind that using this contentMode option some portion of the content may be clipped to fill the view’s bounds. |
257,353 | Is there a native c++ variable type that's "bigger" than a double?
float is 7
double is 15 (of course depending on the compiler)
Is there anything bigger that's native, or even non-native? | 2008/11/02 | [
"https://Stackoverflow.com/questions/257353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31325/"
] | C++ has long double, but it's still quite limited. For good time try GNU's gmp library. You can set up numbers as big as you like, and it's quite fun and hackishly when you use gmp\_add instead of a normal +. I'm sure there's a C++ wrapper somewhere. | Boost 1.53 or higher has multiprecision.
<http://www.boost.org/doc/libs/1_54_0/libs/multiprecision/doc/html/index.html> |
17,474,793 | Currently we have a splash screen that is displayed in our app. However, if there is no data to be gathered or processed that is waiting, we'd like to go straight into our first activity. Is there a way to do that without having the splash screen flash?
The AndroidManifest.XML of the splashscreen portion is as follows:
```
<activity android:name="com.example.SplashScreenActivity"
android:label="@string/app_name"
android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
``` | 2013/07/04 | [
"https://Stackoverflow.com/questions/17474793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176436/"
] | Given that the launcher will start the activity you specify in your Manifest, it's not possible to set conditions on whether that activity will be started (or another).
So you're left with the options as Richard Le Mesurier and dors suggest:
1. Start the main Activity, then launch the Splash Activity if needed
2. Start a gui-less Activity (no layout file), then decide which Activity should be presented to the user
I'd prefer the second option, or if you're planning to introduce Fragments anyway, use them here:
1. Use `Fragments`. Start your main activity, which has a Fragment placeholder. If you need to show Splash Screen, load the SplashScreenFragment in that activity, otherwise, load the Fragment that constitutes the first *useful* screen to the user.
**As an aside, the use of splash screens is discouraged; as a user, I'd prefer to see the main Activity with most of the static UI components loaded immediately, and some on-screen indication that something is loading/updating.** | You can do something like this:
1. Your Splash Screen is the main activity (Launcher-Category)
2. If your splash screen can load data (or whatever your splashscreen does), do it. After finished, close the spalsh screen (call finish()) and start the real first activity and pass the data as intent extra.
3. If your splashscreen can not load data or (or whatever your splashscreen does), start the next Activity by using an Intent and finish the spalsh screen activity by calling finish()
So the workflow of your app will be:
1. Click on the launcher icon
2. The Splash Screen Activity will always been started
3. If spalsh screen can not load, than the activity will be finished immediately and the other activity will be started. Your app user will not notice that the splash screen activity if you finish() the splash screen activity immediately, because the activity is never shown on screen in this case |
9,684,478 | Happily using `Rinku` gem to autolink my text. This is helpful when someone pastes in a URL in a comment - `Rinku` will autolink that URL.
However, really long URLs are messing with the page layout. It would be helpful for every hyperlink encountered:
* Shorten the hyperlink text
* Keep the underlying hyperlink
e.g. `http://www.yahoo.com` may be displayed as `http://www.ya...` but in the underlying HTML, the hyperlink is `http://www.yahoo.com`. Twitter does this with tweets.
Have been searching high and low for any existing gems or prior experience on this. Haven't come up with anything so far. | 2012/03/13 | [
"https://Stackoverflow.com/questions/9684478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/625666/"
] | [Looks like](https://github.com/tanoku/rinku/blob/master/README.markdown) Rinku supports customization of the link text:
```
auto_link(text) do |url|
url.truncate :length => 15
end
``` | Not sure about Rinku, but you could easily do this from within the view:
```
<% trunk_url = truncate(url, :length => 15) %><%= link_to(trunk_url, url) %>
```
Basically, truncate the url itself into a string (trunk\_url), then use that as the text for the link\_to. In my case, the url was a field (tm.website). Works perfectly. |
31,541,489 | I'm trying hard to get the modification date from a MP4 file hosted on my server.
I tried the following library:
```
ffmpeg -i video.mp4
```
Without any luck. All I get is duration and a few other fields but I'm not able to get modification date. I tried ffprobe as well and it is not there either.
Any suggestions??
Thanks a lot | 2015/07/21 | [
"https://Stackoverflow.com/questions/31541489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3280699/"
] | I checked for you, and indeed, mp4 has a modification time entry in the MDHD, but it's not exported (see [code](http://git.videolan.org/?p=ffmpeg.git;a=blob;f=libavformat/mov.c;h=92bf2f894099f0e4d50b6184f19852769c372139;hb=HEAD#l1045)). You can file an [enhancement request](https://www.ffmpeg.org/bugreports.html) to get this metadata feature added to FFmpeg, but right now it won't help you and you'll need another tool to read this field. | A simpler alternative to aergistal in terms of output is
```sh
$ ffprobe -v quiet -select_streams v:0 -show_entries stream_tags=creation_time -of default=noprint_wrappers=1:nokey=1 input.mp4
```
which will just print the creation time like so:
```
2020-07-23T11:51:02.000000Z
``` |
493,071 | I have a minimal CentOS 6.3, 64 bit acting as gateway with 4 NIC (1 Gbps), each bonded together one for public traffic and other for private, which performs NATing. It has 6 GB RAM and 4 logical cores. We have been using this for the past two years without any problems.
I don't have any experience with hardware routers, but I have heard that they have less RAM and CPU and use flash disks. How can a box with low hardware configuration perform better (as in, handle more concurrent connections) than a machine with more RAM and CPU?
What are the limiting factors, other than IOS using different methods to handle this? | 2013/03/28 | [
"https://serverfault.com/questions/493071",
"https://serverfault.com",
"https://serverfault.com/users/133041/"
] | "Other than IOS" ?
IOS makes almost all the difference. CentOS is a general-purpose operating system. It's designed to perform well enough under a very wide range of scenarios, using a vast array of different hardware configurations. IOS on the other hand is extremely fine tuned to handle only the kind of workloads you would expect from a piece of network equipment, using the very specific types of hardware you would find in Cisco gear.
Knowing *exactly* what pieces of hardware you're programming for will take you a very long way in terms of performance vs. compatibility. | AFAIK, it's the overhead of a general-purpose operating system; regardless of how fast your connections, the packets are dealt with on a packet-by-packet basis within the kernel's context, increasing latency and strain on the system. I believe it's been already explained in the other Answers better than I could do.
Having said that, there are promising new"ish" technologies increasing in popularity and feasibility that might create a more formidable competitor out of Linux systems in this as well as in other regards; i.e. InfiniBand
Take a look at the following Q&A on StackOverflow:
[How is TCP Kernel-bypass Implemented](https://stackoverflow.com/questions/11729271/how-is-tcpkernel-bypass-implemented)
Further Reading:
* [A Tutorial at CCGrid ’11: Infiniband and 10-Gigabit Ethernet for Dummies](http://www.ics.uci.edu/~ccgrid11/files/ccgrid11-ib-hse_last.pdf)
* [InfiniBand and Linux in a LinuxJournal Article](http://www.linuxjournal.com/article/8009)
* [Access to InfiniBand from Linux - Intel DeveloperZone](https://software.intel.com/en-us/articles/access-to-infiniband-from-linux)
* [InfiniBand OpenSource Project](http://infiniband.sourceforge.net/) |
60,695 | So I was thinking about how I could make a responsive menu a better experience rather than just firing it into a drop down on mobile that has a hamburger as an icon.
Would it perhaps be a better user experience to limit the amount of navigation items, for example if you had:
(We'll use this site as an example)
Questions, Tags, Users, Badges, Unanswered and Ask Question...
To perhaps keep the menu visible but only hide the less important navigation items under a drop down called more with:
Questions, More and Ask Question
Or is the hamburger menu the better experience? | 2014/07/02 | [
"https://ux.stackexchange.com/questions/60695",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/51171/"
] | Paddi MacDonnell wrote an interesting [article on the hamburger menu](http://www.webdesignerdepot.com/2014/06/how-to-solve-the-hamburger-icon-problem/) and related mobile-first approaches to design a few days ago:
It outlines some of the problems of hamburger menus, and concludes with the observation that the device is something of a way to brush the navigation of a complex app under the carpet of the hamburger icon (my carpet analogy, not hers!).
>
> Facebook’s app famously swapped their hamburger icon for a tab bar,
> and as a result saw improved conversions. But Facebook have done
> something far more significant than swap menu designs. Recently
> they’ve released their Messenger app, and the big deal about that is
> that they already had a perfectly functional and popular app that they
> could have integrated the messaging with. Facebook have
> compartmentalized their functions, by focusing each app’s role they’ve
> arrived at two simple apps, instead of one complex one. The reduced
> functionality results in a reduced set of menu options, and less need
> for a hamburger menu.
>
>
> Good apps are highly focussed, and they’ve
> evolved that way through far more rigorous user testing than the Web
> is subjected to. To create an app-style experience we need to simplify
> our sites, simplify again, and then simplify a bit more. If necessary,
> break your architecture down into manageable bite-sized pieces,
> microsites almost. When we present our users with a simple set of
> options, the problem of a complex menu never arises.
>
>
> Making use of the
> hamburger icon is like slapping a band-aid on an injury: it patches it
> up, but underneath something is still broken.
>
>
>
As suggested in the question, if you can sensibly break down the architecture of the app/site in such a way that you can supply enough relevant and useful navigational items without having to resort to the hamburger icon, then that simplifies things for the user.
If, superficially it seems impossible to reduce the number of items to a manageable number, then perhaps it may be worth taking a step back and considering what you might have to do in order to make it possible - and whether that chunking or restructuring process would improve the mobile experience overall.
I would add that while reducing the navigation to the point where a hamburger menu is not needed, you should ensure that you still provide the basic navigation needs of being able to go back to where you came from, proceed to a similar item, move to a next stage, and avoid being left down a dead end.
**Edit**:
See also: [Why and How to avoid Hamburger Menus](http://lmjabreu.com/post/why-and-how-to-avoid-hamburger-menus/) by Luis Abreu, where the same conclusion is reached:
>
> **The solution is reviewing your information architecture.**
>
>
> | I'd prefer expandable and collapsible parent menu items on mobile devices. Each parent item that is expanded, automatically closes any others. This keeps the navigation compact and user friendly across mobile devices.
Whether you trigger this menu via a hamburger icon or otherwise is just one option of many but at least it is a relatively known representation of a menu now on mobiles.
Along the lines of the below:-

Definitely reduce menu items as much as possible for mobile devices but at least this method offers a condensed and user friendly functionality whilst still providing the ability to offer a relatively substantial amount of menu items. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.