INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
What type of algebra are Valiant's algebras for context-free grammars?
In General Context-Free Recognition in Less than Cubic Time, Leslie Valiant gives an algorithm for transitive closure of matrices where the matrices are over an algebra $(S, \cup, \cdot, 0)$ where
> the outer operation ($\cup$) is commutative and associative, ... the inner one ($\cdot$) distributes over it and ... $0$ is a multiplicative zero and an additive identity.
Is there a name for such structures, which are generalisations of semirings?
|
Going by the terminology of nonassociative rings, we could call this a nonassociative semiring, and indeed Google gives some results for that term with a matching definition.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "abstract algebra"
}
|
Remove padding when number of zeros can change
I have an string which is always 12 digits long
Its starts with 'PSS1'
'PSS100000300'
So I need to extract '300'
I can't just grab the last 3 digits as the number can increase to say
'PSS100010300'
And would need the value extracted to be '10300'
|
Try this :
s = Convert.ToInt32(s.Replace("PSS1", string.Empty)).ToString()
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#, regex"
}
|
MATLAB postpones disp calls when doing demanding calculations. Why is that?
I am implementing an algorithm in MATLAB. Among other things it calculates the shortest paths etc. so it's quite demanding for my old computer. I've put in disp() calls through out the program to see what's happening all the time.
However when starting on a particulary heavy for loop the `disp()` seemes not to be called until the loop is over even though it comes before the loop. Why is that? I thought that MATLAB was really executing sequentially or am I just choking it with too many calculations and the `disp()` calls get the lowest priority?
|
I am almost certain it is because of EDT.
That's the function drawnow() is for. See article of Yair Altman for good explanation.
Summary: MATLAB graphics is Java Swing and operations happen on a special thread - Event Dispatch Thread (EDT). Calling `drawnow();` flushes event queue and updates figure window.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "algorithm, matlab"
}
|
service start / stop / restart - no output
I installed debian jessie. When I use a service-command like "service nginx restart" there is no output. Previously I was using debian wheezy and there was feedback like (I don't remember exactly): [ ok ] nginx stopped [ ok ] nginx started
How can I re-enable this output?
|
The only solution I found was to call the service directly: `/etc/init.d/nginx restart`
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 2,
"tags": "service, debian jessie"
}
|
Can I use wildcards in "IN" MySQL statement?
I would like to run something like:
select * from table where field in ("%apple%", "%orange%")
Is there a way? Or at least is there a better way than dynamically building query for every keyword:
select * from table where field like "%apple%" or field like "%orange%"
Thanks.
|
I'm not sure it's any better than what you came up with but you could use MySQL's regex capabilities:
select * from my_table where field rlike 'apple|orange';
Also, as others have mentioned, you could use MySQL's full text search capabilities (but only if you're using the MyISAM engine).
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 18,
"tags": "sql, mysql, wildcard"
}
|
How to declare an inner interface in a class with it's method signatures?
When I do this the code throws no error,
public class MyClass {
interface MyInnerInterface {}
public Integer x = 0;
}
But when i try to add a method to the inner interface it throws error,
public class MyClass {
interface MyInnerInterface {public void fun();}
public Integer x = 0;
}
How to declare an inner interface in a class with it's method signatures ? Also, are inner interface private when no access modifier specified ? I know they have to be public or global when declared at the top level.
|
Interfaces do not specify a method access level. Take out the word `public`. If this interface should be accessible outside the class, you do need to specify an access level greater than `private`.
public class MyClass {
// Can only be used in this class
interface MyPrivateInnerInterface {
void fun();
}
// Can be used in any class in the namespace
public interface MyPublicInnerInterface {
void fun();
}
// Can be used in any namespace!!!
global interface MyGlobalInnerInterface {
void fun();
}
public Integer x = 0;
}
|
stackexchange-salesforce
|
{
"answer_score": 2,
"question_score": 2,
"tags": "apex"
}
|
how can I work with the last element of iterations
for(int t(0); t < 10;++t) { cout<<t<<endl;}
I'm just biginer in C++, and want to know how can I take the last elemnt of my "cout...."; in this case my laste element is 9
thx for help ;)
|
One simple way -
int t = 0;
for (; t < 10; ++t)
cout << t << ;
Tough the correct way to do it will be (one variable should not have two meanings, i.e 1. last element, 2. iterator context) -
int last_element;
for (int t = 0; t < 10; ++t;
{
cout << t << ;
last_element = t;
}
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 0,
"tags": "c++, loops, cout"
}
|
Django pass parameters
I'm trying to pass pk key
urlpatterns = [
path('api/products', ProductAPI.as_view()),
path('api-admin/products/', ProductAdminAPI.as_view()),
url(r'^api-admin/products/(?P<pk>[0-9]\d+)', ProductAdminAPI.as_view()),
]
with this URL `localhost:8000/api-admin/products/3/`
but I'm getting 404
|
Your expression `(?P<pk>[0-9]\d+)` is wrong. You need at least 2 digits to match the expression, since you first ask a character `[0-9]` and then a digit `\d`.
Remove either `[0-9]` or `\d`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, django"
}
|
AngularJS ng-show with yes/no
I have a div I'd like to show once a yes/no radio button is checked. The problem is when i click no. My ng-show is evaluating "no" as false and hiding. I'd like do do something like this
<div ng-show="IsYesOrNo">
But I end up having to do something like this:
<div ng-show="IsYesOrNo=='yes' || IsYesOrNo=='no'">
I'm using 1.2.25. It looks like it actually works the way I expect it in 1.3.0-rc.3.
Is there a better way on how to build my ng-show? Here's a plnkr I threw together demonstrating the behavior.
<
|
What about
<div ng-show="IsYesOrNo !== undefined">HasSet</div>
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "angularjs"
}
|
Can't download with HttpClient with a different server port
I am using Apache's HttpClient via httpclient-fluent-builder to download a http page.
This is the code:
...
try {
response = Http.get("
.use(client) // use this HttpClient (required)
.charset("windows-1252") // set the encoding... (optional)
.asString();
} catch (IOException e) {
Log.d(TAG, "Error: "+e.toString());
e.printStackTrace();
}
Log.i(TAG, ""+ response );
...
Problem is that I get org.apache.http.client.ClientProtocolException
It's something with the host:port/url, beacause it works with urls without ports. I also get this same error with another Httphelper class than fluent-builder. Firewall is off.
Logcat: <
|
Found out what it was via this post that it was the Shoutcast server...
> You should be able to connect to 8000 with your web browser and get the DNAS status page. If, on the other hand, you connect to that port with a media player, it'll return the direct MP3 stream. ( **Unfortunately, in an incredibly boneheaded piece of design, the way SHOUTcast decides which to respond with is by sniffing your User-Agent header for something beginning with Mozilla** , so if you're using an alternative browser or blocking your UA you'll not be able to get the status, and if the stream's down you might just get nothing.)
Drove me crazy.. But it's an easy fix. I just added.
.header("User-Agent", "UserAgent: Mozilla/5.0")
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java, android, httpclient"
}
|
Particles.js with Wordpress
My particles.js won't load with my WorpdPress custom theme. The console throws this error:  {
setState(() {
weight += 1;
});
}
weightDecrement() {
setState(() {
weight -= 1;
});
}
Text(
cardType == CardType.age ? "$age".toString() : "$weight".toString())
Using above on some button. And setting value to Text throws below error. I/flutter (22691): The following assertion was thrown building Calculator(dirty, state: _CalculatorState#82a4b): I/flutter (22691): type 'int' is not a subtype of type 'double' of 'function result'
|
The error statement itself is giving the answer here, Basically what it says is that the state you are trying to set is of type int and it(The dart compiler) expects it to be of type double. And it assumes that because you have defined the type of weight as a double. (`double weight = 0;`).
The quick and straightforward solution is to change the type of weight while initializing it as: `int weight = 0;`
I get your point about why you might be initializing the weight as a double because the weight doesn't have to be a whole number. To follow that, you might want to set the state with a double as follows:
First initialize the weight as `double weight = 0.0;` then modify your functions as:
weightIncrement() {
setState(() {
weight += 1.0;
}
}
And the same for decrementing the weight.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "flutter, flutter dependencies"
}
|
getting counts for each day in a dataframe
I am currently trying out sentiment analysis on a set of tweets and was wondering how to get counts for the number of tweets in a particular day. The problem for me is that each day is super granular, right down to the second of the tweet being sent. How would I get the counts of tweets for a whole day like the 25th of Jan 2016.` .
Then extract the date from each datetime:
df['date_only'] = df['date'].dt.date
And finally groupby:
result = df.groupby('date_only').agg({'tweet': 'count'})
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python"
}
|
background color problem in an access form
I have a form containing a textbox "Text20". I have put some code in the OnCurrent event of the form:
Option Compare Database
Private Sub Form_Current()
Text20.BackColor = vbRed
End Sub
It does nothing when I display the form whereas it should color my textbox. Do you see why ?
Thank you
|
There really is no reason to do this in the code behind. Just right click the control, select conditional formatting and apply the formatting and give it a condition and a format.
No code required.
!enter image description here
In fact, the code you included in your example would re-set that every time the form changes records, which is overkill anyway.
Better yet. Why not just set the color in the property sheet for the control?
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ms access"
}
|
Cant figure out why I am getting this Kramdownn warning
Previously, I had this text being processed by Kramdown without any problems:
* **[GIT]** Setup a git repo for your team
Recently I started getting this error:
kramdown warning: No link definition for link ID 'git' found on line 4
I can't see in the Kramdown revision history that this is now an invalid input and before I got and modify hundreds of files I wonder whether anyone can shed light on this, and in also how I can modify the line most easily. What I want is a that the text "[GIT]" appear in bold on a bulleted line.
|
It's not an invalid input. kramdown will correctly parse that as expected (as of version 1.6.0):
<ul>
<li><strong>[GIT]</strong> Setup a git repo for your team</li>
</ul>
I'm not sure why the warnings were suppressed earlier, but I checked through the Ruby code and that warning was present in the earliest available version. I also checked back to 1.3.3 and it also generates that warning.
Even though kramdown generates the desired output, if you want to avoid the warning, you can escape the brackets.
* **\[GIT\]** Setup a git repo for your team
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "kramdown"
}
|
Converting rows of dataframes into matrices - Python Pandas
I have the following dataframe:
Pclass Sex Fare Embarked Title Family
3 0 1.0 0 0 1
1 1 2.0 1 3 1
3 1 1.0 1 2 0
1 1 2.0 3 3 1
3 0 2.0 1 1 0
I need to take each row and turn it into a 6X32 matrix.
(Example of 3X10)
3,3,3,3,3,3,3,3,3,3
0,0,0,0,0,0,0,0,0,0
1,1,1,1,1,1,1,1,1,1
I need that but for every element of the column and 32 times instead of 10.
My code:
from itertools import repeat
array = []
for i in range(0,len(datos)):
rows = datos.iloc[i,:]
for j in range(0,len(rows)):
array.append([rows[j]]*10)
I'm not sure how to do it to separate each row into a unique array.
|
Everything at once
np.dstack([df.values.astype(int)] * 32)
You can even turn it into a series with matching index
pd.Series(np.dstack([df.values.astype(int)] * 32).tolist(), df.index).apply(np.array)
0 [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,...
1 [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
2 [[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,...
3 [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
4 [[3, 3, 3, 3, 3,
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, pandas, numpy"
}
|
Why can't I vertically align these two matrices?
Why won't these matrices become left-aligned?
\documentclass[11pt,a4paper,oneside]{report}
\usepackage[pdftex]{graphicx}
\usepackage[T1]{fontenc}
\usepackage{fouriernc}
\usepackage{mathtools}
\usepackage{amsfonts,amsmath,amssymb,amsthm}
\usepackage[a4paper, hmargin={3.5cm,3cm}, vmargin={2.5cm,2.5cm}]{geometry} % margin
\usepackage{multicol}
\begin{document}
\begin{align*}
&\renewcommand\arraystretch{1.4}
\begin{bmatrix}
a_{1}&u_{2}&\frac{a_{1}}{d}u_{3}\\
a_{2}&u_{1}&\frac{a_{2}}{d}u_{3}\\
a_{3}&0&u_{4}\\
\end{bmatrix}\\
\intertext{with}
&\renewcommand\arraystretch{1.4}
\begin{vmatrix}
a_{1}&u_{2}&\frac{a_{1}}{d}u_{3}\\
a_{2}&u_{1}&\frac{a_{2}}{d}u_{3}\\
a_{3}&0&u_{4}
\end{vmatrix}=1
\end{align*}
\end{document}
!enter image description here
Thank you
|
This is a **_very dirty trick_** , but it works. It aligns the matrices' elements rather than the delimiters.
!enter image description here
\documentclass[11pt,a4paper,oneside]{report}
\usepackage[pdftex]{graphicx}
\usepackage[T1]{fontenc}
\usepackage{fouriernc}
\usepackage{mathtools}
\usepackage{amsfonts,amsmath,amssymb,amsthm}
\usepackage[a4paper, hmargin={3.5cm,3cm}, vmargin={2.5cm,2.5cm}]{geometry} % margin
\usepackage{multicol}
\begin{document}
\begin{gather*}
\renewcommand\arraystretch{1.4}
\begin{bmatrix}
a_{1}&u_{2}&\frac{a_{1}}{d}u_{3}\\
a_{2}&u_{1}&\frac{a_{2}}{d}u_{3}\\
a_{3}&0&u_{4}\\
\end{bmatrix}\mathrel{\phantom{=1}}
\intertext{with}
\renewcommand\arraystretch{1.4}
\begin{vmatrix}
a_{1}&u_{2}&\frac{a_{1}}{d}u_{3}\\
a_{2}&u_{1}&\frac{a_{2}}{d}u_{3}\\
a_{3}&0&u_{4}
\end{vmatrix}=1
\end{gather*}
\end{document}
|
stackexchange-tex
|
{
"answer_score": 4,
"question_score": 1,
"tags": "horizontal alignment, align, matrices, delimiters"
}
|
Applying the definition of Lebesgue Integral to specific functions
I am fairly sure this question will sound rather naive, but I do have a problem with **_applying_** the Lebesgue Integral. Actually this question can be divide in two sub-question, related to two examples I have in mind.
1. I know that the integral of $f(x) = x^{-\frac{1}{2}}$ over $[0,1]$ cannot be obtained through Riemann Integration. Fair enough, but how do we actually _compute_ it through Lebesgue Integration?
_[Here I mean, from the very basics of the theory, without using calculus shortcuts, with the addition that we are allowed to do this from some theorem]_
2. I (sort of know) that we cannot compute the integral of a gaussian function $e^{-x^{2}}$ by using standard Riemann techniques. Can the Lebesgue integral accomplish it? If so, how?
* * *
_PS: I do hope what I wrote make sense. If it is not the case, please feel free to point me out any conceptual mistake._
|
Computing integral of Gaussian on whole line is possible using standard techniques. The problem is that no elementary antiderivative exists so you can't easily obtain integrals over arbitrary intervals. The function is integrable in the Lebesgue sense, just as it is integrable in "improper" Riemann sense. So Lebesgue theory doesn't introduce anything new here. In general it doesn't equip us with many new computational tools. Instead of that significance relies on its good properties: working well with limits and nice spaces of integrable functions. But on the side of computations it gives you nothing new, except that it allows you to justify some useful procedures involving limits which would be difficult to justify in Riemann setting. The computation itself is unchanged though.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 5,
"tags": "real analysis, integration, measure theory, self learning, lebesgue integral"
}
|
How do I make a grid with rounded corners?
How do I make an object which is a grid with rounded corners as seen in the photo below?
The rounded corners are big and cut through multiple of the squares inside the grid.
, subdivide it, delete its faces, switch to top view, select the grid, shift select the first plane, go into _Edit_ mode, then _Mesh > Knife Project_ and it will cut the grid on the plane. Give some corrections:

{
Name = name;
Time = time;
}
Я хочу задать значение этого свойства через консоль `firstPerson.Time = Int32.Parse(Console.ReadLine());` Возможно ли задать допустимые значения для Time, чтобы при вводе чисел за пределами диапазона, появлялось сообщение об этом?
|
Person firstPerson = new Person { Name = "First", Time = 1 };
bool isSuccess = false;
while (!isSuccess)
{
try
{
int n = Int32.Parse(Console.ReadLine());
if (n > 0 && n < 100) // требуемое условие
{
firstPerson.Time = n;
isSuccess = true;
}
else
{
Console.WriteLine("Введенное число не удовлетворяет критериям.");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#"
}
|
Generate multiple tag query URLs
As we know WordPress supports multiple tag queries (',' and '+'). The only problem with this `add_query_arg()` doesn't handle these methods if a query param is already exists in the URL.
From the following url `www.domain.com?post_type=ptype¶m=value1 add_query_arg('param', 'value2')` will generate `www.domain.com?post_type=ptype¶m=value2` insead of `www.domain.com?post_type=ptype¶m=value1,value2` or `value1+value2`
I would only use comma separated (OR) method. Could you please help me to write a function which adds additional param value next to an exsisting one? regular expressions perhaps?
|
$url = parse_url( $your_url );
$query = $url['query'];
$args_arr = array();
parse_str( $query, $args_arr );
if( isset( $args_arr['param'] ) ) {
$query_string = $args_arr['param'];
$query_string .= ',value2';
} else {
$query_string = 'value2';
}
add_query_arg( 'param', $query_string );
That's completely untested, but you get the concept. Basically, wordpress is gonna want to replace what you have set in `param`, so you need to get what you have in param, then add what you want to add to it. You can definitely make that into a function if you want to, depends on your usage case.
|
stackexchange-wordpress
|
{
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, multi taxonomy query, advanced taxonomy queries"
}
|
How to shorten a sentence while keeping the same meaning and impact?
I have the following sentence:
> Whether you are a software developer or a recruiter, sign up now to gain access to the best recruitment network!
I feel this is too long for a subheading and is trying to find a way to address this sentence in a more concise manner.
If this be of interest to you, the headline is
> A New Way to Hire
|
How about this?
> Developers and recruiters: sign up now for the best recruitment network!
|
stackexchange-english
|
{
"answer_score": 0,
"question_score": 0,
"tags": "single word requests, word choice, word usage, sentence, syntactic analysis"
}
|
Using ActionView helper class to write HTML
I am a newbie to Rails and I have seen that to write HTML code, rails provide you with hepler classes. So I am under an impression that writing HTML code directly in a rails application is not considered good.
What I did was used a form helper class to generate a form in html as follows:
<%= form_for @sub do |s| %>
<%= s.text_field :email %>
<%= s.submit 'Sign up' %>
I am a back end developer and so far it was good, but when I got the front end html the code was:
<div id="subscribe">
<form action='/subscribers' method='post'>
<input id='subscriber_email' name='subscriber[email]' type="email" placeholder="email address" required="required">
<input name='commit' type="submit" value="➔">
</form>
</div>
how can i add classes and types to tags using actionview?
|
Have a look at the documentation about the ActionView Formhelpers.
You can set the classes easily in the backend by adding the class attribute:
<%= s.text_field :email, :class => "myClass" %>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, actionview"
}
|
Merge 2 lists containing obejcts with matching ids
I have 2 lists that contain objects that look like this:
list 1:
{'name': 'Nick', 'id': '123456'}
list 2:
{'address': 'London', 'id': '123456'}
Now I want to create a third list, containing objects that look like this:
{'name': 'Nick', 'address': 'London', 'id': '123456'}
i.e, I want to find the matching id's, and merge those objects.
|
you can use `groupby` to get all the matching dicts, then unify them using `ChainMap`, like this:
from itertools import groupby
from operator import itemgetter
from collections import ChainMap
list1 = [{'name': 'Nick', 'id': '123456'}, {'name': 'Donald', 'id': '999'}]
list2 = [{'address': 'London', 'id': '123456'}, {'address': 'NYC', 'id': '999'}]
grouped_subdicts = groupby(sorted(list1 + list2, key=itemgetter("id")), itemgetter("id"))
result = [dict(ChainMap(*g)) for k, g in grouped_subdicts]
print(result)
Output:
[{'id': '123456', 'address': 'London', 'name': 'Nick'},
{'id': '999', 'address': 'NYC', 'name': 'Donald'}]
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "python"
}
|
Html.ActionLink (): new { route value} is acting strangely. I don't know where length = 17 parameter is coming from
I've this link on a page
<% = Html.ActionLink(item.Title, "Edit", "ArticleManagement",
new { id = item.ArticleDataID })%>
and a simple method to receive the article Id
public ActionResult Edit(int id)
{
//Do something
}
Unfortunately, I'm getting an error" **parameter dictionary contains a null value for parameter id of int32 for Edit(Int32)...** "
When I check the Url, I see something like " **< "
What is " **Length=17** "? and what's doing there? Anyway, so far I'm working with a collection that has only 3 items on it.
Thanks for helping
|
You need to add null as the last parameter:
<%=Html.ActionLink("Title", "Edit", "ArticleManagement",
new { id = 1 }, new { @class = "link-class", attr = "attribute value" })%>
I think it uses you route values as html attributes without the null.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 4,
"tags": "asp.net mvc, model binding"
}
|
Intersection of Two Permutations
If you are generating 2 digits codes $[X, X]$ where you have 5 choices for $X$.
The number of choices for each code is: Order matters so the total number of permutations is $n^r = 5^2 = 25$.
If for the first code the choices were [1,5], [4,8] (inclusive) and in the second code the choices were [3, 7], [2, 6].
How do you find the number of codes which are common to the first and the second?
|
Hint: For the first digit to be common, you have choices that are both $[1,5]$ and $[3,7]$. How many is that? How many choices for the second digit? Now multiply, just as you did in the example.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "combinatorics, permutations"
}
|
Implode and print_r
I want to print an array the way that print_r is printing it without the tags as a string
For example:
If I have an array:
array (
0 => 'doh',
1 => 'ray',
2 => 'me',
3 =>
array (
0 => 'fah',
1 => 'soh',
2 => 'lah',
3 => 'te',
4 => 'do',
),
)
I want to print a string with "doh ray me fah soh lah te do" (All array elements).
I tried implode() but its only returning "doh ray me"
Any suggestions?
|
$results = array();
array_walk_recursive(
$your_array,
function ($value, $key) use (&$results) {
$results[] = $value;
});
echo implode(' ', $results);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "php, arrays"
}
|
What is Dem Operation Cycle in AUTOSAR?
I am learning AUTOSAR module Dem. I am going through specification document of Dem module. I wanted to know what is Operation cycle in Dem?
|
The intention is to let you define several different operation cycles because you may have different ways of handling certain diagnostic information in different cycles.
The most typical cycle would be to have an ignition cycle and a driving cycle. That way you could have different logic for some DTCs when the ignition is on but the engine hasn't yet started, and for when the engine is up. You can also have time-based operation cycles, which restart every X minutes.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "diagnostics, autosar"
}
|
How to use KalturaMediaFilter for statusIn?
I am using kaltura java API in my project. I want to list down all deleted videos. So I am using following filter:
KalturaMediaEntryFilter entryFilter = new KalturaMediaEntryFilter();
entryFilter.statusEqual = KalturaEntryStatus.DELETED;
Now i want to list all videos with status READY and DELETED I know there is filter named "statusIn" but i don't know how to use that filter. I tried to use below combinations, but giving me an error:
entryFilter.statusIn = "KalturaEntryStatus.READY,KalturaEntryStatus.DELETED";
entryFilter.statusIn = "READY,DELETED";
entryFilter.statusIn = "ready,deleted";
Above combination does not workout. Please correct me or suggest how to use that filter.
|
Use: entryFilter.statusIn = "2,3";
See the reference of the Kaltura entry status enum: <
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "java, kaltura"
}
|
Can steady currents be time dependent?
Electrostatics/magnetostatics applies when charge density doesn't vary with time, which by the continuity equation implies div J = 0.
But do steady currents also require the current density J to not vary with time?
|
Yes. $\frac{d \rho}{dt}=0$ alone is not sufficient to ensure that $\frac{d \vec{J}}{dt}=0$. Since $\vec{J} = \rho \vec{v}$ we have
$\displaystyle\frac{d\vec{J}}{dt} = \frac {d\rho}{dt} \vec{v} + \rho \frac {d\vec{v}}{dt}$
Even if $\frac {d\rho}{dt}=0$, a non-zero $\frac {d\vec{v}}{dt}$ will produce a non-zero $\frac{d\vec{J}}{dt}$.
For example, you could have charge density $\rho$ that is constant in time and space but which oscillates backwards and forwards with velocity $v = \sin(\omega t) \vec{x}$, in which case $\vec{J} = \rho\sin(\omega t) \vec{x}$ and $\frac{d \vec{J}}{dt} = \rho \omega \sin(\omega t) \vec{x}$.
|
stackexchange-physics
|
{
"answer_score": 0,
"question_score": 0,
"tags": "electromagnetism"
}
|
JQuery - keep a div in animated state whilst hovering over a different div?
I am trying stuff that's out of my depth as usual! I'm trying to make a navigation for my new website, it's supposed to slide down when the user hovers over another div. That other div will have a graphic of some sort saying "menu". I need to nav to stay open when hovering over the "other" div or the menu div itself. So far I have it working but on a div the menu is inside, which is not really the right thing.
Is there some way to bind these two divs together or something like that? Wish I was better at JQuery!
My site is here if you would like to take a peek. The white div represents the div the user would hover over to open the menu.
Any help is welcome, thanks :D
|
Here is a working fiddle: <
here is the updated js:
$('.menu_button').hover(function() {
$('#nav').slideDown();
}, function() {
$('#nav').slideUp();
})
See html in the fiddle.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "jquery, html, jquery animate, bind"
}
|
Google Images search mouseovers, how do they work?
Pretty straightforward: Google image search has this nice UI mechanic that pops a larger-scale image with info on mouseover.
For example.
Lookbook does this too.
What would be the easiest way to replicate this effect, and what tools should I look for?
|
here's a sample i just did in 30 mins similar to my old plugin
<
it should be enough to get you started i hope. there are certain things i botched due to time
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "javascript, html, css, mootools"
}
|
List of all the applications from App Store
I am trying to build a website which will display a list of all the applications from the app store. It is similar to < But i am not getting how to get the list of all the apps. Is there any API provided by APPLE to get the list or we have to write some service to get the list ?
|
You can parse the data from the rss feeds from the apple store from the link :-
Top Free Applications:- <
Top Paid Applications:- <
There is a generator in itunes.apple.com which generates the url for the list(based on the type) you want to get. check this link for it.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "iphone"
}
|
What am I doing wrong with srand to build a non repeating random array in C++?
I am trying to build a random array of length (size1). The way that I've researched doing this is to have two separate arrays, one for my random numbers and a secondary "checking" array to make sure the numbers don't repeat. These are labeled (shuffle) and (visit) in my code respectively. count1 is an integer for counting through my for loop.
I have included the following in different combinations and it hasn't worked.
#include <ctime>
#include <time.h>
#include <cstdlib>
The code I seem to be struggling with is this:
srand((unsigned)time(0));
for (count1 = 0; count1 < size1; count1++)
{
num = (rand()%size1);
if (visit[num] == 0)
{
visit[num] = 1;
shuffle[count1] = num;
}
}
|
It is easier to fill your array with the numbers 0 to size1-1 and then shuffle those numbers.
So in c like code (haven't used c in a long time):
for (int count = 0; count < size1; count++) {
shuffle[count] = count;
}
and then shuffle it
for (int index = 0; index < size1; index++) {
int shuffleIndex = index + rand() % (size1 - index);
int temp = shuffle[shuffleIndex];
shuffle[shuffleIndex] = shuffle[index];
shuffle[index] = temp;
}
Basically, for the first element in the array, select any index and switch the values. Now the first index is randomly selected. For the second element, select a random index (excluding the first as that has already been randomly selected) and do the same. Repeat until you get to the last element.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, arrays, if statement, for loop, srand"
}
|
How are dynamic blending shadows like this created?
I would like to know, how dynamic shadows, that 'blend' onto other objects, are created.
!enter image description here
|
These can be done using shadow mapping. Basically, place the camera at the light source and render the scene into a depth buffer; the resulting buffer identifies all the lit surfaces since they are just the surfaces the light can "see". This texture is then used in the pixel shaders in the main render to mask away light on surfaces behind the shadow map. There are plenty of shadow mapping tutorials on the Web, so consult those for details.
|
stackexchange-gamedev
|
{
"answer_score": 7,
"question_score": 7,
"tags": "opengl, lighting, lwjgl, shadows"
}
|
How do I get the default mail client using Powershell?
I want to get the default mail client from Powershell script.
I know that this information is stored in the windows registry: `HKEY_CLASSES_ROOT\mailto\shell\open\command` but the `HKCR` is not available by default from Powershell.
Do you know any way to access the above key or to get the default mail client in another way?
Thanks in advance, Qinto.
|
`HKEY_CLASSES_ROOT` is an amalgamation of `HKEY_LOCAL_MACHINE\Software\Classes` and `HKEY_CURRENT_USER\Software\Classes`.
So you can do it as follows:
$node = Get-ItemProperty HKCU:\Software\Classes\mailto\shell\open\command
if (!$node) { $node = Get-ItemProperty HKCU:\Software\Classes\mailto\shell\open\command }
$MailClient = $node.'(default)'
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "powershell"
}
|
ThreeTen and parsing an Instant
I'm using ThreeTen and attempted to format an Instant. Would be easier to just split it but I'm curious, should this work? From everything I've read Instant should be parse-able, and with all the components of the pattern:
@Test
public void testInstants() {
Instant instant = Instant.now();
String dbDatePattern = "YYYY-MM-dd HH:mm:ss.SSS";
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dbDatePattern);
String dbDate = formatter.format(instant);
} catch (Exception ex) {
int dosomething = 1;
}
}
Error: org.threeten.bp.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfWeek
dd is day of month not DayofWeek. Probably getting tossed a red herring, but it seems odd.
|
The pattern letter "Y" means week-based-year in ThreeTen-Backport and JSR-310 (it meant year-of-era in Joda-Time). In order to calculate the week-based-year, the day-of-week is needed, hence the error.
Note that an `Instant` cannot supply fields for the formatter you are trying to create. Only a `ZonedDateTime`, `LocalDateTime` or `OffsetDateTime` can. An `Instant` is a special case that must be formatted using `DateTimeFormatter.ISO_INSTANT` or similar.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "java, jsr310, threetenbp"
}
|
Post or Get, which is more appropriate to call a simple asp page via jQuery Ajax
I have a html page that I need to call another asp page to get the date/hour via an ajax call. Which method would be better or best, Post or Get?
Since I am only retrieving a few bits of data and not sending any data to the page info is one method better or proper than the other?
This is the simple ASP page.
<%@LANGUAGE="VBSCRIPT"%>
<% Option Explicit %>
<%=Weekday(Date)%>
<%=Hour(Now)%>
And this is the Ajax call to the asp page above.
jQuery.ajax({
url: '/v/timecheck.asp',
type: 'GET',
cache: false,
success: function(data){
// do something with the data
},
error: function() {
//do something on error
return false;
}
})
The reason I have to make the Ajax call to this ASP page is I cannot query the server direct from this page.
|
My rule of thumb when deciding either one is:
* The interaction involve database, POST
* The interaction involve sensitive information, POST
* Requesting simple data, GET
* Sending user input, POST
* Sending/requesting large data, POST
* Clean URL, POST
As you can see, most cases involve POST for many reason. Such as in your case, you could use GET or POST. Either way, jQuery make calling both function easy.
A simpler **$.POST**
$.post("/v/timecheck.asp", function (data) {
if (data.time != "") {
//retrieve success
{
else
{
//retrieve fail
};
});
or simpler **$.GET**
$.get("/v/timecheck.asp", function(data) {
if (data.time != "") {
//retrieve success
{
else
{
//retrieve fail
};
});
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ajax, http, asp classic, vbscript"
}
|
How can I use Python from a sketch?
I'd like to be able to use Python from a sketch. According to the Arduino playground, one can use PySerial from a computer to talk with an Arduino via Python.
It looks like from that page you can also use various API's to use Python with an Arduino from a computer. However, I'd like to know if you can execute Python directly from a sketch. It would be nice because then you could execute Python directly from a sketch, and not all of it would have to be written in Python.
If this is not possible, is there an easy way to execute Python on an Arduino? Looking at the various API's it was hard to determine exactly what they did, and if you could execute a `.py` script from a computer or from anything on the Arduino.
|
> It looks like from that page you can also use various API's to execute Python directly on the Arduino.
I don't see that, at all. All those links show you how to communicate with the Arduino over serial using Python on the host side.
You'd need a python interpreter to be able to run python on the Arduino. There is the Python On A Chip project and it seems like they have support for the Mega.
> 2010/09/01 (1bdb8d31f27b) New platform: Arduino Mega.
Some more info from the PyMite page:
> any device in the AtMega family which meets these requirements: 20KiB Flash and 4K RAM, will run today
I doubt you'll find anything that'll let you mix Arduino and Python code in the same sketch.
|
stackexchange-arduino
|
{
"answer_score": 4,
"question_score": 2,
"tags": "programming, python, sketch"
}
|
How to achieve the attached view with Angular Material Table
I can't seem to achieve the form that I want using Angular Material, Bootstrap or HTML/CSS way is a piece of cake, but using AM I'm finding it hard to manipulate with custom forms.enter image description here
Link that I'm trying to achieve the form that I want <
|
Solved! The way I solved is by adding a container, header, td mat-cell and inside it create thecontent
It might not be the right approach but it will do the work
<th mat-header-cell *matHeaderCellDef> </th>
<td mat-cell *matCellDef="let element"> <img src="sdfsdf.png">
<tr>
<td><img src="Sdfsfsdf.png"></td>
</tr>
</td>
</ng-container>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "angular, angular material"
}
|
How do I programmatically change a GroupBox Header font color?
How do I programmatically change a GroupBox Header font color?
I have:
<GroupBox x:Name="gGBxOpenFile">
<GroupBox.Header>
<Label Foreground="Red">Open File</Label>
</GroupBox.Header>
</GroupBox>
I can change the contents
gGBxOpenFile.Header = "Opened"
but don 't know how to change the font color to black.
|
Add a name to the label
<Label x:Name="myLabel" Foreground="Red">Open File</Label>
Change the color
myLabel.Foreground = Brushes.Black;
And can change the content via myLabel
myLabel.Content = "Opened";
No need to name the GroupBox. This works.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "c#, wpf"
}
|
knn- same k, different result
I have a matriz ZZ. After I ran **prcomp** and chose the first 5 PCs I get `data_new`:
P= prcomp(zz)
data_new = P$x[,1:5]
then I split into training set and test set
pca_train = data_new[1:121,]
pca_test = data_new[122:151,]
and use KNN:
k <- knn(pca_train, pca_test, tempGenre_train[,1], k = 5)
a <- data.frame(k)
res <- length(which(a!=tempGenre_test))
Each time I run these 3 last rows, I get a different value in **res**. Why?
Is there a better way to check what is the test error?
|
From the documentation of `knn`,
> For each row of the test set, the k nearest (in Euclidean distance) training set vectors are found, and the classification is decided by majority vote, with ties broken at **random**.
If you don't want the randomization to occur, you could use `set.seed` to ensure the same "randomization" on each run.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "r, knn"
}
|
How to get the loaded image path in pygame
i have loaded an image file via pygame.
now i want to get this image name..
image = pyagme.image.load(image)
now i'm looking for something like this:
print image.path()
Any suggestions?
|
A `Surface` in pygame has no knowledge about how it was created (manually/loaded from file or string/etc.).
Since you already know the path of the image when you load it, just keep it (don't overwrite the variable).
image_path = "/some/path/to/image.png"
image = pyagme.image.load(image_path)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -3,
"tags": "python, pygame"
}
|
Probability that the size of a subset is "above expected"
I am reviewing a paper claiming the following statement, and since I'm not familiar with probabilities beyond basic stuff, it puzzles me a lot:
We have a "universe" set $U$ of size $n$ and a subset $S$ of $U$. Each element of $U$ has probability $p$ (a constant) of belonging to $S$. The claim is that, with probability $p$, the size of $S$ is at least $p\cdot n$.
Is there a black-box theorem to justify this? And if it's relevant, there is no proof that the events are actually independent (they _might_ be though, It'd need some work to decide for sure).
|
If the choices of elements is independent, the statement is not true. Let $p=1-\frac 1{n}+\frac 1{10^n}$. We can only have $|S|=n$ to meet the constraint, so every element must be in $S$. The chance of this is $p^{n}\approx 1-e\lt p$ The only way it can be true with this $p$ is if you choose all the elements as a group with probability $p$ and none of them with probability $1-p$ or something close to that.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "probability"
}
|
What is the solar system orientation to its direction of travel?
I saw the picture and seem incorrectly drawn. Its shows the the edge of the solar system leading facing the Heliosheath. It would not be like NASA to post something as incorrect as this. The solar system should at 60 degrees to the direction of travel? I'm not sure maybe this picture is correct? , the Solar System is moving approximately edge-on through the gas cloud as in the NASA diagram.  and A. Fujii)
|
stackexchange-astronomy
|
{
"answer_score": 6,
"question_score": 2,
"tags": "solar system, astrophysics"
}
|
How to set initial size of std::vector?
I have a `vector<CustomClass*>` and I put a lot of items in the vector and I need fast access, so I don't use list. How to set initial size of vector (for example to be 20 000 places, so to avoid copy when I insert new)?
|
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
|
stackexchange-stackoverflow
|
{
"answer_score": 232,
"question_score": 165,
"tags": "c++, stl"
}
|
WebPack 2 nested SCSS
I can't figure out why my nested `SCSS` code does not work.
**Example of nested SCSS**
.line {
.right {
top: 0;
height: 100%;
width: 20px;
}
}
**Webpack2 loader**
exports.scss = {
test: /\.scss$/,
loaders: ['style-loader', 'css-loader?modules&importLoader=2&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]!sass-loader' ]
}
If I write it like this then it works
.line.right {
top: 0;
height: 100%;
width: 20px;
}
*I don't want to extract to another file for now.
|
What you are missing is the `&`
.line {
&.right {
top: 0;
height: 100%;
width: 20px;
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "css, module, webpack, sass, webpack style loader"
}
|
Yii выпадающее меню
Вот есть такое меню:
<?php $this->widget('zii.widgets.CMenu',array(
'items'=>array
(
array('label'=>'Регистрация', 'url'=>array('/user/registration'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Вход', 'url'=>array('/user/login'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Выход ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest),
array('label'=>'Управление', 'url'=>array('/'), 'visible'=>Yii::app()->user->name=="admin"),
array('label'=>'Профиль', 'url'=>array('/user/profile'), 'visible'=>!Yii::app()->user->isGuest),
),
)); ?>
При наведении на пункт УПРАВЛЕНИЕ должно выпадать меню. Как это реализовать с помощью CSS, знаю, но как в вышеуказанном коде показать те подпункты, что должны выпасть?
|
У каждого пункта есть `items` работающий аналогично
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "yii"
}
|
Why did Arrow play homage to Blue sky?
Why did Arrow play homage to Breaking Bad in S02E06 by showing Blue Sky?
 {
axios.get(`
.then(res => {
const posts = res.data;
this.setState({ posts });
})
};
i got error
Access to XMLHttpRequest at ' from origin ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
doamin.com/api/v1/categories:1 Failed to load resource: net::ERR_FAILED
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)
Please Fixed my issue . Thanks in advance
|
i have check your request is there is no issue with your api. Please add some code in your server side .htaccess file and check it
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "reactjs"
}
|
What does default CSS's browsers depend on?
Hi (please excuse me for my ugly english ;-) )
Do you know if the default CSS of any user agent ... :
* depends on its release number ?
* depends on its layout engine ?
* depends on the release number of its layout engine ?
* depends on the OS ?
* depends on the OS release number ?
If yes (for any choice), have you any example do demonstrate it ?
Thank you very much. :-)
|
It only depends on the browser make/version. You can find here an overview of default styles.
The main differences are in the margins of the block elements. One would recommend to use a CSS reset sheet to clean it up, but I'd just specify the margin for every actually-to-be-used block element yourself.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "html, css, browser, user agent"
}
|
Configuration for Serilog.Sinks.MySQL when using appsettings.json file
I added Serilog to my app and the Console Sink works great. I then added the MySQL sink to the configuration. My settings are:
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.MySQL" ],
"MinimumLevel": "Debug",
"WriteTo": [
{ "Name": "Console" },
{
"Name": "MySQL",
"Args": {
"connectionString": "server=<server>;uid=<username>;pwd=<password>;database=logging_database",
"tableName": "logging",
"storeTimestampInUtc": true
}
}
],
}
I'm able to access the database with phpMyAdmin, so I know it's working.
The error that I get is:
Error: 0 : Unable to connect to any of the specified MySQL hosts.
Has anyone seen this or know how to fix it????
|
The issue appears to be with name resolution. The MySql server I was connecting to was being hosted on another server. I threw together a quick installation on a spare machine and just used IP address and it worked fine. So, on a hunch, I tried using the IP address instead of the name and it worked.
I also had to add SslMode=none into the connection string. I discovered that the sink doesn't gracefully handle connections that don't support SSL.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "mysql, serilog"
}
|
valueChanged event listener java swing = why double clicked?
I got little problem, with selecting item from JList. I use valueChanged ListSelectionListener but when i select any item it is clicked twice and i need it to be clicked only once. Are there any other action listeners which can do it?
this problem:
![
Full code there: <
|
Read the section from the Swing tutorial on How to Write a ListSelectionListener
You need to check the `getValueIsAdjusting()` method of the `ListSelectionEvent` and only do your processing when the value returns false.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, swing, actionlistener, jlist"
}
|
Finding the limit of curvature equation
Given the equation y = $e^x$ and the curvature, $\kappa = e^x/(1+e^{2x})^{3/2}$
(b) Find the $\lim\limits_{x \to\infty} = e^x/(1+e^{2x})^{3/2}$
|
$$\frac{e^x}{(1+e^{2x})^{\frac{3}{2}}} < \frac{e^x}{e^{3x}} = \frac{1}{e^{2x}} \to 0\ \textbf{as} \ x \to \infty$$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "calculus, multivariable calculus, curvature"
}
|
Store images temporary in Google App Engine?
I'm writing an app with Python, which will check for updates on a website(let's call it A) every 2 hours, if there are new posts, it will download the images in the post and post them to another website(call it B), then delete those images. Site B provide API for upload images with description, which is like:
`upload(image_path, description)`, where `image_path` is the path of the image on your computer.
Now I've finished the app, and I'm trying to make it run on Google App Engine(because my computer won't run 7x24), but it seems that GAE won't let you write files on its file system.
How can I solve this problem? Or are there other choices for free Python hosting and providing "cron job" feature?
|
GAE has a BlobStore API, which can work pretty much as a file storage, but probably it's not what you whant. Actually, the right answer depends on what kind of API you're using - it may support file-like objects, so you could pass urllib response object, or accept URLs, or tons of other interesting features
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "python, google app engine, hosting"
}
|
Regex matching specific url
I'm trying to test if a url with a wildcard at the end matches with another one.
^http?://(?:www\\.)?lichess\\.org/?.*
is my regex, I want it to match with < everything after .org/ should be random.
Sorry for the inconvenience.
|
Try this:
/(http:\/\/en\.lichess\.org\/)((?:[a-z][a-z0-9_]*))/i
Like This:
var string = '
var match = string.match(/(http:\/\/en\.lichess\.org\/)((?:[a-z][a-z0-9_]*))/i);
if(match && match.length){
console.log('Match Found');
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "javascript, regex"
}
|
Unable to solve "The type name 'Models' does not exist in the type 'NotificationApp'" Error after some command execution
I was running command below:
dotnet new page -n Index -na myapp.Pages.Area -o Pages/Area
ns=-na=myapp.Pages
dotnet new page -n Index $ns.Area -o Pages/Area
And it eventually caused the error:
> Views/_ViewImports.cshtml(1,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'NotificationApp' is a type not a namespace. Consider a 'using static' directive instead [/home/seocliff/Desktop/dotNetProjects/NotificationApp/NotificationApp.csproj]`
Now everytime I run `dotnet build` or `dotnet run` above error keeps appearing. Any solution?
|
I removed the namespace lines within `_ViewImports.cshtml`:
@using NotificationApp
@using NotificationApp.Models
I also removed related files to "ErrorViewModel", like the following:
**ErrorViewModel.cs** within `Views/Home/Shared`
**Error.cshtml** within `Views/Home/Shared`
Also I had temporarily commented **Error** Action Method:
// public IActionResult Error()
// {
// return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
// }
Then I run `dotnet build` and then launch the app again with `dotnet run`. It all worked out well. I will further investigate how it cause this issue as I unable to find a proper answer
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net core"
}
|
Rescaling standardised parameters fitted through gradient descent
As a learning exercise, I have been implementing multiple linear regression from scratch using gradient descent to fit the parameters.
Following the conventional approach to the algorithm, I have managed to dramatically speed up the convergence by standardising all of the features such that they have mean 0 and standard deviation 1 according to the formula: $$x' = \frac{x-\bar{x}}\sigma$$
My question is: is there an easy approach to rescale the resulting intercept and parameters such that they can take a vector of feature values and predict a value for Y all in the original scale?
|
You have standardized each feature of $x=(x_1,x_2,\dots,x_n)$ like this $$x_i' = \frac{x_i-\bar{x_i}}{\sigma_{i}}$$ Your resulting regression is $$ \frac{y-\bar{y}}{\sigma_{y}} = \alpha_0+\sum_{i=1}^{n}\alpha_i\cdot x_i' =\alpha_0+ \sum_{i=1}^{n} \alpha_i \frac{x_i-\bar{x_i}}{\sigma_{i}}=\sum_{i=1}^{n}\alpha_i\frac{x_i}{\sigma_{i}}+\left(\alpha_0-\sum_{i=1}^{n}\alpha_i\frac{\bar{x_i}}{\sigma_{i}}\right)$$ Which implies $$ y = \sum_{i=1}^{n}\sigma_{y}\alpha_i\frac{x_i}{\sigma_{i}}+\sigma_y\left(\alpha_0-\sum_{i=1}^{n}\alpha_i\frac{\bar{x_i}}{\sigma_{i}}\right)+\bar{y}$$
Thus, you can use $\beta_i=\frac{\sigma_y\alpha_i}{\sigma_i}$ and intercept $\beta_0=\sigma_y\left(\alpha_0-\sum_{i=1}^{n}\alpha_i\frac{\bar{x_i}}{\sigma_{i}}\right)+\bar{y}$
|
stackexchange-stats
|
{
"answer_score": 0,
"question_score": 2,
"tags": "regression, multiple regression, gradient descent"
}
|
Cron job to back up mysql
I have a Fedora server with a USB backup drive connected to it. I have managed to mount the drive and want to run a daily backup of my MySql database. I am completely new to cron jobs and really need some help please.
Cheers.
|
The crontab syntax is really easy to understand. Just try it.
For the backup of your MySQL databases you could just use `mysqldump` which is shipped with MySQL. There are more sophisticated means of making backups of a MySQL database but `mysqldump` should just do fine for you.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 0,
"tags": "mysql, backup, cron"
}
|
Use that $ (\mathbb{Z}/p\mathbb{Z})^{*} $ is cyclic to give a direct proof that $ \left( \frac{-3}{p} \right) = 1 $ when $ p \equiv 1\ (\bmod\ 3) $.
> Use that $ (\mathbb{Z}/p\mathbb{Z})^{*} $ is cyclic to give a direct proof that $ \left( \frac{-3}{p} \right) = 1 $ when $ p \equiv 1\ (\bmod\ 3) $.
>
> (Hint: There is an element $ c \in (\mathbb{Z}/p\mathbb{Z})^{*}$ of order 3. Show that $ (2c+1)^2 = -3 $.)
I could really use some help with some direction on where to start with this proof. I've gone through a some examples and I can see that it works, but I can't seem to prove it for the general case.
Any responses would be much appreciated!
|
Hint: Since $c$ is a third root of unity, $c$ is a root of $x^3-1$ in $\mathbb F_p = \mathbb Z/p\mathbb Z$. Moreover, $c \neq 1$, so $c$ is a root of the polynomial obtained by factoring $x-1$ out of $x^3-1$, which is $x^2+x+1$. (Note that you can only do this factoring because $\mathbb F_p$ is an integral domain.)
Use the fact that $c^2+c+1=0$ to simplify $(2c+1)^2$.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 0,
"tags": "group theory, number theory, cyclic groups, legendre symbol"
}
|
Como alterar código do Bootstrap 3?
É possível eu editar do meu gosto alguma parte de um código CSS do Bootstrap? Se sim, como?
|
É possível sim. Basta abrir o código no seu editor de preferência e mandar ver.
Todo desenvolvedor tem sua IDE preferida, mas você pode alterar até no bloco de notas em uma emergência (ou se for masoquista).
E como o repositório do fonte do boostrap é o Github, você também pode criar uma conta lá, fazer um _fork_ do projeto e editar a sua cópia online. O endereço do fonte é esse:
<
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 2,
"question_score": 5,
"tags": "css, bootstrap 3"
}
|
Having trouble finding element on page with xpath
I am trying to access the data as shown below.
!HTML code
I am using this command to capture the information but to no avail. Does anyone have any tips on where I'm going wrong?
Code trials:
posts = firefox.find_elements_by_xpath(//*[@id="flotGagueValue0"])
print(posts)
for post in posts:
print(post)
|
You are looking for ".text".
posts = firefox.find_elements_by_xpath(//*[@id="flotGagueValue0"]) print(posts) for post in posts: print(post.text)
I would write it like this for readability:
posts = firefox.find_elements_by_xpath(//*[@id="flotGagueValue0"])
for post in posts:
print(post.text)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "selenium, xpath, web scraping"
}
|
How can I save the content of a rich text box even when the form closes?
This is my first post here, so please don't judge me if I write something wrong ^^
Anyways, I've recently run into an issue with richtextboxes in Visual Basic .NET and WinForms. Let's say I have a Main form and a Log form. The log form contains a richtextbox which functions as a log. From the main form I'm writing text to the log and I also format the lines, so they have different colors (blue for information, red for error). Unfortunately, whenever I close and reopen the log form all text that has been written to it is lost. I've tried saving it to a text file, but that doesn't save the colors of the text.
Is there any way I can save the text and the colors of the lines even when the form closes?
|
Here's what the excellent suggestion from Shrotter might look like:
Public Class Form1
Private RtfPath As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim folder As String = System.IO.Path.GetDirectoryName(Application.ExecutablePath)
RtfPath = System.IO.Path.Combine(folder, "RtbData.rtf")
If System.IO.File.Exists(RtfPath) Then
RichTextBox1.LoadFile(RtfPath)
End If
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
RichTextBox1.SaveFile(RtfPath)
End Sub
End Class
Of course, you should always wrap the loading/saving of the file in a Try/Catch block in case anything goes wrong.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "vb.net, visual studio, winforms, text, richtextbox"
}
|
VIF values and interactions in multiple regression
I am running a multiple regression of the form y~a+b+c+ab+ac+bc
I have checked the VIF values for the direct effects - should I check them for the interactions?
I am assuming not as that would equate to looking at the multicolinearity between a variable and itself (albeit in an interaction) which will surely be very high?
|
I go with Penguin_Knight. You will check interaction term also for VIF but you can ignore high values of VIFs here when you use interaction. You can further check for the detailed overview here:
<
|
stackexchange-stats
|
{
"answer_score": 6,
"question_score": 8,
"tags": "r, multiple regression, multicollinearity, variance inflation factor"
}
|
Is there any standard firestore query to get random documents?
I am trying to get multiple random documents from a dynamic collection. Until know, I have thought to do it using simple queries, something like this:
Pseudocode
arr = [];
while (arr.length < 5) {
// Start the query at a random position
startAt = Math.random() * collection.size;
randomDoc = await dbRef.startAt(startAt).limit(1).get( ... );
arr.push(randomDoc);
}
Here, firstly, I have to get the collection size, as it can be 0 or bigger. Then, select a random document using a kind of "db random pointer/index".
My question is if there is any way to get the same result but without all the loop stuff, only with the query syntax.
Thank you.
|
Clever use of startAt and limit!
As you can see in the reference, there are no built-in methods that would return random documents.
In order to avoid the loop, you can use Promise.all:
const indices = getRandomIndices(collection.size);
const docs = await Promise.all(indices.map(i => {
return dbRef.startAt(i).limit(1).get();
}));
And for the getRandomIndices, I suggest: create an array [0, 1, 2, ...], shuffle it as describe in this SO answer, and slice its 5 first elements.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "javascript, firebase, google cloud firestore"
}
|
using .bashrc to keep X11 forwarding
When I switch to root (sudo su), I first have to run `xauth list` as myself then `xauth add <last entry from xauth list>` once I'm root. I found a great little tip to make this easier by running `xauth add $(xauth -f ~<my username>/.Xauthority list|tail -1)`. This is nice, but I wanted to automate it.
So, I went into /root/.bashrc and added this: `xauth add $(xauth -f ~$SUDO_USER/.Xauthority list|tail -1)`
Unfortunately, that gives the error `error in locking authority file ~<my user>/.Xauthority`
It works if I just replace $SUDO_USER with my username. Clearly $SUDO_USER is set correctly because it knows to look for the correct authority file. So, what's going on here?
|
`~` expansion is done before variable interpolation. If you do a strace, you will see that the actual error is `No such file or directory`
openat(AT_FDCWD, "~<myuser>/.Xauthority-c", O_WRONLY|O_CREAT|O_EXCL, 0600) = -1 ENOENT (No such file or directory)
write(2, "xauth: error in locking authori"..., 62xauth: error in locking authority file ~<myuser>/.Xauthority
use `/home/$SUDO_USER/.Xauthority` instead
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "bash, x11, sudo"
}
|
Android Display .Doc File in WebView?
In my app,I have link < I want to view in webview ,I try with google document viewer its work fine But i need it without google document viewer,How to show it??
|
you can use the js for google Doc viever
myScript="<html><iframe src='
url='
id=28'&embedded='true' style='width:600px; height:500px;'
frameborder='0'></iframe></html>"
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadData(myscript,"text/html", "UTF-8");
you can use myscript as string variable and use this javascript code(please make sure to remove double quite if above code) and load in webview
* You can change the url - width- height variables according to your scripting.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "android, android webview, doc"
}
|
Most lightweight webservice framework to mock external Webservice in Scala
I am trying to test a component which relies on an external webservice, which I access through Play WS library. This components receive the url of the webservice.
I would like to unit test the component by getting it connected to a fake webservice.
Which scala web frameworks would be more suitable for the purpose?
|
I failed to find something simplier than scalatra. Although code on main page is **really simple** you would have to do some extra work to embed scalatra in your own app/tests.
import org.scalatra._
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.webapp.WebAppContext
private class Mocker extends ScalatraServlet {
get("/somepath") {
<h1>Mocked response</h1>
}
}
// ↓ you won't need that part if you start jetty as sbt command
private val jetty = new Server(8080)
private val context = new WebAppContext()
context setContextPath "/"
context setResourceBase "/tmp"
context addServlet(classOf[Mocker], "/*")
jetty.setHandler(context)
jetty.start
Standalone app is really that simple.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "web services, scala, scalatra"
}
|
Thinkpad USB Dock 3.0 screens and network stops working after Windows 10 update
As the title says my dock stopped working after a Windows Update this morning. Keyboard and mouse works but not RJ45 and no screen. Has anyone experienced this?
What I have tried:
Downloaded latest drivers from Lenovo:
<
When this did not work I tried updating from DisplayLink:
<
Info:
> Thinkpad USB Dock 3.0 DU9019D1
Current OS version:
> Windows 10 Pro Version 1703 OS Build 15063.483
|
Solved it like this:
I have a Elitebook 840, found out Gen version by looking at my CPU. In my case it is a i7-5600U which is a Gen 2. Downloaded the latest Bios drivers from HP and after upgrade everything worked:
<
 where some of cells are merged? For example, I want to extract the data as follows:
List<List<string>> data = new();
data.Add(new() List<string> {"something", "418", "The value"});
data.Add(new() List<string> {"something1", "400", "The value"});
...
and so on. The problem arises with merged cells - how can I get the count of merged cells and its value? How do I get the items that are in the merged cells range (something, 418, something1, 400 etc.?
If there are better techniques to extract the data (there for sure are), it would be really helpful to receive a good tip for that.
Any answer is highly appreciated.
.MergeArea.Rows.Count;
To get value of Cell merged:
string val=oSheet.Cells(iRow, iCol).MergeArea.Cells(1,1).Value;
To get first row of Cell Merged:
int iRow1=oSheet.Cells(iRow, iCol).MergeArea.Cells(1,1).row;
if iRow != iRow1 , it is row merged to iRow1
To read your excel: ex:
For int iRow = 1 To oSheet.UsedRange.Rows.Count
string val1=oSheet.Cells(iRow, 1).Value;
string val2=oSheet.Cells(iRow, 2).Value;
string val3=oSheet.Cells(iRow, 3).MergeArea.Cells(1,1).Value;
//Add value to List
Next
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, excel"
}
|
Ruby on rails, deactivation of a user
I am using sorcery gem for user authentication. My model is:
create_table "users", :force => true do |t|
t.string "email", :null => false
t.string "crypted_password"
t.string "salt"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "remember_me_token"
t.datetime "remember_me_token_expires_at"
t.string "activation_state"
t.string "activation_token"
t.datetime "activation_token_expires_at"
end
I could not find in the internet if there is a built-in function for deactivating a user. Will it be safe to find a user and just change the parameter `activation_state` to inactive?
|
You can call
`user.setup_activation`
it will set `activation_state` to 'pending' and create new `activation_token`.
Or you can set `activation_state` to 'pending' manually. That's all.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, sorcery"
}
|
Element.insert at bottom-1 with prototype
I want to insert an Element at the position bottom -1 of his parent.
The following code insert at the bottom
el.insert({bottom: content})
thanks
|
You can insert it "before the last child element" like this:
el.select('*').last().insert({before:content});
`el.select('*')` gives the child elements in a nice prototype-extended collection.
`last()` of course retrieves the last element of that collection. You might want to retrieve it separately and make sure it is not `undefined` (which is what will be returned if there are no children) before attempting to "insert before it".
Also, IMO it feels better to pass in a non-wildcard selector if possible. For example, when the containing element is an `<ul>`, pass in `'li'`.
Links:
Prototype Element#insert
Prototype Array#last
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "javascript, prototypejs"
}
|
cloning full site to local include images CSS file
I want to clone a site and keep file structure as site original, like have CSS folder, images folder etc. all things are the same on the web, is there some tools can achieve this, I have tried:
wget -m
but it's seem didn't contain CSS, JS file because they in a different sub-domain like tech.xxx.com
|
I've used DownloadThemAll! FireFox add-on and it works pretty well.
<
!DownloadThemAll! Screen Shot
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "clone, wget"
}
|
Detecting the end of an https message
i am trying to implement a non blocking SSL connection using nio sockets & SSlEngine. Unfornetly the message must contains enough data so it can be decrypted by the sslengine. And i am wondering how does a normal SSLSocket in blocking mode know that the https message have fully arrived??
Is there any flag announcing the end a https message/packet?
Thanks
|
SSL packs the data into records and each record contains the size at the beginning. So the SSLengine itself knows how many data it needs. According to < a call to `unwrap` would return `BUFFER_UNDERFLOW` if the record is not fully read and thus can not be decrypted and you need to read more data from the connection in this case.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sockets, rest, http, ssl, nonblocking"
}
|
Is it possible to send email with only jQuery?
Can I send email using jQuery only? I don't have .Net or PHP etc running on the site.
|
You can not send email with Jquery. You will have to use sever-side language such as `php`, `asp.net` etc. Since you don't have these already installed, you will have to install them to be able to actually send emails. Also, even if you have these installed, you will still need an email sending mechanism, for example email settings at your host where you upload your site.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 2,
"tags": "jquery"
}
|
Is it possible to merge two MySQL databases into one?
Lets say I have two MySQL databases with some complex table structures. Neither database has the same table name. Lets say these tables contain no rows (they do but I could truncate the tables, the data is not important right now, just testing stuff). Lets say I need these 2 databases merged into one. For instance:
DB1:
cities states
DB2:
index subindex posts
I want to end up with a single DB that contains:
cities states index subindex posts
Is this possible?
|
You can use `RENAME TABLE` on all the tables from one of the databases.
See: <
RENAME TABLE current_db.tbl_name TO other_db.tbl_name;
Providing there are no duplicates.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "mysql, database"
}
|
Excluding collections from view layer using script
Hello Im working on really big project and I need to exclude all collections from layerand reverse using script I tried this
import bpy
coll = bpy.data.collections
for c in coll:
c.exclude = False
But it doesnt seem to work, any ideas where it went wrong or how to solve my problem? Any help is appreciated.
|
You need to use refence from view_layer.layer_collection:
import bpy
vl_colls = bpy.context.view_layer.layer_collection.children
# toggle
for coll in vl_colls:
coll.exclude = not coll.exclude
# Layer collection vs Collection:
reference
* LayerCollection(bpy_struct)
* Collection(ID)
[![!\[\]\(outliner.png\)](
## Properties of LayerCollection(bpy_struct):
[![!\[\]\(layercoll%20props.png\)](
* Exclude: `.exclude`
* Hide in Viewport: `.hide_viewport`
* Holdout: `.holdout`
* Indirect Only: `.indirect_only`
Accessed through `bpy.context.view_layer.layer_collection.children`
## Properties of Collection(ID):
[![!\[\]\(coll%20props.png\)](
* Disable Selection: `.hide_select`
* Disable in Viewport: `.hide_viewport`
* Disable in Render: `.hide_render`
Accessed through `bpy.data.collections`
|
stackexchange-blender
|
{
"answer_score": 6,
"question_score": 3,
"tags": "python"
}
|
What is stored in the modelview matrix?
I have been trying to learn more about matrices in opengl; right now I'm stuck trying to understand where things are stored inside the modelview matrix. (location,scaling,rotations etc) This is obviously very important as understanding matrices is one of the first steps to fully understand modern opengl.
I have been trying to find some good articles, and I've currently found 2: (1,2)
However, I stil don't understand where the values are stored; any help is very appreciated (links, pinpointers etc)
|
Here is a reference of how different (affine) transformation matrices are constructed:
**Identity** :
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
**Translate** (x, y ,z):
1 0 0 x
0 1 0 y
0 0 1 z
0 0 0 1
**Scale** (sx, sy, sz):
sx 0 0 0
0 sy 0 0
0 0 sz 0
0 0 0 1
**Rotate along x axis** (by angle t):
1 0 0 0
0 cos(t) -sin(t) 0
0 sin(t) cos(t) 0
0 0 0 1
**Rotate along y axis** (by angle t):
cos(t) 0 sin(t) 0
0 1 0 0
-sin(t) 0 cos(t) 0
0 0 0 1
**Rotate along z axis** (by angle t):
cos(t) -sin(t) 0 0
sin(t) cos(t) 0 0
0 0 1 0
0 0 0 1
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "opengl, matrix"
}
|
Making two http requests sequentially in angular, rxjs
Currently I have the following request:
return this.registrationService.registratePerson(data).pipe(
switchMap(
res => {
return this.registrationService.sendPassportScan(this.form.value.passportScanCopyFile, res.AisUserIsn);
}
)
);
The second request makes use of the result obtained in the first one, that's something that I need but the problem with it is that now it returns what comes from the second request (the inner one). Is it possible somehow with the help of rxjs operators to make it return an observable containing fields from the inner request as well as those from the outer one?
In the application the 5th version of rxjs is used.
|
Sure. Something like this:
return this.registrationService.registratePerson(data).pipe(
switchMap(
res => forkJoin(
of(res),
this.registrationService.sendPassportScan(/* relevant args */),
)))
(The resulting stream will contain a 2 element array).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "angular, rxjs5"
}
|
SharePoint Workflow: Standard vs Enterprise
I've started at a new company recently and I've heard some people from other business units say that one of the reasons they chose Enterprise license CALs over Standard is "you can do more with SharePoint workflows".
This surprised me, and was the first time I heard or read this any where.
Is this true?
|
The only way I could see this holding water is if they are referring to workflows revolving around publishing. Foundation, Standard, and Enterprise all run the same workflow engine and have access to the same actions.
|
stackexchange-sharepoint
|
{
"answer_score": 1,
"question_score": 1,
"tags": "2013, workflow, enterprise, standard, license"
}
|
Is there any reasonable way to crawl the code snippet from answers in Stackoverflow?
As the title tells, I want to known whether there is a promising way to detect code blocks in technical website like Stackoverflow. Detecting the pattern of DOM tree seems to be not a good one as the layout could be changed in the future.
|
The stackexchange API may be what you are searching for.
Using stack apps, you can gather some user-submitted data easily.
Stack Apps even has it's own community where you can ask specific questions.
You can extract answers to specific questions using the /answer GET API.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, web crawler"
}
|
How to initialize an Option array to None in Scala
I have defined a class in Scala (2.9.1) as follows:
class A(val neighbors: Array[Option[A]]) {
def this() = this(new Array[Option[A]](6))
// class code here ...
}
My problem is that neighbors is initialized with nulls, when I would like it to be initialized with `None`. I tried this, but the compiler complains with the error message "not found: type None":
class A(val neighbors: Array[Option[A]]) {
def this() = this(new ArrayNone)
// class code here ...
}
I can do this, which gives the desired behavior, but it doesn't seem very elegant:
class A(val neighbors: Array[Option[A]]) {
def this() = this(Array(None, None, None, None, None, None))
// class code here ...
}
So, my question is, what is the best way to do this?
EDIT: I am referring to the behavior when `new A()` is called.
|
The easiest way to do this would be
Array.fill(6)(None:Option[A])
Additionally you can change your class's constructor to take a default parameter like this:
class A(val neighbors: Array[Option[A]] = Array.fill(6)(None))
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 6,
"tags": "arrays, scala, constructor"
}
|
Delete user shows error code (Ubuntu 17.10 )
When i'm trying to delete user with this code `sudo deluser username` than this message occurs
Warning: group `username' has no more members.
userdel: user username is currently used by process 14804
/usr/sbin/deluser: `/usr/sbin/userdel username' returned error code 8 Exiting.
so, what can i do for that ??
|
The process with PID 14804 is running as user `username`. This process has to terminate before you can remove the user. You can use
ps -o pid,args -p 14804
to see what this process is and
sudo kill -9 14804
to kill it if you are sure you don't need it any more and there's no better way to terminate it.
The "Warning" says that there's a group named `username` of which user `username` is the only member. You probably want to remove it, too:
sudo delgroup username
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sudo, users"
}
|
Making a new list from an existing list
Basically just looking if there is an easy way to reverse the list. People were getting to confused with my original question.
This was the list: `words = ['hey', 'hi', 'hello', 'hi']` How to reverse it (to a new list) and only add to new list if it is not already in it.
|
This snippet iterates through the list of words in reverse; and adds new unique entries to a new list.
words = ['hey', 'hi', 'hello', 'hi']
result = []
for word in reversed(words):
if word not in result:
result.append(word)
print(result)
Output
['hi', 'hello', 'hey']
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "python, list"
}
|
Google Play Protect
With Android 8 (Oreo), Google is promoting this feature
* Google Play Protect: Working to keep your device and data safe from misbehaving apps by **scanning over 50 billion apps per day** , even the ones you haven't installed yet!
My question is: how do they scan 50b apps/day if Google Play store doesn't even have that many apps? A quick look at this shows there is roughly 3.5 million apps in their store as of late 2017 <
|
oh, I think that includes apps already installed on people's phones. I believe there is 2+ billion Android users out there
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "android, google play"
}
|
Why Comparison Of two Integer using == sometimes works and sometimes not?
I know that i am comparing reference while i'm using == which is not a good idea but i did not understand why is this happening.
Integer a=100;
Integer b=100;
Integer c=500;
Integer d=500;
System.out.println(a == b); //true
System.out.println(a.equals(b)); //true
System.out.println(c == d); //false
System.out.println(c.equals(d)); //true
|
The Java Language Specification says that the wrapper objects for at least -128 to 127 are cached and reused by `Integer.valueOf()`, which is implicitly used by the autoboxing.
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 3,
"tags": "java, types, comparison"
}
|
Generate preview images with custom text?
I´m working on a webshop where you can personalize Glasses, Pens etc. with gravures...
We also want a "Preview" function like in this shop (click on "Vorschau"): <
They are generating the preview images through this link:
**What is a .dtm file and how can I implement this feature on my website?**
Thanks in advance!
|
They are using a custom program (a cgi script is like a program) called webproducer to render that preview. The .dtm extension is meaningless, those requests are being responded as images.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, image, web, dynamic image generation, image generation"
}
|
How to get values of query parameters
I have an url `www.xyz.com/?R1=xxx&R2=yyy&R3=zzz`
How can i get value of query parameters `R1`, `R2` and `R3`?
I am beginner in Meteor.
|
This is not Meteor-specific and depends on your router. Here are some links to the section about query parameters for each of the most common routers used in Meteor:
* Iron Router
* Flow Router
* React Router
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "meteor"
}
|
where is the yellow warning icon in ie9
does anyone know how do we enable the yellow warning icon in ie 9?
I need to see the errors for a website (the website is deployed, and not on localhost)
|
Click the gear at the top right and choose Internet Options, then go to the Advanced tab and uncheck the "Disable script debugging (Internet Explorer)" option. After applying your settings it should now attempt to debug any errors it comes across.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "javascript, debugging, internet explorer 9, javascript debugger"
}
|
Is there a canon explanation for why Star Trek away teams don't wear environmental suits?
Last night I was watching the TNG episode "Relics", where Riker, La Forge and Worf beam aboard a disabled 75-year-old ship with minimal life support. Upon arrival, Riker takes a tricorder reading and reports that the air is "stale" but breathable. Outside of the obvious reasons of production costs and actor comfort, is there any reason why away teams would be allowed to beam into a relatively unknown environment without being required by regulations to wear an environmental suit (or at least bring along some spare oxygen)?
|
I'm not sure of how "unknown" the atmospheric conditions aboard the ship were. They always scan for an atmosphere first and Starfleet officers trust their technology almost implicitly. If they beam over then they're probably already confident that they are not in danger. The tricorder checks are just to make sure.
There reaches a point when you have to assume that they have the same common sense that you do, even if it's not shown on-screen.
Besides, the transporter keeps the story moving faster than a shuttle.
|
stackexchange-scifi
|
{
"answer_score": 16,
"question_score": 31,
"tags": "star trek, star trek tng"
}
|
Collection Wrapper as JSON List?
I need to wrap a `List<Something>` in a DTO (say, `Wrapper`) so that some custom annotations work as expected. I end up with this:
public class Wrapper {
private List<Something> list;
@CustomAnnotationsHere
public List<Something> getList() { ... }
public void setList(List<Something> list) { ... }
}
However, this makes Jackson serialize/deserialize the `Wrapper` object as
{
"list": [...]
}
which, IMHO, is too verbose and unnecessarily complex. Is there any way to have Jackson serialize/deserialize this `Wrapper` object as a list (the value of the `list` field)?
I would swear I once came across an annotation-based way of achieving this, but at the moment I can't recall where.
|
Add `@JsonValue` to the field for serialization, and a single-argument constructor for deserialization?
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "jackson"
}
|
Code shared by multiple controllers and models -- where is the best place to keep it?
So this is a newbie rails design question. Lets say I want some of my common functionality to be sitting in a set of helper classes (either as class methods or instance methods).
And I want to use these helper objects inside controller (not view) or even may be a model. can I do that? how? Does it have to be a module or class or can be anything?
Is there rails specific pattern for this?
|
If their are not tied to one of the three tiers, you should place them in the /lib directory.
The convention under /lib is that you should name your folders as modules, and files and classes, and that you should always try to encapsulate your additional behavior in modules. Let's say, you have some class
module MyModule
class MyHelperClass
end
end
You should put it into /lib/my_module/my_helper_class.rb
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "ruby on rails, ruby, helper"
}
|
Visit The College of Winterhold quest uncompletable?
When you meet Faralda at the bridge to the College of Winterhold, there is an option to persuade her to let you across the bridge. However, if you succeed, the misc. quest "Visit The College of Winterhold" will not complete and will never be completeable. Is there a way to fix this, with a console command/etc? I'm playing on PC.
|
use the console command
setstage MG01Pointer 200
to complete this quest.
|
stackexchange-gaming
|
{
"answer_score": 6,
"question_score": 7,
"tags": "the elder scrolls v skyrim"
}
|
Why a working script does not execute as a cron job?
I wrote a script to backup a database. When I execute it directly, it works. I tried to make it a cron job and while it runs (I checked with `service status cron`) it seems that it silently fails.
Here is the script:
#!/bin/bash
echo "Starting mongo backup"
mkdir /home/ubuntu/backups
docker exec -it mongodb mongodump --archive=/root/mongodump.gz --gzip
docker cp mongodb:/root/mongodump.gz /home/ubuntu/backups/mongodump_$(date +%Y-%m-%d_%H-%M-%S).gz
echo "Mongo dump complete"
printf "[default]\naccess_key=\nsecret_key=\nsecurity_token=\n" > ~/.s3cfg
s3cmd put /home/ubuntu/backups/* s3://my-backup-bucket/
echo "Copy to S3 complete"
rm /home/ubuntu/backups/* -r
echo "Files cleaned"
I used only absolute paths **(EDIT: yeah actually I didn't)** , no environment variable, no un-escaped %. I don't know what I missed.
|
One possible reason is that you don't use absolute paths to the commands and some of your commands are not located in `/usr/bin` or `/bin` that belong to `$PATH` envvar in Cron by default.
You can find out where is located each executable of your commands by the command `which`, for example `which s3cmd`. Then you can put the commands with their absolute paths in your script.
Another approach is to assign new value for `$PATH` in your script or in `crontab`: Why crontab scripts are not working?
You can redirect the output of your Cronjob to a file to debug where is the problem. For this purpose modify your the job in this way:
* * * * * /path/to/the-script >/path/to/log-file 2>&1
In addition I would prefer to use `$HOME` instead of `~` within the scripts.
|
stackexchange-askubuntu
|
{
"answer_score": 6,
"question_score": 5,
"tags": "bash, scripts, cron"
}
|
Combining 2 SQL queries from a WCF service
Basically I don't know how to query my database so it returns only fields containing `username` and `date`. I can query them separately but not together.
However there's no option for `AND` in intellisense.
These are the 2 queries:
[OperationContract]
public List<TimeData> GetUsersSpecific(string DateToSearch, string NameToSearch)
{
TimeDataEntities3 e = new TimeDataEntities3();
var x = (from q in e.TimeDatas
where q.Date.Contains(DateToSearch)
select q);
var y = (from r in e.TimeDatas
where r.Username.Contains(NameToSearch)
select r);
return ();
}
But really i'd like something like:
var y = (from r in e.TimeDatas
where r.Username.Contains(NameToSearch)
AND where r.Date.Contains(Datetosearch)
select r);
|
You need to use `&&` operator instead of `AND` one:
var timeData = from t in e.TimeDatas
where t.Date.Contains(DateToSearch)
&& t.Username.Contains(NameToSearch)
select t;
Now you have access to `Date` and `Username` properties through `timeData`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, sql, wcf"
}
|
How to add minutes to a date variable in java
I have a date variable (endTime) with some value (eg : 10:40). I need to create a new variable by adding 10 minutes to endTime. How can I do it?
Thanks in advance
public static String endTime = "";
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Calendar cal = Calendar.getInstance();
endTime = timeFormat.format(cal.getTime());`
|
You can use `add` method on your `Calendar`:
public static String endTime = "";
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 10)
endTime = timeFormat.format(cal.getTime());`
Found in Javadoc, it takes me 30 seconds.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "java"
}
|
Are all autonomous Systems zeitinvariant? And viceversa not true?
so I am studying dynamical systems with the term autonomous and time-invariant systems a part of it.
Are all autonomous systems time-invariant or not? and are all time-invariant systems autonomous? I am a bit perplexed with the terms. I would appreciate if someone could help. Thanks
|
Yes, all autonomous systems are time(-shift) invariant. If you have a solution $x(t)$ of $\dot x=f(x)$, $x(0)=x_0$, then $y(t)=y(t+a)$ solves $$\dot y(t)=\dot x(t+a))=f(x(t+a))=f(y(t)),~~y(0)=x(a).$$
And if the dynamic of how the system moves from a state $x(t)$ to $x(t+\Delta t)$ is time independent, and smooth enough, the the generating vector field is also time invariant.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "dynamical systems"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.