INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Ubuntu 17.10 - Poweroff operation is inhibited by myself
When I find myself in a terminal and want to shut down my computer, I will often use the poweroff command. This has always worked for me on Ubuntu 16.04 64-bit. However, on Ubuntu 17.10 64-bit, I am getting this message:
aaronfranke@ub17vm:~$ poweroff
Operation inhibited by "aaronfranke" (PID 951 "gnome-session-b", user aaronfranke), reason is "user session inhibited".
Please retry operation after closing inhibitors and logging out other users.
Alternatively, ignore inhibitors and users with 'systemctl poweroff -i'.
I know that I can work around the issue using the suggested command, but I want to know, why is this happening? Is there an issue that can be fixed? Should I bother to fix it?
|
Similar messages can appear when you type `reboot` in the command line. The solution is to use `sudo reboot` instead. In your case it would be `sudo poweroff` or `sudo shutdown` which does the same thing. Always make sure you have saved all your work and closed down Libre Office, etc.
The other solution for me is to pick **Reboot** from the system menu. In this case the `sudo` isn't necessary. In you case you would pick **Shutdown** from the system menu.
Lastly, you can do as the message suggests and use:
systemctl poweroff -i
|
stackexchange-askubuntu
|
{
"answer_score": 4,
"question_score": 4,
"tags": "command line, 17.10, shutdown"
}
|
Energy and pressure relationship for cosmic rays
How to prove $E = 3P$ for cosmic rays? In other words $\gamma = \tfrac43$ for cosmic rays. Whereas for $\gamma=\tfrac53$ we have $E = \tfrac32 P$.
|
The difference in the denominator is usually linked to diferent power laws in the one-particle Hamiltonian of non-interacting systems (e.g. classic ideal-gas: $H_i=\frac{\vec{p}^2_i}{2m}$, ultrarelativistic gas: $H_i=|\vec{p_i}|c$).
This discussion can be of interest.
|
stackexchange-physics
|
{
"answer_score": 0,
"question_score": 0,
"tags": "energy, fluid dynamics, statistical mechanics, pressure, cosmic rays"
}
|
intellij idea 2016 автоматически удаляет неиспользуемые и неправильные import-ы?
Привет знатокам! Навел курсор на класс, который хотел добавить в Maven, Нахал Alt+Enter, 2 раза стрелкой вниз (думал, что это Add depen. по привычке), но теперь студия скрывает все импорты. ИХ просто не добавляет. Как можно это исправить, товарищи ? В настройках Imports ничего нет
|
File - Settings - Editor - General - Auto Import убирать галочку "Optimize imports on the fly"
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "intellij idea"
}
|
Change units from degrees to meters in QGIS 3.6
I'm cleaning up shapefiles (mainly for US areas) in QGIS 3.6 to import into other CAD environments such as Rhino. One problem encountered is that the units are in degrees, resulting in imports being several orders of magnitude wrong. How do I change the unit to meters?
I searched and understand it's something to with the CRS (switching to UTM instead of WGS), but as there seems to be many options/zones, I'm not really sure which is the correct one.
 into 64-bit using .net 4.0 and VS2010 on a W7/x64 OS. I have purchased a commercial license, if that matters and downloaded from the links provided in the receipt.
