message
stringlengths 2
17.7k
| message_type
stringclasses 2
values | message_id
int64 0
19
| conversation_id
int64 0
1.03k
|
---|---|---|---|
In The Light Fantastic, after talking about the dimensions of the Pyramid of Tsort, it says
All in all, it was a lot of effort to go through just to sharpen a razor.
What's the joke here?
|
instruction
| 0 | 350 |
In the real world, there is or was a belief, brought on by the Egyptomania of the early 20th century, that pyramids had special powers—including, specifically, the power to sharpen or maintain the sharpness of razor blades.
Pyramid power refers to the belief that the ancient Egyptian pyramids and objects of similar shape can confer a variety of benefits. Among these assumed properties are the ability to preserve foods, sharpen or maintain the sharpness of razor blades, improve health, function "as a thought-form incubator", trigger sexual urges, and cause other effects. Such unverified theories regarding pyramids are collectively known as pyramidology.
Czechoslovakian Karel Drbal even patented a pyramid-shaped device specifically designed for razor blades. Among the specifications:
It is beneficial to leave a new blade in the pyramid one to two weeks before using it. It is essential to place it there immediately after the first shave, and not the old, dull one. But it is possible to use an old one, if it is properly resharpened. The blade placed using the method above is left unobstructed until the next shave. The west edge should always face west. It improves the sharpening effect.
|
output
| 1 | 350 |
After a ```git pull origin master```, I get the following message:
warning: Pulling without specifying how to reconcile divergent branches is
discouraged. You can squelch this message by running one of the following
commands sometime before your next pull:
git config pull.rebase false # merge (the default strategy)
git config pull.rebase true # rebase
git config pull.ff only # fast-forward only
You can replace "git config" with "git config --global" to set a default
preference for all repositories. You can also pass --rebase, --no-rebase,
or --ff-only on the command line to override the configured default per
invocation.
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), 51.49 KiB | 850.00 KiB/s, done.
The pull seems successful, but I am unsure.
What can I do to fix this?
|
instruction
| 0 | 351 |
This is a new warning added in Git 2.27:
* "git pull" issues a warning message until the pull.rebase configuration variable is explicitly given, which some existing users may find annoying---those who prefer not to rebase need to set the variable to false to squelch the warning.
To remove the warning, set one of the suggested values to your preferred default behaviour for git pull if you don't specify behaviour on the command line (using --ff, --no-ff, --ff-only, --rebase). In all cases, git will attempt a fast-forward merge if possible. The settings control what happens when there are changes in your branch but not present in the remote branch.
```
git config pull.rebase false # merge (the default strategy)
```
This is the existing default behaviour; set this for no warning, and no change in behaviour; git will merge the remote branch into your local one.
```
git config pull.rebase true # rebase
```
Here, git will attempt to rebase your changes on top of the remote branch.
```
git config pull.ff only # fast-forward only
```
If a fast-forward merge is not possible, git will refuse to proceed.
> Refuse to merge and exit with a non-zero status unless the current HEAD is already up-to-date or the merge can be resolved as a fast-forward
|
output
| 1 | 351 |
In India, we eat rice using our fingers. Generally in the West, a fork or spoon is used. I have tried eating rice with spoon but I don't feel satisfied with it.
We eat dry rice but we mix curry and vegetables with it and then eat it with our hands.
Is there a way to eat rice with your hands in front of Westerners such that it doesn't appear to be disgusting to them? By disgusting I mean that they shouldn't feel like vomiting or looking away to avoid me. Even though in India we eat with our fingers, many people eat such that their whole palm is covered with food. That indeed looks disgusting.
I cannot avoid hurting them by following different etiquette, but I certainly want to maintain a degree of cleanliness.
|
instruction
| 0 | 352 |
First and foremost, you can eat the way you want. When it comes to western culture, the only thing that is generally disliked are noises, eating with the mouth wide open (included speaking with full mouth), and (excessively) dirtying the table. Eating rice with hands will be seen (mostly) as strange, not disgusting.
Second, context. Are you eating at a formal dinner with your colleagues and a client? Eat with the fork, as everybody else. Are you eating at the work's canteen? Eat the way you prefer and let other deal with their limits. And so on.
Third, respect and open mindness: you are worried other peoples find you disgusting for eating rice with hands, but at the same time you show the same "closed mind" (in a way, ok? I'm not trying to offend you) in wanting to eat rice with hands at all cost otherwise you will not feel satisfied; believe me, eating with a fork will not starve you as will not change food nutritional content.
Even more if you are eating at a foreign restaurant, e.g. at an italian restaurant rice is cooked and thought to be eatean with a fork. Respect local culture, open yourself to a new experience, and try to learn a different way to enjoy food.
In the end: feel free to do whatever fit you most, don't be afraid of other people judging you (their fault), but at the same time don't close yourself in your garden (your fault).
|
output
| 1 | 352 |
The typical argument goes like this:
Without net neutrality, cable companies could censor websites, favoring their own business partners.
Typically, proponents of legislation point to some perceived injustice, and argue that new laws are needed to address it. But the very use of the subjunctive in the quotation (could censor), suggests that this might be considered by its opponents as a solution in search of a problem. If so, why haven't they used that rhetorical tactic? Conversely, if such incidents have occurred, why don't the neutrality supporters cite them?
|
instruction
| 0 | 353 |
There have been a few examples, in part, these examples have pushed this more into the spotlight. It's often under the term 'traffic shaping' if you are interested, here is Sandvine, a company that offers those shaping services. If you are interested in the peer2peer domain (which is heavily bringing this issue to the forefront) here is a national list of ISP's and their throttling practices on bit torrent users: Curious if this documented list counts as citing.
For the US:
Verizon has run testing on it.
“YouTube is being throttled to 10Mbps as well,” one person wrote on Thursday. “In the ‘stats for nerds,’ it would load at roughly 1,250KBps which translates to 10Mbps. Put the VPN on and that number tripled easily. Didn’t have an issue playing 1080p in 60fps, though.”
(part of the problem with throttling is if you know your way around it, there isn't an issue. Tax on the non-tech savvy).
Verizon stated they were not throttling, however, articles suggest they did and still are. Here is an article stating Verizon is actively throttling video connections over their network. Over to Comcast who has been engaging in this practice but not admitting it until much more recently:
* When Comcast throttled BitTorrent users, they had a lawsuit brought against them that won.
* Sprint: They deny they do, though it's apparent they can. User backlash results in people monitoring if they are being throttled. Of course, there are several accusations.
* Bell and Rogers in Canada.
Telus has also blocked union sites and have engaged in some pretty underhanded anti-union tactics. Not sure if blocking sites fall under net neutrality though.
|
output
| 1 | 353 |
Does having a longer Ethernet cable slow your connection?
|
instruction
| 0 | 354 |
For all practical purposes, there will be no effect on the speed of your connection.
There will be a very insignificant amount of delay due to long cables. This won't affect the maximum speed of your connection, but it would cause some latency. pjc50 points out that it's about a nanosecond for every foot of cable length, which is a good rule of thumb used by many engineers when developing systems which are very dependent on latencies on those timescales.
In reality, you will never notice a difference. A "fast" ping time on the Internet is 10 ms, which is 10,000,000 ns. Adding even a few hundred feet of cable isn't going to have a noticeable effect at that point. In fact, nearly every step of the way involves delays which are more extreme than those seen from signal propagation. For example, most consumer grade routers will wait for the last byte of an incoming packet to be received and check it for errors before sending the first byte of the packet on its way. This delay will be on the order of 5,000 ns! Given that the maximum length of cable you can run (per the Ethernet spec) is 300 ft, the cable length could never cause more than 300 ns of delay due to the cable!
|
output
| 1 | 354 |
Border around formatted text in Inkscape
|
instruction
| 0 | 355 |
Here is solution step by step:
* Create some flowed text by using the text tool to first drag a rectangle and then type.
* Separately, create a rectangle roughly around the text (really, the rectangle can be anywhere)
* With the rectangle selected, chose "Path" > "Linked Offset". Then grab the small diamond and drag it in to make a second, smaller rectangle.
* Select the text and the smaller rectangle and choose "Text" > "Flow into frame". Then select the smaller rectangle and remove the stroke to make it invisible. Now the text will flow within the smaller (invisible) rectangle, which is dynamically linked to the shape of the larger (visible) rectangle.
* Then, if you like, you can add a small border radius on the visible rectangle and you get this nice looking result.
* If you do need to modify the space between the text and the rectangle, you can carefully select it by grabbing it with the text and the subtracting the text from the selection, or you can drill down to it within the XML Editor. When you do get it selected, then you can adjust the margin.
* Finally, group the text and the two rectangles, and you're all set!
|
output
| 1 | 355 |
I learned about the equilibrium constant. Now, I've seen that the equilibrium constant of burning is extremely small $(K \ll 1)$. here, I have a question. you see, $K$ is still NOT 0, which means that the forward reactions happen at least a tiny bit. Then, shouldn't we see some parts of anything burning at least a little bit?
|
instruction
| 0 | 356 |
The equilibrium constant for combustion of organic matter in air with oxygen is not small, but extremely large ($K_\mathrm{eq} \gg 1$), as is expected from a reaction that is simultaneously very exothermic and (usually) increases entropy due to the formation of more gaseous molecules than the input oxygen.
The major reason carbon-based life can exist at ambient temperature in an oxygen atmosphere is purely kinetic, not thermodynamic. You, the tree outside and everything else made of carbon is right now undergoing continuous combustion. However, in the absence of catalyst, this process is too slow below a couple hundred degrees Celsius for it to be self-sustaining. More technically, combustion of organic matter is a highly exergonic process, but the activation energy is high. The meagre amount of heat generated by the handful of molecules reacting is too quickly diluted into the surroundings, and the reaction does not accelerate and spiral out of control (a fire, as described by the eternal Feynman).
Very luckily for us, Life figured out this vast untapped source of chemical energy held back by kinetics approximately three billion years ago and developed a whole metabolic process to extract this energy in a stepwise fashion using catalysis, which we call aerobic respiration. Without it, multicellular organisms could well never had evolved.
|
output
| 1 | 356 |
The name "Bleach" seems to be having no relevance to the plot unlike most other series. Was it just chosen at Kubo-sensei's whim or does it have some significance? Maybe some cultural significance associated with shinigami, etc. that I am now aware of?
|
instruction
| 0 | 357 |
Kubo himself has commented on this. Below is the quote from Bleach Answers Wiki:
> The title wasn't Bleach when Tite Kubo decided to draw a story about Shinigami. This was before he drew the one-shot manga that appeared in Akamaru Jump. The weapon wasn't a sword, but a scythe. Only Rukia had a scythe and the other characters used guns. At that point, the title was Snipe (as in "Sniper"). Right before he started drawing, he began to think that a sword would be better and realized he couldn't use Snipe as a title anymore. He began looking for a title that grasped the bigger picture. Shinigami are associated with the color black, but it would have been boring to use "black". "White", on the other hand, can suggest black as a complementary color. So Tite Kubo chose "Bleach" to evoke the impression of the color white.
There are also other theories, which aren't as well supported by interviews with Kubo but still seem to have some evidence supporting them. One is that shinigami "cleanse" souls, similar to what bleach does (Kubo himself mentioned this in an interview, but it's not clear whether he noticed this before or after deciding on the name). Another is that Kubo is a fan of the band Nirvana, and their first album is Bleach. So there might be more than one reason, but the quoted one above is the one he usually gives when asked about it.
|
output
| 1 | 357 |
Why don't rally cars have airbags?
|
instruction
| 0 | 358 |
If you are ever lucky enough to drive a competition car, the first thing that will strike you is that you can't move. Once you're in your bucket seat with your fire retardant overalls on, wearing a full face helmet and neck brace and strapped firmly in with your multipoint harness, you'll feel like you've been pinned to the seat.
You can't look over your shoulder like you can in a road car. You can't reach the location where the glove-box is. In the event of a collision, the chances of your helmet coming into contact with the steering wheel are absolutely minimal.
However, if you watch rally cars in action, especially on gravel, you'll see them yumping (rally speak of hitting a jump), you'll see them in and out of ditches, ruts and rivers. Many of the impacts a rally car suffers during normal use would far exceed the trigger points to deploy a standard air-bag. Deployment of such a device when landing an airborne car that's travelling in excess of 120mph (200km/h) with spectator lined roads could have deadly consequences.
Similarly, in racing when there are multiple cars jostling for position on the same piece of track, deployment would be likely from all the "door handling" (a term to describe "acceptable" contact between race cars) and if one in the middle of a pack were to deploy, forcing the drivers hands away from the wheel, it would likely cause carnage.
In summary, air bags are not fitted to competition cars because they could pose a serious and significant risk to both the occupants of the cars and people outside such as other competitors, marshals and spectators.
|
output
| 1 | 358 |
Was the Millennium Falcon a one-off or was it mass produced?
|
instruction
| 0 | 359 |
The Millennium Falcon is not unique; it was a model YT-1300f Corellian light freighter. This implies that there are other similar ships, including other variations on the YT-1300 model.
You can find a lot of information about the Millennium Falcon in a companion book, Star Wars: The Force Awakens: Incredible Cross-Sections. The model number also appears on-screen at least once: in Star Wars: Rebels episode "Fighter Flight" on a poster.
Note, however, that the Millennium Falcon has been highly customized; some of the custom work is mentioned in The Force Awakens. It's not clear just how much of the ship is stock and how much is custom.
If you're willing to go outside Canon into Legends, the model number of the ship, and other similar Corellian light freighters, can be seen in some of the video games, and there is an entire novel called Millennium Falcon that details its history. The ship was serial #YT-1300 492727ZED, one of many such vessels, but from the beginning the ship was shown to have some "quirks" to distinguish it from its counterparts.
In Legends, the ship was also destroyed and rebuilt from scratch at least once, so it's arguable as to whether it's still the same ship or not.
|
output
| 1 | 359 |
Usually when I see lists of things to do to be more energy efficient, they require one to own their own home. What can I do to be more energy efficient in an apartment?
For example, I can't install solar panels, I can't upgrade/change my appliances, I can't install better insulation or windows, and I can't install a programmable thermostat.
Pretty much the only thing I can do (and have done) is switch all of my bulbs to CFLs. I also keep all of my electronics on power strips which I turn off when I leave my apartment and when I'm sleeping.
|
instruction
| 0 | 360 |
There are a lot of little things you can do that can add up. Here are some suggestions:
* Wash clothes in cold water only.
* Turn your freezer/refrigerator up a few degrees.
* Purchase insulated curtains/shades, and close them during the day when you are at work.
* Make sure your furniture is arranged so that it is not blocking any vents or radiators.
* Purchase a draft guard to place at the bottom of your door leading to the outside where temperature-controlled air can escape from your apartment.
* Install a low flow shower water head. Shower head screw on/off easily. Keep the old head to replace when/if you move.
* Clean Your Refrigerator: It's unlikely that you'll purchase new energy efficient appliances for your rental, but you can tweak the ones you already have. For example, by cleaning the coils on the back of your fridge you'll help one of the biggest energy hogging appliances run more efficiently.
* Use Energy Efficient Bulbs, even if you're put off by the slightly higher upfront cost, you can simply unscrew them and take them with you when it's time to move.
* Use Power Strips: A lot of energy is wasted through electronics left plugged in, and the resulting vampire energy. Put a stop to it by using one of a number of cool, smart energy strips, which will turn off vampire energy when the electronics are not in use.
* Use a Humidifier & Lower Your Heat: Keeping humidity levels up during the winter is not only good for your health, but also for your air and furniture. It also helps keep the ambient air temperature feeling warmer than dry air, which means you can turn your thermostat down. If your HVAC system doesn't have a humidifier built-in, then you can get an inexpensive and portable humidifier to use during dry conditions.
|
output
| 1 | 360 |
Is there any way to exit ```less``` without clearing the screen?
|
instruction
| 0 | 361 |
This is actually a function of the terminal emulator you are using (xterm, gnome-terminal, konsole, screen). An alternate screen, or altscreen, gets launched when programs such as ```less``` or ```vim``` are invoked. This altscreen has no history buffer and exits immediately when you quit the program, switching back to the original screen which restores the previous window content history and placement.
You can prevent ```less``` from launch in an altscreen by passing the argument "-X".
```less -X /path/to/some/file```
You can also pass "-X" as an environment variable. So if you are using ```bash```, place this in ```~/.bashrc```:
```export LESS="-X"
```
However, this disbles the termcap (terminal capability) initialization and deinitialization, so other views when you use ```less``` may appear off.
Another option would be to use ```screen``` and set the option ```altscreen off``` in your ```~/.screenrc```. ```less``` will not clear the screen and should preserve color formatting. Presumably ```tmux``` will have the same option.
|
output
| 1 | 361 |
How can I do 'insert if not exists' in MySQL?
|
instruction
| 0 | 362 |
In MySQL, ```ON DUPLICATE KEY UPDATE``` or ```INSERT IGNORE INTO table``` can be viable solutions.
* An example of ```ON DUPLICATE KEY UPDATE``` update based on mysql.com:
```
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;
```
* An example of INSERT IGNORE based on mysql.com:
```
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
```
Or:
```
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
```
Or:
```
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
```
|
output
| 1 | 362 |
What does ```class``` do in Ruby?
|
instruction
| 0 | 363 |
First, the ```class``` syntax opens up ```foo```'s singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.
```a = 'foo'
class << a
def inspect
'"bar"'
end
end
a.inspect # => "bar"
a = 'foo' # new object, new singleton class
a.inspect # => "foo"
```
Now, to answer the question: ```class``` opens up ```self```'s singleton class, so that methods can be redefined for the current ```self``` object (which inside a class or module body is the class or module itself). Usually, this is used to define class/module ("static") methods:
```class String
class << self
def value_of obj
obj.to_s
end
end
end
String.value_of 42 # => "42"
```
This can also be written as a shorthand:
```class String
def self.value_of obj
obj.to_s
end
end
```
Or even shorter:
```def String.value_of obj
obj.to_s
end
```
When inside a function definition, ```self``` refers to the object the function is being called with. In this case, ```class``` opens the singleton class for that object; one use of that is to implement a poor man's state machine:
```class StateMachineExample
def process obj
process_hook obj
end
private
def process_state_1 obj
# ...
class << self
alias process_hook process_state_2
end
end
def process_state_2 obj
# ...
class << self
alias process_hook process_state_1
end
end
# Set up initial state
alias process_hook process_state_1
end
```
So, in the example above, each instance of ```StateMachineExample``` has ```process_hook``` aliased to ```process_state_1```, but note how in the latter, it can redefine ```process_hook``` (for ```self``` only, not affecting other ```StateMachineExample``` instances) to ```process_state_2```. So, each time a caller calls the ```process``` method (which calls the redefinable ```process_hook```), the behaviour changes depending on what state it's in.
|
output
| 1 | 363 |
"I have a problem where i'm initialising a variable on the scope in a controller. Then it gets changed in another controller when a user logs in. This variable is used to control things such as the navigation bar and restricts access to parts of the site depending on the type of user, so its important that it holds its value. The problem with it is that the controller that initialises it, gets called again by angular some how and then resets the variable back to its initial value.
I assume this is not the correct way of declaring and initialising global variables, well its not really global, so my question is what is the correct way and is there any good examples around that work with the current version of angular?"
|
instruction
| 0 | 364 |
You've got basically 2 options for "global" variables:
* use a ```$rootScope```
* use a service
```$rootScope``` is a parent of all scopes so values exposed there will be visible in all templates and controllers. Using the ```$rootScope``` is very easy as you can simply inject it into any controller and change values in this scope. It might be convenient but has all the problems of global variables.
Services are singletons that you can inject to any controller and expose their values in a controller's scope. Services, being singletons are still 'global' but you've got far better control over where those are used and exposed.
Using services is a bit more complex, but not that much, here is an example:
```
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
return {
name : 'anonymous'
};
});
```
and then in a controller:
```
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
}
```
|
output
| 1 | 364 |
How do I initialize a TypeScript Object with a JSON-Object?
|
instruction
| 0 | 365 |
This question is quite broad, here are two solutions.
### Solution 1: Helper Method
Here's an example of using a Helper Method that you could change to fit your needs:
```class SerializationHelper {
static toInstance(obj: T, json: string) : T {
var jsonObj = JSON.parse(json);
if (typeof obj["fromJSON"] === "function") {
obj["fromJSON"](jsonObj);
}
else {
for (var propName in jsonObj) {
obj[propName] = jsonObj[propName]
}
}
return obj;
}
}
```
Then use it:
```var json = '{"name": "John Doe"}',
foo = SerializationHelper.toInstance(new Foo(), json);
foo.GetName() === "John Doe";
```
* Advanced Deserialization
This could also allow for some custom deserialization by adding your own ```fromJSON``` method to the class (this works well with how ```JSON.stringify``` already uses the ```toJSON``` method, as shown below):
```interface IFooSerialized {
nameSomethingElse: string;
}
class Foo {
name: string;
GetName(): string { return this.name }
toJSON(): IFooSerialized {
return {
nameSomethingElse: this.name
};
}
fromJSON(obj: IFooSerialized) {
this.name = obj.nameSomethingElse;
}
}
```
Then use it:
```var foo1 = new Foo();
foo1.name = "John Doe";
var json = JSON.stringify(foo1);
json === '{"nameSomethingElse":"John Doe"}';
var foo2 = SerializationHelper.toInstance(new Foo(), json);
foo2.GetName() === "John Doe";
```
### Solution 2: Base Class
Another way you could do this is by creating your own base class:
```class Serializable {
fillFromJSON(json: string) {
var jsonObj = JSON.parse(json);
for (var propName in jsonObj) {
this[propName] = jsonObj[propName]
}
}
}
class Foo extends Serializable {
name: string;
GetName(): string { return this.name }
}
```
Then use it:
```var foo = new Foo();
foo.fillFromJSON(json);
```
There are too many different ways to implement a custom deserialization using a base class, and ultimately it depends on how your own choice.
|
output
| 1 | 365 |
Why is digital photography so expensive?
|
instruction
| 0 | 366 |
Digital photography is not expensive but buying into it is.
With film photography camera and lenses were a moderate investment but these lasted quite long. Even a battery in a film camera would last several years. Cameras and lenses were mechanical and much simpler than today's models. This made them require less expertise to manufacture and also made them incredibly sturdy. A lifespan of a decade for a camera and several decades for lenses was not uncommon.
However, the real cost of film photography is film and development. Each roll of film costs several dollars and gives up to 36 images. Specialized rolls were more expensive and had fewer exposures. Then, if you did not do development yourself, you had to pay for development. Also prints. Even if you did your own, chemicals and papers were recurring costs. And there was the added expensive of creating a wet darkroom. In the end, the hobby was quite costly.
With digital photography, you pay nearly all costs up-front and it comes out much cheaper for anyone who is into the art and shoots regularly. A mid-range DSLR with good lens and memory can easily be obtained for less than $2500. Many entry level ones exist for under $1000. If you were to shoot 10,000 frames before both your camera and lens dies, it would cost you between 2.5¢ to 10¢ per frame. It is far far less than even just the film for each frame. Still most cameras have shutters rated to at least 100,000 frames and lenses last much longer than cameras. Even if you only captured 1000 images, you would have a better deal than with film photography. All digital cameras come with rechargeable batteries, good for 500-1000 shots-per-charge (for DSLRs) and can be charged at least 50-100 times before needing to be replaced. That means you actually will not use up the battery before you have taken full advantage of the better value of digital photography.
Market conditions are forcing the price of digital photography to increase. The loss of market share of compact and ultra-compact digital cameras to cellphones forced manufacturers to discontinue such products and concentrate on higher-end offering. While the number of unit sales of digital cameras has been declining, the average price is going up to compensate for reduced revenue. This trend is expected to continue for a while.
|
output
| 1 | 366 |
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:
```$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
```
That's because the user can input something like ```value'); DROP TABLE table;--```, and the query becomes:
```INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
```
What can be done to prevent this from happening?
|
instruction
| 0 | 367 |
The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
1. Using PDO (for any supported database driver):
```
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute([ 'name' => $name ]);
foreach ($stmt as $row) {
// Do something with $row
}
```
2. Using MySQLi (for MySQL):
Since PHP 8.2+ we can make use of execute_query() which prepares, binds parameters, and executes SQL statement in one method:
```
$result = $dbConnection->execute_query('SELECT * FROM employees WHERE name = ?', [$name]);
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
```
Up to PHP8.1:
```
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
```
If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.
|
output
| 1 | 367 |
I want to be able to output the current loop iteration to my template.
According to the docs, there is a ```loop.counter``` variable that I am trying to use:
```
{% for user in userlist %}
*
{{ user }} {{loop.counter}}
{% if loop.counter == 1 %}
This is the First user
{% endif %}
{% endfor %}
```
But is being outputed to my template. What is the correct syntax?
|
instruction
| 0 | 368 |
The counter variable inside the loop is called loop.index in Jinja2.
```
>>> from jinja2 import Template
>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4
```
In addition to `loop.index`, there is also
* `loop.index0` (index starting at `0`)
* `loop.revindex` (reverse index; ending at `1`)
* `loop.revindex0` (reverse index; ending at `0`)
etc.
|
output
| 1 | 368 |
Are the players on the same team as the DM?
|
instruction
| 0 | 369 |
The GM isn't on a team, they’re the referee.
The way Pathfinder, D&D, and similar games work is that there are one or more player characters (the "party") that are controlled by the players.
The GM (DM, in D&D) usually doesn't run a player character (PC), but they are responsible for representing all aspects of the world, all the non-player characters (NPCs) and monsters and stuff, and adjudicating the rules.
So the GM may be controlling a character or creature that is friendly to the PCs, or a character or creature that is hostile to the PCs, or both at once! The GM is the orcs you fight and the friendly cleric that heals you and the rain that falls on you.
GMs aren't supposed to be hostile to you in general; they are generally taught to give the players a fun challenge. It's no good to be "against" the players, because you can always kill PCs just by saying "rocks fall, everyone dies!" The GM is on your team inasmuch as they want everyone to have fun. Because their role is running monsters and the other stuff that you fight, they are often in opposition to you tactically, as they are responsible for the "other team" as part of their job. Some new GMs do get confused by this and decide it's them against the party, but that ends up being a problem that has to be solved by them wising up or their players leaving.
The context of your question isn't clear, so I'll add a note that might be relevant - some GMs, especially new ones, do run a PC of their own that's part of the party, these are referred to as GMPCs (or DMPCs). This is generally frowned upon because of the conflict of interest inherent in doing it, but it happens. That GMPC may be on your side, on your side most of the time, betray you, have other plans - just like any other person in the game world might.
|
output
| 1 | 369 |
C++ vs. The Arduino Language?
|
instruction
| 0 | 370 |
If you have previous programming experience and you are aware of concepts as OOP, it is better to go for C/C++. The arduino language is really great for beginners, but have some limitations (e.g. you must have all your files in the same folder). And it is basically a simplification of C/C++ (you can practically copy&paste arduino code to a C/C++ file, and it will work). Also it makes sense that you can go and use a full well known IDE such as Eclipse.
Initially it is required a bit more of setup and configuration of your dev environment, but IMHO it is worth it for programmers with experience in any other language.
In any case, it won't harm you to start using the arduino language and the arduino IDE for a few days to get familiar with the arduino hardware and then move to C/C++ with Eclipse for really developing your project.
|
output
| 1 | 370 |
How can I adapt Ubuntu to a high resolution display?
I have a display with 3200x1600px on only 11'' and everything looks really tiny.
|
instruction
| 0 | 371 |
There are some steps to take:
1. System wide Menu and titlebar scaling
Starting with Ubuntu 14.04 we have an option that helps a bit:
Scaling Support
open the System Settings (here in english:)
```LANG=c unity-control-center
```
Go to "Displays" and set the "Scale for menu and title bars".
Since Ubuntu 17.10 the scaling can be set in
```LANG=c gnome-control-center
```
Go to ```Settings > Devices > Displays``` there
see also: How to find and change the screen DPI?
2. Universal Access
Go to "Universal Access" (```unity-control-center universal-access```) and select "Large Text".
Note: not all applications handle this correctly, some will not reserve the extra space, so some UI elements are not accessible with this option!
3.Increase unity dock size
In ```unity-control-center```->```Appearance```->```Look``` at the botom, you can adjust the size.
4. Adapt Firefox
see: Adjust Firefox and Thunderbird to a High DPI touchscreen display (retina)
(or use Chrome, which works fine since Version 41.0.2272.76 Ubuntu 14.10, though Chrome will need to be restarted to take effect)
5. Increase font in Pidgin
There is a plugin you can install:
```sudo apt-get install pidgin-extprefs
```
Then you can increase the font in Plugins->Extended Prefs
6. Create starter for applications that still don't scale
Some applications still don't obey the global scaling (mainly java) for those few applications you can create a starter to only Fix scaling of java-based applications for a high DPI screen
Note: In older Ubuntu versions, with unity-tweak-util in the section "Fonts" you can set the "Text Scaling Factor" to 2.0. This will scale the fonts in most applications to double size.
|
output
| 1 | 371 |
Say I want to make a file:
```filename = "/foo/bar/baz.txt"
with open(filename, "w") as f:
f.write("FOOBAR")
```
This gives an ```IOError```, since ```/foo/bar``` does not exist.
What is the most pythonic way to generate those directories automatically? Is it necessary for me explicitly call ```os.path.exists``` and ```os.mkdir``` on every single one (i.e., /foo, then /foo/bar)?
|
instruction
| 0 | 372 |
In Python 3.2+, using the APIs requested by the OP, you can elegantly do the following:
```
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
```
With the Pathlib module (introduced in Python 3.4), there is an alternate syntax (thanks David258):
```from pathlib import Path
output_file = Path("/foo/bar/baz.txt")
output_file.parent.mkdir(exist_ok=True, parents=True)
output_file.write_text("FOOBAR")
```
In older python, there is a less elegant way:
The ```os.makedirs``` function does this. Try the following:
```import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
```
The reason to add the ```try-except``` block is to handle the case when the directory was created between the ```os.path.exists``` and the ```os.makedirs``` calls, so that to protect us from race conditions.
|
output
| 1 | 372 |
Assume that Jane Doe has published a paper in 2010 where she has developed a model or a theorem or a similar result, let’s say, that it relates to growth.
Now assume that Jane Doe is writing another paper in 2015, where she refers to the model/theorem from her paper in 2010.
Is it acceptable for Jane to write something like the following?
Doe’s growth model (2010), implies that ...
Doe’s growth theorem (2010) implies that ...
The Doe growth model (2010) implies ...
|
instruction
| 0 | 373 |
This is, unfortunately, a case where English grammar can be tricky and exactly how you phrase things is going to matter.
It is often seen a presumptuous to name something after yourself: "Newton's Laws" and "Hawking radiation" and "Rayleigh scattering" are retrospective judgements of significance by the community. Claiming a similar name is an assertion in advance that your work will be at a similar level of significance.
The problem, then, is that if you say "Doe's growth model", it is ambiguous whether that is intended to be a construction like "Hawking radiation" or whether it just means "the growth model that happens to have been developed by Doe."
This potential problem can be avoided by rephrasing to avoid the parallel construction: "the growth model by Doe et al (2010)", or better yet, "the growth model presented in (Doe, 2010)." The point here is that the significant item under discussion is the growth model, not Doe, and the sentence should be phrased to make that as clear as possible.
Finally, note that these sorts of phrasings can work both for double blind review and for review where the authors' identities are known: even when the identity of the author is known, the important thing should be the relationship between the work, not the fraction of authors that are shared between two papers (unless you are specifically trying to talk about independent co-discovery).
|
output
| 1 | 373 |
I've been with my current employer for about a year now. Due to the way the company is setup, I'm the only one with knowledge on a process that is quite important to the company. The company is going through some restructuring, and has been letting people go. As the newest guy in my department, I'm obviously concerned.
My question though, is if I am let go, am I obligated to spend my time teaching someone else this process that only I know about?
|
instruction
| 0 | 374 |
As long as you're still getting paid, you're obligated to do whatever your employer tells you to do during your official work hours (if it's within the context of your job and legal).
Refusing to do so would, at best, burn bridges and, at worst, result in them instantly terminating your contract and no longer paying you or potentially get you into legal trouble.
If they're no longer paying you, you're not obligated to do anything. You're also not obligated to work overtime (paid or not).
If you're asked to work overtime or do unpaid work, it would be reasonable to decline or (if it's a non-trivial amount of hours) request additional payment. Although this is not to say they would think it's reasonable.
Your contract may, of course, create different obligations, and you should adhere to those instead of what's written here. Any relevant notice periods should also be specified there, in some other legal document or in some regional employment law.
If you want to leave a good impression and avoid burning bridges, it would be advisable to try to pass on knowledge (through teaching or documentation) even if you're not specifically asked to do so. You might even want to (gently) push back on other tasks and emphasise the importance of passing on your knowledge. Although some won't be able to see the importance of transferring what you know.
|
output
| 1 | 374 |
Bash test: what does "=~" do?
|
instruction
| 0 | 375 |
The ```~``` is actually part of the operator ```=~``` which performs a regular expression match of the string to its left to the extended regular expression on its right.
```[[ "string" =~ pattern ]]
```
Note that the string should be quoted, and that the regular expression shouldn't be quoted.
A similar operator is used in the Perl programming language.
The regular expressions understood by ```bash``` are the same as those that GNU ```grep``` understands with the ```-E``` flag, i.e. the extended set of regular expressions.
Somewhat off-topic, but good to know:
When matching against a regular expression containing capturing groups, the part of the string captured by each group is available in the ```BASH_REMATCH``` array. The zeroth/first entry in this array corresponds to ```&``` in the replacement pattern of ```sed```'s substitution command (or ```$&``` in Perl), which is the bit of the string that matches the pattern, while the entries at index 1 and onwards corresponds to ```\1```, ```\2```, etc. in a ```sed``` replacement pattern (or ```$1```, ```$2``` etc. in Perl), i.e. the bits matched by each parenthesis.
Example:
```string=$( date +%T )
if [[ "$string" =~ ^([0-9][0-9]):([0-9][0-9]):([0-9][0-9])$ ]]; then
printf 'Got %s, %s and %s\n' \
"${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}"
fi
```
This may output
```Got 09, 19 and 14
```
if the current time happens to be 09:19:14.
The ```REMATCH``` bit of the ```BASH_REMATCH``` array name comes from "Regular Expression Match", i.e. "RE-Match".
In non-```bash``` Bourne-like shells, one may also use ```expr``` for limited regular expression matching (using only basic regular expressions).
A small example:
```$ string="hello 123 world"
$ expr "$string" : ".*[^0-9]\([0-9][0-9]*\)"
123
```
|
output
| 1 | 375 |
If I have a Bash script like:
```#!/bin/bash
f() {
# echo function name, "f" in this case
}
```
Is there any way to do this? This could be used in help messages such as
```printf "Usage: %s: blah blah blah \n" $(basename $0) >&2;
```
Only in this case what I wanted is not ```$0```, which is the file name of the script.
|
instruction
| 0 | 376 |
From the Bash Reference Manual:
FUNCNAME
An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.
This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information.
When bash arrays are accessed without an index the first element of the array will be returned, so ```$FUNCNAME``` will work in simple cases to provide the name of the immediately current function, but it also contains all other functions in the call stack. For example:
```# in a file "foobar"
function foo {
echo foo
echo "In function $FUNCNAME: FUNCNAME=${FUNCNAME[*]}" >&2
}
function foobar {
echo "$(foo)bar"
echo "In function $FUNCNAME: FUNCNAME=${FUNCNAME[*]}" >&2
}
foobar
```
Will output:
```$ bash foobar
In function foo: FUNCNAME=foo foobar main
foobar
In function foobar: FUNCNAME=foobar main
```
|
output
| 1 | 376 |
I know that the public practice of any religion other than Wahabbi Islam is strictly forbidden in Saudi Arabia, and there would be no places of worship. I also know that the morality police raided a a hotel several years ago where Mass was being celebrated, and arrested the priest and the acolytes.
But I am also told that many expats from countries with large Catholic communities such as the Philippines, India, and Sri Lanka do gather in private homes for worship. Is this officially tolerated, or would I endanger the hosts or other participants by asking about them?
|
instruction
| 0 | 377 |
Essentially, there is no religious freedom in Saudi Arabia, and nobody is likely to openly change - indeed:
> conversion from Islam to another religion is considered apostasy and punishable by death.
All citizens are considered Muslim by the state.
In 2008, the Vatican tried to get a Catholic Church built in Saudi Arabia, and had discussions with the Saudi government, but the result was that it was not permitted.
So that brings us to the Christians (including Catholics) that DO exist in the country. There are considered to be more than a million Roman Catholics in the country, as well as from many others.
> Saudi Arabia allows Christians to enter the country as foreign workers for temporary work, but does not allow them to practice their faith openly. Because of that Christians generally only worship in secret within private homes. Items and articles belonging to religions other than Islam are prohibited. These include Bibles, crucifixes, statues, carvings, items with religious symbols, and others.
So, to your question about whether this secret practice is allowed or tolerated? Not so much. They have an entire 'government' organisation - The Saudi Arabian Mutaween (Arabic: مطوعين), or Committee for the Propagation of Virtue and the Prevention of Vice (i.e., the religious police) which prohibits the practice of any religion other than Islam.
The government also doesn't let clergy of other religions into the country for conducting religious services (naturally this means no Christian baptisms, weddings etc by official clergy legally).
And if they find someone practising in their homes? International Christian Concern (ICC) protested what it reported as the 2001 detention of 11 Christians in Saudi Arabia, for practicing their religion in their homes. In June 2004, ICC reported on what it termed a "pogrom-like" crackdown by Saudi police on Christians after media reports of Koran desecration in Guantanamo Bay.
|
output
| 1 | 377 |
Is there a way to achieve protections similar to "Copyleft" under the patent system?
|
instruction
| 0 | 378 |
"Copyleft" is a specific application of copyright law (restricting the license to use copyrighted material by requiring that those obtaining it must also redistribute it for free / under specified terms).
Any work under "copyleft" is protected by copyright law (thanks to The Berne Convention copyright is "automatic" in most of the world), and those copyright protections are what allow the author to dictate the terms under which the copyrighted work is used.
As far as I'm aware there is no Berne Convention equivalent in patent law: in order for you to have patent protection and the ability to dictate how your invention is used (by licensing the patent for it to impose Copyleft-style requirements on those using it) you must file for (and receive) a patent.
Note that the sort of "keeping information free" protection the Copyleft folks would seek is inherent in US Patent Law and most other patent systems -- it is known as Prior Art.
In its most simplistic definition (cribbed from Wikipedia):
> Prior art …, in most systems of patent law, constitutes all information that has been made available to the public in any form before a given date that might be relevant to a patent's claims of originality. If an invention has been described in the prior art, a patent on that invention is not valid.
So if you have designed and publicly released something patentable (and can document the date of such a release to the satisfaction of the patent authorities) you can seek to invalidate any subsequent patent claims on the grounds that prior art exists.
|
output
| 1 | 378 |
In monopoly, can an opponent put a property up for auction at a higher price than I have in cash?
|
instruction
| 0 | 379 |
This is definitely allowed, and a good tactic to leverage a cash advantage.
There is no minimum or maximum price for an auction. The rules state:
Bidding may start at any price.
Monopoly auctions do not have "the bidding will start at $10". They just have "bidding is open". Once the auction begins, a bid by any player sets the minimum price for the auction at that bid. Your opponent could easily bid $10 on the property, forcing you to either let them have it for $10 or bid more than you have in cash. You could bid first, say starting the bid at $5, but that doesn't meaningfully change the situation, as they can just respond by out-bidding you at $10.
You may bid more money than you have in cash, but you are still obligated to pay it if you win the auction. This may be a reasonable play if you can afford it by mortgaging property and/or selling houses, especially to drive up the price for your opponent. But be careful not to bid more than you can pay after mortgages and sales, as if you win the auction and can't pay your bid, you go bankrupt. In particular, if you bid more than you can afford, you opponents can all just let you win the bid, at which point you go bankrupt and the property you just bought would go up for auction again (in addition to all your other properties).
|
output
| 1 | 379 |
What is the purpose of having a countdown during a rocket launch?
|
instruction
| 0 | 380 |
There is a window of opportunity for a launch to occur, known as a launch window. This certainly occurs when trying to get somewhere such as the International Space Station, but even earth orbiting satellites have a window of time where the rocket can meet its performance.
Bottom line is, the exact time of launch is very important, and a complex sequence of events have to happen in just the right order to make it happen. SpaceFlightNow provided a generic countdown timeline for the Falcon 9, I'll re-post a few of the highlights. Some of these things are done to keep the batteries topped off till the last minute. You don't want to put the fuel in until the last minute, to save it (Most rocket fuel is cryogenic). When the rocket has its fuel loaded, you want to keep non-essential personnel away from it, making it so any tasks they need to do is put off until the end. You don't want to arm the system to launch until you are completely ready, thus, it only happens right before. There are many more such examples of why things are done in a particular order, but hopefully this will give you a sense.
```L-13:30:00 Dragon Power Up
L-7:30:00 Launch Vehicle Power Up
L-3:50:00 Liquid Oxygen Loading
L-3:40:00 Rocket Propellant 1 Loading
L-1:00:00 Weather Briefing
T-0:09:40 Verify that Terminal Countdown has started
T-0:09:30 Merlin 1C: Lox Bleeder Valves Open
T-0:07:00 Dragon to Internal Power
T-0:04:46 Stage 1 & Stage 2 Auto Sequence starts
T-0:04:30 Transfer to Internal Power
T-0:04:10 Vehicle Release Auto Sequence
T-0:03:40 TEA-TEB Ignition System Activation
T-0:03:25 Flight Termination System to Internal Power
T-0:03:11 Flight Termination System Armed
T-0:03:02 LOX Topping Termination
T-0:03:00 Second Stage Thrust Vector Actuator Test
T-0:02:00 Range Verification
T-0:01:30 Final Engine Chilldown, Pre-Valves/Bleeders Open
T-0:01:00 Flight Computer to start-up
T-0:00:50 First Stage Thrust Vector Actuator Test
T-0:00:40 Propellant Tank Pressurization
T-0:00:20 All Tanks at Flight Pressure
T-0:00:15 Arm Pyrotechnics
T-0:00:03 Merlin Engine Ignition
T-0:00:00 LIFTOFF
```
|
output
| 1 | 380 |
How does one attack a two-time pad (i.e. one time pad with key reuse)?
I am new to cryptography and my problem is with two time pad attacks on OTP.
The problem I had in my course was that I have 10 ciphertexts encrypted with the same key $K$. I am then given another ciphertext that I should decrypt.
I know that XOR-ing two ciphers gives me the XOR of their original messages.
My question is what is the correct thing to do after that?
I tried to take 3 ciphertexts $C_1, C_2$ and $C_3$.
Then get $S_1 = C_1 \oplus C_2 \oplus $```' '```, also get $S_2 = C_1 \oplus C_3 \oplus$ ```' '```.
After that I compared all corresponding characters in $S_1$ and $S_2$,
and if $S_1[i] = S_2[i]$ then I calculate $S_1[i] \oplus C_2[i]$ to get $K[i]$.
I tried this on paper before coding and it worked, but I might be missing something.
Is this the right approach? Why does it work?
|
instruction
| 0 | 381 |
The classical answer to "what is the correct thing to do after you have the XOR of the two original messages" is crib-dragging.
That is, you take a guess of a common phrase that may appear in one of the plaintexts (the classical example against ASCII english is the 5 letter " the "), and exclusive-or that against the XOR of the two original messages in various locations. If one of the plaintexts had the text of the crib (" the " in our example), then the result of the exclusive-or is what the other plaintext had in that position; if neither plaintext had that, it's likely that the result of the exclusive-or is just gibberish. And, once you have a plausible short section, you can extend it (for example, if you know that one of the plaintexts is " na**", you can go through the dictionary of all words that start with "na", use those as cribs, and see which makes the other plaintext make sense).
In addition, you can often deduce things directly from the bit pattern. For example, if the messages are in ASCII, then one thing to note that bit 6 of letters is set, but bit 6 of spaces, numbers and (most) punctuation is clear; because spaces are far more common than numbers and punctuation, then that will give you a good guess of where spaces occur in the texts (albeit without telling you which message a specific space appears in).
Now, if you have 11 messages all encrypted with the same pad (an "11-time pad"), things get even easier. Obviously, you can grab a crib across one message, and check it against the other 10; if it makes all 10 make sense, then it is almost certainly accurate. Even better, by using the observation that you can distinguish spaces from letters (again, by comparing bit 6), you can find where all the spaces appear in the messages; these all act like 1 character cribs, probably revealing virtually all the text of all the messages.
|
output
| 1 | 381 |
I have a small home automation lab (that I keep saying I'll expand, but haven't). In this setup, I have a control system to control lights (utilizing the x10 protocol), blinds, a Nest thermostat and two web cams.
With the recent record setting DDoS attacks utilizing unsecured IoT devices, I'd like to secure my small setup a bit.
What can a home user do to secure their network while still maintaining the "connect from anywhere" aspect that is a big part of the marketing?
|
instruction
| 0 | 382 |
The absolute most common issue with IoT devices is default passwords. So change all the passwords. Pick a unique, random password for every device and write it down on paper (paper is safe from remote attackers and hard drive failures). 12 random (i.e. computer-generated) lowercase letters represent a good compromise between security and being hard to type. Each device should have a different password so that breaking one doesn't let the attacker break all of them. Enter the passwords in a password manager and use that password manager in the computers you use to control the devices.
If the device has different authorization channels, for example an administration password and a day-to-day usage password, use different passwords for both and only record the administration password on selected devices.
The second generic security measure is to ensure that all your devices are behind a firewall or at least a NAT device. A typical home router is sufficient, but you should turn off UPnP which can allow inadvertent back channels from the outside. The goal is to ensures that there's no direct way to connect from the Internet to the device. Connections should always go through a gateway that itself requires authentication to cross, and that you keep patched with any security updates.
You should also apply security updates on all the device if they exist at all, which can be a problem.
|
output
| 1 | 382 |
What are objective advantages or disadvantages of using the markup language LaTeX instead of a WYSIWYG word processor like MS Word or LibreOffice Writer?
Please use objective arguments.
|
instruction
| 0 | 383 |
LaTeX is better at:
* Dealing with mathematical notation. Layout and entry are generally easier using LaTeX than some other sort of equation editor.
* Consistent handling of intra-document references and bibliography. As of a couple of years ago the major WYSIWYG editors still had problems with re-numbering cross-references and bibliography items. This is never a problem with BibTeX or LaTeX.
* Separation of content and style. In principle this means that you can write your document without caring how it is formatted, and at the end of the day wrap it in the style-file provided by the journal publisher before submission to conform to the house style. In practice some of the journal publishers demand special formatting commands that partially moots this process. Furthermore recent versions of Word and LibreOffice Writer, when properly used, should be able to keep track of various levels of section heading separate from the body text, and apply uniform styling to each level. The gap is somewhat closing.
* Tables and illustrations. With PSTricks or TikZ, one can produce high quality illustrations within the document (though the learning curve is a bit steep there). And I've found LaTeX to be better at preparing complex tables.
WYSIWYG (especially Word and Writer) is better at:
* Collaborative editing. Without using an online site for collaborative LaTeX editing (such as ShareLaTeX), working collaboratively on a LaTeX file ideally requires some sort of separate revision control software. Word and Writer have very good comments/annotations and edit-tracking features. When a large number of authors are commenting on the writing of one file, this can be very useful.
* Spell check. Admittedly most text editors one uses to edit TeX files also do spell check. But this is generally conveniently built into WYSIWYG editors.
* Compatibility. Unless you work in mathematics, computer science, or physics (and sometimes even if you work in those fields), it is more likely that your collaborators will know what to do with a Word or Writer file than a LaTeX file.
* Minimum barrier to entry. If you just care about getting the ideas down on paper, you can use a WYSIWYG editor just like a typewriter. Sure, it may be tedious to fix the formatting later on, compared to LaTeX where one need to first figure out how to setup a bare-minimum file before using, it may be an attractive point.
A wash:
* Most journals provide templates for both Word and LaTeX, so there's no real winner there.
Suggestion: if you want to convince someone to start using LaTeX, start them out first in one of the WYSIWYG environments designed for LaTeX first (for example LyX). This will help somewhat to ameliorate the scary entry barrier.
|
output
| 1 | 383 |
Could Gandalf not have made his own One Ring?
|
instruction
| 0 | 384 |
Possibly
In the foreword to The Lord of the Rings, Tolkien observes:
Saruman, failing to get possession of the Ring, would in the confusion and treacheries of the time have found in Mordor the missing links in his own researches into Ring-lore, and before long he would have made a Great Ring of his own with which to challenge the self-styled Ruler of Middle-earth.
Tolkien therefore definitely conceives of Saruman as being capable of making a Ring, and therefore Gandalf would presumably have been likewise capable.
However, what we can also take from that statement is that making a Ring is not a simple task; there is some "lore" involved, and we know from elsewhere that Saruman had made especial study of the Rings of Power, but yet Tolkien states that even he would have required knowledge found only in Mordor to complete his own work.
So, to summarize:
* Yes, but,
* It's neither quick nor easy, because,
* There is considerable "lore" involved, and,
* It requires hundreds or even thousands of years of dedicated study to get to a "Saruman-level" of "lore", and,
* Even then there will be missing knowledge which may only be found in Mordor.
* So for all practical purposes it's actually "No".
|
output
| 1 | 384 |
It’s the year 2018, and you live in the good ol’ North American landmass. The fascist landmass. By this year, the dystopian N.A.F party controls all of the landmass and secret police prowl the streets armed with automatic rifles. Protest the rules and NAF makes you disappear -- permanently.
Onto the subject
As you’ve seen in a lot of movies and whatnot, dystopian governments like to make people fit into a mandatory dress code. 1984 did it, a lot of other dystopian media did it, and so on. I plan to do the same, but I want to make my dystopian government a logical one, that only does what’s necessary to keep power. What is a logical reason why mandatory dress codes would be forced upon citizens?
|
instruction
| 0 | 385 |
**Control the Supply**
The citizens of your dystopia work in a government-controlled factory. They shop in a government-controlled shop with government-controlled prices. What does the shop have in stock? The products of more government-controlled factories, of course.
It is not illegal to wear non-standard clothes. It is illegal to buy or sell them (that would be black marketeering) and it is usually illegal to make them (that would be diversion of government-supplied raw materials). One might "repair" government-pattern clothes into non-standard shapes, e.g. cutting trousers short or making a skirt out of an old bedsheet.
Few people make their own clothing. A sure sign they have too much time on their hands, why don't they join in a government-sponsored community activity instead?
Of course there is "special store No. 0815" which is open to senior regime officials and their families. These officials work so long hours in their selfless service of the people that they cannot possibly stand in the waiting line of a normal store. The special store opens by appointment, e.g. right between the parade for the Dear Leader's birthday and the official reception. And it stocks suitable clothes for that reception.
|
output
| 1 | 385 |
When would one use an impact driver versus a regular drill?
|
instruction
| 0 | 386 |
Drills and impact drivers are similar in that they're both rotating power tools and they have some overlap in usage, but they work differently and have different strengths.
Drills apply a constant torque and tend to have good control across a range of speeds and clutch settings. They're good for work that requires care or precision, like drilling a hole or driving a a smaller screw.
Impact drivers provide much higher torque but in rapid bursts–very much like a hammer provides bursts of linear force.
This makes them good for heavy-duty jobs like driving long lag bolts (you can even take the lug nuts off your car wheels with most impact drivers), but the banging action makes them a little bit difficult to control. They're also not good for driving into something very soft–between the hammer strikes there's no torque applied and the bit can actually rotate backwards. You can see this by holding the chuck with your hands while the driver is on; you'll feel the pulsing of the strikes but chuck won't actually rotate. Finally, some impact drivers don't have a clutch, which means you need to be very careful if you're driving something that could be over-tightened or broken by the high torque.
Besides the higher torque, impact drivers have another huge advantage in that you don't have to hold them tightly to provide the torque. The momentum of the rotating striker inside is what provides the rotation force, so even when you're driving something very tough it's quite easy to hold the tool. Drills on the other hand provide a constant torque and require the user to provide the reaction and prevent the tool from spinning.
If you have to pick a single all-purpose tool for general DIY use, a drill is much easier to control and is useful in a wider range of situations.
|
output
| 1 | 386 |
Alternative to Windows Snipping Tool for Mac OSX
|
instruction
| 0 | 387 |
Mac OS has a built-in snipping tool similar to the one in Windows:
* ⌘+⇧+3 captures the whole screen
* ⌘+⇧+4 captures a custom rectangle
(click and drag over the screen region you want to capture)
* ⌘+⇧+4 then space captures a specific window (move the mouse cursor over the desired window, then click)
Press esc to cancel.
Screenshots are saved onto your Desktop and timestamped.
Holding control in addition to any of the sequences above causes the image to be copied instead of saved to the desktop.
By default the image format is png. However, you can change the format by typing in the Terminal:
```defaults write com.apple.screencapture type image_format
killall SystemUIServer
```
Where ```image_format``` is one of ```jpg```, ```tiff```, ```pdf```, ```png```, ```bmp``` or ```pict``` (among others). If you omit the second line, you will need to log out and in again for the change to take effect.
The settings for the shortcuts in the system preferences are located at:
System Preferences → Keyboard → Keyboard Shortcuts → Screen Shots
The MacOS X application that enables screenshots is called Grab. It is located at ```/Applications/Utilities/Grab.app```
|
output
| 1 | 387 |
What is the difference between kerning vs. letter spacing?
|
instruction
| 0 | 388 |
Any font has built-in spacing determined by the “side bearing” of each character. In metal type, the side bearing is the physical right or left edge of the individual piece of type that determines its spacing from the characters on either side. Digital fonts mimic this in the basic design process.
* “To kern” means to adjust the spacing between a pair of letters, numerals, punctuation, etc. (properly “glyphs”) so that their spacing looks correct. The letters AV, for example, have to overlap in any usual typeface, otherwise at least one of them ends up looking lost and bewildered. Their kerning is tightened to snug them up to one another. An italic f will collide with a following question or quote mark in some fonts, so the kerning must be opened up from the default spacing.
An ancient scribe could kern effortlessly with pen and ink, and if you read old manuscripts you'll see lots of places where a letter intrudes into the space of the one next to it. With metal type, it wasn't so easy. Kerning required cutting away some of the metal base, or table, of the character. The amount of time, skill and work involved is left as an exercise for readers whose minds are in need of a little boggling. The shapes of the letters in metal type intended for long passages of text such as books, or especially newspapers, were designed to minimize the amount of kerning that would be necessary.
Kerning tables built into a digital font assign preset kerning values to specific letter pairs, according to the designer's best estimate of how they should look. There can be a dozen or so pairs (or none!) in a cheapo font, thousands in a high-end one. No matter how thoroughly and well a kerning table is built, though, there will still be situations where some awkward combination requires that the kerning be loosened or tightened from the preset values of the glyphs.
* Letter spacing (often “tracking” in software applications) adjusts the spacing between all the glyphs in a piece of text. This can help to make a page look a little more open and inviting, for example, especially with a similarly open leading. Very large type, such as a big headline, almost always benefits from tightening the tracking. Tiny type, such as in captions or footnotes, is made more readable by opening the letter spacing a bit, especially if the paper is absorbent and will allow the ink to spread a little.
A final note: Use caution with both kerning and tracking. Tracking is very often wildly overdone, kerning is seldom done enough.
|
output
| 1 | 388 |
I read somewhere that C♯ and D♭ actually differ 41 by cents from each other. As far as I know, there should be 2 semitones between C and D. Moreover, C♯ is one semitone above C and D♭ is one semitone below D. Therefore, C♯ and D♭ should be equivalent. If so, how can C♯ and D♭ actually differ by 41 cents from each other?
|
instruction
| 0 | 389 |
When we talk about the exact frequencies of each pitch class, we have to know the temperament, and a reference pitch. For example, 12-tone equal temperament (12TET) with A4=440Hz is a standard in modern music. From those two parameters, we can extrapolate the exact frequency of every possible note.
12TET is nearly ubiquitous nowadays (at least in Western music), but it doesn't sound as clean as Just Intonation (JI). In essence, 12TET has made every key sound equally imperfect. JI creates a scale where the intervals in the primary chords are all very nice simple ratios, and so the chords ring out very cleanly, but it only works in that key. Important note: within a given JI tuning, each of the 12 pitch classes still has only one single frequency. There is no difference between C♯ and D♭ in, say, "Pythagorean tuning based on A, with A=440Hz".
But most music doesn't stay in one key. While a piano can't make pitch adjustments on the fly (which is why we've agreed to use 12TET for it), most instruments in an orchestra can. So when the piece is in A major, the orchestra will use JI and adjust C♯ to be a little flatter than it would be if using 12TET. But then if the piece modulates to F♯ minor, they'll start playing it slightly sharp.
When people say that C♯ is not the same as D♭, what they really mean (whether they realize it or not) is that context may make for different micro-adjustments. In C major, a C♯ might be the third of an A major chord, perhaps a secondary dominant of the ii chord, while D♭ might be the root of the Neapolitan chord. These would result in different tuning choices.
|
output
| 1 | 389 |
Not sure if this is a Mozilla-specific JS syntax, but I often found variables being declared this way, for example, in add-on SDK docs:
```var { Hotkey } = require("sdk/hotkeys");
```
and in various chrome Javascript (```let``` statement is being used in place of ```var```),
```let { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
```
I found it very confusing but I am not being able to find any documentation about both syntax, even on MDN.
|
instruction
| 0 | 390 |
They're both JavaScript 1.7 features. The first one is block-level variables:
```let``` allows you to declare variables, limiting its scope to the block, statement, or expression on which it is used. This is unlike the ```var``` keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
The second one is called destructuring:
Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
...
One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.
For those familiar with Python, it's similar to this syntax:
```>>> a, (b, c) = (1, (2, 3))
>>> a, b, c
(1, 2, 3)
```
The first code chunk is shorthand for:
```var {Hotkey: Hotkey} = require("sdk/hotkeys");
// Or
var Hotkey = require("sdk/hotkeys").Hotkey;
```
You can rewrite the second code chunk as:
```let Cc = Components.classes;
let Ci = Components.interfaces;
let Cr = Components.results;
let Cu = Components.utils;
```
|
output
| 1 | 390 |
When reading some documentation about the security of a product, I found that the vendor uses the SHA-2 of a password to encrypt data (AES-256), instead of using this password directly.
Are there any advantages of doing so?
An attacker is not going to crack the encrypted data using this SHA-2-as-a-password key but rather exhaust the password keyspace (if feasible) and try its hash. Therefore the only reason I can think of is that there is an extra computational step (the creation of the hash). I would have rather increased the password entropy if the point is to computationally complexify the attack.
|
instruction
| 0 | 391 |
It sounds like a primitive version of a key derivation function (KDF), in particular they probably could have avoided reinventing the wheel by using PBKDF2.
There are several reasons why you don't want to use the password directly as an AES key.
* To distribute the bits. The main property here is that a hash function's output is, statistically speaking, uniformly distributed. People tend to pick passwords that aren't fully random, in particular, most passwords would only contain characters you can type in a keyboard. When used as an encryption key, a non-statistically random key may expose weaknesses in the encryption function.
* To fit the keys to the encryption key length. Most passwords are going to be either longer or shorter than the key space of the encryption function. By hashing your password, the exact key length will be exactly the size of the input key of your encryption function. While the entropy of the derived key doesn't increase, this avoids the likelihood of exposing weakness in the encryption function if you just simply zero pad the password or worse truncate the password.
* To slow down key derivation decryption. Per your description, the software is only using a single SHA256 round, which is not much. But with proper password based KDF, like PBKDF2, there are usually tens of thousands or hundreds of thousands of rounds of the underlying hash function. This slows down computing the keys, increasing the effective strength of passwords without increasing its length.
* To keep the user's plain text password out of memory, thus preventing it from being accidentally dumped to disk during hibernation or crash dump. While this wouldn't protect the hash from being used to decrypt the data you're encrypting, it will prevent the password from being reused to decrypt other files (which presumably uses different salt) or being tried on your online accounts or other devices that you use.
|
output
| 1 | 391 |
My online friend is asking for money in order to visit my home country. Is this a legit request or a scam?
|
instruction
| 0 | 392 |
The first rule for every such question is simple:
If you have to ask, it's probably a scam
While we cannot possibly examine every possible situation from every angle, online scams are simply far too common to trust someone you have known only on the Internet or even what appears to be a real friend or relative, who may have had their email accounts hacked or might be simply being impersonated. So the basic advice is: don't send out your private details, don't pay for anything and don't send any money for any purposes.
Some common examples are:
* love interest who wants to meet you.
* 'supposed' friend in need.
* prize/lottery.
* inheritance of some distant relative.
* person in distress asking you to take care of their financial assets.
* some government/private fine/tax/loan/offer scam
If you know the person who seems to have send the email asking for money in person, contact them in an other way or have them answer a personal question only they know the answer to, before you accept their email as real.
In many countries there are organisations to whom you can report internet fraud or suspected internet fraud. They also offer advice about common scams and how to recognise them.
In the USA: The IC3 (part of the FBI) (further information from the FBI on romance scams)
In Canada: The Canadian Anti-Fraud Centre
In the UK: Action Fraud
The second rule for every such question is also simple:
google this requirement
A legitimate requirement, if exist, would be found on the relevant official sources, including the airline or Embassy web sites. For example, Indian nationals are required to show USD 500/week to enter Thailand.
Many countries also require visa applicants to show means of financial resources. However cash is rarely accepted as such evidence (since one can just borrow it for a day), and depositing this cash in applicant's bank account a day before applying for a visa usually backfires.
|
output
| 1 | 392 |
When converting from RGB to grayscale, it is said that specific weights to channels R, G, and B ought to be applied. These weights are: 0.2989, 0.5870, 0.1140.
It is said that the reason for this is different human perception/sensibility towards these three colors. Sometimes it is also said these are the values used to compute NTSC signal.
However, I didn't find a good reference for this on the web. What is the source of these values?
|
instruction
| 0 | 393 |
If you convert RGB -> grayscale with slightly different numbers / different methods, you won't see much difference at all on a normal computer screen under normal lighting conditions -- try it.
### RGB -> ^gamma -> Y -> L*
In color science, the common RGB values, as in html rgb( 10%, 20%, 30% ),
are called "nonlinear" or
Gamma corrected.
"Linear" values are defined as
```Rlin = R^gamma, Glin = G^gamma, Blin = B^gamma
```
where gamma is 2.2 for many PCs.
The usual R G B are sometimes written as R' G' B' (R' = Rlin ^ (1/gamma))
(purists tongue-click) but here I'll drop the '.
Brightness on a CRT display is proportional to RGBlin = RGB ^ gamma,
so 50% gray on a CRT is quite dark: .5 ^ 2.2 = 22% of maximum brightness.
(LCD displays are more complex;
furthermore, some graphics cards compensate for gamma.)
To get the measure of lightness called ```L*``` from RGB,
first divide R G B by 255, and compute
```Y = .2126 * R^gamma + .7152 * G^gamma + .0722 * B^gamma
```
This is ```Y``` in XYZ color space; it is a measure of color "luminance".
(The real formulas are not exactly x^gamma, but close;
stick with x^gamma for a first pass.)
Finally,
```L* = 116 * Y ^ 1/3 - 16
```
"... aspires to perceptual uniformity [and] closely matches human perception of lightness." --
Wikipedia Lab color space
|
output
| 1 | 393 |
¿Cuál es la diferencia entre echo, print, print_r, var_dump y var_export en PHP?
|
instruction
| 0 | 394 |
Aquí hay una descripción general de estas funciones de PHP:
###echo
* Muestra una o más cadenas separadas por comas
* No tiene un valor de retorno
* Ejemplo:
```echo "Cadena 1", "Cadena 2";
```
###print
* Muestra solo una simple cadena
* Devuelve 1, por lo cual puede ser usada en una expresión
* Ejemplos:
```print "Hello";
if($expresion && print "Cadena"){
// Hacer algo
}
```
###print_r()
* Muestra una representación más entendible de un solo valor cualquiera
* No solo acepta cadenas, también acepta arreglos y objetos formateándolos para ser visualizados de una forma más entendible
* Puede devolver su valor de salida como un valor de retorno si le pasa ```true``` como su segundo argumento
* Útil para la depuración
Ejemplo: Si tenemos el siguiente arreglo:
```$a = array ('a' => 'manzana', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
```
Nuestro ```print_r($a);``` nos devolverá algo como esto:
```Array
(
[a] => manzana
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
```
###var_dump()
* Muestra una representación más entendible de un valor cualquiera o más separados por comas
* No solo acepta cadenas, también acepta arreglos y objetos formateándolos para ser visualizados de una forma más entendible
* Usa un formato diferente al anterior ```print_r()```, por ejemplo, también muestra el tipo del valor
* Útil para la depuración
* No tiene un valor de retorno
Ejemplo: Si tenemos el siguiente arreglo:
```$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
```
Nuestro ```var_dump($a);``` nos devolverá algo como esto: (nótese que nos muestra el tipo de valor de cada elemento en nuestro arreglo)
```array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
```
###var_export()
* Muestra una representación más entendible y ejecutable de un valor cualquiera
* No solo acepta cadenas, también acepta arreglos y objetos formateándolos para ser visualizados de una forma más entendible
* Usa un formato de salida diferente de ```var_dump()``` y ```print_r()```, la salida es un código de PHP válido
* Útil para la depuración
* Puede devolver su valor de salida como un valor de retorno si le pasa ```true``` como su segundo argumento
Ejemplo, si realizamos lo siguiente
```class A {
public $var;
}
$a = new A;
$a->var = 5;
var_export($a);
```
Obtendremos como resultado:
```A::__set_state(array(
'var' => 5,
))
```
###Notas
* ```echo``` es mucho más rápido que ```print```
* ```echo``` y ```print``` son constructores de lenguaje
* ```print_r()``` y ```var_dump()``` son funciones
* ```echo``` y ```print``` pueden recibir sus argumentos mediante paréntesis como una función ```echo("Hello", "world");``` ó ```print("Hello World");```
|
output
| 1 | 394 |
In Android, I defined an ```ImageView```'s ```layout_width``` to be ```fill_parent``` (which takes up the full width of the phone).
If the image I put to ```ImageView``` is bigger than the ```layout_width```, Android will scale it, right? But what about the height? When Android scales the image, will it keep the aspect ratio?
What I find out is that there is some white space at the top and bottom of the ```ImageView``` when Android scales an image which is bigger than the ```ImageView```. Is that true? If yes, how can I eliminate that white space?
|
instruction
| 0 | 395 |
* Yes, by default Android will scale your image down to fit the ImageView, maintaining the aspect ratio. However, make sure you're setting the image to the ImageView using ```android:src="..."``` rather than ```android:background="..."```. ```src=``` makes it scale the image maintaining aspect ratio, but ```background=``` makes it scale and distort the image to make it fit exactly to the size of the ImageView. (You can use a background and a source at the same time though, which can be useful for things like displaying a frame around the main image, using just one ImageView.)
* You should also see ```android:adjustViewBounds``` to make the ImageView resize itself to fit the rescaled image. For example, if you have a rectangular image in what would normally be a square ImageView, adjustViewBounds=true will make it resize the ImageView to be rectangular as well. This then affects how other Views are laid out around the ImageView.
Then as Samuh wrote, you can change the way it default scales images using the ```android:scaleType``` parameter.
By the way, the easiest way to discover how this works would simply have been to experiment a bit yourself! Just remember to look at the layouts in the emulator itself (or an actual phone) as the preview in Eclipse is usually wrong.
|
output
| 1 | 395 |
I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?
|
instruction
| 0 | 396 |
As serialization doesn't work generally (only when the order of properties matches: ```JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})```) you have to check the count of properties and compare each property as well:
```const objectsEqual = (o1, o2) =>
Object.keys(o1).length === Object.keys(o2).length
&& Object.keys(o1).every(p => o1[p] === o2[p]);
const obj1 = { name: 'John', age: 33};
const obj2 = { age: 33, name: 'John' };
const obj3 = { name: 'John', age: 45 };
console.log(objectsEqual(obj1, obj2)); // true
console.log(objectsEqual(obj1, obj3)); // false```
If you need a deep comparison, you can call the function recursively:
```const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };
const obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };
const obj3 = { name: 'John', age: 33 };
const objectsEqual = (o1, o2) =>
typeof o1 === 'object' && Object.keys(o1).length > 0
? Object.keys(o1).length === Object.keys(o2).length
&& Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
: o1 === o2;
console.log(objectsEqual(obj1, obj2)); // true
console.log(objectsEqual(obj1, obj3)); // false```
Then it's easy to use this function to compare objects in arrays:
```const arr1 = [obj1, obj1];
const arr2 = [obj1, obj2];
const arr3 = [obj1, obj3];
const arraysEqual = (a1, a2) =>
a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));
console.log(arraysEqual(arr1, arr2)); // true
console.log(arraysEqual(arr1, arr3)); // false
```
|
output
| 1 | 396 |
I'm working with another developer on a project, and we're using Github as our remote repo. I'm on a Mac using git 1.7.7.3, he's on Windows using git 1.7.6.
This is what's happening
* One of us (let's call him developer A, but it doesn't matter which one) pushes a set of commits to GitHub.
* The other (developer B) makes some local commits.
* B does a ```git pull```.
* B does a ```git push```.
* Looking at the commit history log, I see Merge branch 'master' of github.com:foo/bar
The commit log gets littered with "Merge branch" messages over time, and also shows developer B as committing changes that developer A made. The only way we've found to prevent this issue has been to do a ```git pull --rebase``` at step 3, but I don't know what side effects rebasing will introduce. This is my first time working on a multi-developer git repo, so is this just normal behavior? Any thoughts on how to solve this issue?
|
instruction
| 0 | 397 |
The commit you are seeing is perfectly fine. A ```pull``` effectively runs ```git fetch``` and then ```git merge``` so a merge is usually happening when you run ```git pull```.
The alternative to use rebasing instead of merging is possible, but usually you should avoid it. Rebasing allows you to keep a linear history, but also removes any information about the branching that originally happened. It will also cause the history of the current branch being rewritten, recreating all commits that are not contained in the target branch (in your case, the remote). As the recreated commits are different commits, this can cause a lot of confusion when developing together with others, especially when people already checked out parts of those commits before they get rewritten (for example with feature branches). So as a rule of thumb, you should never rewrite any commit that was already pushed.
The commits you see are there to combine two (or more) branches. It is perfectly fine to have a commit that does nothing else then merging multiple branches. In fact it makes it very clear when you have a merge commit that combines branches when looking at the history. In comparison to rebasing, merging also allows you to effectively see the original history as it was developed, including the actual branches that coexisted.
So, long story short: Yes, having merge commits is perfectly fine and you should not worry about them.
|
output
| 1 | 397 |
You are asleep on your boat on open sea. When you wake up you discover you have been robbed. A quick inspection of security cam footage reveals that the pirates who robbed you left your ship exactly an hour ago. The sea is flat, extends indefinitely, and is fully covered in a thick persistent fog. You have no idea in which direction the pirates fled. But you do know that these pirates always continue in a straight line at full speed away from their victim. Their maximum speed on open water is 20 nautical miles per hour. Your boat can reach 21 nautical miles per hour.
How do you catch the pirates?
|
instruction
| 0 | 398 |
If we assume the ocean is flat and extends indefinitely in all directions, there is a strategy that guarantees we can catch the pirates in at most 800,000 years.
Put our current location as the origin of a coordinate system. We will describe our position in polar coordinates, as a function of time: $(r(t),\theta(t))$ (where we have arbitrarily chosen a direction to be $\theta=0$, and $t=0$ is when we realized we had been robbed).
We begin by traveling in the $\theta=0$ direction for 20 hours, putting our position at $(420, 0)$. We are then the same distance from the origin as the pirates. Next, we will travel in a spiral, in a manner so that $r'(t)=20$ at all times. This guarantees we will always be the same distance from the origin as the pirates. For $t\geq 20$, we will have $r(t)=420+20(t-20)=20t+20$.
Our speed is
$$
\sqrt{(r')^2+r^2(\theta')^2} = 21\text{ mph},
$$
and $r'(t)=20$ for $t>20$, so
$$
\theta'(t)=\sqrt{\frac{41}{r^2}}=\frac{\sqrt{41}}{20+20t}.
$$
If there is a $t\geq 20$ for which $\theta(t)$ is the angle in which the pirates fled, we will catch them. This means we will certainly catch the pirates by the time $\theta$ has increased from $0$ to $2\pi$. If $t_0$ is the time this happens, we have
$$
2\pi=\int_{20}^{t_0}\theta'(t)\,dt=\int_{20}^{t_0}\frac{\sqrt{41}}{20+20t}dt.
$$
Solving for $t_0$ gives
$$
t_0=21\mathrm{exp}\left(\frac{40\pi}{\sqrt{41}}\right)-1\approx 7,005,043,026.
$$
This means we can catch the pirates in at most 7,005,043,026 hours, or about 800 millennia. Better later than never!
|
output
| 1 | 398 |
Was ist der Unterschied zwischen den Fragewörtern "wieso", "weshalb" und "warum"?
|
instruction
| 0 | 399 |
Es gibt im heutigen Deutschen keinen semantischen Unterschied zwischen den drei Frageadverbien (genauer: Kausalfrageadverbien) warum, weshalb und wieso. Die drei Wörter sind also Synonyme und somit beliebig gegeneinander austauschbar.
Wenn man sehr feinsinnig ist, könnte man im Ursprung der drei Wörter folgende Unterscheidung finden:
* warum als Frage nach dem Grund oder dem Motiv
Warum freut sich die Frau?
Weil sie im Lotto gewonnen hat.
* wieso als Frage nach der Ursache
Wieso fällt ein Apfel auf den Boden?
Weil er der Schwerkraft ausgesetzt ist.
* weshalb als Frage nach dem Zweck
Weshalb besucht er die Schule?
Weil er etwas lernen möchte.
Etymologie
* warum
bezeugt im Althochdeutschen wār umbe über Mittelhochdeutschen warumbe aus wār wo und umbe um. Gleichgestellt zu worum; Quelle: Grimmsches Wörterbuch
* wieso
Übertragung aus dem lateinischen qui sic? → wie so? alt. Ital. per che?, modern Ital.: perché? = per che ragione? ("aus welchem Grund"); Quelle: Grimmsches Wörterbuch
* weshalb
aus welchem Grunde – Verschmelzung der Präposition halb(en) (wegen) mit dem vorangestellten Genitiv des Pronomens was; Quelle: Grimmsches Wörterbuch
Allerdings sind die Grenzen zwischen den Begriffen häufig verwischt und in der Alltagssprache wird diese Unterscheidung kaum wahrgenommen.
|
output
| 1 | 399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.