INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Check internet connection type (iOS)
I am creating an application, which implements MultipeerConnectivity framework and therefore I would like to check user's internet connection TYPE before allowing him to proceed. In other words, my question is:
Is there a way in iOS to check wether user connected to the internet via Cellular or WiFi? I am sure there is but I could not find it.
Notice: I am not asking how to check wether user is connected to the Internet or not(I know how to do that). Thank you in advance. | This one is not swift, but I'm sure you'll find a swift variant.
See the Reachability class, which you can find at Apple as example and can tweak as you want. Chances are high you are already using it already to detect if you are connected or not.
From this class, you can ask the connection status:
Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];
if(status == NotReachable)
{
//No internet
}
else if (status == ReachableViaWiFi)
{
//WiFi
}
else if (status == ReachableViaWWAN)
{
//3G
}
See iOS Detect 3G or WiFi | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "ios, swift"
} |
Mimic the structure of a module that uses module.exports
I have a module that I imported from NPM. Essentially, its structure is as follows:
module.exports = function a() {
return 'a';
};
module.exports.b = function b() {
return 'b';
};
Resulting in the following structure, when printed to the console: `{ [Function: a] b: [Function: b] }`.
How can I mimic this structure, without using `module.exports`? I need this, so that I can mock it in Jest.
I tried the following, but none of these worked:
const a = {
function() {
return 'a';
},
b() {
return 'b';
},
};
Resulting in: `{ function: [Function: function], b: [Function: b] }`
And:
function A() {
this.b = function b() {
return 'b';
};
return 'a';
}
Resulting in: `[Function: A]`
I also tried a few other methods, but the above two seemed the most promising. | `module.exports` is just a variable, so you can follow the library code exactly, but assign into the variable of your choice:
const a = function() {
return 'a';
}
a.b = function() {
return 'b';
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, data structures, module, mocking, jestjs"
} |
remove a string starting with @ in data frame column in R
Let's say if the data frame is `df` with column `foo`. Is there a way to remove a string starting with @ in data frame column in R.
Example:
df <- data.frame(foo=c("@john is awesome than @steve",
"@steve is good","@mike is nice"))
df
foo
1 @john is awesome than @steve
2 @steve is good
3 @mike is nice
How do I remove the entire name @john,@Steve, @mike all that starts with @.
The Final output should be
foo
1 is awesome than
2 is good
3 is nice
I would like to get rid of all the strings from a column `foo` in data frame `df` that start with delimiter @. | A combination of mine and Richard Scriven's comments.
df$foo <- gsub(" ?@\\w+ ?", "", df$foo)
df
# foo
# 1 is awesome than
# 2 is good
# 3 is nice
The `@\\w+` matches the ampersat followed by one or more letters. The `?` matches an optional space at the beginning and the end.
So altogether it looks for a match of
[optional single space]@[one word][optional single space] | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "r, string"
} |
Rxjs conditional delay
I want an observable to be delayed depending on its value. For example:
of(someBool).pipe(delay(1000))
skip delay when `someBool` is false, but wait a sec when it's true. | You can use `delayWhen` for that:
of(someBool).pipe(
delayWhen(val => val ? interval(1000) : of(undefined))
)
* * *
Side note, according to the docs using `empty()` instead of `of()` should IMHO work, but doesn't appear to. I believe this might be a bug. I have reported it. | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 12,
"tags": "rxjs5"
} |
Mixpanel events not sent
I have created a simple react app, and I try to send some events to mixpanel.
However nothing is sent. No api requests are shown in network console, when mixpanel.track('test') is called.
when mixpanel.init('token') is called, I receive this response: `{"notifications":[],"config":{"enable_collect_everything":false}}`
this is my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
let mixpanel = require('mixpanel-browser');
mixpanel.init('my-secret-token');
mixpanel.track('test');
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
I have initialized my react app by create-react-app, and installed mixpanel-browser module.
I also have created mixpanel project, and triple checked that token.
Any ideas what I am doing wrong? | Ok, it seems to have something to do with my chrome browser. When using safari, everything works fine, but with chrome nothing is sent.
macOS: high sierra, 10.13.6 (17G65) chrome version: 68.0.3440.106 | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "javascript, node.js, reactjs, mixpanel"
} |
Why does shorting the phases of a BLDC motor cause it to lock?
Normally a motor can be locked by shorting its phases.
When the motor is not connected and we short all the the three phase terminals (tie them together) and try to rotate the shaft it offers lot of opposition.
Why is this the case? | Shorting the phases is creating a low resistance load which makes the motor work hard. This is the braking opposition you notice. | stackexchange-electronics | {
"answer_score": 3,
"question_score": 0,
"tags": "motor, brushless dc motor"
} |
i need NHibernate.ByteCode.Castle source code
I need to get into **FluentNhibernate** and **NHibernate** code so i rebuild the solutions and used the new assemblies, but the problem is that there is an assembly called **NHibernate.ByteCode.Castle.Dll** which refuses to load the my own version of **Nhibernate** and keep telling me that the Public Token doesn't match, so where can i get the source code for this assembly, so i can reference my NHibernate assembly and rebuild it???
or may be the question is : is it open source ??? | :$ how stupid I am !!!!
it comes with Nhibernate source code,but what made me confused is when I opened the Nhibernate Solution, the Nhibernate.ByteCode.Castle project wasn't there! !!!
but there is another solution file called NHibernate.Everything.sln, i opened it, and **voila** !!! there it is in the solution. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "fluent nhibernate, bytecode"
} |
Show that $P(A\cap B) =\frac14$
A ball is drawn at random from $4$ balls labelled $1, 2, 3, 4$. The sample space is $Ω = \\{1, 2, 3, 4\\}$ and we take $P(\\{i\\}) = \frac14$ for $i = 1, 2, 3, 4$. and we consider the events $A = \\{1\\} ∪ \\{2\\},\ B = \\{1\\} ∪ \\{3\\}, \ C = \\{1\\} ∪ \\{4\\}$.
Show that $P(A\cap B) =\dfrac14$
**Attempt:**
$A∩B = (\\{1\\} ∪ \\{2\\}) ∩ (\\{1\\} ∪ \\{3\\})$
$= \\{1\\} ∪ (\\{2\\} ∩ \\{3\\})$ by the distributive law
$P(A∩B) = P(\\{1\\} ∪ (\\{2\\} ∩ \\{3\\}))$
$= \dfrac 14 + \left(\dfrac 14 \times \dfrac 14\right) = \dfrac 14 + \dfrac 1{16} = \dfrac5{16}$
Am I doing something wrong here? When I don't simplify using the distributive law, I get the correct answer of $\frac 14$, like so:
$$P(A∩B) = (\\{1\\} ∪ \\{2\\}) ∩ (\\{1\\} ∪ \\{3\\}) = \left(\dfrac 14+\dfrac 14\right) \times \left(\dfrac 14+\dfrac 14\right) = \frac 12 \times \frac12 = \dfrac 14$$ | Note that $\\{2\\}\cap\\{3\\} = \varnothing$, so in your calculations
$$P(A \cap B) = P(\\{1\\} \cup (\\{2\\} \cap \\{3\\})) = P(\\{1\\}) + P(\\{2\\} \cap \\{3\\}) = \frac14 + 0 = \frac14$$
You incorrectly evaluated $P(\\{2\\} \cap \\{3\\})$ as $\dfrac{1}{16}$, which is the difference of the two numerical answers in the question. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "probability"
} |
Mersenne numbers congruent to two
Prove that $2^{2^n-1} = 2 \pmod{2^n - 1}$ given that $2^n = 2 \pmod n$.
How would I go about proving that? I started by saying let $m = 2^n - 1$ Then, $2^n = 1 \pmod{m}$.
So I need to prove $2^m = 1 \pmod m$. I'm not sure how to proceed. | Observe that $2^n \equiv 1 \pmod{ 2^n-1} $.
Given that $2^n \equiv 2 \pmod{n}$, we know that $2^n - 1 \equiv 1 \pmod {n}$, or that $2^n -1 = kn + 1 $ for some integer $k$.
Thus, $2^{ 2^n -1 } = 2^{kn + 1} \equiv 2 \pmod{2^n-1}$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "elementary number theory"
} |
Snapcraft - how do I use an absolute path to files of a previous part
I'm creating a Snap which contains 2 parts. The second part needs files that have been created in the first part otherwise it will not build.
I tried to use a relative path, starting in the root directory of the current part, but libtool does not accept it. If I use the absolute path it builds but now the snapcraft.yaml is not portable anymore.
This is what I have now:
build: |
./autogen.sh && ./configure LDFLAGS='-L/home/snapcraft/mySnap/parts/libdb4.8/install/usr/local/BerkeleyDB.4.8/lib/' CPPFLAGS='-I/home/snapcraft/mySnap/parts/libdb4.8/install/usr/local/BerkeleyDB.4.8/include/'
Is there an environmental variable that holds the absolute path of previous parts? Or is there any other way to do this?
Thanks | I was able to resolve this issue by adding the necessary files to the staging area
stage:
- usr/local/BerkeleyDB.4.8/lib/*
- usr/local/BerkeleyDB.4.8/include/*
and then pointing to them using the $SNAPCRAFT_STAGE environment variable.
build: |
./autogen.sh && ./configure LDFLAGS='-L$SNAPCRAFT_STAGE/usr/local/BerkeleyDB.4.8/lib/' CPPFLAGS='-I$SNAPCRAFT_STAGE/usr/local/BerkeleyDB.4.8/include/' | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "compiling, snap"
} |
HighChart And R weird Column chart breaks
I am trying to figure out how to get rid of these breaks within my chart: enter image description here
Below is the R code to produce that chart. Thank you for your help.
hchart(dfDouble %>% filter(Year == 2021), "column", hcaes(x = Day, y = FC), name = "Current FC", showInLegend = TRUE) %>%
hc_add_series(dfDouble %>% filter(Year == 2020), "column", hcaes(x = Day, y = FC), name = "Prev FC", showInLegend = TRUE) %>%
hc_title(text = "Revenue YTD") | Seting **plotOptions.column.borderWidth** to 0 should help remove breaks between stacked column segments.
According to the documentation: _The width of the border surrounding each column or bar. Defaults to 1 when there is room for a border, but to 0 when the columns are so dense that a border would cover the next column._
plotOptions: {
column: {
stacking: 'normal',
borderWidth: 0,
},
},
Live demo: <
API References: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "r, highcharts, shiny"
} |
Why is $ required around \oplus in a math environment?
I wrote the following:
\begin{equation*}
\begin{tabular}{c|c|c}
P & Q & P \oplus Q \\
\hline
\text{T} & \text{T} & \text{F} \\
\text{T} & \text{F} & \text{T} \\
\text{F} & \text{T} & \text{T} \\
\text{F} & \text{F} & \text{F} \\
\end{tabular}
\end{equation*}
and the latex compiler complained 'missing $ inserted' on the first line of the table (the one with the \oplus code. I changed that line to:
P & Q & P $\oplus$ Q \\
and it worked. If equation is a math environment, why is LaTeX requiring \oplus to be enclosed between $ symbols? | Everything is already said in the comments. `tabular` puts every cell in text mode, and `array` does the same, but in math mode.
So, in your case,
\begin{equation*}
\begin{array}{c|c|c}
P & Q & P \oplus Q \\
\hline
\text{T} & \text{T} & \text{F} \\
\text{T} & \text{F} & \text{T} \\
\text{F} & \text{T} & \text{T} \\
\text{F} & \text{F} & \text{F} \\
\end{array}
\end{equation*}
By the way, as @GonzaloMedina already said, there is much more text than math in there. Then, may be, you could write
\begin{center}
\begin{tabular}{c|c|c}
$P$ & $Q$ & $P \oplus Q$ \\
\hline
T & T & F \\
T & F & T \\
F & T & T \\
F & F & F \\
\end{tabular}
\end{center}
EXTRA: IMO you could delete the last `\\`, since there is no rule after the last row. | stackexchange-tex | {
"answer_score": 3,
"question_score": 1,
"tags": "tables, math mode, equations"
} |
"Name=AJAXREQUEST", "Value=_viewRoot" to set elementvalue of ajax field?
Looking at some old scripts to learn a bit I observe this in a web_submit_data: "Name=AJAXREQUEST", "Value=_viewRoot", and "Name=thenameoftheelementIwantToSet", "Value=thevalueIwantToSet", (and more name-value pairs)
Is this a wayt to actually set a value if the elements name is 'thenameoftheelementIwantToSet' and the value is 'thevalueIwantToSet' ? And the name 'AJAXREQUEST', is it a reserved word as in actually stating that this element manipulation is to be done on a AjaxElemnt or could it say whatever? | The processing of these name / value pairs are done on the server your application or web page is running on. It's totally up to the app as to what is valid or not. From LoadRunner's perspective you're just passing a pair of strings. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ajax, loadrunner"
} |
Translation of months and days in Calendar Views Module
The Views Calendar template displays months and days, i.e. June, July, Monday, Tuesday, etc.
When someone changes from english to french, how can I tell it to display the months in a different language? | You need to translate the strings. Go to Administration » Configuration » Regional and language » Translate interface, in the menu.
Then search for !month-name and !day-abbreviation and translate the strings to your language.
You can also download translations for the whole module on <
You can also use the Localization update module. From the UI of the module you can download and keep track of new translations for your downloaded modules. | stackexchange-drupal | {
"answer_score": 1,
"question_score": 0,
"tags": "views, datetime, i18n l10n"
} |
TSQL skipping over exec statement without running stored procedure
I have a SQL Server stored procedure that normally runs fine. However, for one record as I walk through the stored procedure it is "skipping" a line without running it.
if not exists ( select * ... ) begin
exec @Result = InsertRecord_A @AccountNo, @ID, @EventID;
if @Result <> 0 return @Result;
-- Do something else
insert into ...
select ...
end
That line, `exec @Result...` is being skipped in this case. Normally it launches the procedure `InsertRecord_A` but I can't get it to run on this record.
Any ideas?
Update: There is the following error message:
Msg 201, Level 16, State 4, Procedure InsertRecord_A, Line 0
Procedure or function 'InsertRecord_A' expects parameter '@EventID', which was not supplied.
What is odd about the error message, is when walking through it, @EventID shows it has a value of 460 which is correct. | Try explicitly setting the parameters to the correct values, rather than passing them by ordinal position and hoping they're in the correct order:
exec @Result = InsertRecord_A @AccountNo = @AccountNo, @ID = @ID, @EventID = @EventID;
This is of course assumes that your `InsertRecord_A` procedure does take 3 procedures with the same names as your variables.
If you're not sure about this, you can run `exec sp_help InsertRecord_A` or look in the `sys.parameters` table to check what they're called. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "sql, sql server, tsql, stored procedures"
} |
AWS - How can I setup RDS?
I am trying to setup RDS on my AWS account. I created the RDS instance, But I am not able to access the database interface. I am trying to access it using putty, But it is saying - "Command not found".
Please clarify whether I am missing something.
Thanks | You didn't mention the RDS Database engine you are using, but here are some general tips.
1. Use a local database client (such as mysql workbench for mysql)
2. Make sure your RDS security group allows your local ip address to access the RDS instance on the correct port.
If you give more information about your setup we'll be able to help you more. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "mysql, amazon web services, putty, amazon rds"
} |
Intel's C++ compiler for Windows
It supposedly integrates with Visual Studio, but does it come with it's own C++ standard library? Or does it use the one provided by VC++? | At least the last time I checked, it used the one that came with VC++. I believe you _can_ buy the Dinkumware library for it separately, if you really want to (but Dinkumware supplies Microsoft's library, so you're getting a different version of the same, not something radically different). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, intel"
} |
How to write in .csv format when output is a list with unequal sizes list components in R
I am working with a R program whose output is a list of size n and each components is also a list of unequal sizes. Here is sample, let M is a list (with n=3) whose components are given below
> M<-
[[1]][[1]]
[,1] [,2]
[1,] 0.37129 0.90591
[2,] 0.41116 0.91866
[3,] 0.45105 0.93140
[4,] 0.46855 0.88944
[5,] 0.42869 0.87671
[6,] 0.38884 0.86396
[[1]][[2]]
[,1] [,2]
[1,] 0.46855 0.88944
[2,] 0.50844 0.90215
[[2]][[1]]
[3,] 0.52595 0.86020
[4,] 0.48609 0.84750
[[3]][[1]]
[,1] [,2]
[1,] 0.23322 0.25205
[2,] 0.27293 0.26451
[3,] 0.29221 0.21904
Question: How to write this output list (here, M) to a single csv file? | As suggested by arun you can put this specific list into a matrix.
But as you want to save a big object for further use in R you should definitely use:
save(myObject, file="myObject.rda")
You can then load it with:
load("myObject.rda")
This has several advantages over .csv :
1) it is smaller on disk
2) it is faster to save and load
3) you will get immediately the structure of the object you saved, whatever this structure is | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "r, csv"
} |
execute before_filter/before_action for all subresources
I have a model and a controller 'Parent'. It has a bunch of `has_many` relationships: children, cars, food, etc, and each has a controller.
Parent has a field called 'dead'. When `dead: true`, I want all children relationships to display a particular message on their `#show` and `#index` pages.
I could just put a lot of `if statements` everywhere i want a check
if self.parent.dead
<show special message>
end
A cleaner way is to put that in a `before_filter`. Still, I need to do it for every child controller. So I guess the question is, is there a clean way of executing something for all dependent records? I want a behaviour somewhat similar to `dependent: :destroy`, only I'm not actually deleting anything, i just want to executer `before_filter` for all dependent records.
Thanks! | You can define that in a concern and you can include that concern in whichever child controller you want to display the message in. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, has many"
} |
Strange Ruby behavior with || and &&
def a
puts 'a'
end
def b
puts 'b'
end
p a || b #=> prints both 'a' and 'b' although it would only print a
p a && b #=> prints only a
What's going on? I'm using 1.9.3
Edit: I forgot puts returns nil, now it makes sense, thanks to the first answer :) | Nothing strange, since `:puts` method returns `nil`, the second argument of `&&` operator didn't evaluated. However, in first case you've get the both call to `:a`, and then to `:b`, because `:a` method returned `nil`. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -1,
"tags": "ruby, logical operators, puts"
} |
How to Close SSIS Connection with RetainSameConnection = True
I have an ODBC connection with RetainSameConnection set to True.
I think it is remaining open after my package completes, because simple queries like `SELECT COUNT(*) FROM MyTable` directly from my query browser hang.
Does this sound likely? How can I prove / disprove my theory? Is there a way to force this connection to close in SSIS after I've finished with it? | I disproved my theory by doing a `SELECT TOP 1 * FROM MyTable` which successfully returned instantly.
Weirdly, the problem was the `COUNT(*)` was actually really slow - when I added some clauses (that affect no records) the count returned instantly. The clauses changed the query execution plan so that the primary key is used. Not sure why it wouldn't use the key anyway...
-- Slooooow - 500K records
SELECT COUNT(*) FROM MyTable
-- Instant - 500K records
SELECT COUNT(*) FROM MyTable WHERE ColX > 0 AND ColY > 0 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "ssis, connection"
} |
How to debug a Windows Store app that crashes on a customer's machine?
I got a support email from a customer saying his app crashes when it starts and all he gets is a message like:
> _(App Name)_ ran into a problem You can send info to Microsoft about what went wrong to help improve this app.
>
> Files that will be sent to Microsoft C:\Users\User_Name\AppData\Local\Temp\WER####.tmp.appcompat.txt C:\Users\User_Name\AppData\Local\Temp\WER####.tmp.hdmp
I thought - Microsoft isn't going to help them really with my silly app. They should send the dump file to me for debugging, but how to do it? A sample dump file I got from a crashing app was 90MB and after zipping it is still 30MB. How do I debug the app? Is there a simple way to get these dump files from a customer? These also get deleted right after you switched from the crashing app window to the desktop unless you leave it running (crashed) in snapped view and hit WinKey+D. | It seems like the Windows developer Dashboard has an option to get mini dump files for most common crashes that could help find the problem (assuming your customer is having one of the most common problems for a crash or that there are actually few problems causing your app to crash and all of them are there). You just need to go to:
Dashboard/App/Reports/Quality/Most common crashes
There you can download a cab file that includes the mini dump from there. You might be able to extract the file by just renaming cab to zip or using a tool that extracts cab archives. Then just open the dump file in WinDbg and start debugging! | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "windows 8, windows runtime, windbg, windows store apps, windows store"
} |
python remove single quotes and spaces from a list
Im using python3 and i want to make this list to containe only the temp items and removing all the spaces and singel quotes.
a = ["', ' 'temp1', ' 'temp12', ' 'temp3', ' 'temp4', ' 'temp5' "]
I want it to look like this :
['temp1','temp12','temp3','temp4','temp5']
How can i do this ? | One way to go about this :
result = a[0].replace(' ', '').replace("'", '')[1:].split(',')
print(result)
* * *
Output:
['temp1', 'temp12', 'temp3', 'temp4', 'temp5'] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -2,
"tags": "python, python 3.x"
} |
Get the current position in the array on event?
I have a click event on an `ul`. With `$.inArray` I want to get the current index of the `li`. With this I can then animate the right div. My Markup is like so:
<div class="nav">
<ul>
<li></li>
<li></li>
</ul>
</div>
<div class="sideways">
</div>
<div class="sideways">
</div>
And so on. You can swipe through the "sideways" divs and with the `ul` it's possible to also navigate to the divs through a navigation. Now my code looks like this:
$('.nav ul li').click(function(){
$this = $(this);
k = $.inArray($this, $('.nav ul li'));
});
k always returns -1. Why does this happen? Why doesn't it return the current index? | If you want to get the index on click why you just don't use .index()?
$('.nav ul li').click(function () {
alert($(this).index());
});
<script src="
<div class="nav">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<div class="sideways"></div>
<div class="sideways"></div> | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "jquery"
} |
Inverse Label Encoding for plotting purposes
I have a feature in a DataFrame encoded with integers, i.e., int64 type. Further, I have a dictionary with the equivalent classes. Is there a way to draw a bar plot for this feature with the original categories?
df = pd.DataFrame({"feature_1": [-1, 0, 1, 1, 0, 1]})
tags = {"Good": 1, "Bad": 0, "Indiferent":-1}
I would like to obtain a pie chart with relative frequency (expressed %) of every case, with the string labels contained in the dictionary. | This should work for you. Just have to manipulate the df to replace the values for the words you want, then get the count.
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame({"feature_1": [-1, 0, 1, 1, 0, 1]})
tags = {"Good": 1, "Bad": 0, "Indiferent":-1}
df = df['feature_1'].replace({v:k for k,v in tags.items()})\
.value_counts()\
.reset_index()\
.rename(columns = {'index': 'feature_1','feature_1':'count'})
sns.catplot(x = "feature_1", y = 'count', data = df, kind = 'bar')
,
array('Size', false, '2097152'),
array('Upload', false),
),
))
And when I'm using localhost the image is uploaded successfully. But when I move to my hosting the validation error shows for image field. The mimetype of file 'foto.jpg' could not be detected. What can be the reason of this? | same thing happened to me, this was crazy stuff, more than 2 hours trying to figure out what's wrong, here is how to fix it:
install fileinfo extension on linux:
> pecl install fileinfo
then you need to add to your php.ini this line:
> extension=fileinfo.so
restart your apache and you are done!
*if you server is freeBSD you have to do this:
> cd /usr/ports/sysutils/pecl-fileinfo/ make install | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 6,
"tags": "zend framework, upload, zend form"
} |
How to delete all data in a partition?
I have a CosmosDB collection with a number of different partitions. I want to delete all of the data in one of the partitions so I tried to run the command:
db.myCollection.deleteAll({PartitionKey: 'pop-9q'})
Where `PartitionKey` is the field that I partition/shard based on. But when I execute this it returns the not very helpful message:
> ERROR: An Error has occurred
Why would I be getting this message and how can I either get more details on the cause or find a resolution? | Currently, at this time, you are unable to perform a bulk delete. Please Up Vote and Comment on this functionality: Add the ability to delete ALL data in a partition
Additionally, which API are you consuming? For Gremlin API you could execute something like the following: g.V().drop() | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "azure cosmosdb, azure cosmosdb mongoapi"
} |
Flutter compileSdkVersion 31 cause "BluetoothAdapter has been deprecated"
I changed `SDK Version to 31` and cause the following error. I tried to update the `ServiceManager.java` according to this link BluetoothAdapter deprecated but it does not work.
How can I solve this error? Please help
. Пробовал простой транслит, но он не справляется с мягкими знаками. Можно сделать в бд 2 поля, name_eng и name_rus, когда вводишь в адресную строку название на енг он делает поиск и выводит поле рус. Есть по проще вариант, без создания доп поля? | Самый правильный вариант – с двумя полями. При сохранении новой записи в БД выполняете транслитерацию и сохраняете транслитерированный вариант в свое отдельное поле. Таким образом у вас будет один однозначный вариант соответствия адресной строки соответствующей странице. Плюс, поле с транслитом в БД нужно сделать индексируемым (уникальным) - это позволит быстро открывать любую страницу, даже если их будут сотни тысяч. | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql"
} |
Minimum distance to a subspace is attained by an orthogonal vector
Given a subspace $S$ in some inner product space $X$, we know that $\forall p \in X$, $\exists s_o \in S$, s.t. $\forall s \in S$, $\|p - s_o\| \leq \|p - s\| \Leftrightarrow p - s_o \perp S$
We want to show that given a translated (affine) space $M = d + S$, $\forall p \in X$, $\exists m_o \in M$, s.t. $\|p - m_o\| \leq \|p - m\| \Leftrightarrow p - m_o \perp M$
Attempt:
* * *
Let $m_o = s_o+d, m = s+d$
$\langle p - s_o, s \rangle = 0$
$\Rightarrow \langle p - (m_o - d), m - d \rangle = 0$
Is there a way to argue from here that the above implies:
$\langle p - m_o, m \rangle = 0$ | It is just the Pythagorean theorem. Given $p\in X$, let $p_0$ be the projection of $p$ on $S$ and assume that $$ \min_{s\in S}\|p-s\| $$ is attained by some $q\in S$ with $q\neq p_0$. Then $(p-p_0)\perp (p_0-q)$, hence: $$ \|p-q\|^2 = \|(p-p_0)+(p_0-q)\|^2 = \|p-p_0\|^2 + \|p_0-q\|^2 > \|p-p_0\|^2 $$ contradicting the minimality of $q$. | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "linear algebra, optimization, inner products"
} |
Acceptable Intel i5 Proccessor Temperature?
> **Possible Duplicate:**
> What is the safe temperature range for a Core-i5 processor?
I'm just wondering if my processor I working under an acceptable temp. From what I have read 42 is pretty decent under idle conditions. But looking as Intel Extreme Tuning its appears red while every thing else is blue. Any suggestions?
, or I have a simple array of DB connnections. Naturally, ApplicationModel has accessor for it.
I pass around a reference to the ApplicationModel in constructors of those objects that need it. Alternative is to make ApplicationModel a Singleton with the same functionality. - Then you do not need to pass it around... I stopped using Singleton for this purpose not so long ago as I find dependency injection more useful. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "architecture, d"
} |
Angular 2 - if query string present, load another stylesheet
I have an Angular 2 app and want to turn one of my components into an iframe widget when the query string `widget=true` is present. When this string is present I want to load an additional stylesheet into the component to change the widget view a little bit. Is this possible? How would I do this?
_Just to clarify:_
I have a component that I use as a regular page but want to be able to have it as an iframe widget too. When the query string `widget=true` is present I will know that the page is in an iframe. In this case I want to load an additional stylesheet to the component | Well there are several ways.
First, obvious and dirty, is including styles as `<style>` tag with `*ngIf` checking for this parameter in the URL.
Second, what I find better, is setting the style into styleUrls component meta property:
let styleUrls = [];
if (window.location.href.contains('widget=true')) {
styleUrls.push('/path/to/style');
}
@Component({
selector: 'hero-app',
template: `
<h1>Tour of Heroes</h1>
<hero-app-main [hero]=hero></hero-app-main>`,
stylesUrls:
})
export class HeroAppComponent {
/* . . . */
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "angular, widget, stylesheet"
} |
Mono ignores existing file, throws error
I am trying to compile this workspace with Mono, specifically the Sm4shCommand/AnimCmd project. When I compile it with MonoDevelop, I get
/home/----------/Downloads/Sm4sh-Tools-master/AnimCmd/CSC: Error CS2001: Source file `System/Windows/Forms/HexBox/Forms/GotoDialog.designer.cs' could not be found (CS2001) (Sm4shCommand)
I get the same error when I try to compile it with xbuild.
The file it says doesn't exist is in the project. Is there a reason it isn't recognizing it? | Assuming you are on Linux...
It that a file case issue that on Windows or OS-X you would not see, edit the `Sm4shCommand.csproj` file and change `GotoDialog.designer.cs` to `GotoDialog.Designer.cs`
./AnimCmd/System/Windows/Forms/HexBox/Forms/GotoDialog.Designer.cs
AnimCmd/Sm4shCommand.csproj: <Compile Include="System\Windows\Forms\HexBox\Forms\GotoDialog.designer.cs"> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, mono"
} |
google nexus 7 development rotation not working
I recently started creating a mobile application on the google nexus 7. I have previously tested this application on the kindle fire and both portrait and landscape mode worked on all screens but when I upload the application onto the nexus the application always stays in portrait.
Has anyone run into this or know why the nexus only shows my application in portrait mode? | Is your device rotation lock turned on? It's in the quick pull down menu. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "android, tablet, screen orientation"
} |
Implicit Function Theorem Proof (Rudin)
Given $f\in\mathscr{C'}$ where $f$ is a map from the open set $E\subset R^{n+m}$ to $R^{n}$, $f(a,b)=0$ for some point $(a,b)\in E$.
In the second part of the proof it says:
> Finally, to compute $g'(b)$, put $(g(y),y)=\phi(y)$. Then $$ \phi'(y)k=(g'(y)k,k)$$ for $y\in W=\\{y\in R^m : (0,y)\in V\\}, k\in R^m$
What $V$ or $W$ is isn't really important. My question is where does the k come from and why does it simply disappear later in the proof? | $k$ is an arbitrary tangent direction introduced to better describe the derivative in the form of a directional derivative. The author could also have written $$ ϕ'(y)=(g'(y),I)\text{ or }ϕ'(y)= g'(y)\oplus I $$ but probably wanted to avoid this concatenation of matrices. | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "real analysis, analysis, implicit function theorem"
} |
Drupal 7: entity field as single/multivalued based on content type
I have a 'gender' entity(taxonomy) field.
I want to use it as single valued for content type X and multi-valued for content type Z in Drupal 7?
Is there any other work around to achieve this functionality? | Shortly, no.
Take a look at project Field instance cardinality and an issue #1029298.
> This currently only works with fields that use options widgets (ie select list or checkboxes), and only allows them to be overridden to be single-valued.
Theoretically, you can create field as multi-valued and limit cardinality for _content type X_ programmatically. | stackexchange-drupal | {
"answer_score": 2,
"question_score": 2,
"tags": "taxonomy terms, nodes, entities"
} |
How does C# generate GUIDs for Classes?
Apparently C# (or Visual Studio) generates a GUID for each class. I can get the GUID using the following code:
Type myType = typeof(myObject);
Guid myGuid = (Guid)myType.GUID.
My question is when does this GUID change. Is it generated based on a code change or is it based on class creation? I'd appreciate a point towards some relevant documentation.
Thanks | I don't think there is documentation on how C#/.Net "automatically" generates the GUID for type.
If you need the Guid to stay persistent (or control it in some other way) you should use GuidAttribute.aspx) instead of letting system to create one for you:
[System.Runtime.InteropServices.GuidAttribute("00000000-0000-0000-feed-000000000000")]
class Test1{}; | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "c#, visual studio"
} |
Link turns white when clicked even though a:active has been set to purple
On my site, most links (apart from those in the navbar) turn white when clicked or right-clicked. E.g. <
This is despite my setting links to #6f5499, which is a purple colour: < as such:
a, a:hover, a:focus, a:active { color: #6f5499; }
What's going on? | The problem is the CSS code below. The rule after the comma(`,`) targets every link of the webpage instead of the links inside `alert`
.alert a:hover, a:focus { color: white; }
Change it to
.alert a:hover, .alert a:focus { color: white; } | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "css"
} |
Getting a collection of successors in Java
In this method, I'm trying to get the collection of successors from the current one. This is for the Tents and Trees game in Java where I extract the pattern from a file to build the board. '%' represents a tree, '.' represents an empty spot, '^' represents a tent, '#' represents the grass.
public Collection<Configuration> getSuccessors() {
Collection<Configuration> successors = new LinkedList<Configuration>();
return successors;
//return new ArrayList<>(); // replace
}
I don't know if this is the right way, but it doesn't return anything when I run the program. What am I doing wrong? | You are creating an empty LinkedList and returning it. This LinkedList has 0 elements, so you return anything.
You need to insert something in the LinkedList.
I hope my answer will be helpful. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, collections, backtracking"
} |
Show blank space in crystal report
I have four sections, Report header,page header,detail and footer. All my data are listed in footer section. The problem is that when I print the data, the 3 sections above show big blank space.
 | The problem with your report is that you have data in wrong section. Since you have 4 sections
1. Report header
2. Page header
3. Detail
4. Footer
You are missing Report footer or Page footer (in your description of question or in your report). In your case, your data is probably in Page footer which is always printed at the bottom of the page (you can't change that). To avoid that you need to put your data in Report header, Page header or Report footer with unchecked option "print at bottom of page" (check on picture) and suppress all other sections.
Hope it helps

 Behind your label-object, there is an identical section of the tube separated from the rest, (so its normals are discontinuous).
**Fix** : `M` > Merge > By Distance, with a near-0 threshold
(Right, below) Much of the tube has its custom-normals inverted.
**Fix** : `Alt``N` Normals.. > Recalculate Outside
 After recalculating the normals (left), you can see they are twisted. Under the Data tab, 'Normals' panel, you can leave 'Auto Smooth' checked...
**Fix** : Under the 'Geometry Data' panel, you can 'Clear Custom Split Normals Data' (right), without doing the model any harm.
.`? At the moment the result would be
> 1*(a*(b*c)).
simplify(S,S1):-
s(S,S1).
s([H|T],C) :- T\=[],s(H,SA), s(T,SB), s0(SA*SB,C).
s([H|T],H) :- T==[].
s(A,A).
s0(A*B,S):-
S = A*B.
Thanks for your help. | Depends on what Prolog you're using. SWI has foldl/4 built in, which is like "reduce" in other languages. So, you could simplify your program to the following:
s(B,A,A*B).
simplify([H|L],E):- foldl(s,L,H,E). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "prolog"
} |
How to protect from DDOS attack that is coming from an exit node
Newroz Telecom (an ISP) is using an exit node (or gateway) for each city they operate in. That is all the users in city A is sharing one public IP (when the users go to a website to show their IP they all get the same result).
I am having DDOS attacks that is coming from a user/users of this ISP, blocking the IP will mean blocking the entire city, how can i fight DDOS in such environment ?
Best regards, | Here are a few options:
Can you TCPDump the traffic and maybe find a packet that is the ddos packet string and block it?
In all honesty, the only way this will probably be fixable is to ask the ISP to check and find the abuser. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 2,
"tags": "ddos"
} |
Skip Columns During Teradata Table Import From CSV Using SQL Assistant
I have a CSV file with data I need to import to a Teradata table, but it has a useless column that I would like to exclude from the import. The useless column is the first column, so the CSV rows are set up like:
'UselessData','Data','Data','Data'
Typically, I would import using SQL Assistant by choosing File -> Import Data from the menu and using the basic query:
INSERT INTO TableName VALUES (?,?,?,?)
But this will collect the extraneous useless data in Column 1. Is there a way to specify that an import take only certain columns or send the useless column to `NULL`? | AFAIK you can't do that with SQL Assistant.
Possible workarounds:
* Switch to Teradata Studio or TPT for loading (will also load faster)
* Load **all** columns into a Volatile Table first (and don't forget to increase the _Maximum Batch size for simple Imports_ in _Tools -> Options -> Import_ ) and then Insert/Select into the target. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "sql, csv, import, teradata, import from excel"
} |
Excessive growth of Access 2010 database
I have a problem of excessive database growth when inserting data via ODBC into an Access 2010 database (.accdb). For example, in one case the database grows from 24MB to 140MB, but when compacted shrinks back to ~24MB.
What I've noticed is that the database have tables with multiple text fields which are indexed. Can it be causing such excessive growth? Are there any other reasons for this? | The reason for the growth is most likely the fragmentation. It occurs when data is often deleted. I believe it is unrelated to the insertion. Had a similar problem with my database. I found that I unnecessarily inserted records just to show a certain dialog box, and deleted them straight away. It was a "shortcut" in the coding of a feature in a program. When I corrected the code (basically, I have modified the code to not delete the records, but just keep) the growth stopped. So, just check your Insertion procedure. If it deletes first (to avoid duplicates or outdated data), then change this code to UPDATE existing records. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "database, ms access, odbc, ms access 2010"
} |
Is there a way to cut down my time complexity of O(n^2)?
I have made a program (hw), which count the frequency of all words. All of my algorithms takes O(n) or O(n log n), however my word counter takes O(n^2)
The algorithm looks like this:
for (int i = 0; i < no of elements; i++)
for (int j = 0; j < no of elements; j++)
if (the ith word == the jth word)
{
increase that word counter by 1;
break;
}
The reason i use this way is because the word list is unsorted. So my question is, would it be a good idea to use insertion sort or a sort which can sort the word list in alphebetical order? And how does such kind of sort look like for string array? The word list is a string array, eg:
string words[no of elements]
Thank you for your time. | Yes you can sort your elements in O(nlogn) time using any good sorting algorithm like quicksort. Then just check for repeats iterating over sequential elements.
EDIT: in most languages (like C++) the strings can be compared using normal comparison operators. and hence sorted like any array. Moreover, there are usually built-in functions to do so. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "performance, algorithm, sorting"
} |
Is there a way to select to a character in Emacs?
I've just migrated from vim and one thinkg I miss is the motions like `vi(` or `vf<char>`. Is there a way to do something similar in Emacs? Perhaps it is possible to get isearch to select from _here_ to the match? | control-space sets the mark. region from Mark to cursor position is selected.
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "emacs"
} |
Python, py2exe, & pyopengl ImportError: No module named win32
When I try to build an exe using py2exe, it builds but when i try to run the exe it throws this error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
File "OpenGL\GL\__init__.pyc", line 3, in <module>
File "OpenGL\GL\VERSION\GL_1_1.pyc", line 10, in <module>
File "OpenGL\platform\__init__.pyc", line 35, in <module>
File "OpenGL\platform\__init__.pyc", line 26, in _load
File "OpenGL\plugins.pyc", line 14, in load
File "OpenGL\plugins.pyc", line 28, in importByName
ImportError: No module named win32
It only does this when I use pyopengl, It builds and runs perfectly with pygame and almost any other library/module I have used.
My setup.py script looks like this:
from distutils.core import setup
import py2exe
setup(console=['main.py'])
I am on Windows 7 64bit | Actually, After another hour or so of searching I found the solution!
For anyone else who has this problem: < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "python, opengl, pygame, py2exe, pyopengl"
} |
Detect WM_LBUTTONDBLCLK on a button of Toolbar
How can we detect `WM_LBUTTONDBLCLK` on a button (ex. `ID_FILE_NEW`) on a Toolbar? | This seems to be straight forward with `PreTranslateMessage()`. I have tested with this code snippet.
BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
{
// Detect Clicks in Toolbar detektieren
if (pMsg->hwnd == m_wndToolBar.GetSafeHwnd())
{
if (pMsg->message == WM_LBUTTONDBLCLK)
{
CPoint pt = pMsg->pt;
m_wndToolBar.ScreenToClient(&pt);
int nIdx = m_wndToolBar.CommandToIndex(ID_FILE_NEW);
CRect rcIdx;
m_wndToolBar.GetItemRect(nIdx, &rcIdx);
if (rcIdx.PtInRect(pt))
{
MessageBox(_T("yupii double click detected"));
return TRUE;
}
}
}
return CMDIFrameWndEx::PreTranslateMessage(pMsg);
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "winapi, mfc, window"
} |
Как посчитать кол-во вхождений одной строки в другую?
С клавиатуры вводятся две строки. Найти количество вхождений одной (являющейся подстрокой) в другую. Пример1: s = 'saddassad', t = 'sad' Результат1: 2 Пример 2: s = 'qeqeqeq', t = 'qeq' Результат2: 3
s = input()
t = input()
def suffix_counter(str, sufix):
if len(str) < len(sufix):
return 0
suffix_counter(s, t) | Просто используйте метод `count`. Позволяет найти подстроки любой длины в строке. Пример:
print('030302'.count('03'))
>>> 2
Примечание: таким же способом можно посчитать количество вхождений элемента в список, но не слайса, как в случае со строкой:
print([0, 3, 0, 3, 0, 2].count(0))
>>> 3
print([0, 3, 0, 3, 0, 2].count([0, 3]))
>>> 0 | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python, python 3.x"
} |
ASP.NET Query associated with three tables
I'm not very much aware of DB and Query
i've three tables
EMP(Contains details) Junction(contains ID of EMP table and ID of skill table) skill(contains skills)
here junction table is providing many to many relationship to emp and skill, i.e., one emp can have many skills and one skill can have many emp. now the problem is i've to populate a GridView with E_details by Selecting the the skills from the skiltable. can you tell me a example to make a select query for EMP table by selecting particular for which emp ID and Skill ID are present in Junction Table...
Thanks | If you are using ADO.NET you could write it as follows:
string query = @"SELECT e.*
FROM EMP e
INNER JOIN Junction j ON e.ID = j.empID
WHERE j.skillID = @SkillID";
int skillID = 5;
using (var conn = new SqlConnection("connectionString"))
{
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@SkillID", skillID);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = (int)reader["ID"];
int name = (string)reader["Name"];
// etc.
}
}
}
}
In ASP.NET just feed the `skillID` variable as a query string variable to the request. And project each column read into a model you can use to populate inside a GridView. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, asp.net, sql"
} |
igraph: convert list to vertex sequence
I am using the R implementation of igraph. I did not understand why `get_diamenter()` returns a `igraph.vs` object, while `shortest_paths()$vpath` returns a `list` object. I am trying to plot the shortest path between two nodes. I can plot the network diameter, since I can do
diam <- get_diameter(net_vc, directed=F)
vcol <- rep("gray40", vcount(net_vc))
vcol[diam] <- "gold"
But I cannot plot the shortest path in a similar way:
sp = shortest_paths(net_vc, from=V(net_vc)$Name=="I0", to=V(net_vc)$Name=="I11")
sp <- sp$vpath
vcol <- rep("gray40", vcount(net_vc))
vcol[sp] <- "gold"
It returns: `Error in vcol[sp] <- "gold" : invalid subscript type 'list'`
How can I convert this list to a vertex sequence, so that `as.vector(sp)` would return the position of the vertices, so as to index `vcol`? | The documentation for `get_diameter` says:
> get_diameter returns a path with the actual diameter. If there are many shortest paths of the length of the diameter, then it returns the first one found.
So it returns a single path. On the other hand, `shortest_paths` allows a _list_ of `to` vertices. It will return a list of shortest paths, a list of igraph.vs's, one for each vertex in the `to` list. You will get a list even if you call `shortest_paths` with a single vertex in `to`. So, to set the colors the way you want you need to reference the first (and only) element of the list. You need:
sp = shortest_paths(net_vc, from=V(net_vc)$Name=="I0", to=V(net_vc)$Name=="I11")
sp <- sp$vpath[[1]]
vcol <- rep("gray40", vcount(net_vc))
vcol[sp] <- "gold" | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r, igraph"
} |
What is a "lagged bath"?
First question, and this is one I've searched for in vain.
In the context of setting up cooling baths, I've come across the term "lagged" bath. I cannot extract what this means from any available context. I assume it has something to do with time passing (i.e. a lag), but I'm not certain. If I had to guess, I'd assume it means allowing the cooling agent to come to equilibrium temperature, but again, not certain.
Any direct technical experience that can explain this term would be greatly appreciated. | I'm not 100% certain on this, but my best guess on this would be referring to 'lagged' as in 'lagging', as in insulation material. So, a lagged bath is an insulated bath. | stackexchange-chemistry | {
"answer_score": 9,
"question_score": 5,
"tags": "experimental chemistry, terminology"
} |
AngularJS: data fetched by gapi client does not show up on UI
I have an angular js app. I am using gapi to sign in and then call my google cloud endpoints to fetch the data. The sign in thing works fine and also it fetches the data fine from end points.
But after it fetches the data, if I assign the data to a `$scope` variable (which is bound to UI), it does not update the UI. There is no error even. Below is my code snippet. Any ideas?
function TestCtrl($scope){
$scope.contactsList = [];//UI template is bound to this list
//Assuming the gapi client is already loaded
gapi.client.contactendpoint.list().execute(function(resp) {
if (!resp.code) {
$scope.contactsList = resp.items;//Does not update ui list
} else {
alert("Error, response is: "
+ angular.toJson(resp));
}
});
}
Regards, Nadeem Ullah | You need to use $apply() if you wish to update the scope from outside of the angular framework (for example from browser DOM events, setTimeout, XHR or third party libraries). More info available at
function TestCtrl($scope){
$scope.contactsList = [];//UI template is bound to this list
//Assuming the gapi client is already loaded
gapi.client.contactendpoint.list().execute(function(resp) {
if (!resp.code) {
$scope.$apply(function(scope) {
scope.contactsList = resp.items;
});
} else {
alert("Error, response is: " + angular.toJson(resp));
}
});
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "cloud, angularjs, endpoints"
} |
How to == Model Method Class in Helper for CSS?
**calendar_helper**
def day_classes(day)
classes = []
classes.empty? ? nil : classes.join(" ")
classes << "future" if day > Date.today # This make future days a white background, by default days are blue background
# The Below Line Gives an Error (I want missed_dates date_missed to be red background):
classes << "missed" if day == current_user.missed_dates.group_by {|i| i.date_missed.to_date}
end
**NameError in Pages#home**
undefined local variable or method 'current_user'
**css**
.future { background-color: #FFF; }
.missed { background-color: red; }
I built the calendar off of a railscasts tutorial. | Add this line to your `Calendar` class:
delegate :current_user, to: :view
Since `SessionsHelper` is get automatically included into view, it should be able your `view` variable, that is getting passed to your `Calendar` class.
> Thank you that removed the error, but for some reason the days that I marked as date_missed didn't turn red
I guess `current_user.missed_dates.group_by {|i| i.date_missed.to_date}` is an array of missed dates, so, in order to check if your day is in that array, use `include?`:
missed_dates = current_user.missed_dates.group_by {|i| i.date_missed.to_date}
classes << "missed" if missed_dates.include?(day) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "html, css, ruby on rails, ruby, helper"
} |
Notepad++ and Perl, End STDIN. Ctrl+Z in the console not working
** Title original said Ctrl+D
I have perl set up to execute and run in Notepad++.
Here's the Execute command:
NPP_SAVE
cd "$(CURRENT_DIRECTORY)"
C:\strawberry\perl\bin\perl "$(FILE_NAME)"
I'm trying to work through an example that reads in a list via STDIN, but I can't end the input, because CTRL+Z doesn't appear to work in Notepad++'s console. I press it and nothing happens, it doesn't continue the program, or end. I eventually have to terminate.
Here's the code I'm running
#!perl
use warnings;
use strict;
my @list_of_strings = <STDIN>;
@list_of_strings = reverse @list_of_strings;
print @list_of_strings; | <
> While your program is executing press F6 (again), in string "Exit message" type EOF's ASCII code < alt>+<26> and press "Send" button.
I'm not completely sure what that means, and don't have windows to try it, but that's the first hit from a google search on "notepad++ console end of file". | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "perl, notepad++"
} |
How to multiply each value in an array of coordinates
I have an array of coordinates:
const markerCoords = [
{ topLeftX: 68.5, topLeftY: 19 },
{ topLeftX: 57.5, topLeftY: 57.5 },
{ topLeftX: 140.5, topLeftY: 52 },
{ topLeftX: 136, topLeftY: 70 },
{ topLeftX: 134.3, topLeftY: 88.3 },
{ topLeftX: 270.5, topLeftY: 68.8 },
{ topLeftX: 211.7, topLeftY: 135.3 },
{ topLeftX: 245.5, topLeftY: 189.7 },
{ topLeftX: 199.5, topLeftY: 222.5 },
{ topLeftX: 128.5, topLeftY: 241.6 },
{ topLeftX: 174.3, topLeftY: 263.5 },
{ topLeftX: 167.8, topLeftY: 285.7 },
{ topLeftX: 134, topLeftY: 309 },
{ topLeftX: 251, topLeftY: 304.6 }];
And I want to multiply each value by x, and map the new coordinates to a new similar array. Like so:
const newMarkerCoords = markerCoords.map({topLeftX, topLeftY} => {topLeftX * x, topLeftY * x})
It is to place markers on the correct spots, when I scale the image map bigger. | This is probably what you want:
const newMarkerCoords = markerCoords.map(item => {return {topLeftX:item.topLeftX*x, topLeftY:item.topLeftY*x};}) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, reactjs"
} |
Playing in time line stops when the bar touches the mark out point
Basically my questions is: what is this orange bar attached to the playing cursor and how can I remove it to make the cursor stop at the marker when I'm playing selection. Many thanks!
. | stackexchange-avp | {
"answer_score": 3,
"question_score": 1,
"tags": "premiere, playback"
} |
Schema.org give a div a itemprop="image"?
I am replacing an image with a `<div>` with `background-image` for the reason of `background-size: cover;` The page is structured the same way as before with a image just that "the image" is a div now.
Does is makes sense to give that itemprop to a `<div>`? | CSS is not recognized by any Microdata parser that I'm aware of. You'll need to add a meta tag to specify the image like this:
<div itemscope itemtype="
<meta itemprop="image" content="bg.jpg"></meta>
<div style="background-image:url('bg.jpg')"></div>
</div> | stackexchange-stackoverflow | {
"answer_score": 55,
"question_score": 34,
"tags": "html, css, semantic web, semantic markup, schema.org"
} |
Closed form of the solution of a nonlinear differential equation
I should solve the following problem: given a function $u(x)$, the sum of the function and its reciprocal must be equal to the integral of the function raised to $k$. Taking the derivative of the two members, left and right, I get the following differential equation: $$\frac{d}{dx}\left(u(x)+\frac{1}{u(x)}\right)=u(x)^k$$ that can be transformed in: $$u(x)'\left[ 1-\frac{1}{u(x)^2}\right]-u(x)^k=0$$ Its solution can be expressed in closed form for $k=1$ using the $LambertW$ function. Also for $k=2$ and $k=3$ there are solutions in a closed form. Is it possible to find a closed form solution for every $k\in \mathbb{N}$? Thanks. | Write the equation as $$ \frac{u'}{u^k}-\frac{u'}{u^{k+2}}=1. $$ Integrate to get $$ \frac{1}{(1-k)u^{k-1}}+\frac{1}{(k+1)u^{k+1}}=x-x_0, $$ where $x_0$ is a free constant. This relation can be rewritten as $$ u^{k+1}(x_0-x)(1-k^2)+u^2(k+1)+1-k=0. $$ | stackexchange-math | {
"answer_score": 0,
"question_score": 2,
"tags": "ordinary differential equations"
} |
iPhone - When does a deprecated method usually becomes obsolete?
I'm using some methods in some apps that are now marked as deprecated since iOS5. I'd like to know when these updates will become urgent.
So, usually, when does a deprecated method becomes obsolete ? Is there a chance that this will be with iOS 5.1 ? Or is this always with a major version like iOS 6.0 ? | This depends and changes from method to method and property to property. If you look at something like the
cell.textColor
it has been deprecated since iOS 3.0 and can still be used. So unfortunately there's not a specific answer to the general thing about stuff being deprecated. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 8,
"tags": "ios, cocoa touch, deprecated, obsolete"
} |
Multiple nodes with the same receiving and transmitting address
I want to make a network with arduinos and nrf24l01 chips. The network will be like this:
* 1 master arduino
* multiple (no specific number) slave nodes
I want all nodes to have the same receiving and the same transmitting address and the master arduino to understand which one send the message from the message itself. For example:
**Master:** Receiving: 0xABCDABCD71 Transmitting: 0xABCDABCD01
**Slave 1** Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71
**Slave 2** Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71
**Slave 3** Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71
**Slave 4** Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71
When master send a message, all nodes will receive it. What I want to ask is :
* Is that possible?
* Will there be any problems?
* Is there any other way so I can add more nodes in the future without changing the code? | as well as comment #1 the other thing will be the ack packets that the slaves will send back to the master to confirm message recieved. with all slaves sending back a ack at about the same time there will be no way for master to tell which ack is from which client, and thus who needs a retransmit. a way around this is to turn off ack for the clients and make the master transmit max times regardless. there is a rf24 fork that has broadcast mode, the makes it more easy to specify not to wait for ack before retransmitting | stackexchange-arduino | {
"answer_score": 1,
"question_score": 2,
"tags": "nrf24l01+"
} |
Layover in CDG Enough Time for Customs?
My girlfriend and I will be travelling from Cincinnati to Athens, Greece in the next few months. There will be a stop on the way to Athens at CDG in Paris. I'm assuming that I will have to pass through customs once arriving at CDG. However, my layover there is only 1 hour. Is this enough time to pass through customs and board my connecting flight? | One hour can be really short, even if there are no delays on your flight from Cincinnati.
As a precaution, before landing in Paris, notify the flight attendant of the situation; tell them what is your next flight (number and destination) and ask them if they know what gate is your next flight, and if it is in the same terminal.
It might be possible that they will let you exit the plane before other passengers.
Remember, DON'T PANIC.
Anecdotal, the last time we went through CdG (from Montréal to Italy,2 3 years ago), it was a short layover and we were stuck at one checkpoint because they were understaffed; we ran like hell after that. | stackexchange-travel | {
"answer_score": 3,
"question_score": 3,
"tags": "customs and immigration, airports, layovers"
} |
Silverlight datagrid Observable collection send a list of notifications
In my silverlight application I use a datagrid. The item source is an ObservableCollection< Customer > The Customer object implements INotifyPropertyChanged. The problem is that from second to second I update all customers elapsed time. If I have in the grid 5000+ records this is a problem for performance.
Do you know if it is possible to have in silverlight something like:
_grid.SuspendLayout();
//update model
_grid.ResumeLayout();
... or suspend bindings.
Since I update only elapsed time column I would like to update only that column ... not the whole grid. Does the datagrid support some event to receive a list of updates? In this case maybe I can think of implementing my custom ObservableCollection. | Have you tried using OneTime binding mode instead of TwoWay? If you use OneTime, you can decide to manually refresh the grid by saving changes on your context. You can also control edits using `grid.BeginEdit()` and `grid.CommitEdit()`. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "silverlight, performance, datagrid, inotifypropertychanged"
} |
How to connect multiple IR Cameras with C# via usb
**In context:** At the moment I have a code example designed in C# for connecting a single camera Optris. The code work in windows form for one camera, I try to modify the code to work for two cameras, but the system always connects with the last cameras configuration.
then the view of the modified example for two cameras where it shows the same image corresponding to the second camera.
**The modifications made**
The image that is displayed in the second picture box was duplicated from the example code with all the variables and methods, additionally all the duplicate variables of the code example was simply added the number two.
Additionally, added the original code and the code with the modification: enter link description here
Thanks for your help | Looking in the documentation (< and watching your code, seems that .dll uses a singleton pattern.
I tried to clone the dll and make two invokes, and works!
Working with 2 cameras
You have two options:
1. Clone the dll for every camara that you need to connect.
2. Try to find the "problem" or contact with the sdk programmers.
Regards! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, camera, camera calibration"
} |
Caching mysql database with node.js
I need to provide a caching layer for mysql database on my node.js server app.
The caching should be able to hold array objects (not just a key-value store).
What module should I use for it ?
Currently i'm using those modules:
express
socket.io
mysql | I found this module : <
The problem is that I do not not how stable it is.. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, node.js"
} |
Can't install debug version of my android application
I wrote an android application in IDEA. When I used Debug-mode (connected to my device) - everything worked nice. But when I manually downloaded apk file to my phone and tried to install application - it said:
" **Installation failed**. _Reason for failture_ : **This app is for testing only.** _Suggestion_ : **install the official version of this app.** "
How to solve this problem?
PS: phone: Huawei p40 lite. | Solved this problem with clicking "Build -> Build APK" in IDEA.
It also can be solved via adding:
# Disble testOnly mode for Android Studio
android.injected.testOnly=false
in `gradle.properties` file. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "android, installation"
} |
Save multiple text files to csv files
I'm working on a script to format a directory full of text files and export them to CSV files. I want it to perform the search and replace on each file to format it properly, export it to a CSV with the same filename, then move to the next txt file. I have the search and replace working, but can't work out how to save each text file with its original filename. What am I doing wrong?
$path = "H:\My Documents\EmailSaveAs\"
$files = Get-ChildItem -Path $path -include *.txt -recurse
echo $files
foreach($file in $files) {
Foreach-Object {
$_ -replace "`r`n`t", "," -replace "\s`r`n", "," -replace "Bytes `r`nOut", "Bytes Out" -replace "`t", "," -replace "Idle-`r`ntimeout", "Idle-timeout" -replace ",#Date", "#Date"
} |
Set-Content $path $(.BaseName + ".csv")
} | Try this:
$path = "H:\My Documents\EmailSaveAs\"
$files = Get-ChildItem $path -include *.txt -recurse
echo $files
foreach($file in $files) {
$updatedContent = Get-Content $file.FullName -Raw | Foreach-Object {
$_ -replace "`r`n`t", "," -replace "\s`r`n", "," -replace "Bytes `r`nOut", "Bytes Out" -replace "`t", "," -replace "Idle-`r`ntimeout", "Idle-timeout" -replace ",#Date", "#Date"
}
$newFilename = [io.path]::ChangeExtension($file, ".csv")
Set-Content $newFilename $updatedContent
}
Your original code was accessing `$_` when it wasn't executing in a pipeline context. Note that the `-Raw` parameter on Get-Content is new in V3. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "powershell"
} |
How to get the last 24 hours worth of videos from a specific channel?
There are solutions for retrieving the last video a user uploaded, but is there a way to actually query a YouTube channel to fetch the ID's of all the videos uploaded in the last 24 hours?
I am hoping that the YouTube has an API parameter for this, but I haven't been able to find one. If the ability to fetch such results is not possible, than my other solution was going to be to fetch the last 10 videos from a channel and see which ones of them have been uploaded within the last 24 hours.
Edit: Here is how I could get a users uploads, but I only want the ones within 24 hours:
def GetAndPrintUserUploads(username):
yt_service = gdata.youtube.service.YouTubeService()
uri = ' % username
PrintVideoFeed(yt_service.GetYouTubeVideoFeed(uri)) | Using the latest Data API do a search.list call setting type = video, channelId and publishedAfter.
That will give you the videos uploaded to that channel in the specified time. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "python, youtube, youtube api, gdata"
} |
How to use tar command options when calling kubectl cp command
It seems the `kubectl cp` command uses `tar` command in the background. How can I use (pass them via the `kubectl cp` command) some of `tar` command options such as `--exclude`? For example, this could be helpful to exclude specific files/directories that are not needed to be copied out of the container.
Thanks | You can do it as -
kubectl exec -n <some-namespace> <some-pod> -- tar cf - --exclude='pattern' /tmp/foo | tar xf - -C /tmp/bar
As example -
I got a pod running in the namespace "pankaj"; and inside my container i got 2 files at path - /tmp/foo
/tmp/foo # ls
file1.txt file2.txt
My use is I want to copy only file file1.txt so I will be doing it like -
kubectl exec -n pankaj <pod name> -- tar cf - --exclude='file2.txt' tmp/foo | tar xf - -C /Users/pa357856/test
the result will be I will get only file1.txt
$ pwd
/Users/pa357856/test
$ ls tmp/foo/
file1.txt | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "kubernetes, copy, command line arguments, kubectl, tar"
} |
What is the most up to date design template I should use?
I am a web-developer and am starting a new project. First step is designing the site. In the past, I have used 960 grid system but I was wondering if this is still the standard pretty much? Is there something better now that suits the responsive craze? | Well there is now 978.gs that is better than 960. That said there is no reason to use 978.gs or 960 but since the OP asked for a web design template other than 960 I provided the solution of 978.gs. You ask for a design template when you should be designing in the browser if you're using Bootstrap. If you use 978.gs you will need to build your own CSS which defeats the purpose of Bootstrap.
If you are going to target responsive I would suggest looking into Bootstrap or Foundation and start learning how to design in the browser.
Google search for designing in the browser.
Also, not to be rude, the 1st step isn't "designing", you are missing a few steps:
* Purpose and goals
* content strategy
* sketch/mockup
* wireframe | stackexchange-graphicdesign | {
"answer_score": 3,
"question_score": 0,
"tags": "website design, template design, responsive design"
} |
How can I reduce whistling due to wind across a gas fireplace vent?
We have a gas fireplace venting through the roof of our attic bedroom; there's a cap on a chimney up there. Double-wall construction, such that it pulls combustion air in from outside.
When the wind blows, the vent whistles loudly.
How can I reduce this noise? | The first thing I would check, is to make sure there are no blockages in the vent. If there is debris restricting the flow of air, it could produce noise.
Another cause of this could be that the wind is blowing just rught across the top of the pipe causing it to vibrate, similar to blowing across the top of a bottle to produce sound. To prevent this, you could try cutting small V shaped notches around the perimeter of the end of the pipe.
!enter image description here
Cutting the end of the pipe at a slight angle (2-5° < 90°), may also prevent the wind from crossing the end of the pipe in a way that produces noise.
!enter image description here | stackexchange-diy | {
"answer_score": 3,
"question_score": 3,
"tags": "vent, exhaust vent, chimney, noise"
} |
Why a decimal value from MySQL is converted into/shown as integer?
My database includes a table named `Quotations`. This table has a column named `Cost` with a datatype _decimal (10, 2)_. Values are saved/updated as per my expectation inside the column just like (`25.75`, `4.35`, `10.38` etc).
Problem is that whenever I use `{{ $quotation->cost }}` to display the information, all the _decimals_ are printed as _integers_ like (`25`, `4`, `10`). But if I check it with `{{ dd($quotation) }}`, it shows all the exact decimal values like (`25.75`, `4.35`, `10.38` etc).
I shall appreciate it if someone points out the root cause of the problem. | Problem solved. I thank everybody for your timely responses.
Before the solution, I actually was ignoring `protected $casts = [ 'cost' => 'integer' ]`. Replacing `integer` to `float` resolved my issue. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, laravel, decimal"
} |
Какую почту указывать в заявку на бесплатную ultimate версию?
Помогите кто подавал заявку, будучи студентов ВУЗа, на получение бесплатной ultimate версии intelliji IDEA, в заявке надо указать свою почту(она у меня на @mail.ru) или какую-то вузовскую на @bsuir.by(ВУЗ БГУИР - Минск, Беларусь) P.S. : смущает фраза при подаче заявки "Я подтверждаю, что указанный адрес электронной почты в университетском домене корректен и принадлежит мне" | Почту, выданную ВУЗом с его доменом. Эта почта принадлежит тебе, она просто сделана ВУЗом, все в порядке там. Я также регистрировался, скачивал, все ок. | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "intellij idea, free, version"
} |
How can I synchronize multiple processes in Erlang?
I'm thinking about implementing a GPS+I2C inertial measurement system (IMU) in Erlang. I would like to start taking multiple samples from a set of I2C slaves based on the GPS 1PPS mechanism, in order to measure everything at the same time.
Since Erlang uses message queues for receiving messages, what can I do to ensure synchronization between GPS and I2C sensors? Can I handle both in separate processes without losing synchronicity? | > How can I synchronize multiple processes in Erlang?
receive
{Pid1, Data} -> do_something
end,
receive
{Pid2, Data} -> do_something
end
receive
{Pid3, Data} -> do_something
end,
...
The first receive will block until data from the process with pid Pid1 sends a message. If the Pid1 process takes the longest to execute, then the subsequent receives will all execute immediately. If the Pid1 process takes the least amount of time to execute, then at least one of the subsequent receives will block.
The overall result is that all the receives will execute in the time it takes for the longest process to finish and send a message. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "gps, erlang, i2c"
} |
Using Office Ribbon in a Word Processor
I heard Microsoft allows use of commercially available Office UI controls, with the exception of competing products, such as a word processor or spreadsheet app, etc.
How true is that?
Also, if it is not true, do you know of any _free_ Ribbon controls? | You should look at Jensen Harris' blog entry about licensing the Office user interface which explains it in great detail. However I believe the relevant point here is:
> There's only one limitation: if you are building a program which directly competes with Word, Excel, PowerPoint, Outlook, or Access (the Microsoft applications with the new UI), you can't obtain the royalty-free license. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "user interface, ms office, ribbon"
} |
iOS7.1 keyboard blur
!enter image description hereI was developing an app and I ran into this issue. How would I achieve a keyboard background blur like the one in youtubes iphone/iPad app? I can't figure it out. Any help would be awesome! | Set the Keyboard appearance property to `UIKeyboardAppearanceDark`.
## Example
[textField setKeyboardAppearance:UIKeyboardAppearanceAlert];
## From the documentation
//
// UIKeyboardAppearance
//
typedef NS_ENUM(NSInteger, UIKeyboardAppearance) {
UIKeyboardAppearanceDefault, // Default apperance for the current input method.
UIKeyboardAppearanceDark NS_ENUM_AVAILABLE_IOS(7_0),
UIKeyboardAppearanceLight NS_ENUM_AVAILABLE_IOS(7_0),
UIKeyboardAppearanceAlert = UIKeyboardAppearanceDark, // Deprecated
}; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "ios"
} |
AWK counting back
I have a list of domains matched and piped in through grep with various length but all match the last three records. I'm trying to output all of the non-qualified sub-domains.
I have:
awk -F'.' -v OFS='.' '{$(NF-3)=$(NF-2)=$(NF-1)=""; print $0}'
my output leaves trailing ...... on the output
Thanks | Try substituting them:
$ awk -F'.' 'sub(FS $(NF-2) FS $(NF-1) FS $NF,"")' <<<"www.cse.iitb.ac.in"
www.cse
I'm not sure why this works and your method doesn't, but according to this unix.com post, that's the way. | stackexchange-askubuntu | {
"answer_score": 0,
"question_score": 0,
"tags": "awk"
} |
Python one-liner to standardise input string
I'm trying to standardise the user input in this format: `dddL` where `d` is a digit and `L` a capital letter. If the user doesn't add enough digits, I want to fill the missing digits with leading zeroes, if he adds anything else than at most 3 digits and a letter, just reject:
input/standardised example:
input: '1a'
output: '001A'
input: '0a'
output: '000A'
input: '05c'
output: '005C'
input: '001F'
output: '001F' (unchanged)
input: '10x'
output: '010X'
input: '110x'
output: '110X'
My broken attempt right now returns nothing for some reason: (doesn't yet deal with rejecting invalid input)
>>> x = ['0a', '05c', '001F', '10x']
>>> [i.upper() if len(i)==4 else ('0' * j) + i.upper() for j in range(4-len(i)) for i in x]
[]
I'm not looking necessarily for list processing, I only want it to work for a single variable as input | One implementation:
acceptableInput = re.compile(r"\d{3}[A-Z]")
paddedInput = i.upper().zfill(4)
if acceptableInput.match(paddedInput):
# do something
else:
# reject | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, list comprehension"
} |
Cannot uninstall Miktex 2.9 on Windows 10 due to administrative/shared setup
When trying to uninstall (Settings >> Apps & Features >> Miktex 2.9 >> Uninstall) a regular Miktex 2.9 installation (user installation, not administrator) on Windows 10, I encounter the following error:
MiKTeX
---------------------------
Administrative startup refused because this is not a shared MiKTeX setup.
---------------------------
OK
Miktex itself is broken (some .exe files are missing, the updating process in Miktex Console fails with an error, execution of pdflatex doesn't work, etc.), so I'd like to completely uninstall it and do a fresh new installation. Any help is appreciated. | For me, I found that the error message was correct: I hadn't installed MiKTeX for all users (i.e. "not shared") and therefore admin rights were not needed to uninstall. I don't know why the uninstaller is not smart enough to handle this scenario, but **the solution is simple:**
Open the MiKTeX Console as usual (no admin rights), go to the "Cleanup" tab, then select Uninstall (screenshot below).
.
The linked document states that the service is `Highly scalable, available, and durable`, but I can't find more details on what exactly that means. For example, is it replicated across all regions?
Is it best to:
a) read secrets from the parameter store at application startup (i.e. rely on it being highly available and scalable, even if, say, another region has gone down)?
or
b) read and store secrets locally when the application is deployed? Arguably less secure, but it means that any unavailability of the Parameter Store service would only impact deployment of new versions. | If you want to go with the parameter store go with your option a. And fail the app if get parameter call failed. (This happens, I have seen rate limiting happening for Parameter Store API requests) See here.
Or
The best option is AWS secrets manager. Secrets manager is a superset of the parameter store. It supports RDS password rotation and many more. Also its **paid**. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "amazon web services, aws ssm"
} |
Keep getting The provider requires SessionState to be enabled on IIS 6
While trying to deploy a simple asp.net mvc project on an IIS 6 server, I keep getting this error " **The provider requires SessionState to be enabled** ".
To rule out that I am doing something wrong, I am now trying to deploy just the template you get when you start a new asp.net mvc solution in vs2008. And yes, I have enabled session state in IIS config, also added the `<sessionState mode="InProc" />` line to web.config, but that didn't make any difference.
Tried both the .mvc isapi mapping, as well as the wildcard mapping, and I still get the dreaded error message.
Am I overlooking something obvious ? | Not really an answer, but what I did was to add a new site to IIS, and let that run on port 81. It's for internal test / demo purpose, so that's not much of a problem.
Then I set up a virtual directory as you can read from many guides out there, setup wildcard isapi rule to the .net 3.5 dll and the site was up right away.
I now ran into the _The provider requires SessionState to be enabled_ \- error twice. On my testmachine at home and here at work, while deploying an mvc site to the default website in IIS 6, something must be going wrong, but can't tell you what...
And thanks Chad for trying to help me ! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": ".net, asp.net mvc, iis 6"
} |
How fast is memcached set operation?
I need to design a cache for storing objects coming in from multiple clients. These clients can all come in parallel. These objects need to stored on memcached, and retrieved later for use.
String newKey ;
private synchronized String setData(Data newData) {
do {
newKey = createRandomKey() ;
} while (memcacheClient.get(newKey) != null) ;
memcacheClient.set(newKey, 10000, newData) ;
}
My question is, will this method become a bottleneck for parallel client access ?
OR
Should I create a shared List and a Thread. The thread will do the setData, asynchronously ? | The delay of the loop heavily depends on how random createRondomKey can achieve. Do you have to use random keys? Is it possible to come up with some semantic naming schemes (e.g., userid/category/blabla)? That will also save you the efforts to remember the random keys. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, memcached"
} |
Uncertainity regarding the proof from Rosenlicht's "Introduction to Analysis"
I would be very grateful if somebody could explain me the part in the red rectangle in the proof below. I don't quite get it why the author claims that if $\delta$ is sufficiently small then $p+1\le q-1$. I don't get it why it is the consequence of the inequality $\beta-\alpha \le x_q-x_{p-1}<(q-p+1)\delta$. Thank you for the explanation.
* * *
/2$, then $$\beta - \alpha < (q-p+1)\delta \leq (q-p+1)(\beta-\alpha)/2,$$ hence $$2 < q - p + 1.$$ The desired inequality follows from this.
Put simply, as the step $\delta$ of the partition becomes small, some $x_i$'s must begin to appear between $\alpha$ and $\beta$. When that happens, the first $x_i$ to the right of $\alpha$ is less than or equal to the last $x_i$ to the left of $\beta$. The calculation given determines how small this $\delta$ has to be. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "calculus, real analysis, integration, proof explanation"
} |
what would be the folder name according to resolution and language in android drawable folder?
friends,
i want to support multiple resolutions and languages in my android application.
now problem is
i have following folders in my drawable folder
1)drawable-hdpi 2)drawable-ldpi 3)drawable-mdpi
and for languages
1) drawable-en-rUS
what would be the combination of these? so that android could understand(which folder to use) for example low resolution with english language support folder.
do i need to combine these both names or what is the solution?
any help would be appreciated. | E.g. `drawable-en-rUS-port-hdpi`. See the docs for further info. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "android, resolution"
} |
Hibernate is unable to retrieve a value
I have following classes and need to execute a criteria on them, but hibernate does not find the property.
Class Car extends Vehicle
{
String name;
getter and setter of name;
}
Class Vehicle {
Engine engine;
@OneToOne(cascade = CascadeType.ALL)
public Engine getEngine() {
return engine;
}
setter goes here
}
Class Engine {
String name;
getter and setter of name;
}
My Code
....
Criteria cre = session.createCriteria(Car.class,"car");
cre.add(Restrictions.eq("engine.name", "314Full));
return (Car) cre.list().get(0);
....
It runs into following error
**could not resolve property: engine.name of: com.myproject.car** | Try
session.createCriteria(Car.class,"car").createAlias("engine","engine"); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "hibernate, jakarta ee"
} |
Insert element in Array (Matlab)
I need to insert a 0 in my array after the `if` condition is right.
Here is my attempt:
for i=1:length(HPred)
if HPred(i) ~= HPired(i)
if HPred(i) - HPired(i) > 5
HPred(i) = [HPred(i) 0 ]; % Here is the problem
i=i+1;
elseif HPred(i) - HPired(i) < -5
HPired(i) = [HPired(i) 0]; %also
i=i+1;
end
end
end
The error Code is:
> In an assignment A(:) = B, the number of elements in A and B must be the same.
> Error in Einlesen (line 167) HPired(i) = [HPired(i) 0];
Can someone help me? | You can insert like so:
HPred = [HPred(1:i) 0 HPred(i+1:end)];
As you write and the gotten error body, it does not meaningful in syntax. Also you can define an inline function using `cat` (to concatenate matrices) as mentioned here:
insert = @(a, x, n)cat(2, x(1:n), a, x(n+1:end));
insert(3, [1,2,4,5], 2)
> ans = 1 2 3 4 5
And you can use it for your case:
HPred = insert(0, HPred, i); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "arrays, matlab, insert"
} |
WebSphere/Rational Application Developer(RAD), tmp directory for builds?
I am trying to build my java classes but they aren't going to the directory defined in the WEB-INF/classes directory.
RAD will build but the class files aren't output. And they also aren't output to the:
.metadata.plugins\org.eclipse.wst.server.core
Directory either. There must be a temp place for the classes? Do you know where they are?
The IDE doesn't show errors, so I am assuming RAD is doing some kind of internal build? | I fixed the issue by disabling the Java Builder and then enabling the builder and the classes are now outputting. Strange | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, websphere, rad"
} |
Is is possible to set per file custom metadata in dropbox
I want to be able to set custom metadata on a file in dropbox. Ideally a string of at least 32 bytes for each file. I've looked through the core API docs but I haven't seen a way.
However I'm new to Dropbox so maybe I missed something or there is another way?
Thanks! | There isn't any way to set additional metadata on the file for your app. You could use the Datastore API (< to store the string and the associated file path. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "dropbox, dropbox api"
} |
Adding/Removing MetaColumn from MetaTable
I'd like to add/remove a column from MetaTable. But `table.Column` is of type `ReadOnlycollection<MetaColumn>`.
How can I modify, add or remove a column from the table?
Thank you. | Have you tried ScaffoldColumn?
[MetadataType(typeof(FooMetadata))]
[TableGroupName("Foo")]
public partial class Foo
{
[ScaffoldColumn(true)]
public string MyNewColumnNotinDBTable
{
get
{
return "FooBar";
}
}
}
public class FooMetadata
{
[ScaffoldColumn(false)] // hide Id column
public object Id { get; set; }
public object Name { get; set; }
public object MyNewColumnNotinDBTable { get; set; }
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net, dynamic data, metatable"
} |
Excel SUM current column (via Excel::Template)
I'm using Excel::Template to generate a series of Excel files via perl. However, I need to do a `SUM` function on the current Column. I know I can do
=SUM(3:15)
but that gives the sum of _ALL_ columns in rows 3-15. Is there an easier way to do what I'm trying to do? | =sum(indirect(concatenate(address(<row_start>,column()),":")&address(<row_end>,column())))
gives me exactly what I need. Not exactly sure how it works, but found on MrExcel.com | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "perl, excel, excel template"
} |
Can't require gem in IRB console using jruby
I'm using jRuby at the moment (version 1.6.5) on my local machine.
rvm use jruby
If I do a
which cucumber
I get /Users/sebastiano/.rvm/gems/jruby-1.6.5.1/bin/cucumber
but when I open up the Ruby console (irb) and I try requiring 'cucumber'
require 'cucumber'
I get:
LoadError: no such file to load -- cucumber
Any clue on that? I can see the gem installed in '/Users/sebastiano/.rvm/gems/jruby-1.6.5.1/gems' | Actually I got it. I had to do `require 'rubygems'` as the first instruction. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ruby, rubygems, jruby, irb"
} |
How to hide projects in "my timesheet" for users not assigned to the project in openerp 7.0?
Currently i have a question regarding the my timesheet function. If i create a project and select the `timesheet/stundenzettel` box, the employees are able to enter their working hours on the specific project using the my `timesheet/"mein stundenzettel"` function. So far so good. Unfortunately every user can book on every project where the `timesheet/stundenzettel` box is checked, regardless if he is a member of the project team or not.
As an example i have some freelancers working and some projects but i do not want them to
see all company projects
be able to book their working time on wrong projects
Is there a way to only show projects where the user is assigned to? | You need to define the access control list for the timesheet model. You can do that in the Settings >> Technical >> Security >> Access Control List.
In the ACL you can define the rules for accessing the different models. If you need to see how it works, you can check ACLs defined by the sales module. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python, odoo"
} |
Silverlight 4: Any touch library that supports gestures & touch events?
Silverlight provides only Touch.FrameReported event and doesnt provide any events for the UIElements like it does for mouse events(ex: MouseDown, MouseUp). Is there any touch library available for the silverlight which provides these touch events and supports gestures.
Google did not help me much or may be my search terms are not correct. Any pointers will be appreciated. | Here is some useful stuff, but it is nowhere near a complete library:
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "silverlight, multi touch"
} |
How to convert 8.991M and 0.785M to number like 8.911.000 and 785.000 in Excel?
I would like to convert 8.991M to million in Excel, -> 8.991.000
Here are some examples I have in the data set, with negative values as well.
0.785M
0.452M
0.414M
7.459M
3.355M
3.548M
-0.405M
-2.549M
1.164M
-11.463M | ## VALUE & SUBSTITUTE
=VALUE(SUBSTITUTE(SUBSTITUTE(A1,".",""),"M",""))*1000
Format cells by using e.g. `Right-Click > Format Cells > Number Tab > Select Number`. Set `Decimal Places` to `0` and tick `Use Thousands Separator`.
, SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)
Suppose I have 5 entry in list and entry no. 4 is hidden. when I select entry no. 5 above signal giving me current Index as entry no. 4 of hidden item.
how can I select correct Index (should be 5) when item is hidden in list? | I think what you're looking for is `QSortFilterProxyModel::mapToSource`. It takes the proxy's index and returns the corresponding index from the source model.
QModelIndex proxyIndex = <whatever>
QModelIndex sourceIndex = myProxyModel.mapToSource(proxyIndex); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "qt5, qtableview, qstandarditemmodel, qsortfilterproxymodel"
} |
using threading for multiple requests
In order to test our server we designed a test that sends a lot of requests with JSON payload and compares the response it gets back.
I'm currently trying to find a way to optimize the process by using multi threads to do so. I didn't find any solution for the problem that I'm facing though.
I have a url address and a bunch of JSON files (these files hold the requests, and for each request file there is an 'expected response' JSON to compare the response to). I would like to use multi threading to send all these requests and still be able to match the response that I get back to the request I sent.
Any ideas? | Well, you have couple of options:
1. Use `multiprocessing.pool.ThreadPool` (Python 2.7) where you create pool of threads and then use them for dispatching requests. `map_async` may be of interest here if you want to make async requests,
2. Use `concurrent.futures.ThreadPoolExecutor` (Python 3) with similar way of working with `ThreadPool` pool and yet it is used for asynchronously executing callables,
3. You even have option of using `multiprocessing.Pool`, but I'm not sure if that will give you any benefit since everything you will be doing is I/O bound, so threads should do just fine,
4. You can make asynchronous requests with `Twisted` or `asyncio` but that may require a bit more learning if you are not accustomed to asynchronous programming. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, multithreading, python 2.7, asynchronous"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.