The error is
System.TypeInitializationException was unhandled
Message=The type initializer for 'Emgu.CV.CvInvoke' threw an exception.
Source=Emgu.CV
TypeName=Emgu.CV.CvInvoke
I followed the instructions provided in this article. In fact I used the samples projects in the article and they build fine with V2.2, but when I replace with V2.3 binaries (both emgu and opencv), run into the error.
Has anyone successfully built an Emgu ( **Version 2.3.x** ) x64 project? Please provide some guidance.
|
The cause of this error (should anyone else run into the same problem) is that the program cannot access opencv_imgproc231.dll or opencv_core231.dll even though they are present in the output "bin" directory.
There are two solutions:
1. Add them to the project and set their properties to `copy always` as they are EMGU's two key files.
2. If step 1 doesn't work, replace the current key files in the bin folder with new copies.
If both methods fail then there may be a problem with the build, so download a new copy of EMGU from Sourceforge and try again. The error will later be incorporated within an technical article in order to provide a clearer explanation of how to solve it.
Cheers, Chris
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c#, opencv, emgucv"
}
|
CP Lockout based on IP alone?
I have a client who has found that when one user is locked out of the CP, all others are locked out too. This makes me think that this is based on IP address alone rather than username.
Anybody got any experience with this issue?
Thanks
EDIT IN RESPONSE TO QUESTIONS:
This happened over a weekend so I wasn't online to check the database at the time. However the message received was 'You are only permitted to make four login attempts every 30 minute(s)'. So one user locked triggered this lockout but it affected all other users in his company.
Looking at the check_password_lockout() method in Session.php it looks like the check is based on username **OR** useragent. So it would appear that if he locked himself out in a particular browser, all other users on that IP would be locked out if they were using the same browser.
I'm not a security expert in any way, but shouldn't that SQL check be **AND** not **OR**? Any thoughts?
|
It's normal that EE restricts logins based on IP address. Restricting on user agent wouldn't be much use, because a malicious script could just change the user agent for every request.
That said, the normal EE error message is `You are only permitted to make four login attempts every 1 minute(s)`. You must have increased this from 1 minute to 30 minutes, which is clearly unusable.
In the control panel, go to **Admin** > **Security & Privacy** > **Security and Sessions**.
There, you will find the setting: **Time Interval for Lockout**
Set this back to `1`, or if that is still too long for you, even `0.5`.
After changing this session, you probably also want to empty the `exp_password_lockout` table to remove any lockouts currently in effect.
|
stackexchange-expressionengine
|
{
"answer_score": 4,
"question_score": 1,
"tags": "login"
}
|
Android Ble, Pheriperal Advertise status during the scan
In my application I need to start some BLE scans, get the results and then show them in a list or in a grid.
When i start the scan my device start to look for advertisements basing on which ScanFilters I wrote.
Every time a Pheriperal is found I the application trigger the scan callback method and i can add the new device into the list.
If i got an error the app trigger the callback method and i can tell the user about the broblem.
**Example**
_Imagine the Scan going on for 30s. At the moment it starts i get 3 Ble Pheriperal. At second 15 one of them stop to advertise and turn bluetooth off. At the end of the scan my list will have 3 Ble devices but i will not be able to connect to one of them._
**How do I know which of them is the one which turned off? Where do i get his status?**
Thanks for the help.
|
You can try this, technically it is possible as per the documentation. in `onScanResult` callback, check for the `callbackType` parameter. If it is CALLBACK_TYPE_MATCH_LOST then get the device from the `results` and remove it from your cache.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, bluetooth, bluetooth lowenergy"
}
|
Use grep output as an ln -s directory
I am writing a bash script where i want to use the grep output below " **06** " in a link i'm creating.
echo [super-shows]Super.Show.S06.1080p.BluRay.DD-EX.5.1.x264 | grep -oP '(?<='S')\d{2}(?=\.)'
ln -s /home/Download/[super-shows]Super.Show.S06.1080p.BluRay.DD-EX.5.1.x264 /home/Media/TV/Super.Show/**06**
|
It's easy with using xargs, propably that is allready installed, if not I'm sure it's available in the package manager for every distribution.
echo "[super-shows]Super.Show.S06.1080p.BluRay.DD-EX.5.1.x264" | grep -oP '(?<='S')\d{2}(?=\.)' | xargs -I{} ln -s /home/Download/[super-shows]Super.Show.S06.1080p.BluRay.DD-EX.5.1.x264 /home/Media/TV/Super.Show/**{}**
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "bash, grep, gnu, gnu parallel, ln"
}
|
How much does nipple choice affect wheel weight/stiffness?
Would I be a fool to replace the nipples on a Dura Ace 7900 C24 wheelset with a set of DT Swiss anodised alloy nipples, in the interest of aesthetics? I want the bike to look nice, but don't want to compromise on performance!
|
Alloy would save a tiny amount of weight. I wouldn't expect it to make any difference to wheel stiffness, so long as you lubricate the threads when building it (alloy nipples are stiffer to turn otherwise, so it's harder to get the tension right). Brass is stronger, but you shouldn't have to rely on that to get a stiff wheel.
But long term, alloy is more likely to seize.
<
<
|
stackexchange-bicycles
|
{
"answer_score": 5,
"question_score": 5,
"tags": "road bike, wheels, performance, wheel building"
}
|
How can I group by a field emitted events?
I have a class User:
class User {
String companyId;
}
and a class Company:
class Company {
String id;
List<User> users;
}
I need to "group" the Users emitted by a `Observable<User>` by company and return a `Observable<Company>`. I have this:
public Observable<Company> getCompanies(Observable<User> users) {
return users.distinct(new Func1<User, String>(){
@Override
public String call(User user) {
return user.companyId;
}
}).map(new Func1<User, Company>(){
@Override
public Company call(User user) {
return new Company(user.companyId);
}
});
}
It works but it's just getting distinct users by companyId. I need to set the `List<User>` of each company. Is there any operator I can use to solve this?
|
Solved! There is a `groupBy` operator -.-"
public Observable<Company> getCompanies(Observable<User> users) {
return users.groupBy(new Func1<User, String>(){
@Override
public String call(User user) {
return user.companyId;
}
}).flatMap(new Func1<GroupedObservable<String, User>, Observable<List<User>>>() {
@Override
public Observable<List<User>> call(GroupedObservable<String, User> grouped) {
return grouped.toList();
}
}, new Func2<GroupedObservable<String, User>, List<User>, Company>() {
@Override
public Company call(GroupedObservable<String, User> grouped, List<User> users) {
return new Company(grouped.getKey(), users);
}
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "rx java2"
}
|
split row_number() over partition over multiple columns
I have a query which uses row_number() over partition. When the result comes out it looks like
Product Row_Number Price
A 1 25
A 2 20
A 3 15
B 1 100
B 2 10
B 3 2
I want to get the result to show over columns like
Product Row1 Row2 Row3 price1 price2 price3
A 1 2 3 25 20 15
B 1 2 3 100 10 2
Should I use something like rank()???
I'm using Teradata
|
You can add two more window functions to get the 2nd and 3rd highest price, this should run in the same STAT-step as your current ROW_NUMBER, so there's no additional overhead:
select
product,
price as Price1,
min(price)
over (partition by product
order by price desc
rows between 1 following and 1 following) as Price2,
min(price)
over (partition by product
order by price desc
rows between 2 following and 2 following) as Price3
from tab
qualify
row_number()
over (partition by product
order by price desc) = 1
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "sql, teradata, row number"
}
|
How can I cut my reputation losses?
I have asked a question, with good intentions, but it seems that it was totally not welcomed by the community. So, how can I cut the reputation losses from that question?
It has an answer, so I can't delete it. I flagged it, but I currently still lose some reputation because of it. What can I do in this situation?
|
Don't point at them and go _"How can I stop the downvotes on that one? That one over there. That question you all find so bad."_. That will have the opposite result.
The questions will most likely remain, but in some time people will have forgotten about them, and they will no longer appear on the front page or on top of most lists. Just move on and focus your attention on better things, if there is no way for you to rescue the question in the first place.
|
stackexchange-meta
|
{
"answer_score": 12,
"question_score": 10,
"tags": "support, reputation, down votes"
}
|
How can I find the source for a DLL\PDB in C#?
I'm attempting to write a C# application that takes built DLLs & PDBs for managed projects and find all the CS\VB files that were used to compile them for cataloging in a database.
Does anyone know of a library that can be used to find all the original source file paths that were used to build a DLL? ICorDebug might do it, but I can't find where to attach the PDB or get a list of source files.
|
The Roslyn repo has an app/library called `pdb2xml` that will list the source files in the PDB.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#, dll, pdb files"
}
|
.NET 4 - Using nullable operator (??) to simplify if statements
I have this piece of code, that checks whether a returned object is null. If so, it will return 0, or else it will return a property inside the object.
var userPoints = (from Point p in entities.Point
where p.UserName == userName
select p).SingleOrDefault();
if (userPoints == null)
{
return 0;
}
else
{
return userPoints.Points;
}
Is it possible to simplify the if statements with the nullable operator? I've tried this, but the system throws an exception when attempting to read the property
return userPoints.Points ?? 0;
|
No, unfortunately there's nothing which will do exactly that. Options:
* Use the conditional operator:
return userPoints == null ? 0 : userPoints.Points;
* Change your query to make _that_ do the defaulting:
return (from Point p in entities.Point
where p.UserName == userName
select p.Points).SingleOrDefault();
Personally I'd go for the latter approach :) If you wanted a default other than 0, you'd need something like:
return (from Point p in entities.Point
where p.UserName == userName
select (int?) p.Points).SingleOrDefault() ?? -1;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": ".net 4.0"
}
|
Autosys Box run configuration
I have an Autosys box and there is a couple of jobs inside it. For example, MY_BOX is the name of the box and it has the jobs JOB_1 and JOB_2.
I would like to configure the box in such a way that it runs continuously. (i.e.) as soon as the JOB_2 completes (success or failure), MY_BOX should start running again. Could you please tell me how to configure this?
I tried setting the "run condition" for MY_BOX as SUCCESS(JOB_2), however, the Box does not start after the completeion of JOB_2.
|
I'm not exactly sure how to make MY_BOX run immediately after the success of JOB_2, but you could set the interval on which MY_BOX runs to just about (or a little bit more) than the average run of MY_BOX.
I.E. - if MY_BOX runs for about 10 minutes, have MY_BOX run every ten/eleven minutes. Or try setting it's condition to the SUCCESS(MY_BOX).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "unix, autosys"
}
|
System subheadings in Android app
Like here.
!enter image description here
Like those blue `phone`, `email` , `adress`. I've been googling for a while, havn't found any built-in way to add them :(. Is there any? (Supporting 2.3, preferably)
**Here is the same question with good answer too** : Android 4.0 Sub-Title (section) Label Styling
**And here is the _more or less_ good way to reach what I want (but it's grey):** `<TextView style="?android:attr/listSeparatorTextViewStyle" ... >`
|
To get 2.x support, you can use the HoloEverywhere library.
The style you are looking for is "Holo.TextView.ListSeparator(.Light)"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, user interface, heading"
}
|
How do I find an isomorphism between varieties
Our book defines an isomorphism between varieties when there exist two maps say $\phi: V \rightarrow W$ and $\psi: W \rightarrow V$ both morphisms and $\psi \circ \phi =id_V$ and $\phi \circ \psi =id _W$. I am confused how do I find such maps in general because when I am given the maps it is one thing to check but I have no idea how to define such a map. For example
$V=V(x+y,z-1)$ and $W=V(x-z^2, y+z)$ both in $K^3$ algebraically closed field. So I guess what I know is that I want $\psi \circ \phi =(x,y,z)$ and $\phi \circ \psi =(x,y,z)$. Then I do not know that to look at. Can someone guide me through to understand how to make isomorphism?
|
The category of affine varieties over $K$ is equivalent to the category of reduced finitely generated $K$-algebras (If you wish irreducible on the variety side, you have to add integral domain at the algebra side).
So you have to show (or to find an isomorphism) $$K[x,y,z]/(x+y,z-1) \cong K[x,y,z]/(x-z^2,y+z)$$
Both are isomorphic to the polynomial ring in one variable.
So as a instruction I would suggest to find isormorphisms
$$K[x,y,z]/(x+y,z-1) \cong K[x] \cong K[z] \cong K[x,y,z]/(x-z^2,y+z)$$
and take the composite to be your desired isomorphism. Once you have done that, you will not have a problem giving the inverse isomorphism.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "algebraic geometry, commutative algebra"
}
|
getting weird extra numbers on program to count down in python
sorry if the title is weird. I don't know how else to word my problem. I am trying to make a program to start at 2 and count down by 0.1 seconds until zero. this is the code I have so far
import time
starting_int = 2
for i in range(20):
time.sleep(0.1)
print(starting_int)
starting_int -= 0.1
I am getting this result
2
1.9
1.7999999999999998
1.6999999999999997
1.5999999999999996
1.4999999999999996
1.3999999999999995
1.2999999999999994
1.1999999999999993
1.0999999999999992
0.9999999999999992
0.8999999999999992
0.7999999999999993
0.6999999999999993
0.5999999999999993
0.49999999999999933
0.39999999999999936
0.2999999999999994
0.19999999999999937
0.09999999999999937
if it is at all possible to just get the first 2 int. please let me know how I can fix my problem.
|
I think the problem before was that it was an integer not a float and so this should work
import time
starting_int = 20
for i in range(20):
time.sleep(0.1)
print(starting_int / 10)
starting_int -= 1
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, math, counting"
}
|
Ignore proxy for specific request
**How do I prevent Ember from proxying specific requests?**
I have an API listening on port 3000, so when I serve my Ember app I run:
ember server --proxy
Everything runs fine except when my app sends Bootstrap GET requests to my API (which isn't meant to handle them). Here's the error I get:
GET /assets/bootstrap.css.map - - ms - -
Error proxying to
connect ECONNREFUSED 127.0.0.1:3000
The page ends up loading correctly, but it takes a long time because it's waiting for my API to timeout the request.
|
Issue went away when I removed `/*# sourceMappingURL=bootstrap.css.map */` from `bootstrap.css`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ember.js"
}
|
How can i use JSON stringify in Angular?
i'm newbie to Angular. I'm trying to get Json data which written like that :
id:1,
name: "Friends",
type: "Group",
Now, i know i can't use this kind of data unless i add double quotes - like that (it's the only way it is working):
"id":1,
"name": "Friends",
"type": "Group",
What is the best way to parse JSON in Angular?
I've tried to combine JS , but it didn't work :
app.controller('contacts', function ($scope,$http,$log) {
$http.get('
.then(function(response) {
$scope.myData = function() {
return JSON.stringify(response.data)
};
$log.info(response.data.name);
});
});
|
You can use `angular.fromJson` and `angular.toJson` for that purpose:
scope.myData = function(){
return angular.fromJson(response.data);
}
However JSON is a global variable and you should have access to it, since angular uses the same.
< <
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "angularjs, json"
}
|
How can i merge/combine multiple projects into one in android studio?
i have three separate projects in android studio say A , B and C with A being the main project, i want B and C to be part of A, say when clicking in a button it takes me to B and another button to C. Any suggestions guys? thanks.
|
Found a solution to my problem: first of all make sure that build.gradle of your apps in the projects you want to combine has the same information(sdk version etc.. and sync after changing), then just copy the necessary files(.java and .xml from project B to A) and make sure to change the package name starting with com. in the java files of project B to the same package name of the project A, lastly add the activities of the new java files added in the manifest. That worked for me, hope it does for you too!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android"
}
|
Integral from superconductivity theory
I am dealing with the following integral $$\int_{0}^{\infty}\frac{dx}{x^2}\left(\frac{1}{\cosh^2x}-\frac{\tanh{x}}{x}\right).$$ My attempt to calculate this integral: calculate residues of $$f(x)=\frac{x-\sinh x\cosh x}{x^3\cosh^2 x},$$ then use Cauchy theorem about residues (integration over the contour over Im axis). I know that the answer is $-7\zeta(3)/\pi^2$, but I don't understand how to check it.
The function $f(x)$ has the second order pole at $x_0=i\pi/2+i\pi n$ (also the third order poles at $x=0$ but it's not important). To calculate residue, I use $$\mathrm{res}\,f(x)=\lim\limits_{x\rightarrow x_0}\frac{1}{2}\left[f(x)(x-x_0)^2\right]'.$$
Can anyone help with this integral?
|
Nice question. We may start with the Weierstrass product for the hyperbolic cosine: $$ \cosh(x) = \prod_{n\geq 0}\left(1+\frac{4x^2}{\pi^2(2n+1)^2}\right) \tag{1}$$ and apply $\frac{d}{dx}\log(\cdot)$ and $\frac{d^2}{dx^2}\log(\cdot)$ to both sides, getting: $$ \frac{\tanh x}{x}=\frac{8}{\pi^2}\sum_{n\geq 0}\frac{1}{\pi^2+(2n+1)^2 x^2} $$
$$I= \int_{0}^{+\infty}\frac{dx}{x^2}\left(\frac{1}{\cosh^2(x)}-\frac{\tanh(x)}{x}\right) = -\sum_{n\geq 0}\int_{0}^{+\infty}\frac{64\,dx}{\left(4x^2+\pi^2(2n+1)^2\right)^2}\tag{2} $$ Computing the inner integrals we get $$ I = -\sum_{n\geq 0}\frac{8}{\pi^2(2n+1)^3}=-\frac{8}{\pi^2}\left[\zeta(3)-\frac{1}{8}\zeta(3)\right]=\color{red}{\frac{-7\zeta(3)}{\pi^2}}.\tag{3} $$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 3,
"tags": "definite integrals, contour integration"
}
|
I have to return filtered object
I have array, which i get from checkbox checking. And I have array of objects with categrories. I want to get an array filteredPeople that contains only objects with categories that contains at least one of from selectedClicents
let selectClients = ['Web', 'Design'];
let people = [
{ category: ['Web', 'Design'] },
{ category: ['Web'] },
{ category: ['PWA', 'Design'] },
{ category: ['Ecommerce'] },
];
|
You can use `Array.prototype.some` and `Set.prototype.has` along with `filter` to get the filtered list from `people` array
I've used a ES6 `Set` for O(1) lookup:
const selectClients = ['Web', 'Design'];
const keys = new Set(selectClients);
const people = [
{ category: ['Web', 'Design'] },
{ category: ['Web'] },
{ category: ['PWA', 'Design'] },
{ category: ['Ecommerce'] },
];
const res = people.filter(({category}) => category.some(cat => keys.has(cat)));
console.log(res);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, arrays, object, filter, filtering"
}
|
Old-style/Antique typesetting in LaTeX/TeX
I would like to typeset a page that looks "antique." Are there packages/fonts in LaTeX that do that? I could find antique fonts online, but they don't include math symbols. An < (dated 2006) lists various free math fonts that were available then, but none of them look antique.
Examples of what I am looking for:
1. Einstein's General Relativity Paper
2. JSTOR; American Mathematical Monthly, in 1960 (requires subscription)
3. Another one from JSTOR (AMM 1960)
4. JSTOR; AMM (1894)
Thanks!
|
If you don't mind using XeLaTeX, you could use the Old Standard font, which is available on CTAN (though not packaged for regular TeX/pdfTeX, unfortunately), along with the mathspec package as so:
\usepackage{mathspec}
\defaultfontfeatures{Mapping=tex-text}
\setallmainfonts{Old Standard}
Here's a screenshot taken from the \blindmathpaper command generated by the blindtext package.
!old standard font in XeLaTeX
It doesn't have its own math symbols, so some of these are taken from Latin Modern (--the default behavior with mathspec--), but I think they go well enough together.
|
stackexchange-tex
|
{
"answer_score": 12,
"question_score": 30,
"tags": "fonts"
}
|
Google script Create new sheet file and move it to a specific folder Then copy the contents and 2 tabs from the active sheet to the newly created file
Welcome: I will not go into the code at the beginning, but I would like to ask a few questions. To learn the logic of operation.
Question 1:
When I create a new file using the function
var newFile = SpreadsheetApp.create("Name new sheets")
var newFileId = newFile.getId()
A new file is always saved to the root directory of the google disk?
Question 2
If I always write root directory of the google disk.The only way to move a newly created file is to use
var TARGE_FOLDER_ID = "asdFHd4hasdasn6nJMGLSQt8das331"
DriveApp.getFileById(newFileId).makeCopy("Name new sheets",TARGE_FOLDER_ID);
And after copying the removal from the main google drive folder?
|
> When I create a new file using the function
Yes `SpreadsheetApp.create("Name new sheets")` puts files in the root directory you will have to move them
> If I always write root directory of the google disk.The only way to move a newly created file is to use
Yes something like this Move file
var folder=DriveApp.getFoldersByName(folderName).next();//gets first folder with the given foldername
var file=SpreadsheetApp.create(fileName);
var copyFile=DriveApp.getFileById(file.getId());
folder.addFile(copyFile);
DriveApp.getRootFolder().removeFile(copyFile);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "google apps script, google sheets, google drive api"
}
|
Ember RESTAdapter not populating my store
i'm trying to write a simple ember application based on RESTful API. My code looks like that:
### store.js.coffee
DS.RESTAdapter.reopen
namespace: 'api/v1'
EmberClient.Store = DS.Store.extend
adapter: DS.RESTAdapter.create()
### routes/songs.js.coffee
EmberClient.SongsRoute = Ember.Route.extend
model: ->
@get('store').findAll('Song')
### models/song.js.coffee
EmberClient.Song = DS.Model.extend
title: DS.attr('string')
### api response:
{"songs":[{"id":10,"title":"Intro"},{"id":12,"title":"Fantasy"}]}
The thing is, i'm not able to loop through the results in my template cause the store is null. Request to my API is fired, api response is returned but EmberInspector says, that `EmberClient.Song` has 0 records.
|
You have some errors
1- Change your store definition to `adapter: DS.RESTAdapter` instead of `adapter: DS.RESTAdapter.create()`:
EmberClient.Store = DS.Store.extend
adapter: DS.RESTAdapter
If you remove the code above will work too, because ember by default use the `DS.RESTAdapter`.
2 - Use `findAll('song')` instead of `findAll('Song')`
Here is a jsbin with this working <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, ember.js, ember data"
}
|
Test for absolute convergence $\sum_{k=1}^\infty \frac{(-1)^{k+1}k^k}{(k+1)^k}$
Test for absolute and conditional convergence. $$\sum_{k=1}^\infty \frac{(-1)^{k+1}k^k}{(k+1)^k}$$
$$\lim_{k\to\infty}|a_n| = \lim_{k\to\infty} \frac{k^k}{(k+1)^k}$$ I'm stuck on what to do next.
|
Hint: $$\left(\frac{k}{k+1}\right)^k = \frac{1}{\left(1+\frac{1}{k}\right)^k}$$
What is the limit of $\left(1+\frac{1}{k}\right)^k$?
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "real analysis, analysis"
}
|
How to declare multiple register variables in one line in c?
I'm implementing destroy method for a linked list by keeping pointers to previous and current nodes. I'd like to declare them as register variables in a single line. Is it possible?
void list_destroy(list *ls) {
// does this mean both prev and curr are register variables?
register node *prev, *curr;
for (prev = 0, curr = ls; curr != 0; curr = curr->next) {
if (prev != 0)
free(prev);
prev = curr;
}
free(ls);
}
or
void list_destroy(list *ls) {
node register *prev, *curr;
for (prev = 0, curr = ls; curr != 0; curr = curr->next) {
if (prev != 0)
free(prev);
prev = curr;
}
free(ls);
}
|
`register` is a storage class specifier, so it applies to all the declarators in the declaration. It applies to bit `prev` and `curr` in these examples.
Commonly, you put storage class specifiers first on the line (before any type specifiers) but that is not required. Storage class and type specifiers can be in any order (but all must be before the declarators and any pointers or qualifiers or other modifiers on the declarator)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c, syntax"
}
|
Can I control where CKEditor finds plugins to load?
I'm writing a CKEditor plugin specific to my Web app. Until now, I've successfully kept my own files outside of the CKEditor code structure, but the only documentation I can find about the plugin creation process (being a user-made tutorial, no less) says to just shoehorn my plugin code into `ckeditor/_source/plugins`.
Is this really the only way to go? Am I stuck with commingling my code with CKEditor release code, or is there a way to tell it where to load plugins from? A PLUGINPATH setting, if you will?
|
Looking at the tutorial you posted, I see that the section called Plugin Configuration uses `CKEDITOR.plugins.add` to load the plugin resources. Have you tried using `CKEDITOR.plugins.addExternal` instead? The API documentation for it can be found here.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 6,
"tags": "javascript, ckeditor"
}
|
How to use API docs in C# using JSON (OpenWeatherMap)
I'm trying to create a **`Windows 10 Weather Application`** in **_`WPF`_** using **_`C#`_**. I have **`Weather Api`** from OpenWeatherMap
I'm using **_`JSON`_**. But, I don't know how to implement forecast data. I never used **_`API`_** before. I would be very thankful if you could help.
|
Here are some useful links to work with json in c#
<
<
How to install JSON.NET using NuGet?
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "c#, json, wpf, api, openweathermap"
}
|
serve postscript file with php script
I want to give a link to a postscript file, but first I want to make a script that will monitor the downloads of this file. The link has to be 'direct' so I added `.ps` extension to be interpreted by PHP. In the begining the script opens the text file, writes some information and then I don't know what to do.
Basically I have something like this (file `apendix.ps`):
header('Content-type: application/postscript');
header('Location: appendix.ps');
but then, the link to this file has to have different name, so eventually I'm serving different file than in 'direct' link.
Is it possible to write a script `appendix.ps` which does something in the begining and then serves real `appendix.ps` file?
regards
chriss
|
You can use readfile:
header('Content-type: application/postscript');
readfile('appendix.ps');
You also may want to send a "Content-Disposition" header to hint to the user agent how its intended to be displayed.
If you want to suggest to open it in a new window, Ie: trigger a download action:
header('Content-Disposition: attachment');
If you want to suggest to display it in the browser if it can:
header('Content-Disposition: inline');
Noting of course these are just _suggestions_ and the browser may not play ball or even be able to, but they're handy to have.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, postscript"
}
|
VB.net How to Compare difference in years
New VB coder here, trying to check if todays date is more then 10 years past a date from a grabbed database entry, and display a message if it is.
The Database is already imported and set up in the VB application H ave made, and working, I made a report to display the information.
I am guessing I need to use the Datediff but I can't seem to get it to work, Thanks.
I will give my variable name here
Dim Custsince as Date
'From the Database here
CustSince = CustListodr("Custsince")
Thanks in advance, working with dates is not my strong point.
|
You can just use a `TimeSpan` directly by subtracting the dates:
Dim customerLength = DateTime.Now - Custsince
Dim approxYears = customerLength.TotalDays / 365
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "vb.net, date"
}
|
Find out windows version from non-privileged user command line
I need a way to find out what version of windows I'm running in using simple command line tools (no powershell). I need it to work from a non-privileged user, and I need to be able to parse out the difference between Windows XP, Vista, server 2008, and 7. I'm currently using: `wmic os get Caption` but that fails when the user doesn't have permissions to run wmic.
**Update:** To clarify, I need this command to not break with different service pack levels, etc. which probably rules out parsing a specific version number. Also if you look at this list of windows versions, you'll see that the numbers reported on Windows 7 and server 2008 r2 are the same.
|
I solved this problem by parsing the output of:
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion" /v "ProductName"
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 15,
"tags": "windows, cmd"
}
|
T-SQL, select rows
as shown in the screenshot, for different id, I want to select all rows that have common updateTime. For example here, all three IDs have common updateTime 9:30:02 and 9:30:04. Therefore, I want to select the 3rd and 4th rows (for id 211709), 6th and 8th rows (for id 301801), 9th and 10th rows (for id 931801), I want to select all these 6 rows. What sql code should I write? Thanks in advance!!!
 FROM MyTable c WHERE c.UpdateTime = UpdateTime) = COUNT(DISTINCT Id)
)
If you wonder what the `HAVING` clause does - for every UpdateTime you checking if number of IDs with this UpdateTime equals total number of IDs.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -2,
"tags": "sql, sql server, tsql, select, ssms"
}
|
Php, optional public variable
i've some public variables in my class, here is how i define them
class MyClass
{
public $var1;
public $var2;
public $var3;
function __construct($params)
{
if(isset($params['var1']))
$this->var1 = $params['var1'];
if(isset($params['var2']))
$this->var3 = $params['var2'];
if(isset($params['var3']))
$this->var3 = $params['var3'];
}
}
but as i said theese are optional parameters. Some object's will use it, some wont use it. My question is i'm defining it everytime even it's used or not. Should i define it when it's passed something like:
if(isset($params['var1']))
public $var1 = $params['var1'];
i'm quite newbie with php, just need to know what i'm doing at top is right?
edit:typo.
|
You can create an array instead and store only those values that are submitted like this:
class MyClass
{
public $data = array();
function __construct($params)
{
if(isset($params['var1']))
$this->data['var1'] = $params['var1'];
if(isset($params['var2']))
$this->data['var2'] = $params['var2'];
if(isset($params['var3']))
$this->data['var3'] = $params['var3'];
}
}
This way you have a single concrete **_known_** variable you can refer to anytime to get needed data back.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, oop, public"
}
|
Kibud and Hidur
Does providing the person you are supposed to honor, such as one's father and Rebbi, the opportunity to do a mitzvah in a more mihudar way at the expense of your own hiddur fall under what is required under the laws of honoring?
Imagine the following situation:
The person who you must honor asks you to pick up a Lulav set while you are shopping for your own. They give the money for it. Now, at the shop/stand you find the two sets you are going to buy. One for you, one for him. Both are completely kosher and both are mihuddar. However one is somewhat _nicer_ under the guidelines of hiddur. Who should you get the nicer one for? Yourself, or the person you need to give honor to?
|
Based on the Shiarei Knesset HaGedolah & Iggeret Shmuel brought in the Shaarei Teshuvah (OC §658, end) it appears that when pertaining to commandments that are incumbent on an individual one is not obligated to give precedence, to somebody who is ordinarily due, and by foregoing any exemplary elements (הידור) whereby himself not fulfilling the commandment in an exemplary manner.
R. Yitzchok Zilberstien (Chashukei Chemed on Sukkah 41b) draws a direct parallel from the above to a case resembling OP's, however, he concludes that the above should only apply when giving precedence will hinder the conferrer from fulfilling the commandment altogether, whereas if he will only lack the הידור element but still fulfill the commandment (e.g. of shaking the four species) then honor should be given to the one due.
|
stackexchange-judaism
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mitzvah, kibbud av veim honoring, hiddur mehudar"
}
|
Need formula for next letter in alphabet in google spreadsheet
I've searched for a while but I can't find the function to get the next letter in the alphabet. Does it exist?
A1="A"
=char(A1+1);
expected result "B"
|
Use this instead:
**=CHAR(CODE(A1)+1)**
!enter image description here
This will work for capital letters _A_ through _Y_.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 4,
"tags": "google sheets"
}
|
Using spring forms in templates
I have a registration form in my header.jsp which includes fields; name-email-password.
When user clicks "register" button, it will be POSTed to my registration controller:
@RequestMapping(value ="/register", method = RequestMethod.POST)
public String registerUserAccount(@Valid @ModelAttribute("user") RegistrationForm userAccountData,
BindingResult result, ... )
Since I'm using spring form tag, I include an empty user object for data binding in my index view.
The problem is I keep getting
Neither BindingResult nor plain target object for bean name 'user' available as request attribute
This form resides in my header file, so it is accessible from all pages. Do I have to add a user object to every `ModelAndView` or is there a neater way to tackle this problem.
|
You can to do the following:
@ControllerAdvice
public class ModelAdvice {
@ModelAttribute
public RegistrationForm registrationForm() {
return new RegistrationForm();
}
}
`@ControllerAdvice` is used when you want something to apply to all controllers. In this case you want to apply the `@ModelAttribute` to all the controllers since as you say the registration form is in all the pages.
For more find grained control, you would probably want to implement a HandlerInterceptor that would add to the the required data to `HttpServletRequest` when needed
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "spring, spring mvc, sitemesh"
}
|
Splitting strings with unescaped separator in R
I have to read a file with R, where a variable number of columns is separated by the `|` character. However, if it is preceded by a `\` it should not be considered a separator.
I first thought something like `strsplit(x, "[^\\][|]")` would work, but the problem here is that the character before each pipe is "consumed":
> strsplit("word1|word2|word3\\|aha!|word4", "[^\\][|]")
[[1]]
[1] "word" "word" "word3\\|aha" "word4"
Can anyone suggest a way to do this? Ideally it should be vectorized since the files in question are very large.
|
I believe this works; using Anirudh's downvoted answer (not sure why the downvote, it doesn't work but the regex was correct)
strsplit(x, "(?<!\\\\)[|]", perl=TRUE)
## > strsplit(x, "(?<!\\\\)[|]", perl=TRUE)
## [[1]]
## [1] "word1" "word2" "word3\\|aha!" "word4"
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "regex, r"
}
|
SQL query, specify which top results?
I have a SQL query that current returns the top 50 rows from a query.
LEFT JOIN users u
ON c.id = u.id
ORDER BY c.date DESC LIMIT 50;
I would like to change the LIMIT 50 to be dynamic, so I could specify results 1-24, 25-50, etc. How can I change LIMIT 50 to work this way?
Thanks!
|
ORDER BY c.date DESC LIMIT 0, 25;
ORDER BY c.date DESC LIMIT 25, 25;
ORDER BY c.date DESC LIMIT 75, 25;
$page = 0; // 1, 2, 3
$perPage = 25;
$query = ' ... ORDER BY c.date DESC LIMIT ' . ( $page * $perPage ) . ', ' . $perPage;
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "php, mysql"
}
|
"unexpected in macro definition"
I wrote
#ifndef Header1.h
#define Header1.h
class Complex
{
[...]
};
#endif
in my project (Visual Studio 2010) and I get an Error C2008: '.' : unexpected in macro definition. I don't understand what the problem is with "Header1.h" or how to fix it.
|
Don't use the . use an _ instead
#ifndef HEADER1_H
#define HEADER1_H
class Complex
{
[...]
};
#endif
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c++, macros"
}
|
UITabBarController not using NavigationController
I'm using MonoTouch and my application setup looks something like this,
NavController -TabBarController -NavController -View1
This works then I click on a tab and am directed to View1. The problem is that this was performed by the tabBarController and not the navigationController. So I get no Back button. Is there a way to capture a TabItemClicked event and manually use the NavigationController to push the View1 onto the stack? So I can get a back button.
I'm hiding the TabBar once I get to View1, so at the moment, there is no way back from View1.
|
Hope it may help you <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "uinavigationcontroller, xamarin.ios, tabbar"
}
|
Forming a variable name with string + integer and calling functions
Firstly, I am new to these and the question could be stupid. Anyway, I have a procedure like this:
procedure Tform1.QueryChange(sqltext : String; query : Integer);
begin
if query = 1 then begin
ADOQuery1.Close;
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add(sqltext);
ADOQuery1.Open;
end;
if query = 2 then begin
ADOQuery2.Close;
ADOQuery2.SQL.Clear;
ADOQuery2.SQL.Add(sqltext);
ADOQuery2.Open;
end;
I would like to remove the if blocks and make one united code:
ADOQuery+query.Close; (know that looks very silly)
ADOQuery+query.SQL.Clear;
ADOQuery+query.SQL.Add(sqltext);
ADOQuery+query.Open;
My goal is when query=1 code will use ADOQuery1.Close; etc. when query=2 code will use ADOQuery2.Close;
|
Instead of creating variables `ADOQuery1`, `ADOQuery2`, `ADOQuery3` etc of type `TADOQuery`, create an array:
ADOQueries: array of TADOQuery;
Then set the number of elements in it, when you know how many they will be:
SetLength(ADOQueries, NumberOfQueries);
Alternatively, if you know from the beginning how many elements there will be, you can define `ADOQueries` to be a static array instead:
ADOQueries: array[0..7] of TADOQuery;
Now you can do
procedure TForm1.QueryChange(sqltext: String; query: Integer);
begin
ADOQueries[Query].Close;
ADOQueries[Query].SQL.Clear;
ADOQueries[Query].SQL.Add(sqltext);
ADOQueries[Query].Open;
end;
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "delphi"
}
|
How can i express in regexp "match until a pattern without including that pattern"?
I have this input :
{ :
and i'd like to match only the value1 from the first URL. I thought the below regexp :
[^#]\w*\s:
but this matches "value1 :"
How can i express "match until \s: ,without including that pattern?
|
Zero-width lookahead. In Java you could do it like this:
[^#]\w*(?=\s:)
You may think about making this regex more flexible, to handle extra whitespaces and such... just in case the input is just slightly different from what you expect.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "regex"
}
|
A question of pits and stomachs
Since around the year 2000, confirmed by **Ngrams**, the common phrase " **I felt (dread etc) in the pit of my stomach** " has become somewhat corrupted to " **I had (or felt) a pit in my stomach** ". I've seen it several times recently in internet posts and popular fiction.
I doubt there's a 'patient zero' to be found, but I'm curious what might explain why this has become increasingly popular, when before 2000 it was virtually non-existent.
I hope this isn't seen as opinion-based -- I'm looking for a scholarly, or at least informed, reason why this might have arisen.
|
"Pit in my stomach" is still controversial, and is considered by some to be an error, including Professor Paul Brians, of Washington State University, who has included it in his book "Common Errors in English Usage", alongside such gems as "ad nauseum", and "along the same vein". Mark Liberman, writing on Language Log, traces it as far back as 1980, and calls it an eggcorn.
|
stackexchange-english
|
{
"answer_score": 1,
"question_score": 2,
"tags": "idioms, american english"
}
|
an elegant way to build the string in c#
string to build up using keyvaluepair is like this: "name1=v1&name2=v2&name3=v3"
what i am doing:
var sb = new StringBuilder();
foreach (var name in nameValues)
{
sb.AppendFormat("{0}={1}&", name.Key, name.Value);
}
//remove last '&' sign, this is what i think is ugly
sb.ToString().Remove(lastIndex);
any elegant way to avoid the last removal statement of '&' sign?
|
var joined =
String.Join("&", nameValues.Select(n => n.Key + "=" + n.Value).ToArray());
Given that we're not concatenating to one big string (we're producing many small strings) concatenation carries no performace penalties in this case. And in .NET strings are length prefixed anyway so the whole concatenation performance issue is less relevant than in C. String.Join() is very fast as well, faster than StringBuilder.
**TLDR:** Use `String.Join()`
|
stackexchange-stackoverflow
|
{
"answer_score": 18,
"question_score": 10,
"tags": "c#, stringbuilder"
}
|
Is it possible to get the controller, action and routeValues from a URL (based on the Global.asax routes)?
I have a URL. Is it possible to somehow get the controller- and action-name and the routevalues? (which would normally be generated by the .NET MVC framework based on the definition in global.asax)
|
It is possible, check Haacked routing debugger.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "asp.net mvc, debugging, routes"
}
|
Remove image transparency
I'm working on a Machine Learning problem at college and my first job is to convert images into black and white.
The problem is that my image has transparency, and I don't know how to remove it.
What I am trying:
public static Bitmap RemoveTransparency (Bitmap src)
{
Bitmap target = new Bitmap (src.Size.Width, src.Size.Height);
Graphics g = Graphics.FromImage (target);
g.Clear (Color.White);
g.DrawImage (src, 0, 0);
return target;
}
An example of an input image:
!My captcha image
An example of output image after "RemoveTransparency" call:
!Output image
Does anyone know what's going on? Seems like background an the letters have the same color... and my my background is black if I'm coloring to white?
Thank you!
|
You need to set the `CompositingMode` of your `Graphics` object to `SourceOver` before drawing the other image on top of it.
g.Clear(Color.White);
g.CompositingMode = CompositingMode.SourceOver;
g.DrawImage(src, 0, 0);
The default `CompositingMode` is `SourceCopy`, which is taking the transparent black (R=G=B=A=0) pixels in your `src` image and rendering them as black pixels. `SourceOver` will do alpha blending, which is what you're looking for.
See here for details: CompositingMode Enumeration.aspx)
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "c#, .net, bitmap"
}
|
Determine whether a function series is uniformly convergent
> Determine whether $\sum_{j=0}^{\infty} \frac{\sin(jx)}{(2+x^2)^j}$ is uniformly convergent for $x\in\mathbb{R}$
So I started by saying as $|\sin(jx)|\le1$ so $\sum_{j=0}^{\infty} \frac{\sin(jx)}{(2+x^2)^j} \leq \sum_{j=0}^{\infty} \frac{1}{(2+x^2)^j} = \sum_{j=0}^{\infty}(\frac{1}{(2+x^2)})^j=\sum_{j=0}^{\infty}\frac{1}{1-\frac{1}{2+x^2}}=\frac{2+x^2}{1+x^2} $ So the function is pointwise convergent to the limit function $f(x)=\frac{2+x^2}{1+x^2}$
How do I now prove whether or not it is uniformly convergent? Thanks
|
Hint: $$\bigg|\frac{\sin(jx)}{(2+x^2)^j}\bigg|\leq \frac{1}{2^j}$$ now use Weierstrass M-test.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "real analysis, analysis, convergence divergence, uniform convergence"
}
|
pipe for read command does not work
read command in sh works if I redirect `file1` as standard input like
$ cat file1
first second
$ read u v <file1
$ echo $u
first
$ echo $v
second
However, if I redirect standard output from echo like
$ echo first second | read a b
$ echo $a
It does not work. I thought read gets standard input from pipe in the second case. Why am I wrong? Thank you.
|
**In your first example :**
`read` and 'echo" being shell built-in commands, they will be executed by the interactive shell you are typing commands in (the same process) and therefore the result of these commands concern the environment of your running shell.
Hence when returning from the `read` instruction, you are still in the same shell perfectly aware of u and v variables values.
**In your second example :**
Even if the command is built-in, the pipe forces your interactive shell to fork a child process. In this occurrence, it will fire a subshell that will execute the read command and update its own environment (assign a value to u and v variables) without influencing the environment of its parent.
Therefore when the read has completed, the subshell terminates and you come back to your interactive shell which is totally unaware of u and v variable values as set by its child.
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 1,
"tags": "shell"
}
|
Parse an object from MVC controller to view C#
I am storing an object from a list to a local variable and trying to pass it to a view like below:
public class BedController : Controller
{
// GET: Bed
public ActionResult Index(PatientRegister model, int id)
{
var patient = PatientRegisterController.BedsList.Single(x => x.NewPatient.BedNumber.Equals(id.ToString()));
return View(patient);
}
}
But I don't know how to access this object from the view itself something like
patient.SelectSomeOfTheProperites //This is the object that I parsed from controller
|
Add return object type as model
@model Bed
Access the return object property as
@model.SelectSomeOfTheProperites
Hope this helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, asp.net mvc"
}
|
Best way to print the value of a variable?
Which of the following is better coding style and why?
print("We have x = %i" %x)
print("We have x = "+str(x))
|
Your first example was better. `print("We have x = %i" %x)` because you are working with a string object. It takes less memory than working with 2 string objects and an int.
Since you are asking with a python3 tag, here is a newer format for python string formatting using str.format
dic = { 'x': '1'}
print("We have x = {x}".format(**dic))
or you can do this positionally:
print("The sum of 1 + 2 is {0}".format(1+2))
This works with 2.6+ and 3.3+
|
stackexchange-codereview
|
{
"answer_score": 2,
"question_score": -2,
"tags": "python, python 3.x"
}
|
Is there a way to define an alias that executes a bin from a specific folder in MacOS?
I am currently using a Macbook Pro running MacOS Mojave 10.14.3. I have recently gotten into ruby programming but find their whole gem package management a little confusing. When i `gem install` a package, it installs it in my `/usr/local/lib/ruby/gems/2.6.0/bin` folder and if I want to execute a gem or get a gem version, for example the `solargraph` gem, I must type a command: `/usr/local/lib/ruby/gems/2.6.0/bin/solargraph -v`. I was wondering if there is way for me to define an alias for the path `/usr/local/lib/ruby/gems/2.6.0/bin` so that I could type something like `gemexec solargraph -v` which would achieve the same result as `/usr/local/lib/ruby/gems/2.6.0/bin/solargraph -v`. Thanks for your help. BTW I am using the ZSH shell.
|
You can make a function that will do this for you and place it in your .zshrc file.
function gemexec() {
/usr/local/lib/ruby/gems/2.6.0/bin/"$1"
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "ruby, terminal, rubygems, exec, zsh"
}
|
Function of exponential order whose derivative is not
I am looking for a function of exponential order(i.e. bounded in absolute value by $Me^{ct}$ for some $M, c$) whose derivative is not of exponential order.
My thought was to look for functions which oscillate wildly between + and - in continually decreasing "periods," but I'm having trouble finding specific functions. Any help is appreciated.
|
How about this: $\sin(e^{t^2})$
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 2,
"tags": "functions, exponential function"
}
|
Treat spaces as spaces after n column
How to run bash `column` command that after n columns it treats spaces as spaces and not as a separator?
Input:
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces
Output:
col1 col2 col3 col4
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces
Maybe replace spaces with other char before the `column` command and after that replace it again with spaces? `awk` or `sed` might be the right tool for this, but I'm not too familiar with them.
Any help is appreciated! Please, don't shoot me down. This is my first question here...
|
Another awk that replaces first 3 spaces with a tab:
awk '{for (i=1; i<=3; ++i) sub(/ +/, "\t")} 1' file
field1 field2 field3 field 4 with spaces
foo1 foo2 foo3 foo4
bar1 bar2 bar3 bar 4 with spaces
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "linux, bash, awk, sed"
}
|
Die Grenze »zu« oder »nach« einem Land?
Bei Duden heißt es:
> der Fluss bildet die Grenze _zu_ Polen.
aber auch
> an der Grenze _nach_ Bayern.
Welche grammatikalischen Regeln greifen hier?
|
Im Prinzip kann man in den meisten Fällen beides sagen, allerdings ist mit der
> Grenze _nach_ Polen
eher der Grenz _übergang_ mit dem Grenz _übertritt_ gemeint ("nach" intendiert eine Bewegung)
und mit der
> Grenze _zu_ Polen
eher die Grenz _linie_ (Landkarte, Zaun, usw.), hier ist i.A. keine Bewegung involviert.
Man würde also eher
> Im Dezember überschritt Hannibal die Grenze nach Italien
und
> Die Elbe bildet die Grenze zu Polen
sagen.
|
stackexchange-german
|
{
"answer_score": 8,
"question_score": 10,
"tags": "preposition"
}
|
How to remove in angular js?
The angular expression is `{{ notification.noti_val }}`. The value stored in the expression is `saha like own wall`.
How can I remove the ` ` characters?
|
You need to specify your value as safe html. In angular you can use `$sce`service to do so. I have created this jsbin explaining the use case and it fixes your issue
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, angularjs"
}
|
Как задеплоить ftp в Kubernetes
Господа здравствуйте. 2 недели пытаюсь задеплоить в kub ftp По данной сылке. < Есть проблема захожу по cmd без проблем. Пытаюсь зайти по FileZilla вылетают алерты:
Превышено время ожидания (соединение потока передачи данных) Не могу получить содержимое каталога Не могу просмотреть каталог '/'.
Вообщем задаюсь вопросом как задеплоить ftp в kub. Есть ли простые примеры для чайников ?
|
В данном случае проблема заключалась в том что ftp мог работать только через 21-ый порт. И использование а filezilla было бесмысленным. Открыв WincScp вопрос решился.
Для чайников совет. Вначале киньте в докер, потом можно в куб. так проще.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linux, docker, ftp, kubernetes"
}
|
Build a Comma Delimited String
I want to build a comma delimited string from Range `A1:A400`.
What is the best way of doing this? Should I use a `For` loop?
|
The laziest way is
s = join(Application.WorksheetFunction.Transpose([a1:a400]), ",")
This works because `.Value` property of a multicell range returns a 2D array, and `Join` expects 1D array, and `Transpose` is trying to be too helpful, so when it detects a 2D array with just one column, it converts it to a 1D array.
In production it is advised to use at least a little bit less lazy option,
s = join(Application.WorksheetFunction.Transpose(Worksheets(someIndex).Range("A1:A400").Value), ",")
otherwise the active sheet will always be used.
|
stackexchange-stackoverflow
|
{
"answer_score": 18,
"question_score": 7,
"tags": "string, excel, vba"
}
|
How to handle Loop for error during Requests in Python?
I am trying to get data from an website and I am with an issue that I can't pass trough an array.
I need to run `requests.get(value[0])`, `requests.get(value[1])`, `requests.get(value[N])`. But when I got an error this loop just STOP.
The code:
import requests
value = [' '
try:
for item in value:
response = requests.get(item)
print(response)
except:
print('response')
And those two URLs are a real case, if I run this script will explode an exception, but the second URL is a valid URL, I've tried some other options using `while`, putting `pass` instead of `print()` but without success, how can I handle that to let my loop for, keep doing its job??
Thanks!!!
|
Switch the places of `for` and `try`, like:
for item in value:
try:
response = requests.get(item)
print(response)
except:
print('response')
Also, avoid using bare excepts. Observe what error the code is raising, then change your except to catch that exception, e.g:
for item in value:
try:
response = requests.get(item)
print(response)
except requests.exceptions.Timeout:
print('timeout exception')
Add more exceptions by new exceptions you get. Or if you don't want your program to stop when you encounter a new exception, at least print the error:
except Exception as error:
print(error)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, python 3.x, for loop, python requests"
}
|
Lightning Web Component passing the particular value and retrieving the data in other component
Hi I have a requirement in which i am passing the data from parent to child component and need to fetch the particular data in the track property in child component.
Parent Component.
@track info = [];
Info.push({
name:"Priya",
Age:"12",
School:"Asvidya",
City:"Delhi"
});
<C-child info = {Info} ></child>
Child Component.
@track priyaAge;
@track informationgirl = [];
@api
get info() {
return this.informationgirl;
}
set info(value) {
this.informationgirl = value.detail;
}
As per req i just want to pick out the age of priya from the incoming data and store in the @track priyaAge in child component.
|
You can see an example in the playground
in the parent component :
<c-child info={info}></c-child>
@track info = {
name:"Priya",
Age:"12",
School:"Asvidya",
City:"Delhi"
};
In the child component
@track priyaAge;
@track informationgirl = [];
@api
get info() {
return this.informationgirl;
}
set info(value) {
this.informationgirl = value.detail;
this.priyaAge = value.Age
}
|
stackexchange-salesforce
|
{
"answer_score": 2,
"question_score": 2,
"tags": "javascript, lightning web components, salesforcedx, lwc wire adapter"
}
|
How to import MaterialX library into blender?
Does anyone have any idea how to get the MaterialX library into blender as the picture below showcases?
. If you can point me in the direction of a good knowledge base i'd be much grateful.
|
This is part of the USD Hydra addon: GPUOpen-LibrariesAndSDKs/BlenderUSDHydraAddon
Download the latest release, and install it like any other addon.
Then in Properties Editor > Render Properties Tab: Switch the render engine to USD Hydra:
, so be patient to get the full list.
|
stackexchange-blender
|
{
"answer_score": 0,
"question_score": 0,
"tags": "materials, shaders, gpu, library"
}
|
Name a list with Table
I am struggling to find a way to assign a value from a list to names from another pre-defined list with Table[].
names = {first, second, third}
numbers = {{1, 1}, {2, 2}, {3, 3}}
What I want is:
first = {1, 1}
second = {2, 2}
third = {3, 3}
so that {1, 1} is stored in _first_ etc.
I tried the following:
namelists = Table[(names[[i]]) = (numbers[[i]]), {i, Length[names]}];
In this case, namelists[[1]] = {1, 1}, however _first_ does not store any information...
|
Clear[first, second, third]
names = {first, second, third}
numbers = {{1, 1}, {2, 2}, {3, 3}}
Table[Evaluate[names[[i]]] = numbers[[i]], {i, 3}]
first
second
third
|
stackexchange-mathematica
|
{
"answer_score": 11,
"question_score": 5,
"tags": "list manipulation, variable"
}
|
android how to highlighted an text
I have created a listview. and there I also did the drag n drop of items. I want on which item mouse touched that text should be highlighted.(For example U open the Google & if put the mouse on Google then it highlit the text Google in small letters) I wanna same on my list items TextView items. How can I do it. Please answer me. Thanks
|
If you're stuck on the highlighting text in a TextView part, here's an example of that, borrowing heavily from Highlight Text in TextView or WebView.
public class Main extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView myTextView = (TextView)findViewById(R.id.my_textview);
myTextView.setText(myTextView.getText(), TextView.BufferType.SPANNABLE);
Spannable text = (Spannable)myTextView.getText();
text.setSpan(new BackgroundColorSpan(0xFFFFFF00), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(text);
}
}
If instead, you just want to set the background color of the TextView, take a look at android TextView: setting the background color dynamically doesn't work.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android"
}
|
How to set material to gameobject dynamically using c# script in unity?
I want to set material to a gameobject in unity using c# script.
I am using this code to set the material of mesh renderer attached to the gameobject -
MeshRenderer mesh = gameObject.GetComponent<MeshRenderer>();
mesh.materials[0] = materialsCopy[0];
here materialsCopy is an array of type Materials which I've made public and I am attaching the Materials by drag & drop to the materialsCopy but when I run the game I get a white colored mesh instead of the set material of the 0 index materialsCopy. The 0 indexed materialsCopy has albedo set to an image. I want this image to get attached to the gameobject. How should I proceed ?
In addition to this I am also getting a warning - Tiled GPU perf. warning: RenderTexture color surface (0x0) was not cleared/discarded, doing
|
Try
Renderer rend = GetComponent<Renderer> ();
rend.material = materialsCopy[0];
|
stackexchange-gamedev
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, unity, 3d meshes"
}
|
Why do I get java.lang.exception unrecognized body on routes with friend/authenticated as a wrapper?
I am using friend along with friend-redis-token where sessions are stored in redis for my compojure application.
for a route which is something like..
(POST "/service/logout" {headers :headers}
(session/invalidate-session
(headers "x-auth-token")))
Everything works fine!
As soon as I wrap the handler with friend/authenticated. I get the error
:WARN:oejs.AbstractHttpConnection:/service/logout
java.lang.Exception: Unrecognized body: ...
I am using the following middlewares:
(jsonware/wrap-json-body)
(jsonware/wrap-json-params)
(jsonware/wrap-json-response)
to convert everything in body to JSON, could that bve conflicting with friend ?
|
I believe the problem might be with the return value of `session/invalidate-session`. So try something like this:
(POST "/service/logout" {headers :headers}
(do (session/invalidate-session
(headers "x-auth-token"))
""))
Compojure tries to be clever about doing the right thing with the return values of routes and this often ends up causing problems such as this.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "clojure, compojure"
}
|
Does an ARM (LPC21xx) Programmer pulls P0.14/BSL to ground?
Most of ARM programmers come with BSL,RESET,TXD, RXD, GND and VCC pins which we need to connect with respective pins of ARM.
For ISP, We require need to ground P0.14/BSL after Reset.
As these programmers have Both BSL and RESET pins, Does programmer itself Resets controller and pulls BSL to ground OR do I need to first pull BSL to ground, Reset controller and then start programming using softwares like FlashMagic?
Also, Does ARM remains in Bootloader if I pull P0.14/BSL to ground after power up till next reset or does it have any sort of time out that it will jump to application code after that.
Or as Wouter van Ooijen rephrased it, whether the bootloader will spontaneously jump to the application after a certain timeout?
I am working with LPC2138.
|
As starblue points out, you are referring to the LPC range of microcontrollers. Mentioning this in the title and/or text of your question is advisable.
Whether the programmer pulls BSL low for you (and also whether it resets the chip for you!) depends on the programmer and the PC software you use.
FlashMagic and lpc21isp can be configured to do both for you, provided of course that the programmer hardware (which can be as simple as an FT232RL chip) supports this and is connected to the target correctly.
I cannot make sense of your last question. Maybe you want to know whether the bootloader will spontaneously jump to the application after a certain timeout? AFAIK not.
|
stackexchange-electronics
|
{
"answer_score": 4,
"question_score": 1,
"tags": "arm, programmer, bootloader, isp"
}
|
what does this function declaration mean in c++
virtual const char* what() const throw()
{
}
AFAIK it's a function that will return a constant pointer to a mutable char. The rest I am not sure. Could anybody help?
|
Regarding the `const throw()` part:
* `const` means that this function (which is a member function) will not change the observable state of the object it is called on. The compiler enforces this by not allowing you to call non-`const` methods from this one, and by not allowing you to modify the values of members.
* `throw()` means that you promise to the compiler that this function will never allow an exception to be emitted. This is called an _exception specification_ , and (long story short) is useless and possibly misleading.
|
stackexchange-stackoverflow
|
{
"answer_score": 39,
"question_score": 35,
"tags": "c++"
}
|
Complex Integral Definition Question
Using the definition of the complex integral, I was asked to evaluate the integral of the conjugate of a complex number $z$, denoted by $z*$ around the closed contour consisting of the portion of the parabola $y = x^2$ from $(0,0)$ to $(1,1)$ followed by the line segment from $z = 1 + i$ to $z = 0$.
My attempt at the problem was to first sketch the contour. Then I am essentially integrating $1 - i$ from $0$ to $1$, which is trivially $1-i$, but I'm not sure if this is correct. Any help would be greatly appreciated.
|
We wish to evaluate the contour integral
$$\displaystyle I=\oint_C z^* \,dz$$
where $C$ is the closed contour comprised of $(i)$ $C_1$, the parabolic path $y=x^2$ from $(0,0)$ to $(1,1)$ and $(ii)$ $C_2$, the line segment from $(1,1)$ to $(0,0)$.
One the parabolic path, we use the parameterization $x=t$ and $y=t^2$ so that $z^*=t-it^2$ and $dz=(1+i2t)\,dt$, to find
$$\int_{C_1}z^*\,dz=\int_0^1 (t-it^2)\,(1+i2t)\,dt\tag1$$
One the line segment from $(1,1)$ to $(0,0)$ we use the parameterization $x=t$ and $y=t$ to find
$$\int_{C_2}z^*\,dz=\int_1^0 (t-it)\,(1+i)\,dt \tag2$$
It is left as an exercise for the reader to evaluate the integrals on the right-hand sides of $(1)$ and $(2)$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "complex analysis, contour integration"
}
|
Improvement of JS Regex to restrict all letters of a word in a specific range
I'm solving the Ranges challenge in RegexGolf, but I'm somewhat stuck in trying to shorten the regex.
Here is a screenshot of the conditions -
 will be 1 character shorter each. I don't see how it could be minimized further, so your regex could be
^[a-f]+$
Note: One of the 1-score solutions comments, that _i dont know regex but i know javascript_ , so I'd guess that there was some cheating involved.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "javascript, regex"
}
|
How to remove inactivate conda environment names from jupyter notebook?
I have created multiple miniconda environments in my macbook. But when I open jupyter notebook, it shows non-existent conda environments I created long ago and which are no longer available in conda environments.
How to remove these non-existing environment names from jupyter notebook?
# My current conda list

=0;
}
B.h
class B: public A{
public:virtual void storedata(int a, int b, int c, int d);
}
B.cpp
void storedata(int a, int b, int c, int d)
{ do something }
C.h
class C: public B{
public:virtual void storedata(int a, int b, int c, int d);
}
C.cpp
void storedata(int a, int b, int c, int d)
{
B::storedata(int a, int b, int c, int d);
}
Why could the derived class C could call the B::storedata in C.cpp?
|
Why shouldn't it be able to? The point of overriding a virtual function is to allow you to customise the behaviour of objects of the derived type, but sometimes the desired behaviour consists of performing the processing that a base did, possibly conditionally or with some pre- or post- action. Indeed, you can provide implementations of pure virtual functions, and that's mainly useful so that derived classes can conveniently call the abstract base class's implementation when it happens to suit them. In this case, the override is useless because it only does exactly what the B version does, but in general it's potentially useful to allow the B version to be called.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c++, inheritance, virtual"
}
|
Simulator wont start on home TableView
I've created a table view which is embeded in a Navigation Controller as such and connects to another view controller. I've the connection from the table to the navigation controller as a modal segue and the segue from the table bar to the View Controller as a push segue yet I am still getting the error:
> Unsupported Configuration
> Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier:
This worked last week and now its not. Ive tried adding storyboard IDs but thats not working. I appreciate any help.
|
Did you check your start point in your storyboard? In other words, on the left side of your starting navigation controller, do you have the arrow pointing to it? If not, drag it until you make it point to the navigation controller.
Also, if you're doing that dynamically, have you provided your UIViewController/UITableViewController/UINavigationController Storyboard IDs? Please, double check that by clicking on your view controller in your storyboard, then in the Inspector (right side of Xcode window), go to the third tab and make sure you have set the ID and make sure they are consistent with your code.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "iphone, ios, objective c, debugging, storyboard"
}
|
CakePHP and EasyPHP URL rewriting
I'm tring to get CakePHP 2.2.3 working with EasyPHP 12.1 on my local machine. I'm getting an error from Cake that says:
> URL rewriting is not properly configured on your server.
1. Help me configure it please
2. I don't / can't use URL rewriting
I followed all of the instructions on the 'Help me configure it' page with no success. I've just installed both EasyPHP and Cake and have only modified the `http.conf` file.
I also created a virtualhost using EasyPHP's built in form.
|
Check if your `.htaccess` files are these. First, in your root directory:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
</IfModule>
In `app` directory:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
</IfModule>
And `webroot` directory:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "apache, cakephp, localhost, easyphp"
}
|
About distance of a point from a set
Consider a subset D of normed space X and y is a vector which is not in D. So we find distance of y from set D say this distance is '£' . Now i read that if set D is closed then we take guarantee that '£' is always positive means £>0. So i think if D is not closed( Open) then is there any possibility that £ =0 as y is not in D and if yes then how. I thing a lot about it. But not found any solution
|
If $D$ is open then the distance between any point of the boundary of $D$ and $D$ is zero, with the boundary defined as
$$\partial D:=\overline D\setminus D^\circ$$
where if $D$ is open then $D=D^\circ$, with $D^\circ$ being the interior of $D$ and $\overline D$ the closure of $D$. Then
$$d(x,D)=0,\quad x\in\partial D$$
and obviously $x\notin D$ by the above definition. Example: let the open set of the real line (with the standard topology) $(0,1)$, then
$$d(0,(0,1))=d(1,(0,1))=0$$
and $0\notin (0,1)$, and $1\notin(0,1)$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 3,
"tags": "general topology"
}
|
Crop a imageView using a customView
I'm making an application which can crop a picture of a person. I have also attached the image to show exactly what I'm making. It is just like WhatsApp application. The blue square is actually a customView extended from View class. I'm overriding onDraw() function which uses canvas to draw the square. How can I capture image defined by area of blue square?!enter image description here
Thank you
|
Get the exact coordinates of your blue area and then create a bitmap from the original one using the coordinates you just calculated!
Bitmap newBitmap = Bitmap.createBitmap(mBitmap,x,y,width,height);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android canvas"
}
|
Double strsplit
I have a situation like this:
df
List Count
R472_21:345 1
R47_2:90 1
R844_21:98 2
R845_54:123 2
R975_12:1 2
I would like to split the elements of the column "List" in the following way:
R472 21 345
R47 2 90
..........
I tried this code to split according to `:` but I'm not able to split according `_` at the same time.
test <- unlist(strsplit(as.character(df$List), "\\:"))
Any suggestion about?
|
Use a | for OR in your pattern to split on. So you are splitting on "_" or ":".
df <- read.table(header=TRUE, text="List Count
R472_21:345 1
R47_2:90 1
R844_21:98 2
R845_54:123 2
R975_12:1 2 ")
strsplit(as.character(df$List), "_|:")
Result:
[[1]]
[1] "R472" "21" "345"
[[2]]
[1] "R47" "2" "90"
[[3]]
[1] "R844" "21" "98"
[[4]]
[1] "R845" "54" "123"
[[5]]
[1] "R975" "12" "1"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "r"
}
|
A peculiar family of sets
This is really stumping me.
I'm rewriting the problem so I'm not just asking for homework help, but I was studying for a test on logic and this problem came up:
Define an indexed family of sets $\\{A_i\\}_{i\in\mathbb{N}}$ where $A_i\subseteq\mathbb{N}$ for all $i\in\mathbb{N}$ that satisfies the following properties:
1\. Every natural number is in at least one of the sets -> $(\forall n\in\mathbb{N})(\exists i \in \mathbb{N})(n\in A_i)$
2\. None of the sets are equal to $\mathbb{N}$ -> $(\forall i\in\mathbb{N})(\exists n\in\mathbb{N})(n\not\in A_i)$
3\. None of the sets have an upper bound -> $(\forall i \in \mathbb{N})(\forall m \in \mathbb{N})(\exists n\in\mathbb{N})(n > m \wedge n\in A_i)$
4\. One of the sets is a strict subset of every other one -> $(\exists j\in\mathbb{N})(\forall i\in\mathbb{N})(i\neq j \rightarrow A_j\subsetneq A_i)$
I've been working on this for a good half hour. Does anybody know of a set that will fit those criteria?
|
Idea : take $A_1$ the set of all primes (which is unbounded). Takes $A_2$ the union of $A_1$ and the set of all primes times $2$. Takes $A_3$ to be the union of $A_1$ and the set of all primes times $3$. And so on for $A_k$.
By prime decomposition, every natural number $n$ is in $A_{n/p}$ for some prime $p$. Obviously by construction, $A_1$ is a proper subset of any $A_k$ for $k\ne 1$. Since $A_1$ is unbounded, so are the $A_k$'s. And no set are equal to $\mathbb N$. Consider $A_k$ and consider a prime $p > k$. Then $p^2 \cdot k \not \in A_k$.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 4,
"tags": "elementary set theory, logic"
}
|
Get list of items of type T from a class entity
I have Class A with following structure
public class A
{
public list<B> Items // where B is a class entity
}
public class B{
public List<B> OwnItems;
public List<C> Items // where C is a class entity
}
public class C
{
public string name;
public string Address;
public int Age;
public double Salary;
}
How to get list of C class entities from Entity A using c#
|
You can use LINQ with the help of **SelectMany** for this:
A a = new A();
// Populate a's `Items` property...
....
var allC = a.Items.SelectMany(b => b.Items.Select( c => c)).ToList();
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "performance, list, c# 4.0"
}
|
Writing web forms filler/submitter with QT C++
I'm scratching my head on how to accomplish the following task: I need to write a simple web forms filler/submitter with QT C++, it does the following:
1) Loads page url 2) Fills in form fields 3) Submits the form
Sounds easy, but I'm a web developer and can't find the way how to make QT accomplish the task, I only managed to load url with QWebView object using WebKit, have no idea what to do next, how to fill in fields and submit forms. Any hints, tutorials, videos? I appreciate this.
|
QWebElement class does all the work, just reading through the class documentation gave me a full idea on how to accomplish my task. Thanks to eveyrone for suggestions.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "qt, automation, webkit, qtwebkit, autofill"
}
|
Each element in a list repeated a different number of times
I have two lists
chr=(1 2 3) # either chr=(1 2 3) or chr=({1..3}) is fine
pos=(2 3 5)
and I wanna have the output
1
1
2
2
2
3
3
3
3
3
1st element of one list is repeated as many times as 1st element in the other list and so on. Outputting to different lines.
I'm trying
for i in "${chr[@]}"; for p in "${pos[@]}"; eval printf \"\$i%.0s \" {1..$p};done; done
and
while read line; do for i in {1.."${pos[@]}"}; do echo "$line"; done; done < chr.list
|
for i in ${!chr[@]}; do for j in $(seq ${pos[i]}); do echo "${chr[i]}"; done; done
The first loop assigns the indices `0, 1, 2` to `i` (we could also use `${!pos[@]}`).
The second loop takes the value of `pos` at given index and creates a sequence for the repetition (2x, 3x, 5x) and prints the value of `chr` at given index.
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 1,
"tags": "bash, shell"
}
|
Is it possible to create a VS Code extension that runs a specific gulp task?
Since I'm a lazy programmer, I've built a gulp task that does some minor tasks for me but I'd like to turn this into an extension so I can install it on my computer and it just "works". Like I install it, boot up VS code and the tasks execute and start watching my code automatically.
I haven't found much things online but then again I could be googling the wrong things. Anything helps - thanks!
|
Have a look at run task on folderOpen option: vscode docs.
This works for me:
// in tasks.json
{
"label": "Tasks: copy3",
"type": "shell",
"command": "gulp",
"args": [
"copy3",
"--file",
"${fileBasename}"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
}
},
Now the `copy3` task in gulpfile.js will automatically be run when that folder (or workspace) is opened. You may have to select `Tasks: Allow Automatic Tasks in Folder` first in the command palette. And definitely reload.
No extension - it is built-in behaviour more recently. See run task on folder open.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "visual studio code, gulp, visual studio extensions"
}
|
What is the difference between ~다면서 and ~다며
Lately I have been listening to the song that sings. The first part of the song goes:
I was wondering if someone could explain to me the usage difference between ~ and ~. I know this is a SONG so it will be more poetic and less conversational, but I am a stickler and really want to understand the nuances behind everything :)
~
|
Hi random Korean passing by :D Your question is reeeeealllllly tricky.....
A B. : He did B, even though A. (OR the same meaning as below)
A B. : He did B, saying/doing/etc A.
So, has more various meanings and uses than . Both are usually used in spoken language or when explaining a certain situation.
OMG this is so hard to explain. The best way to get a feel of nuances is to actually talk with native speakers, I think..... r( )
|
stackexchange-korean
|
{
"answer_score": 5,
"question_score": 3,
"tags": "grammar, difference, verb endings"
}
|
Python list to dictionary
I have two list one with the label and the other data. for example
> label = ["first","second"] list = [[1,2],[11,22]]
I need the result to be a list of dictionary
> [ { "first" : 1, "second" : 2, }, { "first" : 11, "second" : 22, } ]
Is there a simple way to do that. Note the label and list might vary, but number of entry remain the same.
|
>>> label = ["first","second"]
>>> lists = [[1,2],[11,22]]
>>> [dict(zip(label, l)) for l in lists]
[{'second': 2, 'first': 1}, {'second': 22, 'first': 11}]
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 0,
"tags": "python"
}
|
Disallow xml robots.txt
Google webmaster FAQs suggest that this will exclude all xml files from search:
User-agent: Googlebot
Disallow: /*.xml$
Is this legal for other bots as well?
User-agent: *
Disallow: /*.xml$
|
Yes, this is valid. Whether other bots actually understand and obey is completely up to them, though!
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 0,
"tags": "robots.txt"
}
|
Simple destructuring extractor for command line args
The preferred approach would be to use something similar to the commented out line below.
def main(args: Array[String]) {
// val (dbPropsFile, tsvFile, dbTable) = args
val dbPropsFile = args(0)
val tsvFile = args(1)
val dbTable = args(2)
However I am having a little quarrel with the compiler over it:
Error:(13, 9) constructor cannot be instantiated to expected type;
found : (T1, T2, T3)
required: Array[String]
val (dbPropsFile, tsvFile, dbTable) = args
^
So all told this should be an easy few points for someone out there.
|
Use `val Array(dbPropsFile, tsvFile, dbTable) = args`
scala> val Array(a,b,c) = Array(1,2,3)
a: Int = 1
b: Int = 2
c: Int = 3
scala> a
res0: Int = 1
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "scala"
}
|
Variable number of quantifiers (as in $\exists n \exists x_1 \ldots \exists x_n$)
In mathematics we casually use expresions with variable number of quantifiers, like $$\forall a \in A\ \exists n \in \mathbb{N}\ \exists b_1,\ldots,b_n \in B\ \ \ a = b_1 + \cdots + b_n.$$ I'm wondering what is the formal status of such expressions. Is this just a convenient notation for second-order formulas? Because I guess $\exists n \in \mathbb{N}\ \exists b_1,\ldots,b_n \in B$ could be switched to $\exists S \subseteq B, |S|<\infty$.
I'd like to know what is the logical basis for these expressions.
|
If you see $b_1, \dots, b_n$ as a function from an index set $\\{1, 2, \dots, n\\}$ to $B$, then it's an abbreviation for $$\forall a \in A \;\exists n \in {\mathbb N} \;\exists b \colon \\{1, 2, \dots, n\\} \to B \;\; [a = \textstyle\sum_{i=1}^n b(i)].$$ (And this is not equivalent to $$\forall a \in A \; \exists S \subseteq B \;\;[ |S| < \infty \land a = \textstyle\sum S],$$ because in the first formulation the $b_i$ can be repeated).
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 6,
"tags": "logic, predicate logic"
}
|
Size of Enumeration<String>
How can I get the size of an `Enumeration<String>` without iterate over it?
While debugging I can see the `size` of the the enumeration but I can't find a way to get this value.
|
The `Enumeration` interface does not expose its size, and some (many?) implementations indeed do not have this knowledge. Without any knowledge of the specific implementation, you have no choice but to iterate over it.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 10,
"tags": "java"
}
|
Macbook Pro 2011(early) BCM4331 Wifi not working on kernel 4.4.0-108 and 4.4.0-109
My wifi broke on the new kernels ... I'm running xubuntu on a macbook pro 2011(early). Ever since we got new version of the kernel higher than 4.4.0-104, I can't get wifi to work anymore ... Any Ideas ?
|
SOLVED
I booted into the working 4.4.0-104 kernel and reinstalled bcmwl-kernel-source and dkms. That reinstalled the wl.ko module for all kernels, since the wl.ko module was missing from the newer kernels and was not loaded at boot.
$sudo apt remove bcmwl-kernel-source dkms --purge
$sudo apt install bcmwl-kernel-source dkms
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 1,
"tags": "wireless, macbook pro"
}
|
Bind TextArea linebreaks to html
I have a textarea binded to a div such that anything you type in the textarea updates the div.
The only thing that bindings doesn't respect is newlines in textarea so if you hit 'enter' within textarea, the div doesn't get a break.
Fiddle: <
I am using a helper and it doesn't work.
As per Point 4 on this link: < it is not supposed to work. But even with the solution on that link, I can't get it to work.
Any ideas on how to update the div with `<br/>` tags on linebreaks within the textarea?
|
Use a computed property to format the location's line breaks.
HTML:
<script type="text/x-handlebars">
{{#with App.obj}}
{{view Ember.TextArea valueBinding="location"}}
<div>{{{formattedLocation}}}</div>
{{/with}}
</script>
JavaScript:
App.obj = Ember.Object.create({
location:'Palo Alto',
formattedLocation: function() {
return this.get('location').replace(/\n\r?/g, '<br />');
}.property('location').cacheable()
});
<
In the example I removed your helper so it would be a bit easier to follow exactly what is going on. If you need to use a helper and are unable to figure it out let me know and I will add the helper back in.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "ember.js"
}
|
Java - java.lang.NullPointerException (put data into List<>)
I would like to know why I have got this error. Have you got idea and do you know how to fix it?
Error(I get this error in put()):
Exception in thread "main" java.lang.NullPointerException
at nacs.put(nacs.put:36)
at Program.main(Program.java:69)
Program: (Main)
Nac nacs = new Nac();
nacs.put(new Intsult(1));
nacs.put(new Intsult(2));
Class:
public class Nac implement IPoraw
{
public List<IAbstrsUlt> abs;
public void put(IAbstrsUlt value)
{
abs.add(value);
}
}
|
Initialize list.
private List<IAbstrsUlt> abs = new ArrayList<IAbstrsUlt>();
_Note: You should always try to declare your members more restrictive. Default value for Object is null. ReferOracle tutorial to know default values._
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 0,
"tags": "java"
}
|
jquery keyup event depend on id parameter
i am using jquery keyup method to convert letters to uppercase which is working now.but how can i add exception into so that my `txtEmail` id wont get converted into uppercase
<input runat="server" clientidmode="static" type="text" id="txtEmail" value="" />
//Only this emaild should not get change to uppercase
<input runat="server" clientidmode="static" type="text" id="txtAdd1" value="" />
jQuery :
$("input[type=text]").keyup(function () {
$(this).val($(this).val().toUpperCase());
});
i can not change HTML markup. i want to do it in jquery itself.
|
Try .not()
$("input[type=text]").not('#txtEmail').keyup(function () {
* * *
also use `this.value` instead of `$(this).val()` lil faster.
* * *
`**fiddle**` by jagruti
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "jquery"
}
|
Grails flash message w/ gritter
Normally the message appears by using
<g:if test='${flash.message}'>
<div>${flash.message}</div>
</g:if>
whenever an action is triggered.
How do you set it to appear like a gritter notification? So that say i click a submit button
<button class="btn btn-primary" data-dismiss="modal" type="submit">Log me in</button>
A pop-up on the upper right will appear. Here's the gritter snippet. I find it hard since im new to javascript
$('#flash-message').click(function(){
$.gritter.add({
title: 'Notice',
text: '${flash.message}',
image: '',
sticky: false,
time: ''
});
return false;
});
|
Just wrap the g:if around the JavaScript block, so it won't be generated if there's no message.
PS: you will probably need to rewrite the content of your gritter text attribute, I'm not sure it's going to work like that.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, grails, gritter"
}
|
How to Select 1 Row From Each 10 Rows in MySQL
I am recording a real time change of a given signal into my database table.
Then I draw line graph to visualize the change of the signal level.
I want to get (10n+1)th rows in the table to make a rough graph. 10 is also arbitrary. User may change it to another value.
Does someone know how to make this **_just using a MySQL Query_**
If no, I will go with PHP after selecting all the data.
Here my table structure is:
|id |signal1 |signal2 | signal 3 |
+----------+----------+----------+------------+
|1 |0.41452 | 1.32135 | 0.31231 |
...
|
If you have an auto_incrememt id column, you can select rows that are divisible by n
SELECT * FROM tableName1 WHERE MOD(id,10)=0;
// id divided by 10 with a remainder equal to 0 (exact)
or without sequential column id's
SELECT * FROM (
SELECT
@row := @row +1 AS rowNum, colName1
FROM (
SELECT @row :=0) r, tableName1
) ranked
WHERE rowNum % 10 = 1
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "php, mysql"
}
|
How to serialize to json on C# application project (no Asp.net)?
I wrote an application project in c#. Is there a way to serialize a collection to Json string format? If I use C#4? C#3?
Another q: within Visual Studio 2010 ultimate I remember I could search and download dll from the web: Web Downlaoder or so. I cnnot find it again. Does any one know it?
TIA
|
Install Nuget < using visual studio extension manager, look for json.net in nuget (right click on your project and select Manage nuget packages), add it to your project, you can serialize using this library without adding dependency on system.web
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, json, visual studio 2010, serialization, c# 4.0"
}
|
How do I remove Bootstrap from asp.net project?
I created an ASP.Net webforms project and after doing all the backend stuff, I now want to work on the design. I want to use Google Material Design Lite. The project currently has all the Bootstrap styles that it puts in when I created the project and I want to remove all of that. I removed all of the stylesheet files I could find, and yet the appearance of the site remains the same. Where is it getting the stylesheet information from if not from *.css files and how do I get rid of it?
|
You'll have to remove the masterpage and import your own stuff. Create a webpage without using a masterpage. And then import your own CSS.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "css, asp.net, twitter bootstrap"
}
|
Create list of list of numbers. If sorting is wrong a new sublist should be created
a) Input is list of numbers
i/p = > [2,5,1,4,7,3,1,2,3]
b) output should be sorted sublists
o/p = > [[2,5],[1,4,7],[3],[1,2,3]]
|
**Algorithm**
input = [2,5,1,4,7,3,1,2,3]
output = [[]]
for idx,val in enumerate(input):
if idx > 0 and input[idx-1] > input[idx]:
output.append([val])
else:
output[-1].append(val)
print output
Output is
[[2, 5], [1, 4, 7], [3], [1, 2, 3]]
**Explanation of the algorithm in words:**
Create an output list with an empty sublist. Enumerate over the input list. If the previous element (if one exists) is not bigger than the actual element add the element to the last sublist of the output. If it's bigger create a new sublist in output and add it to this new sublist.
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": -16,
"tags": "python, sublist"
}
|
How can I delete a has_many relation when update?
I have two tables, example:
table_one n x 1 table_two
However, table_two has many table_one elements.
Models:
class TableOne < ActiveRecord::Base
belongs_to :table_two
end
class TableTwo < ActiveRecord::Base
has_many :tables_one, class_name 'TableOne'
end
I would like to auto delete all elements in `table_one` when the `table_two` update (before it)
ps: or, where is the correct place to put `table_one.table_two.delete_all`?
**UPDATE 1**
This command:
table_two = TableTwo.last
table_two.tables_one = [TableOne.new(<attributes>), TableOne.new(<attributes>, TableOne.new(<attributes>]
table_two.save
Should remove all the existing tables_one of table_two and then add the three new table_one.
|
I can't try right now but I think you want that:
class TableTwo < ActiveRecord::Base
has_many :table_two, :dependent => :delete_all
end
**Edit** adding the dependent tag to avoid the foreign key to be nullified instead of destroying the record Source: <
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "ruby, activerecord, ruby on rails 4"
}
|
Where is the site.css file located for Identity?
I have an asp.net core 2.1 MVC application. I have ran the Scaffold Identity which has generated all the HTML and models used. I can't however find the css file that identity is using for its layouts?
In chrome developer tools it tells me site.css is being loaded from `/Identity/css/site.css` and bootstrap is being loaded from `/Identity/lib/bootstrap/dist/css/bootstrap.css`. These files don't seem to exist anywhere in my project. Am I missing something?
It's not using the `site.css` file that's located in `wwwroot/css`.
|
The Identity default UI is a Razor Class Library. The static resources are being embedded and loaded from the library. Specifically, the Static Files middleware is loading up the embedded resources as if they were on the filesystem, using a `ManifestEmbeddedFileProvider`.
Long and short, you can override those by simply creating files in the same location in your project. Then, your project's versions will take over. Unfortunately, the scaffold doesn't provide a way to scaffold static resources as well. However, you can simply view the source in your browser and then copy that into your project's version of the file.
You can also view the source of the RCL here. That way you can reference whatever code you need, without even needing the scaffold. Anything you add to your own project overrides what's coming from the RCL.
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 9,
"tags": "razor, asp.net core, asp.net core mvc, asp.net identity"
}
|
Core Animation question about swapping views
-(IBAction)buttonPressed1:(id)sender
{
SignView *tempVC = [[SignView alloc] initWithNibName:@"SignView" bundle:Nil];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationTransition: UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
[UIView setAnimationDelay:0.0f];
[UIView setAnimationDuration:0.2f];
[self presentModalViewController:tempVC animated:YES];
[tempVC passDataWithString:button1.titleLabel.text andColor:currentlySelectedColor isNightModeOn:nightMode.on];
[UIView commitAnimations];
}
can anyone help me figure out why this code doesn't work?
|
This method will call beginAnimations: and commitAnimations, which cannot be nested.
[self presentModalViewController:tempVC animated:YES];
So move it to before beginAnimations: or after commitAnimations.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "iphone sdk 3.0, uikit, uiview, interface builder, core animation"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.