INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to make multiple subplots with dictionary variable?
I have a dictionary with 17 keys, all with equal number of records. I want to make 17 subplots with each subplot showing each key's graph. When I use my code, I get all 17 lines(line chart) in all subplots.
My Code:
for j in range(1,18):
plt.subplot(4,5,j)
for index, (key, value) in enumerate(degree_gender_ratios.items()):
plt.plot(value)
:
from matplotlib import pyplot as plt
import numpy as np
f, ax = plt.subplots(4,5)
Now, just operate over each of your entries in the dict. No need for enumerations:
for a, (key, value) in zip(ax.flatten(), degree_gender_ratios.items()):
a.plot(value)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, python 3.x, python 2.7, jupyter notebook"
}
|
use function variable outside of the function WiTHOUT calling the function
I have a need for this. Is it possible?
I tried the following but it doesn't work:
$test;
function func_name() {
global $test;
$test = 'string';
}
echo $test; // I get nothing
|
If you don't call the function, nothing will happen.
You need to add `func_name();` before `echo $test;`
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": -4,
"tags": "php, string, function, global"
}
|
What API to use for uploading images to a Rails based website from an iPhone application?
Looking at using either ObjectiveResource or ASIHTTPRequest ...
1. Which is superior for uploading images? Or is there a better option???
2. Are there any examples of using either or both to upload images (or any other binary content)?
Thanks
|
I haven't used ObjectiveResource. ASIHTTPRequest is fairly easy to use. You'll probably need multipart/form-data request, so there is a ASIFormDataRequest subclass for that. I had some problems with ASIFormDataRequest and Rails though. From what I remember, images in request were accompanied by "charset=some-encoding" parameter (and it was hardcoded), so Rails wouldn't accept it as a valid image when charset=utf8 was there. Another problem was, you couldn't have arrays (like array_item[]) in your POST requests. You simply couldn't add more than one parameter with the same name. But both problems are pretty easy to patch if you really want to use ASI framework. Take a look at < and at the comments in ASIFormDataRequest.h
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "iphone, file upload, asihttprequest, objectiveresource"
}
|
How to install full ubuntu on a USB drive
Okay. I have booted from the same USB drive with the `toram` option. I have unmounted the partition on the USB drive through the terminal, basically following this answer:
Can Ubuntu be installed to the pendrive it was booted from?
I am now in the installation stage, but I can't figure out the partitions I have to choose in order to install it on only the USB drive, as I'm running windows 10 as my main operating system on my laptop. Please help
 partition that uses the rest of the space. The swap space is nice to have but not really essential.
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "partitioning, system installation"
}
|
How to check if circles intersect each other?
I'm trying to do trilateration where I know the coordinates of three known points and the estimates of the radii - not guaranteed to be really precise. My question is, how can I check if the circles actually intersect each other? Does the checking step mentioned in this tutorial make sense, considering the estimate values?
|
If by the checking step you mean the first three lines in the tutorial, it does make sense. It sounds like your center points are known well, even if the distances are not. For two circles, each with a range of radii, you can do two checks-one with the minimum radii and one with the maximum. For the most part, you will then know if they intersect none, some, or all of the time the radii are in that range. There are pathological cases where the intersection will disappear in the middle. One example would be center $(0,0)$, distance $(\frac{5}{8},\frac{7}{8})$ and center $(1,0)$ distance $(\frac{1}{2},\frac{7}{4})$. If the error in you distance estimates is small, this is unlikely.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "circles"
}
|
Rotate image around the bottom?
Say I have a clock and I would like to rotate the hour hand view to some hour, assuming its a `UIImageView`, where its bottom is exactly at the center of the screen,so rotate where the bottom is the anchor point, I do :
hour.layer.anchorPoint = CGPointMake(0.5,1.0);
let angle:CGFloat = (5.0 / 12.0) * (3.14 * 2.0);
hour.transform = CGAffineTransformMakeRotation(angle);
But what happens is that it moves from his original position, and change the angle to something else.
I can't understand how you set the anchor point ? In relation to.. ?
|
Turns out, you first have to set anchor , only then to set the frame of the view, if you first set a frame and then change the anchor, you get a wrong anchor.
So the code is :
hour.layer.anchorPoint = CGPointMake(0.5,1.0);
hour.frame=CGRectMake(self.frame.size.width/2.0-hourW/2.0, self.frame.size.height/2.0-hourH, hourW,hourH)
self.addSubview(hour)
hour.layer.anchorPoint = CGPointMake(0.5,1.0);
let angle:CGFloat = (5.0 / 12.0) * (3.14 * 2.0);
hour.transform = CGAffineTransformMakeRotation(angle);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "swift, cocoa touch, uikit, core animation"
}
|
Why no line numbers in gVim help file?
I've `:set number` in _vimrc, but when I open vim help using `:h <command>`, I don't see line numbers. I'll have to explicitly execute `:set number` to get line numbers.
|
Because Vim has some specific logic when opening help files and resets certain options. Among them, there is the 'number' option.
You might be able to fix this using an BufWinEnter autocommand:
au BufWinEnter * if &bt is# 'help' | set nu | endif
(untested)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "vim"
}
|
Inject service or class in guard in NestJS
Needs to DI Kafka client in guard:
auth.guard.ts
export class AuthGuard implements CanActivate {
private _client: ClientKafka; <----- // TODO implement nestjs DI mechanism
public async canActivate(context: ExecutionContext): Promise<boolean> {
try {
const request = context.switchToHttp().getRequest();
const authorization: string = request.get('Authorization');
...code here just send data to jwt service...
return true;
} catch (err) {
return false;
}
}
}
I use _new_ in canActivate for creating an instance of Kafka client in auth.guard.ts. But how to inject a class in guard with @Inject? I used to create @Global module, which provides and export Kafka client class, but it's not working...
|
Use This in the module for globally using the guard
providers: [{provide: APP_GUARD, useClass: AuthGuard}]
As for your question about injecting a class inside a guard, you need to inject it inside the constructor of the AuthGuard class
export class AuthGuard implements CanActivate {
constructor(private clientKafka : ClientKafka){}
}
if this doesn't work, try using
constructor(@Inject(private clientKafka : ClientKafka)){}
Hope this resolves your issue :)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "apache kafka, dependency injection, nestjs, guard"
}
|
How do I write a custom generator function with python
I have this
for A in [0, -0.25, 0.25, -0.5, 0.5, -0.75, 0.75, -1.0, 1.0, -1.25, 1.25, -1.5, 1.5, -1.75, 1.75, -2.0, 2.0, -2.25, 2.25, -2.5, 2.5, -2.75, 2.75, -3.0, 3.0, -3.25, 3.25, -3.5, 3.5, -3.75, 3.75, -4.0, 4.0, -4.25, 4.25, -4.5, 4.5, -4.75, 4.75, -5.0, 5.0]:
Is it possible to make it with generator function? I have now this:
def frange(start, stop, step=1.0):
while start <= stop:
yield start
start += step
and use like this:
for error in self.frange(-2.5, 2.5, 0.25):
but its returns `[-2.5, 2.25, ... , 0 , 2.25, 2.5]` and for my program it's very hard to calculate. because I finding the value the near to zero, but I don't know how much combinations it could be.
I need go from zero and next value must be in minus and plus value. like `[0, -0.25, 0.25...]`.
|
Maybe you meant a generator instead of a lambda:
def opposing_numbers(increment, maximum):
yield 0
value = increment
while value <= maximum:
yield -value
yield value
value += increment
Then call it as:
opposing_numbers(0.25, 5)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "python, generator"
}
|
Passing optional array from PHP to jQuery
I have a problem if this optional array is empty:
<script>
var parsedArray = JSON.parse('<?php echo json_encode($myArray); ?>');
console.log(parsedArray );
</script>
All is fine if array is NOT empty, but the problem comes if there are no values in array;
> Uncaught SyntaxError: Unexpected token A in JSON at position 0
Console.log just spits `Array` out if array is empty.
I want to learn how is this done properly. How to pass an empty array to jQuery so I can run `myArray.length` function on it for example and so that it returns 0 if it is empty.
|
I think it is not necessary to do the if statement i figured it out and my problem was that I did the json_encode($myArray) in PHP code and then JSON.parse in javascript
it works like this without problems:
in PHP just declare the array
$myArray = [];
and in php file under script spit it out like this:
var myArray = <?= json_encode($myArray) ?>;
And now even if array is empty it will spit out `[]`;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript, php, jquery"
}
|
bootstrap menu is hiding main text
I'm going crazy with this. I got the twitter-bootstrap menu running in my c# code and it looks and works great. However, the menu is overwriting my text of the site I've built. It seems no matter what I do the body of the site appears under the menu.... I'm thinking it's a CSS issue because if I resize the page to mobile size the body is then placed under the menu.
I'm not even sure what code I should cut and paste...?
I've tried various or row, ... etc...
How do I get my body text to show below the menu vs. underneath it?
Thanks
|
I had this problem too, I had to do a padding in my `_layout.cshtml`. This solved it for me.
<body style="padding-top: 40px;">
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, asp.net mvc 4, twitter bootstrap"
}
|
Create a mutation which takes multiple values of an ENUM
I've created a model that has a field which takes multiple values of an `ENUM`. How can I write a mutation which will allow me to add multiple values at once?
For example, I have a sign up mutation:
export const signUp = gql`
mutation signUp(
$email: String!,
$name: String!,
$password: String!,
$attended: [USER_ATTENDED!]!,
$role: [USER_ROLE!]!,
) {
createUser(
authProvider: {
email: {
email: $email,
password: $password,
},
},
name: $name,
attended: $attended,
role: $role,
) {
id,
createdAt,
name,
email,
}
}
`;
I would expect `$attended` and `$role` to accept multiple values.
|
You can pass multiple values by using brackets: `[]`. In your case, the variables in GraphiQL need to like like this:
{
"email": "[email protected]",
"name": "Name",
"password": "secret",
"attended": ["A", "B"],
"role": ["ROLE_A", "ROLE_B"]
}
In Apollo, this should work:
const variables = {
email: "[email protected]",
name": "Name",
password: "secret",
attended: ["A", "B"],
role: ["ROLE_A", "ROLE_B"]
}
More information about GraphQL variables is available here and here.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "graphql, apollo client, graphcool"
}
|
Is there a way to check which template file is being loaded, if it is not a page template file?
I don't see any way of testing which template file is being loaded, if the template file is not a page template. Otherwise I would use is_page_template().
For instance, I am using a home.php template file to pull in the content from multiple pages(don't ask), how would I check that home.php is the template file being used when viewing the sites root url?
|
Just type in some text like "Debug" into the non-Php area of home.php (the part not surrouded by ) and see if it appears. If so, you know that home.php is being used.
|
stackexchange-wordpress
|
{
"answer_score": 2,
"question_score": 1,
"tags": "templates, conditional tags"
}
|
Who is this engineer?
So whilst ~~SE is going completely mental~~ an error occurred I came across this non-feline engineer working on the SE server.
:
def methodA(self):
# do stuff
def methodB(self):
# do more stuff
def __enter__(self):
# somehow enter object namespace / transfer methods into global namespace
def __exit__(self, *args):
# exit object namespace / get rid of globalized methods
foo = Bar()
with foo:
methodA() # all works fine
methodB()
methodA() # throws an error
This is just a thought, that might not work at all. Or maybe there's a solution without the with statement.
|
This answers the original question but I suggest **don't use it**.
* * *
Similar to the suggested way of wKavey.
But I'm not sure why I would want to do that. I would need to make sure that there is no variable `methodA` in the global namespace.
class Bar():
def __init__(self, value=5):
self.value = value
def methodA(self):
return self.value
def methodB(self):
return -self.value
def __enter__(self):
global methodA
global methodB
methodA = self.methodA
methodB = self.methodB
def __exit__(self, *args):
global methodA
del methodA
global methodB
del methodB
pass
foo = Bar()
with foo:
print(methodA()) # all works fine
print(methodB())
methodA() # throws an error
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "python, python 3.x, with statement"
}
|
UML MVC pattern List class use
When designing a class diagram for a theoretical MVC-Pattern-based system, is it best to use List classes?
For example:
**With List class:**
!diag 1
**Without list class:**
!diag 2
I personally feel the latter is a better approach due to less code duplication, is there a better approach to this?
|
I don't think there is a need for a list class. Your controller can hold all references to the model.
Regardless of that, your UML models have a problem: in both cases you have an attribute `customers:Customer[]` and an composition link. This means that you have TWO references from the controller (or list) to the model. Either remove the attribute or the link.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "model view controller, uml, class diagram"
}
|
Sharing comon library in JavaScript front end apps
I'm setting up the framework for building a suite of apps in reactjs. They will all communicate with a suite of APIs for the backend. I wanted to build a common JavaScript library "project" where I can put code that could be used by all apps. For instance:
lib
|--api (JS service classes to communicate with API backend)
|--ui
|--components (common shared react components)
..etc..
I would like to be able to start a new app and include parts of the lib - /lib/api/ for example.
I'll be doing a similar setup with the backend code, which is not JavaScript.
What is the best way to structure this so the lib can easily be included in other projects? We're using git for source control but don't know it well. Should these be git submodules? Or should I look at some kind of private npm repository?
|
You can:
* Public them to npm (private or not)
* Just add dependencies from git via `npm add`, as usual
In general, many companies tend to use packages scoped with a `@companyname/` namespace. That's what I'd recommend. Whether it's public or private is up to you.
In my opinion git submodules is not what you're looking for. It's more cumbersome to manage than normal npm/yarn dependencies.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, git, npm, architecture"
}
|
Best open source crash reporting tool for Android Application
I want to use crash reporting tool for my application but i don't have budget. Can any one have idea of any open source crash reporting tool except crashlytics.
|
The best one is Splunk Api.Download the **splunk-mint.jar** and place it in your `libs` folder.The just added the following code before `setContentView()` within `onCreate()`:
Mint.initAndStartSession(MainActivity.this, "Your api key");
You will able to see the entire log-cat/crash report in the splunk website.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "android, crash reports"
}
|
How to justify whole text in Rmd with bookdown::gitbook as output
I would like to justify all the text in my gitbook, but I couldn't find a solution. So far I've tried:
* Set the text-align as justified in the style/body, right after the YAML Header:
`<style> body { text-align: justify } </style>`
It doesn't work.
* Set the text-align as justified in div tag for the whole text:
`<div style="text-align:justify;"> my whole text </div>`
It works, but the numbering of the topics are lost (probably with other features I didn't figure out).
The thing is, I don't want to lose any standard feature of the output from bookdown::gitbook but the "text-align" (which I want it to be justified).
Also, it would be too much work to have to put a div tag in all the sentences. Any help?
Thanks in advance!
|
Put your CSS code in a css file, say, `custom.css`:
body {
text-align: justify;
}
Then include it via the `css` option (I don't know what you meant by "preamble" in your post; if it meant the LaTeX preamble, it would be the wrong place to put CSS):
bookdown::gitbook:
css: "custom.css"
If it doesn't work (I have tested it and it works for me), please provide a reproducible example, and ideally also a published (web) version of your example, so we can easily investigate your CSS.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 7,
"tags": "html, css, r markdown, bookdown, gitbook"
}
|
Aumentar TextView cada cierta cantidad de segundos
Pues eso mismo, quiero saber si se pueden aumentar la cantidad de `TextView` cada 5 (cinco) segundos por ejemplo.
**Código:**
historia = (TextView)findViewById(R.id.cuerpoProgramado);
**Timer de cinco segundos:**
private final static int TIEMPO = 5000;
public void timer(){
handler.postDelayed(new Runnable() {
@Override
public void run() {
handler.postDelayed(this, TIEMPO);
}
}, TIEMPO);
}
Ahora, lo que quiero saber es si se pueden incremetar los `TextView` cada cinco segundos y que cada uno venga con un texto diferente pero sin que se borre el primero. A modo "ilustrativo"":
textview.setText("hola")
timer()
textview.setText("¿Cómo estas?")
**Resultado:**
hola
¿Cómo estas?
|
Puedes definir los mensajes a mostrar en un array:
String[] mensajes = {"Hola", "Como estas?", "Franqo", "es un gran día!"};
int counter;
y mediante un `handler` llamar cada elemento en el array para mostrarlo en tu `TextView`:
final Handler myHandler = new Handler();
myHandler.postDelayed(new Runnable() {
@Override
public void run() {
if(counter < mensajes.length) {
textview.setText(textview.getText().toString() + "\n" + mensajes[counter]);
myHandler.postDelayed(this, 5000); //5 segundos
counter++;
}
}
}, 1000);
|
stackexchange-es_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, android studio, textview, timer"
}
|
Regex (Java) to remove all characters up to but not including (a number or a letter a-f followed by a number)
I need help constructing the regular expression to _remove all characters up to but not including (a number or a letter a-f followed by a number)_ in Java:
Here's what I came up with (doesn't work): `string.replaceFirst(".+?(\\d|[a-f]\\d)","");`
That line of code replaces the entire string with an empty string. `.+?` is every character up to `\\d` a digit OR `[a-f]\\d` any of the letters a-f followed by a digit.
This doesn't work, however, can I have some help?
Thanks
EDIT: changed `replace` with `replaceFirst`
|
s = s.replaceFirst(".*?(?=[a-f]?\\d)", "");
Using `.*?` instead of `.+?` insures that the first character gets checked by the lookahead, solving the problem @johusman mentioned. And while your `(\\d|[a-f]\\d)` isn't causing a problem, `[a-f]?\\d` is both more efficient and more readable.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, regex"
}
|
Custom value for list_display item on Django admin
In a model I have a subtitle field, which is populated with `None` if no value exists for the field for the given object.
Is there any way to display the value to something custom (like `Not Available` or `Not Applicable` than just displaying `(None)`
field
sub_title = models.CharField(max_length=255, null=True, blank=True)
admin
list_display = 'sub_title',
:
list_display = ('get_sub_title',)
def get_sub_title(self, obj):
if obj.sub_title:
return obj.sub_title
else:
return 'Not Available'
get_sub_title.short_description = 'Subtitle'
The docs provide several other options for providing a callable.
|
stackexchange-stackoverflow
|
{
"answer_score": 41,
"question_score": 24,
"tags": "python, django, django admin"
}
|
set likes based on 2 parameters
I'm working on a project which should be able to put likes on it... one from each user that log into the page. I'm using ruby, active record and sinatra.
post '/like/:isbn' do
if favourite = Favourite.find_by(book_id: params[:book_id])
redirect to "/info/#{ params[:isbn] }"
else
favourite = Favourite.new
favourite.book_id = params[:book_id]
favourite.user_id = current_user.id
favourite.save
redirect to "/info/#{ params[:isbn] }"
end
end what I'm trying to do is searching for this favourite `where my book_id = book_id && user_id = user_id`... but I can't think of a way of putting it into ruby code....
|
why don't you try this
Favourite.where(:my_book_id=> book_id , :user_id=> user_id)
this will return the array of favourite which has both `:my_boo_id = book_id` and `:user_id = user_id`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ruby, sinatra activerecord"
}
|
Смена GET-параметра при нажатии на ссылку
Нужно, чтобы при нажатии на ссылку передавался `GET`-параметр, например `?id=1`. При повторном нажатии на ссылку этот `GET`-параметр менялся, например на 2. Тоесть, нажал на ссылку - ?`id=1`, еще раз нажал - `?id=2`, опять нажал `?id=1` и так далее.
|
if ( isset($_GET['id']) && $_GET['id]==1)
echo "<a href='/?id=2'>ссылка</a>";
else
echo "<a href='/?id=1'>ссылка</a>";
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "php, get"
}
|
Access an index of an array with dynamically generated name
I have some Java code which contains some arrays. Say one of them is `b`. I have a string `a` whose value points to the names of those arrays at different times. So if `a` currently contains `b`, I want to access the 3rd element of `b` through `a`. Something which I could have done in Javascript with `window[a][2]`. is it possible in Java?
|
Use **collections**. Looks like you're looking for `HashMap`
Something like that:
Map<String, List<String>> map = new HashMap<String, List<String>>();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java, javascript, arrays"
}
|
How do I evaluate a complex limit involving the conjugate?
I know that
$$ \lim_{z \to 0} \frac{\bar{z}}{z} $$
Does not exists because if we consider a $z_0$ as a real number ($z = x$), the limit is 1, and if $z_0$ is a pure imaginary number ($z = iy$), the limit is -1. With that, I can prove that the limit does not exists.
But if I have:
$$ \lim _{z\to 0}\left(\left(\frac{z}{\bar{z}}\right)^2\right) $$
And do the same tests, I always get the limit equals to one. Is it correct to say that this limit equals 1 because of the two ways of approaching it gives the same result?
|
If $t>0$ and $z=(1+i)t$, then$$\frac z{\overline z}=\frac{1+i}{1-i}=i,$$and therefore$$\left(\frac z{\overline z}\right)^2=-1.$$So, again, the limit does not exist.
|
stackexchange-math
|
{
"answer_score": -2,
"question_score": 0,
"tags": "limits, complex numbers"
}
|
Unix Bash rename files using a regex
I would like to rename all files from a folder using a regex(add a name to the end of name) and move to another folder.
It my opinion, it should be looking like this:
`mv -v ./images/*.png ./test/*test.png`, but it is not working.
Can anyone suggest me a solution?
|
I also like the rename command that John T posted, but it's not available on all systems. This should work everywhere:
for i in *.png; do mv -v $i `basename $i .png`.test.png; done
|
stackexchange-superuser
|
{
"answer_score": 6,
"question_score": 4,
"tags": "bash, rename, mv"
}
|
Must a question have a question?
Simple enough? Since everything here is about straight precise questions and straight precise answers, should there be a question in every question?
This question, where the users asks in 2 steps, brought me here.
* This does not work.
* This is my code.
Yes we can understand what is happening but there is no question _per se_. So yeah.. Must a question have a question?
|
If the post contains no question, we are required to guess. Sometimes the intended question is obvious. Sometimes it just _seems_ to be obvious, and we waste a lot of cycles answering something that the OP isn't asking.
Everyone benefits if the OP is clear about what is really needed, and direct questions are the way to provide that clarity. For that reason, I almost always ask the OP to provide a specific question.
This is a typical request:
> Will you clarify your goal? What do you expect to happen, what is currently happening, and what problems have you encountered that prevent you from accomplishing it?
This can be trimmed as needed if the OP provided partial information.
|
stackexchange-meta
|
{
"answer_score": 5,
"question_score": -3,
"tags": "discussion, questions"
}
|
Can a basis for a vector space $V$ can be restricted to a basis for any subspace $W$?
I don't understand why this statement is wrong:
> $V$ is a vector space, and $W$ is a subspace of $V$. $K$ is a basis of $V$. We can manage to find a subset of $K$ that will be a basis of $W$.
Sorry if my English is bad... and if you can show me an example of something that contradicts it, it'd be great.
|
Take for example $V = \mathbb{R}^2$, $W = \\{(x,y)\in\mathbb{R}^2 : x = y\\}$, and $K = \\{(1,0),(0,1)\\}$.
$W$ is a subspace of $V$, but there is no subset of $K$ that gives a basis for $W$.
|
stackexchange-math
|
{
"answer_score": 18,
"question_score": 13,
"tags": "linear algebra, vector spaces"
}
|
which of the given for loop is faster?
Well,I went for interview today and there Interviewer asked me a question and it's like this.
let a = "Aditya";
1.for (let i=0; i<a.length; i++)
2.for(let i=a.length; i>0; i--)
3.for(let i=0, length=a.length; i<length; i++)
which of the above for loop runs faster 1 , 2 , 3? Arrange it, and give the reason as well. I was like well I used (1) most the so it could be the faster one but he told me I was wrong and I tried google couldn't find any helpful solution.Please help me out.
|
The best answer is probably:
Why do you even care? Choose the one that is the most readable. Unreadable code takes more time for people to understand, and the benefits of a few milliseconds faster do not matter. If such small performance things matter, you should be writing assembly.
> He told me 3rd one is the fastest and 2nd is equivalent to it and the 1st one is slowest.
Not really. Modern browsers do optimize all three loops so much that they actually run with the same speed.
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": -2,
"tags": "javascript, for loop, operator precedence"
}
|
problem with background image size
I have Ubuntu 12.04 installed and I just added a bunch of wallpapers. They look fine when opened using an image viewer, but when used as the actual desktop background they exceed the monitor size (i.e. parts of the image are cut off). I have an HP 15 with Ubuntu 12.04 64-bit and a 1366x768 screen with Intel HD 4000 graphics.
|
`Right Click` on the Desktop and select `Change Desktop Background`.
You can try the _`tile, zoom , center ,scale, fill, span`_ options to fit the image according to your preference as shown.
!enter image description here
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 0,
"tags": "12.04, resolution, wallpaper"
}
|
How much disk space needed for Bitcoin SV testnet node implementation?
I want to create Bitcoin SV node but not sure how much disk space it needed.
please someone answer me as soon as possible
|
I do not know the actoal SV-testnet blockchain size. But, if see to mainnet - because of this is relative fresh fork of Bitcoin, blockchain size is close to Bitcoin's one, i.e. 200G. Please, be careful:
* BitcoinSV runs as a daemon on a Linux only, and there is not exists a GUI wallet.
* It uses directory $HOME/.bitcoin to hold blockchain and wallet.dat. As result, if you use Bitcoin on same Linux server/account, then BitcoinSV will hurt your Bitcoins wallet.dat and blockchain. I recommend backup or rename your .bitcoin before run SV.
* Config command "zapwallettxes" does not work correctly. In my case, it clears balance from wallet.dat, I restored it from backup.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "blockchain, bitcoin, bitcoind, bitcoin testnet, block comments"
}
|
Eset Security Suite Firewall problem
I recently upgraded from Eset NOD32 antivirus 4 to Eset Smart Security RC 5 .However i further upgraded to the latest version that is 5.0.93.0 I am using Vypress Chat and similar applications for sharing files and communicating over LAN network of my university, but I noticed I can only use these softwares once the firewall is disabled. Kindly guide me how can I add an exception for these applications. There is also interface change in Eset version 5, before that in Eset Smart Security 4 i was easily able to solve such problems.
Help me out!
|
Here is the KB article for configuring the Smart Security 5.x firewall to allow or disallow specific application exceptions. It appears to be quite the involved process, too involved to easily copy over here.
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": -2,
"tags": "windows 7, windows, firewall, nod32"
}
|
Why is AlMg3 called aluminum alloy?
In AlMg3, magnesium atoms outnumber aluminum atoms by a factor of three. In terms of mass, the ratio of aluminium to magnesium is a mere $27.0 / (3\times24.3) = 0.37$.
_Shouldn't AlMg3 be better called magnesium alloy?_
|
**AlMg3 is not the chemical formula of the alloy** , it's the product name for a wrought alloy. Its technical sheet specifies the following composition:
> _**Product name**_
> AlMg3
>
> _**Class of product**_
> Al-Mg alloy for MIG/TIG welding.
>
> _**Corresponding standards**_
> DIN 1732, SG-AlMg3, AWS A5.10, ER 5754
>
> _**Nominal composition (weight %)**_
> Al: Bal. Si: 0.4 Mg: 3 Mn: 0.5
Thus, **the 3 in the product name refers to 3 % (in weight) of magnesium.**
|
stackexchange-chemistry
|
{
"answer_score": 14,
"question_score": 3,
"tags": "metal, metallurgy, alloy"
}
|
Why is tert-butoxide often used in elimination reactions when it is not necessary?
I understand that tert-butoxide is used to favor the Hofmann product in elimination reactions due to its steric bulk (and thus inability to abstract a proton in a more substituted position); however, I have often seen proposed organic synthesis involving the use of tert-butoxide when it is seemingly irrelevant. For example, 1-bromobutane will undergo an elimination reaction with or without a sterically hindered base (such as tert-butoxide); however, anytime I see reactions involving elimination reaction with primary substrates, such as the bromo group in 1-bromobutane, tert-butoxide is used rather than ethoxide. Is tert-butoxide simply used to disfavor the formation of substitution products. Is its steric bulk enough to not allow it to act as a good nucleophile in substitution reactions?
|
Several reasons:
1. t-BuOK is especially known as a **strong base,** and a **poor nucleophile.** Its large, bulky structure causes it to perform exceptionally poorly in substitution, literally eliminating any side reactions when the desired product is the elimination product.
2. It is easily available, like Raphaël insists.
3. It's basic strength depends on the medium. It is very strong in DMSO, where the solvent complexates well with $\ce{K+}$ ions. However it is relatively weaker in benzene. This flexibility gives it inevitable popularity.
4. Many condensation reactions (Stobe's, Darzen's) are seen to have greater yield when t-BuOK is used.
|
stackexchange-chemistry
|
{
"answer_score": 10,
"question_score": 10,
"tags": "organic chemistry, synthesis"
}
|
What type of serialization uses Wcf behind the scenes?
I know there's 3 type s of serialization in .net :
Soap , Xml , Binary.
Wcf instructed the DataContract attribute which also serialize ... but via **what** ?
Binary is not - i know.
**So by which mechanism** ?
|
It is the binding defined for the given endpoint which specifies the serialization mechanism. For example:
* `basicHttpBinding` and `wsHttpBinding` use SOAP
* `netTcpBinding` uses binary serialization
* `webHttpBinding` could use XML, Json, ...
You can read more about the different built-in bindings and their properties on this article. Thanks to the extensibility of WCF you could of course write your own custom bindings.
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 9,
"tags": "wcf"
}
|
Would Klingons (especially Worf) consider "deceiving" an enemy in battle to be dishonorable?
Sometimes in battles, Captain Picard or another senior staff member orders deception: vent plasma, for example, in order to make it appear as though significant damage has occurred to the ship. I believe such a ploy may have been ordered in "Gambit," but I'm not certain. Is such deception considered dishonorable amongst Klingons? Wouldn't they rather go out fighting?
|
**Deception is an acceptable strategy in warfare for honorable Klingons.**
The earliest example of this on _Star Trek: The Next Generation_ is in the first season episode "Heart of Glory" where we were presented with two Klingons rescued from a badly damaged freighter. During their debriefing:
> **KLINGON1** : Our only chance was to trick them [the attacking Ferengi] into lowering their shields.
>
> **KLINGON2** : We reduced power and lured them in.
>
> **KLINGON1** : They suspected nothing.
>
> **KLINGON2** : Then, when they lowered their shields to beam over a landing party, we opened fire.
In the second season episode "Peak Performance", Riker tried to recruit Worf to join his team in upcoming wargames.
> **RIKER** : You're outmanned, you're outgunned, you're out-equipped. What else have you got?
>
> **WORF** (considering for a long moment): Guile.
|
stackexchange-scifi
|
{
"answer_score": 74,
"question_score": 39,
"tags": "star trek, star trek tng"
}
|
How to close a popup and redirect to an iframe?
I have a page that contains an iframe, and the iframe opens a popup.
This popup after submitting a form should close and reload the iframe that opened it.
The popup is closed and redirect by this way:
window.opener.location.href = "
window.close ();
This has worked for me while I've been working directly from the iframe but when I do it from the page that contains the iframe the iframe does not refresh.
So... how can I reload the iframe in that case?
|
Well, there is no way to access the DOM of an iframe if it doesn't have the same origin as the containing page. So in that case, you won't be able to tell if the form is submitted. You would have to edit the JS of the iframe page and have the popup reload that page when you submit the form.
window.opener.location.reload()
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, redirect, iframe, popup, window.opener"
}
|
Solving a system of equations $x^2 +y^2 −z(x+y)=2,y^2 +z^2 −x(y+z)=4,z^2 +x^2 −y(z+x)=8$
I'm trying to solve the following system over $\Bbb R$:
> $\begin{cases}{x^2 +y^2 −z(x+y)=2\\\ y^2 +z^2 −x(y+z)=4\\\ z^2 +x^2 −y(z+x)=8}\end{cases}$
Adding all the equations gives $2(x^2+y^2+z^2-xz-yz-xy)=14$. This doesn't look like $(x+y+z)^2$… Do you have some hints?
|
$$2(x^2+y^2+z^2-xz-yz-xy)=((x-y)^2 +(y-z)^2+(z-x)^2)$$ Subtracting first two equation give $$(z-x)(x+y+z)=2$$ Similarly develop other relation. $$\left(\frac{4}{(x+y+z)^2}+\frac{16}{(x+y+z)^2}+\frac{36}{(x+y+z)^2}\right)=14$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "algebra precalculus, systems of equations, nonlinear system"
}
|
Idea of improvement
Wouldn't it be great if I asked a question, someone comments, below the question, then if any other comments answer the question, I could click a button and mark it as an answer and the whole comment could be the actual answer :) Which a tick or something like that just would save some time :)
|
I'd have to see numbers on how often this happens before I'd get behind it. Sure, I've seen it before, but it's a tiny fraction of questions that get answered in the comments. I don't know if we need a new feature to deal with a small fraction of cases, particularly when most of those can be rectified by asking the commenter to post an answer. (I've done this before. If you leave them a comment telling them you want to upvote their answer, people usually jump right on it.)
|
stackexchange-meta
|
{
"answer_score": 6,
"question_score": -7,
"tags": "feature request, comments, comment voting"
}
|
On 1-dimensional cellular automata
I'm interested in linear 2-state cellular automata (with local rules only) that could compute the majority function. Say the state of a cell is either 0 or 1. Is it possible to have a cellular automaton that sets all cells to 1 if the majority of initial states is 1 and sets all cells to 0 if the majority of initial states is 0? The cellular automaton could be synchronous or asynchronous. I tend to believe that the answer is negative (mainly because of rule locality). Any literature on this problem? I also believe that one could approximate it in the sense that one could devise a cellular automaton that fails only on a small fraction of its inputs (purely experimental at this point).
|
This is a well known problem. It's known to be impossible to solve exactly, but either approximable in the sense you describe or solvable exactly if you relax the conditions under which it recognizes a majority: see
|
stackexchange-cstheory
|
{
"answer_score": 14,
"question_score": 6,
"tags": "cellular automata"
}
|
What will be the best UI component to render array items horizontally
I have an array of 'n' number of items. I am displaying them in a horizontal stack view, having fixed width of the superview.
Issue is, when the number of items are more, then the horizontal stack view is not displaying all of them.
I need to display all the items of an array in some UI placeholder horizontally with some decent amount of spacing in between. If the items are more they should come in the next line.
Will horizontal stack view be suitable for my requirement ? If not, then which UI component should I use? Example will be appreciated.
|
`UICollectionView` is exactly what you're after. Use it with the standard `UICollectionViewFlowLayout` in horizontal mode.
It will then display all its elements filling "lines" from top to bottom, thus achieving a grid layout, which seems like what you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, uistackview"
}
|
how to access own Node.js server in https web site which deployed in nginx
i do deploy a website in nginx and translate it from http to https using `let's cerbot` before. it runs well. My question is, in my website, i need to access my own `Node.js Server` using `axios`. As before, i used `http`, it goes well expect security.But now, below the Https connect, the browser blocks my http connect.So i tried update my Node Server to support Https connect using `Self-signed SSL certificates`, but the browser blocks it as well. Who can tell me how can i fix this problem and make the site work well.Thank you!
|
You should setup nginx as reverse proxy for nodejs server
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "node.js, express, https"
}
|
When doing a scipy.signal.spectrogram, how can I tell how many time segments there will be?
I have:
frequencies, times, spectrogram = signal.spectrogram(
samples, sample_rate, nperseg=nperseg, window=signal.hann(nperseg), noverlap=noverlap, mode='magnitude')
I have `nperseg=320` and `noverlap=80`, with a `sample_rate=16000`.
I had `232800` samples.
However, my `spectrogram.shape` is now `(161, 969)`. So that's 161 frequency bins with 969 time segments. How was that 969 calculated?
|
time_per_segment_ms = 20
nperseg = int(sample_rate * 0.001 * time_per_segment_ms)
overlap = nperseg // 4
seconds_per_segment = (nperseg - overlap) / sample_rate
ms_per_segment = int(seconds_per_segment * 1000)
That about does it
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, scipy, fft, spectrogram"
}
|
Make a global when true in Laravel 5 Model
I come from cakePHP where it is possible to have every get or list query to include a standard where "something = something" in the Model. Per function in the controller this can be ignored, but for all others this is used.
Now I am wondering how to do this in Laravel 5. I would like to add something like below code in the Model or in the Controller (but preferably in the Model):
public function __construct(Page $page) {
$page->where('is_active', 1);
}
So that when running any query on the pages table it will only give me active pages. Except when I manually add `where('is_active', 0)` or something else to include all active and inactive pages.
Any help would be very appreciated
|
Most of what you want can be achieved by using a query scope on the model.
You'd put something like this in your model:
/**
* Scope a query to only include active users.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive($query)
{
return $query->where('active', 1);
}
And then when you wanted to use it you'd do something like this:
$users = App\User::active()->orderBy('created_at')->get();
It doesn't set a default for all queries, but it might be a better long term solution. Docs are here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, laravel 5"
}
|
Configure Logic App with Managed Identity
I am new to the Azure services and seek help with the Managed Identities. My task is to create a managed connection between my Logic App and my Log Analytics Workspace. I have created a system assigned identity and have the respective object ID. When I use the Azure Logs Monitor action in my logic app, it asks if I should connect by signing in or service principal. Image for Azure Log Analytics Action fields when service principal option is selected.
What should be the next step, should I add the Object ID of my logic app in the log analytics workspace, then what about the fields in the above image link.
|
Service Principal doesn't have any roles in the scenario above. The image asks for an **app's client ID, Tenant ID and secret**. All we need to do is **create an app in the app registration** , **create a secret in it** and get these three parameters from there. **Add this app as a contributor or desired role as per need in the workspace** (in my case which is Log Analytics workspace), **add the three parameters into the Logic App action** as seen in above image and we are good to go. The Logic app would run on the managed connection now.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "azure logic apps, azure log analytics, azure managed identity, azure service principal, azure managed app"
}
|
Why difference quotient of convex functions increases in both variables
Let $f: \mathbb R \rightarrow \mathbb R$ be a convex function and $$ g(x,y)=\frac{f(x)-f(y)}{x-y} \textrm{ for } x\neq y. $$ I wish to prove that $g$ is increasing function in both variables.
Thanks
|
Fix $y_2 > y_1 > x$ and define $$ \phi(y) = \frac{f(y) - f(x)}{y - x} $$ Then noticing that there is some $0 < t < 1$ such that $ y_1 = (1-t)x + ty_2$ by convexity we have that $$ \phi(y_1) = \frac{f(y_1) - f(x)}{y_1 - x} = \frac{f((1-t)x + ty_2) - f(x)}{(1-t)x + ty_2- x} \leq \frac{(1-t)f(x) + tf(y_2) - f(x)}{(1-t)x + ty_2 - x} = \frac{t(f(y_2)-f(x))}{t(y_2 - x)} = \phi(y_2)$$ You can get all the other cases in a similar fashion.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 2,
"tags": "analysis"
}
|
Eclipse error log view missing
I installed eclipse oxygen (4.7.0) "Eclipse IDE for Java Developers". After installation I mentioned that "error log" view is not available any more.
I restarted eclipse multiple times and used also other workspaces.
How can I get back the error log view?
|
I have found a solution: Just install Eclipse SDK by
> Help->Install New Software...

I have a complex query:
SELECT *
FROM `relations` L1
WHERE `minor_from` = 2 and `major_from` = 2 and `type` = "friend"
AND EXISTS
(
SELECT * FROM `relations` L2 WHERE
(L1.`minor_from` = L2.`minor_to` AND L1.`major_from` = L2.`major_to` and L1.`minor_from` = L2.`minor_to` AND L1.`major_from` = L2.`major_to`) AND
(L2.`minor_from` = L1.`minor_to` AND L2.`major_from` = L1.`major_to` and L2.`minor_from` = L1.`minor_to` AND L2.`major_from` = L1.`major_to`)
)
Which gives friends of user.
I am able to add whereRaw in Bookshelf.js but cannot add alias L1 `SELECT * FROM relations L1`
Any idea how to query that.
Edit:
It will be helpful if someone can tell me how to run complete raw query.
|
To mark it as answer:
I used knex.js to do that. I could have and probably will use knex methods but for testing I have this:
knex('relations as L1').where('L1.minor_from', '=',req.body.minor ).where('L1.major_from', '=',req.body.major).where('L1.type', '=', 'friend').whereExists(function() {
this.select('*').from('relations as L2').whereRaw(' (L1.`minor_from` = L2.`minor_to` AND L1.`major_from` = L2.`major_to` and L1.`minor_from` = L2.`minor_to` AND L1.`major_from` = L2.`major_to`) AND (L2.`minor_from` = L1.`minor_to` AND L2.`major_from` = L1.`major_to` and L2.`minor_from` = L1.`minor_to` AND L2.`major_from` = L1.`major_to`)');
}).then(function(collection) { res.json(200, collection);});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, mysql, node.js, bookshelf.js, knex.js"
}
|
VB.NET getting date format from date
I need to extract the dateformat from a given date. How am I suppose to do that. Please help.
|
Most of dates are built like this:
xsysz
Where s is a separator that can be `'/', '.', ' '` or even `''`. `x`, `y` and `z` are digits. The problem is that you cannot solve the date format for every possible date because of its ambiguity:
Example: 3-2-2010
Germany: 3rd February 2010
USA: 2nd March 2010
You need additional information (is there any separator?) or some preconditions (year-month-day or year-day-month?) in order to be able to do that. (Same for time... of course)
If you have this preconditions, so you might try with regular expressions. DateTime isn't able to do that for you.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": ".net, vb.net, datetime, formatting"
}
|
MySQL Query Distinct ID over multiple lines
MySQL table 'Features'
prop_id name
----------------------------
1 Wifi
2 Off Road Parking
1 Off Road Parking
2 Close to beach
3 Close to Pub
1 Close to Pub
Prop_id is the id in another table of the property
what i would like to do is get the id's of all the properties where they have 'Wifi' and 'Close to pub'
so in this case i would like it to only return 1
Hope that i have made sence!
|
There are several ways to achieve this, one ugly way is:
select prop_id from features
where name = 'Wifi' and prop_id in (
select prop_id from features where name = 'Close to Pub'
)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql"
}
|
Manhwa/manhua where the main character has to climb a massive cliff to sign in
This is a Manhua/manhwa where the main character has to sign in according to the system and get rewarded for it.
There was a scene where the main character has to climb a massive cliff to sign in and then his cultivation soars.
|
It seems like it may be the isekai _Sign In The Mystery Box To Dominate The World Of Cultivation_. When MC goes to a "sign in" location, he gets loot boxes.

Following is my code:
from google.appengine.ext.webapp import template
...
html = html + template.render('templates/footer.html',
{'links': 'Enter <a href="/">another sighting</a>.'})
The following is the 'footer.html' in templates:
<p>
{{ links }}
</p>
</body>
</html>
And following is the output:
!Output on browser
Any help would be appreciated. (This is the situation in both Firefox and Google Chrome)
|
Add the `safe` filter to your variable:
{{ links|safe }}
Or mark your string as safe in the python code using `mark_safe` function:
from django.utils.safestring import mark_safe
html = html + template.render('templates/footer.html',
{'links': mark_safe('Enter <a href="/">another sighting</a>.')})
This is the django's automatic HTML escaping mechanism. You can control it with autoescape template tag but I don't recommend to do it :-)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, html, django, google app engine"
}
|
Can creat function return zero and what's the meaning of it?
I'm currently working with a legacy code in Linux and encounter with a piece of code that uses `creat` function in `fcntl.h` header for creating a new file or rewriting an existing one. This code assumed return value below zero as an error and above zero as a valid file descriptor and didn't consider zero.
Is zero a valid file descriptor and indicating a successful function call or not? Documentations say:
> Upon successful completion, the function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error.
|
Yes, zero is a valid file descriptor. It is typically stdin, but if you first `close(0)` and then call `creat(...)`, the kernel will reuse file descriptor number 0 for the created file.
If the code you're looking at doesn't consider this, it might be a bug. Even if your executable never closes fd 0 itself, it would would fail in an environment where file descriptor 0 has already been closed before your code started to run. In the bash shell, you can trigger this with `./myprogram 0<&-`.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "c, linux"
}
|
Images not appearing in Google Chrome
I have an image (with a number in the image name - it's called ad1.jpg). Anyhow, it loads fine on any major browser I tested, yet it never seems to load on Google Chrome for some reason. I saw it once today, but aside from that, it's the old image title that appears instead of the image.
I am 150% sure that the problem is that Google Chrome is not properly reading the image name because of the number. Is there an actual problem with using number in image names using HTML5 standards? If not, does Chrome actually have a problem reading numbers in image names?
|
I had a similar problem, it was because of an 'Ad Blocker' installed on my browser. It read the word 'ad' and blocked it. Is it possible that is the problem?
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 1,
"tags": "html, image, google chrome, numbers"
}
|
Why is there a strange white space inside my div after setting its height and width to 0?
<div style=" height:0;
width: 0 ;
border: 1px solid black ; ">
This is all the code  instead.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, pipe, pygame, path finding"
}
|
What does it mean that the spectrum is discrete?
Let $T$ be some operator on a Hilbert space. What does it mean that the spectrum is discrete?
|
"Discrete" here means "not continuous". If the spectrum of an operator is "all integers" then its spectrum is discrete. If the spectrum of an operator is "all real numbers from 0 to 2, inclusive" then its spectrum is continuous, not discrete.
For example, the operator $\frac{d^2}{dx^2}$, on the interval [0, 1], has eigenvalue equation $\frac{d^2f}{dx^2}= \alpha f$ with boundary conditions f(0)= 0, f(1)= 0.
In order to have non trivial solution to that equation, the eigenvalues, $\alpha$ must be $(n\pi)^2$ for some integer n and the corresponding eigenvectors are $sin(n\pi x)$. The spectrum is the set of all numbers of the form $(n\pi)^2$ for n a positive integer. The spectrum, the set of all eigenvalues, is "discrete".
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "functional analysis, spectral theory"
}
|
jquery chaining generic callback function
Often times I come across situations where I want to execute a jQuery function or initialize a jQuery plugin like jQuery datatables and would like to have code execute after the function has finished. jQuery functions such as hide or fadein or other transformation functions take an optional callback parameter to accomplish this. However there are other jQuery functions which just return the 'this' object to allow for chaining. I would like to know if there is a way using chaining or some other method to execute some kind of generic function which takes a callback after whatever jQuery function I call finishes.
Something like:
$("#element").datatable().executeCallback(myCallbackFunction);
|
Take a look at jquery queue < this might help you.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, jquery, jquery plugins"
}
|
Are d8, 10, 12, etc. dice, fair dice?
Given a perfectly formed d8, or d10 or any d dice in _Dungeons& Dragons_ (D&D), are they all fair dice? Is it equally possible to roll any number on any given dice?
I am writing a text based, online D&D engine that would allow a DM to create their own world and invite their friends to play that world online. I am writing a cryptographically secure random number generator to roll the dice, but knowing nothing about D&D, I don't know if all the dice are fair.
|
# Yes, d2, d3, d4, d6, d8, d10, d12, and d20 have uniform distributions
Of these, the d4, d6, d8, d12, and d20 are regular polyhedrons.
The d2 and d10 are not regular polyhedrons, but each face is nonetheless equally-likely.
|
stackexchange-rpg
|
{
"answer_score": 48,
"question_score": 12,
"tags": "statistics, dice"
}
|
Q: How often is an LDAP user store refreshed in WSO2 Identity Server?
I am using WSO2 Identity Server 5.0.0. I have setup a primary read-only LDAP connection in user-mgt.xml. I created a new group on the LDAP server to assign permissions in the Roles section. The new group is not listed. How long does it take to refresh the LDAP groups and is there a way to force a refresh?
|
Normally LDAP groups are read on-demand when it is listed down in the UI. If you have more then 1000 groups in the LDAP, then all the group would not be listed down in the UI.
If you mentioned about the roles under users.. It means that assigned roles for the users... Yes.. there is cache in WSO2IS called `userRoleCache` which will cache the roles for given user. This cache would be refreshed after 15min. Currently you can not configure this timeout value. If you want, you can completely disable the cache using following user store manager property (in `user-mgt.xml` file)
`<Property name="UserRolesCacheEnabled">true</Property>`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "wso2, wso2 identity server"
}
|
Xcode Project-Wide compiler flag
With Xcode 4.2 and the LLVM compiler, when compiling for ARMv6 there are some very weird bugs in the generated application (such as "width" property of CGSize returning the "height" instead). To fix this, I found I must set the compiler flag -mno-thumb. I know how to set compiler flags on a file-by-file basis, but is there a way to set a compiler flag for the entire project?
|
You can set project wide compiler flags in the project settings under the "Language" section of the "Build Settings" tab.
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 8,
"tags": "xcode, xcode4, xcode4.2, compiler flags"
}
|
Configuration Defaults for VMWare vSphere Virtual Machines
We have a number of hosts running VMWare ESXi 5.5 all attached to a vCenter instance. We access and manage all of our VMs with the vSphere Web Client.
A number of people who do not necessarily have a lot of VMWare experience create VMs on a cluster of these hosts. Due to storage limitations we prefer that they set their hard disks to Thin Provision when creating new VMs.
However, this setting is hidden well in the UI and many people end up forgetting it.
My question is, does VMWare provide any way to set some kind of default VM configuration? Perhaps with settings on vCenter, vSphere Web Client, or even each individual host? Like I said we are mostly concerned with defaulting to Thin Provisioning for new hard disks.
Thanks!
|
You could create a VM template for those users and have them deploy from template. In addition you could check to see whether linked clones are an option for your deployment needs. As a sidenote; You may want to reconsider whether those who cannot properly operate vCenter should have access to it.
|
stackexchange-serverfault
|
{
"answer_score": 4,
"question_score": 5,
"tags": "vmware esxi, virtual machines, vmware vsphere, vmware vcenter"
}
|
Why is my custom API endpoint not working?
I tried to include this code in my plug-in php files as well as in `functions.php`. (In the end I would like it to be in the plug-in's php file but I'm not yet sure if possible, that would probably be the topic of another question.)
It is a very basic method for now, I'm just trying to get a response with some content.
In both cases, I get a 404 response.
add_action( 'rest_api_init', function () {
register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(
'methods' => 'GET, POST',
'callback' => 'api_method',
) );
});
function api_method($data) {
var_dump($data);
return 'API method end.';
}
And I tried to access URLs (in brower or with AJAX)
* <
* <
* <
* <
I guess I'm missing something.
|
Maybe start with just `GET`. Your route looks weird as well. Try just:
register_rest_route('my-project/v1', '/action/', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'api_method',
]);
* * *
And your callback is not returning a valid response. Let your callback look more like this:
$data = [ 'foo' => 'bar' ];
$response = new WP_REST_Response($data, 200);
// Set headers.
$response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);
return $response;
* * *
Finally you must combine `wp-json`, the namespace `my-project/v1` and your route `action` to the URL you now can check for what you get:
|
stackexchange-wordpress
|
{
"answer_score": 4,
"question_score": 5,
"tags": "rest api, endpoints"
}
|
how can i change in this file "ip_local_port_range"?
I'm new to Ubuntu I'm on `Ubuntu 12.04 LTS` and want to change in this file but i can't
/proc/sys/net/ipv4/ip_local_port_range
tried to use this command
echo "1024 65000" > /proc/sys/net/ipv4/ip_local_port_range
but after rebooting the file didn't changed ?!!!
|
For the change in a running system use
sudo sysctl -w net.ipv4.ip_local_port_range="1024 65000"
or
echo "1024 65000" > /proc/sys/net/ipv4/ip_local_port_range
* * *
To survive a reboot, open the configuration file
sudo nano /etc/sysctl.conf
and add the lines below
# increase system IP port limits
net.ipv4.ip_local_port_range = 1024 65000
After the next reboot you can see, the correct values are set.
|
stackexchange-askubuntu
|
{
"answer_score": 3,
"question_score": 1,
"tags": "12.04, command line"
}
|
Any measurable function $f:X \to \mathbb R, \Sigma=\{X,\emptyset\}$(where $X$ is a non empty set) must be constant.
Any measurable function $f:X \to \mathbb R, \Sigma=\\{X,\emptyset\\}$(where $X$ is a non empty set, $\Sigma$ is a sigma algebra on $X$) must be constant.
**My attempt:-** We know that $f:X \to \mathbb R$ is measurable. Assume on contrary that $f$ is not constant. I could write the proof till here. I don't know how to proceed? Please help me.
|
Assume that $f$ takes at least two different values $a<b$, $f(x)=a,f(y)=b$. Then $A=f^{-1}((a,+\infty))$ must be in the $\sigma$-algebra $\Sigma$ because $f$ is measurable. But this means that $A=∅$ or $A=X$. We definitely cannot have $A=∅$ because $y \in A$. Thus, $A= X$. But this would imply $f(x) = a \in (a,+\infty)$, which is a contradiction.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "measure theory, measurable functions"
}
|
calling function in c++ program where function is declared in other c++ program
how can one called function in c++ program where function is declared in **other** c++ program? how can one do this? can i use **extern**?
|
I would suggest the best way is to refactor the first C++ program such that the required function is made part of a _library_. Then both your programs can link to that library and the function is available to both (and to any other programs requiring it).
Take a look at this tutorial. It covers how to create and then use a library using `gcc`. Other similar tutorials will exist for other C++ variants.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "c++"
}
|
if (ComboBox1) statement error
I created a ComboBox where a user needs to choose a language.
private void ComboBox1_SelectedIndex(object sender, EventArgs e)
{
if (ComboBox1.SelectedIndex.ToString == "English")
{
this.Frame.Navigate(typeof(MainPage));
}
I'm not sure what I am writing wrong. Should I convert the option of English to a string or can I select is as an item?
|
selecteditem is the value selected
selectedindex is the index selected
you have also to check weather your combobox is selecting an item else an exception'll be thrown
private void ComboBox1_SelectedIndex(object sender, EventArgs e)
{
if (ComboBox1.SelectedIndex!=-1 && ComboBox1.SelectedItem.ToString() == "English")
{
this.Frame.Navigate(typeof(MainPage));
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#, if statement, combobox, selectedindex"
}
|
How did Cobb manage to go to sleep and dream to save Saito after Mal's death?
As far as I can tell the subjects in _Inception_ need to sleep in order to dream and for going under fast and consistent sleep they use sedatives.
Now my question is how did Cobb manage to just fall asleep and dream in a matter of seconds, amidst that turmoil when Mal dies by the hand of Ariadne, to go save Saito?
|
If I recall correctly both Saito and Cobb are already in limbo at that point, so Cobb does not have to 'go down a level' merely go 'across'.
As we see him washed up on a shore before he meets Saito and there is a shore near the city he built we could assume that he has crossed the sea in some sort of imagined/constructed boat but has run into a storm or some sort of interference as he gets close to Saito.
|
stackexchange-movies
|
{
"answer_score": 6,
"question_score": 4,
"tags": "plot explanation, inception"
}
|
Tags em uma tabela para cada?
Eu tenho a tabela "noticia"e eu vou fazer um sistema de tags, essas tags terá que ter uma tabela para cada ou apenas uma tabela ?
|
Você não precisa de uma tabela para cada TAG, você cria somente uma outra tabela com as tags e o id da noticia conforme exemplo abaixo. Uma outra forma é criar uma coluna dentro da tabela de notícias onde você pode colocar as tags separadas por vírgula!
Noticia | Tag
--------- | ------
Id | Id
Desc | IdNoticia
| Tag
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, query, tabela banco de dados, chave estrangeira"
}
|
How do I develop a QGIS Data Provider?
I want to develop a data provider for QGIS, but I cannot find any documentation on how to. I can see that Python plugins are popular, but from the repository it looks like data providers are written in C++ (which I am perfectly fine with) and that they're somewhat dynamically loaded in.
Can anyone point me to documentation on how to do this? Or is my only choice to join their mailing list and ask a "how to get started" question there?
|
This has been asked on the developer mailinglist. Although it's a while ago I suppose the question (and the answers) are still valid: <
I'm not aware of any documentation since writing a new provider has probably been done mostly by core developers. So I guess there's unfortunatley no other choice than to browse through the repository of existing providers and start reading code: <
|
stackexchange-gis
|
{
"answer_score": 1,
"question_score": 2,
"tags": "qgis"
}
|
How do I make a textarea work in an iframe cross-browser?
I'm using the following code and the textarea appears, but I can't edit the text in the textarea or even get a blinking cursor to show in Firefox:
<iframe contentEditable='true'; src="you.php"></iframe>
"you.php" is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
<html>
<head></head>
<body>
<textarea contentEditable='true';>the text.</textarea>
</body>
</html>
|
You don't need contentEditable to edit the contents of a textarea. Try this:
<iframe src="you.php"></iframe>
you.php:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
<html>
<head></head>
<body>
<textarea>the text.</textarea>
</body>
</html>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, iframe, cross browser, textarea"
}
|
How to automate creation of OpenType features based on glyph and/or class names?
I use FontLab Studio, but if there are ways to do what I'm asking in Glyphs, I'd make the switch.
I know how to write OpenType features by hand, based on the naming-conventions of my glyphs and classes. And I've tried to expedite this lengthy process by copying features from another font, or loading them from a `.fea` files. But this only works if the name and number of the glyphs are the same, and even then the `.otf` file usually fails to export. I know there are such things as "Macros" in FontLab but I haven't used them before for lack of understanding.
So, is there a way to automate creation of OpenType features based on glyph and/or class names? Or to expedite this process with Macros or something else?
|
Glyphs uses it's own elaborate glyph naming scheme, which is design to be more "human-readable" and is used to auto generate some OpenType features. For example:
* You can create stylistic sets by using the suffix `.ss01` for the first set, `.ss02` for the second set etc.
* You can create figure sets with the following suffixes: `.tf` for tabular lining, `.tosf` for tabular old-style, `.lf` for proportional lining and `.osf` for proportional old-style.
There are a number of tutorials on glyphsapp.com that explain more about the OpenType features and glyph naming in Glyphs:
* <
A useful post about porting existing projects to Glyphs and the differences in workflow when moving to Glyphs:
* <
* * *
_Side note: I couldn't recomment Glyphs enough. The UI and workflow in general is a lot cleaner and more intuitive than most font editors, without sacrificing features._
|
stackexchange-graphicdesign
|
{
"answer_score": 1,
"question_score": 1,
"tags": "automation, font design, opentype, fontlab studio"
}
|
Asking users to accept answer when they comment that it answers their question
I've had a couple of answers today where the OP indicated via a comment that I solved their problem, but the question wasn't upvoted or accepted. In both cases the person probably wasn't able to upvote since they were new, but they could have accepted my answer. I felt a little guilty asking them to accept the answer, but since it solved their problem I felt that it would help others who stumbled on the question trying to solve their own problem to know that my solution really was the answer.
Is asking the OP to accept your answer when they've said that it solved their problem a reasonable thing to do or does that feel like nagging for reputation?
|
I think that's acceptable. If you were encouraging them to accept an _incomplete_ or _un_ helpful answer, that would be nagging for reputation. Encouraging them to accept a good answer (even your own) is just teaching them the right way to use the system.
Look at it this way, if you saw a comment on _someone else's_ answer that led you to believe it was the right answer, would you leave a comment encouraging the questioner to accept it? You probably would, so you shouldn't feel guilty if you do the same on your own answers.
|
stackexchange-meta
|
{
"answer_score": 207,
"question_score": 190,
"tags": "discussion, accepted answer, etiquette"
}
|
Why would someone chose midpoint displacement over perlin noise for 3D terrain generation?
I myself am creating a terrain generation algorithm and would be interested in knowing why others have chosen midpoint displacement over perlin noise. Minecraft is an example where midpoint displacement was preferred. If anyone knows why I would be glad to hear it.
|
Different methods of fractal generation tend to produce terrain with different characteristics. The reason for their use could be stylistic rather than for any technical performance reason. Different algorithms also allow you to change different parameters to give the final result. I have no direct answer re: MD vs Perlin though, sorry..
|
stackexchange-gamedev
|
{
"answer_score": 3,
"question_score": 5,
"tags": "algorithm, minecraft modding, terrain, perlin noise"
}
|
Repeated "link-only" answers
Check these link-only, and duplicate answers by the same author.
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11...
All these answers appeared on the low-quality posts review list repeatedly, like this.
Are these questions duplicates? Or only answers?
How can we avoid this?
|
I've already flagged the posts as _In need of moderator intervention_ , and it's helpful now. Also the answers have been deleted.

INSERT Test values (GETDATE())
SELECT * FROM Test
GO
ALTER TABLE Test ALTER column SomeDate datetime2
GO
INSERT Test values ('16000101')
SELECT * FROM Test
GO
|
stackexchange-stackoverflow
|
{
"answer_score": 36,
"question_score": 27,
"tags": "c#, sql server"
}
|
What does % mean in linux / how to install jmf
I am fairly new to linux and am using fedora 14 (64 bit). I have to install the java media framework for one of my projects. In the installation instructions on their website (< they use the % symbol. I have done some research and googling and can't find what the significance of % is. Does anyone know? I have been able to find just about every other symbol meaning (., .., #, and more). They use it in the following context
> Run the command
>
> `% /bin/sh ./jmf-2_1_1e-linux-i586.bin`
|
`%` is the command prompt. Like `>` in DOS, which along with the current working directory might appear as `C:\>`.
You can actually change this to be anything that you like, but `%` is the default for a regular user account under the csh or zsh shell. The shell is the program that displays the command line, reads what you type, and executes the command. The sh or bash shells use `$` for their command prompts.
If you are logged in as root (the admin or superuser account), most shells change the prompt character to `#`, to remind you that you better be careful about what you type.
So, when you see `% foobar` in documentation, it just means open a terminal window, type `foobar`, and hit enter.
|
stackexchange-superuser
|
{
"answer_score": 3,
"question_score": 1,
"tags": "linux, fedora, fedora 14"
}
|
Git command to commit to remote branch
I created a branch in my local machine then staged after making change to change.html
git checkout -b myBranch //create a branch in my local machine
git add change.html
then I created a branch in github page, called "fix/remoteRepo". then I did following to create a short name for the remote URL repo.
git remote add haeminsh
then to commit change.html to the remote repo,
git push myBranch haeminish
I am getting following error:
fatal: 'myBranch' does not appear to be a git repository.
fatal: Could not read from remote repository.
What is the problem? I do not want to make any changes to the master but to my remote repo.
* * *
How do I find a correct URL?
|
You need to run: `git push <remote> <branch>`. Here your remote name is `haeminish` and branch name `myBranch`.
First remove current remote `haeminish` then, add `haeminish` with correct URL.
$ git remote rm haeminish # remove remote haeminish
$ git remote add haeminish # add new 'haeminish' with correct url
# replace <username> & <reponame> with exact value
$ git push haeminish myBranch
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "git"
}
|
How does Postgres host based authentication work?
I am installing DSPACE which needs PostgresSQL.
Please see this link: DSPACE INSTALL
It says:
> Then tighten up security a bit by editing pg_hba.conf and adding this line:
>
>
> host dspace dspace 127.0.0.1 255.255.255.255 md5.
>
I have read on the internet as to how the above line works. It needs a connection type followed by database name/user name followed by IP address and the authentication scheme.
My question is: Should this not be a local (in place of host) connection since the dspace user is running locally?
Can someone show me step by step as to what happens when a request comes in? Where are the instructions that the dspace user will submit a request using md5?
|
DSpace uses JDBC, so `local` won't work for it. Here `local` means a completely different kind of inter-process connection that has nothing to do with IP and can only address local processes: Unix sockets. JDBC uses only IP, so DSpace needs a `host` descriptor.
That period at the end of the line is not supposed to be part of it. The documentation was unclear there -- I've fixed it.
As Laurenz Albe noted, DSpace doesn't specify that MD5 password hashes be used. The PostgreSQL server controls which methods will be tried, based on what you specify in `pg_hba.conf`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "postgresql, dspace, pg hba.conf"
}
|
Generate all 4-perfect numbers
Your program or function should output all the 36 4-perfect numbers in increasing order separated by newlines.
An `n` positive integer is a `k`-perfect number (multiply perfect number) if the sum of its divisors including itself (i.e. the sigma function of `n`) equals `k*n`.
For example `120` is a `3`-perfect number because `1 + 2 + 3 + 4 + 5 + 6 + 8 + 10 + 12 + 15 + 20 + 24 + 30 + 40 + 60 + 120 = 360 = 3*120`.
### Details
* Your entry should actually produce the output and terminate on your machine before you submit your answer. (i.e. the program should terminate in a reasonable time)
* Hardcoding is allowed.
* Built-in functions or data closely related to the problem (e.g. sigma function) are disallowed.
* This is code-golf but as the task is non-trivial without major hardcoding non-golfed entries are welcomed too.
(This is a great detailed page about the history of all multiply perfect numbers.)
|
# CJam, 377 bytes
All the characters are part of extended ASCII, so I'm counting this as a single byte per character
"Ò|+^ø¥©~öôxõÕÊïB.X}Ã+ç
âà©¥;ØÓé@ä¦qØH®üzGOwCàæ/Â$ªh#þ>üJNDÂTR{^Ìý±OáÉÚ6ï®I?Çvqf³e1é^¶Y½5ãþ#_-__xF'IMØ*¬È6Vô+§mâ?µTJÉ9$·Ùöµ¨±Dac&¼'h,q÷ZwÎE^§Å{åÁûà\µ;óÛ¤{n'ÜGÐÓR!³¥èè>(~\"NbU*ötmù¦ªUe|Rñ¾!a9TYÇ&êë½ôâ··¨JÆ#Ù&îCÎÍð4q<ÌÏïj;Åd*òz(x ?ßâ%d8ƬÔUÎ=¶îÖÀ+mHH9â\"=PʱedèËU· /þr<ÆGR;|úÀè¶¡õrì@öÆ"255bBbAa/N*
I'm sure Stack Exchange will have swallowed some of the characters, so you might want to copy the code [from this pastebin.
Test it here.
This solution is purely hardcoded. It interprets the code points of the characters as the digits of a base-255 number, gets the base-11 digits of that, splits on the digit `10` and joins the resulting arrays by newlines.
|
stackexchange-codegolf
|
{
"answer_score": 3,
"question_score": 5,
"tags": "code golf, math, number, kolmogorov complexity, number theory"
}
|
Set values for particular columns in a row of a Pandas Dataframe
Referring to Set value for particular cell in pandas DataFrame I see
df.set_value( rownum, colnum, 'Someval')
to set a given cell. Assume in my dataframe all the columns are integers.
Is there a way to use
set_value
to set a range of columns in a given row, or do I need a different function?
df.set_value ( rownum, colstart:colend, 'someval')
gave a syntax error.
After some contortion I found this:
df.ix[ rownum , colstart:colend] = 'Someval'
This one works but I was wondering about set_value or perhaps some other short way.
|
As noted directly above by @MaxU, you are looking for
df.iloc[ rownum , colstart:colend] = 'Someval'
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, pandas, dataframe"
}
|
Does Sage of Ages roll replacement happen before or after the roll?
Sage of ages, level 24:
> Keeper's Prescience (24th level): At the start of each of your turns, roll a d20. You can use the result of that roll in place of any one d20 roll you make before the start of your next turn.
Does this replacement occur before the d20 roll or can it be used to replace an already rolled d20?
|
**The use of the d20 is decided before the result of the roll is known**
> You can use the result of that roll in place of any one d20 roll you make before the start of your next turn.
The key here is that you are replacing a roll, and not a result.
Compare Elven Accuracy DDI
> Trigger: You make an attack roll and dislike the result.
where the trigger is a roll with a result, rather than just a roll.
and Divine GuidanceDDI
> Trigger: An ally within 10 squares of you makes an attack roll against your oath of enmity target
>
> Effect: The target makes a second attack roll and uses either result
|
stackexchange-rpg
|
{
"answer_score": 1,
"question_score": 8,
"tags": "dnd 4e"
}
|
C# out parameter in extension method
In an extension method, I am receiving an error that my 'out' parameter does not exist in the current context. I assume this means that extension methods cannot have 'out' parameters, but this is not specified in the documentation. I would appreciate it if someone could please clarify!
public static int customMax(this int[] data, out index)
{
int max = data[0];
index = 0;
for (int i = 1; i < data.Length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
|
Extension methods can have out parameters. You need to specify the type of your out parameter. So change code
public static int customMax(this int[] data, out index)
to
public static int customMax(this int[] data, out int index)
and it should all work
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 5,
"tags": "c#, extension methods, out"
}
|
Delete post from admin but not from database
Is it possible to have a post not deleted from the MySQL database on deleting from the wp-admin panel ?
|
By default wordpress do not delete posts but rather moves them to the trash. They do not appear in the normal posts admin, but you can still see them in the trash and recover them from it.
|
stackexchange-wordpress
|
{
"answer_score": 1,
"question_score": 0,
"tags": "posts, customization"
}
|
Create picture from geocordinates
I have the geocordinates of a trip and I would like to save the picture that display the path on a map. Do you know an api or library that woud do that ?
|
You can use Static Map for that. The Google Static Maps API lets you embed a Google Maps image on your web page.From there, you can draw your path.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, google maps, gps, openstreetmap"
}
|
How to add Check Constraints for Django Model fields?
While subclassing `db.models.Model`, sometimes it's essential to add extra checks/constraints.
For example, I have an `Event` model with `start_date` and `end_date`: I want to add validation into the fields or the model so that `end_date > start_date`.
At least I know this can be done outside the `models.Model` inside the `ModelForm` validation. But how to attach to the fields and the `models.Model`?
|
I would not put constraints like these in the save method, it's too late. Raising an exception there, doesn't help the user who entered the data in the wrong way, because it will end up as a 500 and the user won't get the form with errors back etc.
You should really check for this in the Forms/ModelForms clean method and raise a ValidationError, so `form.is_valid()` returns false and you can send the errors in the form back to the user for correction.
Also note that since version 1.2, Django has had Model Validation.
It would look something like this:
class Foo(models.Model):
# ... model stuff...
def clean(self):
if self.start_date > self.end_date:
raise ValidationError('Start date is after end date')
|
stackexchange-stackoverflow
|
{
"answer_score": 59,
"question_score": 47,
"tags": "django, django models, django forms, check constraints"
}
|
DeviceId() shows me nullpointer?
i am developing an app in that i just need IMIE number of device...
I tried:
telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imie = telephonyManager.getDeviceId();
In Menifiest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Let me tell, if that require any other things to do??
thanks in advance.
|
I think you're doing it right, but according to the Android Developers Blog:
> We have seen a few instances of production phones for which the implementation is buggy and returns garbage, for example zeros or asterisks.
Also, it probably won't work on an emulator.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "android, telephony"
}
|
Extracting part of a string (for a vector of strings)
x<-c("123-12","12-24","6-4")
How do I extract the portion of each string before the dash into a new vector? In this example my result should be equivalent to
c("123","12","6")
How do I do the same thing, except extract everything after the dash? I.e.
c("12","24","4")
For my problem, you can assume that every element of x will have one and only one dash.
|
For extracting the string before the dash, replace the dash and everything after by an empty character string.
sub('-.*', '', x)
For extracting the string after the dash, do the opposite
sub('.*-', '', x)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "r"
}
|
should I always use convertView as my main ViewElement in Base adapter?
the variable convertView in getView of BaseAdapter . What is it for? when creating items should I always use convertView? What is the problem if I don't use it?
|
What is it for?
it an instance of the `View` if you inflate, the first time its value is null. E.g.
if (convertView == null) {
convertView = inflate...
}
> when creating items should I always use convertView?
yes, but try to implement the ViewHolder pattern around it. It will speed up the scroll's performance.
> What is the problem if I don't use it?
it depends on the the number of items you have in your `ListView`. We can go from laggy ux to crashes.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, baseadapter, getview, convertview"
}
|
Guice + Конфигурация приложения
Добрый день, подскажите есть ли более object-oriented, чем @Named аннотации, способ вставлять данные из файла конфигурации в классы при помощи google guice?
|
Вот Вам вариант который я писал сам для себя... guice-config
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, dependency injection"
}
|
How to optimize mysql database automatically in PHP?
i have a database and need to automatically optimize this 24 hourly
What should I do?
|
i wrote a class
class DbPerformance
{
var $TablesHaveOverHead = array();
function DbPerformance()
{
if (date("H") == '00')
{
$this->GetOverheadTables();
$this->OptimizeDatabase();
}
}
function GetOverheadTables()
{
$result = mysql_query("SHOW TABLE STATUS ");
while ($row = mysql_fetch_assoc($result))
{
if ($row["Data_free"] > 0)
{
$this->TablesHaveOverHead[] = $row['Name'];
}
}
}
function OptimizeDatabase()
{
if (!empty($this->TablesHaveOverHead))
{
$tables = implode(",", $this->TablesHaveOverHead);
mysql_query("OPTIMIZE TABLE $tables;");
}
}
}
$optimise = new DbPerformance();
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "php, mysql, database, optimization"
}
|
Get explicit, vector-valued function for a curve defined by an implicit expression.
$ \mathcal {B} = \\{(x,y) \in \mathbb R^2 $ such that $ 0 = x^2 + y^2 + xy \exp (-x^2) \\} $
$ \mathbf f(x,y) = f_1(x,y) \mathbf i + f_2 (x,y) \mathbf j = \mathcal {B} $
Please show explicit expressions of the functions $f_1(x,y)$ and $f_2(x,y)$.
|
With due credit to both commenters, here is what I was seeking.
Start from the implicit expression:
$$ 0 = x^2 + y^2 + xy \exp (-x^2) $$
Complete a square.
$$ \left (y + \frac 12 x \exp (-x^2) \right )^2 = y^2 + xy \exp (-x^2) + \frac 14 x^2 \exp (-2x^2) $$
Therefore
$$\sqrt {\frac 14 x^2 \exp (-2x^2) -x^2} = y + \frac 12 x \exp (-x^2) $$ $$ $$ $$ y = \frac {-1}2 x \exp (-x^2) + x \sqrt {\frac 14 \exp (-2x^2) - 1} $$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "multivariable calculus, implicit function"
}
|
Jquery :contains showing alert for all span
I have a span `<span style="font-weight: bold;">Text goes her</span>` like this
$('#contentarea').bind('click',function(e){
e.preventDefault();
if($(e.target).is('span')){
if($(e.target).find(":contains(font-weight: bold;)")){{
alert('bold');
}
}
});
i am not getting the actual result, if i click any span text it will alert,please help me, i need to find out the span contains the **font-weight: bold;**
|
you can use the attribute selector...(if you just need to select the span containing the style attribute as font..)
try this
$('span[style^="font-"]')
this should select the span with style starting with `font-`
or
$('span[style="font-weight: bold;"]')
fiddle
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "jquery, html, jquery ui, css"
}
|
Select all rows where two columns have the same value?
I'm working with SQL and was wondering how I would get all of the rows where values in 2 columns are equal. For example, imagine this table:
+----+---------+
| ID | Version |
+----+---------+
| AB | 1 |
| AB | 1 |
| BA | 2 |
| BA | 2 |
| CB | 1 |
+----+---------+
I want to select all rows where the IDs and versions match other rows with the same values in their ID and Version columns. In other words, I want to find duplicate values. So the desired output would be:
+----+---------+
| ID | Version |
+----+---------+
| AB | 1 |
| AB | 1 |
| BA | 2 |
| BA | 2 |
+----+---------+
How would I go about doing this as efficiently as possible in a table with over a million rows?
|
The simplest method are probably window functions:
select t.*
from (select t.*,
count(*) over (partition by id, version) as cnt
from t
) t
where cnt >= 2;
If you have an index on `(id, version)` (or `(version, id)`), then the database engine should be able to take advantage of that.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, database"
}
|
Can my Raspberry Pi Zero W python program be duplicated and resold?
I have a Raspberry Pi Zero W that runs a program under the main username, Pi. I'm going to give this Pi to someone for their own use, however I expect them to use the Pi for their application without being able to access the code itself (and potentially replicate). I have two questions:
1- If they tried copying the SD card, it will still ask for the same password right?
2- The Pi is preconfigured to use a specific SSID and Password, copying the SD card will still limit any use of the Pi at another wifi point right? So they would be able to duplicate my Pi but only be use it in the preconfigured wifi details?
|
If someone has physical access to the SD Card they can do ANYTHING, even if they don't know the password.
|
stackexchange-raspberrypi
|
{
"answer_score": 2,
"question_score": -1,
"tags": "pi 3, python, security"
}
|
Allowed memory size exhausted in FlattenException Symfony
i got this error at least 20 times each minute on my production server logs.
My website is getting down when visitors number arrives to ~50.
Any suggestion?
> [Fri Dec 14 23:52:32.339692 2018] [:error] [pid 12588] [client 81.39.153.171:55104] PHP Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 32 bytes) in /vendor/symfony/symfony/src/Symfony/Component/Debug/Exception/FlattenException.php on line 269
|
In your production, you don't need to debug component, for reducing memory use composer with --no-dev --no-interaction --optimize-autoloader.
If you can access your server via ssh, check memory consuming.
My suggestion if you have 50 visitors at the same time, This is a good time to upgrade the server.
Also, you can try to reduce max_execution_time to open some more memory.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "symfony"
}
|
Is there a way to test Azure CosmosDb locally with a Linux docker image?
Unfortunately Microsoft's docker image is Windows only which isn't suitable in our case: <
I was wondering if we'd be able to use a MongoDb docker image to test locally, would that work? Are the APIs compatible?
|
Cosmos DB's API for MongoDB is compatible with server version 3.6 so possibly yes.
If you don't have to test locally there are free options for testing including free tier which gives you 400 RU/s and 5GB free for ever. Or you can use Try Cosmos which gives you 30 days free at higher RU/s.
Hope that is helpful.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mongodb, azure, docker, azure cosmosdb"
}
|
Making subsite page the homepage in sharepoint
Is it possible to make a subsite page as the homepage in sharepoint without any access to codes to location where all the files are stored?
|
Apparently subsites cannot be made welcome page directly due to some security issues. It is possible to create a redirect page in the main site and make it the landing page and then redirect the user to the subsite from there.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sharepoint"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.