INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Best lightweight Ruby IDE for Mac OSX?
Anyy recommendations on a IDE to use for the MAC?
I currently use TextMate and its ok. Is tere a ay though for it to auto suggest tags?
For example.. typing pu.. would bring up puts etc.
I also tried RubyMine and Komodo but they are both way to bloated for my liking. | You can try MacVim with this set of plugins: < . It`s rather lightweight, supports easy navigation and can be customized to any needs. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby, macos, ide"
} |
How to display .tiff images in iphone?
I want to display .tiff images coming from server in my native iphone application. Is it possible to display .tiff images in native iphone application? I am trying to solve this problem since 2 hrs with no success. I searched the net for nearly 2 hrs with no solution to this problem.
Can anyone help me to solve this problem...
Any sample code will be very helpful...
Thanx in advance... | Here it says that the tiff format is supported by the `UIImage` class so you can load it in one of those and put it into an `UIImageView`. Have you already tried this? If the answer is yes, post some code | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "iphone, objective c, tiff"
} |
Can you configure the port on wildfly for microprofile-health endpoint?
The standard behaviour for wildfly-17 (and 18) with microprofile-health-smallrye is, that the /health endpoints are published under the management port.
**Is there a way to configure it to use a different port?**
That behaviour is difficult in some situations (with docker and kubernetes) to open up the management port completely, and make it accessible, for other "machines" than localhost.
Thanks in advance,
Gabriel | Jeff Mesnil answered my thread on the wildfly-user chat -> It is not possible to run health endpoint on application port. WildFly only expose them to the managment port. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 5,
"tags": "wildfly, health monitoring, microprofile"
} |
Different number of sub-levels in different chapters
Is it considered bad form to have a different number of sub-levels in different chapters in a technical report? Or would something like the following be admittable?
> Chapter 1 - Introduction
>
> Chapter 2 - Theory
>
> Section 2.1 - Explosions
>
> Section 2.2 - Drag Loads
>
> Section 2.2.1 - Drag Loads on Piping
>
> Section 2.3 - Compressibility Effects
>
> Chapter 3 - Simulations
>
> Section 3.1 - Stationary Simulations
>
> Section 3.2 - Transient Simulations
>
> Chapter 4 - Conclusions
And, do each heading has to be followed by text, as in the following?
> **Chapter 2 - Theory**
>
> In this chapter we will consider...
>
> **Section 2.1 - Explosions**
Where I work, we try to stick to the IEEE Style, if that in any way affects the answers. | If you're following a style guide, see what it has to say about this. Some may want to specify a maximum depth of nesting, or specify what kinds of divisions qualify as new levels.
If someone else isn't setting the rules, set your own -- just be consistent about it, and avoid the temptation to create new entries where they aren't needed. Generally, if you've gone more than four levels deep in anything but a highly technical document, you're creating more confusion than you're reducing. | stackexchange-english | {
"answer_score": 1,
"question_score": -1,
"tags": "writing, style manuals"
} |
OpenLDAP schema and attribute for account type
We have different account types:
* **Personal** \- For employees
* **Sponsored** \- For users that are affiliated with the organization but not official employees
* **E-mail only** \- Only for e-mail usage (campaigns, etc)
* **Shared** \- For offices or departments
Right now, we use an Oracle database to distinguish account types but are looking to move this information into LDAP.
Anyone aware of a schema and attribute that would be applicable to denote these accounts?
**Schemas currently loaded:** Default OpenLDAP schemas along with the eduPerson and eduOrg schemas. | The employeeType of the inetOrgPerson objectclass would appear to be the appropriate field.
You may be able to determine E-mail only by lack of certain fields. | stackexchange-serverfault | {
"answer_score": 3,
"question_score": 2,
"tags": "ldap, openldap, schema"
} |
Regular expression to match z1 or z2 in Ocaml
How to write regular expressions in ocaml?
How can I write a regular expression for `"z1" + "z2"` (z1 or z2) ?
I tried this way, but it is giving me errors.
let p = Str.regexp "("z1")|("z2")";; | If you intend to match double quotes in your input you should escape them:
"(\\"z1\\")\\|(\\"z2\\")"
And you can shorten the alternation using `z1|z2`:
"(\\"z1\\|z2\\")"
Otherwise, if double quotes aren't part of the input, the pattern should be:
"(z1\\|z2)" | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": "regex, ocaml"
} |
how can I write html code between PHP tag
I want to write html code between php without using of echo
I want to write like this
<?php
<div>
<ul>
<li>My Text</li>
<li>My Text</li>
<li>My Text</li>
<li>My Text</li>
<li>My Text</li>
</ul>
</div>
?> | Or use heredoc syntax. <
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
echo $str;
?> | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -5,
"tags": "php, html"
} |
What is the relationship between median disease free survival and median follow-up distribution?
I created a Kaplain Meier disease free survival curve with the following statistics (in months):
n events median 0.95LCL 0.95UCL
127.0 36.0 59.6 45.0 NA
After subsetting, for the 36 patients with disease onset I calculated the follow-up distribution (in months):
Min. 1st Qu. Median Mean 3rd Qu. Max.
2.104 9.485 25.940 25.260 35.660 59.570
I understand that the median KM survival means the time to 50% disease onset, but I was wondering if my follow-up distribution make sense with this the KM analysis? If I presented both of these numbers how would I relate these two calculations? | The two distributions would only be equal if the censoring is uniform, which is a stronger condition than non-informativeness or independence.
As such, it does not mean anything. For instance, if you have a fixed censoring time for all the individuals, then the distribution of the subset which has an event will always underestimate the real distribution of the events, simply because you will not observe events that would happen later. | stackexchange-stats | {
"answer_score": 0,
"question_score": 1,
"tags": "survival, descriptive statistics, kaplan meier"
} |
how it is executing for $a++ + $a++ + $a vs $a + $a++ + $a++
I've seen a question on SO like this and confused :( , as I know `$a++` will increment value that will available when I'll print `$a`, itll print 2 . but if I print `$a++` it is 1 not 2
<?php
$a=1;
echo $a + $a++ + $a++; // it returns 5
?>
but
<?php
$a=1;
echo $a++ + $a++ + $a ;// it returns 6
?>
I want to know why the later in prints 6 instead if 5? not sure about associativity or precedency for now. can anyone explain? | When `++` occurs after the variable, it's a "post-increment" operator, meaning the initial value is returned before incrementing. When it occurs before the variable, it's a "pre-increment" operator, which increments before returning the newly-incremented value.
Additionally, when evaluating `left + right++`, you need to evaluate `right++` first because post-increment takes precedence (you need to return the value before you can evaluate the addition).
Thus `$a + $a++ + $a++` will evaluate as `($a + (1++)) + $a++ -> (2) + 1 + ($a++) -> 2 + 1 + (2++) -> 5`, and `$a++ + $a++ + $a` will evaluate as `(1++) + $a++ + $a -> 1 + (2++) + $a -> 1 + 2 + (3) -> 6`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php"
} |
Is there a way to automatically link private repo's Github issues to the project board without access token?
Is there a way to automatically link Github issues to the project board without the access token?
I know that there is a way with access token like below.
<
But, I'd like to link the private repository's issues when it's opened to the project board **without the access token because of security concerns.**
Is there any way to archive that?
Thanks! | No - the only way to access your private repository by any service or library from outside is to use Personal Access Token.
You should not be concerned about the security of this solution as long as you keep your TOKEN in secret. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "github, github actions, github api"
} |
How to preserve the item order in a Python dictionary?
I am writing a script in which the computer will play a game of war with itself. I need the script to only return the value of the first entry in the list:
Note: This is only an example
test = {'hey':1, 'hi':2, 'hello':3, 'greetings':4, 'goodmorning':5, 'night':6}
for a in test:
print test[a]
#this returns
1
2
3
4
5
6
I would like this script to only return the value of the first entry. | Since dictionaries are unordered, and if you are dependent on using a dictionary, but order matters to you, you should consider using an OrderedDict from collections. This will preserve the order of your dictionary based on insertion. So, if you enter `a, v, b`, it will be in that order.
Demo:
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d['a'] = 1
>>> d['v'] = 1
>>> d['b'] = 1
>>> d
OrderedDict([('a', 1), ('v', 1), ('b', 1)])
To get the first value based on requirements to get only the first entry:
d.items()[0][1] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "python, arrays, list, dictionary"
} |
Changing shapefile to fit inside feature of another
I have shapefiles with maps of school districts by state. However, some of these districts go beyond the state's area, shown below. I want to preserve the districts, just remove all the bits going out into the lakes and such. How can I automatically adjust the boundries of the districts that extend beyond the state's land mass so that they don't any longer?
Ideally, using QGIS, but any solution is welcome. In other words, I'm just looking to cut off features in the school district shapefiles based on the Michigan feature in the U.S. map shapefile.
 _Michigan school districts_
 _Michigan school districts and state outline_ | As @Joseph has mentioned in comments, the best way is to use a "Clip tool".
Besides, you can use "Intersection".
Both can be found in
> Vector > Geoprocessing Tools
* * *
**References:**
* GrindGIS | Basic Editing Geoprocessing Tools in QGIS
* QGIS Tutorials | Geoprocessing | stackexchange-gis | {
"answer_score": 3,
"question_score": 1,
"tags": "qgis, polygon, clip, geoprocessing, overlapping features"
} |
Flex 4 - Define a style for html links in CSS
It's been 2 hours that I'm trying to do this, I never thought it would be such a nightmare, and Google isn't helping me at all.
Does anybody know how can I define a CSS style for html hyperlinks inside a `mx|Label` component such as `a`, `a:link`, `a:hover` and `a:active` ?
( _I can't use s|Label since it doesn't dispatch`link` events..._)
I tried everything (even really stupid ones), but am unable to find anything that actually works:
mx|Label.a {...}
mx|Label a {...}
mx|Label:a {...}
a {...}
mx|Label.a:link {...}
mx|Label a:link {...}
mx|Label:a:link {...}
a:link {...}
*|a {...}
*|a:link {...}
mx|a {...}
mx|a:link {...}
None of these are working, and I didn't found any help anywhere, nobody seems to have encountered this issue.
I'll be extremely grateful if someone could help me on this.
Thanks in advance. | The only working solution I found is setting the styles manually using ActionScript :
var styleSheet:StyleSheet = new StyleSheet();
styleSheet.parseCSS( "a:hover { color: #6666ff; text-decoration: underline; } a { color: #0000ff; }" );
label.styleSheet = styleSheet;
...which I find pretty ugly (mixing .css file with hard-coded styles...)
Somebody got anything nicer? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "html, css, apache flex, hyperlink"
} |
How to use M21 and SVD sniper rifles in BC2: Vietnam?
Can someone please suggest what is a good strategy and attachments for M21 and SVD rifles as I am really struggling with them. At which range should they be used, where to aim, at which rate to shoot, etc.
If I use it as an assault rifle with 4x scope then at middle-close range any regular rifle would outperform it. If I put 12x scope and snipe with it then the only way to get a kill for me is to find someone dumb enough to stand still while I shoot 3 times. | You should treat them as designated marksman rifles and not true sniper rifles. In other words engage at medium range where you have the accuracy advantage but not at the extreme range of a sniper rifle. If the enemy gets too close, withdraw and find a better spot. Look for large stretches of open terrain so you can keep the target in sight to get off follow-up shots to your first shot. This'll help you actually get kills with them. | stackexchange-gaming | {
"answer_score": 1,
"question_score": 0,
"tags": "battlefield bad company 2 vietnam"
} |
SSHで接続しようとすると connection refused と表示される
iTerm `ssh [email protected]`
ssh: connect to host 192.0.2.1 port 22: connection refused | connection refused sshd
* IP `192.0.2.1`PC
* sshd
*
*
| stackexchange-ja_stackoverflow | {
"answer_score": 14,
"question_score": 3,
"tags": "linux, ssh"
} |
How to add custom neo4j browser guide as Built in Guide?
It is possible to create custom neo4j browser guide and run it.
Ex: `:play Also neo4j has default browser guides like `:play cypher`.
I want to make my neo4j guide as built in guide like `:play mycustomguide` How can I do it? | That's only possible for guides that currently reside on guides.neo4j.com
You'd have to patch the browser code for that. github.com/neo4j/neo4j-browser
But you can configure in neo4j.conf a start command that allows you to play your guide automatically at the beginning, see:
< | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "neo4j, neo4j browser"
} |
"Indeed!" for exclamation
I was wondering what the French translation of "indeed" would be, as a one-word exclamation
> What a beautiful goal!
>
> Indeed!
Would it be "en effet" or "effectivement"?
> Quel beau but!
>
> En effect! / Effectivement! | "Indeed" is quite formal in English so to keep the same tone, a good translation would be:
* En effet !
In casual spoken French, you are more likely to hear:
* Oui !
* C'est vrai !
* Absolument !
and other similar replies, including even:
* Tout à fait, Thierry ! | stackexchange-french | {
"answer_score": 5,
"question_score": 2,
"tags": "expressions, traduction"
} |
react params - Warning: Unknown prop `params` on <a> tag. Remove this prop from the element
I am trying to make a profile page with react router and `Warning: Unknown prop params on <a> tag. Remove this prop from the element.` I am trying to pass params to a route so each user has their own unique page loaded with their content. The solution I got was from 2015 and I don't know if they had removed it. Is there a new/updated version of passing params into the path of a route or am I doing something wrong?
<Route component={userProfile} path="/user/:userId" userIdentity={Meteor.userId()}/>
<p><Link to="/userProfile/:userId" params={{userId: Meteor.userId()}}>My Profile</Link></p> | Are you just trying to pass the `userId` as a param? You can access it in your Link'd component `<UserProfile />` by calling `this.props.match.params.userId` and going from there. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "reactjs, meteor, parameters, react router"
} |
Return referenced sheet name within an formula in excel
Is there a way to check which spreadsheet is being referenced **within** a formula.
For example, I have the following reference `=('2015'!A1)` and I need to check which sheet I am using in the reference. In this example it's " **2015** ". But sometimes I changes to "2016", sometimes to "2012"... Is there a way to check or return the referenced sheet within the formula? Preferably without VBA. | If you have that specific format with brackets and your formulas are simple as your example, this will do the trick:
=MID(FORMULATEXT(A1),FIND("(",FORMULATEXT(A1))+1,FIND("!",FORMULATEXT(A1))-FIND("(",FORMULATEXT(A1))-1) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "excel, excel formula"
} |
How to write "AND" in LINQ
var customer = _customerRepository.Single(c => c.Email == email)
I also want to say c=>c.psw == password.
For some restrictions, I have to use lambda expression. How to write such a query? | Try using `&&`:
var customer = _customerRepository.Single(c => c.Email == email &&
c.Password == password);
Note that `Single` will throw an exception if the email or password is incorrect. This is most likely not an exceptional situation but simply an error in the user's input. Therefore it might be better to use `SingleOrDefault` and checking for `null` instead of using `Single` and catching the exception. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 2,
"tags": "linq"
} |
.htaccess redirect after replace a word?
I need to use .htaccess file to replace a word in a URL; something like this:
Example URL:
Redirect to:
How can I use mod_rewrite to redirect every URL containing **/oldword/** to the same URL after replacing that word? | This should do it for you:
RewriteRule ^oldword/(.*) /newword/$1 [L]
Edit: It might not work exactly depending on your RewriteBase settings, but it'll be close.
Second Edit: If you need to have a 301 Moved Permanently header associated with the old URLs, you can do something like this as well:
RewriteRule ^oldword/(.*) /newword/$1 [R=301,L] | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 2,
"tags": "regex, .htaccess, mod rewrite, redirect"
} |
Android Grid view with different width of column
I am trying to make grid view with two column but the problem is that I want to change the width of every column randomly.
I try to create it using stagger grid view but it only change the height of column and I need to change of width of column.
I am adding image what I want to make below:
;
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup()
{
@Override
public int getSpanSize(int position)
{
if (position == 0)
{
return 2;
}
else if(position == 1)
{
return 2;
}
else if(position == 2)
{
return 3;
}
else if(position == 3)
{
return 1;
}
}
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "android"
} |
Laravel 5.4 return error message if user try login without password
I need to show an error like the error when user write a wrong data in the login form when user does not enter his password. I think the method I should overwrite is validateLogin()
protected function validateLogin()
{
$this->validate(request(), [
'email' => 'required', 'password' => 'required'
]);
}
But it isn't given me the error message in view. I got the error when I left email field empty but not when I left password empty | The problem wasn't in the ValidateLogin Method it was in the view.
@if ($errors->has('email'))
<span class="help-block" style="margin-top:30px;">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
I was just need to have the same if condition for the password. thanks for your help | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "laravel, laravel 5, laravel 5.4"
} |
Django Streaming DumpData
How do you get Django's dumpdata management command to stream contents to a file instead of loading everything into memory?
I'm trying to convert a 1GB Sqlite3 database to PostgreSQL, and one method I'm considering is dumping the database to json using `python manage.py dumpdata --all --format=json > mydatabase.json`.
This ran for about 5 minutes before it consumed all my memory and crashed my machine. | You can try a patch from < but I think a better way is to dump data to sql. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "python, database, django"
} |
The /top-answer-tags method is not working
I tried the new `/top-answer-tags` method on Ask Ubuntu, but it isn't working:
**URL:**
<
**Output:**
{
"error": {
"code": 500,
"message": "A generic error has occurred on the server; developers have been notified."
}
} | Hmm... subtle.
Looks like, technically, some of the top score you've earned there are on tags that no longer actually exist. I'm filtering those out for the time being (so you look like a user who hasn't yet got 30 top tags)... probably going to change that to just drop down however many tags on the list. Depends on how expensive that turns out to be though. | stackexchange-stackapps | {
"answer_score": 0,
"question_score": 1,
"tags": "bug, status completed, api v1.1"
} |
What is the difference between x:Name="someName" in SL and ID="someID" in Asp.Net?
I have an Asp.Net background and trying to learn Silverlight.
Can you explain, what is the difference between x:Name="someName" in Silverlight, XAML and ID="someID" in Asp.Net markup?
(If they both make a element unique, why one is called Name and the other is called ID ? ) | I gather _compatibility with ASP.Net_ was not one of the requirements considered when they designed Silverlight (which derived in turn from WPF) :)
"ID" is a very technical term whereas "Name" is a bit more human readable. They are after all just the matching _name_ of a member of the code-behind class generated at compile time. ID as a term makes more sense for data keys etc.
Classic ASP, and then ASP.Net, date back to before WPF _and way before Silverlight_ so the naming is going to be a bit more old-school. Being more recent the naming of most elements tends to be a bit more sensible in Silverlight (compared to ASP).
Note: _This is all just my opinion based on working with all the above technologies for many years._ Hope it helps. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "asp.net, .net, silverlight, xaml"
} |
How to count NA in head of vector?
x=c(NA, 2, -3, NA, -5, 5, -7, -8, -9, -10, NA, -2, 2, -14, -15, NA, -17, 2, NA, -20)
I would like to select the first 10 values that are not `NA`. so I do:
head(x[!is.na(x)], 10)
Now I want to know how many NA were ignored:
sum(is.na(head(x[is.na(x)], 10)))
# [1] 5
which is not correct: it should be 3 | This should do it:
sum(is.na(head(x, which(cumsum(!is.na(x)) == 10))))
The `cumsum` of the logical vector given by `!is.na` gives us the index of the tenth non-`NA` number, which is the input we want for the `head` function (because we want all values of until we get to the tenth non-`NA` value). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "r, vector, na"
} |
Slide div element using animate() not working
I'm trying to make my div element to slide from left to right using `animate()` jQuery method. Everytime somebody clicks on button it should check the divs left property value. If the value equals to -90% it should slide it from left to right. Otherwise (if it is 0) it should slide it back (left:-90%).
JS:
$("button").click(function() {
if($("div").css('left') == "-90%"){//check if left:-90%, if true slide it to right
$("div").animate({left: "0px"},1000);
}else{
$("div").animate({left: "-90%"},1000);//if left is not -90% slide it to left
}
});;
HTML:
<button>Click Me</button>
<div>
</div>
CSS:
div{
height:100px;
width:90%;
position:absolute;
background-color:#77A3C5;
left:-90%;
}
button{
display:block;
position:absolute;
} | No need to get fancy with percentages, just keep it simple with this:
$("button").click(function() {
if($("div").position().left < 0){
$("div").animate({left: "0px"},1000);
}else{
$("div").animate({left: "-90%"},1000);
}
});
Demo: | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -1,
"tags": "javascript, jquery, html, css"
} |
How set text field and button at center of view automatically when mode change?
I want to set text field , uibutton, label and image view at the center of UIView automatically when i change mode of view either land scape or portrait mode.My mean that when i change orientation then text field and button and image automatically set in center of view. How i set them by using interface builder or dynamically? | Write code in this method
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if (fromInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || fromInterfaceOrientation == UIInterfaceOrientationLandscapeRight )
{
//write your code specific to orientation
}
else if(fromInterfaceOrientation == UIInterfaceOrientationPortrait || fromInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
{
//write your code specific to orientation
}
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "iphone, uiimageview, uibutton, uitextfield, uiinterfaceorientation"
} |
Converting Character to Date Class in R
I have an R dataset filled with character strings that look like this:
`date <- "2019-03-12T14:32:24.000-01:00"`
Is there a way to convert this date and time to a date class where both the date 2019-03-12 and the time T14:32:24.000-01:00 are displayed? I need a way to manipulate these dates later on, so I can find the time difference between two dates down to the seconds. I'm building the solution in R. Thanks! | You can use `lubridate`'s `ymd_hms`.
date <- "2019-03-12T14:32:24.000-01:00"
date1 <- lubridate::ymd_hms(date)
date1
#[1] "2019-03-12 15:32:24 UTC"
Note that timezone has changed to UTC now and hence you see a different time.
If you only want the date you can use `as.Date` and extract the time part with `format`.
as.Date(date1)
#[1] "2019-03-12"
format(date1, '%T')
#[1] "15:32:24" | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r, datetime"
} |
Is it bad practice in Laravel to specify where() and find() in one query?
In controller, which shows simple users
User::where('is_admin', false)->find($id);
In controller, which shows admins
User::where('is_admin', true)->find($id);
Of course, to add more magic we can do
public function scopeAdmins($query)
{
return $query->where('is_admin', true);
}
And use
User::admins()->find($id);
But it is just syntactic sugar | I don't see any issue with how you have it. Both the scope or the raw where clause would work. The scope is mostly syntactic sugar. The nice thing about scopes it is puts all admin constraints in one location so if you change how users are flagged as admin you only have to change it in one place.
You could potentially make the scope a little more generic like this:
public function scopeAdmins($query, $isAdmin = true)
{
return $query->where('is_admin', $isAdmin);
}
Then get admins like
User::admins()->find($id); // or more explicitly User::admins(true)->find($id);
Then to get non admins like
User::admins(false)->find($id); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "php, laravel"
} |
Implement No Cache using Spring Security
I would like to know as to how can I implement a No Cache functionality using Spring Security. That is , when a user logs out of the application he/she can always make use of the browser back button to visit the previous pages.
I want to prevent this behavior and show the user a page expired message and ask him to relogin.
how can i achieve this using Spring security. | If the user hits the back-button in his browser, it will probably go back to a page in its local browser cache and not perform a new request to the website.
The only way you would be able to perform the functionality you need is if you send an ajax-request on each page you have to see if the user session is still valid. This approach is however invalidated when the user turns javascript off in his or her browser. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, spring, spring security, servlet filters"
} |
Removing leading zero in java code
May I know how can I remove the leading zero in JAVA code? I tried several methods like regex tools
"s.replaceFirst("^0+(?!$)", "") / replaceAll("^0*", "");`
but it's seem like not support with my current compiler compliance level (1.3), will have a red line stated the method replaceFirst(String,String)is undefined for the type String.
## Part of My Java code
public String proc_MODEL(Element recElement)
{
String SEAT = "";
try
{
SEAT = setNullToString(recElement.getChildText("SEAT")); // xml value =0000500
if (SEAT.length()>0)
{
SEAT = SEAT.replaceFirst("^0*", ""); //I need to remove leading zero to only 500
}
catch (Exception e)
{
e.printStackTrace();
return "501 Exception in proc_MODEL";
}
}
}
Appreciate for help. | If you want remove leading zeros, you could parse to an `Integer` and convert back to a `String` with one line like
String seat = "001";// setNullToString(recElement.getChildText("SEAT"));
seat = Integer.valueOf(seat).toString();
System.out.println(seat);
Output is
1
Of course if you intend to use the value it's probably better to keep the `int`
int s = Integer.parseInt(seat);
System.out.println(s); | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 4,
"tags": "java"
} |
How can i match this text with a regex?
I've tried to make a regex expression to match a piece of code, but no success. The expression doesn't work in vs2008.
I've created this one:
/\*<parameters>\*/(?<value>[\r\n]*.*)/\*</parameters>\*/
the source to match is:
/*<parameters>*/
@parameter blue
,@parameter2 red
,@parameter3 green
,@parameter4 yellow /*</parameters>*/
Or better:
/*<parameters>*/ \r\n @parameter blue \r\n ,@parameter2 red \r\n ,@parameter3 green \r\n ,@parameter4 yellow /*</parameters>*/
Can anybody help me?
thanks, Rodrigo Lobo | Try this Regex out: `/\*<parameters>\*/(?<value>[^/]*)/\*</parameters>\*/`
A good tool for fooling around with real c# Regex patterns is regex-freetool on code.google.com | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "c#, regex"
} |
Continuous Extension of Maps
**Problem:** Let $f\colon \mathbb{Z}\rightarrow \mathbb{Z}^2$ be a bijective map. Can $f$ be extended to a continuous map from $\mathbb{R}$ to $\mathbb{R}^2$?
I tried this question with positive answer.
**Solution:** The spaces $\mathbb{Z}$ and $\mathbb{Z}^2$ are discrete subspaces (w.r.t. induced topology) of $\mathbb{R}$ and $\mathbb{R}^2$, hence $f\colon \mathbb{Z}\rightarrow \mathbb{Z}^2$ must be continuous. By Tietze's Theorem, $f$ can be extended to a continuous map from $\mathbb{R}$ to $\mathbb{R}^2$.
**Question:** Is this answer correct? Point out if any mistake is there. Further, if it is correct, I also welcome any different argument also. | It's basically correct. $\mathbb{R}^2$ is an absolute extender (Tietze applies for codomain the reals, and this is a basic corollary), and $\mathbb{Z}$ is closed in $\mathbb{R}$. So we see the original map as one from $\mathbb{Z}$ to the plane, also continuous. | stackexchange-math | {
"answer_score": 3,
"question_score": 4,
"tags": "general topology"
} |
How to round date time index in a pandas data frame?
There is a pandas dataframe like this:
index
2018-06-01 02:50:00 R 45.48 -2.8
2018-06-01 07:13:00 R 45.85 -2.0
...
2018-06-01 08:37:00 R 45.87 -2.7
I would like to round the index to the hour like this:
index
2018-06-01 02:00:00 R 45.48 -2.8
2018-06-01 07:00:00 R 45.85 -2.0
...
2018-06-01 08:00:00 R 45.87 -2.7
I am trying the following code:
df = df.date_time.apply ( lambda x : x.round('H'))
but returns a serie instead of a dataframe with the modified index column | Try using `floor`:
df.index.floor('H')
* * *
Setup:
df = pd.DataFrame(np.arange(25),index=pd.date_range('2018-01-01 01:12:50','2018-01-02 01:12:50',freq='H'),columns=['Value'])
df.head()
Value
2018-01-01 01:12:50 0
2018-01-01 02:12:50 1
2018-01-01 03:12:50 2
2018-01-01 04:12:50 3
2018-01-01 05:12:50 4
df.index = df.index.floor('H')
df.head()
Value
2018-01-01 01:00:00 0
2018-01-01 02:00:00 1
2018-01-01 03:00:00 2
2018-01-01 04:00:00 3
2018-01-01 05:00:00 4 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 6,
"tags": "python, pandas, datetime, dataframe"
} |
.htaccess redirect only if GET parameter exist
I have the following line in my `.htaccess` file:
Redirect 301 /folder1
This will redirect everything from `/folder1` to `
I need a condition to only allow this redirection if the URL contains a `mykey=` GET parameter, else ignore this redirection command.
How can I do that? | You cannot do this using `Redirect` directive that does basic URI matching.
You will need to use `mod_rewrite` based rules for this like this:
RewriteEngine On
RewriteCond %{QUERY_STRING} (^|&)mykey= [NC]
RewriteRule ^folder1(/|$) /folder2/file.php [R=301,L,NC]
Make sure to clear your cache before testing.
**References:**
* Apache mod_rewrite Introduction | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "apache, .htaccess, redirect, mod rewrite, http redirect"
} |
Creating a table but with other entities in a compound key?
I have 2 Primary key tables and 1 Compound table.
I want to have some other information apart from the 2 primary keys from the primary key table in the compound table.
Would I just repeat this data or is their a way to add other fields into a the compound field without repeating it?
Thanks. | Your current design looks close to right. But I think your `EventVolunteer` table should look like this:
CREATE TABLE EventVolunteer (
eventID INTEGER,
volunteerID INTEGER,
FOREIGN KEY eventID REFERENCES Event(eventID),
FOREIGN KEY volunteerID REFERENCES Volunteer(volunteerID),
PRIMARY_KEY(eventID, volunteerID)
)
This bridge table should exist to store relationships between events and their volunteers, and nothing else. All metadata for events and volunteers should be in the `Event` and `Volunteer` tables, respectively.
If you need to bring in some information, then you can do so via joining the `Event` and `Volunteer` tables with this bridge table. This join is much less of a penalty than you might think, if you have indices setup in the right places. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, sql, database"
} |
Music group that does electric guitar covers of classical music?
I'm looking for a specific group that does electric guitar covers of classical music. The traits I know about this group:
* Album cover is a white guitar similar to the Les Paul
* They made a cover of Ode to the Joy, Rondo Alla Turca and Can Can music. | Is it possible that you are thinking of the game soundtrack of Bachsmith II < Actually the Rondo Alla Turca is from the first part: < Seems that the performers are `The Notetrackers`. Here is the cover of the game that I think matches your description:  which is called the sparsity parameter. I am confused as to why would we be interested to restrict the activation of hidden neurons ? | An autoencoder attempts to reconstruct the input. During the process it could learn the identity function if the size of the hidden layers is greater than the number of inputs. However that is not desirable.
During learning, the autoencoder discovers the most common features in the input. For example if the input is a natural image, it discovers an edge because it is the most common feature in all natural images.
In the simplest case, the autoencoder is constructed with fewer hidden units than its input layer. As hidden units are added, it can enlist more features to represent the input. However, as the number of hidden units exceeds the number of input units, the features becomes more and more dependent. The autoencoder can discover those features when the hidden layers are densely activated.
Sparsity restricts the activation of the hidden units, which reduces the dependency between features. This allows us to increase the number of features, which is desirable. | stackexchange-stats | {
"answer_score": 8,
"question_score": 7,
"tags": "deep learning, unsupervised learning, autoencoders"
} |
How to list features that can be enabled and disabled in ./configure script?
Lots of open source software is distributed in source code with autotools build system. In order to build such software i issue `./configure && make`. But for some software i need to build only subset of it - for example, in SRP i'm interested only in library and not in terminal or ftp client. To specify what to build `./configure` script accepts `--disable-`, `--enable-`, `--with-`, `--without-` etc command-line keys that are listed in `./configure --help`, "Features and packages" section.
Given third-party open source archive with `./configure` script is it any way i can easily get list of all features available to enable-disable? Of course such information is available in source code, for example in `makefile.am` and `makefile.in` \- but they are huge and hard to read. Maybe easier way exist, something like `./configure --list-features`? | `./configure --help` will do the trick.
This shows any `--enable-X` or `--with-X` arguments that are defined using the macros `AC_ARG_ENABLE` or `AC_ARG_WITH`, as well as a list of environment variables that the configure script will pay attention to, such as `CC`.
In some large projects that are organized as a series of sub-projects each with their own configure script, you may need to do `./configure --help=recursive` to see all the features/packages for all the sub-projects. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 14,
"tags": "autotools"
} |
helpe to convert from java to php
I have written a java code and I need help writing it in PHP because I do not have enough experience with PHP
public static String mo31385a(String str, String str2, String str3) {
int length = str.length();
char[] cArr = new char[length];
for (int i = 0; i < length; i++) {
char charAt = str.charAt(i);
int indexOf = str2.indexOf(charAt);
if (indexOf < 0) {
cArr[i] = charAt;
} else {
cArr[i] = str3.charAt(indexOf);
}
}
return new String(cArr);
}
i want thes function by php plz | Here:
function mo31385a($str, $str2, $str3)
{
$cArr = array();
for ($i = 0; $i < strlen($str); $i++)
{
$charAt = $str[$i];
$indexOf = strpos($str2,$charAt);
if (!$indexOf)
{
$cArr[] = $charAt;
continue;
}
$cArr[] = $str3[$indexOf];
}
return implode("",$cArr);
} | stackexchange-stackoverflow | {
"answer_score": -2,
"question_score": -5,
"tags": "java, php"
} |
How to resume the submit request that was blocked by event.preventDefault(); when the function is executed
</script>
function videomsg() {
event.preventDefault();
alertify.confirm('custom_title', '',
function() {
/***I want to undo the event.prevent default inside here that stopped my submit request***/
},
function(){ })
.set({transition:'zoom',message: 'custom_label.'})
.show();
}
</script>
I want to undo the `event.preventDefault` inside the `alertify.confirm` function that has stopped my submit request for a button. It | >
> var confirmOpt = true;
>
>
>>
>> function videomsg() {
>> if(confirmOpt){
>> event.preventDefault();
>> alertify.confirm(''custom_title '', function(){ confirmOpt = false;
>> $("#form_id").click(); } , function(){ }).set({transition:'zoom',message:
>> 'custom_message'}).show();
>> }
>>
>
>
> }
>
>
> This is how i fixed my problem, if you get stuck with similar situation try this. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, php, jquery"
} |
Can't enter password in nagios3 installation wizard
I am trying to install nagios 3 on Ubuntu 14.04.1 using How do I install nagios?
I have entered `sudo apt-get install -y nagios3` followed by my password.
I then get the dialog in the link below:
!enter image description here
The text below "Nagios web administration password:" looks strange almost as if I have entered it (which I haven't).
The text in the screenshot also looks different to that in the guide I am following.
I don't appear to be able to enter a password into the dialog and the only keys that the dialog will respond to are the arrow keys and the enter key. I haven't experienced any other text entry problems in the terminal.
I am using kitty as my terminal emulator. Any ideas where I am going wrong? | You could try another terminal, say `xterm`.
In any case, the password that is being asked here is for basic authentication via your (usually Apache) webserver. It is saved using `htpasswd` files, so you can set a blank password now and always set it later. Install `apache2-utils`, and then run:
sudo htpasswd /etc/nagios3/htpasswd.users nagiosadmin
(You can also run `sudo dpkg-reconfigure nagios3-cgi`, to go through the configuration steps again.) | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "software installation, nagios3"
} |
Eiffel "create" over C++ constructor?
What is the difference between C++'s constructor and Eiffels create procedure declaration?
What value is there in being able to have multiple constructor functions for a class? Or is there any other benefit to Eiffels "create"?
Thankyou | In C++ you can overload constructors, so you can define multiple constructors as well.
Having constructor procedures as in EIFFEL has the advantage, that you can define different constructors having the same signature (i.e. same number and type of arguments).
Just imagine a `Triangle` class: You might want to construct a triangle by giving the lengths of the three sides (three float values), or by giving two sides and the enclosing angle (also three float values).
In C++ you would have to define an additional parameter (e.g. a enum value for the 'construction mode'), in EIFFEL you can simply define two construction procedures with different names. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "c++, eiffel"
} |
Is it possible to view another shell's history?
I am running something in a `bash` window that I don't want to interrupt or even suspend momentarily. Is it possible to view command history of that particular window's session? I have multiple windows open, so viewing `.bash_history` won't help much. | No, `bash` doesn't support that. The history is kept in memory and not available for other processes until it is saved to `.bash_history` in the same session using `history -a` or `history -w`. But the moment it's written to the file system, the information from which session the command originated is lost.
The closest you can get is using some lines in `.bashrc` to let `bash` append every command directly after execution: <
Then you can see the commands from all shells in near real-time in `.bash_history`.
To access the history for a specific session you need to interrupt the foreground process in that session using e.g. `Ctrl+Z`. | stackexchange-unix | {
"answer_score": 6,
"question_score": 6,
"tags": "command history"
} |
How to calculate ranging by a few conditions?
I have 2 tables:
activity
user_id login_time
1 2018-04-15
2 2018-04-18
3 2018-04-19
3 2018-04-20
1 2018-04-20
2 2018-04-20
4 2018-04-20
\--
payments
user_id amount
1 10
1 30
2 100
3 35
4 0
I'm looking for number of users, which have login_time = 20.04.2018 by grops.
Desired result on 20.04.2018:
total_amount number of users
0-10 1
10-20 0
30-50 2
50-and more 1
Please help | Use case when and inner join
select case when amount<=10 then '0-10' when amount>10 and amount<20 then '10-20'
when amount>=30 and amount<50 then '30-50'
when amount>=50 then '50-and more' end as total_amount,count(payments.user_id)
from payments inner join activity on payments.user_id=activity.user_id
where login_time='2018-04-20'
group by case when amount<=10 then '0-10' when amount>10 and amount<20 then '10-20'
when amount>=30 and amount<50 then '30-50'
when amount>=50 then '50-and more' end | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "mysql, database, join, select, histogram"
} |
Create a `CheckConstraint` within a `UniqueConstraint`
Before creating a new record I want to check a condition that the combination of `native_linux_user` and `is_active` is unique but `is_active` must be `True`. Multiple `native_linux_user` with `is_active=False` may exist, but only one `native_linux_user` with `is_active=True` can exist.
I tried to use a `CheckConstraint` within a `UniqueConstraint` like this, but it didn't work. How do I make this type of constraint?
__table_args__ = (
UniqueConstraint(
'native_linux_user',
CheckConstraint('is_active=True', name='active_check'),
name='_username_uniqueness'
),
) | From SQL side you can create partial `UNIQUE` index:
CREATE UNIQUE INDEX idx_unique_native_linux_user_is_active
ON table (native_linux_user) WHERE is_active=True;
And SQLAlchemy model with corresponding `Index`:
class Foo(Model):
id = Column(Integer, primary_key=True)
native_linux_user = Column(String, nullable=False)
is_active = Column(Boolean)
__table_args__ = (
Index('idx_unique_native_linux_user_is_active', native_linux_user,
unique=True,
postgresql_where=(is_active==True),
),
) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "python, postgresql, sqlalchemy"
} |
Sorting data store by date?
I use ExtJS version 4.0.7. I have a data store with fields: _recordName_ and _recordDate_. What I want to do is to **sort these records by date** , however recordDate format is: **d/m/y**. After sorting the records, I need to **bind a grid panel** with these records. At this point **user still wants to see recordDate in d/m/y format**.
As a summary, I have a recordDate field in a datastore with format d/m/y (because user wants to see it in that format in the grid panel), but to sort by date I need to reverse to format as y/m/d without changing the format in the grid panel.
Example:
**recordDate in the datastore:** 27/08/2012 (and this is what user want to see at the grid panel)
**date format to sort by date:** 2012/08/27 | As @Evan mentioned:
> If it's a date object, it's not relevant. If you're storing it as a string, then it's not date sorting, it's string sorting.
You need to set your model in a similar fashion:
Ext.define('MyModel', {
extend : 'Ext.data.Model',
fields : [{
name : 'recordDate',
type : 'date',
dateFormat : 'd/m/Y'
},{
name: 'recordName,
type: 'string'
}]
});
Since recordDate will now be a date object, you can use a datecolumn in your grid
columns:[{
text : 'Date',
dataIndex : 'recordDate',
xtype: 'datecolumn',
format:'d/m/Y'
},{
text : 'Name',
dataIndex : 'recordName'
}] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "sorting, extjs4"
} |
problems reinstalling ubuntu-desktop and purging gnome completely
I purged gnome but when I'm at the login screen I can only log in with gnome: if I try to change shell everything is blank. Logging in with gnome lead to a black screen and I can't even open the terminal.
When running
sudo apt-get install ubuntu-desktop
I get the same results as this I tried those answers with no luck. I also tried all the solutions and various command lines here without finding a solution.
I would like to get the standard Ubuntu shell, I don't use unity. | I was able to run `sudo apt-get -f install` after this:
sudo apt-get update
sudo apt-get remove gnome-backgrounds
sudo apt-get remove --auto-remove gnome-backgrounds
sudo apt-get remove gnome-session
sudo apt-get autoremove
sudo apt-get update
sudo apt-get dist-upgrade | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "16.04, gnome"
} |
Explain recursive function for finding max element in array
I decided to incorporate recursions into my code and for that I want to train using it. I have a recursive function which finds the max element in the given array.
def maxx(lst):
if len(lst) == 1:
return lst[0]
else:
m = maxx(lst[1:])
return m if m > lst[0] else lst[0]
maxx([1,3,2])
> 3
I tried to draw a sequence of events and I can't get why the code above works? Because according to what I see it should be **2** not **3**. Where is my mistake? Is there a method that correctly expands the recursion and thus helps you to understand its flow?

Depth 1:
lst = [3,2]
m = maxx([2])
Depth 2:
lst = [2]
returning 2
Back to Depth 1:
lst = [3,2]
m = 2
return m (2) if m > lst[0] (3) else return lst[0] (3)
returning 3
Back to Depth 0:
lst = [1,3,2]
m = 3
return m (3) if m > lst[0] (1) else return lst[0] (1)
returning 3
The reply by Alfabravo is correct, I think that's where you lost track of lst[0] as you went back up the tree. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "recursion"
} |
Oracle - Join two tables by concatenating repeating rows
I have 2 tables like this :
table_a
id col2
1 A
1 B
2 A
2 B
3 B
table_b
id col1
1 X
2 Y
3 Z
result:
id col1 col2
1 X A_B
2 Y A_B
3 Z B
How can I achieve this? | You want `listagg()`:
select b.id, b.col1,
listagg(a.col2, '_') within group (order by a.col2) as col2
from table_b b join
table_a a
on b.id = a.id
group by b.id, b.col1; | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "sql, database, oracle"
} |
How to get the output date format as 2016-05-03T01:38:54.003Z in PHP?
Input time format:
> 2016-05-03 01:38:54
Ouput time format:
> 2016-05-03T01:38:54.003Z
Here what is `.003`, is it millisecond or microsecond?
And in PHP the microsecond format is `'u'`, but when I am trying to use this using the following code snippet, I am getting 6 digits after the decimal point:
<?php
date_default_timezone_set("Asia/Kolkata");
echo date('Y-m-d\TH:i:s.u\Z', strtotime("2016-05-03 01:38:54"));
I am getting the output as:
> `2016-05-03T01:38:54.000000Z`
But in this output after the decimal point it is showing 6 digit, which I want to change it to 3 digit. How can I do that?
So how should I get the output format? | date_default_timezone_set("Asia/Kolkata");
$t = strtotime('2016-05-03 01:38:54');
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
$new= $d->Format("Y-m-d\T H:i:s.u\Z");
echo substr($new, 0, -4) ."Z";
//output 2016-05-03T 01:38:54.030Z | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "php, date, datetime"
} |
Illegal attempt to dereference collection when querying using JPA relations
I have 2 classes:
@Table(name = "PEOPLE")
@Entity
class Person {
@OneToMany(mappedBy = "owner")
Set<Car> cars;
}
@Table(name = "CARS")
@Entity
class Car {
@ManyToOne
@JoinColumn(name = "OWNER_ID", referencedColumnName = "ID")
Person owner;
@Column(name = "MODEL")
String model;
}
I'm trying to query people by model. Running the following code **fails** , even though the connections between the tables are clear:
select mo from Person mo where mo.cars.model = ?
The error is:
org.hibernate.QueryException: illegal attempt to dereference collection [...] with element property reference [model] [select mo from Person mo where mo.cars.model = ?]
Any idea how to resolve the issue? | When the relationship between the entities is already defined, you can use the `join fetch` syntax:
select mo from Person mo join fetch mo.cars c where c.model = ? | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 11,
"tags": "java, hibernate, jpa"
} |
Is there any way to get Function Import support while using DbContext Generator?
I am trying to use the new-ish Entity Framework 4.1 DbContext Generator because it generates very clean POCO classes for all of the entities, and it uses the DbContext API instead of the ObjectContext API. The problem I am having is that there appears to be no way to map "Function Imports" in the DbContext API (or at least using the generator). Is it not possible to use stored procedures for function imports with the DBContext API, or am I just doing something wrong?
Thanks
**UPDATE** I think that this is possible, but I would need to figure out how to get at the underlying ObjectContext of the DbContext API, anyone know how to do that at least? | At least the **Code-First** approach of EF 4.1 doesn't support mapping to Stored Procedures:
> Code First does not support mapping to stored procedures. However, you can call stored procedures directly by using ExecuteSqlCommand or SqlQuery. For example: context.Database.ExecuteSqlCommand("EXECUTE [dbo].[GetAllProducts]");.
But you seem to go Model-First/Database-First approach. I don't know if there is a solution. One could guess there is a way, since it is only said that _Code-First_ doesn't support SP mapping.
And you can access the underlying `ObjectContext` from your `dbContext` instance this way:
ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "c#, ado.net, entity framework 4.1, ado.net entity data model"
} |
how to extract lists having same element value?
I have a list of list like this `data=[["date1","a",14,15],["date1","b",14,15],["date1","c",14,15],["date2","a",14,15],["date2","b",14,15],["date2","c",14,15],["date3","a",14,15],["date3","b",14,15],["date3","c",14,15]]` I want to get lists having the same 2nd index. i tried this code but i got 9 lists when i just need 3 lists.
data=[["date1","a",14,15],["date1","b",14,15],["date1","c",14,15],["date2","a",14,15],["date2","b",14,15],["date2","c",14,15],["date3","a",14,15],["date3","b",14,15],["date3","c",14,15]]
for i in data:
a=[]
for j in data:
if (i[1]==j[1]):
a.append(j)
print(a)
i expected to get `["date1","a",14,15],["date2","a",14,15],["date3","a",14,15]` `["date1","b",14,15],["date2","b",14,15],["date3","b",14,15]` `["date1","c",14,15],["date2","c",14,15],["date3","c",14,15]` | data=[["date1","a",14,15],["date1","b",14,15],["date1","c",14,15],["date2","a",14,15],["date2","b",14,15],["date2","c",14,15],["date3","a",14,15],["date3","b",14,15],["date3","c",14,15]]
from itertools import groupby
from operator import itemgetter
print(
[list(v) for k,v in groupby(sorted(data, key=itemgetter(1)), key=itemgetter(1))]
)
In order for groupby to work the data has to be sorted.
Depending on your use case, the list instantiation of the iterator might not be needed. Added it to see proper output instead of `<itertools._grouper... >` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python 3.x"
} |
Has grammatical gender ever been observed to emerge in a language that previously had none?
Does a language exist whose older forms are known to have lacked the category of grammatical gender, and which proceeded to evolve one (perhaps from a non-gender-based system of noun classes)? Are "pre-gender" stages of language evolution, where they existed, universally a thing of such distant past as to be beyond reconstruction? | Surprisingly, Indo-European seems to be an example. Silvia Luraghi has an article "The origin of the Proto-Indo-European gender system: Typological considerations" ( _Folia Linguistica_ 45/2 (2011), 435–464) which discusses this, and it appears that there is agreement that the M/F/N system of later languages developed from a two-gender system where masculine and feminine were not distinguished, and the system was based on an animate / inanimate. | stackexchange-linguistics | {
"answer_score": 2,
"question_score": 8,
"tags": "historical linguistics, nouns, gender"
} |
Why is this regex selecting this text
I am using the regex
(.*)\d.txt
on the expression
MyFile23.txt
Now the online tester says that using the above regex the mentioned string would be allowed (selected). My understanding is that it should not be allowed because there are two numeric digits 2 and 3 while the above regex expression has only one numeric digit in it i.e `\d`.It should have been `\d+`. My current expression reads. Zero of more of any character followed by one numeric digit followed by .txt. My question is why is the above string passing the regex expression ? | This regex `(.*)\d.txt` will still match `MyFile23.txt` because of `.*` which will match 0 or more of any character (including a digit).
So for the given input: `MyFile23.txt` here is the breakup:
.* # matches MyFile2
\d # matched 3
. # matches a dot (though it can match anything here due to unescaped dot)
txt # will match literal txt
To make sure it only matches `MyFile2.txt` you can use:
^\D*\d\.txt$
Where `^` and `$` are anchors to match start and end. `\D*` will match 0 or more non-digit. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "regex"
} |
Why would not UIImageview be the perfect circle?
let radius = self.bounds.width / 2
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
I applied the above code But it creates a strange shape.
 -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, swift, uiimageview"
} |
How can I make a query, selecting only CATEGORIES which have PRODUCTS into it?
I have a DB structured like this:
CATEGORIES > SUBCATEGORIES > PRODUCTS
In just want show the categories which have an number of products related to it, but I don't know if my method is the best. I thinking in putting some SELECT statement inside the first WHERE, but this sounds "unpratical". I searched into Google/MySQl docs and nothing helped me.
Example of what I have done with CATEGORIES > SUBCATEGORIES:
SELECT c.*
FROM categories c
WHERE
(
SELECT count(*)
FROM subcategories sc
WHERE sc.id_categories = c.id
) > 2
With this query I can sucessfully see which categories have more than 2 subcategories related to them, I just could do the same, adding the PRODUCTS table to this query. But I almost sure this is going to slow the query. There is some more fast way of doing this type of query? Thanks! | Something like this, I don't know your FK relations, so I'm just guessing here.
SELECT *
FROM Categories
WHERE EXISTS(
SELECT NULL
FROM products
JOIN SubCategories ON products.fkSubCatID = SubCategories.PkSubCatID
WHERE SubCategories.fkCatID = Categories.pkCatID
HAVING Count(*) > 2) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "mysql, sql, relational database"
} |
Mod cluster configuring sticky session attribute name
Is it possible to configure the sticky session attribute name in mod-cluster?
I need to use a name different to JSESSIONID.
I´ve tried
ProxyPass / balancer://xxxxx/ stickysession=TESTSESSIONID|testsessionid
ProxyPassReverse / balancer://xxxxx/
but didn't work. | It is not possible till now.
There is a request for enhancement: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "apache, mod proxy, proxypass, mod cluster, sticky session"
} |
Emulator will not show APP
I have imported a softkeyboard APP through eclipse I have tried running it on the emulator and my app icon doesnt even show up..There are no error messages on my app or from the emulator..does anyone know why this may be happening?? I tried to see if I could change the keyboard settings on the emulator but I did not see any option for that. I have tried accessing the text message icon and the softkeyboard that appears is not mine, its the emaulators default..Please advise Thanks so much! | You should check logcat to get the error or some warning messages, please give more details about your problem :D | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, android emulator, android softkeyboard"
} |
convert json array to javascript array
i have a json array that i want to convert into a plain javascript array:
This is my json array:
var users = {"0":"John","1":"Simon","2":"Randy"}
How to convert it into a plain javascript array like this:
var users = ["John", "Simon", "Randy"] | `users` is already a JS object (not JSON). But here you go:
var users_array = [];
for(var i in users) {
if(users.hasOwnProperty(i) && !isNaN(+i)) {
users_array[+i] = users[i];
}
}
**_Edit:** Insert elements at correct position in array. Thanks @RoToRa._
Maybe it is easier to not create this kind of object in the first place. How is it created? | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 8,
"tags": "javascript, json"
} |
What if I know for sure that my target variable is not normally but Beta distributed?
As stated in the question, what sort of modeling technique would be most appropriate? | beta regression: see Fransisco Cribari-Neto and Achim Zeileis, "Beta Regression in R", Journal of Statistical Software, volume 34, issue 2, April 2010. If you have linear regression problem with a Beta noise process, then this is the neat solution. | stackexchange-stats | {
"answer_score": 5,
"question_score": 3,
"tags": "modeling, beta distribution"
} |
How create beta (testing) website?
How create beta (testing) website use same webroot and cake folder ? That beta (testing) website probably is at < or < | A testing or "staging" server should be set up completely independently of the production server. You should _not_ reuse any component of the live system, which even includes the database. Just set up a copy of the production system with a separate database, separate files, if possible a separate (but identical) server.
The point of a _test_ system is to _test_ code that is possibly buggy and _may_ delete all your live data, shoot your dog and take your lunch hostage. Also, your test system may not be compatible with the production system, depending on what you're going to change down the road.
As such, create a new virtual host in your Apache config (or whatever you're using) and set it up exactly like the production system. Done. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "php, cakephp"
} |
asp.hyperlink in gridview Format 0 as null
I am calling a giant stored proc via linq to sql that brings back some numbered data from 0 to 9. I would like to be able to display any zeros as nulls (so there is no hyperlink). I could do this in my stored procedure, but it would make it really hard to read and maintain (there is a lot of case logic going on).
I have the following code linking my procs results to the linqdatasource. Is there a way to update all records by formatting the data before binding or after the fact on the hyperlink?
protected void LinqMainMenu_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
var db = new App_Data.MYAppDataContext();
e.Result = db.sp_MainMenuTest( (Int16)Session["myid"]);
}
Thanks | You could reformat the results by doing something like:
e.Result = db.sp_MainMenuTest( (Int16)Session["myid"]).Select(i => new
{
Field = (i.Field == 0) ? null : i.Field
});
If you can't use this approach, you cna always do it in GridView.RowDataBound event handler, get the cell value, if zero, reformat.
HTH. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "c#, asp.net"
} |
Color of 'ls' changed after zsh upgrade
I am currently using `zsh 5.0.2 (x86_64-pc-linux-gnu)`, when doing `ls` the folders was showing in blue, but after an upgrade everything is in white .. When doing `ls --color=auto` or `ls --color=tty` it goes back to normal. How to make it permanent? What configurations should I change? | ### How to make it permanent? What configurations should I change?
Add the following alias to the end of `~/.zshrc`:
alias ls='ls --color=auto' | stackexchange-superuser | {
"answer_score": 2,
"question_score": 1,
"tags": "bash, zsh, ls"
} |
$f$ is a linear map from $M_n(\mathbb{C})$ to $M_k(\mathbb{C})$
Define $M_n(C)$ as the linear space over the field $\mathbb{C}$ consisting of all the $n\times n$ matrices over $\mathbb{C}$.
Let $f$ be a linear map from $M_n(\mathbb{C})$ to $M_k(\mathbb{C})$ satisfying the following condition:
if $A$ is a $n\times n$ Hermitian matrix, which by definition is a complex matrix satisfying $A=A^*$, then $f(A)$ is an Hermitian matrix in $M_k(\mathbb{C})$.
Prove that $\forall A$ in $M_n(\mathbb{C})$ we have $f(A^*)=f(A)^*$. | The first step consists on showing that the result is true for anti-hermitian matrices, i.e., matrices such that $M=-M^*$. To see this note that $iM$ is hermitian. Then, $$ f((iA)^*)=-if(A^*)=f(iA)^*=-if(A)^*. $$ Once this has been shown, note that any matrix $A$ can be written as the sum of a hermitian and an anti-hermitian matrix: $$ A=\frac{A+A^*}{2}+\frac{A-A^*}{2}. $$ The result follows immediately by working through the equation $$ f(A)^*=f\left(\frac{A+A^*}{2}+\frac{A-A^*}{2}\right)^*. $$ If you need more details let me know and I'll add them. | stackexchange-math | {
"answer_score": 3,
"question_score": 4,
"tags": "linear algebra"
} |
azure vhd mount exception ERROR_HTTPS_NOT_SUPPORTED
I have uploaded a VHD using Cloud storage studio. It gave a https based blob URL. On windows azure, when I try to mount that VHD using drive.Mount method, I get following exception:
ERROR_HTTPS_NOT_SUPPORTED
Thank you. | It was issue with uploading Cloud Storage Studio. When one upload the vhd using https, it gives URL of https, and when some upload vhd using http it gives URL of http. I uploaded the vhd using http and problem got solved. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "visual studio 2010, azure, blob, vhd"
} |
Python indentation issue: Expected an indentation block
def process_health_case(request):
about = request.POST['about']
details = request.POST['narrative_text']
image=request.FILES['image_scan']
connection = Connection('mongodb://sbose78:[email protected]:10068/BOSE')
if images:
db=connection['BOSE']
fs=gridfs.GridFS(db)
fs.put(image,filename="image_scan2")
else:
#nothing
return render_to_response('home/new_narrative.html',{ }, context_instance=RequestContext(request))
I'm getting
expected an indented block (views.py, line 41)
And line 41 is the last line.
Where am I wrong?
Thanks. | You can't use a comment as an empty statement, you should use `pass` if you want to have an explicit else that does nothing.
if images:
db=connection['BOSE']
fs=gridfs.GridFS(db)
fs.put(image,filename="image_scan2")
else:
pass
return ....
Since there's no statement, just a comment in the `else` in your code, python thinks the `return` is supposed to be the content of the `else` and gives an intentation error. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "python, django"
} |
Hibernate Native SQLQuery extract values
How can I extract multiple values from native SQLQuery?
SQLQuery query = session.createSQLQuery("SELECT param1, param2 from table_name where ..);
When I use `query.list()` or `query.uniqueResult`, it returns always list of Object\Object, which cannot be cast to anything even if I add scalars. No problems on extraction single value:
session.createSQLQuery("SELECT param1 from table_name where ..);
Long result = (Long)query.uniqueResult();
But how can I extract 2 or more values ? | According to SQLQuery.list() API:
> Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[]
Sample code:
SQLQuery query = session.createSQLQuery("SELECT param1, param2 from table_name where ..);
List<Object[]> list = (List<Object[]>)query.list();//Object[] objs = (Object[])query.uniqueResult()
for (Iterator<Object[]> iterator = list.iterator(); iterator.hasNext();) {
Object[] e = iterator.next();
String param1 = (String)e[0];//case object type to another by youself...
}
If your program add scalar to `SQLQuery`, _Hibernate_ could return match object type as you expected. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "java, hibernate"
} |
R: Request price feed through Bloomberg API
I have just installed the Rbbg package, the Bloomberg API for R. I can't, however, find any documentation. Would someone either be able to point me to some documentation, or, alternatively, give me some guidance w.r.t importing price feeds/data from Bloomberg to R?
Thanks, much appreciated!
Mike | Found the solution. You have to install Java APIv3 from the Bloomberg terminal (by typing WAPI into the command bar). Once installed you connect it to R using :`install.packages("Rbbg", repos = " and `conn <- blpConnect(log.level = "finest")`. Finally, to extract share price information you use `bdp(conn,securities,function)`.
Useful manual at < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "r, feed, bloomberg"
} |
Is eWASM deployed on Ethereum?
The project is there for 2 years, is still under development. I'm wondering if it's mature enough to use. | It's deployed on the kovan testnet but not on the mainnet. | stackexchange-ethereum | {
"answer_score": 1,
"question_score": 0,
"tags": "ewasm"
} |
Water glass and wine glass
You have two equal glasses. One is filled with water. One is filled with wine.
Now you take a spoonful from the water glass, put it into the wine glass, and stir until it is well mixed. Then you take a spoonful from the wine glass, put it into the water glass.
Now, is there more water in the wine glass than wine in the water glass?
(Please note: I am not a molecular physicist.) | Counter-intuitively, there are exactly equal amounts. We can see this if we consider that each glass has lost and gained the same amount of liquid (a spoonful), so any loss to the other glass is precisely offset by gain from that glass.
Unless, of course, the " **filled** with water/wine" statements were to be taken literally, in which case the water glass will have more wine because the wine glass lost some when it overflowed. | stackexchange-puzzling | {
"answer_score": 2,
"question_score": 2,
"tags": "logical deduction"
} |
like within query
I am using **vs 2010** and want to perform a query on **sql server database**. But i have a problem i want to retrieves a row on the basis of name which i want to retrieves it using _second character of name_ that is i don't know the first character that is **for example the name is nik as i enter i it will retrives a record which having nik as value of name column.** Can any one guided me...I know following query what things i have to modified in it.
select * from table1 where name like '"& n % &"' | > for example the name is nik as I enter i it will retrives a record which having nik as value of name column
try
select * from table1 where name like '_i%'
* TSQL Like | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server, vb.net, tsql"
} |
how to customize next_posts_link link in wordpress
I am using
<?php next_posts_link( '← Next' ); ?>
for pagination in wordpress ,it works ,but how to customize it ,I prefer a button for next but now it appears as 'Next →' | **Refer this site:**
next_posts_link | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": 0,
"tags": "php, wordpress"
} |
Convert data frame to a list, with function from apply family
Like in title i need to converte some data frame
data1 <- data.frame(Year = rep(c(2016, 2017, 2018, 2019), each = 12), Month = rep(month.abb, 4), Expenses = sample(50e3:100e3, 48))
Create a list year_y in which each year (element) contains a data frame with expenses in each month. Then using list year_y create a list containing for each year(element) the month with biggest expenses. Here is what the final result should look like:
$‘2016‘
[1] "Jul"
$‘2017‘
[1] "Nov"
$‘2018‘
[1] "May"
$‘2018‘
[1] "May"
And the thing is i need to use apply function family in both steps | Using base R. Use the the `split()` function to divide the original data frame by year. Then use `which.max()` to determine which month has the highest expenses.
data1 <- data.frame(Year = rep(c(2016, 2017, 2018, 2019), each = 12), Month = rep(month.abb, 4), Expenses = sample(50e3:100e3, 48))
lapply(split(data1, ~Year), function(mon) {
mon$Month[which.max(mon$Expenses)]
}) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "r, list, dataframe, apply"
} |
Index change doesn't work on new DataFrame
I convert dictionaries to a DataFrame and change the index but I still get the numeric index numbers assigned by Pandas. Why didn't the index change to the name column?
import numpy as np
import pandas as pd
exam_scores = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19]}
scores = pd.DataFrame(exam_scores)
scores.set_index('name')
print(scores.describe)
<bound method NDFrame.describe of name score
0 Anastasia 12.5
1 Dima 9.0
2 Katherine 16.5
3 James NaN
4 Emily 9.0
5 Michael 20.0
6 Matthew 14.5
7 Laura NaN
8 Kevin 8.0
9 Jonas 19.0> | Set it inplace to make the reset_index permanent
import numpy as np
import pandas as pd
exam_scores = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19]}
scores = pd.DataFrame(exam_scores)
scores.set_index('name', inplace=True)
scores | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, pandas"
} |
Disappear keyboard in uitextview
i'm using uitextview in swift and for keyboard disappear i'm using uitextview delegate method
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
textView.resignFirstResponder()
return false
}
return true
}
but i don't want to use this delegate method to return the keyboard bcz i want to use return key for next line. is there any other ways to disappear keyboard? and for some reason i don't wana use touch event. | You cannot have both a return and a dismiss key on the keyboard unless you use a custom keyboard. A custom keyboard can be added by setting the `inputView` property
A better standard practice is to have a button on top of the keyboard giving the user an option to hide it. This can be done by assigning an `inputAccessoryView` for the `UITextView`. More here | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "ios, swift, uikit"
} |
Set an iPhone 6 launch image on Visual Studio Tools for Apache Cordova
We are using CTP 3 of VS extension for Cordova.
We are trying to add a splash screen for iPhone 6 and iPhone 6+. We need this to solve and issue where iPhone 6+ resolution is incorrect within the app.
Is there a naming convention for the splash screen files for ios?
We know these file names are being added to the XCode project and work successfully (in res\screens\ios):
* screen-ipad-landscape-2x.png
* screen-ipad-landscape.png
* screen-ipad-portrait-2x.png
* screen-ipad-portrait.png
* screen-iphone-568h-2x.png
* screen-iphone-portrait-2x.png
* screen-iphone-portrait.png | We ended up forcing vs-mda-remote to use cordova 4.2.0 which helped solve the problem (see this question).
Then we added this to the config.xml and the respective files.
<platform name="ios">
<splash src="res/screens/ios/screen-414w-736h@3x~iphone.png" width="1242" height="2208"/>
<splash src="res/screens/ios/screen-iphone-landscape-736h.png" width="2208" height="1242"/>
</platform> | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "ios, iphone, cordova, visual studio cordova"
} |
How come January doesn't have an 'r' in the name like February?
What is the reason for why February has an 'r' after the 'b' but January doesn't have an 'r' after the 'n'? Like so: Janruary, February. There must be an explanation for this, historical or otherwise. | In the Roman calendar _January_ was the month of _Janus_ , the god of gates and doorways ( _janua_ ), this month being the "doorway" to the year. _February_ was the month of purificatory rites, _februa_. | stackexchange-english | {
"answer_score": 4,
"question_score": -6,
"tags": "names, reason why"
} |
init wordpress svn repo in an existing wordpress directory
I have an existing wordpress install that i'd like to upgrade using SVN rather than doing the in-app updates/traditional unzip and upload.
Is this possible?? Can i some how just init the svn repository right over the stuff i've currently got?
thanks!! | You can do this using svn export. The steps would be to SSH into your website, cd to the directory in which you would like the files to be in, then run the svn export command. It will be something like:
svn export svn://path-to-svn.com/trunk/
Make sure that what you have in your SVN is exactly what you want on your live server. One potential issue if you are not careful is that you can overwrite file within your wp-content folder. For instance, imagine that you add a new plugin via the live website. This will add files to the wp-content/plugins folder. If you perform your svn export, you will overwrite these files with whatever is in SVN. An alternative is that you can carefully and selectively export individual files and folders in order to avoid overwrite import files.
Source: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "svn, wordpress, installation"
} |
Finding the Zero Residual Line with Centroid
I need help with finding the zero residual line of three points: _A_ = (3, 1), _B_ = (1,5), and _C_ = (6, 4).
I learned that the zero residual line can pass through the centroid when you are given three points and I found the centroid to be ($\frac{10}{3}, \frac{10}{3}$) by finding the average of the x-coordinates and the y-coordinates separately. I also thought about finding the equation for line $BA$ and, in point-slope form, I got that to be $y - 5 = -2(x - 1)$. I thought about having a line that goes through the centroid and is parallel to line _BA_ , which would be $y - \frac{10}{3} = -2(x - \frac{10}{3})$. However, when I find the residuals, I don't get their sum to be zero, so I am assuming that the equation for the zero residual line is incorrect. Therefore, I want to know where I am wrong and what can I do to fix it. | I guess that the "zero residual line" is the line given by the best fit for a linear regression.
If we consider a line with equation $y=f(x)=ax+b$ we can minimize $$\left(f(3)-1\right)^2+\left(f(1)-5\right)^2+\left(f(6)-4\right)^2 $$ i.e. the quadratic form $$ q(a,b)=42 - 64 a + 46 a^2 - 20 b + 20 a b + 3 b^2 $$ with respect to $a$ and $b$. By setting $\frac{\partial q}{\partial a}=\frac{\partial q}{\partial b}=0$ we get the system of equations $$ \left\\{\begin{array}{rcl}92 a + 20 b &=& 64 \\\ 20 a + 6 b &=& 20 \end{array}\right.$$ with the solution $a=-\frac{2}{19}, b=\frac{70}{19}$.
In such a case $\left(f(3)-1\right)+\left(f(1)-5\right)+\left(f(6)-4\right)=0$ and the line found this way goes through the centroid of $(3,1),(1,5),(6,4)$, namely the point $G\left(\frac{10}{3},\frac{10}{3}\right)$.
]
and then I would like to output it which I do like this
- script: |
echo value is ${{variables.SonarVerbose}}
but it echo's [coalesce(variables['SonarVerbose'],false)] and not an expected 'false'.
Is this not possible ? | It looks that self assignment is not possible. As workaround you may use this:
variables:
sonarVerboseNew: $[coalesce(variables.sonarVerbose,false)]
steps:
- script: echo $(sonarVerboseNew)
- bash: echo "##vso[task.setvariable variable=sonarVerbose;]$(sonarVerboseNew)"
- script: echo $(sonarVerbose) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "azure devops, yaml, azure pipelines"
} |
How to change the Schema name and move the table into another schema?
I have a bit problem while changing the schema name. My problem is I have a table1 with schema1 and there is another schema called schema2. So how can I move the table1 in schema2?
Thanks in Advance | ALTER SCHEMA schema2
TRANSFER schema1.table1;
GO
Ref. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "sql, sql server, tsql"
} |
Preventing the duplication of CSS files?
I got a user control which implements a reference to a css file, now I want to use this user control many times on page, and this will lead to duplication of inclusion of the css file.
With javascript files it is simple by using the `ScriptManager`.
So what is your suggestion for a solution or similar approach to the `ScriptManager`? | There is no easy way to check if the styles are registered to the page like ClientScript utility.
If you register your styles as an external css file to page like that :
HtmlLink link = new HtmlLink();
link.Href = relativePath;
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
Page.Header.Controls.Add(link);
You can then check if it exists by looping the page header's Controls collection and looking for the path of the CSS file. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "c#, asp.net, css"
} |
Block Pyramids in Minecraft - closed formula for total number of blocks
The total number of blocks within pyramids on Minecraft doesn't quite correspond with Square pyramidal numbers (on Wikipedia). Because of the blocky nature of the environment, the "even rows" of the pyramid are missed out. So, a simple 3-block-high pyramid has $1 + 9 + 25 = 35$ blocks.
Hence the sum for a pyramid of height $n$ is given by $$\sum_{k=1}^n(2k - 1)^2$$
What's the corresponding shortcut formula for this series, involving $n^3$ ? | So we look for $$ P_n := \sum_{k=1}^n (2k-1)^2 $$ for an $n$-layer pyramid. We have $(2k-1)^2 = 4k^2 - 4k + 1$, hence \begin{align*} P_n &= 4\sum_{k=1}^n k^2 - 4\sum_{k=1}^n k + n \\\ &= 4\cdot \frac 16\cdot n(n+1)(2n+1) - 4 \cdot \frac 12 n \cdot (n+1) + n\\\ &= \frac 23 \cdot (2n^3 + 3n^2 + n) - 2n² -2n + n\\\ &= \frac 43 n^3 + \frac 23 n - n\\\ &= \frac 13 n (4n^2-1) \end{align*} | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "sequences and series"
} |
When to translate "ein" to describe people
I know that in German the words "ein" or "eine" are often dropped when referring to a person's occupation or role. Is this always the case from a grammatical point of view? Or is it a matter of style?
> Er ist Lehrer.
>
> Er ist ein Lehrer. (?)
I want to translate the following sentence, for example:
> _Samuel de Champlain was a talented map-maker, or cartographer._
Would it be correct to use the indefinite article here?
> Samuel de Champlain war ein begabter Kartenzeichner, oder Kartograf.
Would it also be correct without the article? (It sounds wrong to me).
> Samuel de Champlain war begabter Kartenzeichner, oder Kartograf.
Thank you very much. | You can (and should) drop the article when you convey that someone is part of something. For instance, if you're saying that someone 'is teacher', you say that they belong to the group of teachers.
That rule does not only apply to profession, but also to nationality, origin, etc.
> Er ist Lehrer.
You also drop the article in [verb + als]:
> Er arbeitet als Lehrer.
In all other cases–in respect to your very example, that is professions–you must not drop the article. Thus, you're last sentence is wrong.
> Er ist ein begabter Lehrer.
You can read more on this on canoo.net. | stackexchange-german | {
"answer_score": 6,
"question_score": 8,
"tags": "grammar, article"
} |
Why my active objects are not sliding down when the passive rotates?
I'm making a rigid body scene for the first time. When I rotate the passive plate myself when the timeline is playing, it works and they slide down. But when I give a rotation keyframe to the passive plate and then play the timeline, nothing happens.

