qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
57,762,430 | I'm new at PL/SQL. I'm trying to program a `trigger` that `insert` in a `table` A just if there is an `insert` in `table` B (to have an insert in table B, the following `select` must returns 1).
```
SELECT 1
INTO v_exists
FROM TFRG V
WHERE
SUBSTR(:NEW.COD_OBJT, 1, 2) = V.CDP
AND SUBSTR(:NEW.COD_OBJT, 12, 2) = V.CDS
AND V.CDSIT = 'V'
AND V.CDG IN (‘E’,’G’);
```
The problem is that I don't know how to include this select in my trigger:
```
CREATE OR REPLACE TRIGGER Trigger_name
-- PL/SQL Block
AFTER INSERT
ON B FOR EACH ROW
declare
v_exists NUMBER;
begin
begin
SELECT 1
INTO v_exists
FROM TFRG V
WHERE
SUBSTR(:NEW.COD_OBJT, 1, 2) = V.CDP
AND SUBSTR(:NEW.COD_OBJT, 12, 2) = V.CDS
AND V.CDSIT = 'V'
AND V.CDG IN (‘E’,’G’);
INSERT INTO A
(NR);
VALUES
(:new.objt);
exception
when NO_DATA_FOUND then
null;
end;
exception
when OTHERS then
null;
END
``` | 2019/09/02 | [
"https://Stackoverflow.com/questions/57762430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2037602/"
] | ...Or you can use **any()** operator.
>
> The any operator without an argument returns true if the collection is not empty.
>
>
>
[docs](http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventions-complete.html#_Toc371341806)
OData/v4/2.0/Case?$filter=Names/any() | The below one was working for me, hope this helps.
<https://api-uk.securitycenter.windows.com/api/machines?$filter=not> machineTags/any()
Am filtering out the results where the machine tags are empty array. |
65,523,998 | I've been fighting with awk to make this work but I've been unable to do it. I have two lines as follows:
```
= filename: /path/to/file
years="1990,2001"
```
I need to check each year between the quotes against a given value and then print the previous line if it matches and get the filename as a result (it only needs to match the first one found). The value and operator i.e. `<,>,=,<=,=>,~` will be passed via a variable to awk like:
```
value="2000"
string"=\$2 < $value" # just an example
awk ... '"$string"' ...
```
There are conditional statements which can generate this string based on the input received.
I've tried separating each field using a space, quote and comma as a delim:
`awk -F'[," ]' '{i=(1+(i%N));if(buf[i]&& $2<2000) print buf[i]; buf[i]=$0;}'`
This works but I need to loop through all the columns += $2. I tried to do something like this:
`awk -F'[," ]' '{for(f=2;f<=NF;f++);i=(1+(i%N));if(buf[i]&& $f>1950) print buf[i]; buf[i]=$0;}'`
But that didn't work (I'm probably just doing it wrong).
I also considered getting rid of `if(buf[i]&& $2>1950) print buf[i]; buf[i]=$0;` and just joining the two lines and separating the fields, checking with the loop on += $5 and then printing just "$3" since that will always be the filename, but I can't figure out how to merge the two lines into one.
Example:
--------
year < 2000
Input text:
```
= filename: /mnt/project1/record1.txt
years="2005,2019,2011,2012,2013"
= filename: /mnt/project1/record2.txt
years="1996,2000"
= filename: /mnt/project1/record3.txt
years="2005,2001,2012"
= filename: /mnt/project1/record4.txt
years="2010,2009,1997,2000"
```
Output (match):
```
/mnt/project1/record2.txt
/mnt/project1/record4.txt
``` | 2020/12/31 | [
"https://Stackoverflow.com/questions/65523998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12234893/"
] | I'm still learning AWK but IIUC you want something similar to the
following `script.awk`:
```
#!/usr/bin/awk -f
BEGIN {
FS = "= filename:"
}
{
if ( NF == 2 ) {
filename = $2
getline
}
}
/^years="1990,2001"$/ \
{
print "filename: " filename
}
```
Run with the following `input`:
```
= filename: /path/to/file5
years="1990,2001"
= filename: /path/to/file4
years="1990,2002"
= filename: /path/to/file3
years="1990,2003"
= filename: /path/to/file2
years="1990,2004"
= filename: /path/to/file1
years="1990,2005"
= filename: /path/to/file0
years="1990,2006"
```
like that:
```
$ ./script.awk input
filename: /path/to/file5
``` | Assumptions:
* OP will always be searching for dates **less than** (`<`) a given target date (eg, `2000` in OP's example)
* a line starting with `^= filename:` is always followed by a line starting with `^years=` (otherwise we would need more sample input data before adding more logic)
Sample data:
```
$ cat file_year.dat
= filename: /mnt/project1/record1.txt
years="2005,2019,2011,2012,2013" # no match
= filename: /mnt/project1/record2.txt
years="1996,2000" # match on 1996 < 2000
= filename: /mnt/project1/record3.txt
years="2005,2001,2012" # no match
= filename: /mnt/project1/record4.txt
years="2010,2009,1997,2000" # match on 1997 < 2000
= filename: /mnt/project1/record5.txt
years="2010,2009,2007,1947" # match on 1947 < 2000
```
**NOTE**: comments added to show what should (not) match; comments do not exist in the actual data file
One `awk` idea:
```
awk -v tgt=2000 ' # pass target date in as awk variable "tgt"
/^= filename: / { fn=$(NF) # save the filename in awk variable "fn"
next # skip to the next line of input
}
fn != "" { n=split($0,arr,"[,\"]") # if "fn" is set then split the current line on double quotes
# and commas; store results (ie, individual years)
# in array "arr[]"
for (i=2; i<n; i++) # process arr[2-(n-1)] elements (individual years)
if ( arr[i] < tgt ) # if less than "tgt" ...
{ print fn # print associated filename ("fn") and ...
break # break out of loop
}
fn="" # clear "fn" varible
}
' file_year.dat
```
This generates:
```
/mnt/project1/record2.txt
/mnt/project1/record4.txt
/mnt/project1/record5.txt
``` |
6,836 | What food stuffs pair well with **orange wine**?
This website has a little information on orange wines: [Crushing: Orange Wines](http://blog.cookingchanneltv.com/2010/10/19/orange-wine-in-time-for-halloween/).
But what I would like to know is what foods go well with these orange wine and why they are paired as such? | 2017/05/13 | [
"https://beer.stackexchange.com/questions/6836",
"https://beer.stackexchange.com",
"https://beer.stackexchange.com/users/5064/"
] | I tend to think of drinks with scary names. Specifically you could serve [Zombie Dust](https://www.3floyds.com/beer/zombie-dust/) from 3 Floyds Brewing which has the advantage of being a really [excellent beer](https://www.beeradvocate.com/beer/profile/26/64228/).
[](https://i.stack.imgur.com/W8nCR.jpg)
A Google search for "Halloween themed beer" will yield several articles with similarly scary named beers such as [here](https://www.craftbeer.com/craft-beer-muses/12-frighteningly-delicious-beers-halloween) and [here](https://learn.kegerator.com/scary-halloween-beers/).
Lastly, there is the [Pumpkin Ale](https://www.beeradvocate.com/beer/style/72/) beer style. | Why not try some orange wine. Pumpkins and pumpkin colored foods and drinks are often associated with Halloween.
[Crushing: Orange Wines](http://blog.cookingchanneltv.com/2010/10/19/orange-wine-in-time-for-halloween/)
>
> “That’s right: red, pink and white have company,” exclaimed a recent newsletter from the Chelsea Wine Vault. Laden with cartoony images of a wine glass filled with bright orange liquid and a grape vine dangling bright orange grapes, the newsletter featured an infamous, under-the-radar vino known as orange wine. Save all judgment! Unlike gimmicky green beer sold on St. Pat’s Day, orange wine has a legitimate backstory…
>
>
> The practice of making orange wines, despite its relative anonymity, spans centuries, dating all the way back to Eurasian wine production in Georgia (and we’re not talking the Peachtree State here). Much of the orange wine that is commercially distributed today comes from Italy (specifically its northeastern Friuli region), but other producers include France, Germany and California.
>
>
>
[](https://i.stack.imgur.com/Bce1K.jpg)
**Orange Wines** -- A great get for your Halloween Party? Photograph by: Tom Censani |
31,416,496 | I'm using Symfony 2.6 and I'm trying to use translations inside my \Twig\_Extension but translator always use and return the default\_locale translated text. (in my case "EN")
I created a service in services.yml:
```
utils.twig_extension:
class: Skaphandrus\AppBundle\Twig\UtilsExtension
public: false
arguments: ["@service_container", "@translator.default"]
tags:
- { name: twig.extension, alias: utils.twig_extension }
```
and inside my extension:
```
private $container;
private $translator;
public function __construct($container, Translator $translator) {
$this->container = $container;
$this->translator = $translator;
}
```
And inside my method I have:
```
return $this->translator->trans('message');
```
But when I run the code it always return the "EN" locale message.
Thanks in advance for any help. | 2015/07/14 | [
"https://Stackoverflow.com/questions/31416496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3157658/"
] | I agree with the others stating to use jQuery or straight DOM calls.
Here is another shot at the jQuery solution - very similar to the one above. I went ahead and presented it because it targets the images directly - in case that's what you're really trying to accomplish.
```
$(function()
{ var mainDiv = $('div.pink:first'),
imgs = $('img');
mainDiv.click(function()
{ alert('1');
});
imgs.click(function(e)
{ e.stopImmediatePropagation();
});
});
``` | You have a mix of jQuery and DOM methods calls. Note also that for attaching event listeners, you should wait for all HTML document to be ready.
I'd recommend using either DOM methods ot jquery methods. Following is an example of jquery:
```
$(function(){
$('.pink:first').on("click", function(e) {
alert('1');
});
$('.yellow').on('click', function (e) {
e.stopPropagation();
});
})
```
See also this [JSfiddle](http://jsfiddle.net/leofcx/AHyN5/7/) |
19,982,085 | This is my first post in this forum. I am facing a problem in splitting the below string.
String in a File with leading space, multiple spaces in between and pipe symbol:
```
$str= | U-mom | 9.2 | 2.30E-04 | 9.60E-04 | 1.04E-04 OK |;
```
I could not place multiple spaces in my string shown above, but there are multiple spaces after `"U-mom"`
1. I have tried splitting it using: `$str = join "", split ' ', $str;`
Result: `|U-mom|9.2|2.30E-4|9.60E-4|1.04E-04OK|`
2. Next I have used: `split(/\|/,$str);`
stored each string in array and the result is:
---
```
0
U-mom0
9.20
2.30E-040
9.60E-040
1.04E-04OK0
```
The result outputs 0 as starting array and 0 comes as suffix in every element of array.
Require help to overcome this problem. | 2013/11/14 | [
"https://Stackoverflow.com/questions/19982085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2992395/"
] | Remember that `split`'s first parameter is a regular expression and not a string. (Or, it should be a regular expression). You can do something like this:
```
my @values = split /\s+\|\s+/, "$string";
```
Note that this will make `$values[0]` a null string since there's a `|` with blank spaces at the beginning of your string. If those blank spaces aren't there, `$values[0]` would be `| U-mom`. Also note that the last entry will end with `|` since there are no blank spaces after the last `|`. if there were spaces, your last entry would actually be correct.
One way to get around this is to purposefully put spaces before and after your string:
```
my @values = split /\s+\|\s+/, " $string ";
splice (@values, 0, 1); # Removes that first blank entry;
```
Now, we can print it out:
```
for my $entry (@values) {
say "$entry";
}
```
Or...
```
for my $index (0..$#values) {
say "Index: $index Entry: '$values[$index]'";
}
``` | The split function accepts a regular expression. If you know that there are going to be leading and trailing spaces, just build that into your regular expression to split on.
```
my $str = "| U-mom | 9.2 | 2.30E-04 | 9.60E-04 | 1.04E-04 OK |";
print "$_\n" for split(/\s*\|\s*/, $str);
# output:
# U-mom
# 9.2
# 2.30E-04
# 9.60E-04
# 1.04E-04 OK
```
`\s*` matches zero or more whitespace characters |
453,418 | How can I do this on the command line?
e.g. copy `/dir/another/file` to `/tmp/` so I have `/tmp/dir/another/file` | 2012/07/25 | [
"https://superuser.com/questions/453418",
"https://superuser.com",
"https://superuser.com/users/139884/"
] | [rsync](http://linux.die.net/man/1/rsync) can be a good help for this :
```
rsync -Ravz my/first/dir/file.txt another_dir
```
will gave as result
```
another_dir/my/first/dir/file.txt
``` | You can use `tar` to preserve paths while copying files:
```
tar cf - /dir/another/file | (cd /tmp && tar xf -)
``` |
11,243,714 | I'm porting our existing web application from Wicket 1.4 to 1.5. In the app there are two template pages which are children of a base page. The templates are named secure and unsecure, and they define pages for authenticated and unauthenticated users. Any pages in the app inherit from these templates. In Wicket 1.4 this set up worked fine without any problems.
After porting to Wicket 1.5 I get the following error:
>
> Unable to find component with id 'PageTitle' in [HtmlHeaderContainer]
>
>
>
'PageTitle' is a Wicket Label and is used dynamically build the page title in the base page, it is positioned in the `<head>` tag of the base page mark up. What I've discovered is that the `<head>` mark up is being rendered twice, so I presume I get the error because Wicket creates the PageTitle once and then tries to create it again (The `<head>` is defined in the base page mark up only).
The quick and dirty fix is to move the PageTitle to the templates (duplicated code). Is there a better way to solve this problem?
Hopefully my description is clear enough, however, I can supply a code example if needed. | 2012/06/28 | [
"https://Stackoverflow.com/questions/11243714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1444622/"
] | Make sure that if you are overriding `viewWillAppear` that you call
```
[super viewWillAppear:animated];
```
If you don't, the Scroll View will not scroll up properly.
**Swift**
```
super.viewWillAppear(animated)
``` | >
> If the auto scroll of UITableViewController doesn't work with the
> UITextFields in cells or scroll weirdly, do these steps. **Swift 5 iOS
> 13.2 tested 100%**
>
>
>
First implement **viewWillAppear** but don't call **super.viewWillAppear** (this will **stop** auto scroll)
```
override func viewWillAppear(_ animated: Bool) {
}
```
Then let's do the scroll **manually**.
```
override func viewWillAppear(_ animated: Bool) {
//Notification center observers
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)),
name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)),
name: UIResponder.keyboardWillHideNotification, object: nil)
}
//keybord show action
@objc func keyboardWillShow(notification: Notification) {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: notification.getKeyBoardHeight, right: 0)
}
//keyboard hide action
@objc func keyboardWillHide(notification: Notification) {
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
extension Notification {
var getKeyBoardHeight: CGFloat {
let userInfo: NSDictionary = self.userInfo! as NSDictionary
let keyboardFrame: NSValue = userInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
return keyboardRectangle.height
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
``` |
40,082 | How is it possible to check in JS/jQuery if the user is on the root site of the root sitecollection in the webapplication? (Sharepoint 2010)
Thanks!
**Example:**
* <http://www.mysite.com/Pages/Whatever.aspx> -> ROOT WEB & ROOT SITECOLLECTION
* <http://www.mysite.com/subsite/Pages/Test.aspx> -> **NOT** ROOT WEB & ROOT SITECOLLECTION
* <http://www.mysite.com/sites/Random/Pages/Awesome.aspx> -> ROOT WEB & **NOT** ROOT SITECOLLECTION
* <http://www.mysite.com/sites/Random/subsite/Pages/Awesome.aspx> -> **NOT** ROOT WEB & **NOT** ROOT SITECOLLECTION | 2012/07/03 | [
"https://sharepoint.stackexchange.com/questions/40082",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/3692/"
] | You can use ECMAScript to achieve it.
```
var clientContext = new SP.ClientContext();
var rootWeb = clientContext.get_site().get_rootWeb(); //always return the root web of the site collection
```
See some examples [here](http://antoniolanaro.blogspot.se/2011/05/ecmascript-how-to-get-lists.html). | I've solved this by adding a usercontrol to the masterpage where I check the current url. If it passes as rootweb from sitecollection, then I use the scriptmanager to write a clientscriptblock into the page. I guess using a webservice was also a possibility, but the fastest way for me was this one... |
59,389,208 | I am building an angular app. I am navigating from first component to second through click event. While navigating to the second component I am wiling to pass some data from first component to the second component. I have followed a tutorial to achieve this but couldn't do it. Below is my code
First component.ts
```
export class FirstComponent implements OnInit {
@Output() messageEvent = new EventEmitter<string>();
constructor(){
}
ngOnInit() {}
sendMessagetoSecond(ahu) {
this.messageEvent.emit(ahu)
console.log(ahu)
}
```
first component.html
```
<map name="ahuMap">
<area shape="rect" coords="818,232,917,262" (click)="sendMessagetoSecond()" [routerLink]="['/secondComponent']">
</map>
```
second component.ts
```
ahu : string
receiveMessage($event) {
this.ahu = $event
}
```
second component .html
```
<body>
<app-first (messageEvent)="receiveMessage($event)"></app-first>
ahu: {{ahu}}
<div>
....
</div>
</body>
```
This is what I tried. The problems I am facing are:
1-Variable is not being transferred to the second component
2-HTML of first component is also being loaded in second component.
Is there something that I am missing or doing wrong? | 2019/12/18 | [
"https://Stackoverflow.com/questions/59389208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8957025/"
] | You can use a shared service to pass data between components. When you have data that changes over time, RxJS BehaviorSubject will be very useful in this case.That it will ensures that the component always receives the most recent data.
To do so,
you need first to create a service in which you will add a private BehaviorSubject that will hold the current value of the message that you want to share between components. And two methods, one to handle the current data stream as an observable that will be used by the components and the other to update the value of the message.
>
> data.service.ts
>
>
>
```
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable()
export class DataService {
private messageSource = new BehaviorSubject('default message');
constructor() {}
fetchMessage(): Observable<string> {
return this.messageSource.asObservable();
}
sendMessage(message: string) {
this.messageSource.next(message)
}
}
```
Once the service is created, you need just to inject it in your components' constructor then call its methods fetchMessage/sendMessage in order to get or change your message value.
So,here is how you can use it to pass data from parent to child for example:
>
> parent.component.ts
>
>
>
```
import { Component, OnInit } from '@angular/core';
import { DataService } from "./data.service";
@Component({
selector: 'parent',
template: `
{{message}}
<button (click)="newMessage()">send Message</button>
`
})
export class ParentComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.fetchMessage.subscribe(message => this.message = message)
}
newMessage() {
this.data.sendMessage("Hello from Parent Component")
}
}
```
>
> child.component.ts
>
>
>
```
import { Component, OnInit } from '@angular/core';
import { DataService } from "./data.service";
@Component({
selector: 'child',
template: `
{{message}}
`
})
export class ChildComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.fetchMessage().subscribe(message => this.message = message)
}
}
```
Hope this may help you. | [in this demo, I am passing a value from app.component.ts to view component.component.ts using test.service](https://stackblitz.com/edit/angular-641dln?file=src%2Fapp%2Fapp.component.ts)
Here, in the constructor of app.component.ts giving a value to a variable which is in test.service, then assigning that value to a variable into view component.component.ts. |
22,871,206 | I am a huge fan of open source contributions square has done to the Android community and was looking into their latest contribution Otto (event bus )
<http://square.github.io/otto/>
Digging deeper I see that Otto uses reflection and there is no ordered broadcast ( a pattern where a unconsumed message is handed down from one receiver to the next receiver listening on the same type of event ) Otto believes in more of a fire and forget model .
Now android has `LocalBroadcastManager` (LBM ) in its v4 support library which serves the same purpose , though it's more bulkier and has more restrictions on the objects that are passed . But on the brighter side it does support ordered broadcast and its more akin to the normal broadcast.
Both Otto and LBM are within the same process space so in terms of speed I guess both would be same. The only real difference I could see is that Otto allows you to define custom events and you do not have to serialize/Parcel the Objects .
Hence my real question is when would you use Otto if LBM does the same things .
References :
<http://nick.perfectedz.com/otto-event-system/>
[Using Intents or an event bus to communicate within the same app](https://stackoverflow.com/questions/17317922/using-intents-or-an-event-bus-to-communicate-within-the-same-app)
<https://plus.google.com/107049228697365395345/posts/6j4ANWngCUY> | 2014/04/04 | [
"https://Stackoverflow.com/questions/22871206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1172805/"
] | >
>
> >
> > Both Otto and LBM are within the same process space so in terms of speed i guess both would be same .
> >
> >
> >
>
>
>
I've found that registering Otto events are quite expensive, sometimes it takes more than 16 milliseconds to register event subscribers (That means you drop 1 FPS!). That's somewhat expected, as event subscribing in Otto is done by reflection.
While for LBM, it only takes a few hundred µs only for registering, which is almost 32x faster. (Result from traceview, Samsung Galaxy S4)
But of course, using Otto can write less code, there's a trade off. | 1. otto makes code cleaner, smaller
2. otto makes testing easier |
8,741,142 | I want to send a large amount of cached json data from an import process to an MVC controller which will in turn respond with a text file in CSV format.
The problem is if I use an AJAX call, there is no way for the browser to handle the response and download the file.
If I use a regular form post, then the browser would handle the returned file response. However, AFAIK to post a form I can't send Json data and I don't want to send the data on the query string.
Seems like I'm between a rock and a hard place. What are my best options for achieving this? I want to avoid writing data files to the server. Basically I just want to send lots of json data and return as a download request to the browser. | 2012/01/05 | [
"https://Stackoverflow.com/questions/8741142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/306098/"
] | Just my two cents. If you don't want to create a file, just cache data in session (or wherever you like).
So:
1. perform ajax post of json data
2. in the Controller Action store the data somewhere (e.g. Session) and create a key to access it later (a guid) and return it as a json object.
3. in the success ajax function, invoke another action passing the key obtained via normal location.href = url + key
It's pretty the same of saving a file server side, except there's no file. | Actually, I think the best solution is the following:
1. Do an AJAX POST which fetches the CSV from the server
2. Use the `data:` URI scheme to view the CSV:
Either directly
```
location.href = "data:text/csv;charset=utf-8,Value 1, Value 2, Value 3";
```
or prepare a link when the AJAX finishes, something like this:
```
<a href="data:text/csv;charset=utf-8,Value 1, Value 2, Value 3">Conversion finished. Save</a>
```
This works with limitations in IE8. Full support in IE9 and, of course, everywhere else. |
59,931,770 | I have a pyspark dataframe:
```
id | column
------------------------------
1 | [0.2, 2, 3, 4, 3, 0.5]
------------------------------
2 | [7, 0.3, 0.3, 8, 2,]
------------------------------
```
I would like to create a 3 columns:
* `Column 1`: contain the sum of the elements < 2
* `Column 2`: contain the sum of the elements > 2
* `Column 3`: contain the sum of the elements = 2 (some times I have duplicate values so I do their sum) In case if I don't have a
values I put null.
Expect result:
```
id | column | column<2 | column>2 | column=2
------------------------------|--------------------------------------------
1 | [0.2, 2, 3, 4, 3, 0.5]| [0.7] | [12] | null
---------------------------------------------------------------------------
2 | [7, 0.3, 0.3, 8, 2,] | [0.6] | [15] | [2]
---------------------------------------------------------------------------
```
Can you help me please ?
Thank you | 2020/01/27 | [
"https://Stackoverflow.com/questions/59931770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11709732/"
] | For Spark 2.4+, you can use [`aggregate`](https://docs.databricks.com/_static/notebooks/apache-spark-2.4-functions.html) and [`filter`](https://docs.databricks.com/_static/notebooks/apache-spark-2.4-functions.html) higher-order functions like this:
```
df.withColumn("column<2", expr("aggregate(filter(column, x -> x < 2), 0D, (x, acc) -> acc + x)")) \
.withColumn("column>2", expr("aggregate(filter(column, x -> x > 2), 0D, (x, acc) -> acc + x)")) \
.withColumn("column=2", expr("aggregate(filter(column, x -> x == 2), 0D, (x, acc) -> acc + x)")) \
.show(truncate=False)
```
Gives:
```
+---+------------------------------+--------+--------+--------+
|id |column |column<2|column>2|column=2|
+---+------------------------------+--------+--------+--------+
|1 |[0.2, 2.0, 3.0, 4.0, 3.0, 0.5]|0.7 |10.0 |2.0 |
|2 |[7.0, 0.3, 0.3, 8.0, 2.0] |0.6 |15.0 |2.0 |
+---+------------------------------+--------+--------+--------+
``` | Here's a way you can try:
```
import pyspark.sql.functions as F
# using map filter the list and count based on condition
s = (df
.select('column')
.rdd
.map(lambda x: [[i for i in x.column if i < 2],
[i for i in x.column if i > 2],
[i for i in x.column if i == 2]])
.map(lambda x: [Row(round(sum(i), 2)) for i in x]))
.toDF(['col<2','col>2','col=2'])
# create a dummy id so we can join both data frames
df = df.withColumn('mid', F.monotonically_increasing_id())
s = s.withColumn('mid', F.monotonically_increasing_id())
#simple left join
df = df.join(s, on='mid').drop('mid').show()
+---+--------------------+-----+------+-----+
| id| column|col<2| col>2|col=2|
+---+--------------------+-----+------+-----+
| 0|[0.2, 2.0, 3.0, 4...|[0.7]|[10.0]|[2.0]|
| 1|[7.0, 0.3, 0.3, 8...|[0.6]|[15.0]|[2.0]|
+---+--------------------+-----+------+-----+
``` |
7,777 | I need to install modules so that the database changes happen. I can't just let it be an install on logging to admin type of approach as I have a bash script that I am using to provision my test servers. It seems that as I clone modules from my git repo some of them are not installed so I need to forcefully install them in the php script I run that adds my test stores and what not. I have looked through all manner of class and the best I have found is
isModuleOutputEnabled()
But that is not going to cut it. Ideas on how to do a forceful install?
---
possible identification of the issue
====================================
It seems that simple clearing the cache and calling the `Mage::app()` and even trying to log in a admin user fails to trigger the modules to install. But if you clear the cache by hand, right before the first time you go to the /admin login screen, it then will install things as you would expect. As of yet getting the page (`wget`) before clearing the cache also fails to install the modules.
---
Update 1
========
I have tried to do some forcing here, but I don't get what is going on... the extensions load fine when I wait till after the fresh install and just place the files in the folders, but when I clone it in beforehand I don't see it in the `core_resource` table or the table for the modules. Example test for the post install script is
```
$resource = Mage::getSingleton('core/resource');
$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;
echo "Test modules";
if(isset($modulesArray['Aoe_AsyncCache'])) {
echo "AsyncCache exists.";
$tableName = $resource->getTableName('asynccache');
/**
* if prefix was 'mage_' then the below statement
* would print out mage_catalog_product_entity
*/
echo "known as ".$tableName;
} else {
echo "AsyncCachedoesn't exist.";
}
```
When ran I see `AsyncCache exists. known as 'asynccache'` yet it is not in the database. That table was not installed. Not again, the module does install fine if I wait... But oddly, if I do this git clone, it never installs. I'm really unsure what is going on.
---
Update 2
========
I seems that any module that has a database tied to it is not being installed. So background on what is going on. I'm using `vagrant` and it's on a url of <http://local.mage.dev> as the url. Now when I use the provision.sh script, I have it install Magento from the ssh. I does in stall. But a great example of the issue is that when I so a simple,
```
./mage config-set preferred_state alpha
./mage clear-cache
./mage sync
./mage download community BL_CustomGrid
./mage install community BL_CustomGrid
```
The table is not installed. I don't get why. Magento is installed. If I wait for the first log in I can use connect to do the install. I get notice on the command line that it has install the BL\_CustomeGrid just fine, but it hasn't... the tables are not there.
---
Update3
=======
I tried to combine all the suggestions in to one. I have the Mage app being invoked after each github clone, then the cache is cleared. I then clear the cache one last time before I go to log in. I can't see to get the table installed. I almost wonder if it has something to do with the vagrant but seems unlikely being that Magento does install. But proof of what I did, here is the [sub question on calling the php script that is doing nothing but invoking mage and clearing the cache.](https://stackoverflow.com/questions/18797273/need-to-call-a-php-script-from-bash-script-through-eval/18797468#comment27732062_18797468)
---
Update4
=======
Important note:
===============
I have not only done a test where I reconfirmed that if I do the install after the magento install. The normal log in, upload files, clear cache, log out, log back in and the module is installed. BUT when I add a programmatically login of the admin user, I echo that the user is loged in, and even thou I clear the cache, it still fails.
The goal is that one, I need to find the `install('module_name')` or something like that, or two, be able to 100% do what happens when the user signs in clears caches and logs back out.
***Programmatic replication of how a module is installed we know (logout,clear cache,etc..) fails***
---
---
The scripts in play
===================
The script that invokes install-invoke-app.php And so there is full context, here is the function.sh that is called and where you can see that the invoking of Mage is done
***provision.sh***
This is what is called from `vagrant` which will configure my test bed and install a full Magento install programmatically
```
start_seconds=`date +%s`
echo -en "\a" > /dev/tty5 | echo -e "\a"
cd /srv/www/
. scripts/install-functions.sh
if [[ has_network ]]
then
apt-get install pv
cd /srv/www/
. scripts/install-prep.sh
cd /srv/www/
. scripts/main-install.sh
else
echo -e "\nNo network connection available, skipping package installation"
fi
#double check the network
if [[ has_network ]]
then
#check and install wp
cd /srv/www/
. scripts/db-install.sh
#check and install magento
cd /srv/www/
. scripts/mage-install.sh
else
echo -e "\nNo network available, skipping network installations"
fi
# Add any custom domains to the virtual machine's hosts file so that it
# is self-aware. Enter domains space delimited as shown with the default.
DOMAINS='local.mage.dev'
if ! grep -q "$DOMAINS" /etc/hosts
then echo "127.0.0.1 $DOMAINS" >> /etc/hosts
fi
end_seconds=`date +%s`
echo "-----------------------------"
```
***install-functions.sh***
This is just some of the functions of this bash script. It's only what is used in this set of the server install. Note that this is where we are calling `php "/srv/www/scripts/mage/install-invoke-app.php"` which is what should be invoking the MAGE and installing any modules. Now the extensions should have programmatically been installed. ***This is not happening.***
```
install_repo(){
if [ $2 ]
then
echo "just 1"
git clone $1 -q
else
echo "just 1 and 2"
git clone $1 $2 -q
fi
success=$?
if [[ $success -eq 0 ]];
then
echo "Repository successfully cloned."
echo "cleaning"
cd $r/
rm -rf LICENSE.txt STATUS.txt README.md RELEASE_NOTES.txt modman
cd ../
cp -af $r/* .
rm -rf $r/
#eval $3
php "/srv/www/scripts/mage/install-invoke-app.php"
#if [ -z "$3" ]
#then
# echo "no callback"
#else
# eval $3
#fi
else
echo "Something went wrong!"
fi
sleep 1 # slow it down to insure that we have the items put in place.
}
#declare -A list = ( [repo]=gitUser )
install_repolist(){
gitRepos=$1
for r in "${!gitRepos[@]}" #loop with key as the var
do
giturl="git://github.com/${gitRepos[$r]}/$r.git"
echo "Adding $r From $giturl"
if [ -z "$r" ];
then
echo
else
install_repo $giturl $2 $3
fi
echo
done
return 1
}
```
***install-mage.sh***
This is called after the provision.sh script has installed all the basics of the server. It should already have `nginx` and `php5`/`php-fpm` and all the rest of the modules needed.
```
#!/bin/bash
cd /srv/www/mage/ #move to the root web folder
dbhost="localhost"
dbname="mage"
dbuser="devsqluser"
dbpass="devsqluser"
url="local.mage.dev"
adminuser="admin"
adminpass="admin2013"
adminfname="Mc"
adminlname="Lovin"
adminemail="test.user@wsu.edu"
echo
echo "We will clear any past install"
echo
echo "--Clear old caches reports and sessions"
cd /srv/www/mage/ #move to the root web folder
rm -rf ./var/cache/* ./var/session/* ./var/report/* ./var/locks/*
rm -rf ./var/log/* ./app/code/core/Zend/Cache/* ./media/css/* ./media/js/*
echo
if [ -f /srv/www/scripts/mage/clean.sql ]
then
mysql -u root -pblank $dbname < /srv/www/scripts/mage/clean.sql | echo -e "\n Initial custom mage cleaning MySQL scripting..."
else
echo -e "\n COUNLDN'T FIND THE CLEANER SQL FILE"
fi
echo "Now installing Magento with sample data..."
#chack to see if there is already the files ready for instalation
if [ ! -f /srv/www/mage/app/Mage.php ]
then
if [ ! -f /srv/www/mage/magento-1.7.0.2.tar.gz ]
then
echo
echo "didn't find the packages, so now Downloading them..."
echo
wget http://www.magentocommerce.com/downloads/assets/1.7.0.2/magento-1.7.0.2.tar.gz
wget http://www.magentocommerce.com/downloads/assets/1.6.1.0/magento-sample-data-1.6.1.0.tar.gz
fi
echo
echo "Extracting data..."
echo
pv -per magento-1.7.0.2.tar.gz | tar xzf - -C ./
pv -per magento-sample-data-1.6.1.0.tar.gz | tar xzf - -C ./
echo
echo "Moving files..."
echo
cp -af magento-sample-data-1.6.1.0/media/* media/
cp -af magento-sample-data-1.6.1.0/magento_sample_data_for_1.6.1.0.sql data.sql
cp -af magento/* magento/.htaccess .
cd /srv/www/mage/ #move to the root web folder
echo
echo "Setting permissions..."
echo
chmod o+w var var/.htaccess app/etc
chmod -R o+w media
fi
echo
echo "Installing Adminer..."
if [ ! -f /srv/www/mage/adminer.php ]
then
wget http://downloads.sourceforge.net/adminer/adminer-3.7.1-mysql-en.php > adminer.php
fi
echo
echo "Importing sample products..."
mysql -h $dbhost -u $dbuser -p$dbpass $dbname < data.sql
#pear mage-setup .
#pear install magento-core/Mage_All_Latest-stable
#./mage mage-setup .
#./mage config-set preferred_state stable
echo
echo "Initializing PEAR registry..."
pear mage-setup .
echo
echo "Downloading packages..."
pear install magento-core/Mage_All_Latest
echo
echo "Cleaning up files..."
rm -rf downloader/pearlib/cache/* downloader/pearlib/download/*
rm -rf magento/ magento-sample-data-1.6.1.0/
#rm -rf magento-1.7.0.2.tar.gz magento-sample-data-1.6.1.0.tar.gz data.sql
rm -rf index.php.sample .htaccess.sample php.ini.sample LICENSE.txt
rm -rf STATUS.txt LICENSE.html LICENSE_AFL.txt RELEASE_NOTES.txt
echo
echo "Installing Magento..."
php -f install.php --\
--license_agreement_accepted yes \
--locale en_US \
--timezone America/Los_Angeles \
--default_currency USD \
--db_host $dbhost \
--db_name $dbname \
--db_user $dbuser \
--db_pass $dbpass \
--url $url \
--use_rewrites yes \
--skip_url_validation yes \
--use_secure no \
--secure_base_url "" \
--use_secure_admin no \
--admin_firstname "$adminfname" \
--admin_lastname "$adminlname" \
--admin_email "$adminemail" \
--admin_username "$adminuser" \
--admin_password "$adminpass"
if [ ! -f /srv/www/mage/app/etc/local.xml ]
then
echo "failed install try it again"
else
if [ -f /srv/database/init-mage.sql ]
then
mysql -u root -pblank < /srv/database/init-mage.sql | echo -e "\nInitial custom mage MySQL scripting..."
else
echo -e "\nNo custom MySQL scripting found in database/init-mage.sql, skipping..."
fi
cd /srv/www/mage/
echo "Starting to import base WSU modules from connect"
#./mage install http://connect20.magentocommerce.com/community Flagbit_ChangeAttributeSet
./mage config-set preferred_state alpha
./mage clear-cache
./mage sync
./mage download community Flagbit_ChangeAttributeSet
./mage download community BL_CustomGrid
./mage install community Flagbit_ChangeAttributeSet
#./mage install community BL_CustomGrid
echo "Starting to import base WSU modules fro github"
declare -A gitRepos
#[repo]=gitUser
gitRepos=(
[wsu_admin_base]=jeremyBass
[wsu_base_theme]=jeremyBass
[Storeutilities]=jeremyBass
[StructuredData]=jeremyBass
#[Storeuser]=jeremyBass
[sitemaps]=jeremyBass
[webmastertools]=jeremyBass
[ldap]=jeremyBass
[Aoe_FilePicker]=jeremyBass #https://github.com/fbrnc/Aoe_FilePicker.git
[Aoe_ClassPathCache]=jeremyBass #https://github.com/fbrnc/Aoe_ClassPathCache.git
[Aoe_Profiler]=jeremyBass #https://github.com/fbrnc/Aoe_Profiler.git
[Aoe_ManageStores]=jeremyBass #https://github.com/fbrnc/Aoe_ManageStores.git
[Aoe_LayoutConditions]=jeremyBass #https://github.com/fbrnc/Aoe_LayoutConditions.git
[Aoe_AsyncCache]=jeremyBass #https://github.com/fbrnc/Aoe_AsyncCache.git
[Aoe_ApiLog]=jeremyBass #https://github.com/fbrnc/Aoe_ApiLog.git
#[mage-enhanced-admin-grids]=mage-eag
)
cd /srv/www/mage/
install_repolist $gitRepos 0 "wget http://$url"
unset gitRepos #unset and re-declare to clear associative arrays
declare -A gitRepos
cd /srv/www/mage/
echo "importing WSU favicon"
wget -q http://images.dev.edu/favicon.ico -O favicon.ico
#run actions that are hard to do direct sql quries on
php /srv/www/scripts/mage/install-post.php
echo
echo "doing the first index"
echo
cd shell && php -f indexer.php reindexall
mysql -u root -pblank $dbname -e "DELETE FROM $dbname.adminnotification_inbox;" | echo -e "\n >> Removed admin notifications ..."
# Enable developer mode
#if [ $MAG_DEVELOPER_MODE == 1 ]; then
# sed -i -e '/Mage::run/i\
#Mage::setIsDeveloperMode(true);
#' -e '1,$s//Mage::run/' $WWW_PATH/index.php
#fi
echo
echo "Finished installing Magento"
echo
fi
```
***install-post.php***
This file happens after the install-mage.sh file has completed the Magento install. All modules have been downloaded and ***what we need is to have had all the module's tables installed. IE: the sql installs for the modules should have been ran by now***
```
<?php
//just as a guide, no real purpose
echo getcwd() . " (working from)\n";
//set up the store instance
require_once "app/Mage.php";
umask(0);
Mage::app();
Mage::app()->getTranslator()->init('frontend');
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::registry('isSecureArea'); // acting is if we are in the admin
Mage::app('admin')->setUseSessionInUrl(false);
Mage::getConfig()->init();
/**
* Get the resource model
*/
$resource = Mage::getSingleton('core/resource');
/**
* Retrieve the read connection
*/
$readConnection = $resource->getConnection('core_read');
/**
* Retrieve the write connection
*/
$writeConnection = $resource->getConnection('core_write');
// switch off error reporting
error_reporting ( E_ALL & ~ E_NOTICE );
$changeData = new Mage_Core_Model_Config();
echo "applying default store settings\n";
//pattern
//\((.*?), '(.*?)', (.*?), '(.*?)', '?(.*?)'?\),
//$changeData->saveConfig('$4', "$5", 'default', 0);
echo " - applying design settings\n";
$changeData->saveConfig('design/package/name', "wsu_base", 'default', 0);
$changeData->saveConfig('design/theme/template', "default", 'default', 0);
$changeData->saveConfig('design/theme/skin', "default", 'default', 0);
$changeData->saveConfig('design/theme/layout', "default", 'default', 0);
$changeData->saveConfig('design/theme/default', "default", 'default', 0);
$changeData->saveConfig('design/theme/locale', "NULL", 'default', 0);
function make_store($categoryName,$site,$store,$view){
//#adding a root cat for the new store we will create
// Create category object
$category = Mage::getModel('catalog/category');
$category->setStoreId(0); // No store is assigned to this category
$rootCategory['name'] = $categoryName;
$rootCategory['path'] = "1"; // this is the catgeory path - 1 for root category
$rootCategory['display_mode'] = "PRODUCTS";
$rootCategory['is_active'] = 1;
$category->addData($rootCategory);
$rootCategoryId=0;
try {
$category->save();
$rootCategoryId = $category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}
if($rootCategoryId>0){
//#addWebsite
/** @var $website Mage_Core_Model_Website */
$website = Mage::getModel('core/website');
$website->setCode($site['code'])
->setName($site['name'])
->save();
//#addStoreGroup
/** @var $storeGroup Mage_Core_Model_Store_Group */
$storeGroup = Mage::getModel('core/store_group');
$storeGroup->setWebsiteId($website->getId())
->setName($store['name'])
->setRootCategoryId($rootCategoryId)
->save();
//#addStore
/** @var $store Mage_Core_Model_Store */
$store = Mage::getModel('core/store');
$store->setCode($view['code'])
->setWebsiteId($storeGroup->getWebsiteId())
->setGroupId($storeGroup->getId())
->setName($view['name'])
->setIsActive(1)
->save();
}
return $rootCategoryId;
}
echo "Applying the default multi-store setup\n";
$installed_stores = array();
$installed_stores['studentstore'] = make_store("Student store root",
array('code'=>'studentstore','name'=>'Student store'),
array('name'=>'Student Store'),
array('code'=>'studentstore','name'=>'base default veiw')
);
$installed_stores['teststore'] = make_store("Test store root",
array('code'=>'teststore','name'=>'Test store'),
array('name'=>'Test Store'),
array('code'=>'teststore','name'=>'base default veiw')
);
// let us refresh the cache
try {
$allTypes = Mage::app()->useCache();
foreach($allTypes as $type => $blah) {
Mage::app()->getCacheInstance()->cleanType($type);
}
} catch (Exception $e) {
// do something
error_log($e->getMessage());
}
$types = Mage::app()->getCacheInstance()->getTypes();
try {
echo "Cleaning data cache... \n";
flush();
foreach ($types as $type => $data) {
echo "Removing $type ... ";
echo Mage::app()->getCacheInstance()->clean($data["tags"]) ? "[OK]" : "[ERROR]";
echo "\n";
}
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
echo "\n";
try {
echo "Cleaning stored cache... ";
flush();
echo Mage::app()->getCacheInstance()->clean() ? "[OK]" : "[ERROR]";
echo "\n\n";
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;
echo "Test modules";
if(isset($modulesArray['Aoe_AsyncCache'])) {
echo "AsyncCache exists.";
$tableName = $resource->getTableName('asynccache');
/**
* if prefix was 'mage_' then the below statement
* would print out mage_catalog_product_entity
*/
echo "known as ".$tableName;
} else {
echo "AsyncCachedoesn't exist.";
}
```
***install-invoke-app.php***
```
<?php
//just as a guide, no real purpose
echo getcwd() . " (working from)\n";
//set up the store instance
require_once "app/Mage.php";
umask(0);
Mage::app();
Mage::app()->getTranslator()->init('frontend');
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::registry('isSecureArea'); // acting is if we are in the admin
Mage::app('admin')->setUseSessionInUrl(false);
Mage::getConfig()->init();
// switch off error reporting
error_reporting ( E_ALL & ~ E_NOTICE );
// let us refresh the cache
try {
$allTypes = Mage::app()->useCache();
foreach($allTypes as $type => $blah) {
Mage::app()->getCacheInstance()->cleanType($type);
}
} catch (Exception $e) {
// do something
error_log($e->getMessage());
}
$types = Mage::app()->getCacheInstance()->getTypes();
try {
echo "Cleaning data cache... \n";
flush();
foreach ($types as $type => $data) {
echo "Removing $type ... ";
echo Mage::app()->getCacheInstance()->clean($data["tags"]) ? "[OK]" : "[ERROR]";
echo "\n";
}
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
echo "\n";
try {
echo "Cleaning stored cache... ";
flush();
echo Mage::app()->getCacheInstance()->clean() ? "[OK]" : "[ERROR]";
echo "\n\n";
} catch (exception $e) {
die("[ERROR:" . $e->getMessage() . "]");
}
echo "finish invoking the mage app.";
//time to login as admin
Mage::app('admin')->setUseSessionInUrl(false);
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
// supply username
$user = Mage::getModel('admin/user')->loadByUsername('admin'); // user your admin username
if (Mage::getSingleton('adminhtml/url')->useSecretKey()) {
Mage::getSingleton('adminhtml/url')->renewSecretUrls();
}
$session = Mage::getSingleton('admin/session');
$session->setIsFirstVisit(true);
$session->setUser($user);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
Mage::dispatchEvent('admin_session_user_login_success',array('user'=>$user));
if ($session->isLoggedIn()) { echo "Logged in \n"; } else{ echo "Not Logged \n"; }
``` | 2013/09/10 | [
"https://magento.stackexchange.com/questions/7777",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/2242/"
] | Answer
======
It turns out that just clearing the cache and doing a wget, or login a user in programmatically, or even both was not enough to trigger the code to install a module.
This is what works.
```
rm -rf var/cache/*
php "/srv/www/mage/index.php"
```
Where `/mage` is the store root folder, I just needed to execute the `index.php` file and then it worked. I can't say why it wouldn't on `wget`, or why calling `MAGE:app()` and all combinations didn't work, but clearing the cache folder and calling the file is the ticket for stably rebuilding the cache from the command line.
Hope this saves someone some time. Cheers | Not sure if I got your question right but if you want to trigger setup script w/o opening the website in your browser why not just create the shell script which will just `wget` the home page of your Magento installation? |
5,300,070 | For a "dashboard" module I need to dynamically load user controls based on criteria as the user enters the page (role, etc). The problem is that the events are not being fired at all from the controls
As I understand it I need to load the controls in the OnPreInit method of the dashboard page, however I cannot get a reference to the Placeholder control at this point of initialization (i.e. I get a NullReferenceException); trying to load the Placeholder dynamically via `Page.FindControl` gives me, ironically, a StackOverflowException.
I've tried loading the controls in PreRender and OnInit as well but the events in the controls are not wired up properly and will not fire.
The code is basically this:
```
// this does not work; if I try to access the placeholder control itself
// ("phDashboardControls") I get a NullReferenceException, if I try
// Page.FindControl("phDashboardControls") I get a StackOverflowException
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
Control ph = Page.FindControl("phDashBoardControls"); // Placeholder
if (ph != null)
{
// GetControlsToLoad just instantiates the controls and returns
// an IList<Control>. Eventually it will have logic to
// determine which control needs to be loaded based on user role etc.
foreach (Control control in GetControlsToLoad())
{
ph.Controls.Add(control);
}
}
}
// IModularControl is a custom interface defining a single
// Initialize method to set up a control...
private void Page_Load(object sender, EventArgs e)
{
foreach (Control control in this.phDashboardControls.Controls)
{
if (control is IModularControl)
((IModularControl)control).Initialize(this.CompanyID);
}
}
``` | 2011/03/14 | [
"https://Stackoverflow.com/questions/5300070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40667/"
] | Use String.Equals() specifying case insensitivity. | Something like this?
```
var res = (from p in list where
(p.FirstName ?? "").ToUpper() == (firstName ?? "").ToUpper() ||
(p.LastName ?? "").ToUpper() == (lastName ?? "").ToUpper() select p)
.ToList<Client>();
```
It really depends on what you want to do when either is `null`. This should treat `null` as equivalent to an empty string for comparison purposes. |
10,651,161 | I have a class that uses a nested class, and want to use the nested class `operator<<` to define `operator<<` in the upper class. Here is how my code looks like:
```
#include <memory>
#include <iostream>
template<typename T>
struct classA {
struct classB
{
template<typename U>
friend inline std::ostream& operator<< (std::ostream &out,
const typename classA<U>::classB &b);
};
classB root;
template<typename U>
friend std::ostream& operator<< (std::ostream &out,
const classA<U> &tree);
};
template<typename T>
inline std::ostream& operator<< (std::ostream &out,
const classA<T> &tree)
{
out << tree.root;
return out;
}
template<typename T>
inline std::ostream& operator<< (std::ostream &out,
const typename classA<T>::classB &b)
{
return out;
}
int main()
{
classA<int> a;
std::cout << a;
}
```
* When compiling without support for C++11, the definition of operator<< for the inner class seems not to be found by the compiler:
```
so.hpp:24:7: error: no match for ‘operator<<’ in ‘out << tree.classA<int>::root’
so.hpp:24:7: note: candidates are: ...
```
* With GCC 4.6 and 4.7 when compiling with std=c++0x:
```
so.hpp:21:3: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
In file included from /usr/include/c++/4.7/iostream:40:0,
from so.hpp:2:
/usr/include/c++/4.7/ostream:600:5: error: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = classA<int>::classB]’
```
Can someone tell me why this code is not legal, and what's the best way to do what I want? | 2012/05/18 | [
"https://Stackoverflow.com/questions/10651161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760721/"
] | Bo provided the *reason* why this is happening (the type `T` is not deducible in the call to the nested `operator<<`. A simple workaround for this, and something that I recommend in general, not only here, is not befriending a template, but rather a single free function. For that you will need to *define* the function inline:
```
template<typename T>
struct classA {
struct classB
{
friend inline std::ostream& operator<< (std::ostream &out,
const classB &b) {
// definition goes here
}
};
classB root;
friend std::ostream& operator<< (std::ostream &out,
const classA<U> &tree) {
// definition goes here
}
};
```
There are a couple of differences among the two approaches. The most important one is that this approach will have the compiler define a non-templated overload for `operator<<` for each instantiation of the template, which because it is no longer a template, does not depend on deducing the arguments. Another side effects are that the approach is a little *tighter* (you are only befriending *one* function, while in your initial approach you befriended the template and all possible instantiations (which can be used as a loophole to gain access to your class internals). Finally the functions so defined will only be found through ADL, so there are less overloads of `operator<<` for the compiler to consider when the argument is not `ClassA<T>` or `ClassA<T>::ClassB`.
---
*How access can be gained with your approach*
```
namespace {
struct intruder {
ClassA & ref;
intruder( ClassA& r ) : ref(r) {}
};
template <>
std::ostream& operator<< <intruder>( std::ostream& _, ClassA<intruder> const& i ) {
std::cout << i.ref.private_member << std::endl;
return _;
}
}
```
*Alternative*
Alternatively you can befriend a particular specialization of a template. That will solve the `intruder` problem, as it will only be open to `operator<<` to `ClassA<intruder>`, which has a much lesser impact. But this will not solve your particular issue, as the type would still not be deducible. | Try this:
```
template<typename T>
inline std::ostream& operator<< (std::ostream &out,
const classA<T> &tree)
{
//out << tree.root;
::operator<<( out, tree.root);
return out;
}
```
and then you will get a straightforward confession of ineptitude:
```
test.cpp:34:3: error: no matching function for call to ‘operator<<(std::ostream&, const classA<int>::classB&)’
test.cpp:34:3: note: candidates are:
test.cpp:23:22: note: template<class T> std::ostream& operator<<(std::ostream&, const typename classA<T>::classB&)
test.cpp:30:22: note: template<class T> std::ostream& operator<<(std::ostream&, const classA<T>&)
```
Workaround: maybe you can use a member function in nested classB, and use it instead of operator<< ... Of course, that solution has a multitude of drawbacks, but it may get you out of this hurry. |
44,275,882 | I am getting the response from ajax as json:
```
{"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}
```
I need to separate these values in javascript like 2017-05-11, 2017-05-18, etc.
I tried split function in javascript but it failed. How do I achieve it?
I need the dates separately in a loop. | 2017/05/31 | [
"https://Stackoverflow.com/questions/44275882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5576232/"
] | You just use method parse of JSON. After that, you receive array value for property "checkin\_date". Just use it as normal array. See code below:
```js
var json = '{"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]}';
var result = JSON.parse(json);
var checkin_date = result['checkin_date'];
for(var i=0; i<checkin_date.length; i++){
console.log(checkin_date[i]);
}
``` | If you need to loop through each value as a date, you first need to convert the values. Take a look:
```js
var dates = {"checkin_date":["2017-05-11","2017-05-18","2017-05-23","2017-05-25"]};
dates
.checkin_date
.map(date => new Date(date)) // here you convert the string dates to values of type Date
.forEach(date => console.log(date)) // here you loop through every Date and do whatever you want, in this case I just logged the output.
``` |
315,637 | In ARCGis its possible to Clip your Data Frame so you just see the Data within the defined area. Like shown here:
<https://www.cdc.gov/dhdsp/maps/pdfs/GIS-Tips-Data-Frame-Clip-Function.pdf>
With this functions the loading of large WMS Basemaps Speeds up.
Is this possible in QGIS Map View? | 2019/03/15 | [
"https://gis.stackexchange.com/questions/315637",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/138792/"
] | In QGIS, you have powerful styling possibility called inverted polygons. Just take the clip polygon you need. Style it the way you want the outside. Then change the style to invert polygon. Screenshot is in french, please tell me if you need the same in english. Below I used a 80% opacity white inverted polygon.
The only thing is my answer doesn't physically "cut" the WMS underneath, it's just styling.
[](https://i.stack.imgur.com/tX6BU.png) | Perhaps **GDAL** helps here.
You can create a basemap using the GDAL WMS driver and clip it with *gdalwarp* to a virtual format file (**VRT**).
To increase loading performance, enable local caching inside the WMS description XML (<https://gdal.org/drivers/raster/wms.html>).
In the following example (basemap of Vienna) I'm using a small trick to add the WKT description of the image boundary via SQL ([gdalwarp cutline without using a shapefile](https://gis.stackexchange.com/questions/265997/gdalwarp-cutline-without-using-a-shapefile)).
With the GDAL config option "**GDALWARP\_DENSIFY\_CUTLINE**" set to "NO" we keep the VRT size small ([Very large VRT file generated by gdal after cutline](https://gis.stackexchange.com/questions/294591/very-large-vrt-file-generated-by-gdal-after-cutline/294681#294681)).
And here we go:
1.) Copy the following line into the OSGeo4W shell and press ENTER. If you get no VRT file, you have to change the path of the qgis.db and/or the path of the Cache directory and the resulting VRT file
```
gdalwarp -r near -of VRT --config GDALWARP_DENSIFY_CUTLINE NO -cutline "C:\OSGeo4W\apps\qgis\resources\qgis.db" -csql "select ST_GeomFromText('Polygon((1801649 6135190, 1803604 6132890, 1805904 6132085, 1804984 6131165, 1806249 6129210, 1806249 6127830, 1810964 6128635, 1814874 6127715, 1816139 6126680, 1817634 6129440, 1821888 6128520, 1825798 6127485, 1826718 6126680, 1829708 6126910, 1829593 6129900, 1831548 6130130, 1835228 6132890, 1838217 6133120, 1841437 6130820, 1845577 6129670, 1845232 6133465, 1843162 6134040, 1842012 6136225, 1841207 6136570, 1841552 6138755, 1841092 6140135, 1842127 6143354, 1842702 6146804, 1841207 6147034, 1842012 6150829, 1839597 6150599, 1837412 6152669, 1838562 6154739, 1834883 6155429, 1834653 6152554, 1830168 6155314, 1829708 6159683, 1827983 6160488, 1825568 6159683, 1824648 6160258, 1823383 6159339, 1823843 6157269, 1823038 6156349, 1822578 6154049, 1820623 6154164, 1820048 6155429, 1817634 6153014, 1813494 6151864, 1813839 6151174, 1812459 6149794, 1810504 6149104, 1809469 6146689, 1808204 6146689, 1807859 6148184, 1804179 6150599, 1803144 6148644, 1802454 6146574, 1802914 6145309, 1802339 6144159, 1803029 6143239, 1804294 6141744, 1803489 6138525, 1801649 6135190))')" -dstalpha "<GDAL_WMS><Service name='TMS'><ServerUrl>https://maps1.wien.gv.at/basemap/geolandbasemap/normal/google3857/${z}/${y}/${x}.png</ServerUrl></Service><DataWindow><UpperLeftX>-20037508.34</UpperLeftX><UpperLeftY>20037508.34</UpperLeftY><LowerRightX>20037508.34</LowerRightX><LowerRightY>-20037508.34</LowerRightY><TileLevel>15</TileLevel><TileCountX>1</TileCountX><TileCountY>1</TileCountY><YOrigin>top</YOrigin></DataWindow><Projection>EPSG:3857</Projection><BlockSizeX>256</BlockSizeX><BlockSizeY>256</BlockSizeY><BandsCount>3</BandsCount><UserAgent>QGIS</UserAgent><Cache><Path>c:/temp/gdalwmscache</Path><Extension>.png</Extension></Cache></GDAL_WMS>" vienna.vrt
```
2.) Drag & Drop the VRT file into QGIS map canvas. Unfortuantely, you won't see the basemap yet, even if you try to zoom to the extents. Looks like QGIS is not able to calculate the extents of the virtual raster. But you can insert the original XYZ layer with the URL "https://maps.wien.gv.at/basemap/geolandbasemap/normal/google3857/{z}/{y}/{x}.png" (Max. Zoom Level 18) and zoom to its extents. Then zoom to Vienna (Wien).
You will recognize, that the clipped image has a different zoom level than the XYZ layer. I guess this happens because QGIS processes the two datasources differently. But you can freeze/lock the maximum zoom level inside the WMS XML description to a lower value - i.e. 12 (search for "<TileLevel>"). With a lower max. level value you even prevent to get unreadable text labels in printouts.
[](https://i.stack.imgur.com/wDijI.jpg)
>
> Best of all, you can replace the GDAL datasource of your clipped basemap with the content of the VRT to store it directly in your QGIS project! Use the invaluable plugin "**changeDataSource**" for the replacement.
>
>
>
[](https://i.stack.imgur.com/jMhcA.jpg)
[](https://i.stack.imgur.com/mBWq5.jpg) |
50,540,742 | I have an `OnLongClickListener` attached to a view within my list item view (not on the `ListView` itself). Even though I return true in the `onLongClick` callback, `onItemClick` on the `ListView` is also called once the finger leaves the screen. Normally this doesn't happen but the long press triggers a `notifyDataSetChanged` on the adapter which seems to reset some state and register the touch up event a new item click.
I want to prevent this additional `onItemClick` from triggering. I have tried to invalidate the views and cancel pending input events but neither did the trick. | 2018/05/26 | [
"https://Stackoverflow.com/questions/50540742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/210130/"
] | I got the same issue while using docker toolbox. Using one more '/' before your source path as well as before your target path will resolve this problem. In your case it will look like this:
```
docker run -ti -h python -v /${pwd}://root/docker -p 9999:9999 ubuntu:latest /bin/bash
```
if this doesn't work then try using absolute path with extra '/' like this:
```
docker run -ti -h python -v //c/path_to_application://root/docker -p 9999:9999 ubuntu:latest /bin/bash
``` | I suggest you to use absolute path in windows, Something like:
```
docker run -ti -h python -v /c/path_to_application:/root/docker -p 9999:9999 ubuntu:latest /bin/bash
```
Add `/c/then_remaining_part_to_your_app`, note that `/c/` is the drive. |
152,070 | After installing CentOS 6.5 I removed Gnome Desktop Environment by running
```
yum groupremove Desktop
```
Now everything works fine, but whenever the computer starts there is no log-in prompt. The screen just shows CentOS progress bar. I have to press `Alt`+`Ctrl`+`F6` in order to switch to terminal and see the log-in prompt.
How can I configure CentOS to do this automatically? | 2014/08/25 | [
"https://unix.stackexchange.com/questions/152070",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/60154/"
] | Found the clean answer. Background - when installing the GUI by doing the
groupintstall remember that you had to set id:3:initdefault to id:5:initdefault in /etc/inittab before typing init 6 for root to boot the GUI.
So just reset /etc/iniittab back to id:3:initedefault BEFORE! for doing
groupremove.
What appears to happen is the system has no way of finding the prompt because it's
still readying itself for a GUI install.
It take about 30 seconds to a minute to get the prompt back so be patient. | Although not a good solution, but adding `chvt 2` (or any other valid virtual terminal number instead of 2) to `/etc/rc.local`
seems to work as a temporary solution for me. This makes OS to switch to tty2 automatically.
I'm still looking for a better solution (showing a log-in shell on tty1 instead of CentOS progress bar) |
9,137,706 | I have a BizTalk orchestration with an expression. The expression has the following:
```
construct msg_mymessage { msg_mymessage = msgInputXML; }
```
msgInputXML and msg\_mymessage use the same schema, same message type and both show up under the Messages in Orchestration view.
After the expression I have a Construct Message and in the Construct message I have a Transform that uses msg\_mymessage as a source and some other message as a destination.
I'm getting the errors:
use of unconstructed message 'msg\_mymessage'
'msg\_mymessage':message has not been initialized in construct statement
I'm not sure why I get this error. What should I be looking for? | 2012/02/04 | [
"https://Stackoverflow.com/questions/9137706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32892/"
] | Make sure that you use an assignment shape (inside a construct message wrapper) when you create msg\_mymessage. Then just copy the code in the expression shape (msg\_mymessage = msgInputXML;)
<http://msdn.microsoft.com/en-us/library/ee253499(v=bts.10).aspx> | In your constructed messages shape, you need to define the message type you are going to create. when you drop the shape, the drop down dialog will ask you what type of message you are constructing. You can select more than one. so if you happen to have a message checked that isnt being constructed in this shape, you will get this exact message also. |
26,240,304 | I am experiencing a weird issue on an iOS app that I have never seen before.
Push notifications are coming through when the user is in the application. I have logic that draws a custom view when the proper method is triggered in the AppDelegate upon receiving the push notification.
However, if the user backs out of the app to the home screen, iOS is not showing any push notifications for the app anymore. My understanding is that this part is handled at the OS level. It should automatically set the badge number and show a pop-up which the user can engage to jump into the app from the push notification.
Any ideas? | 2014/10/07 | [
"https://Stackoverflow.com/questions/26240304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2913347/"
] | Apple change the way push notifications request permissions in iOS 8.
Seems like you are partially there as you receive the push when your app is open but this bit is extracted from the iOS SDK documentation.
If you want your app’s push notifications to display alerts, play sounds, or perform other user-facing actions, you must call the `registerUserNotificationSettings:` method to request the types of notifications you want to use. If you do not call that method, the system delivers all push notifications to your app silently. Because the registration process takes into account the user’s preferred notification settings, requesting access to user-facing notification types also does not guarantee that they will be granted. To find out what notification settings are available, use the `currentUserNotificationSettings` method.
So looks like your notifications don't have the permission to be shown to the user and are silently send to the app.
In any case if you can paste your code would be helpful for a more accurate answer. | This is a sample of push notification. If the field alert is empty, the push notification will not display a banner. When you're inside the app it will trigger the "didReceivePushNotification". Maybe the problem is alert field is empty. Im using this tool that simulates push. <https://github.com/noodlewerk/NWPusher>
```
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
}
}
``` |
74,860 | I recently upgraded from an iPhone 4s to iPhone 5. **How do I transfer all my apps to the new iPhone 5?** I have tried two times without success:
*First attempt:*
1. From iTunes, make "a full backup" of the 4s on "this computer."
2. From iTunes, restore the backup to the iPhone 5
This transferred all my contacts, call history, messages, and photos but all my 3rd party apps were missing. (Also messages I had received on the iPhone 5 before restoring were over-written... any way to prevent this?) The size of the resulting backup files was only 10GB; about the amount of photos and videos on my 4s. Note: I can view the list of my purchased 3rd party apps from the app store and download/install them one at a time. When I re-install the apps, they retain all their old data and even old icon locations.
*Second attempt:*
1. From iTunes, click 'Automatically sync new apps'
2. Again, make "a full backup" of the 4s on "this computer," (this time using the "Encrypt iPhone backup" in hopes my passwords would also be retained.)
3. Again, restore the backup to the iPhone 5
This time, the backup size was about 20GB. However, still no 3rd party apps were transferred except a few apps I had re-installed since the last restore.
When I view my apps on the 4s from iTunes (version 11.0.1.12) I see one significant difference from most [on-line instructions](https://apple.stackexchange.com/a/28241/14309). Although 99 apps are visible on the right, I am unable to select any of them because they are not listed on the left:

If it makes any differnce, my iPhones 4s still has iOS version 5.1.1 while the iPhone 5 has iOS version 6.
Also, at the end of the restore, the iPhone 5 seems to reboot automatically. However, after waiting for a long time, nothing happened so I restarted the phone manually.
**So how do I make a truly full backup of my iPhone 4s and fully restore it on my iPhone 5?** | 2012/12/14 | [
"https://apple.stackexchange.com/questions/74860",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/14309/"
] | I had the same issue (I use iTunes on Windows 7). I Bought a new iPhone 5 and used the Backup / Restore method to move my stuff from the old iPhone 4S to the new one. The process only restored all the Apple apps, plus Contacts, Phone Calls, and Messages. When I tried to backup again - hoping it would restore the rest - it went through a restore process in iTunes (for about 5 minutes) and then I got the message that my iPhone will restart but never did (I had to restart it manually).
What I also noticed was that, when I retried, the Backup seemed to be very quick.
I called Apple Support who said that there is a problem with the Backup process. I would be able to restore my Apps via the Purchased Apps process but I would lose all my user data (such as games progress). I was extremely frustrated because I use my iPhone and iPad as tools, not game devices.
I went to the App Store on the iPhone and started downloading some of the Purchased apps from the what seemed to be the iCloud. To my surprise, all app data was there (eg. WhatsApp chats, and The Vault data). I am not sure how this works because I never deliberatelly setup app backup on the cloud, but I **suspect** that the "Documents and Data" == "On" setting on Settings --> iCloud does exactly that, and in return does not include this information on the PC backup.
All seems fine now (at least for the apps for which I care and tried). The issue I still have is this uncertainty on what exactly is my iPhone doing and where is my stuff at any point in time. | Apps purchased are not contained in the backup, therefore they will not restore. They can be found in your iTunes, under apps purchased and can be downloaded again to your device. Appdata however is found in the backup - it can be extracted with software such as iPhone Backup Extractor, and then imported back to the device. Hope this helps! |
12,825,826 | I have a piece of code that hides an element on mouseout.
The code looks like this:
```
var myMouseOutFunction = function (event) {
setTimeout(function () {
$(".classToHide").hide();
$(".classToShow").show();
}, 200);
};
```
This produces a result very close to what I want to do. However, I want to wait the time on the timeout (in this case 200 ms) then check to see if my mouse is still "out" of the element. If it is, I want to do .hide() and .show() on the desired elements.
I want to do this because if a user slightly mouses out then quickly mouses back in, I don't want the elements to flicker (meaning: hide then show real quick) when the user just wants to see the element. | 2012/10/10 | [
"https://Stackoverflow.com/questions/12825826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1434239/"
] | Assign the timeout's return value to a variable, then use `clearTimeout` in the onmouseover event. | You should use `mouseenter` and `mouseleave` of jquery. mouseenter and mouseleave will get called only once.and use a flag if to check if `mouseenter` again called.
```
var isMouseEnter ;
var mouseLeaveFunction = function (event) {
isMouseEnter = false;
setTimeout(function () {
if(isMouseEnter ){ return;}
$(".classToHide").hide();
$(".classToShow").show();
}, 200);
};
var mouseEnterFunction = function(){
isMouseEnter = true;
}
``` |
6,485,705 | Tried the following example compiled with `g++ -std=gnu++0x t1.cpp` and `g++ -std=c++0x t1.cpp` but both of these result in the example aborting.
```
$ ./a.out
terminate called after throwing an instance of 'std::system_error'
what():
Aborted
```
Here is the sample:
```
#include <thread>
#include <iostream>
void doSomeWork( void )
{
std::cout << "hello from thread..." << std::endl;
return;
}
int main( int argc, char *argv[] )
{
std::thread t( doSomeWork );
t.join();
return 0;
}
```
I'm trying this on Ubuntu 11.04:
```
$ g++ --version
g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
```
Anyone knows what I've missed? | 2011/06/26 | [
"https://Stackoverflow.com/questions/6485705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13022/"
] | You have to `join` `std::thread`s, just like you have to join `pthreads`.
```
int main( int argc, char *argv[] )
{
std::thread t( doSomeWork );
t.join();
return 0;
}
```
**UPDATE:** [This Debian bug report](http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=576485) pointed me to the solution: add `-pthread` to your commandline. This is most probably a workaround until the `std::thread` code stabilizes and g++ pulls that library in when it should (or always, for C++). | For what it's worth, I had **different issue** with **similar code** using [threads](https://stackoverflow.com/questions/32580527/issue-with-stdthread-when-using-g-in-32-bit-mingw-4-8-0) in g++ (MinGW). Work-around was to put some "delay" between creating a thread and joining it.
Code with infrequently failing assertion:
```
std::atomic_bool flag{false};
std::thread worker( [&] () { flag.store(true); } );
worker.join();
assert(flag.load()); // Sometimes fails
```
Work-around:
```
std::atomic_bool flag{false};
std::thread worker( [&] () { flag.store(true); } );
while (not flag.load()) { std::this_thread::yield(); }
worker.join();
assert(flag.load()); // Works fine
```
Note that `yield()` alone did not help, hence the while loop. Using `sleep_for(...)` also works. |
33,716,978 | I am trying to toggle between a couple of texts, where the only one that shows is the one that was "turn on" most recently. For example, the default would look something like this:
Click A
Click B
If you click 'Click B', the text for that will toggle to something else, let's say "You've clicked B".
Click A
You've Clicked B
If you click 'Click A' right afterwards, then the previous text will go back to its default, ie "You've Clicked B" will revert back to 'Click B' and then 'Click A' will be turn on.
Right now, neither of them are toggling, they are just both on.
Here is what I have:
JavaScript
```
toggle_visibility("t1");
toggle_visibility("t2");
function toggle_visibility(id) {
function toggle(id){
var text = document.getElementById(id);
if(text.style.display == 'none'){
text.style.display = 'block';
}
else{
text.style.display = 'none';
}
}
toggle(id);
}
```
HTML
```
<div id="t1" <a href="Click A" onclick="toggle_visibility('t1');">
<h1>You've Clicked A</h1></div>
<div id="t2" <a href="Click B" onclick="toggle_visibility('t2');">
<h1>You've Clicked B</h1></div>
``` | 2015/11/15 | [
"https://Stackoverflow.com/questions/33716978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5447028/"
] | It's because you're calling `itertor.next()` twice inside your loop for every `iterator.hasNext()`.
You should do:
```
while(iterator.hasNext()) {
TrueFalseQuestion trueFalseQuestion = iterator.next();
System.out.println(trueFalseQuestion);
System.out.println(trueFalseQuestion.getPoints());
}
```
What happens in you're first iteration is that when you call:
```
System.out.println(iterator.next());
```
The first `TrueFalseQuestion` gets printed, however in the very next statement, when you do:
```
System.out.println(iterator.next().getPoints());
```
You're unknowingly printing the `points` of the second `TrueFalseQuestion`.
So, in you're second iteration, again when you do:
```
System.out.println(iterator.next());
```
The third `TrueFalseQuestion` is printed, and finally, on the very next line when you do:
```
System.out.println(iterator.next().getPoints());
```
There isn't a fourth `TrueFalseQuestion` and you get a `NullPointerException` because you are calling `getPoints()` on a `null` value. | array value in your program can not found your array so it display null pointer exception
notice that your array index start with 0 |
35,752,870 | I have a problem adding scrollbar to my JPanel. This is my code but it isn't working! I need help!
---
```
public class DocumentView extends JPanel implements EventListener,MouseListener{
public String name;
private Document document;
private Dimension dim;
public DocumentView dv;
JScrollPane scrollPane = new JScrollPane(dv,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public boolean selected = false;
public DocumentView() {
setBackground(Color.GRAY);
this.add(scrollPane);
setVisible(true);
addMouseListener(this); //za kontra focus
}
}
```
What is not working
-------------------
it is supposed to be a document and you can add pages in it...So when I add more than 2 pages in one document it can not show all it just adds them but I can't see them...that is way I need scroll bar....not working , I mean it doesn't add scroll when I add more than 2 pages. | 2016/03/02 | [
"https://Stackoverflow.com/questions/35752870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6008928/"
] | When adding a scrollbar, you need a panel and a scrollpane:
```
scrollPanel = new JPanel();
scrollPane = new JScrollPane(scrollPanel);
```
From now on, components added to the scollPanel will create a scrollbar(vertically and/or horizontally). The scrollbar will automatically adjust its height when new components are added because your scollPanel (JPanel) will have its preferredSize adjusted when new components are added/removed (if you use a layout). The layout manager will handle this for you.
[](https://i.stack.imgur.com/3aHC8.gif)
A working example as follows:
```
class MainPanel extends JPanel{
private JScrollPane scrollPane;
private JPanel scrollPanel;
private JButton btnAddPage;
public MainPanel(){
setPreferredSize(new Dimension(400, 140));
setLayout(new BorderLayout());
initComponents();
}
private void initComponents(){
scrollPanel = new JPanel();
scrollPanel.setSize(new Dimension(300, 300));
scrollPane = new JScrollPane(scrollPanel); //Let all scrollPanel has scroll bars
btnAddPage = new JButton("Add New Page");
btnAddPage.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
addPanel(new Page());
scrollPanel.revalidate();
}
});
add(scrollPane, BorderLayout.CENTER);
add(btnAddPage, BorderLayout.SOUTH);
}
public void addPanel(JPanel pnl){
scrollPanel.add(pnl);
}
}
```
A Page class to simulate the pages you wanted to add:
```
class Page extends JPanel
{
private static int idx = 1;
private JLabel pageContent;
public Page(){
setPreferredSize(new Dimension(80, 80));
setBackground(Color.YELLOW);
pageContent = new JLabel("Page " + (idx++));
add(pageContent);
}
}
```
A runner class to drive the codes:
```
class ScrollPaneDemo{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
JFrame frame = new JFrame("Scrollable Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
```
---
*PS: When dealing with scrollbars, you may have to carefully choose your layout the layout you choose will directly determine the dimension of your panel or even your added components, ultimately affecting the effectiveness of your scrollpane.* | Welcome to StackOverflow!
I'd like to give you some hints, so that you could solve your problem by yourself.
* The value of *dv* is empty when you it gets passed to the constructor of JScrollPane
* Take a look at the control hierarchy. You are creating a class for your DocumentView that will contain a JScrollPane that contains a DocumentView. I assume you want to make your DocumentView scrollable. Consider wrapping the whole control inside an independent JScrollPane (at a higher level).
* Tip: Try to set every instance variable (also called "fields") to private. Public fields are very rare.
**Regarding the control hierarchy**
There are two ways I'd like to recommend
1. Dedicated controls: You could create a dedidcated Document- and PageView class. DocumentView could inherit from JPanel and would contain the JScrollPane. The JScollPane wraps another JPanel with FlowLayout (vertical). Every time a new page is added to the DocumentView it will create a new instance of your PageView and add it to the JPanel that is wrapped inside your JScrollPane. The PageView simply displays the content.
2. Assuming you have infinite space: This is the way most Swing components are designed. Create a DocumentView that assumes that there is infinite space. Simply align every page vertically (one after another). Then you should overwrite the *getPreferredSize* method and return the size your control takes up. No you can simply wrap your whole DocumentView inside a JScrollPane. |
56,871,202 | I need to export from Excel as CSV using VBScript. The database I'm importing the CSV into wants the data to be in quotes.
```
' Set output type constant
Const xlCSV = 23
Const xlYes = 1
Const xlAscending = 1
Const xlDescending = 2
' Open Excel in background
Set objExcel = CreateObject("Excel.Application")
objExcel.DisplayAlerts = FALSE
' Make Excel object visible
objExcel.visible = TRUE
' Open source file
Set obj2 = objExcel.Workbooks.open("\\ntptc\Public\test\bins\DomesticCollectionItemsV2.csv")
' Set data format
obj2.Worksheets("DomesticCollectionItemsV2").range("D:E").NumberFormat = "0"
obj2.Worksheets("DomesticCollectionItemsV2").range("Q:R").NumberFormat = "dd/mm/yyyy"
obj2.Worksheets("DomesticCollectionItemsV2").range("X:Y").NumberFormat = "dd/mm/yyyy"
'Sort data
Set objWorksheet = obj2.Worksheets(1)
Set objRange = objWorksheet.UsedRange
Set objRange1 = objExcel.Range("N1")
Set objRange2 = objExcel.Range("O1")
objRange.Sort objRange1,xlYes
' Remove duplicates
obj2.Worksheets("DomesticCollectionItemsV2").range("A:EE").RemoveDuplicates Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15), xlYes
obj2.Worksheets("DomesticCollectionItemsV2").range("A:EE").RemoveDuplicates Array(12,13,14,15,16,17,18,19,20,21,22,23,24,25), xlYes
' Remove Expired and erroneous data
Dim myRow
For myRow = 5000 To 1 Step -1
If (obj2.Worksheets("DomesticCollectionItemsV2").Cells(myRow, 14).Value = "Expired") Then
obj2.Worksheets("DomesticCollectionItemsV2").Rows(myRow).EntireRow.Delete
End If
If (obj2.Worksheets("DomesticCollectionItemsV2").Cells(myRow, 14).Value = "Quotation") Then
obj2.Worksheets("DomesticCollectionItemsV2").Rows(myRow).EntireRow.Delete
End If
Next
'Sort data
objRange.Sort objRange1, xlAscending, objRange2, , xlAscending, , , xlYes
' Remove Expired and erroneous data
Dim myRow1
For myRow1 = 10000 To 1 Step -1
If (obj2.Worksheets("DomesticCollectionItemsV2").Cells(myRow1, 15).Value = "Assisted Collection Contract") Then
obj2.Worksheets("DomesticCollectionItemsV2").Rows(myRow1).EntireRow.Delete
End If
If (obj2.Worksheets("DomesticCollectionItemsV2").Cells(myRow1, 15).Value = "Clinical Waste Collection Service Contract") Then
obj2.Worksheets("DomesticCollectionItemsV2").Rows(myRow1).EntireRow.Delete
End If
If (obj2.Worksheets("DomesticCollectionItemsV2").Cells(myRow1, 15).Value = "NULL") Then
obj2.Worksheets("DomesticCollectionItemsV2").Rows(myRow1).EntireRow.Delete
End If
Next
' Open template
Set obj1 = objExcel.Workbooks.open("\\ntptc\Public\test\bins\toby\When-is-my-bin-day(new3).xlsx")
' Copy from source file to template
obj2.Worksheets("DomesticCollectionItemsV2").range("A1:AE110000").copy
obj1.Worksheets("DataTransform").range("A:AE").pastespecial
obj1.Worksheets("DataTransform").range("D:E").NumberFormat = "0"
obj1.Worksheets("DataTransform").range("Q:R").NumberFormat = "dd/mm/yyyy"
obj1.Worksheets("DataTransform").range("X:Y").NumberFormat = "dd/mm/yyyy"
' Close Source file
obj2.Close False
' Copy within template
obj1.Worksheets("DataTransform").range("AN:AP").copy
obj1.Worksheets("Export File").range("A:C").PasteSpecial -4163
'obj1.Worksheets("Export File").range("A:A").NumberFormat = "0"
obj1.Worksheets("Export File").range("C:C").NumberFormat = "dd/mm/yyyy"
obj1.Worksheets("DataTransform").range("AR:BB").copy
obj1.Worksheets("Export File").range("D:N").PasteSpecial -4163
' Remove duplicates
obj1.Worksheets("Export File").range("A:N").RemoveDuplicates Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14), xlYes
' Set worksheet to be exported
Set obj3 = obj1.Worksheets("Export File")
' Save output as CSV
obj3.SaveAs "\\ntptc\Public\test\bins\KESCollections.csv", xlCSV
' Close Template
obj1.Close False
' Close Excel
objExcel.Quit
```
If I add the quotes or format the cell in Excel to add the quotes, it outputs with three lots of quotes each side of the cell data.
I've tried formatting the columns as custom using `"\0\"` or `"\@\"`. I've tried adding the quotes in VBS but whatever I do I still get too many quotes in the CSV
Original output
```
100060018803,Garden Waste Collection Service,09/07/2019
```
Actual output
```
"""100060018803""","""Garden Waste Collection Service""","""09/07/2019"""
```
Desired output
```
"100060018803","Garden Waste Collection Service","09/07/2019"
```
Is there anyway to get it to output the CSV with just one set of quotes? | 2019/07/03 | [
"https://Stackoverflow.com/questions/56871202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11504559/"
] | `kubectl` expects exactly one namespace:
```
➜ / kubectl create ns
error: exactly one NAME is required, got 0
```
depending on your shell you could pack it into a loop. here's an example for bash and zsh:
```
➜ / foreach ns (ns1 ns2 ns3); kubectl create ns $ns; end
``` | You could chain together 2 kubectl commands like so:
```
kubectl create ns app1 && kubectl create ns app2...
``` |
16,023,657 | I would like migrate this code with ARC.
I know I have to use :
```
@autoreleasepool {}
```
But I have a problem with the two pool drain, I don't know how to do.
```
- (void)downloadImageToCache:(NSString*)_urlImage
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (!(_urlImage) || (_urlImage == nil))
{
[pool drain];
return;
}
NSURL *url = [NSURL URLWithString:_urlImage];
NSData *data = [[[NSData alloc] initWithContentsOfURL:url] autorelease];
if (data != nil)
{
...do something...
}
else
{
...do something...
}
[pool drain];
}
``` | 2013/04/15 | [
"https://Stackoverflow.com/questions/16023657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2123039/"
] | You can just "early-return" from the autorelease pool, that will release
all objects from the pool:
```
- (void)downloadImageToCache:(NSString*)_urlImage
{
@autoreleasepool {
if (!(_urlImage) || (_urlImage == nil))
{
// no need (not allowed) to call `drain`
return;
}
NSURL *url = [NSURL URLWithString:_urlImage];
NSData *data = [[[NSData alloc] initWithContentsOfURL:url] autorelease];
if (data != nil)
{
...do something...
}
else
{
...do something...
}
// no need (not allowed) to call `drain`
}
}
``` | With the new @autorelease block syntax, the pool will be drained when execution exits the block. So you can just do this:
```
- (void)downloadImageToCache:(NSString*)_urlImage
{
@autoreleasepool {
if (!(_urlImage) || (_urlImage == nil))
{
return; //leaves @autoreleasepool block, automatically drains
}
NSURL *url = [NSURL URLWithString:_urlImage];
NSData *data = [[[NSData alloc] initWithContentsOfURL:url] autorelease];
if (data != nil)
{
...do something...
}
else
{
...do something...
}
} //leaves @autoreleasepool block, automatically drains
}
```
See [AutoreleasePools](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html) for more information |
64,880,675 | I see a lot of exercises that put onComplete but with my code this is the error
The getter 'onComplete' isn't defined for the type 'UploadTask'.
Try importing the library that defines 'onComplete', correcting the name to the name of an existing getter, or defining a getter or field named 'onComplete'
WHY ??
```
void uploadImage() async {
if (safeNeuralNetwork()) {
//Subir imagen a firebase storage
final Reference postImageRef =
FirebaseStorage.instance.ref().child("Post Images");
var timeKey = DateTime.now();
print(sampleImage);
UploadTask uploadTask =
postImageRef.child(timeKey.toString() + ".jpg").putFile(sampleImage);
var imageUrl =
await (await uploadTask.onComplete).ref.getDownloadURL();
url = imageUrl.toString();
print(url);
// Guardar el post en la bbdd
saveToDatabase(url);
//Regresar en Home
Navigator.pop(context);
}
}
``` | 2020/11/17 | [
"https://Stackoverflow.com/questions/64880675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13181371/"
] | Thank you very much it works. This is the final code
```
print(sampleImage);
UploadTask uploadTask =
postImageRef.child(timeKey.toString() + ".jpg").putFile(sampleImage);
print('aaa');
print(uploadTask);
var imageUrl = await (await uploadTask).ref.getDownloadURL();
url = imageUrl.toString();
print(url);
// Guardar el post en la bbdd
``` | Use the TaskSnapshot class instead. You don't need onComplete.
Example:
```
TaskSnapshot taskSnapshot = await uploadTask;
``` |
9,739,223 | How to find the below pattern is there or not in a given string using Regex or any other methods in C#
```
NAME <some text here> RANK
```
The spaces coming after NAME,before RANK and after RANK should be considered. The text between <> will vary. | 2012/03/16 | [
"https://Stackoverflow.com/questions/9739223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1127849/"
] | Use:
```
var result = Regex.IsMatch(input, @"NAME\s.*?\sRANK\s{3}");
``` | From the requirements, these might work (I'm still not sure about some of the boundry conditions in your description).
`NAME(?=[ ]).+?(?<=[ ])RANK(?=[ ])`
or
`(?<=^|[ ])NAME(?=[ ]).+?(?<=[ ])RANK(?=[ ]|$)`
The dot doesen't include newlines. It can be replaced with [\s\S] or you can simply add (?s) at the begining to include them. |
44,624,495 | I have one simple json
```
{
"subjectObj": [{
"id": "1",
"option": "java"
}, {
"id": "2",
"option": "c++"
},{
"id": "3",
"option": "c"
}]
}
```
I just want to display this json as `ul`.I did this using jquery but I want to do it java script.
```
function OnSuccess(data) {
$.each(data, function() {
$("#ulCategory").append("<li>" + this.option + "</li>");
});
}
<body>
<div id="ulCategory"></div>
</body>
``` | 2017/06/19 | [
"https://Stackoverflow.com/questions/44624495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7378551/"
] | The DOM way ("pure javascript way") for this would be (assuming ES5!):
```js
function OnSuccess(data) { // assuming data is the array from subjectObj, otherwhise use data data.subjectObj for the loop
var ulCategory = document.getElementById('ulCategory');
for (var i = 0; i < data.length; i++) { // replacing the $.each loop
var liEl = document.createElement('li'); // create the element
liEl.innerText = data[i].option; // add the text (if it would be HTML add liEl.innerHTML but be sure you know and parse what you insert, othrewhise you will open for XSS injections
ulCategory.append(liEl); // append it to your ul
}
}
```
**EDIT**: moved the DOM lookup to a variable for performance reasons from suggestions of the comments. | change your function as below, You need to loop through the array that is `data.subjectObj`
```
function OnSuccess(data) {
$.each(data.subjectObj, function(index) {
debugger;
$("#ulCategory").append("<li>" + this.option + "</li>");
});
}
``` |
6,931,951 | Is there some function, similar to `srand()`, that I need to call to make sure that `std::random_shuffle()` always produces different results? i.e. if I call it several times with the same data, I want the order to be different every time. How can I make sure of that? | 2011/08/03 | [
"https://Stackoverflow.com/questions/6931951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561309/"
] | random\_shuffle is deprecated since C++14 (removed in C++17) and replaced with shuffle (exists since C++11)
<http://en.cppreference.com/w/cpp/algorithm/random_shuffle>
possible usage:
```
shuffle(items.begin(), items.end(), std::default_random_engine(std::random_device()()));
``` | Generally call `srand(time(NULL))` **before** calling `std::random_shuffle()` would give you what you need, it give you different result each time you call `std::random_shuffle()`. It's because `std::random_shuffle()` internally calls `rand()` in many popular implementations (e.g. VS-2008 and GCC).
Of course you can supple a RNG yourself if you want to call the other overloaded `std::random_shuffle` with a extra parameter. |
2,686,032 | Please help I am in major trouble with our production database. I had accidentally inserted a key with a very large value into an autoincrement column, and now I can't seem to change this value without a huge rebuild time.
```
ALTER TABLE tracks_copy AUTO_INCREMENT = 661482981
```
Is super-slow.
How can I fix this in production? I can't get this to work either (has no effect):
```
myisamchk tracks.MYI --set-auto-increment=661482982
```
Any ideas?
Basically, no matter what I do I get an overflow:
```
SHOW CREATE TABLE tracks
CREATE TABLE tracks (
...
) ENGINE=MYISAM AUTO_INCREMENT=2147483648 DEFAULT CHARSET=latin1
``` | 2010/04/21 | [
"https://Stackoverflow.com/questions/2686032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/120237/"
] | After struggling with this for hours, I was finally able to resolve it. The auto\_increment info for myISAM is stored in TableName.MYI, see state->auto\_increment in <http://forge.mysql.com/wiki/MySQL_Internals_MyISAM>. So fixing that file was the right way to go.
However, myisamchk definitely has an overflow bug somewhere in the update\_auto\_increment function or what it calls, so it does not work for large values -- or rather if the current value is already > 2^31, it will not update it (source file here -- <http://www.google.com/codesearch/p?hl=en#kYwBl4fvuWY/pub/FreeBSD/distfiles/mysql-3.23.58.tar.gz%7C7yotzCtP7Ko/mysql-3.23.58/myisam/mi_check.c&q=mySQL%20%22AUTO_INCREMENT=%22%20lang:c>)
After discovering this, I ended up just using "xxd" to dump the MYI file into a hexfile, edit around byte 60, and replace the auto\_increment value manually in the hexfile. "xxd -r" then restores the binary file from the hex file. To discover exactly what to edit, I just used ALTER TABLE on much smaller tables and looked at the effects using diffs. No fun, but it worked in the end. There seems to be a checksum in the format, but it seems to be ignored. | Have you dropped the record with the very large key? I don't think you can change the auto\_increment to a lower value if that record still exists.
From the [docs on myisamchk](http://dev.mysql.com/doc/refman/5.1/en/myisamchk-other-options.html):
>
> Force AUTO\_INCREMENT numbering for new records to start at the given value (or higher, if there are existing records with AUTO\_INCREMENT values this large)
>
>
> |
22,934,823 | An `Intent` is a passive data structure that carries information from one `Activity` to another. An `Intent` is also capable of holding data in the form of name-value pairs (via `putExtra()`).
But while overriding the `onCreate()` method we pass a `Bundle` as the parameter, which ultimately also holds values in the form of name-value pairs and is able to store information with the help of `onSaveInstanceState()`.
In such a scenario why do we need both and what differentiates the two?
I suppose I have led you guys into a misbelief that I have misunderstood what an `Intent` is:
When I said "An `Intent` is a passive data structure that carries information from one `Activity` to another", what I intended to point out was that even an `Intent` can carry information (other than the context and action description) with the help of `putExtra()` method. Why do we need to use a `Bundle` then? | 2014/04/08 | [
"https://Stackoverflow.com/questions/22934823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/605123/"
] | From the source of **Intent** class, there really is no difference between the two. Check below code from Intent class:
```
public Intent putExtra(String name, String value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putString(name, value);
return this;
}
```
And
```
public Intent putExtras(Bundle extras) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putAll(extras);
return this;
}
```
So I think, only difference is **ease of use**.. :) for 1st, you don't need to create your bundle explicitly. | I think you already have understood what a `Bundle` is: a collection of key-value pairs.
However, an Intent is much more. It contains information about an operation that should be performed. This new operation is defined by the action it can be used for, and the data it should show/edit/add. The system uses this information for finding a suitable app component (activity/broadcast/service) for the requested action.
Think of the Intent as a Bundle that also contains information on who should receive the contained data, and how it should be presented. |
44,581 | I heard a lot about what food goes well with some sauce or drink. Why does someone say that? Based on what? Do they only try those foods together or is there any sort of property on the food that indicates what it goes well with? | 2014/06/01 | [
"https://cooking.stackexchange.com/questions/44581",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/22942/"
] | They say this because it is statistically very likely that, when a person with the same cultural background as the sayer eats the combination, that person will like what they eat.
This is *not* a restatement of your question: "A goes well with B" suggests that there is some quality in A and in B which determines how well they fit. But in fact, whether a person likes a thing is much more dependent on the person than on the thing. So, whether two foods go together depends on the eater, not on the food.
Kate Gregory already listed a few things eaters tend to like, but you can already see that it is a very mixed list. For example, she already mentions in point 3 that contrast can cause a good pairing, but in the last point, also says that similar levels of taste are considered a good pairing.
If you want to know why people like what they like, you need to ask a psychologist, not a cook. I have actually done research in that area (but not with a food focus), but explaining it in detail will take us too far from the topic of the site. For food taste (in general; not just for pairings), my observation is that there are two major drivers. The first is biological value: sugar, fat and to some extent salt are always liked, bitterness (which in nature is mostly found in alkaloids, which are frequently poisonous) is disliked. The second one is familiarity. In pairings, familiarity is the number one factor, my guess is that it makes much over 50% of the final judgement. | There are a lot of books/articles out there now that outline flavour pairings based on chemical components. While I agree with the original answer (great detail, carefully considered) I think food science (especially chemistry) deserves a bigger profile. Think of it like the periodic table of elements. There are only so many basic flavours, so you find matches in very strange places you wouldn't expect. Not a tasty example, but ever notice that cheap Parmesan smells a bit vomit-y? That borage flower (a common herb) tastes bizarrely like fresh oysters and cucumber-y? That's because they actually share important flavonoids. I guess chefs/food writers use this concept like painters use a colour wheel. If borage reminds tastebuds of oysters, maybe it would go well with the same ingredients that people traditionally pair with oysters, right? |
220,611 | For the console version of *Witcher 3*, is it possible to sort Inventory items like it is on the PC version? And if so, how do I do it?
As far as I know, at least, you can sort the Inventory as I recall seeing a "Sort" button at the bottom-left corner. | 2015/05/24 | [
"https://gaming.stackexchange.com/questions/220611",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/14598/"
] | On PS4, press L3 (clicking the left joy stick) then you'll get sorting options. It's a bit odd because it only sorts once you close. I usually hit L3 then close which defaults "sorting by type". You must of course be in the inventory view for this option.
I'm sure there is an equivalent for Xbox. Not sure what console you are using. | On the PS4 version of *Witcher 3: Wild Hunt*, you must open the inventory and press R3, which is pressing down on the right joystick. I'm not sure how to do it on the XBox version. |
1,764,970 | Can linq somehow be used to find the index of a value in an array?
For instance, this loop locates the key index within an array.
```
for (int i = 0; i < words.Length; i++)
{
if (words[i].IsKey)
{
keyIndex = i;
}
}
``` | 2009/11/19 | [
"https://Stackoverflow.com/questions/1764970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193315/"
] | For arrays you can use:
[`Array.FindIndex<T>`](http://msdn.microsoft.com/en-us/library/03y7c6xy.aspx):
```
int keyIndex = Array.FindIndex(words, w => w.IsKey);
```
---
For lists you can use [`List<T>.FindIndex`](http://msdn.microsoft.com/en-us/library/0k601hd9.aspx):
```
int keyIndex = words.FindIndex(w => w.IsKey);
```
---
You can also write a generic extension method that works for any [`Enumerable<T>`](http://msdn.microsoft.com/en-us/library/9eekhta0%28v=vs.110%29.aspx):
```
///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
int retVal = 0;
foreach (var item in items) {
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
```
---
And you can use LINQ as well:
```
int keyIndex = words
.Select((v, i) => new {Word = v, Index = i})
.FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;
``` | This solution helped me more, from [msdn microsoft](https://social.msdn.microsoft.com/Forums/vstudio/en-US/3d02c96a-b3db-4e67-9b54-c08dbb5cc988/row-number-in-linq-query?forum=csharpgeneral):
```
var result = query.AsEnumerable().Select((x, index) =>
new { index,x.Id,x.FirstName});
```
`query` is your `toList()` query. |
27,641,524 | I am trying to create a function which will dynamically set the value of whatever global variable is passed as a parameter. It's not working, and I'm trying to figure out why. Can someone please explain why this doesn't work:
```
var things = 5;
function setup(variable) {
variable = 7;
}
setup(things);
console.log(things); //should return 7. returns 5 instead. the function had no effect on the global variable
```
and this also doesn't work:
```
var things = 5;
function setup(variable) {
window.variable = 7;
}
setup(things);
console.log(things); //should return 7, but returns 5. still not accessing the global variable.
```
but this does:
```
var things = 5;
function setup(variable) {
window[variable] = 7;
}
setup("things");
console.log(things); //returns 7
```
I suspect that what is happening is that the parameter `variable` is being set as a local variable inside of the function, so any changes are only happening to the local version. But this seems strange because the parameter that's been passed is a global variable. Can someone explain to me what is happening and how to better write this code? Does this require a method (which can then use `this` to access the original object)?
Thanks!! | 2014/12/24 | [
"https://Stackoverflow.com/questions/27641524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2864935/"
] | Javascript is pass-by-value. (Objects, arrays, and other non-primitives are passed by value-of-reference.) That means that the value of the variable (or reference) is passed to the function, but the function parameter does not become an alias for the actual argument. Thus, you cannot change a variable outside a function without referencing it (as you do in your last example).
See [this answer in another thread](https://stackoverflow.com/a/13104500/535871) for more information. | When variables are passed as arguments to functions, a copy of their value is made and assigned to the name of the argument in the function.
For example:
```
function foo(a) {
a = 7; // sets the temporary variable(argument) a to 7
}
var bar = 24;
foo(bar); // copies bar's value and passes in the copy to foo
```
For a function to modify a variable itself, you would have to access it another way. In other languages there are things called pointers that point to a place in memory. This allows you to modify variables directly, as you have where they are located - you can simulate this with JavaScript:
```
var spam = 3;
var memory = ["bar", 29, "x", foo, false];
function foo(a) {
memory[a] = 7;
}
foo(3);
```
The above example sets an array called memory and fills it with random gibberish. Then, a function named `foo` is created that allows for the modification of elements in this memory array. |
315,778 | I just started using CCNet, and in the process of getting my build projects set up I racked up a lot of build history from trial and error. I really don't want to keep that old stuff around, but I can't seem to see where/how to get rid of it. I'm sure this is a silly question, and I apologize if I'm overlooking something that should be obvious. I did [RTM](http://confluence.public.thoughtworks.org/display/CCNET/Documentation) and Google for about a half hour, and poked around my CCNet installation, but it's not jumping out at me. I deleted the state files for the projects (don't know if that has anything to do with it), but the old builds are still there if I drill into a project's stats from the dashboard. Any suggestions? Thanks.
**Answered**: I had explicitly set the artifacts directory to a location that was not under the CCNet server directory and consequently never looked in it again... went looking and, disco, there's the build histories. | 2008/11/24 | [
"https://Stackoverflow.com/questions/315778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4296/"
] | Don't forget you can use [Artifact Cleanup Publisher](http://www.cruisecontrolnet.org/projects/ccnet/wiki/Artifact_Cleanup_Publisher) to keep your build history from growing to the size of Mars over time. | The logs are stored in the artifacts directories under artifacts\MyProjectName\Build\log\*.xml.
The State file stores things like the last build date, time, info.
Best to stop the service, and then delete the *.state in ProgFiles\CC.net\server and also delete the artifacts\MyProjectName\Build\log*.xml files. |
811,548 | I'm using sqlite3 in python 2.5. I've created a table that looks like this:
```
create table votes (
bill text,
senator_id text,
vote text)
```
I'm accessing it with something like this:
```
v_cur.execute("select * from votes")
row = v_cur.fetchone()
bill = row[0]
senator_id = row[1]
vote = row[2]
```
What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example:
```
bill = row['bill']
senator_id = row['senator_id']
vote = row['vote']
```
I know you can do this with MySQL, but does anyone know how to do it with SQLite?
Thanks!!! | 2009/05/01 | [
"https://Stackoverflow.com/questions/811548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I know you're not asking this, but why not just use sqlalchemy to build an orm for the database? then you can do things like,
```
entry = model.Session.query(model.Votes).first()
print entry.bill, entry.senator_id, entry.vote
```
as an added bonus your code will be easily portable to an alternative database, and connections and whatnot will be managed for free. | I use something like this:
```
class SqliteRow(object):
def __init__(self):
self.fields = []
def add_field(self, name, value):
self.fields.append(name)
setattr(self, name, value)
def to_tuple(self):
return tuple([getattr(self, x) for x in self.fields])
```
with this:
```
def myobject_factory(cursor, row):
myobject= MyObject()
for idx, col in enumerate(cursor.description):
name, value = (col[0], row[idx])
myobject.add_field(name, value)
return myobject
```
`MyObject()` is a class that inherits from `SqliteRow`.
SqliteRow class is a base class for every object that I want to have returned by a query.
Every column becomes an attribute and is logged into the `fields` list.
Function `to_tuple` is used to change the whole object to a form suitable for queries (simply pass the whole object and forget).
To get different class types of that function. You would need to make a factory object, that will generate objects based on the list of fields (for example: dict with { some\_unique\_value\_made\_of\_fields: class} )
This way I get a simple ORM. |
41,513,597 | I found that static files served from a Rails application running in `/home/pupeno/projectx` take more or less half as much time than the ones served from `/mnt/c/Users/pupeno/projectx`. It's almost acceptable. I tried webrick and puma (as well as passenger and unicorn, which don't work yet).
So, if I'm going to host my source code in `/home/pupeno`, how do I access from Windows applications such as RubyMine?
For the record, this is the application being served from the Windows file system:
[](https://i.stack.imgur.com/zy50W.png)
and this is the Linux file system:
[](https://i.stack.imgur.com/aTKSy.png) | 2017/01/06 | [
"https://Stackoverflow.com/questions/41513597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] | With Windows 10 [version 1903 and later](https://devblogs.microsoft.com/commandline/whats-new-for-wsl-in-windows-10-version-1903/), WSL filesystems are available in Windows via the `\\wsl$` mount. Either browse there manually or launch `explorer.exe` from a WSL path:
```sh
$ cd /home/me
$ explorer.exe .
```
If you have an existing WSL installation and you upgrade to Windows 1903 you may find that the `\\wsl$` mount doesn't work. Some users have found that [disabling and re-enabling WSL fixes the issue](https://github.com/microsoft/WSL/issues/4027#issuecomment-495816016).
In PowerShell:
```sh
Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
# Reboot when prompted
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
# Reboot when prompted
```
Disabling and re-enabling WSL didn't seem to harm my existing Ubuntu installation but it's probably worth backing up anything you want to save just in case. | fire the CLI command **explorer.exe \\wsl$** in Windows powershell/cmd |
41,905,253 | I am implementing a feature on the collectionView where user scrolls the collectionView at the bottom (20 items) and it requests another set of data (20 more items) from the server.
I have implemented the following two approaches. But I wonder which approach is better? or is there any other better approach which I am not aware of?
The first approach is to use the `indexPath` in the `cellForItemAtIndexPath` as follows
```
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
if(collectionView == productCollectionView)
{
__weak ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
// load more data
if(indexPath.row == numberOfItemsPerSection-1)
{
numberOfItemsPerSection += 20;
offset += 20;
[self loadFromURL];
}
// loading image and text happening here.
// it is not included here
return cell;
}
}
```
The second approach is to **scrollViewDidScroll** as follows
```
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (scrollView.contentOffset.y == scrollView.contentSize.height - scrollView.frame.size.height && pElements.count == numberOfItemsPerSection) {
numberOfItemsPerSection += 20;
offset += 20;
[self loadFromURL];
}
}
``` | 2017/01/28 | [
"https://Stackoverflow.com/questions/41905253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1669996/"
] | I do this thing through CollectionViewDelegate method like:
```
- (void)collectionView:(UICollectionView *)collectionView
willDisplayCell:(UICollectionViewCell *)cell
forItemAtIndexPath:(NSIndexPath *)indexPath{
if indexPath.row == numberOfitem.count-1 && !self.waiting {
waiting = true;
self.loadMoreData()
}
}
-(void)loadMoreData(){
// After getting the response then
[numberOfitem addObjects : your response in term of array];
waiting = false;
}
```
In swift 4.0
```
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// Note: ‘isWating’ is used for checking the paging status Is currency process or not.
if indexPath.section == self.dataSoruce.list.count - 2 && !isWating {
isWating = true
self.pageNumber += 1
self.doPaging()
}
}
private func doPaging() {
// call the API in this block and after getting the response
self.dataSoruce.append(newData);
self.tableView.reloadData()
self.isWating = false // it means paging is done and the user can able request another page request via scrolling the table view at the bottom.
}
``` | **Swift 3 :** CollectionView Delegate method
```
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.row == numberofitem.count - 1 { //numberofitem count
updateNextSet()
}
}
func updateNextSet(){
print("On Completetion")
//requests another set of data (20 more items) from the server.
}
``` |
7,143,805 | I user the innerHTML for the code:
```
<div>
<span id="tag"></span>
</div>
var i = 15;
function timer(){
var div = document.getElementById("tag");
i--;
setInterval(function(){
div.innerHTML = i;// use innerHTML
//div.removeChild(div.childNodes[0]);
//div.appendChild(document.createTextNode(i));
i--;
},15000);
}
timer();
```
the ff,safari,chrome is ok, but in ie8 value is no change; | 2011/08/22 | [
"https://Stackoverflow.com/questions/7143805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767177/"
] | It gets executed even if you return inside the try block. I put one return statement inside try as well as one inside finally and the value returned was from finally, not from try.
```
public class HelloWorld{
public static void main(String args[]){
System.out.println(printSomething());
}
public static String printSomething(){
try{
return "tried";
} finally{
return "finally";
}
}
}
```
The output I got was "finally." | When ever a method tries to return to the caller, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. |
4,113,469 | I am going to import some data, and I have the data available in either a JSON feed or a XML feed. I can't decide if I should use the XML or the JSON feed.
What are the pros and cons of choosing either feed, and what is your prefered choice? | 2010/11/06 | [
"https://Stackoverflow.com/questions/4113469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79465/"
] | XML mean more bytes on the wire: closing tags, by definition, mean XML will be larger than JSON for the same data.
XML tags are human readable meta-data for the data you send. If humans aren't reading it, what does it matter?
XML has XSD schemas for validation.
XML parsers are standard and ubiquitous.
I see both. JSON is starting to be used more and more.
Pick one. It probably doesn't matter much. I'd prefer JSON these days. | If you are importing/exporting data, and it needs to be in a reliable format, then I would suggest XML. Yes it is very bloaty, compared to JSON, but you do have the power of XSD Schemas, to make sure the data is in the correct format before you waste time importing it.
However, if you don't have XSD schemas, go with JSON. |
2,665,846 | Snippets:
```
private double memberVal;
public double MemberVal
{
get { return memberVal; }
set { memberVal= value; }
}
```
and
```
public double MemberVal
{
get; set;
}
``` | 2010/04/19 | [
"https://Stackoverflow.com/questions/2665846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205595/"
] | Almost. In the second example, `MemberVal` is not publicly accessible. | ```
private double memberVal;
public double MemberVal
{
get { return memberVal; }
set { memberVal= value; }
}
public double MemberVal
{
get; set;
}
```
second of the code-snippets is not supposed work on .net 2.0, coz it was introduced in .net 3.0.
The second is the short-hand notation for the first one but works only on .net 3.0 or higher. |
28,049,177 | I am not able to create vector mbtiles files for my city region (Nashik, Maharashtra, India), I am using nutiteq SDK for displaying Offline Maps. I have tried creating mbtiles using Mobile Atlas creator, but the output .mbtile file does not works in Nutiteq SDK.
Please assist on this. I only want to display a specific region .mbtiles in my App.
Thank You in Advance. | 2015/01/20 | [
"https://Stackoverflow.com/questions/28049177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4474556/"
] | MBTiles is general format which can contain also vector data (tiles), not only raster . Both TileMill and Mobile Atlas Creator can create only rasters, first one from vector data, and second one by scraping it from on-line APIs. You can use raster MBTiles with Nutiteq SDK, iOS sample:
```
// file-based local offline datasource
NSString* fullpathVT = [[NSBundle mainBundle] pathForResource:@"MBTILESFILENAME" ofType:@"mbtiles"];
NTTileDataSource* tileDataSource = [[NTMBTilesTileDataSource alloc] initWithMinZoom:0 maxZoom:19 path: fullpathVT];
// Initialize a raster layer with the previous data source
NTRasterTileLayer* rasterLayer = [[NTRasterTileLayer alloc] initWithDataSource:tileDataSource];
// Add the raster layer to the map
[[self getLayers] add:rasterLayer];
```
Android:
```
MBTilesTileDataSource tileDataSource = new MBTilesTileDataSource(
0, 19, filePath);
RasterTileLayer rasterLayer = new RasterTileLayer(tileDataSource);
mapView.getLayers().add(rasterLayer);
```
TileMill and Mobile Atlas Creator (MOBAC) does not support creating vector mbtiles. All the sources from where MOBAC gets data are raster ones, so it is not possible in principle. So there is no easy and free source to download the files as far as I know. I can suggest two options:
1. Use Nutiteq Maps service (subscription-based) which is currently in private beta. This works technically this way, that you define in your app which map package or packages can be loaded to the device, and SDK downloads directly your selected map.
2. With Nutiteq Maps SDK Enteprise license you can use custom map packages and sources, and custom download control.
You should contact Nutiteq to get access to beta, or enterprise license. Disclaimer: I'm founder of Nutiteq. | You can create MBTiles from any .osm.pbf file using this tool - <https://github.com/systemed/tilemaker>
1. Download .osm.pbf file from [Geofabric](https://download.geofabrik.de/). To download for a custom area, you can use [Protomaps](https://protomaps.com/extracts) or [BBBike Extract](https://extract.bbbike.org/)
2. Download [tilemaker](https://github.com/systemed/tilemaker/releases)
3. Execute the following command
```
tilemaker --input netherlands.osm.pbf --output netherlands.mbtiles --process resources/process-openmaptiles.lua --config resources/config-openmaptiles.json
```
You can read more about it in this blog post - <https://blog.kleunen.nl/blog/tilemaker-generate-map> |
137,574 | I'm interested in compiling a list of bookstores around the world that stock a good selection of high-level mathematical books. The aim is so that a mathematician travelling, or on holiday, can easily check the list to see if there is a book store nearby that she or he could happily spend an hour browsing in.
Some particulars:
* It must be a **physical** bookstore.
* It should have a good selection of **research level** books. This criterion is designed to exclude stores that stock primarily popular books and undergraduate textbooks, such as some university and chain bookshops. | 2013/07/24 | [
"https://mathoverflow.net/questions/137574",
"https://mathoverflow.net",
"https://mathoverflow.net/users/23572/"
] | Two in **New York City**: The Strand, Broadway and 12th Street, and the original Barnes and Noble, 5th Avenue and 18th Street. | The obverse of a bookstore, but still somehow relevant:
The (excellent) [Harvard Birkoff "noncirculating library"](http://www.math.harvard.edu/graduate/):
 |
55,375,124 | I required my `SimpleXLS` package class that I installed via composer but when I try to test it my `SimpleXLSX` looks like it's undefined.
```
<?php
include './_inc/bootstrap.php';
require_once('./vendor/shuchkin/simplexls/src/SimpleXLS.php');
if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
print_r( $xlsx->rows() );
} else {
echo SimpleXLSX::parseError();
}
``` | 2019/03/27 | [
"https://Stackoverflow.com/questions/55375124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11148364/"
] | Change,
```
if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
```
To,
```
if ( $xlsx = SimpleXLS::parse('book.xlsx') ) {
```
Change any references of `SimpleXLSX` to `SimpleXLS` because according to [this](https://github.com/shuchkin/simplexls/blob/master/src/SimpleXLS.php#L36), the class is called `SimpleXLS`, not `SimpleXLSX`.
**Note:** Composer will handle the autoloading if you include its autoloader. | When using Composer, you should generally not be including specific files inside packages, only the Composer-generated autoloader:
```
require_once './vendor/autoload.php';
```
This only needs to be run once, so could be inside your existing `_inc/bootstrap.php` file, where you'll need to go one directory up, so the line will be:
```
require_once '../vendor/autoload.php';
```
(Note that `require_once` is a keyword, not a function, so doesn't need parentheses, and adding them may cause confusion in complex cases.)
As Script47 points out in a separate answer, you also seem to have confused two similarly-named packages:
* [`shuchkin/simplexls`](https://packagist.org/packages/shuchkin/simplexls) defines a class `SimpleXLS` for reading old-format `.xls` binary files
* [`shuchkin/simplexlsx`](https://packagist.org/packages/shuchkin/simplexlsx) defines a class `SimpleXLSX` for reading newer `.xlsx` zipped XML files |
105,873 | My problem is that Windows 7 won't update - legal MSDN copy.
It says: "the update service is not started", and if I start it, it immediately shuts itself down. In the event viewer is nothing interesting to see, no fatals and no warnings, only start/stop events.
I've got no clue from where to start looking, so here's an Hijackthis log:
```
Logfile of Trend Micro HijackThis v2.0.3 (BETA)
Scan saved at 18:34:05, on 7/02/2010
Platform: Unknown Windows (WinNT 6.01.3504)
MSIE: Internet Explorer v8.00 (8.00.7600.16385)
Boot mode: Normal
Running processes:
C:\Windows\system32\taskhost.exe
C:\Windows\system32\Dwm.exe
C:\Windows\Explorer.EXE
C:\Windows\PLFSetI.exe
C:\Program Files\VMware\VMware Player\hqtray.exe
C:\Program Files\Avira\AntiVir Desktop\avgnt.exe
C:\Program Files\Windows Live\Messenger\msnmsgr.exe
C:\Program Files\Windows Sidebar\sidebar.exe
C:\Program Files\Windows Live\Contacts\wlcomm.exe
C:\Program Files\Skype\Phone\Skype.exe
C:\Program Files\Skype\Plugin Manager\skypePM.exe
C:\Program Files\Mozilla Firefox\firefox.exe
C:\Program Files\TrendMicro\HiJackThis\HiJackThis.exe
R1 - HKCU\Software\Microsoft\Internet Explorer\Main,Search Page = http://go.microsoft.com/fwlink/?LinkId=54896
R0 - HKCU\Software\Microsoft\Internet Explorer\Main,Start Page = http://www.google.be/
R1 - HKLM\Software\Microsoft\Internet Explorer\Main,Default_Page_URL = http://go.microsoft.com/fwlink/?LinkId=69157
R1 - HKLM\Software\Microsoft\Internet Explorer\Main,Default_Search_URL = http://go.microsoft.com/fwlink/?LinkId=54896
R1 - HKLM\Software\Microsoft\Internet Explorer\Main,Search Page = http://go.microsoft.com/fwlink/?LinkId=54896
R0 - HKLM\Software\Microsoft\Internet Explorer\Main,Start Page = http://go.microsoft.com/fwlink/?LinkId=69157
R0 - HKLM\Software\Microsoft\Internet Explorer\Search,SearchAssistant =
R0 - HKLM\Software\Microsoft\Internet Explorer\Search,CustomizeSearch =
R1 - HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings,ProxyOverride = *.local
R0 - HKCU\Software\Microsoft\Internet Explorer\Toolbar,LinksFolderName =
O2 - BHO: AcroIEHelperStub - {18DF081C-E8AD-4283-A596-FA578C2EBDC3} - C:\Program Files\Common Files\Adobe\Acrobat\ActiveX\AcroIEHelperShim.dll
O2 - BHO: (no name) - {5C255C8A-E604-49b4-9D64-90988571CECB} - (no file)
O2 - BHO: Groove GFS Browser Helper - {72853161-30C5-4D22-B7F9-0BBC1D38A37E} - C:\Program Files\Microsoft Office\Office12\GrooveShellExtensions.dll
O2 - BHO: Windows Live ID Sign-in Helper - {9030D464-4C02-4ABF-8ECC-5164760863C6} - C:\Program Files\Common Files\Microsoft Shared\Windows Live\WindowsLiveLogin.dll
O4 - HKLM\..\Run: [PLFSetL] C:\Windows\\PLFSetL.exe
O4 - HKLM\..\Run: [PLFSetI] C:\Windows\PLFSetI.exe
O4 - HKLM\..\Run: [VMware hqtray] "C:\Program Files\VMware\VMware Player\hqtray.exe"
O4 - HKLM\..\Run: [avgnt] "C:\Program Files\Avira\AntiVir Desktop\avgnt.exe" /min
O4 - HKCU\..\Run: [msnmsgr] "C:\Program Files\Windows Live\Messenger\msnmsgr.exe" /background
O4 - HKCU\..\Run: [Sidebar] C:\Program Files\Windows Sidebar\sidebar.exe /autoRun
O4 - HKUS\S-1-5-19\..\Run: [Sidebar] %ProgramFiles%\Windows Sidebar\Sidebar.exe /autoRun (User 'LOCAL SERVICE')
O4 - HKUS\S-1-5-19\..\RunOnce: [mctadmin] C:\Windows\System32\mctadmin.exe (User 'LOCAL SERVICE')
O4 - HKUS\S-1-5-20\..\Run: [Sidebar] %ProgramFiles%\Windows Sidebar\Sidebar.exe /autoRun (User 'NETWORK SERVICE')
O4 - HKUS\S-1-5-20\..\RunOnce: [mctadmin] C:\Windows\System32\mctadmin.exe (User 'NETWORK SERVICE')
O8 - Extra context menu item: E&xporteren naar Microsoft Excel - res://C:\PROGRA~1\MICROS~2\Office12\EXCEL.EXE/3000
O9 - Extra button: Verzenden naar OneNote - {2670000A-7350-4f3c-8081-5663EE0C6C49} - C:\PROGRA~1\MICROS~2\Office12\ONBttnIE.dll
O9 - Extra 'Tools' menuitem: Verz&enden naar
``` | 2010/02/07 | [
"https://superuser.com/questions/105873",
"https://superuser.com",
"https://superuser.com/users/27500/"
] | The following is from Microsoft. The 1st solution fixed my problem:
>
> From the case log, I understand that the error code 80072EFE was
> received when trying to perform Windows Update. If there has been any
> misunderstanding, please let me know. I fully understand the
> inconvenience you have experienced. We will work together to resolve
> this issue through the course of the case. This issue can be caused
> by one of the following factors:
>
>
> 1. The computer was attacked by viruses.
> 2. Some background programs, such as antivirus programs or firewalls (especially CA Firewall), block access to the Windows Update site.
> 3. Incorrect DNS Settings. We will address some of the more common causes of this issue. It is important that we attempt to connect to
> the Windows Update web site after each step to confirm whether the
> resolution has worked. This will prevent us from having to proceed
> with additional troubleshooting steps and provide us with valuable
> feedback to further develop our support resolutions for you and our
> future customers. Your assistance is greatly appreciated.
>
>
> Suggestion 1: Run the tool to clear spyware
> ===========================================
>
>
> 1. Download the file [TDSSKiller.zip](http://support.kaspersky.com/downloads/utils/tdsskiller.zip) from the following link and save it on the Desktop.
> 2. Double click TDSSKiller.zip to unzip the file.
> 3. Double click TDSSKiller.exe to scan the system.
> 4. Wait for the scan and disinfection process to complete. Please Note: The third-party product discussed here is manufactured by a
> company that is independent of Microsoft. We make no warranty, implied
> or otherwise, regarding this product's performance or reliability.
>
> Now try Windows Update to see if the issue has been resolved. Please
> let us know if this step has resolved it. If not, please proceed to
> the next step.
>
>
> Suggestion 2: Reset DNS Settings
> ================================
>
>
> 1. Click "Start", input "NCPA.CPL" (without quotation marks) to Start Search bar and press "Enter".
> 2. Right-click the network connection and click "Properties". If you are prompted for an administrator password or confirmation, type
> the password or provide confirmation.
> 3. Click to highlight "Internet Protocol Version 6 (TCP/IPv6)" and click "Properties".
> 4. Check "Obtain an IP address automatically" and "Obtain DNS server address automatically".
> 5. Click "OK".
> 6. Click to highlight "Internet Protocol Version 4 (TCP/IPv4)" and click "Properties".
> 7. Check "Obtain an IP address automatically" and "Obtain DNS server address automatically".
> 8. Click "OK".
> 9. Reboot the computer. Now try Windows Update again to check if the issue has been resolved. If not, please proceed to the next step.
>
> Suggestion 3: Disable firewalls or other Internet browser programs
> that can affect the Internet connection
>
>
> This issue could be caused by third party applications. Let's first
> try disabling or uninstalling any third party security applications
> you may have installed on the computer. Please be advised that this is
> for troubleshooting purposes only.
>
>
> Once we have resolved the issue,
> the applications should be re-enabled or reinstalled immediately. If
> the third party security application is determined to be the cause,
> please contact the vendor for assistance. You may have a different
> security application not listed below that could also be causing the
> issue. Even if the firewall has been running for some time without any
> problems, new updates may create issues.
>
>
> Here is a list of the most
> common security applications:
>
>
> * Symantec
> * Norton
> * McAfee
> * Zone Alarm
> * Panda Security
> * Kaspersky
> * Sophos Antivirus
> * Comodo Firewall
> * AntispamSniper
> * Webroot
> * Spy Sweeper
> * Accelerator
> * Spybot
>
>
> Once the third
> party security applications have been disabled or removed, please
> access the Windows Update web site again. If you encounter problems
> disabling these programs, we recommend completely uninstalling them
> while troubleshooting.
>
>
> Before uninstalling any application, please
> enable your Windows Firewall and ensure that you have the CDs or files
> needed to re-install the program.
>
>
> | With windows 10, Microsoft has been trying to "bully" other users to upgrade to 10. One form that this has taken has been to given Windows 7 machines low priority on their update servers. And I mean *really* low priority. Also, some updates seemed to turn off updates for who-knows-why if later updates weren't also done at the same time.
This worked for me...
```
net stop http /y
net stop wuauserv
regsvr32 %windir%\system32\wups2.dll
net start wuauserv
```
Then, and this is highly important...
Start windows update, and if it seems to hang...
Let it run for literally 24 hours straight. It literally can take a full day for it to actually get around to downloading updates due to the ridiculoiusly low priority. I can download a Windows 7 SP1 install disk image from a African server using dial-up faster than I can download the updates from 7 to 7SP1 from Microsoft whose corporate campus is literally a 45 minute drive from my house. They're bottlenecking it that much. |
23,265,645 | *[Similar question](https://stackoverflow.com/questions/5012480/8-bit-char-to-hex-representation) however, I'm looking for a qt solution.*
I'm looking for a way convert a 8 bit negative int into a hex representation. The example will explain it better.
```
qint8 width = - 100;
qDebug() << QString::number(width, 16);
// "ffffffffffffff9c"
```
The output is much more than 2 bytes.
However, when i change it to unsigned, it works fine.
```
quint8 width = - 100;
qDebug() << QString::number(width, 16);
// "9c"
```
The documentations states:
>
> typedef quint8
>
>
> Typedef for unsigned char. This type is guaranteed to be 8-bit on all
> platforms supported by Qt.
>
>
>
---
>
> typedef qint8
>
>
> Typedef for signed char. This type is guaranteed to be
> 8-bit on all platforms supported by Qt.
>
>
>
Shouldn't unsigned not be able to deal with negative numbers? | 2014/04/24 | [
"https://Stackoverflow.com/questions/23265645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1214214/"
] | The problem is that `QString::number` can accept `int` or `uint` types. It doesn't have versions for 8-bit integers, so they are implicitly casted to larger integers. It works fine with signed integer because leading zeros are removed.
You can however use `QDataStream`, it provides `operator <<` for large variety of types:
```
QByteArray buffer;
QDataStream stream(&buffer, QIODevice::WriteOnly);
qint8 width = - 100;
stream << width;
qDebug() << buffer.toHex();
// output: "9c"
``` | `QString::number` only takes `int`s and `long`s so both times `width` was promoted to a qint and quint resp
Unsigned promotion does not extend the sign bit while signed promotion does.
and documentation of [QString::number says](http://qt-project.org/doc/qt-5/qstring.html#number)
>
> The base is 10 by default and must be between 2 and 36. *For bases other than 10, n is treated as an unsigned integer.*
>
>
>
that means the extended sign bits are displayed |
27,362,971 | I'm trying to add the new Android 5.0 Material Design Datepicker to my pre 5.0 application using AppCompat. I've added
```
compile "com.android.support:appcompat-v7:21.0.0"
```
to my build.gradle file and updated my Theme to:
```
<?xml version="1.0" encoding="utf-8"?>
```
```
<style name="AppTheme.Base" parent="@style/Theme.AppCompat.Light">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
```
but the Datepicker still looks like this:

And not like this:

Can anybody tell me how to get the new datepicker to work on pre 5.0 devices?
Thanks in advance. | 2014/12/08 | [
"https://Stackoverflow.com/questions/27362971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449811/"
] | Material components is the recommended way for date picker
----------------------------------------------------------
With the `Material Components for Android` you can use the new `MaterialDatePicker`.
add the following to your build.gradle
```
implementation 'com.google.android.material:material:1.1.0'
```
**For kotlin**
```
val builder = MaterialDatePicker.Builder.datePicker()
val picker = builder.build()
picker.show(parentFragmentManager, "date_picker_tag")
```
**For Java**
```
MaterialDatePicker.Builder<Long> builder =
MaterialDatePicker.Builder.datePicker();
MaterialDatePicker<Long> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());
```
It supports the following configurations
**portrait - mode date picker**
[](https://i.stack.imgur.com/KAXZI.png)
**landscape - mode date picker**
[](https://i.stack.imgur.com/Xtyk6.png)
**date range picker**
[](https://i.stack.imgur.com/WGbVf.png)
**Mobile input picker**
[](https://i.stack.imgur.com/ADQKa.png)
**Additional reference**
[Here](https://material.io/components/pickers/#mobile-pickers) is the official design guideline
A complete demo app can be found [here](https://github.com/material-components/material-components-android/blob/master/catalog/java/io/material/catalog/datepicker/DatePickerMainDemoFragment.java) | I liked [this](https://github.com/jaydeep17/datetimepicker) library. It's a clone of [Flavien Laurent Date and Time Picker](https://github.com/flavienlaurent/datetimepicker) with some improvements. Both of them are based on [Official Google Date and Time Picker for Android 4.3+](https://android.googlesource.com/platform/frameworks/opt/datetimepicker/) but adapted for Android 2.1+. |
818 | Since I'm not a Magic player, I have that tag ignored. When I called up the site I was met with a huge wall of greyed out questions. It seems a whole bunch of Magic questions where re-tagged with "Rules".
That got me thinking. A large percentage of questions on this site are going to be rules questions. I'd even go so far as to say non-rules questions would probably be in the minority.
Wouldn't that make the "Rules" tag redundant? Couldn't every question be considered a rules question unless tagged otherwise?
Do we really need a "Rules" tag? | 2012/06/16 | [
"https://boardgames.meta.stackexchange.com/questions/818",
"https://boardgames.meta.stackexchange.com",
"https://boardgames.meta.stackexchange.com/users/2733/"
] | Given the way the tag is *used*, I'm gonna say **NO**.
The excerpt for the tag states,
>
> Objective questions about a game's official rules.
>
>
>
Now, there are two ways you could interpret that...
1. Questions on interpreting or applying *specific rules* during gameplay.
2. Any question where the rules of a game might have bearing on the answer.
Well, #1 seems like a fine, specific bit of meta-data, describing the question and perfectly appropriate.
Ol' #2 applies to *just about any question that could possibly be asked*. And #2 is the one that seems to be used in practice.
Let's take a look at [How does the double strike mechanic interact with other mechanics like lifelink or trample?](https://boardgames.stackexchange.com/questions/5950/how-does-the-double-strike-mechanic-interact-with-other-mechanics-like-lifelink) (picked at random off the front page of the site). Tagged [rules](https://boardgames.stackexchange.com/questions/tagged/rules "show questions tagged 'rules'") [magic-the-gathering](https://boardgames.stackexchange.com/questions/tagged/magic-the-gathering "show questions tagged 'magic-the-gathering'"). Noticeably *not* tagged [double-strike](https://boardgames.stackexchange.com/questions/tagged/double-strike "show questions tagged 'double-strike'") or [mechanics](https://boardgames.stackexchange.com/questions/tagged/mechanics "show questions tagged 'mechanics'").
Yes, the *answer* involves the rules of the game. So what? This should be true for *most* questions, whether implicitly or otherwise. Even [strategy](https://boardgames.stackexchange.com/questions/tagged/strategy "show questions tagged 'strategy'") questions make the assumption that good answers won't be predicated on *ignorance of the rules*.
I *strongly* encourage the use of more specific tags when at all possible. Both for proper categorization, and for the pragmatic reason [Alex P notes](https://boardgames.meta.stackexchange.com/questions/818/do-we-really-need-a-rules-tag/821#821): if you make a tag or tags so generic that they apply to nearly every question on the site, you lose the bonus of having the most popular tag (inserted into the title) also be the one that most broadly classifies the subject matter.
Your sister site [Arqade](https://gaming.stackexchange.com/) learned this lesson [the hard way](https://gaming.meta.stackexchange.com/questions/1651/make-a-special-tag-class-for-game-tags). | My view is that the [rules](https://boardgames.stackexchange.com/questions/tagged/rules "show questions tagged 'rules'") tag is a meta tag and is mostly unnecessary.
Here is the "official" stance on [meta tags](http://blog.stackoverflow.com/2010/08/the-death-of-meta-tags/), straight from the horse's mouth.
---
Is it useful?
-------------
I can empathize with the people who propose that it's useful to have MTG questions tagged with [rules](https://boardgames.stackexchange.com/questions/tagged/rules "show questions tagged 'rules'") so that it helps them categorize the question mentally at first glance. But how useful is it?
My view is that since we encourage users to ask questions in natural grammar (not search engine grammar), it's easy to understand that a question is about the rules of a game if a user reads the question carefully. If a user didn't read the question, then perhaps the topic is irrelevant to begin with and a [rules](https://boardgames.stackexchange.com/questions/tagged/rules "show questions tagged 'rules'") tag would be equally irrelevant.
Also, the Follower-to-Question ratio of [rules](https://boardgames.stackexchange.com/questions/tagged/rules "show questions tagged 'rules'") is 0.0102. **It has 5 followers despite being the most popular tag for questions.** That suggests that most users don't find it useful.
It'd also be interesting to see (but I can't) how many users have ignored the tag.
How do I use it?
----------------
If I were to follow the [rules](https://boardgames.stackexchange.com/questions/tagged/rules "show questions tagged 'rules'") tag, wouldn't that suggest that I'm either 1) interested in learning about *any* rules from *any* game, or 2) knowledgable about *any* rules from *any* game?
I think either scenario is rare. A question tagged [rules](https://boardgames.stackexchange.com/questions/tagged/rules "show questions tagged 'rules'") would ideally be only about rules, independent of any game.
I can also see the usefulness of a tag in that situation, even if it's rarely used, because it won't be used as a meta tag. But the current use of [rules](https://boardgames.stackexchange.com/questions/tagged/rules "show questions tagged 'rules'") is mostly generating noise. |
53,721,733 | I’m a Python newbie and have the following Pandas dataframe - I’m trying to write code that populates the ‘signal’ column as it is below:
| Days | long\_entry\_flag | long\_exit\_flag | signal |
| --- | --- | --- | --- |
| 1 | FALSE | TRUE | |
| 2 | FALSE | FALSE | |
| 3 | TRUE | FALSE | 1 |
| 4 | TRUE | FALSE | 1 |
| 5 | FALSE | FALSE | 1 |
| 6 | TRUE | FALSE | 1 |
| 7 | TRUE | FALSE | 1 |
| 8 | FALSE | TRUE | |
| 9 | FALSE | TRUE | |
| 10 | TRUE | FALSE | 1 |
| 11 | TRUE | FALSE | 1 |
| 12 | TRUE | FALSE | 1 |
| 13 | FALSE | FALSE | 1 |
| 14 | FALSE | TRUE | |
| 15 | FALSE | FALSE | |
| 16 | FALSE | TRUE | |
| 17 | TRUE | FALSE | 1 |
| 18 | TRUE | FALSE | 1 |
| 19 | FALSE | FALSE | 1 |
| 20 | FALSE | FALSE | 1 |
| 21 | FALSE | TRUE | |
| 22 | FALSE | FALSE | |
| 23 | FALSE | FALSE | |
My *pseudocode* version would take the following steps
1. Look down the [‘long\_entry\_flag’] column until entry condition is True (day 3 initially)
2. Then we enter ‘1’ into [‘signal’] column every day until exit condition is True [‘long\_exit\_flag’]==True on day 8
3. Then we look back to [‘long\_entry\_flag’] column to wait for the next entry condition (occurs on day 10)
4. And again we enter ‘1’ into [‘signal’] column every day until exit condition is True (day 14)
5. etc.
What are some ways to populate the ‘signal’ column rapidly if possible (using vectorisation?)?
This is a subset of a large dataframe with tens of thousands of rows, and it is one of many dataframes being analysed in sequence. | 2018/12/11 | [
"https://Stackoverflow.com/questions/53721733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10569839/"
] | You can do
```
# Assuming we're starting from the "outside"
inside = False
for ix, row in df.iterrows():
inside = (not row['long_exit_flag']
if inside
else row['long_entry_flag']
and not row['long_exit_flag']) # [True, True] case
df.at[ix, 'signal'] = 1 if inside else np.nan
```
which is going to give you exactly the output you posted.
---
Being inspired by [@jezrael's answer](https://stackoverflow.com/a/53724569/4755520), I created a **slightly more performant version of the above** while still trying to keep it as neat as I could:
```
# Same assumption of starting from the "outside"
df.at[0, 'signal'] = df.at[0, 'long_entry_flag']
for ix in df.index[1:]:
df.at[ix, 'signal'] = (not df.at[ix, 'long_exit_flag']
if df.at[ix - 1, 'signal']
else df.at[ix, 'long_entry_flag']
and not df.at[ix, 'long_exit_flag']) # [True, True] case
# Adjust to match the requested output exactly
df['signal'] = df['signal'].replace([True, False], [1, np.nan])
``` | ```
#let the long_exit_flag equal to 0 when the exit is TRUE
df['long_exit_flag_r'] = ~df.long_exit_flag_r
df.temp = ''
for i in range(1, len(df.index)):
df.temp[i] = (df.signal[i-1] + df.long_entry_flag[i])*df.long_exit_flag_r
```
If the temp is positive then the signal should be 1, and if the temp is negative then the signal should be empty. (I kind of get stuck here.) |
7,874,972 | How is the lexicographic order defined in Java especially in reference to special characters like `!`, `.` and so on?
An examplary order can be found [here](http://sheepsystems.com/bookdog/HelpBook/LexicalOrder.html)
But how does Java define it's order? I ask because I'm sorting Strings on Java and on Oracle and come up with different results and can't find the specification for the lexicographic order. | 2011/10/24 | [
"https://Stackoverflow.com/questions/7874972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256853/"
] | From the docs for [`String.compareTo`](http://download.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo%28java.lang.String%29):
>
> Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.
>
>
>
and
>
> This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string [...]
>
>
>
So basically, it treats each string like a sequence of 16-bit unsigned integers. No cultural awareness, no understanding of composite characters etc. If you want a more complex kind of sort, you should be looking at [`Collator`](http://download.oracle.com/javase/7/docs/api/java/text/Collator.html). | In Java it's based on the Unicode value of the string:
<http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#compareTo(java.lang.String>)
In Oracle, it will depend on the charset you are using on your database. You'll want it to be UTF-8 to have consistent behavior with Java.
To check the character set:
```
SQL> SELECT parameter, value FROM nls_database_parameters
WHERE parameter = 'NLS_CHARACTERSET';
PARAMETER VALUE
------------------ ---------------------
NLS_CHARACTERSET UTF8
```
If it's not UTF-8, then you can get different comparison behavior depending on which character set your Oracle database is using. |
235,182 | 1. They have tried Democracy
2. The civilization is very much similar to human civilizations but I want it to stay as a monarchy yet still have technology advanced enough to travel around the galaxy.
Is it even possible? | 2022/09/04 | [
"https://worldbuilding.stackexchange.com/questions/235182",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/98219/"
] | **We can learn a thing or two from good old Earth**
>
> It’s good to be the king. But, when it comes to a nation’s economic health, it’s also good to have a king — or queen — on hand. Monarchs open economic doors.
>
>
> “In the presence of royalty, companies can enter circles they wouldn’t be able to get in by themselves,” says Angélique Heijl, deputy director of international economic affairs at VNO-NCW, the largest employers’ organization in the Netherlands. “This holds particularly true for countries where the government plays a large role in the economy.”
>
>
> Monarchs typically serve their respective nations longer than democratically elected heads of state: The recently abdicated Dutch Queen Beatrix was on the throne for 33 years; Elizabeth II of Britain has held her position for 61 years and counting. This kind of leadership stability gives these particular figures additional sway in the business community. ([Source](https://fortune.com/2013/04/30/the-business-case-for-monarchies/))
>
>
>
When it comes to a galaxy-spanning empire, the businesses are ***incredibly important.*** So much so that SciFi (e.g., Johnny Mnemonic) has played around with the idea of business being government in its own right. The influence of business on a civilization so advanced as to span an entire galaxy cannot be over-estimated. Therefore, a government that partners really, really well with business has a high degree of believability.
And a monarchy is it.
Governments do two things: they manage wealth and they impose order. The later is done with the threat of violence ("if you break the law, we will take your freedom!"). The former is the basis of at least two college-level economics classes. But a monarchy and its ability to *grant patents and charters* has an excellent chance of partnering with business.
**Add the inherent difficulties of communication to the mix...**
To add to the boiling pot... democracies kinda depend on reasonably swift communication. That comes from being small in size (Ancient Greece...) or having a tremendous communication system (modern-day democracies). When you depend on the people to elect their leaders, you need a way to ~~manipulate~~ inform your population so they can make wise choices.
Which suggests that the worst conditions for a democracy would be a geographically large area with remarkably poor communication. Given that condition, it's easy for pieces of the democracy to begin breaking away into independence (we've seen that in our own lifetimes!).
A galaxy like the Milky Way is 100,000 light years across. Ignoring for the moment that massive black hole and maelstrom of radiation in the center, that means that your communication must at best cross 50,000 light years to reach everyone. Let's assume FTL... to get a message across in one week you need to travel 2,600,000X the speed of light. Well, it's SciFi, right? What's a little thing like hand-waving excessive speeding?
But that's the only way to have a *practical* democracy. Super speed. Otherwise people can't be kept informed in a way that makes democracy work. The longer it takes to inform the people prior to an election, the more your democracy will look like a monarchy anyway.
**And too many voices kills democracy**
Finally, here's your last problem. A galaxy-spanning bureaucracy would require a lot of levels of abstraction to work. Ignoring how to govern a planet (our attempt at one-world government doesn't work fabulously), we can assume that each planet would want a seat at the proverbial table, right? I mean, think about how Star Wars presents the Senate. I think that's *really optimistic.*
Millions (if not billions) of planets. Maybe 1,000 per region of authority (The U.S. Senate represents 50 states, and it's unwieldy). Thousands (if not millions) of regions of authority. A senate of senates of senates.... Each having executive and judicial branches... Which looks an awful lot like a parliamentary monarchy pretty quickly.
**Conclusion**
I think it's more likely for a monarchy to exist on a galactic level than a democracy as-is. I'm just sayin' | Aristoi + Eugenics
==================
Your aliens have selected a genetic class that systematically weeds out people with "undesirable" traits. With genetic engineering and social programming, they have created a class of people who are genetically and educationally "optimized" (at least in their minds) for rulership.
But this class actually lives quite humble lives. They're really just administrators and bureaucrats living comfortable but not spectacular lives. Because they are surrounded by strict rules about what they are allowed to have and do, they really don't have much freedom.
Sometimes, half the battle of who should be in charge is just picking a fair way to decide. The monarch may be better, or at least they are no worse than the next guy.
God-Rulers:
===========
Your original great monarch is still alive - sort of. AI has created a simulation of the great founder. Each new "Emperor" is considered a reincarnation of this ruler, but they are really a mouthpiece for this AI. This program rules wisely and impartially, worshipped as a god by the people.
AI monarchs:
============
Or why not just make it official, and AI's ARE the monarchs? Each new "ruler" is designed as an upgrade of the previous system.
Humans don't matter:
====================
No one cares who the ruler is, except the humans. And they really don't count. The society provides all needs for all citizens, but that's a fraction of a percent of GDP. Every important decision is made by corporate boards or wealthy plutocrats, but these are mostly AI's, downloaded rich folks living in computers, or hyper-advanced cyborgs. Monarchs are simply not capable of understanding governance at this level of sophistication and are kept away from decision-making like silly children.
It seems like the ruler is in charge, but real administration is done by computers. The REAL powers don't care if the monarch executes people or builds lavish palaces or even carries out whole wars with other civilizations. It is STILL less than a percent of GDP. If it makes the humans feel relevant, then why not? |
250,591 | Early in spring, when the ground was frozen and there was still a feet of snow in the yard, heavy rain filled my basement window well with water. The ground around my house is very sandy, so the water carried sand into the well.
As you can see on this picture, there is a drain, but I suspect it got clogged with sand. The cover seems stuck (or glued) so I cannot check easily.
The red stick is a broom stick showing that a gap formed between by house and the ground, caused by the incoming water.
I tried to work on removing the sand, but looks like sand got everywhere beneath the gravel.
So now, how should I proceed?
[](https://i.stack.imgur.com/lFaAT.jpg) | 2022/06/06 | [
"https://diy.stackexchange.com/questions/250591",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/757/"
] | I would first see that the well is sealed to the building. It seems that the sand is washing into the well where the well meets the building. Second I would see that the ground is pitched away from the building so when it rains water does not run towards the building. Third I would insure that the gutters are clear and any downspouts direct water away from the house. Address those three things as well as the answer from @MonkeyZeus and you should be fine. | >
> So now, how should I proceed?
>
>
>
A shovel, wheelbarrow, and some sweat.
If the sand is not supposed to be in the gravel then you need to remove the contaminated gravel and shake/wash the sand off of it before storing it in a pile. There is no magic vacuum for this. Just keep shoveling until you hit dirt.
By doing this you will reveal how that drain is assembled and will give you a better idea of your options for unclogging it.
After you've hit dirt then backfill with your clean gravel. |
78 | I was quite excited to see that the linguistics SE had begun public beta. However, I must admit that I'm a bit disappointed by the level of the questions on the front page. I guess I was under the impression that the site would be more focused on research-level Linguistics, not just languages in general. Was I wrong about that? Do other people feel similarly? | 2011/09/21 | [
"https://linguistics.meta.stackexchange.com/questions/78",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/230/"
] | Research-level linguistics questions are certainly welcome.
A natural problem the site may face is that research-level interests may prompt big, involved questions that don't have a quick answer, and those who contribute such questions may not have new questions frequently. Conversely, shorter, more frequent, and easier-to-answer questions will come from beginners.
When you're thinking about posting a research-level question, it may help to break up the problem into separate questions so that each can have one best answer and you can ask and get answers a little more often. (It's ok to link to related questions from your own; for example, you may want to mention something you asked earlier or point out something that did not fully answer your question.)
All before getting too far, you might ask specific questions about things like tools, previous work in the area, experimental design strategies... A broader audience will be able to help answer some of these questions than might be able to work on a specialized research topic, so you and the site will both benefit. | Please feel free to ask more questions on research-level linguistics. I'm sure many of us are interested to see them.
In the mean time the questions come from whoever is asking and we all have different interests and knowledge. |
26,918,775 | I'm using fgets to read a string in a char array, and then I want to move the pointer over 5 indices and copy the rest of the array into a separate array, BUT I don't want it to copy a newline character; so I've got something like this:
```
char str1[45], str2[50];
fgets(str2, 50, stdin);
*str2 += 5;
sprintf(str1, "%[^\n]s", str2);
```
but when I try to compile, I get an error that says:
```
unknown conversion type character â[â in format [-Wformat]
```
I'm pretty sure I've used the "%[^\n]s" before with scanf, and it worked just fine, any suggestions? | 2014/11/13 | [
"https://Stackoverflow.com/questions/26918775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143072/"
] | The pattern `%[^n]s` is valid format for `scanf` but it is not a valid format specifier for `printf` (or `sprintf`).
Additionally, `*str2 += 5` does not skip the first 5 characters (as it appears to be the intention) but instead adds 5 for the byte stored in the first element of `str2`. `str2 = str2 + 5` will not compile since str2 is an array. You could assign the result to a temporary or pass it directly to sprintf.
Here is a slightly better way of doing what you are asking:
```
size_t len;
char *str1 = NULL, str2[50];
fgets(str2, 50, stdin);
len = strlen(str2);
if (len > 5) {
if (str2[len-1] == '\n') {
str2[len-1] = '\0'; // remove newline
len--;
}
str1 = str2 + 5;
len -= 5;
}
if (str1 != NULL) {
// do stuff
}
``` | Try removing the final "s" in "%[^\n]s" |
1,360,383 | I have a string like following:
`CREATE GLOBAL TEMPORARY TABLE **some\_temp\_table\_name**`
or
`CREATE GLOBAL TEMPORARY TABLE **some\_temp\_table\_name** something else`
with the regex I want to strip out whatever is in bold letters.
I have the following regex
```
([a-z].*[\s]*)
```
what should I change in the regex? | 2009/09/01 | [
"https://Stackoverflow.com/questions/1360383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44286/"
] | Try this:
>
> `([A-Z\s]+)[a-z_]+\s?([a-z\s]+)`
>
>
>
In Groovy you would do something like this:
```
String clean
= yourString.replaceAll("([A-Z\s]+)[a-z_]+\s?([a-z\s]+)", "$1$2");
``` | try? :
```
([a-zA-Z\s]+TABLE)\s\b[a-zA-Z_]+\b(.*)
``` |
152,559 | ### Background
*You can skip to the end for a (very) short summary though...*
We are a group of good friends, we've all known each other for 7+ years, since high school, and have been playing DnD since then, first 3.5 and then recently 5th edition. Currently, there are 6 players, including the PC "played" by the GM in our campaign.
One of the players, let's call him John (who also DMs regularly, we will come back to this) has always been a good friend and constructive member in the various parties we have played.
John is not only a good friend, but also usually a very pleasant person to be around, and by no means troublesome, in most situations.
Our problem is, he becomes a very problematic player when someone else is a DM, and lately this has grown to such proportions that it became somewhat toxic for the group.
---
John likes being cool. Here's a list of John's examples to illustrate the challenges he presents to the DM and the group
* as a level 3 Rogue, spending 5 minutes trying to convince an NPC merchant to buy a broken wooden wheel for 10 GP, before trying to sneak behind the counter while the merchant could still see him (no magic, no tricks, just... going around crouching trying a stealth roll), and of course getting caught trying to pick pocket the NPC, keeping the DM from interacting with other players the whole time.
* with the same character, trying to steal from a treasure in the hold of the dwarven ship we were protecting, after multiple warnings from the DM on how both the magic protections and guards would make it hard for a confirmed burglar to pull it off, needless to say quite impossible for him (and of course, nowhere to run once he was caught, we're in the middle of the sea).
* stealing a horse in daylight in the middle of the biggest city in the realm, because the merchant didn't want to lower his price, in front of said merchant, with guards all around this part of the city. Note that even if we weren't pressured in any way, nothing that would force us to act quickly, we did on the other hand know that the king there would take the first opportunity he could get to have us locked away.
In most of those situations, when he was presented with consequences - *that were honestly really moderate considering the foolishness of his character's action, take the failed theft on the boat (we managed to convince the dwarves not to iron a "T" on his head for "thief" and had him simply imprisoned for the duration of the escort mission instead*) - he would get mad and sulk, taking any occasion he got to make it known that he was upset and holding grudges. This kind of behavior ends up ruining the mood for everybody in the party, not only the DM.
Since John grew more cocky as the quests went on - since we as a group would rather shrug his attempts off than wasting time having him be in jail, punished, and so on - he actually is the very reason the two other DMs (my co-DM included), have regretfully resorted to applying more logical punishments in their own campaigns, which isn't really a problem for anyone, except John when he messes up.
I have read the very good topic about the [My Guy Syndrome](https://rpg.stackexchange.com/questions/37103/what-is-my-guy-syndrome-and-how-do-i-handle-it), and I believe this applies to John's behavior very well.
As an example, I shall take his latest "feat".
He attacked an enemy camp we were just meant to scout, by himself, despite the warnings from the DM and attempts from the players to explain that it would most likely mean death and mess up the quest, saying "that's what my character would do".
The camp being occupied by approximately 40 to 50 well trained, armored soldiers, a lone Level 5 barbarian stood no chance, and so the DM talked openly with him about the consequences.
John was proposed with various scenarios, among which were the simple death of his character (and the introduction of his future new one in the story shortly after), or being captured, interrogated, etc... and then presumably rescued by us later, which was his choice.
It was also agreed that after suffering grave injuries as a result of both the battle and his imprisonment, his character would be severely weakened for the next session, which meant various debuffs, that John seemingly serenely agreed to.
The next session, John just showed up with the firm intention to sulk the whole time, playing on his portable device most of the time, arguing that his battle oriented character was impossible to fight with and hence could only do "boring stuff his character would never want to do".
Note that his character has also refused every opportunity presented to him to be involved in roleplay while his imprisonment lasted during the previous session, which didn't prevent John from openly complaining about how boring this part of the quest was for him.
---
For those of you that survived reading all that *(congratulations!)*, you might be wondering: *" But why don't you discuss this directly with John ? "*
And this is the reason we've decided to ask for help, because what we thought would be the only logical way to address this issue has failed. We have tried talking about it with him, in a very diplomatic and honestly friendly way, not putting him on the spot, and his response is usually to lash out, as he experiences it, in his own words, "as a personal attack".
This is where I have to bring up the fact that John also is a DM, for his own campaign, which BTW is very enjoyable for everyone. But you would also think that this allows John to know what it is like to DM (he has for years now), and that it would help him understand how his behavior is problematic.
And you'd be right, John actually happens to be a reasonably strict DM, with high expectations for his players when it comes to both role play and commitment to the quest, and that is 100% fine for everyone involved.
What isn't fine for our players, on the other hand, is to see someone so demanding as DM behave in ways he would **never** tolerate in his campaign, and berating others on their lack of role play, for instance.
In general, we are a "happy go lucky" kind of group, and we all enjoy role playing as much as we like making jokes and comments "out of the game", as players and not characters, which doesn't sit well with John when he DMs, and apparently now annoys him as a player too.
What really pushed us to ask this question here, was that even though the last quest was still fun, John's behavior is sometimes getting out of hand, and his constant sulking and post-game remarks are starting to be a real weight on the group; his latest comment on how he "knows that D&D is not a passion and does not involve a significant investment from everyone" really is ticking us off. All of the players are really passionate and involved in both their characters and the campaign.
*Just to be clear, we do not want him to play his characters in a certain way, this is not about coercing him into what we think is THE WAY to play, OUR way.
As a group, we have always agreed on the fact that in the settings built by the DM, the PCs are free to do whatever they want, so that they might RP what they feel like, and feel free to find any solutions, any path, etc.
This is about destructive behavior that ruins the fun for everybody, using freedom of action as a pretext for "YOLO" actions.
And even though we are upset about this current situation, this is in no way a "vent our frustration" question; we really feel out of options and seek for advice on how we should handle this situation*
---
TL;DR : A party member regularly plays his character in such a way that endangers not only himself, but the whole group and sometimes even compromises the campaign.
He is aware of it, but also very defensive about it, he also turns into an insufferable grumpy kid whenever he has to face consequences, ruining the party's mood, and gets aggressive when confronted about it.
We do not want to exclude him, as he remains a very good friend and we would rather solve this problem in a way that allows him to play, along with everyone. | 2019/07/27 | [
"https://rpg.stackexchange.com/questions/152559",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/57093/"
] | The way I understand it
-----------------------
Your problem player rejects your concerns when you try to address behaviours that the whole group agree are problematic **and** would also be problematic for the problem player if one of his players had the same behaviours in the game he masters?
Seems to me like he is asking people to tolerate a behaviour he would not tolerate from others. IMO he should meet you halfway instead of rejecting your arguments, but he's not.
Discussion did not work. More discussion might?
-----------------------------------------------
So trying to talk with him doesn't work and it sounds to me like it does not work because this player is being very childish, transforming his group's valid concerns into something they are not, i.e. personal attacks.
He also seems to have a double standard when it comes to how he behaves.
I personally can be very firm while also being very diplomatic. Honestly, someone who would twist my arguments into personal attacks and try to turn himself into a martyr would get an earful from me about the fact that we are discussing valid concerns and the fact he's acting like... let's say a child.
It would be a very serious discussion about how I do not appreciate his being childish, and if he keeps proving to me than he cannot be civil and respectful during our exchanges, I would totally lose any kind of interest I have in interacting with him.
When a problem player does not want to even start considering that his behaviour might be problematic, when diplomacy fails, there are not many options left: endure, leave or kick him out? Different people/groups have different thresholds for that, but that's an immutable fact of life: once you hit the "point of no return", then your options are very limited.
Trying to deal with the "my guy syndrome"
-----------------------------------------
"My guy would do this" is not automatically a logical or valid argument that answers every situation. This argument can always be debated!
When one of my players uses this "excuse" without further explanation, I probe them further for an explanation, for deeper insight into their character's psyche.
A simple way to do it is to ask him, "But why would your character be/think/act this way?". Ask questions but do not "say stuff about his character" like "He would not be smart/dumb enough to do that", since that would be crossing a line where you start telling him how he should play his character.
Challenge him on his excuses. Like in the instance of the barbarian deciding to invade a whole outpost by himself, when he clearly has no way to win and will clearly end up "badly" for his character, I would have asked him, "Is your barbarian smart or tactical enough to realize he has no chances? Or does he have a death wish?".
Of course, that's really not foolproof because it is a more passive approach and still depends on the problem player's reactions/decisions...
...which brings me to my next point.
If "my guy would do this" is okay for him, then it is okay for other players.
-----------------------------------------------------------------------------
Never forget that you are a group of people. Usually, permissions given to a player are implicitly given to other players... else, you have an unfair group and this will lead to frictions/frustrations for some.
So if the logic of "my guy would do that, there's nothing you can do about it" is valid for him, it is also valid for *you*.
For instance, I once had to deal with a problem player who was a bit similar to yours: strong-headed, constantly shifting arguments to turn a debate about the game into something personal between players. He was also passive-aggressive in how he showed his discontent at the table and was very stubborn that everything he did would be possible (even though that never was our argument; we were very clear that possible does not mean believable or desirable).
His favorite argument was, you guessed it, the "my guy would do that, it totally makes sense" line that he would give to us constantly. Frustrations were building to the point we decided we needed to have a talk about it... which did not work. Basically all we got from him was "you guys want to control my character", when what we really were trying to make him realize was that "Our characters *did try* to influence him, in-game, which is something our characters would do and makes total sense... but since it did not work we now have to have this discussion out of character".
I used all the tricks, showed him parts of the DMG which tackle group interactions and how it is important for the group to establish clear guidelines for what we're looking for, etc, to no avail.
When the discussion got heated between him and the GM, I suggested that we stop it there. I asked the problem player to think about what we said while stressing that this is nothing personal and is only about "managing the game" and I said "hope to see you all next week".
The next week we had a full table (surprisingly), but the problem player kept being problematic. He did more in-game shenanigans which impacted the whole group and derailed the game, once again, when he actually tried to sneak into the King's Chamber during the night we were spending at the Castle to try and steal the King's spellbook. He got caught and thrown in prison, and our group had to undergo a "trial". We succeeded in convincing the King that the thief was acting alone, and the GM salvaged the situation by having the King "punish us" by sending us on a quest.
But here's when the problematic "my guy syndrome" also became a solution: When the King asked us if we needed the thief for this quest, my character acted according to his own beliefs and personality and said, "No, let him rot in jail and hopefully let this be a lesson for him for when we get back". I have to specify we knew the quest would be done in less than 1 session, so *I thought this was a brilliant way to have our problem player get a taste of his own medicine*.
When he got frustrated at the table saying that it would be very boring for him to just watch us play for 3 hours and that I was being a bitch, I calmly told him about "those many times where we had to watch him for more than an hour because of his PC's shenanigans and the fact that if my action would cause 3-4 hours of boredom for him, his actions in the past caused at least 10 hours of boredom for me *and* all others around the table, minimum". I was polite but firm, and when he kept complaining I told him, "that's enough, I don't want to have this debate with you, especially if you are gonna be childish about it". And that was it. He sulked; we played.
But I believe that made him realize that we had just as many ways to influence the game and his character as he did, and that we just had chosen not to do so before, but that we would start enforcing consequences for his character's dumb moves in-character.
**TL;DR: Your characters do not have to rescue the barbarian the next time he derails a mission. Maybe your group will start thinking they are better off without him... and that's totally legit. It is an in-character reaction to a fellow comrade's actions and is totally legit and even uses the main argument of the problem player against him, in-game.** | It sounds like the problem is not how he plays; that is just a symptom. The problems are:
1. He does not care about the enjoyment of others in the group.
2. He does not take criticism like an adult.
So that is what you should be talking to him about. He is not being self-aware, whether intentionally or not.
Asking him if he would tolerate a player doing what he does is a good lead in. Ask him that when he has some time to actually think about it.
Having other players, and not just you as a GM, speak to him will help too. He may not realize this is how everyone sees him; he may see it as a one-on-one confrontation.
Here's a quote from Matt Colville's [The Wangrod Defense, Running the Game #76](https://www.youtube.com/watch?v=JoYR3eCFqoA), a wonderful video about this specific problem:
>
> ... But however you do it, at the end of the day, if a toxic player tries to defend themselves by saying "I'm just playing my character", a simple response is "We are *all* just playing our characters, but you're the only one making other people unhappy."
>
>
>
D&D is group storytelling, not a single-player video game where your actions don't affect anyone else.
But if his fun is ruining other people's fun, and continues to, then you may have to un-invite him and tell him why. Tell him: "It's not just about you." If his behavior ruins other people's fun and he doesn't care, that's probably going to start bleeding into other interactions anyway. |
343,393 | An example of what I'm talking about is on some political candidate websites, like BJ Lawson or Ron Paul's old site.
When you donate, it shows your name in Flash as a recent donor. It might also show a "goal" and how far along you are. Just curious if you can give me ideas on how to accomplish something similar, starting with how to accept credit cards in the first place.
I "think" I should use a 3rd party payment processor to avoid handling credit cards and the responsibility myself, like Paypal, but I'm not sure how my site (and the Recent Donor Flash app) would "know" that the payment was completed successfully. | 2008/12/05 | [
"https://Stackoverflow.com/questions/343393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The safest method is to have the application(s) that put files in the directory first put them in a different, temporary directory, and then move them to the real one (which should be an atomic operation even when using FTP or file shares). You could also use naming conventions to achieve the same result within one directory.
**Edit:**
It really depends on the filesystem, on whether its copy functionality even has the concept of a "completed file". I don't know the SMB protocol well, but if it has that concept, you could write an app that exposes an SMB interface (or patch Samba) and an API to get notified for completed file copies. Probably a lot of work though. | One simple possibility would be to poll at a fairly large interval (2 to 5 minutes) and only acknowledge the new file the second time you see it.
I don't know of a way in any OS to determine whether a file is still being copied, other than maybe checking if the file is locked. |
371,581 | How would I show that there is a ring $R$ with identity $1\_R$ and a subring $S$ not containing $1\_R$, but such that $S$ has its own identity $1\_S$ not equal to $1\_R$? | 2013/04/24 | [
"https://math.stackexchange.com/questions/371581",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/72195/"
] | A simple example (related to the one by **Alex P.**) is given by the rings of matrices
$$
\left\{
\begin{bmatrix}a&0\\0&0\end{bmatrix} : a \in F
\right\}
= S \subseteq
R = \left\{
\begin{bmatrix}a&b\\c&d\end{bmatrix} : a, b, c, d \in F
\right\}
$$
where $F$ might be $\Bbb{Z}, \Bbb{Q}, \Bbb{R}, \dots$.
Here
$$
\begin{bmatrix}1&0\\0&0\end{bmatrix}
= 1\_{S} \ne 1\_{R} =
\begin{bmatrix}1&0\\0&1\end{bmatrix}.
$$ | The rings of the form $(\mathbb Z\_n,\oplus,\odot)$ are quite simple, so let us try them.
If $R=\mathbb Z\_n$ then $1\_R=1$. A candidate for $1\_S$ can be only an element such that $1\_S\odot 1\_S=1\_S$.
In $\mathbb Z\_2$, $\mathbb Z\_3$, $\mathbb Z\_5$ we do not have non-trivial subrings.
In $\mathbb Z\_4$ the only element such that $a\odot a=a$ is $a=1$.
What about $R=\mathbb Z\_6$? Could you find a subring $S$ with the required properties? |
43,040,026 | I'm a little bit stuck on animations, so I have a div that is added dynamically using jQuery `.append()` so when the page is loaded the div content will be added and from css I'll apply some animations using `@keyframes`. My problem is when the div content is closed using jQuery `.remove()` because if the div content is removed how I will apply animation to this ? So basically on page loaded the content will animate from top to bottom and on close should go back from bottom to top, how can I do that reverse animation ? **I want to apply that reverse animation using only css not js.**
```
.child-container {
background: red;
height: 100px;
width: 150px;
padding: 10px;
animation-name: anime;
animation-duration: 1s;
}
@keyframes anime {
from,
0%,
100%,
to {
animation-timing-function: cubic-bezier(0.25, 0.60, 0.35, 1.00);
}
0% {
opacity: 0;
transform: translate3d(0, -200px, 0);
}
100% {
opacity: 1;
transform: translate3d(0, 0, 0);
}
}
```
```js
$(document).ready(function() {
$(".container").append($("<div class='child-container'>Hello Jimmy!<a class='close'><b>X</b></div>"));
$(".close").on('click', function() {
$(this).parent().remove();
});
});
```
```css
.container {
padding: 10px;
background: orange;
}
.child-container {
background: red;
height: 100px;
width: 150px;
padding: 10px;
animation-name: anime;
animation-duration: 1s;
}
.close {
float: right;
cursor: pointer;
}
.close:hover {
color: #fff;
}
/*ANIMATIONS*/
@keyframes anime {
from,
0%,
100%,
to {
animation-timing-function: cubic-bezier(0.25, 0.60, 0.35, 1.00);
}
0% {
opacity: 0;
transform: translate3d(0, -200px, 0);
}
100% {
opacity: 1;
transform: translate3d(0, 0, 0);
}
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
``` | 2017/03/27 | [
"https://Stackoverflow.com/questions/43040026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057912/"
] | You must add a class to handle a new "state" of your element in css.
But you shouldn't use animation and keyframe for that. Instead, use transition. Exemple :
```
.myElement {
top: 0;
transition: top 0.4s linear;
}
.meElementOpened {
top: 50%;
}
```
We set the transition on the element's default class (the one the element must always have) to handle the opening and the closing animation on the top property.
[transition doc](https://developer.mozilla.org/en-US/docs/Web/CSS/transition) | You don't need to use `keyframes` for this sort of animation. What you should rather do is toggle a class with changing `top` properties of your `.child-container` element and apply a `transition`.
Add the `initial` class with a `setTimeout` so that the class is applied and the animation happens. And remove the class on close. Note you can vary the `transition` timing here (I have provided a `1s` duration here).
Updated [fiddle](https://jsfiddle.net/nashcheez/9toav3uh/4/).
Refer code:
```js
$(document).ready(function() {
$(".container").append($("<div class='child-container'>Hello Jimmy!<a class='close'><b>X</b></div>"));
setTimeout(function() {
$(".child-container").addClass("initial");
}, 1);
$(".close").on('click', function() {
$(this).parent().removeClass("initial");
});
});
```
```css
.container {
padding: 10px;
background: orange;
}
.child-container {
background: red;
height: 100px;
width: 150px;
padding: 10px;
top: -200px;
position: relative;
transition: all 1s;
}
.initial {
top: 0;
}
.close {
float: right;
cursor: pointer;
}
.close:hover {
color: #fff;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
</div>
``` |
46,275,479 | I cannot achieve this one.
I want viewB to follow the start of viewA.
Then I want to create a constraint to have a space from the start of viewA to its parent.
[](https://i.stack.imgur.com/GeIg7.png)
.
Code I tried:
```
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:id="@+id/descriptionTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="32dp"
android:layout_marginStart="8dp"
android:text="Txt1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/descriptionTxt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Txt2"
app:layout_constraintEnd_toEndOf="@+id/descriptionTxt"
app:layout_constraintStart_toStartOf="@+id/descriptionTxt"
app:layout_constraintTop_toBottomOf="@+id/descriptionTxt" />
</android.support.constraint.ConstraintLayout>
```
The code above will show in Preview that only viewA will have a margin from the left. viewB does not follow the left of viewA.
Im using com.android.support.constraint:constraint-layout:1.0.2 | 2017/09/18 | [
"https://Stackoverflow.com/questions/46275479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8258130/"
] | Do not use `match_parent`. Instead, start using "0dp" for `match_parent` and define left/right or top/bottom parent constraints
Here is working code:
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/descriptionTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="32dp"
android:layout_marginStart="8dp"
android:text="Txt1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/descriptionTxt2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Txt2"
app:layout_constraintEnd_toEndOf="@+id/descriptionTxt"
app:layout_constraintStart_toStartOf="@+id/descriptionTxt"
app:layout_constraintTop_toBottomOf="@+id/descriptionTxt" />
</android.support.constraint.ConstraintLayout>
```
Also , it is good to use Guidelines to have uniform left/top/right/bottom margin. | >
> try this :
>
>
>
```
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/descriptionTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Txt1"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="@+id/descriptionTxt2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Txt2"
android:layout_marginTop="8dp"
app:layout_constraintRight_toRightOf="@+id/descriptionTxt"
app:layout_constraintLeft_toLeftOf="@+id/descriptionTxt"
app:layout_constraintTop_toBottomOf="@+id/descriptionTxt"
/>
</android.support.constraint.ConstraintLayout>
``` |
26,232,428 | I am trying to make a regex on field which accepts in the following:
Where X is a numerical value between 0-9 so 3 numbers before the - and three after the dash.
I started with the following but I got lost in adding validation after the dash.
```
([0-9-])\w+([0-9-])
``` | 2014/10/07 | [
"https://Stackoverflow.com/questions/26232428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1440586/"
] | ```
var example = "123-455";
var pattern = @"\A(\d){3}-(\d){3}\Z";
var result = Regex.Match(example, pattern);
```
This will not only search for the pattern within your string, but also make sure that the beginning and end of the pattern is at the beginning and end of your target string. This ensures that you won't get a match e.g. for:
```
"silly123-456stuff" or "0123-4567".
```
In other words, it both looks for a pattern, and limits its length by anchoring it to the begining and end of the string. | ```
string pattern = @"^([0-9]{3})-([0-9]{3})$";
Regex rgx = new Regex(pattern);
``` |
1,523 | I've set up a channel using categories to distinguish between different blog post types. The majority will probably be in one category, so it would be great to be able to specify a default category. However, as far as I can see the Category field type (unlike, say, the Drop Down field type) doesn't give you the option to set a default... Is there any way of doing this? | 2014/07/30 | [
"https://craftcms.stackexchange.com/questions/1523",
"https://craftcms.stackexchange.com",
"https://craftcms.stackexchange.com/users/328/"
] | You could output the categories in a way that makes them look like they are from a specific category when they don't have any categories assigned to them.
When you're outputting any of the entries, just add a custom link if there isn't a category assigned:
```twig
{% if entry.categories|length %}
{% for category in entry.categories %}
<a href="/blog/category/{{ category.url }}">{{ category.title }}</a>
{% endfor %}
{% else %}
<a href="/blog/category/default-category-slug">Default Category Title</a>
{% endif %}
```
Create a route that points "/blog/category/default-category-slug" to your filtered listing template (/blog/index, /blog/category etc.).
On the filtered listing template check if the default category slug is in the URL:
```twig
{% if craft.request.getSegment(3) == 'default-category-slug' %}
```
If that evaluates to true, you can now get the entries without any categories assigned to them and loop through them, see this question: [How to find entries with no category](https://craftcms.stackexchange.com/questions/603/how-to-find-entries-with-no-category):
```twig
{% set uncategorized = craft.entries.section('blog').search('-categories:*') %}
{% for entry in uncategorized %}
{# show entry #}
{% endfor %}
```
---
Any other times you need to get the entries that "have" the default category, to loop through them, use [`.relatedTo`](http://buildwithcraft.com/docs/relations) on etc., instead of using:
```twig
{% set entriesWithDefaultCategory = craft.entries.section('blog').relatedTo('the-default-category') %}
```
Use this like on the filtered listing above:
```twig
{% set uncategorized = craft.entries.section('blog').search('-categories:*') %}
``` | Not with the out-of-the-box field types. You could create a field type that is category+default. The [Default Color](https://github.com/marionnewlevant/craft-defaultcolor) plugin might be a good place to start. |
8,703,496 | I want to implement a HashMap in Python. I want to ask a user for an input. depending on his input I am retrieving some information from the HashMap. If the user enters a key of the HashMap, I would like to retrieve the corresponding value.
How do I implement this functionality in Python?
```
HashMap<String,String> streetno=new HashMap<String,String>();
streetno.put("1", "Sachin Tendulkar");
streetno.put("2", "Dravid");
streetno.put("3","Sehwag");
streetno.put("4","Laxman");
streetno.put("5","Kohli")
``` | 2012/01/02 | [
"https://Stackoverflow.com/questions/8703496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1118984/"
] | [Python dictionary](http://docs.python.org/library/stdtypes.html#dict) is a built-in type that supports key-value pairs.
```
streetno = {"1": "Sachin Tendulkar", "2": "Dravid", "3": "Sehwag", "4": "Laxman", "5": "Kohli"}
```
as well as using the dict keyword:
```
streetno = dict({"1": "Sachin Tendulkar", "2": "Dravid"})
```
or:
```
streetno = {}
streetno["1"] = "Sachin Tendulkar"
``` | All you wanted (at the time the question was originally asked) was a hint. Here's a hint: In Python, you can use [dictionaries](http://docs.python.org/tutorial/datastructures.html#dictionaries). |
668,825 | On a standard computer, I change the size of the desktop icons by pressing Ctrl + rolling the scroll wheel (the same operation for zooming in or out in most applications).
But how can I change the icons' size on a touch device, like a Surface tablet, without a mouse ? I tried the "pinch-to-zoom" gesture, which works for zooming in or out in most apps, but it does nothing on the desktop. | 2013/11/02 | [
"https://superuser.com/questions/668825",
"https://superuser.com",
"https://superuser.com/users/233470/"
] | For the Surface tablet, you can hold your finger on a blank area of the desktop screen for a few seconds, and a menu window pops up. Pick `Personalize` > `Display` and choose the size of all items on the desktop. There's an option to choose "Custom sizing options" and pick a larger size (up to 200% of the default). [This link shows how to do this](http://howto.cnet.com/8301-11310_39-57568836-285/five-usability-tips-for-microsofts-surface-rt/). | Its really simple,
press the CTRL key on your keyboard, and roll the mouse scroll up and down to change the icons of desktop screen.
This method works for every page, if you are on desktop, explorer, or webpage. |
71,617,117 | If i write code line like
```
string employeeName= objEmp?.EmployeeName;
```
then this line is not being considered by code coverage because of `?.`.
What i will have to do to consider this line by code coverage in .net core. | 2022/03/25 | [
"https://Stackoverflow.com/questions/71617117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10683751/"
] | using data.table:
```
library(data.table)
setDT(x)[grepl("^Page.",section)==F, header:=section] %>%
.[,header:=zoo::na.locf(header)] %>%
.[section!=header,header:=paste0(header, " / ",section)] %>%
.[,.(section = header)] %>%
.[]
1: BOOK I: Introduction
2: BOOK I: Introduction / Page one: presentation
3: BOOK I: Introduction / Page two: acknowledgments
4: MAGAZINE II: Considerations
5: MAGAZINE II: Considerations / Page one: characters
6: MAGAZINE II: Considerations / Page two: index
7: BOOK III: General Principles
8: BOOK III: General Principles
9: BOOK III: General Principles / Page one: invitation
``` | An slightly simpler `data.table` approach:
```
library(data.table)
setDT(x)
x[, g := cumsum(grepl('(BOOK|MAGAZINE)', section))]
x[, section := ifelse(seq_along(section) == 1,
section, paste(section[1], section, sep = ' / ')), by = .(g)]
x[, g := NULL]
```
The output is:
```
> x
section
1: BOOK I: Introduction
2: BOOK I: Introduction / Page one: presentation
3: BOOK I: Introduction / Page two: acknowledgments
4: MAGAZINE II: Considerations
5: MAGAZINE II: Considerations / Page one: characters
6: MAGAZINE II: Considerations / Page two: index
7: BOOK III: General Principles
8: BOOK III: General Principles
9: BOOK III: General Principles / Page one: invitation
``` |
727,534 | I have been pondering over this question for a few months now. Why exactly do quintic equations have no closed *general* expression for their roots? Looking at graphs and reading about it hasn't really convinced me.
---
<http://en.wikipedia.org/wiki/Quintic_function>
---
Post scriptum: Pardon me if this question is too broad for the forum here but I do not know where else to expect a more convincing explanation from. I am putting it under the 'open questions' category for 'quintic enthusiasts' like myself. :) Thanks in advance. | 2014/03/26 | [
"https://math.stackexchange.com/questions/727534",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/98900/"
] | The short answer, is *why should they*?
Radicals are solutions to special equations of the form $$
?^n = x
$$
which we commonly abbreviate as $\sqrt[n]{x}$, whereas you are looking at arbitrary equations of the form $$
\sum\_{i=0}^n \lambda\_n x^n = 0 \text{.}
$$
Why would you even expect that you can find roots of arbitrary equations by repeatedly finding radics? Sure, it works for $n< 5$, but that only shows these equations are also somewhat special.
To actually *prove* that this doesn't work for $n \geq 5$, Galois theory basically looks at the numbers you get if you start out with some field, say the rational numbers $\mathbb{Q}$, and add to it a particular radical. If you pick $x^2 = 2$, you must thus add the "numbers" $\sqrt{2}$ and $-\sqrt{2}$, and the everything you can *algebraically* express, like $3 + \sqrt{2}$, $7\sqrt{2}$, $\frac{1}{\sqrt{2}}$ and so on. Then you pick a new radical, and do the same over again.
Finally, you compare that with the "numbers" you get if you add *all* the zeros of some polynomial $p = \lambda\_0 + \lambda\_1x + \ldots + \lambda\_n x^n$ in one swoop. In algebraic terms, that means finding a field extensions where $p$ has $n$ zeros. And then you ask: Could I have gotten the same field by the process above, i.e. by repeatedly adding *radical*, i.e. zeros of $x^n = 0$? As it turns out, for $n \leq 4$ the answer is yes, but for $n \geq 5$, there are polynomials $p$ where the answer is no.
But if there was a *formula* using only $\cdot,/,+,-$ and radicals that expresses the roots of $p(x)$, then such roots would *always* have to be reachable by the iterative process above, since that why you do if you *evaluate* such a formula. Thus, start with $n=5$, there's no such general formula. | There are different reasons for insolvability of quinitics in radicals (or in elementary numbers): e.g. algebraic independence, symmetry restrictions, topological restrictions.
Chow [Chow 1999] gives his
Corollary 1:
"If Schanuel's conjecture is true, then the algebraic numbers in" the explicit [elementary numbers](https://en.wikipedia.org/wiki/Elementary_number) "are precisely the roots of polynomial equations with integer coefficients that are solvable in radicals."
That means, the quintics that are not solvable in radicals cannot be solved by elementary numbers (means by applying [elementary functions](https://en.wikipedia.org/wiki/Elementary_function)).
All solutions of polynomial equations can be represented with help of transcendental functions, e.g. theta functions, elliptic functions, Bring radicals, exponential/elliptic modular functions, Siegel modular forms, hyperelliptic integrals.
Here are general closed-form solution formulas for the quintics:
<https://en.wikipedia.org/wiki/Bring_radical#Solution_of_the_general_quintic>
[How to solve fifth-degree equations by elliptic functions?](https://math.stackexchange.com/questions/540964/how-to-solve-fifth-degree-equations-by-elliptic-functions)
$\ $
[[Chow 1999] Chow, T.: What is a closed-form number. Am. Math. Monthly 106 (1999) (5) 440-448](http://timothychow.net/closedform.pdf) |
15,309,077 | I have string:
```
<p justify;"="">Verslo centrai Lietuvos nekilnojamojo turto plėtros asociacijos konkurse ...</p>
```
and want want remove tag
```
<p justify;"=""></p>
```
my code:
```
$content = strip_tags($text, '<p>');
```
but i get empty string: `string(0) ""` , what I do wrong ? | 2013/03/09 | [
"https://Stackoverflow.com/questions/15309077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1067795/"
] | Since your HTML is not properly formatted you could choose a `preg_replace()` approach:
```
$text = '<p justify;"="">Verslo centrai Lietuvos nekilnojamojo turto plėtros asociacijos konkurse ... </p>';
$content = preg_replace('/<[^>]*>/', '', $text);
var_dump($content);
// string(108) "Verslo centrai Lietuvos nekilnojamojo turto plėtros asociacijos konkurse ... "
```
[Codepad Example](http://codepad.org/7givAwHA)
On [strip\_tags() docs](http://php.net/manual/en/function.strip-tags.php) it says: *Because strip\_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.*
Also second parameter is for `$allowable_tags`. | From PHP 7.4.0 the strip\_tags() alternatively accepts an array with allowable tags,
then this:
```
<?php
$html = '<div id="my-div"><p>text<strong><a href="#link"></a></strong></p></div>';
echo strip_tags($html, ['p', 'a']); //accept p and a tags
```
Return this:
```
<p>text<a href="#link"></a></p>
```
Note that only the disallowed tags have been removed. |
45,647,200 | I have a problem with creating GlobalVariables for my webform app.
I am creating a webform app with Visual Studio 2015, VB.net, ASP.net
I followed the instruction that I found on this and other sites but with no successs.
I did the folowwing:
1 Create the module file: Module1.vb
With this scripts:
Public Module GlobalVariables2
Public ModuleEMAIL As String = "ModuleEMAIL@zzzzzzzz"
End Module
Public Class GlobalVariables
Public Shared Property clasEMAIL As String = "clasEMAIL@zzzzzzzz"
End Class
2. But when ever I try to call the variables a compiler error occur.
Function fnBtnText()
Button1.Text = GlobalVariables.clasEMAIL
' generate: Compiler Error Message: BC30451: 'GlobalVariables' is not declared. It may be inaccessible due to its protection level.
```
Button2.Text = ModuleEMAIL
```
'generate: Compiler Error Message: BC30451: 'ModuleEMAIL' is not declared. It may be inaccessible due to its protection level.
End Function
What meas “protection level” in this case?
When the scripts are moved tot another spacename area the same happens.
What am I doing wrong? Did I missed something?
I hope someone van help me out.
Many greatigs, Ton Daamen | 2017/08/12 | [
"https://Stackoverflow.com/questions/45647200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8157587/"
] | Using SimpleXML, you can build up the hierarchy of the XML document using...
```
$data = 'Rajeet Singh|email@gmail.com|0123456789|Delhi
Abhishek|email2@gmail.com|0123456987|Pune';
$lines = explode(PHP_EOL, $data);
$xml = new SimpleXMLElement('<user />');
$root = $xml->user;
foreach($lines as $line){
$data = explode("|",$line);
$user = $xml->addChild('item');
$user->addChild('name', $data[0]);
$user->addChild('email', $data[1]);
$user->addChild('mobile', $data[2]);
$user->addChild('address', $data[3]);
}
echo $xml->asXML();
```
One thing which I don't do is create elements with a numeric postfix, you wouldn't normally (in XML) have elements `item0`, `item1` as this means they are different element types. You wold simply have them all as `item`. If you needed an index, you could create them with `item id="0"` so the id becomes the identifier (for example the unique ID of a database). | For example, you can write as follows.
```
<?php
$string = <<<EOM
Rajeet Singh|email@gmail.com|0123456789|Delhi
Abhishek|email2@gmail.com|0123456987|Pune
EOM;
$line = explode(PHP_EOL, $string);
$tags = ['name', 'email', 'mobile', 'address'];
$xml = '';
$xml .= "<user>" . PHP_EOL;
foreach($line as $key => $row){
$elements = explode("|",$row);
$xml .= "<item{$key}>" . PHP_EOL;
$boxes = array_map(NULL, $elements, $tags);
foreach($boxes as $box){
$xml .= "<{$box[1]}>{$box[0]}</{$box[1]}>" . PHP_EOL;
}
$xml .= "</item{$key}>" . PHP_EOL;
}
$xml .= "</user>" . PHP_EOL;
echo $xml;
```
**EDIT**
If you want to format the array from `Text file`.
```
$string = <<<EOM
Rajeet Singh|email@gmail.com|0123456789|Delhi
Abhishek|email2@gmail.com|0123456987|Pune
EOM;
$tags = ['name','email','mobile','address'];
$users_array = array_map(function($n) use($tags){
$elements = explode('|', $n);
return array_combine($tags, $elements);
},explode(PHP_EOL, $string));
var_dump($users_array);
```
Result...
```
array(2) {
[0] =>
array(4) {
'name' =>
string(12) "Rajeet Singh"
'email' =>
string(15) "email@gmail.com"
'mobile' =>
string(10) "0123456789"
'address' =>
string(5) "Delhi"
}
[1] =>
array(4) {
'name' =>
string(8) "Abhishek"
'email' =>
string(16) "email2@gmail.com"
'mobile' =>
string(10) "0123456987"
'address' =>
string(4) "Pune"
}
}
``` |
38,944,442 | I followed [draft-js document](https://facebook.github.io/draft-js/docs/overview.html#content) to create a very simple demo of draft-js.
Everything seems work well, but when I open the url in Chrome, I can only see a white blank page (there is a hidden editor component there but is not visible)
There is no error on the console of the browser.
The demo project is here: <https://github.com/js-demos/react-draft-js-demo>, you can clone it and follow the readme to run it.
I have reviewed the code very carefully, but can't figure out why. | 2016/08/14 | [
"https://Stackoverflow.com/questions/38944442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342235/"
] | If you just use the sample code on the official website of Draft.js, you will see nothing on the page. It's just a blank text input field. If you click that field, you could type something. Draft.js is not a out of the box plugin, but a "a framework for building rich text editors in React".
 | Actually, I tried a lot to solve this problem but in vain. What I did is using another package that is built on the top of draft js, and It's working fine.
you can find it here:<https://jpuri.github.io/react-draft-wysiwyg/#/> |
1,275,724 | I've read the SVN red-bean book, and research how people layout their SVN repos, we're thinking of using SVN for our product, so would like suggestions on a repos layout.
The product is a desktop application, consisting of a number of .exe, graphics, etc. The current source layout is something like:
```
Program 1
Program 2
Program 3
Common Code
Graphics
```
It's important to note that sometimes Program 1 may use source files that are in Program 2 as well. Common Code and Graphics are used by all programs.
The main question is, if all our users are currently using version 2009 of the product, and we'll need to maintain it, release service packs etc, and begin development of version 2010 at the same time, should trunk contain changes for the 2009 release, or the 2010 release?
```
trunk (where 2010 development happens)
Program 1
Program 2
Program 3
Common Code
Graphics
branches
v2009
Program 1
Program 2
Program 3
Common Code
Graphics
tags
2009 (read only)
2009 SP1 (read only)
2009 SP2 (read only)
```
Would the above be the recommended layout? Or should the trunk contain 2009 development, and the 2010 development in some sort of testing branch?
The above layout does mean if a developer wish to work on Program 1, they'll still need to checkout the entire project, including Program 2, Program 3.
**EDIT, more question**
Thanks for the response to far. Got further question:
During development, there'll be 4 to 6 months where version 2009 is still being use by users and will need to be maintain, while 2010 development is going on. During that time, what's the best way to apply changes to both 2009 and 2010 release? Should those changes be done in the 2009 branch them port to 2010, or vice versa? | 2009/08/14 | [
"https://Stackoverflow.com/questions/1275724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26305/"
] | For every project I've worked in that's been managed by Subversion, the trunk has held the "development" branch. Each release gets a tag (or branch, should it end up being maintained further). Any changes to the branches that are relevant to the devel branch are merged in as necessary. | For what your doing your better off going with GIT, for each major release do a branch. This way if any bug comes up in a major release you can switch back to the branch and then cherry pic different commits in your GIT repository into your release branch. |
4,392,552 | How can I program hourglass behavior (similar like on picture) for my game?

Should I make something like gravitation and process each grain of sand?
What about digital hourglass (like on this clocks)?
 | 2010/12/08 | [
"https://Stackoverflow.com/questions/4392552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446876/"
] | Tangentially, you can model falling sand with [cellular automata](http://www.openprocessing.org/visuals/?visualID=6622). I'd not considered using it for an hourglass simulation, but in principle it might work quite nicely, and be a fun project.
Looking at your digital hourglass -- either the grains move in set patterns, or it *might* use something like this CA. | Modelling it is making a rod for your own back, you'd be better off just drawing the frames by hand and playing them back.
But -- if maths is your thing you could:
* work out the volume of sand in the top.
* define a rate of volume flow through the neck (keep this arbitrary as you'll want to tweak it).
* at any given time you can use the flow rate to work out how much sand has left the top.
* if you know the shape of the top vessel you can work out the current height of sand given the current volume of sand.
* if you know the shape of the bottom vessel you can work out the current height of sand given the volume of sand that's flowed through the neck. |
69,741,708 | I am attempting to reference a column in another dataframe (df2) based on a column of column names in my primary dataframe (df1$reference) to return the extact value where the ID and column name match in a new column (df1$new\_col). Here is a simplified example of my data and the desired outcome:
[](https://i.stack.imgur.com/BkKcz.png)
I have tried rbind but ran into errors due to differences in the number of rows/columns. I also tried bind\_rows/bind\_cols, but am having a hard time joining only the referenced data (I would like to avoid a large join because my real data has many more columns). I feel like indexing would be able to accomplish this but I am not as familiar with indexing outside of simple tasks. I'm open to any and all suggestions / approaches! | 2021/10/27 | [
"https://Stackoverflow.com/questions/69741708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15453998/"
] | We may use `row/column` indexing
```
DF1$new_col <- DF2[-1][cbind(seq_len(nrow(DF1)),
match(DF1$reference, names(DF2)[-1]))]
```
-output
```
> DF1
ID value reference new_col
1 1 4 colD no
2 2 5 colD no
3 3 6 colE no
```
### data
```
DF1 <- structure(list(ID = 1:3, value = 4:6, reference = c("colD", "colD",
"colE")), class = "data.frame", row.names = c(NA, -3L))
DF2 <- structure(list(ID = 1:3, colD = c("no", "no", "yes"), colE = c("yes",
"no", "no"), colF = c("no", "yes", "no")),
class = "data.frame", row.names = c(NA,
-3L))
``` | Maybe something like this?
```
library(dplyr)
left_join(DF1, DF2, by="ID") %>%
mutate(New_col = case_when(reference=="colD" ~ colD,
reference=="colE" ~ colE,
reference=="colF" ~ colF)) %>%
select(ID, value, reference, New_col)
```
```
ID value reference New_col
1 1 4 colD no
2 2 5 colD no
3 3 6 colE no
``` |
1,792,471 | I've been thinking about the access web-based applications have to an OS.
I'm curious:
1. What is the best way of determining
this as it currently stands?
2. Is the trend leaning toward more, or
less access?
3. What functionalities should be
open/closed?
A simple example would be.. say your g-mail alerted you in the task-bar when an incoming e-mail is received. | 2009/11/24 | [
"https://Stackoverflow.com/questions/1792471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13954/"
] | ```
string[] s = initialize the array...
var subset = s.Skip(1).Take(s.Length - 2).ToArray();
``` | If you want to avoid manually indexing the array. Don't try to pull request that anywhere though:
```
var newArray = oldArray.Skip(1).Reverse().Skip(1).Reverse().ToArray()
``` |
11,179,853 | I've this string which I'm displaying in my xhtml page.
I want to cut it down to some limit and put three or four dots at the end of the string.
This is the ui:repeat code:
```xhtml
<ui:repeat var="userMsg" value="#{messagesManagedBean.paginator1.model}">
<center><img class="h-diff" src="../images/differentiator-profile.jpg" width="437" height="1" /></center>
<div id="message">
<div id="senderImg">
<img class="senderImg" src="../images/profile-pic.jpg" width="50" height="50" />
</div>
<div id="message-txt-area">
<div id="senderName">
<p:commandLink styleClass="senderName" value="#{userMsg.userFullname}" action="#{myProfileManagedBean.loadProfileFrontInformation(userMsg.userId)}"></p:commandLink>
</div>
<ui:fragment rendered="#{userMsg.isRead}">
**<div id="message-txt">
#{userMsg.message}
</div>**
</ui:fragment>
<ui:fragment rendered="#{not userMsg.isRead}">
**<div id="message-txt" class="msgNotRead">
#{userMsg.message}
</div>**
</ui:fragment>
<div id="msgAction">
<p:commandLink styleClass="reply-btn" action="#{messagesManagedBean.setSelectedMsg(userMsg)}"
value="Reply" oncomplete="messageDialog.show()" update=":messagesForm:dialogGrid">
<f:param name="userMsg" value="#{userMsg}" />
</p:commandLink>
<ui:fragment rendered="#{userMsg.isRead}">
<p:commandLink styleClass="open-btn" value="Open" action="#{messagesManagedBean.setSelectedMsg(userMsg)}"
oncomplete="messageDialog2.show()" update=":messagesForm:dialogGrid2">
<f:param name="userMsg" value="#{userMsg}" />
</p:commandLink>
</ui:fragment>
<ui:fragment rendered="#{not userMsg.isRead}">
<p:commandLink styleClass="open-btn" value="Open" action="#{messagesManagedBean.setSelectedMsg(userMsg)}"
actionListener="#{messagesManagedBean.messageOpenedListener(userMsg.messageId)}"
oncomplete="messageDialog2.show()" update=":messagesForm:dialogGrid2">
<f:param name="userMsg" value="#{userMsg}" />
</p:commandLink>
</ui:fragment>
</div>
</div>
</div>
</ui:repeat>
```
I want to do the effect on the above code in bold... i.e. on the message which is a string.
I've tried `text-overflow:ellipsis` but didn't work even in Chrome. | 2012/06/24 | [
"https://Stackoverflow.com/questions/11179853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291826/"
] | For `text-overflow: ellipsis;` to work, three things are required:
* `overflow` must be set to `hidden`, `scroll`, or `auto`
* `white-space: nowrap;`
* the text must be longer than the element is wide
Demo: <http://jsfiddle.net/ThinkingStiff/mCJCR/>
```css
#message-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
``` | `text-overflow: ellipsis` only works if you have a defined width/height constraint and `overflow: hidden`. |
47,257,273 | I want to use the [Factory Pattern](https://www.tutorialspoint.com/design_pattern/factory_pattern.htm) using TypeScript to convert raw data into a `User`. I have two different types of `User`s: `Employee` and `Customer`. Both extend the base class and compile without problems. Below is an extremely simplified version of these three classes.
```
abstract class User {
constructor(data: any) { }
static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
return new this(data);
}
}
class Employee extends User {
static '@type' = 'Employee';
static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
return new this(data);
}
}
class Customer extends User {
static '@type' = 'Customer';
static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
return new this(data);
}
}
```
Simple enough. Now for the Factory. I want to create a Factory that will take raw data returned from the server and convert that data into something the rest of the system can use (i.e. an instance of `User`). What I *want* to do is something like
```
class UserFactory {
/**
* Vends a User constructed from the raw data from the server.
*
* @param userData (Object) - the User definition, as obtained from the server
*
* @return (User) the User initialized from `userData`
*/
static vend<T extends User>(userData: any): T {
switch (userData['@type']) {
case Employee['@type']:
return Employee.createFromServer(userData);
case Customer['@type']:
return Customer.createFromServer(userData);
default:
throw new Error('Unknown User type.');
}
}
}
```
As you can probably guess (since I'm here and not relaxing over the weekend), that doesn't work. I get the following error:
>
> Type 'Employee' is not assignable to type 'T'.
>
>
>
Since `T` extends `User` and `Employee` extends `User` without adding or removing *anything* (in this simplified version), it seems like the above *should* work. What's more annoying is it seems the above will work in other languages (e.g. Java (tested), C++), I'm just not sure why it won't work in this situation.
Somebody on GitHub suggested that the problem might be with [overloading the constructor](https://github.com/Microsoft/TypeScript/issues/7955), but clearly that's not occurring here.
So, why isn't `Employee` assignable to type `T`? (How) can I get the above to work? Is there a better way to handle this in TypeScript? A correct answer will answer at least the first 2 questions.
Addendum
--------
`createFromServer()` is redefined in subclasses for a reason. This is a minimally reproducible example. The constructors don't actually take the raw data from the server. Instead the `createFromServer()` converts the raw data into arguments the constructors can understand. | 2017/11/13 | [
"https://Stackoverflow.com/questions/47257273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263719/"
] | [](https://i.stack.imgur.com/LB4QQ.gif)
If this is what you want, I will update both this answer and the demo serveral hours later.
I write the demo in a hurry, so apologize for the ugly UI and the code style.
The demo project is on [Github](https://github.com/DevNewbee/JSTransition).
If you are familiar with the transition, then the key trick here is you just need to add an animation view to the top of the `UIViewControllerContextTransitioning.container` and move it to the position where it would be displayed in destination view controller. When you complete the transition, just remove this animation view directly or by animation. | Custom UIViewController transition - Like today tab of appstore app
Try This : -
<https://github.com/MilanSavaliya321/appstore-clone>
[](https://i.stack.imgur.com/vE9ts.gif) |
464,326 | Does existence of a limit at a point not necessarily mean that it's differentiable at that point?
Take this function:
$$f(x) = \frac{(x - 1)^{2}}{x - 1}$$
The function is not defined at x = 1, but as x approaches 1, f(x) goes to 0; i.e., a "removable discontinuity." But the function is not differentiable at 1, right? | 2013/08/10 | [
"https://math.stackexchange.com/questions/464326",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/89812/"
] | Continuity is necessary for the existence of a $f'$, that means if a function $f$ has discontinuity at $x=a$ then $f$ is not differentiable at $x=a$. Your function is not continuous at $x=1$, therefore it's not differentiable at $x=1$. Moreover, continuity is not a sufficient condition.For example $|x|$ is continuous over $\mathbb{R}$ but it's not differentiable at $x=0$. | I think it depends on the domain of the function.
1. if the domain is $\mathbb{R}$, then $f(x)$ is not defined at $x=1$, so it's not continuous and not differentiable;
2. if the domain is $\mathbb{R}$ but $x\ne 1$, then it's continuous and differentiable in its domain. |
72,677,634 | I have been working on a flutter project and I have noticed ***Avoid using private types in public APIs***.
Is there a way to fix this warning?
```
class SubCategoriesPage extends StatefulWidget {
final MainModel mainModel;
// final Ads ad;
const SubCategoriesPage(this.mainModel, {Key? key}) : super(key: key);
@override
_SubCategoriesPage createState() { // Avoid using private types in public APIs.
return _SubCategoriesPage();
}
}
``` | 2022/06/19 | [
"https://Stackoverflow.com/questions/72677634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13057145/"
] | Since this is a `StatefulWidget`, I'm guessing the `_SubCategoriesPage` class inherits from `State`, since it's being returned by `createState()`.
If so, the return type can be changed to `State`. Since `State` is public, it can safely be returned from the public `createState()` method. | I had the same issue using this code
```
class MyPage extends StatefulWidget {
const MyPage({super.key});
@override
_MyPageState createState() => _MyPageState();
}
```
I tried using this method - State createState() { // Avoid using private types in public APIs.
return \_MyPageState();
but than I got this error message - The name MyPageState isn't a type so it can't be used a type argument. |
3,351,417 | I've got an ajax loaded image gallery that loads an image to the dom and then removes it and loads in the next one and rotates in that way.
Next to where the image comes in i've got a list of static names (they're there on page load and don't do anything) for the images.
What i want to do is as the image is loaded into the dom, i want to match part of it's src attribute to the class / id / rel / whatever of the name in the list.
The desired result is that as the image displays, it's name gets underlined and then when it goes it's name is not underlined anymore as the next images name has now become underlined...
I'm having real trouble with this, if anyone can show me how to do this i would be really bloody grateful!
Thank you! | 2010/07/28 | [
"https://Stackoverflow.com/questions/3351417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209986/"
] | Without all complex Regex in the way you can use id/rel attributes as you suggested initially. With this method you would not be matching the images src tag but matching it's ID attribute.
Here are your descriptions
```
<p id="item_desc_5">Plane</p>
<p id="item_desc_6">Car</p>
```
Here is your CSS class for the underline
```
<style type="text/css">.underline { text-decoration: underline; }</style>
```
Here is an example forat of the ajax'ed in
```
<img src="somepath.jpg" id="item_image_6" />
```
When loading in your image and you can match that with jquery you can do
```
<script type="text/javascript">
jQuery(document).ready(function($) {
var myImage = $('#some_image');
var title = $('#item_desc_' + myImage.attr('id').replace('item_image_', ''));
title.addClass('underline');
});
</script>
```
Now an image with id item\_image\_6 would match the p tag with item\_desc\_6
It was a little difficult for me to give you the exact answer because i couldn't see your code that was ajaxing in the content. | EDITED - I'd do something like this
```
$('#imageid').load(function(){
// image was loaded
part = /some regex/.exec($(this).attr('src'));
if(part != null) $('p').filter('[src*="'+part+'"]').addClass('underline');
}).attr('src','new_src.jpg');
```
the /some regex/ should return the part you want to match |
7,390,496 | I am creating a simple data frame like this:
```
qcCtrl <- data.frame("2D6"="DNS00012345", "3A4"="DNS000013579")
```
My understanding is that the column names should be "2D6" and "3A4", but they are actually "X2D6" and "X3A4". Why are the X's being added and how do I make that stop? | 2011/09/12 | [
"https://Stackoverflow.com/questions/7390496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/908431/"
] | I do not recommend working with column names starting with numbers, but if you insist, use the `check.names=FALSE` argument of `data.frame`:
```
qcCtrl <- data.frame("2D6"="DNS00012345", "3A4"="DNS000013579",
check.names=FALSE)
qcCtrl
2D6 3A4
1 DNS00012345 DNS000013579
```
One of the reasons I caution against this, is that the `$` operator becomes more tricky to work with. For example, the following fails with an error:
```
> qcCtrl$2D6
Error: unexpected numeric constant in "qcCtrl$2"
```
To get round this, you have to enclose your column name in back-ticks whenever you work with it:
```
> qcCtrl$`2D6`
[1] DNS00012345
Levels: DNS00012345
``` | The X is being added because R does not like having a number as the first character of a column name. To turn this off, use `as.character()` to tell R that the column name of your data frame is a character vector. |
2,805,678 | Here's my attempt at limiting the number of characters entered into a text area:
```
var limit = 255;
var txt = $('textarea[id$=txtPurpose]');
$(txt).keyup(function() {
var len = $(this).val().length;
if (len > limit) {
//this.value = this.value.substring(0, 50);
$(this).addClass('goRed');
$('#spn').text(len - limit + " characters exceeded");
return false;
} else {
$(this).removeClass('goRed');
$('#spn').text(limit - len + " characters left");
}
});
```
However, it doesn't work very well. How can I prevent a user from entering text once a certain limit has been reached, say 255 characters? | 2010/05/10 | [
"https://Stackoverflow.com/questions/2805678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275390/"
] | ```
$(this).val( $(this).val().substring(0, limit) );
``` | ```
var limit="NO of characters";<br><br>
$(this).val( $(this).val().substring(0, limit) );
``` |
37,921,865 | I'm doing a query on a really simple table in a typo 3 task. However, only the fields "uid" and "pid" are returned, the other fields are `NULL`.
My Entity:
```
<?php
namespace Name\SampleExtension\Domain\Model;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
class MailAgent extends AbstractEntity
{
/**
* @var integer
*/
protected $uid;
/**
* @var string
*/
protected $customeremail;
/**
* @var string
*/
protected $searchparameters;
/**
* @var string
*/
protected $resultlist;
public function getUid()
{
return $this->uid;
}
public function setCustomerEmail($customeremail)
{
$this->customeremail = $customeremail;
}
public function getCustomerEmail()
{
return $this->customeremail;
}
public function setSearchParameters($searchparameters)
{
$this->searchparameters = $searchparameters;
}
public function getSearchParameters()
{
return $this->searchparameters;
}
public function setResultList($resultlist)
{
$this->resultlist = $resultlist;
}
public function getResultList()
{
return $this->resultlist;
}
}
?>
```
The Repository:
```
<?php
namespace Name\SampleExtension\Domain\Repository;
use TYPO3\CMS\Extbase\Persistence\Repository;
class MailAgentRepository extends Repository
{
public function findByUids($uids)
{
$query = $this->createQuery();
foreach ($uids as $uid) {
$constraints[] = $query->equals('uid', $uid);
}
return $query->matching(
$query->logicalOr(
$constraints
)
)->execute();
}
}
?>
```
And the query inside the task:
```
<?php
namespace Name\SampleExtension\Task;
use TYPO3\CMS\Scheduler\Task\AbstractTask;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
use Name\SampleExtension\Domain\Model\MailAgent;
use Name\SampleExtension\Domain\Repository\MailAgentRepository;
class MailAgentCheckup extends AbstractTask
{
public function execute() {
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$this->MailAgentRepository = $objectManager->get(MailAgentRepository::class);
$query = $this->MailAgentRepository->createQuery();
$allCustomers = $this->MailAgentRepository->findAll();
foreach ($allCustomers as $customer) {
var_dump($customer);
}
return true;
}
}
?>
```
I have no idea why the other fields are not returned, but the uid and the pid are. My guess is that I need to declare the mapping somewhere else.
EDIT: Heres the content of my TCA, which is probably wrong or not enough, but since I'm working on a existing extension I was copying from the TCA's of the tables that work.
**tx\_sampleextension\_domain\_model\_mailagent.php**
```
return [
'columns' => [
'uid' => [],
'customer_email' => [],
'search_parameters' => [],
'result_list' => [],
],
'types' => [],
];
```
This is from another table for which querys etc work
```
return [
'columns' => [
'immovable' => [],
'type' => [],
'title' => [],
'path' => [],
'mark_to_delete' => [],
],
];
``` | 2016/06/20 | [
"https://Stackoverflow.com/questions/37921865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/983869/"
] | It's hard to say how you'd want your Layout to load sometimes, but at the top of your view you can check criteria:
```
@{
if (/* your criteria here */) {
Layout = "path to your layout file";
} else {
Layout = null;
}
}
``` | You must delete Layout at the View or \_ViewStart. |
49,259 | Solzhenitsyn is a dissident writer in the former Soviet Union. He's famous for writing the *Gulag Archipelago*. I recall that he eventually managed to escape to the West, in fact to the USA where after taking a good look around he denounced the the West too.
Once a dissident, always a dissident I suppose. I also recall that he was dropped like a hot potato by the West. I imagine its easy to cheer on a dissident in the 'enemy camp' but not so nice when his critique is turned upon the West.
I'm curious though now about what exactly was the content of his critique. It must have stung, as he was dropped very quickly.
**edit**
In the article published by the Washington Post by Lee Lescaze in 1978 he is reported to have said:
>
> Western societies have taken on a terrible similarity to the state-controlled societies of the communist world in its suffocation of spiritual life ... He says that Western society is morally bankrupt ... He attacks moral cowardice, selfishness and complacency ... materialism, sharp legal manoeuvring, **a press that invades privacy**, TV stupor and intolerable music.
>
>
>
Having just been to a local department store I can see very well what he means by intolerable music. It's a sad indictment on a society that has had so many great musicians and composers. The report does not give any specific details about why S is making the criticisms he has. It paints his criticisms with a very broad-brush. I'm looking for sources that are more specific about his critiques. For example, Lee further reports:
>
> 'A decline in courage' is the most striking feature of what he calls the 'spiritual exhaustion' of the West ... [And] 'the forces of evil have begun their decisive offensive, you can feel their pressure, and yet your screens and publications are full of prescribed smiles and raised glasses. Where is the joy in that?' ... He attacks the Western press ... for reflecting more clearly than any other part of society 'the hastiness and superficiality' that he calls the 'psychic disease of the 20th C'
>
>
>
Q. What does he mean by the 'forces of evil have begun their decisive offensive'? Has he been clarified elsewhere in his writings what he means by this? | 2018/11/08 | [
"https://history.stackexchange.com/questions/49259",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/994/"
] | The speech can be read in it's entirety here. **[A World Split Apart](https://www.americanrhetoric.com/speeches/alexandersolzhenitsynharvard.htm)**. delivered 8 June 1978, Harvard University and is well worth reading.
Solzhenitsyn was a Russian Conservative who's ideology was formed through Orthodox Christianity, Slavic traditionalism, and decades of persecution inside the Soviet Union. His ideology was a fierce weapon when wielded against the Soviet Union, and became an uncomfortable microscope when he was given the venue of the 1978 Harvard graduation ceremony to discuss any topic he wished. The topic he wished to discuss were problems and similarities between the West and Soviet Union. He offered these observations, not as a criticism but as a service to the West from a friend.
At least according to the beginning of his powerful speech.
It starts:
>
> I am sincerely happy to be here on the occasion of the 327th commencement of this old and most prestigious university. My congratulations and very best wishes to all of today's graduates.
>
>
> Harvard's motto is "VERITAS." Many of you have already found out, and others will find out in the course of their lives, that truth eludes us if we do not concentrate our attention totally on it's pursuit. But even while it eludes us, the illusion of knowing it still lingers and leads to many misunderstandings. Also, truth seldom is pleasant; it is almost invariably bitter. There is some bitterness in my today's speech too, but I want to stress that it comes not from an adversary, but from a friend.
>
>
>
then he goes on to say if he was in the east giving a talk he would have confined his discussions of Soviet shortcomings, but since he was in the west the opposite was true. Then he went about critiquing the west, ripping it actually, with great eloquence. In words which still resonate off the page today independent of one's political leanings. The dignitaries in attendance looked on with slack jawed horror. Not, I suspect, because his speech was offensive, off base, not well thought out; but because it was clearly not the topic they expected to hear at Harvards graduation ceremony.
The speech goes down as one of the greatest of all time and remains controversial. It's main critics observe that Solzhenitsyn was ignorant of a Jeffersonian democracy and it's machinations to hold accountable it's governmental functionaries. Those less critical of Solzhenitsyn are continually stunned with how smart, hard hitting and observant his words were.
I give background because one can't appreciate the speech / criticism without understanding where the man came from and who he was.
---
**Background:**
* Shortly after Aleksandr Solzhenitsyn(mother) became pregnant his father is killed in an accident.
* Aleksandr born **Dec 11, 1918** is raised fatherless.
* In **1930**, when Aleksandr is 11 years old his maternal grandmother Zakhar Shcherbak is harassed by the Soviet secret police.
* Two years later **1932**, Zakhar Shcherbak disappears and is never heard from again.
* In **Feb 1945**, Lieutenant Solzhenitsyn (soviet artillery officer) is arrested for writing comments in private letters to a friend about Joseph Stalin, he is sentenced to 8 years in the Gulag for counter revolutionary ideas.
* **1953**, Solzhenitsyn after serving his time in the Gulag, is placed in exile to the southeast part of Kazakhstan. He is also told at this time he has cancer, and is given 3 weeks to live. His experience with the cancer treatment he is given becomes the basis of his book "Cancer Ward".
* **1956**, Kruschev denounces Stalin and pardons all those exiled under article 28 of the counter revolutionary doctrine which includes Aleksandr.
* 1961, submits "One Day in the Life of Ivan Denisovich, which takes a year to pass censors and is ultimately approved for publication personally by Nikita Krustchev. It's a 170 page description of one day in the life inside the gulag system.
* **1962**, "One Day in the Life of Ivan Denisovich", is published domestically and abroad and makes Solzhenitsyn famous both in the Soviet Union and globally.
* **1964**, Khrushchev is removed from power and the Soviet Union will not publish another Solzhenitsyn novel or short story until 1990 after the fall of Communism. Solzhenitsyn spends the next three years in hiding.
* **1967**, Solzhenitsyn begins a war of words with Soviet Officials and becomes one of the most famous dissidents in Soviet History amazingly while still in Russia.
* **1968**, Solzhenitsyn begins publishing works abroad starting with First Circle, published in Paris France.
* **1970**, Wins the Nobel Prize for literature but declines to attend the award ceremony because he fears he will not be permitted to return.
* **1973**, An unpublished archive of Solzhenitsyn's works is seized by the KGB. It was being kept by a confident named Elizaveta Voronyanskaya who reportedly committed suicide. Solzhenitsyn hands over the microfilm of Gulag Archipelago to the west.
* **1974**. After the publication of Gulag Archipelago, the Soviet Union conducts a public campaign to discredit him, resulting in his arrest, conviction of treason, stripped of his Soviet citizenship, and his second expulsion.
* **1976** Goes on the speaking circuit across Europe and the United States. First visits Virmont where he will eventually make his home in exile.
**1978** - After two years of living in the United States he is asked to give his famous address at Harvard University, where your question begins.
---
>
> **Question:**
>
> I'm curious though now about what exactly was the content of his critique. It must have stung, as he was dropped very quickly
>
>
>
You should really read the speech because it's an excellent read and goes down in the West as a cultural event and one of the greatest speeches of all time.
Beyond that he drew broad comparisons between the west devoid of dissension and Soviet Union.
I debated including quotes with the specific section, and might take them out if people think that's better. My quotes are small out of context paragraphs in what were essentially essay's on different topics. I don't want to tarnish or compete with the original speech but just to give folks who don't have time to read the speech a taste.
Specifically:
* Criticism of western decadency under the premise of observations from a friend...
* While he says he would not endorse Soviet style socialism, he continues he would also not endorse western style democracies because the West is devoid of great spirits. A people who were given so much, and had to overcome so little he postured could not develop the great spirits being forged in the furnace's of the Soviet Union.
>
> But should someone ask me whether I would indicate the West such as it is today as a model to my country, frankly I would have to answer negatively. No, I could not recommend your society in its present state as an ideal for the transformation of ours. Through intense suffering our country has now achieved a spiritual development of such intensity that the Western system in its present state of spiritual exhaustion does not look attractive. Even those characteristics of your life which I have just mentioned are extremely saddening.
>
>
> A fact which cannot be disputed is the weakening of human beings in the West while in the East they are becoming firmer and stronger -- 60 years for our people and 30 years for the people of Eastern Europe. During that time we have been through a spiritual training far in advance of Western experience. Life's complexity and mortal weight have produced stronger, deeper, and more interesting characters than those generally [produced] by standardized Western well-being.
>
>
>
* Western leaders were cowards basically chosen for their ability to get along rather than their ability to do what's right.
>
> A decline in courage may be the most striking feature which an outside observer notices in the West in our days. The Western world has lost its civil courage, both as a whole and separately, in each country, each government, each political party, and, of course, in the United Nations. Such a decline in courage is particularly noticeable among the ruling groups and the intellectual elite, causing an impression of loss of courage by the entire society. Of course, there are many courageous individuals, but they have no determining influence on public life.
>
>
> Political and intellectual bureaucrats show depression, passivity, and perplexity in their actions and in their statements, and even more so in theoretical reflections to explain how realistic, reasonable, as well as intellectually and even morally worn it is to base state policies on weakness and cowardice. And decline in courage is ironically emphasized by occasional explosions of anger and inflexibility on the part of the same bureaucrats when dealing with weak governments and with countries not supported by anyone, or with currents which cannot offer any resistance. But they get tongue-tied and paralyzed when they deal with powerful governments and threatening forces, with aggressors and international terrorists.
>
>
> Should one point out that from ancient times declining courage has been considered the beginning of the end?
>
>
>
* West is ignorant of evil not presented in the guise of objectionable ideology.
>
> But the fight for our planet, physical and spiritual, a fight of cosmic proportions, is not a vague matter of the future; it has already started. The forces of Evil have begun their offensive; you can feel their pressure, and yet your screens and publications are full of prescribed smiles and raised glasses. What is the joy about?
>
>
>
* A western obsession with legality rather than morality.
>
> Western society has given itself the organization best suited to its purposes based, I would say, one the letter of the law. The limits of human rights and righteousness are determined by a system of laws; such limits are very broad. People in the West have acquired considerable skill in interpreting and manipulating law. Any conflict is solved according to the letter of the law and this is considered to be the supreme solution. If one is right from a legal point of view, nothing more is required. Nobody will mention that one could still not be entirely right, and urge self-restraint, a willingness to renounce such legal rights, sacrifice and selfless risk. It would sound simply absurd. One almost never sees voluntary self-restraint. Everybody operates at the extreme limit of those legal frames.
>
>
> I have spent all my life under a Communist regime and I will tell you that a society without any objective legal scale is a terrible one indeed. But a society with no other scale than the legal one is not quite worthy of man either.
>
>
>
* The America's Cold War blind spot when it comes to international events not relating to the Soviet Union.
>
> There is the concept of "Third World": thus, we already have three worlds. Undoubtedly, however, the number is even greater; we are just too far away to see. Any ancient and deeply rooted, autonomous culture, especially if it is spread on a wide part of the earth's surface, constitutes an autonomous world, full of riddles and surprises to Western thinking. As a minimum, we must include in this category China, India, the Muslim world, and Africa, if indeed we accept the approximation of viewing the latter two as compact units.
>
>
>
* Western political correctness which he equated with soviet censorship which stifles unpopular opinions, and represses dessention.
>
> Without any censorship, in the West fashionable trends of thought and ideas are carefully separated from those which are not fashionable; nothing is forbidden, but what is not fashionable will hardly ever find its way into periodicals or books or be heard in colleges. Legally your researchers are free, but they are conditioned by the fashion of the day. There is no open violence such as in the East; however, a selection dictated by fashion and the need to match mass standards frequently prevents independent-minded people from giving their contribution to public life.
>
>
>
* With the American Press which he said was the greatest power in forming public opinion but was not accountable to the people.
* He found fault with the Cold War being conducted between two ideologies without regard for people. He found it reflexive and not subject to normal tactics between nations to defuse aggression. treaties, negotiations could not overcome impasses, where ideology was the basis and he placed some of the blame for this on the west.
>
> The split in today's world is perceptible even to a hasty glance. Any of our contemporaries readily identifies two world powers, each of them already capable of entirely destroying the other. However, understanding of the split often is limited to this political conception: that danger may be abolished through successful diplomatic negotiations or by achieving a balance of armed forces. The truth is that the split is a much [more] profound [one] and a more alienating one, that the rifts are more than one can see at first glance. This deep manifold split bears the danger of manifold disaster for all of us, in accordance with the ancient truth that a kingdom -- in this case, our Earth -- divided against itself cannot stand.
>
>
>
* With a western policy which he identified as recreating images of America's government abroad. That every country should emulate or develop to the same standards.
>
> the belief that vast regions everywhere on our planet should develop and mature to the level of present day Western systems which in theory are the best and in practice the most attractive. There is this belief that all those other worlds are only being temporarily prevented by wicked governments or by heavy crises or by their own barbarity or incomprehension from taking the way of Western pluralistic democracy and from adopting the Western way of life. Countries are judged on the merit of their progress in this direction. However, it is a conception which developed out of Western incomprehension of the essence of other worlds, out of the mistake of measuring them all with a Western yardstick.
>
>
>
I don't want to rewrite the entire speech. I don't want to graffiti his speech with my commentary either. I could go on for many more pages. but will choose to end this here now and again restate, Everyone should read the speech themselves.
One of the most exciting questions I've seen on History Stack exchange for quite some time. I hope I did it justice.. I enjoyed revisiting that speech, thank you for the question.
**Sources:**
* **[The Speech](https://www.americanrhetoric.com/speeches/alexandersolzhenitsynharvard.htm)**
* **[Revisiting Aleksandr Solzhenitsyn’s warnings to the West](https://www.catholicworldreport.com/2015/07/08/revisiting-aleksandr-solzhenitsyns-warnings-to-the-west/)**
* **[Aleksandr Solzhenitsyn Center: Timeline](https://www.solzhenitsyncenter.org/timeline/)**
* **[The Russian Revolution](https://en.wikipedia.org/wiki/Russian_Revolution)** | He accuses West of being spiritually void
-----------------------------------------
[Full text is here](https://www.americanrhetoric.com/speeches/alexandersolzhenitsynharvard.htm) . I will skip parts about Soviet Union , Third World and concentrate on critique of the West .
>
> It has become possible to raise young people according to these ideals, leaving them to physical splendor, happiness, possession of material goods, money, and leisure, to an almost unlimited freedom of enjoyment. So who should now renounce all this? Why? And for what should one risk one's precious life in defense of common values and particularly in such nebulous cases when the security of one's nation must be defended in a distant country? **Even biology knows that habitual, extreme safety and well-being are not advantageous for a living organism**.
>
>
>
Common theme, not only for Solzhenitsyn. People in the West are being accustomed to live in relative luxury, they do not have any greater goal in life except their physical well-being and enjoyment. Decadence.
>
> If one is right from a legal point of view, nothing more is required. Nobody will mention that one could still not be entirely right, and urge self-restraint, a willingness to renounce such legal rights, sacrifice and selfless risk. It would sound simply absurd. **One almost never sees voluntary self-restraint. Everybody operates at the extreme limit of those legal frames.**
>
>
>
Morality replaced by (formal) laws, in service of egoism. Again common theme, going back to Gospels, and [Jesus's critique of pharisees](https://en.wikipedia.org/wiki/Woes_of_the_Pharisees).
>
> A statesman who wants to achieve something important and highly constructive for his country has to move cautiously and even timidly. There are thousands of hasty and irresponsible critics around him; parliament and the press keep rebuffing him. As he moves ahead, he has to prove that each single step of his is well-founded and absolutely flawless. **Actually, an outstanding and particularly gifted person who has unusual and unexpected initiatives in mind hardly gets a chance to assert himself**.
>
>
>
Critique of political system - successful politician had to be duplicitous, caring more about avoiding politically non-correct statements then presenting any fresh ideas. Of course, in modern times there is a quite of backlash against this, with populists like Trump elected despite this.
>
> The defense of individual rights has reached such extremes as to make society as a whole defenseless against certain individuals. It's time, in the West -- **It is time, in the West, to defend not so much human rights as human obligations**.
>
>
>
Old philosophical question : **Who is the citizen ?** . Does citizen only enjoy legal rights, or he has to "carry the spear and the shield for the state", or humanity in general .
>
> Destructive and irresponsible freedom has been granted boundless space. Society appears to have little defense against the abyss of human decadence, such as, for example, misuse of liberty for moral violence against young people, such as motion pictures full of pornography, crime, and horror. It is considered to be part of freedom and theoretically counterbalanced by the young people's right not to look or not to accept. **Life organized legalistically has thus shown its inability to defend itself against the corrosion of evil**.
>
>
>
Again, old motif of law not being sufficient protection against the devil. Misuse of freedom, liberalism as a disease of society .
>
> The press too, of course, enjoys the widest freedom. (I shall be using the word press to include all media.) But what sort of use does it make of this freedom?
> Here again, the main concern is not to infringe the letter of the law. There is no true moral responsibility for deformation or disproportion. What sort of responsibility does a journalist or a newspaper have to his readers, or to his history -- or to history? If they have misled public opinion or the government by inaccurate information or wrong conclusions, do we know of any cases of public recognition and rectification of such mistakes by the same journalist or the same newspaper?
>
>
>
Pointing out that media, or to be more precise **those who own and control media** have almost unrestricted power over society.
>
> **The press can both simulate public opinion and miseducate it**. Thus, we may see terrorists described as heroes, or secret matters pertaining to one's nation's defense publicly revealed, or we may witness shameless intrusion on the privacy of well-known people under the slogan: "Everyone is entitled to know everything." But this is a false slogan, characteristic of a false era. People also have the right not to know and it's a much more valuable one. The right not to have their divine souls [stuffed with gossip, nonsense, vain talk.] A person who works and leads a meaningful life does not need this excessive burdening flow of information.
>
>
>
Tabloidization of media, with many superficial "celebrity news" given full spotlight, while on the other hand other, more important stories, being hidden and burried. Also, media trying to create political opinion instead of informing , "fake news" effect.
>
> There is yet another surprise for someone coming from the East, where the press is rigorously unified. One gradually discovers a common trend of preferences within the Western press as a whole. **It is a fashion; there are generally accepted patterns of judgment; there may be common corporate interests, the sum effect being not competition but unification**.
>
>
>
This is actually very interesting, one of the first expression of idea that all mass media is being controlled by same group(s) with sinister agendas.
>
> There are meaningful warnings which history gives a threatened or perishing society. **Such are, for instance, the decadence of art, or a lack of great statesmen**. There are open and evident warnings, too. The center of your democracy and of your culture is left without electric power for a few hours only, and all of a sudden crowds of American citizens start looting and creating havoc. **The smooth surface film must be very thin, then, the social system quite unstable and unhealthy**.
>
>
>
Again, pointing out decadence and lack of morality. Everyone looks only for his selfish self-interest, without threat of law they easily turn to crime.
>
> And yet -- no weapons, no matter how powerful, can help the West until it overcomes its loss of willpower. In a state of psychological weakness, weapons become a burden for the capitulating side. **To defend oneself, one must also be ready to die**; there is little such readiness in a society raised in the cult of material well-being.
>
>
>
Again pointing out spiritual weakness of average Western citizen who doesn't have any higher goal in life then self-preservation.
>
> This means that the mistake must be at the root, at the very basis of human thinking in the past centuries. I refer to the prevailing Western view of the world which was first born during the Renaissance and found its political expression from the period of the Enlightenment. It became the basis for government and social science and could be defined as **rationalistic humanism or humanistic autonomy**: the proclaimed and enforced autonomy of man from any higher force above him. **It could also be called anthropocentricity, with man seen as the center of everything that exists**.
>
>
>
Pointing out perceived root of weakness - humanism.
>
> Then, however, we turned our backs upon the Spirit and embraced all that is material with excessive and unwarranted zeal. This new way of thinking, which had imposed on us its guidance, did not admit the existence of intrinsic evil in man nor did it see any higher task than the attainment of happiness on earth. **It based modern Western civilization on the dangerous trend to worship man and his material needs**.
>
>
>
Again the same.
>
> However, in early democracies, as in the American democracy at the time of its birth, all individual human rights were granted because man is God's creature. **That is, freedom was given to the individual conditionally, in the assumption of his constant religious responsibility**.
>
>
>
Shoutout to Constitutionalists and Originalists . US must return to its spiritual roots.
>
> As humanism in its development became more and more materialistic, it made itself increasingly accessible to speculation and manipulation by socialism and then by communism. So that Karl Marx was able to say that "communism is naturalized humanism."
> This statement turned out not to be entirely senseless. One does see the same stones in the foundations of a despiritualized humanism and of any type of socialism: endless materialism; freedom from religion and religious responsibility, which under communist regimes reach the stage of anti-religious dictatorships; concentration on social structures with a seemingly scientific approach.
>
>
>
Parallels between socialism and modern liberal capitalism. They both have same root, theme used not only by Solzhenitsyn, but all modern rightist movements.
>
> The interrelationship is such, too, that the current of materialism which is most to the left always ends up by being stronger, more attractive, and victorious, because it is more consistent. **Humanism without its Christian heritage cannot resist such competition**. We watch this process in the past centuries and especially in the past decades, on a world scale as the situation becomes increasingly dramatic. **Liberalism was inevitably displaced by radicalism; radicalism had to surrender to socialism; and socialism could never resist communism.**
>
>
>
Without (Christian) religion, West would undoubtedly fall to some kind of dictatorship, current liberalism is just a prelude to rise of radicals. Again, very modern idea - many on the Right side of political spectrum point out militant leftist groups like Antifa as precursors of very undemocratic state.
---
Overall, Solzhenitsyn's speech is very relevant even today. He could be described as Christian Conservative in today's political therms. Many of his talking points are well known even to a casual observer of political events. |
9,120,874 | I have a created a multithreaded application that executes different tasks with the same ScheduledExecutorService (method scheduleAtFixedRate and a fixed threadpool of 10 threads). However all threads except one main task (not to be confused with the main thread!) are asleep most of the time, until there is user input. The data that is shared between the main task and the other (user input) threads is protected by lock objects in synchronized blocks.
The main task executes a reoccuring task at a fairly large frequency, let's say 25 Hz (i.e. period of 40 ms), and it's important that this task is executed timely. Typically this is also the case, but unfortunately not all the time. Other "nice" applications are also running on the same computer (Linux OP), but CPU<<100%.
During 60 minutes of measurement (i.e. 90000 samples) the actual period between two consecutive samples were >= 60 ms in about 50 cases, and in about 30 of these the period was over 100 ms, in a couple of really bad cases (fairly close to each other in time, in the order of seconds), the period was between 1000 and 2300 ms. No user input was given during measurement. Looking at the data logs, it seems obvious that something has prevented the executor from doing its job during these intervals, since they are often followed by a "catch up" of the Executor, i.e. multiple logs from the application within 2 or 3 ms.
I've tried periodic garbage collection at each execution of the task, but (at least in the short term perspective) it only seems to make things worse. I have also measured the execution time of the task. It is mostly around 1 ms, and it should not cause the Executor to break down (or should it?). There *are* deviations here too, occasionally in the order of 100 ms, but they would explain less than 50% of the delays. I have tried looking for TaskRejectedExceptions, found nothing.
So my questions now are basically: What can I expect from a ScheduledExecutorService over time? Is this likely to be a thread problem, despite the fact that only the main task should be running during these circumstances? What might cause the ScheduledExecutor to stop executing temporarily, only to flood the logs with its "catch up" data, and is there any method to control this annoying behaviour? Could any of this be related to the fact that my JVM is just a normal JVM without real time priority capabilities? Any help, ideas or theories on where to start digging, are truly appreciated! | 2012/02/02 | [
"https://Stackoverflow.com/questions/9120874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1186155/"
] | there is a tutorial linked in the emberjs wiki that uses another library for RESTful communication with Rails: <https://github.com/emberjs/ember.js/wiki/Links>
I have used the old sproutcore-datastore ( back in the Sproutcore 2 days... ;-) ) along a very nice post from Peter Wagenet on the Sproutcore blog: <http://blog.sproutcore.com/sproutcore-2-and-ajax/> - it again is not ember-data, but concepts should be similar and the sproutcore-datastore still exists as an addon: <https://github.com/emberjs-addons/sproutcore-datastore>
It is not exactly what you are looking for, but hope it may help. | Here's an example of an Emberjs app using Ember data adapter to make it works with a REST API.
<https://github.com/dgeb/ember_data_example> |
41,024 | I want to listen to music while running, but I have a hard time finding a good way to do so.
My phone is quite big, and my watch is a standard running watch, not a smart watch. I live in a place with lots of rain, so the equipment must be water resistant.
I'm guessing wireless earbuds, but how can I bring the music with me?
Note: I'm not asking for product recommendations, but rather "solution recommendations". I.e. what sort of product(s) should I buy? | 2019/10/01 | [
"https://fitness.stackexchange.com/questions/41024",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/10745/"
] | Here are some options:
* Get a small MP3 player. Anything from an IPod nano to knockoffs that sell on Amazon. [This one has a screen and is less than $20.](https://amzn.to/2nRI0hl) While you will still have to carry it, you can probably fit it in one of the super secret pockets many running shorts have. Some of my shorts have a pocket near the waist band on the back. With that kind of setup you can use wireless or wired head phones.
* Get a watch that has music built in. This is a more expensive option and it will require wireless head phones.
* Get a pouch to carry your phone and water. [I use something like this because I run in the heat.](https://amzn.to/2nO0mjf) This will cost you around $20, and I have used wired and wireless headphones with this setup.
* Get a running belt. These tend to be less expensive than the previous option, but do not carry water. | I regularly listen to music while running. I am using spotify on my mobile phone. Even if your phone is big, I would use it and try to get either something like an arm holder for the phone or have it in my hands. Carrying even more devices would not solve it for me.
In addition I am using wired headphones and locally synced music. Fiddeling with bluetooth or having no connection while running is not that pleasant. I have had that during a city run when my BT headset would not connect and I had to reboot the phone while running. In addition having thousands of runners around you limits your mobile connectivity. The best thing you can do in such a situation is go into flight mode (to force your streaming app to go offline) and continue running. |
8,103,296 | Following this Android tutorial: <http://developer.android.com/resources/tutorials/hello-world.html> I added two lines which should cause null pointer exception:
```
Object o = null;
o.toString();
```
Now I set breakpoint on the second line and start debugger. When debugger breaks, I click "Step over" and application crashes. However, I don't see any useful information in the debugger. Debug window shows ActivityThread.performLaunchActivity, Source window shows "No source found". I don't see any information about exception, null pointer, etc. in any Eclipse debugger window, and don't see anything pointing to my line of code that causes crash. So, what am I missing?
**Edit**. Maybe Android UI framework has its own exception handling mechanizm, which prevents me to see exception immediately in my code? Something like this happens in another UI frameworks, like WinForms, Qt, wxWidgets. | 2011/11/12 | [
"https://Stackoverflow.com/questions/8103296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279313/"
] | After exception occurs you should check Logcat window for details: there you find the entire stack leading to the line of code where exception is. In some cases exception will occur in some other class (not yours) - then you should look for your package/class name in the stack to find otu whether you're "responsible" for it.
Corresponding output will not appear in Logcat immediately - let it run for some time (or until it crashes).
Also you can set "Java exception breakpoint" so the execution will break whenever there is an exception. | Try something like this...
```
try {
Object o = null;
o.toString();
}
catch (Exception e) {
e.printStackTrace();
}
```
...and use the DDMS perspective in eclipse.
Ideally you want to catch specific exceptions so the `catch` block would be...
```
catch (NullPointerException npe {
npe.printStackTrace();
}
```
...but doing a 'catch all' for `Exception` as in my first example and using the eclipse DDMS perspective to view logcat output will give you a good head start. |
2,529,498 | >
> $y\geq 3$, $y>3$
>
>
>
Implication and equality, is in the region of logic than mathematics.
If we take something easy like Germany and the EU:
>
> Germany ⇒ EU
>
>
>
Because Germany is in the EU but the EU might be the UK or Sweden. (narrow goes to broad)
If we change it a bit:...
>
> Germany ⇒ UK, Germany, Sweden...
>
>
>
It's STILL the same
Now let's change it to numbers
>
> $2 \implies 2,3,4$
>
>
>
STILL the same, right?
**So why does my mathematics teacher say this is false!:**
>
> $y>3 \to y\geq 3$
>
>
>
We can represent this as:
>
> $4,5 \implies 3,4,5$
>
>
>
**UPDATE:**
For future users, my explanation is really bad and my knowledge limited. Look at the good answers instead. | 2017/11/20 | [
"https://math.stackexchange.com/questions/2529498",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/504700/"
] | It is true that $y>3 \Rightarrow y\ge 3$ for all $y$, but most of everything else you have written fails to make sense.
---
Writing "Germany $\Rightarrow$ EU" or "Germany $\Rightarrow$ EU, Germany Sweden" makes no sense.
The symbol $\Rightarrow$ is used between *propositions*, claims that can be true or false. But "Germany" isn't a proposition. It makes no sense to ask whether Germany is true or false; nor does it makes sense to ask whether EU is true or false, or for that matter whether the word salad "EU, Germany, Sweden" is true or false. So these are not things that can be meaningfully written on the two sides of $\Rightarrow$.
Similarly neither "$2$" nor "$2,3,4$" nor "$4,5$" nor "$3,4,5$" is something that can be true or false, so these things cannot be written as arguments to $\Rightarrow$ either.
"$2\Rightarrow 2,3,4$" and "$4,5\Rightarrow 3,4,5$" are both nonsense, just like "Germany $\Rightarrow$ EU" is.
You **can** write $\{4,5\} \subseteq \{3,4,5\}$ and get a meaningful (and in fact true) statement out of it, but removing the set brackets and changing $\subseteq$ into $\Rightarrow$ does not result in a mathematically meaningful formula. | The fact that $y>3 \implies y\geq3$ is an example of the logical rule of inference known as *disjunction introduction*. For more info on this and other rules see [here](https://en.wikipedia.org/wiki/Disjunction_introduction). Disjunction introduction states that for any statements $A,B$ (a statement is a true or false sentence), from $A$, we can deduce $A\lor B$. We write this as:
$$A \therefore A\lor B$$
(the symbol $\therefore$ is read as "therefore" or "implies").
Keeping in mind that $y \geq 3$ really means $y =3 \lor y>3$, you can substitute $(y>3) \equiv A, y=3 \equiv B$. Thus,
$$A\therefore (A \lor B)$$
$$(y>3) \therefore (y>3 \lor y=3)$$
The really cool thing about disjunction introduction is that it works for any two statements, $A,B$. For instance, we may use it to make the following deduction:
Socrates is a man.
Therefore, Socrates is a man or pigs are flying in formation over the English Channel.
Disjunction introduction can be proved either via a truth table, or by the definition of the logical $\lor$ connective. Here is the truth table method:
[](https://i.stack.imgur.com/9TqQw.jpg) |
58,655,329 | I need to convert following:
```
Map<Long,Map<String,String>> mapOfMaps
```
to
```
List<List<String>> listOflists
```
where keys of outer map (`mapOfMaps`) are redundant (for this operation). So basically , I can just use `mapOfMaps.values().stream()` to start with.
And for each map object e.g.:
>
> {"apple":"1","orange":"2"}
>
>
>
I need to convert it to a list :
>
> {"apple","1","orange","2"}
>
>
>
What is the most efficient way to do this?
Complete example:
>
> {
> "1L" : { "key1" : "value1" , "key2" : "value2" } ,
> "2L" : { "key3" : "value3" , "key4" : "value4" }
> }
>
>
>
Expected:
>
> [[key1, value1, key2, value2], [key3, value3, key4, value4]]
>
>
> | 2019/11/01 | [
"https://Stackoverflow.com/questions/58655329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2458858/"
] | Below is my version of solution. You can iterate over entry and add values to desired list accordingly.
```
List<List<String>> list = map.
values()
.stream()
.map(value -> {
List<String> list1 = new ArrayList<>();
for (Map.Entry<String, String> entry : value.entrySet()) {
list1.add(entry.getKey());
list1.add(entry.getValue());
}
return list1;
})
.collect(Collectors.toList());
```
**Test Input:**
```
Map<Long, Map<String, String>> map = new HashMap<>();
Map<String, String> submap1 = new HashMap<>();
submap1.put("test", "test2");
Map<String, String> submap2 = new HashMap<>();
submap2.put("test6", "6");
map.put(1l, submap1);
map.put(2l, submap2);
``` | If you're open to using a third-party library the following will work using [Eclipse Collections](https://github.com/eclipse/eclipse-collections):
```
@Test
public void mapOfMapsToListOfLists()
{
MutableMap<Long, MutableSortedMap<String, String>> map = Maps.mutable.with(
1L, SortedMaps.mutable.with("key1", "value1", "key2", "value2"),
2L, SortedMaps.mutable.with("key3", "value3", "key4", "value4"));
MutableList<MutableList<String>> listOfLists = map.valuesView()
.collect(innerMap -> innerMap.keyValuesView()
.flatCollect(this::pairToList).toList())
.toList();
List<List<String>> expected = Lists.mutable.with(
Lists.mutable.with("key1", "value1", "key2", "value2"),
Lists.mutable.with("key3", "value3", "key4", "value4"));
Assert.assertEquals(expected, listOfLists);
}
public ImmutableList<String> pairToList(Pair<String, String> pair)
{
return Lists.immutable.with(pair.getOne(), pair.getTwo());
}
```
I initialized the inner maps as `SortedMap`s in order to guarantee the order of the keys in the call to `Assert.assertEquals` in the test. The interface types I used above are from Eclipse Collections and extend the JDK interface types (e.g. MutableMap extends Map, MutableList extends List), but you can also use JDK types with static utility as follows:
```
@Test
public void jdkMapOfMapsToListOfLists()
{
Map<Long, Map<String, String>> map = Maps.mutable.with(
1L, SortedMaps.mutable.with("key1", "value1", "key2", "value2"),
2L, SortedMaps.mutable.with("key3", "value3", "key4", "value4"));
List<List<String>> listOfLists = MapIterate.collect(map,
innerMap -> Iterate.flatCollect(
innerMap.entrySet(),
this::entryToList,
new ArrayList<>()));
List<List<String>> expected = Arrays.asList(
Arrays.asList("key1", "value1", "key2", "value2"),
Arrays.asList("key3", "value3", "key4", "value4"));
Assert.assertEquals(expected, listOfLists);
}
public List<String> entryToList(Map.Entry<String, String> entry)
{
return Arrays.asList(entry.getKey(), entry.getValue());
}
```
Note: I am a committer for Eclipse Collections |
443,210 | I'm trying to program an access database but I'm using SQL for all my querying. I've got the database almost complete but I have one query that has me stumped. It is a database which contains recipes. I have a table in which I have all the conversions for cooking (Tablespoon to Teaspoon, Teaspoon to Cup, etc.). The user needs to be able to put in an ingredient using whatever units the recipe calls for (in other words, I cannot standardize the units, I have to find what they are). Then I need to be able to convert these into a standardized unit. This is where I'm having the problem because things like vegetables can come in cups, tablespoons, etc. whereas things like meats come in ounces, pounds, etc. I want to avoid creating a bunch of vb if/then's. I feel like there must be a way to do this with SQL but I can't seem to figure it out. | 2009/01/14 | [
"https://Stackoverflow.com/questions/443210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I think for cooking you have to separate two different types of units
1. by weight
2. by volume
You can't standardize these units, or what sense does it make to know that you need 2 cups of meet?
Then when you differentiate those two different types of units, you can standardize them two one unit. Maybe:
1. cups, teaspoon,... in ml
2. meat, vegetables,... in g or pounds, or whatever
If they all have the same base, then you're able to compare them. | The user would have to provide you with the unit, and evey unit would have a type (weight, volume, etc.) Your "conversion table" would just need to include a baseline for every unit type. i.e. 8 oz to a cup, 128oz to a gallon. Knowing those two things you can convert cups to gallons.
Doing this in access in a single query is a different story. If you can do a little VBA, get cup to ounces in one call, then ounces to gallons in another, I think you'll have a much easier time. |
19,325,102 | I want to get the name of the month in JavaScript in capitals.
I know I can use the `getMonth()` method to get the current month and use the number to extract the month name in capitals from an array, but is there a built-in method to do the same? | 2013/10/11 | [
"https://Stackoverflow.com/questions/19325102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1732772/"
] | Like this, see [`toLocaleString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString?redirectlocale=en-US&redirectslug=JavaScript/Reference/Global_Objects/Date/toLocaleString)
While this method has been around for quite some time, it is only recently that browsers have begun to implement the `locales` and `options` arguments and is therefore not yet widely [supported](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString?redirectlocale=en-US&redirectslug=JavaScript/Reference/Global_Objects/Date/toLocaleString#Browser_Compatibility).
Javascript
```
var today = new Date(),
options = {
month: "long"
},
month = today.toLocaleString("en-GB", options).toUpperCase();
alert(month);
```
[jsFiddle](http://jsfiddle.net/Xotic750/mQEe3/) | ```
const today = new Date();
const options = {month: 'long'};
today.toLocaleDateString('it-IT', options);
```
A way for getting the month from a Date Object. |
510,441 | I have a networking Linux application which receives RTP streams from multiple destinations, does very simple packet modification and then forwards the streams to the final destination.
How do I decide how many threads I should have to process the data? I suppose, I cannot open a thread for each RTP stream as there could be thousands. Should I take into account the number of CPU cores? What else matters?
Thanks. | 2009/02/04 | [
"https://Stackoverflow.com/questions/510441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48461/"
] | It is important to understand the purpose of using multiple threads on a server; many threads in a server serve to decrease [latency](http://en.wikipedia.org/wiki/Latency_(engineering)) rather than to increase speed. You don't make the cpu more faster by having more threads but you make it more likely a thread will always appear at within a given period to handle a request.
Having a bunch of threads which just move data in parallel is a rather inefficient shot-gun (Creating one thread per request naturally just fails completely). Using the [thread pool](http://en.wikipedia.org/wiki/Thread_pool_pattern) pattern can be a more effective, focused approach to decreasing latency.
Now, in the thread pool, you want to have at least as many threads as you have CPUs/cores. You can have more than this but the extra threads will again only decrease latency and not increase speed.
Think the problem of organizing server threads as akin to organizing a line in a super market. Would you like to have a lot of cashiers who work more slowly or one cashier who works super fast? The problem with the fast cashier isn't speed but rather that one customer with a lot of groceries might still take up a lot of their time. The need for many threads comes from the possibility that a few request that will take a lot of time and block all your threads. By this reasoning, whether you benefit from many slower cashiers depends on whether your have the same number of groceries or wildly different numbers. Getting back to the basic model, what this means is that you have to play with your thread number to figure what is optimal given the particular characteristics of your traffic, looking at the time taken to process each request. | I'd say, try using just ONE thread; it makes programming much easier. Although you'll need to use something like libevent to multiplex the connections, you won't have any unexpected synchronisation issues.
Once you've got a working single-threaded implementation, you can do performance testing and make a decision on whether a multi-threaded one is necessary.
Even if a multithreaded implementation is necessary, it may be easier to break it into several processes instead of threads (i.e. not sharing address space; either fork() or exec multiple copies of the process from a parent) if they don't have a lot of shared data.
You could also consider using something like Python's "Twisted" to make implementation easier (this is what it's designed for).
Really there's probably not a good case for using threads over processes - but maybe there is in your case, it's difficult to say. It depends how much data you need to share between threads. |
1,282,718 | There's a website ([example](https://www.angst-panik-hilfe.de/medikamente-angstbehandlung.html)) that somehow blocks selecting text. Also it blocks `Ctrl`+`A` to select everything, there is also no “Copy” in the popup menu.
What I have tried:
Some sites use JavaScript to block selection. So I disabled all JavaScript sources in no-script addon in Firefox. I tried the same site in Google Chrome with the Script Safe addon. Made sure that everything is blocked, still can’t select text. Mousepointer remains an arrow and not a text cursor also on the whole site.
Used `about:config` to disable JavaScript completely in Firefox. Still no effect.
I read that some sites use DIVs with the style display:block so I used Inspect to examine the styles of the site. There is not one mention of "block" on the whole website, not in embedded CSS nor in object style=-attributes.
The text is not an image or flash or some HTML5 canvas ect. Everything is within DIV and P tags but no style was found that might block the text selection.
How can the website still block any selection of text? Not to mention why browsers support such behaviours at all. I just want to use a selected word or sentence and want to search google for it using right mouse click. It’s pretty annoying when a website does such things and forces me to type technical terms and names into google by hand. It disturbs my workflow. | 2018/01/05 | [
"https://superuser.com/questions/1282718",
"https://superuser.com",
"https://superuser.com/users/616229/"
] | [<https://www.angst-panik-hilfe.de/angst-panik.css>](https://www.angst-panik-hilfe.de/angst-panik.css) shows:
```
body{-webkit-user-select:none;-moz-user-select:-moz-none;
-ms-user-select:none;user-select:none}
```
So, that effect applies to the entire BODY tag.
Documentation on this CSS: [Mozilla Developer Site: user-select](https://developer.mozilla.org/en-US/docs/Web/CSS/user-select).
You could probably override this by removing the style in Developer Tools (press `F12` in Firefox or Chrome) - you may even be able to create a JavaScript applet that, after investing the time to set this up, can remove that style with less instant effort on your part (which may be a time saver if you plan to visit the site multiple times).
I'd also like to add this note: This might not be the only way to have at least some of that effect. Another possible way could be to have an invisible `DIV` cover the `DIV` that has the text. That way, the mouse cursor would not turn into the I-beam (text cursor) because the cursor would be based on the content of the top-most `DIV`. (`Ctrl`-`A` would probably cover that text, though.)
>
> It's pretty annoying when a website does such things and forces me to type technical terms and names into google by hand. It disturbs my workflow.
>
>
>
Amen! Upon seeing this, I'm disappointed at the existence of such a CSS style being implemented by the major browsers. Such things are pretty annoying, indeed! | I'm using Stylus (<https://add0n.com/stylus.html>) and I made a style to apply to all websites, and thus I am ensuring everything is selectable:
```
* {
-webkit-user-select: auto !important;
-moz-user-select: inherit !important;
-ms-user-select: inherit !important;
user-select: auto !important;
}
```
The asterisk is to make sure the style is not only applied to a certain css element (like `<body>`), but to all elements. I encountered cases where the selection blocking was applied to a button text only, so making a css for `<body>` would not help.
I use selection for instant translation on foreign language websites. |
24,837,898 | I have created this function in a Python file:
```
def abc (xyz):
return xyz
```
I saved the file in `/var/www/` with the file name `a.py`.
Now I want to run this function in an Ubuntu console and pass a parameter to this function. How can I do this? I have tried this:
```
jaskaran@jaskaran-Vostro-1550:/var/www$ python3 a.py
```
This does not show me any error. How can I call the function and be able to see the output in the console? | 2014/07/19 | [
"https://Stackoverflow.com/questions/24837898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3425009/"
] | ```
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from a import abc
>>> abc(123)
123
>>>
``` | Try using something like this:
```
def abc(xyz):
print(xyz)
if __name__ == "__main__":
abc(input("Enter something: "))
```
This will print in the console what you enter as input! ;)
i hope this helps |
1,940,112 | I'm using this script
<http://mondaybynoon.com/2009/02/23/creating-custom-form-elements-using-jquery-selects/>
to create custom css select boxes in my page. Javascript code that is used to apply the css styles on selectboxes, uses their id as a parameter:
```
$(document).ready(function() {
$('#cont').selectbox({debug: true});
});
<select id="cont" name="cont" tabindex="1">
<option value="1">aaa</option>
<option value="2">bbb</option>
<option value="3">ccc</option>
</select>
```
Can I somehow use just the "name" attribute of select boxes and not the "id"??? Is this possible? | 2009/12/21 | [
"https://Stackoverflow.com/questions/1940112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236021/"
] | This isn't exactly concatenation but it will do the job you want to do:
```
puts " Total Revenue of East Cost: #{total_revenue_of_east_cost}"
```
Technically, this is interpolation. The difference is that concatenation adds to the end of a string, where as interpolation evaluates a bit of code and inserts it into the string. In this case, the insertion comes at the end of your string.
Ruby will evaluate anything between braces in a string where the opening brace is preceded by an octothorpe. | Stephen Doyle's answer, using a technique known as "String interpolation" is correct and probably the easiest solution, however there is another way. By calling an objects to\_s method that object can be converted to a string for printing. So the following will also work.
```
puts " Total Revenue of East Cost: " + total_revenue_of_east_cost.to_s
``` |
2,837,515 | I wonder if, when you call something like that
>
> time();
>
>
>
it returns the timestamp relatively to your time zone setting or to UTC ?
For example, when syncing two agents, that must be important to take care of it, doesn't it ? | 2010/05/14 | [
"https://Stackoverflow.com/questions/2837515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341603/"
] | I don't know about an add-in for VS but anytime I want to try something quickly (and don't want to fire up VS and create a console app) I use [Snippet Compiler](http://www.sliver.com/dotnet/SnippetCompiler/). It gets the job done as far as quickly testing methods and what not. I usually use it for things like testing a regex or trying out random datetime formatters. You can add references to other assemblies and it does provide some degree of intellisense. | [LinqPad](http://www.linqpad.net/) will execute C# snippets as well as LINQ. Nice except that autocompletion is not included in the free version. Of course you can write statements in VS with autocompletion, then copy/paste them into Linqpad. |
128,635 | I can connect remotely to my unix server via SSH, both ftp and shell mode using port 22. However I am not able to do so in Visual Studio. I want to be able to edit files live in a GUI interface.
Any solutions for this?
Thanks! | 2010/04/07 | [
"https://superuser.com/questions/128635",
"https://superuser.com",
"https://superuser.com/users/-1/"
] | I found the correct solution via a [similar (but slightly different) question](https://superuser.com/questions/106947/make-firefox-open-new-windows-as-new-tabs-but-open-javascript-popups-as-popups):
* Type `about:config` \* into the address bar.
* Dismiss the warning.
* Change [browser.link.open\_newwindow.restriction](http://kb.mozillazine.org/Browser.link.open_newwindow.restriction) to 0. (and make sure browser.link.open\_newwindow is set to 3 which is the default)
\* SU won't let me hyperlink to `about:config`? | I use the [Tab Mix Plus](https://addons.mozilla.org/en-US/firefox/addon/1122) extension for this. It has tons of options for tweaking tabs to work exactly how you want. I have it set to "single window" mode which makes everything open in a new tab, no matter what. |
564,684 | How is the password I enter in, say a Gmail login form, transferred to the web server securely?
* What does the browser or any client application do?
* What does the web server do? | 2009/02/19 | [
"https://Stackoverflow.com/questions/564684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7205/"
] | By using [SSL](http://en.wikipedia.org/wiki/Secure_Sockets_Layer).
**EDIT**
A nice resource of information about security and encryption is the [Security Now!](http://www.grc.com/securitynow.htm) podcast by Steve Gibson and Leo Laporte. Steve can explain very thouroughly how security works, so go check it out!
The latest episode (#183) is about **Modes of Encryption** ([link to shownotes/podcast](http://www.grc.com/sn/sn-183.htm)) | This depends entirely on whether it's an HTTPS or HTTP request. In general, HTTP authentication requests are sent in what's called "plaintext equivalent". It's Encoded in Base-64, which is easily reversed so it's basically plaintext - meaning it's not secure.
Some browsers, like Internet Explorer have some extensions to allow "secure" passwords to be sent to servers that understand, and can decode them. This generally means IIS running in a domain environment. I put secure in quotes because, as most things Microsoft does, the amount of true security is often up for discussion.
If you're using HTTPS, the password is still sent the same way, but because it's passing over a secure transport it doesn't matter if the password is cleartext or not, since the transport is encoding it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.