I'm currently doing some graduate work and came upon some problems. The content of the course is of a pure form with topics such as
1. Existence and Uniqueness of solutions
2. linear system of 1st order ODE
3. asympotitic behaviour of soltuions and stability analysis
4. boundary value problems for 2nd order ode
There are a lot of theorems and proofs in the course and I am unable to find a suitable book/books for this type of content. Some of the theorems are as follows
Theorems
Can anyone point me in the right direction as to what books would be best suitable for content such as this? Solving differential equations is irrelevant here and more emphasis is put on theory and understanding. | This book by Walter covers the theoretical aspects of ordinary differential equations quite well and was used for my graduate course.
Also the book by Coddington is often suggested as a good source for rigorous existence and uniqueness theorems.
I personally find the book by Hale to be rigorous yet not too hard to read. | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "integration, ordinary differential equations, reference request, partial derivative"
} |
Is it possible to get the final name of a dependency via Mavens properties?
It's possible to get the final name of the current project.
${project.build.finalName}
Is this also possible for dependencies? I'm searching for something like this:
${project.build.dependencies.0.finalName}
Based on this example pom dependency cutout.
<dependency>
<groupId>org.stackoverflow</groupId>
<artifactId>stackoverflow-question</artifactId>
<version>1.6.0-SNAPSHOT</version>
</dependency>
The final name will likely be stackoverflow-question-1.6.0-SNAPSHOT, but as this may be variable due to locked snapshots or releases, I wan't to read it dynamically. Can you help me with that? Thank you very much. | Thank you all, I found it by myself hidden in this stackoverflow question.
<property name="log4j" value="${maven.dependency.log4j.log4j.jar.path}"/>
<echo message="${log4j}"/> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "maven 2, maven 3"
} |
A way to evaluate $\sum_{n=0}^\infty(-1)^{n+1}n$
The binomial expansion of $(a+b)^{-2}$ is given as
$$(a+b)^{-2}=\sum_{n=1}^\infty(-1)^{n+1}na^{-1-n}b^{n-1}\tag{I think}$$
And when $a=b=1$,
$$2^{-2}=\sum_{n=1}^\infty(-1)^{n+1}n=1-2+3-4+\dots$$
So I was wondering if this were a way to evaluate the divergent summation in a ramanujan sort of meaning. | Yes this is Abel Summation (Regularization) because it comes from defining:
$$f(z)=\sum_{n=0}^\infty a_nz^n$$ and evaluating:
$$A:=\lim_{z\rightarrow 1^{-}}\sum_{n=0}^\infty a_nz^{n}.$$
In your case:
$$f(z)=\frac{1}{(1+z)^2}=\sum_{n=1}^\infty ((-1)^nn)z^n.$$
You can find other ways to regularize your sum here. | stackexchange-math | {
"answer_score": 1,
"question_score": -1,
"tags": "sequences and series, divergent series"
} |
Locate stack/heap variables in memory
I am currently trying to hot patch programs (update code and data in the program memory, according to a released patch).
Assume that we can stop a running program, and do the patch. If the patch changes some data initialization or assignment values, how could we know where the variables are, like those in stack or heap?
* * *
Example:
Before patch:
void func() {
int a = 1;
}
After patch:
void func() {
int a = 2;
}
* * *
When patching, how could we know the location of `a` in the stack (or maybe not in the stack)? | Unless you have a lot of knowledge of how the compiler works, you _cannot_ know a priori where these variables are stored, or even how they are represented. Each compiler designer makes his own rules for how/where variables are stored.
You might be able to figure out for a specific compiled program, by inspecting the generated code. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "memory, stack, reverse engineering, computer forensics, volatility"
} |
How do you limit list objects template side, rather than view side
One of the ways to limit objects is to add a limitation to a function like this
def ten_objects():
obj = Model.objects.all()[0:10] # limit to 10
return {'objects': obj}
However how do you achieve this inside a template rather than inside a view?
I know you can filter through objects within a template and limit characters but how do you actually limit the amount of objects displayed in a loop. Via the template. for example the following code will loop through all objects....
<ul>
{% for new in news %}
<li>
<p>{{ news.title }}</p>
<p>{{ news.body }}</p>
</li>
{% endfor %}
</ul>
How do I break the loop, say after the firs 3 objects/items? And how do I do it inside the template? | There is a `slice` filter that you can use in templates. This works exactly the same as slicing within the view.
{% for new in news|slice:":10" %} | stackexchange-stackoverflow | {
"answer_score": 187,
"question_score": 84,
"tags": "django, django templates"
} |
Why can't Ms Access find referenced form?
I'm building a database in which I keep records of employees I work with. When someone is logged into the database and opens the form containing an employee's information, the shouldn't be able to change that information. So when the form opens, all the fields should be visible, but disabled. The code I use is:
DoCmd.OpenForm "frm_Pers_Toev", , , "[PersID]=" & [lstPers], acFormEdit, acDialog
Forms!frm_Pers_Toev!Naam.Enabled = False
When I run this code, the form opens properly, but the field isn't disabled. Instead, I get the runtime error 2450 "Microsoft Access cannot find the referenced form "frm_Pers_Toev".
I use the same sort of method for different forms and then it works fine.
What can I do? | Open the form not in Dialog mode
DoCmd.OpenForm "frm_Pers_Toev", , , "[PersID]=" & [lstPers], acFormEdit
Otherwise the code stops execution until the form closed | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "forms, ms access, runtime error"
} |
Set access-modifier to a C++ #define CONSTANT_NAME constant_value
I've a library (`MyLib.h` and `MyLib.cpp`) which offers routines to some classes (i.e. `ClassX`, `ClassY`, etc.). In `MyLib.h` I have defined two constants by using the `#define` preprocessor directive:
#define LOCAL_STR "this string can not be shared among classes that don't #include "MyLib.h""
#define TOSHARE_STR "this string can be shared among classes that #include "MyLib.h""
Both strings values suggest where I would like to use each string. In my mind, the 1st one must be used only in `MyLib.cpp` code, while the 2nd one inside `ClassX`, `ClassY`, etc. code.
Does C++ provide a way to define the desired visibility for these two constants? Currently they are visible everywhere... | The simple way of making sure that your LOCAL_STR #define is only used in MyLib.cpp is to put it there, rather than in MyLib.h | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c++, access modifiers"
} |
Listing the XPath to an XML node from the command line
Given this snippet of a large deeply nested XML document (bookstore.xml), I want to know the full path to the `amazon` node. How can I print that path from the command line?
<bookstore>
<book>
<title lang="eng">Learning XML</title>
<price>
<retail>39.95</retail>
<discounts>
<amazon>29.99</amazon>
</discounts>
<currency>USD</currency>
</price>
</book>
...
</bookstore>
Ideally it would look like this:
old-gregg$ magic bookstore.xml amazon
/bookstore/book/price/discounts/amazon | I found XMLStarlet and it does exactly what I'm looking for here. To install it using Homebrew:
$ brew update
$ brew install xmlstarlet
$ xml el bookstore.xml | grep amazon
/bookstore/book/price/discounts/amazon | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 2,
"tags": "xml, macos, bash, xpath"
} |
Hide or add new line to variable
Let's say I have this variable in my C# Code
string longVariableStuff = "hsduifgnw8e7rty83rfgediguidogy7834rghf7834ghf170934hf7034hgf734gf8170g437fg73408g1f784g1387fg4731gf7g13fg18347gf78134gf7834gf780134gfuhsdjkfhsdjkafhldsj";
Every time I'm coding, it gets a bit annoying when I scroll back it with the keyboard and my screen jumps to the right.
Is there anyway to just minimize it? Or maybe add a new line in the middle so I can view the whole thing without scrolling right? | Sure, you can just break it up:
string longVariableStuff =
"hsduifgnw8e7rty83rfgediguidogy7834rghf7834ghf170934hf7034hgf7" +
"34gf8170g437fg73408g1f784g1387fg4731gf7g13fg18347gf78134gf783" +
"4gf780134gfuhsdjkfhsdjkafhldsj";
This incurs absolutely no performance penalty, because the strings will be concatenated back into one string at compile time. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c#, visual studio, variables"
} |
Orbit-based metric
Let $(X,d)$ be a metric space and $f:X\rightarrow X$ be continuous. Then, is there any meaning/research done on the metric $$ D(x,y)\triangleq \sum_{n \in \mathbb{N}} \frac1{2^n} d(f^n(x),f^n(y)); $$ where $f^0(x)=x$? | In the linear case (for a bounded operator $T$ on a Banach space), the analogous construction for equivalent norms, possibly with a different ratio in place of $1/2$, is often named _adapted norm_ (see e.g. _Global stability of dynamical systems_ , by Michael Shub). Its main feature is that gives $T$ an operator norm arbitrarily close to its spectral radius. For metric spaces, note that $f$ is $2$-Lipschitz wrto $D$, and that the constant $2$ may be replaced to any $\theta>1$. At least, this shows that for a continuous self-map on a metric space, or on a complete metric space, being Lipschitz is not that special, if the constant is larger that $1$. | stackexchange-mathoverflow_net_7z | {
"answer_score": 2,
"question_score": 2,
"tags": "fa.functional analysis, mg.metric geometry, ds.dynamical systems, discrete dynamical systems"
} |
Chebyshev inequality for standard deviation
everyone! I have a question when I studied matrices of norm and distance. Chebyshev inequality for standard deviation.
If $k$ is the number of entries of $x$ that satisfy $$ |x_i - \operatorname{avg}(x)| \ge a, $$ then $$ k/n \le (\operatorname{std}(x)/a)^2. $$ This inequality is only interesting for $$ a \gt \operatorname{std}(x) $$
Could you tell me how can we get this inequality. Thanks for your help. | That is the non-probabilistic (statistical) version of the Chebyshev inequality.
Let $S$ be the "tail set": $i\in S \iff |x_i - \overline{x}|\ge a$, and let $|S|=k$. Then $$\sum_{i=1}^n(x_i - \overline{x})^2= \sum_{i\in S} (x_i - \overline{x})^2+\sum_{i\notin S} (x_i - \overline{x})^2=\\\ \ge \sum_{i\notin S} (x_i - \overline{x})^2 \ge k \,a^2 $$
Then, defining the sample variance $s_n^2=\sum_{i=1}^n(x_i - \overline{x})^2/ n $ we get:
$$ \frac{k}{n} \le \frac{s_n^2}{a^2}$$
The analogous probabilistic inequality is
$$ Pr(|x-u|\ge a) \le \frac{\sigma^2}{a^2}$$ | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "linear algebra, standard deviation"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.