qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
11,944,542 |
I want to know whether Perl is installed by default on all Unix-based operating systems. Since I want to write server-side programs, I need to choose between Perl and C.
|
2012/08/14
|
[
"https://Stackoverflow.com/questions/11944542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1595858/"
] |
I'm not sure whether Perl is standard on all Unix server installs. I'm not even sure what that means - a server is a piece of hardware, it doesn't have to come with *any* specific software (not even an OS).
I don't think this should be the deciding factor anyway. You can always compile Perl, or distribute Perl with your program. The factors in choosing a language for your project are:
1) Which languages map well to the domain? Using C for a text processing program would be a mistake, this is where Perl and Python shine (perhaps Ruby also?). Using Perl for your hard real time embedded application would probably be a mistake.
2) What experience do the people on the team have?
3) What skills would you (or your company) like to develop? It might be okay to use a new language if this is something that will give you or your company an edge in the long run. The best example of this would be Ericsson switching to Erlang.
|
70,334,538 |
I was trying to implement (in C#8.0) a class with a generic type parameter (constraint to a delegate) having an event parameter with the same generic type. The intended purpose is to have some custom event handling (Subscribe & Unsubscribe functions) while still allowing any kind of delegate associated with it.
```
public class AEvent<T> where T : Delegate
{
private event T eventData;
public AEvent() { }
}
```
Starting out with the code above, the IDE gives me this error:
>
> 'eventData': event must be of a delegate type
>
>
>
Can someone explain briefly why can't I implement this? Or if there's any alternative way of achieving this?
|
2021/12/13
|
[
"https://Stackoverflow.com/questions/70334538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15331253/"
] |
The C# specification *explicitly* states this is not allowed *(my bold)*
[**Events**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#events)
>
> The type of an event declaration **must** be a *delegate\_type* ....
>
>
>
[**Delegates**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/delegates)
>
> The only way to declare a delegate type is via a *delegate\_declaration*. A delegate type is a class type that **is derived from** `System.Delegate`. *...snip...* **Note that `System.Delegate` is not itself a delegate type**; it is a class type from which all delegate types are derived.
>
>
>
As mentioned by others, it doesn't make a huge amount of sense to do this anyway. Whatever you do, and however you generify this, you have no way of specifying the *arity* (how many parameters to pass), so you would not be able to call it.
Your best bet is to use `Action<T>` or `EventHandler<TEventArgs>`, that way you at least know the number of parameters, and can use generics for the rest.
|
37,906 |
I viscerally hate low calorie sugar replacements - all of them, including Splenda (sucralose), except in one application. In my iced coffee I like sugar-free hazelnut syrup. The brand that I've been using is sweetened with Splenda (and sneakily, acesulfame potassium). It would be great except that it's very expensive. I spend $70/month just for that syrup. I have 50 grams of sucralose (that's enough to sweeten my coffee for years) which is the sweetener in Splenda. I also have hazelnut extract. I've made a "syrup" with water, sucralose and hazelnut extract and it turned out OK, but the coffee drink really lacks something without the syrupy quality of the commercial stuff.
The ingredients on the label for the commercial syrup: Purified water, natural and artificial flavors, citric acid, acesulfame potassium, sodium benzoate and potassium sorbate (to preserve freshness), xanthan gum, sucralose (SPLENDA Brand), caramel color.
I know that acesulfame potassium is a sweetener, Splenda generally contains maltodextrin and sucralose, but that doesn't seem to be the case here. There doesn't seem to be any maltodextrin in the product. Unless I'm missing something, that means that the commercial product gets its viscosity from an infinitesimal amount of xanthan gum. Could that be right?
Of course I can get xanthan gum. Say I'm making 2 cups of syrup at a time, I add 1/8 tsp sucralose and two teaspoons of extract to 2 cups of boiling water (off heat). Now what?
|
2013/10/26
|
[
"https://cooking.stackexchange.com/questions/37906",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/20183/"
] |
I don't have a good suggestion for what to use, but at least I can give you some info on xanthan.
Yes, syrup can take viscosity from an infinitesmal amount of xanthan gum. If you add 0.5% to 1% of the fluid's weight in xanthan, you get a pudding consistency. For a syrup-like viscosity, you need much less.
But xanthan is not a sugar, and does not make a syrupy consistency. It makes stuff gooey, not sticky. This may be enough for you, if all you need is some thickness, but the texture won't be the same as normal sugar syrup. I haven't tried commercial sugar-free syrup, so I can't make a comparison there.
Xanthan has also the unfortunate tendency to reduce aroma, although it may not be a problem in the little amounts needed for syrup-like thickness.
|
66,361,067 |
I have a simple asp.net 5 razor pages app which does not show developer exception page but shows this in the browser developer tools
```
The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature.
```
After many iterations and debugging it turns out there was a simple typo in the sql query and instead of showing the developer error page, it was showing blank with the aforementioned error in the browser console !
Questions -
* Is this normal/expected ?
* any way to turn on "more" debugging to identify such errors rather than trial and error ?
environment -
* Visual studio 2019, .net 5
* db access using dapper v2.0.78
* configure excerpts below !
```
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logg)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseDeveloperExceptionPage();
//app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
...
```
there are no try/catch handlers, the code is rather basic
in the razor page
```
public IEnumerable<gEmployee> ListRows { get; private set; }
DAL mDAL;
public string Message;
public void OnGet(int dID)
{
ListRows = mDAL.GetEmployees(dID);
Message = $"Got {ListRows.Count()} Rows";
}
```
this is how i figured out the error when the OnGet() would get called but 2nd line with Message = ListRows.Count would not get executed !!
in GetEmployees
```
public List<gEmployee> GetEmployees(int dID)
{
using (var conn = new SqlConnection(cx.DefaultConnection))
{
var sql = @"SELECT * from gEmployee ";
if (dID > 0)
sql += " WHERE dID = @dID ";
var ListRows = conn.Query<gEmployee>(sql, new { dID = dID}).ToList();
return ListRows;
}
}
```
|
2021/02/25
|
[
"https://Stackoverflow.com/questions/66361067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135852/"
] |
reformat your data, then do whatever you have done before
```
list1=list(zip(list1[::2],list1[1::2]))
list2=list(zip(list2[::2],list2[1::2]))
```
|
23,043,005 |
*I have tried everything suggested here: [Status bar won't disappear](https://stackoverflow.com/questions/17763719/status-bar-wont-disappear) to no avail.*
My iPhone version of my app has no status bar shown, but on my iPad, **which runs the scaled up version of my iPhone version,** there is a status bar that won't go away!
If it makes a difference, my app uses the devices camera for a majority of the app. If you need more info/code, don't hesitate to ask! My app is iOS 7 only, and I use Xcode 5. Also, I would like the status bar gone in the whole app.
**Do not suggest UIViewControllerBasedStatusBar in the plist-- it does not work.**
---
**Related Articles**
<https://stackoverflow.com/a/18740897/294884>
<https://stackoverflow.com/a/21034908/294884>
<https://stackoverflow.com/a/20307841/294884>
|
2014/04/13
|
[
"https://Stackoverflow.com/questions/23043005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3088956/"
] |
For 2016 onwards all you do is:
===============================
Add these two items to your plist:
==================================
```
<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
```
1. It is that simple
====================
2. There is no other method.
============================
(Note - there's a (pointless) "hide status bar" checkbox in "general settings" "deployment info" section. This simply reads the plist file, it's a completely pointless checkbox.)
---
Historic answers...
===================
I've removed the historic answers as they are completely useless. (If any historians need to read it, click "edit history".)
|
33,370,883 |
I've read in various places that I can use Windows batch file `for` to grab the output of a command and put it in a variable, like this:
```
FOR /F %%G IN ('foo-command') DO SET FOO=%%G
```
Great. So my `foo-command` is actually `C:\Program Files\Foo\foo.bat`, and this is stored in the `FOO_BAT` variable. And it takes a parameter `bar` with value `blah blah='foobar' blah`. So I try that:
```
FOR /F %%G IN ('%FOO_BAT% -bar "blah blah='foobar' blah"') DO SET FOO=%%G
```
I get a lovely `'C:\Program' is not recognized...`. Nothing I can do can get around the space in the command.
If you want to reproduce this, create a simple `C:\Program Files\Foo\foo.bat` file containing just the following, and then run the line above in a batch file.
```
echo FooBar
```
**How can I capture the output of a command (which takes parameters) as a Windows batch variable, if the command has spaces in its path?**
* Yes, I've tried putting quotes around `%FOO_EXE%`.
* Yes, I've tried putting everything in a separate variable and using that single variable in the `FOR`.
* Please try this *with the parameters I supplied* before telling me it works. The presence of the parameters changes everything.
|
2015/10/27
|
[
"https://Stackoverflow.com/questions/33370883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421049/"
] |
```
FOR /F "delims=" %%G IN ('CALL "C:\path with spaces\foo.bat" "blah blah='foobar' blah"') do set foo=%%G
```
Give this a try. And yes I tested it. Foo.bat does nothing more then just echo %1.
|
212,823 |
Do we use cache memory in microcontrollers, if not, why not? If yes, what is its application in embedded systems or it is enough just to have RAM?
|
2016/01/22
|
[
"https://electronics.stackexchange.com/questions/212823",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/81163/"
] |
Cache memory adds a level of latency unpredictability that may be unwanted. A lot (most?) of microcontrollers are used in a realtime setting where you have to budget for worst-case timing. It does not matter if your code is fast *on average*, if there is a chance that it won't meet the deadline in *worst case*. Worst case would be that your code or data is not in the cache, and since you have to budget for it anyway, the cache just adds extra cost and complexity.
Some microcontrollers I have worked with has a small embedded SRAM that can be used as a "manual cache". You put stuff there that must have a low latency, be it code or data.
Now, the term "microcontroller" is becoming more and more bloated. Is the 8-core ARM processor in your phone a microcontroller? If so, then yes, of course it should have a cache.
|
6,128 |
Hello I have a website that I would like to keep online no matter what for that purpose I don't mind buying multiple webhosting packages. Its a small website in terms of size but not in terms of client access and employee email accounts. I would like to achieve the following:
1) Add the DNS records of these multiple providers to one domain name, so if the on providers servers go down it can automatically use the next appropriate server.
2) Emails can be replicated across all three servers, I don't mind purchasing webhosting accounts with the same contol panel if I have to achieve the same.
|
2010/12/01
|
[
"https://webmasters.stackexchange.com/questions/6128",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/1044/"
] |
Assuming your site content is fairly static (not a shopping cart or similar) you can do this using your DNS server entries on the domain. You would purchase hosting from several providers (I'll use `acme.com` and `example.com` as the providers). Each provider should provide a list of the DNS servers to use while registering your domain. It may look something like this:
1. NS1.ACME.COM
2. NS2.ACME.COM
3. NS1.EXAMPLE.COM
4. NS2.EXAMPLE.COM
You enter all 4 of these DNS servers in when you register your domain (or in the editing of your domain properties). As a result, if `acme.com`'s DNS servers go down, then `example.com`'s servers will take over. You would have to set up 2 accounts (one for each hosting company) for your email users, however. But this should be fairly transparent once it is set up.
This is a DNS-level solution for your problem, but I think your problem is more complex than simple DNS tricks will solve for you.
|
26,256,447 |
I have successfuly searched my DB table for what i want and passed it into a DataTable (dt).
The idea is that i want (after the search) to redirect someone to the result page he likes.
So if he Searches for example "Michael" , i'd like to show him , the name Michael as a link , and if he presses it redirect him to his page, which is made by ~/Default.aspx?Email="+ id (id also results after the search and is casted to string).
My Code:
```
protected void Button1_Click1(object sender, EventArgs e)
{
DataTable PassRecord = new DataTable();
String str = "select First_Name,Surname,id from ID where (First_Name like '%'+ @search +'%' ) OR (Surname like '%'+ @search +'%') OR (Email_Account like '%'+ @search +'%')";
SqlCommand Srch = new SqlCommand(str, con);
Srch.Parameters.Add("@search", SqlDbType.NVarChar).Value = TextBox1.Text;
con.Open();
Srch.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = Srch;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
var field = dr["First_Name"].ToString();
Response.Write(field);
Response.Write("<br/>");
}
```
As u understand i want to create a link redirecting to the users profile after the search.
Any help is appreciated,
Thanks in Advance !!!
Michael.
|
2014/10/08
|
[
"https://Stackoverflow.com/questions/26256447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4070124/"
] |
The [sourceforge version](http://phpqrcode.sourceforge.net/docs/html/class_q_rcode.html#a1b90c0989105afa06b6e1c718a454fb5) of the method looks like the following:
```
static QRcode::png (
$text,
$outfile = false,
$level = QR_ECLEVEL_L,
$size = 3,
$margin = 4,
$saveandprint = false
)
```
and does not include any colours. You seem to be looking for the [**GitHub version instead**](https://github.com/t0k4rt/phpqrcode), that [defines the method](https://github.com/t0k4rt/phpqrcode/blob/master/phpqrcode.php#L3117-L3121) as the following:
```
public static function png(
$text,
$outfile = false,
$level = QR_ECLEVEL_L,
$size = 3,
$margin = 4,
$saveandprint=false,
$back_color = 0xFFFFFF,
$fore_color = 0x000000
) {
```
(*Psst, the article you read also mentions it: "Start by downloading the latest PHP QR Code library **from GitHub**", and it also includes a link to the [GitHub project](https://github.com/t0k4rt/phpqrcode)*)
|
178,546 |
So far any search for Pogoplug security risk does not bring up anything alarming. Just wondering if anyone else has run across any mention of security issues with this device.
|
2010/08/21
|
[
"https://superuser.com/questions/178546",
"https://superuser.com",
"https://superuser.com/users/46807/"
] |
Let's go down the stack and look at every aspect of its security.
* **Remote Computer**: very easily compromised on an untrustworthy computer via a keylogger, so if you either a) only access your Pogoplug from your (trustworthy) computers, b) change your password often (i.e., at least once every 6 weeks), or c) use the very awesome [Keepass](http://keepass.info) 2.x that has a feature that scrambles then descrambles the password through simulated keystrokes, the clipboard and the arrow keys.
* **Remote Computer's Internet-Your Pogoplug**: not as easily compromised because Pogoplug (if the reviews are correct) operates entirely under Secure Sockets (SSL), meaning any data between the remote computer and the pogoplug is encrypted with encryptions algorithms that only quantum computers can crack before the universe explodes.
* **The Pogoplug**: There aren't any insomnia-worthy viruses or threats out there, since it runs ARM (only common in phones) and Linux. Unless somebody launches a DDoS attack on it (which, assuming your son isn't Osama bin Laden or targeted by 4chan) means that nobody will a) be able to get into it without the codes, or b) care.
* **Your Son and His Friends**: This is the most important part because most modern schemes involve exploiting human psychology and inability to think reasonably when in immense stress. The worst thing that can feasibly happen is that your son accidentally changes the Pogoplug's privacy settings without knowing or forgetting to log out of a borrowed or public computer.
**In Summary**: The Pogoplug itself isn't a security problem, the people who use it are. And for the same reason phishing schemes are so widespread nowadays.
**Edit**: I should mention that when I was analyzing the security weakpoints, I was assuming that there's some superpowerful group of people after your son (e.g. the NSA, Al Qaeda). Otherwise the chances of people even trying the worst-case attacks I show here are nigh unlikely.
|
65,475 |
Find Familiar lets you cast touch spells through your familiar. Warding Bond is a Touch spell, that creates a connection between "you and the target". I can't find anything against it, but would it be possible to have my Wizard make his familiar cast Warding Bond on the Wizard himself, so that the Wizard gets the +1 to AC and saving throws and resistance to damage?
I realized after I wrote this much that Wizards don't get Warding Bond, but I think the question is still valid for multiclassers.
|
2015/07/30
|
[
"https://rpg.stackexchange.com/questions/65475",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/17884/"
] |
So to start with, it's worth pointing out that you can cast *Warding Bond* on yourself. Touch range spells are described as:
>
> Some spells can target only a creature (including you) that you touch.
>
>
>
Further, under the Targeting Yourself section, it says:
>
> If a spell targets a creature of your choice, you can choose yourself, unless the creature must be hostile or specifically a creature other than you.
>
>
>
You can cast touch spells on yourself unless they specifically say you can't, and *Warding Bond* doesn't specify that. This is actually not a bad idea - you'll get the +1 to AC and saving throws, and the double damage you'll take will be canceled out by the resistance to damage.
*Find Familiar* says that:
>
> when you cast a spell with a range of touch, your familiar can deliver the spell as if it had cast the spell.
>
>
>
Your familiar can **deliver** the spell as if it had cast the spell. This is the only way in which the familiar acts as the caster of the spell. It can certainly deliver *Warding Bond* for you, but you will still be the caster of the spell, and the "you" in *Warding Bond* will still be you, not your familiar. This is effectively equivalent to casting it on yourself directly, except that it took your familiar's reaction.
|
28,358,916 |
Getting below exception while reading a PDF. It opens well in Acrobat reader. I read in another question that though its opened in acrobat its not necessary to open via iText because PDF contains an error and he recommends to fix the PDF. But the file is coming from the client and they are able to open Acrobat, so either I have to fix it or show the error or warning in Acrobat.
```
com.itextpdf.text.exceptions.InvalidPdfException: Rebuild failed: Error reading string at file pointer 10891; Original message: Error reading string at file pointer 10891
at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:655)
```
Excerpt of PDF file
```
%PDF-1.1
1 0 obj
<<
/Creator (Developer 2000)
/CreatorDate (
/Author (Oracle Reports)
/Producer (Oracle PDF driver)
/Title (con5010I412014141258.pdf)
>>
endobj
3 0 obj
<<
/Type /Pages
/Kids 4 0 R
/Count 5 0 R
>>
endobj
7 0 obj
<</Length 8 0 R>>
stream
BT
```
1. Is there any way I can show the client that the PDF has error? either via Acrobat or some other software rather Java exception.
2. Is there way to go around this error and proceed? We faced similar issues for secured PDF and we did unlock. Please suggest
|
2015/02/06
|
[
"https://Stackoverflow.com/questions/28358916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006944/"
] |
It is actually a Invalid PDF. When I open the PDF in text editor I noticed that header has CreatorDate with out close bracket. I just added the close bracket with valid date like this CreatorDate (05 November 2014 17:50:24) then It works. I asked client to correct on their side
|
13,137,439 |
I have a method that I call multiple times, but each time a different method with a different signature is called from inside.
```
public void MethodOne()
{
//some stuff
*MethodCall();
//some stuff
}
```
So `MethodOne` is called multiple times, each time with a different `*MethodCall()`. What I'm trying to do is something like this :
```
public void MethodOne(Func<> MethodCall)
{
//some stuff
*MethodCall;
//some stuff
}
```
but the Methods that are called each have a different return type and different parameters. Is there a way to do this using Functors? If not, how would I go about doing this?
Thank you!
|
2012/10/30
|
[
"https://Stackoverflow.com/questions/13137439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733379/"
] |
You best bet would be to use the non-generic `Action` type (or `MethodInvoker` would be the same), i.e.
```
public void MethodOne(Action callback)
{
//some stuff
if(callback != null) callback();
//some stuff
}
```
From this you can call any method by wrapping it at the caller, i.e.
```
MethodOne(SimpleMethod); // SimpleMethod has no parameters and returns void
MethodOne(() => MoreComplexMethod(1, "abc")); // this one returns void
MethodOne(() => { MethodThatReturnsSomething(12); }); // anything you like
```
etc
|
52,333,702 |
I have minimum to none knowledge of powershell :(
Hi I have two possible options to replace text from an .ini file, one is a menu-style batch, where choosing an option will execute a command.
My problem is: if I use the batch code I can only change a known resolution, because I don't know how to add multiple replace actions so they work if one fails.
The Powershell code does executes MULTIPLE replace commands, but I don't know how to edit it to use it as a batch command (`powershell -command` etc.)
Thank you in advance :)
Batch script:
```
@echo off
set ffile='resolutions.ini'
set HDReady='/resolution:1280,720'
set FullHD='/resolution:1920,1080'
set QuadHD='/resolution:2560,1440'
set UltraHD='/resolution:3840,2160'
powershell -Command "(gc %ffile%) -replace %hdready%, %fullhd% | Out-File %ffile% -encoding utf8"
```
Powershell script:
```
$original_file = 'path\resolutions.ini'
$destination_file = 'path\resolutions.ini'
(Get-Content $original_file) | Foreach-Object {
$_ -replace '/resolution:1280,720', '/resolution:1920,1080' `
-replace '/resolution:2560,1440', '/resolution:1920,1080' `
-replace '/resolution:3840,2160', '/resolution:1920,1080'
} | Set-Content $destination_file
```
|
2018/09/14
|
[
"https://Stackoverflow.com/questions/52333702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10153742/"
] |
Your solution above would also return documents where the field is null, which you don't want I guess. So the correct solution would be this one:
```
GET memoire/_search/?
{
"query": {
"bool": {
"filter": {
"exists": {
"field": "test"
}
},
"must_not": {
"term": {
"test.keyword": ""
}
}
}
}
}
```
|
32,396 |
Say I have a 1D (spatial) signal (resolution = $1000$) which is zero everywhere except from $x = 250$ to $750$, where it equals one.
[](https://i.stack.imgur.com/wSVrp.png)
I ultimately want to calculate the spatial width of this signal using FFTs. Of course we know the width here to be $500$; in actuality, I am dealing with a signal that evolves with time and wish to calculate the average "pulse" width over all the time frames, so I do not know the widths. I have opted to use FFTs in this pursuit, so I must conduct a "sanity check" to make sure the method works. This method was suggested to me by a colleague whose intuition is many leagues farther than my own, so if someone could explain the intuition to me, I would appreciate it a lot.
* Step 1: Subtract the DC background (subtract the mean from every point of the signal).
* Step 2: Take the FFT of the signal, then the power (the Fourier transform times the complex conjugate of it). Normalize the power spectrum.
* Step 3: Calculate the half-width at half-maximum (HWHM); here half-width is the half-width of the peak in k-space, of course.
* Step 4: Convert this k-space HWHM back to real-space: real-space width = 1 / (HWHM / resolution).
[](https://i.stack.imgur.com/dcf5M.png)
When I do these steps for the signal above, I calculate a real-space width of $1189427$, laughably off from $500$. Where does the method go wrong?
|
2016/07/30
|
[
"https://dsp.stackexchange.com/questions/32396",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/23123/"
] |
>
> Say I have a 1D (spatial) signal (resolution = $1000$) which is zero everywhere except from $x=250$ to $750$, where it equals one.
>
>
>
This is not "resolution". Resolution is 300 **Dots Per Inch**. In which case, we could say that the total **physical** length of your pulse is $\frac{500}{300} \approx 1.666$ **inches** (or any other **unit of length**).
>
> I ultimately want to calculate the spatial width of this signal using FFTs.
>
>
>
Why?
>
> I am dealing with a signal that evolves with time and wish to calculate the average "pulse" width over all the time frames, so I do not know the widths.
>
>
>
If there will be multiple pulses of different widths on the same signal, then by opting to detect them with the FFT you are setting yourself a very big challenge because the FFT would return to you information about the signal as a whole. So you could, for example, derive an average rate of pulses (even using the algorithm that is presented here) but not the widths of individual pulses.
If it is somehow guaranteed that within a window of 1000 **samples**, there will be a pulse whose length is guaranteed to be staying well below 1000 samples and all we have to do now is detect where the pulse is and how long it is, then opting for the FFT is an overkill.
The usual way to detect pulse widths is via the simple use of a threshold and a counter. Once the signal's amplitude goes above the threshold, the counter starts counting and it stops once the signal's amplitude goes below the threshold. If you are going to operate in a noisy environment, then there are a number of improvements to that such as adding [hysterisis](https://en.wikipedia.org/wiki/Discrete_wavelet_transform) to the threshold, so that it doesn't respond to very short "bounces" of the waveform and adaptive thresholding where the threshold limit would be derived from the given window of observation (here, from the 1000 **samples**).
If you absolutely have to work in the frequency domain, it might be better to look into the [discrete wavelet transform](https://en.wikipedia.org/wiki/Discrete_wavelet_transform) (DWT), whose output is a time/scale(frequency) representation. But the actual detection of the pulse width is likely to be happening (again) using some form of threhsolding on the output of the DWT. (So, again, huge overkill).
|
13,864 |
I always hear a lot about The Rule of Thirds. I'd like to know more about other 'tried-and-true' composition techniques (not special effects) that can make a photo more interesting.
In particular, I'd especially like to know:
* The name of the technique
* Any particular types of settings the technique is particulary useful
* Interesting ways to 'break' the rule
|
2011/07/09
|
[
"https://photo.stackexchange.com/questions/13864",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/5867/"
] |
While this isn't a duplicate, this can essentially be answered by linking to a few questions we've collected regarding other composition techniques (thanks largely to @JayLancePhotography!):
* [Bakker's Saddle](https://photo.stackexchange.com/questions/11450/what-is-bakkers-saddle)
* [Rule of Odds](https://photo.stackexchange.com/questions/11475/what-is-the-rule-of-odds)
* [Diagonal Method](https://photo.stackexchange.com/questions/11060/what-is-the-diagonal-method-and-should-i-use-it-instead-of-the-rule-of-thirds)
* [Golden Ratio](https://photo.stackexchange.com/questions/8965/what-is-the-golden-ratio-and-why-is-it-better-than-the-rule-of-thirds)
Searching the [composition](https://photo.stackexchange.com/questions/tagged/composition) and [composition-basics](https://photo.stackexchange.com/questions/tagged/composition-basics) tag provides a wealth of knowledge.
|
70,876,660 |
I have an object of data and I want to split it array of objects
```
let data = {
"education_center-266": "Software House x",
"education_center-267": "Learning Academy xyz",
"end_date-266": "2022-01-26",
"end_date-267": "2021-01-22",
"start_date-266": "2021-01-26",
"start_date-267": "1998-11-26",
"title-266": "Web Developer",
"title-267": "Teacher",
}
```
I tried differents ways but couldn't reach the result I want..
the result should be
```
[
{
id: "266",
education_center: "Software House x",
title: "Web Developer",
start_date: "2021-01-26",
end_date: "2022-01-26",
},
{
id: "267",
education_center: "Learning Academy xyz",
title: "Teacher",
start_date: "1998-11-26",
end_date: "2021-01-22",
},
]
```
|
2022/01/27
|
[
"https://Stackoverflow.com/questions/70876660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17363169/"
] |
```
const myObjects = {};
Object.keys(data).map((key) => {
const splitKey = key.split('-');
const elemId = splitKey[1];
const realKey = splitKey[0];
if (!myObjects[ elemId ]) {
myObjects[ elemId ] = { id: elemId }; // Create entry
}
myObjects[ elemId ][ realKey ] = data[ key ];
});
// Turn into array
const myObjectsToArray = Object.values(myObjects);
// Or use the myObjects as a key/value store with ID as index
const selectedElement = myObjects[ myID ];
```
|
39,397,702 |
Here is my Perl code
```
use POSIX;
my @arr = split(/\\n\\n/, $content);
my $len = length @arr;
$len = $len / 2;
my $b = round($len) - 1;
```
At the top of my script I have `use POSIX`. I once had `use Math::Round` but that didn't work.
I'm trying to use the `round` function but the page keeps breaking when I call it.
|
2016/09/08
|
[
"https://Stackoverflow.com/questions/39397702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135605/"
] |
You have to actually call `changeToFahrenheit` from your main method, so your code is:
```
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
changeToFahrenheit();
}
public static double changeToFahrenheit(){
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number between 0-20: ");
double celsius = reader.nextInt();
double fahrenheit = (9/5) * celsius +32;
System.out.println(fahrenheit);
return fahrenheit;
}
}
```
To use a function, you must call a function (This is like the equivalent of the `Main` function in C#). By the way, you cannot do `9/5`, since integer division will result in an integer, `1`. Try `9.0/5.0` for the computation.
|
47,688,879 |
I get some problem with my ANGULAR 5 application.
I use some component that need JQUERY it was functional before the migration I didn t change anything.
I add in my component
declare var jQuery: any;
In package. json
```
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"jquery-sparkline": "^2.4.0",
"jstree": "^3.3.4",
```
dev
```
"@types/jquery": "^3.2.16",
```
angular cli
```
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/metismenu/dist/metisMenu.js",
"../node_modules/jquery-sparkline/jquery.sparkline.js",
"../vendor/pace/pace.min.js",
"../node_modules/jstree/dist/jstree.min.js",
"../node_modules/simplebar/dist/simplebar.js"
],
```
Someone have an idea ?
|
2017/12/07
|
[
"https://Stackoverflow.com/questions/47688879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5284946/"
] |
Try this:
```
$sql = "SELECT * FROM `products` WHERE `status`=1 AND `country`=5 AND `product_price` > 50 AND `product_price` <= 100 ORDER BY `product_id` DESC";
$product = $this->db->query($sql)->result_array();
```
|
11,231,418 |
assume a text file with about 40k lines of
```
Color LaserJet 8500, Color Laserjet 8550, Color Laserjet 8500N, Color Laserjet 8500DN, Color Laserjet 8500GN, Color Laserjet 8550N, Color Laserjet 8550DN, Color Laserjet 8550GN, Color Laserjet 8550 MFP,
```
as an example
any1 able to help me with a reg-ex that can trim out all data after the numbers, but before the comma? so that 8500N becomes just 8500
end result would be
```
Color Laserjet 8500, Color Laserjet 8550, Color Laserjet 8500, Color Laserjet 8500, Color Laserjet 8500, Color Laserjet 8550, Color Laserjet 8550, Color Laserjet 8550, Color Laserjet 8550,
```
amazing bonus kudos to anybody that can then somehow suggest the best way to remove duplicates in notepad++ (or other easily available program)
|
2012/06/27
|
[
"https://Stackoverflow.com/questions/11231418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1298883/"
] |
You should replace each match of `(?<=\d)[^\d,]+(?=,)` with empty string.
The above regex reads: *"Any one or more non-digit and non-comma character(s) between digit and comma"*.
In case you may experience such number with trailing letter(s) at then end of string (or line) and you want that trim as well, even there is no comma behind, then use `(?<=\d)[^\d,]+(?:(?=,)|$)`
That reads similar, it just adds *"or end of string"* behind the first meaning.
---
***Update:***
Because it seems that Notepad++ does not support regex lookaround, then the solution is to replace `(\d)([^\d,]+)(,)` with `\1\3` or `(\d)[^\d,]+(,)` with `\1\2`.
|
46,659 |
[This question](https://meta.stackexchange.com/questions/49550/why-am-i-getting-welcome-to-stack-overflow-visit-your-user-page-to-set-your-nam) was just migrated from SO, and it brought the restricted `[faq]` tag with it. Now no one but a moderator can remove this tag.
Restricted tags\* should be stripped from the question when it is migrated.
\*And blacklisted tags, when [this feature](https://meta.stackexchange.com/questions/19018/implement-a-tag-black-list) is implemented in 6 to 8 weeks
|
2010/04/14
|
[
"https://meta.stackexchange.com/questions/46659",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/132636/"
] |
Great suggestion - no need to overwhelm the mods :)
This will be deployed either tonight or in tomorrow's push.
|
48,128,912 |
While writing a c program I encountered a puzzling behavior with printf and write. It appears that write is in some cases called before printf even though it is after it in the code (is printf asynchronous?). Also if there are two lines in the printf, output after that appears to be inserted between them. My question is what causes this behavior and how can I know what will happen when? What about other output functions (ex. puts) - can I look out for something in the documentation to know how they will behave with others. Example code:
```
#include <unistd.h>
#include <stdio.h>
int main(void)
{
write(STDOUT_FILENO, "1.", 2);
printf("2.");
write(STDOUT_FILENO, "3.", 2);
printf("4.\n5.");
printf("6.");
write(STDOUT_FILENO, "7.", 2);
return 0;
}
```
Output:
```
1.3.2.4.
7.5.6.
```
|
2018/01/06
|
[
"https://Stackoverflow.com/questions/48128912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9156061/"
] |
`write` is not buffered `printf` is. Whenever you use `write` it gets to the console - but `printf` is outputted when it gets `\n` here, because then the buffer is flushed.
That's why after `1.3.` you see `2.4.`
You can flush the output by using `fflush(stdout)` right after the `printf` calls. (`Steve Summit` commented this)
You may wonder there is no other `\n` after that `printf` so why do those characters are flushed?
On program termination the output buffer is also flushed. That is what causes the rest of the `printf` outputs to appear. The `setvbuf()` function may only be used after opening a stream and before any other operations have been performed on it.
---
Also as `zwol` mentioned you can turn of line bufferng of `stdout` using this before making any other call to standard I/O functions.
```
setvbuf(stdout, 0, _IONBF, 0)
^^^
causes input/output to be unbuffered
```
|
34,881,724 |
My Azure services target .Net 4.5.2 and run fine in dev. However, build produces the warning(s):
>
> Warning The project 'SurfInfoWeb' targets .NET Framework 4.5.2. To
> make sure that the role starts, this version of the .NET Framework
> must be installed on the virtual machine for this role. You can use a
> startup task to install the required version, if it is not already
> installed as part of the Microsoft Azure guest OS.
>
>
>
I believe these (local) warnings are causing the publish to fail immediately (and these are the ONLY warnings in the error list).
According to MS, 4.5.2 is supposed to be available in January 2016 (I'm not sure exactly what date, but I thought I had read Jan 12 or Jan 16).
I can't suppress these warnings in the normal way because they don't have warning codes.
1) Is .Net 4.5.2 actually available on Azure
2) Is there a way to suppress warnings that don't have codes?
3) Something else I'm not thinking of?
I'm using SDK 2.8.1. And OSVersion="\*".
|
2016/01/19
|
[
"https://Stackoverflow.com/questions/34881724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5811182/"
] |
>
> Is .Net 4.5.2 actually available on Azure?
>
>
>
[Yes](https://azure.microsoft.com/en-us/documentation/articles/cloud-services-guestos-update-matrix/). .NET 4.5.2 is available in the current `osVersion` \* of `osFamily` 2, 3 and 4.
>
> Is there a way to suppress warnings that don't have codes?
>
>
>
Cloud service projects upgraded to Azure SDK 2.9 no longer generate this warning. Projects using a prior version of the SDK (even if version 2.9 is installed) still generate this warning. To suppress this warning without upgrading the project to SDK 2.9 you can add the following snippet to your .ccproj file.
`<ItemGroup>
<WindowsAzureFrameworkMoniker Include=".NETFramework,Version=v4.5.2" />
</ItemGroup>`
|
89,359 |
I've managed to get a Wubi installation onto my USB flash drive, which works on *both* VirtualBox and on a native computer. (The data is on the `root.disk` file.)
It works *completely fine*, except for one little caveat: the files I create or modify don't actually persist on the drive!
My grub.cfg:
```
menuentry "Ubuntu, Linux 2.6.38-13-generic" {
insmod part_msdos
insmod ntfs
set root='(/dev/sdb,msdos1)'
search --no-floppy --fs-uuid --set=root 02E8D1D3E8D1C4D7
loopback loop0 /ubuntu/disks/root.disk
set root=(loop0)
linux /boot/vmlinuz-2.6.38-13-generic root=UUID=02E8D1D3E8D1C4D7 loop=/ubuntu/disks/root.disk ro acpi_sleep=nonvs acpi_osi=Linux acpi_backlight=vendor splash
initrd /boot/initrd.img-2.6.38-13-generic
}
```
My fstab:
```
# /etc/fstab: static file system information.
#
# Use 'blkid -o value -s UUID' to print the universally unique identifier
# for a device; this may be used with UUID= as a more robust way to name
# devices that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
proc /proc proc nodev,noexec,nosuid 0 0
/host/ubuntu/disks/root.disk / ext2 loop,errors=remount-ro 0 1
```
Ideas on why this is happening?
|
2011/12/21
|
[
"https://askubuntu.com/questions/89359",
"https://askubuntu.com",
"https://askubuntu.com/users/8678/"
] |
I feel so silly.
VirtualBox was never writing the changes to the file; it was discarding them after each boot.
It was fine on the native machine.
|
364,052 |
I'm using Minecraft Education Edition. I want to summon 3 to 5 fish whenever a player comes closer to a location in the sea and I want it to put some delay for summoning too, for example: 3 seconds.
Can I achieve this with command blocks or with other methods?
|
2020/02/16
|
[
"https://gaming.stackexchange.com/questions/364052",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/244115/"
] |
**Try resolving the problem using a 'Cure All' batch file.**
These files list all known active effects from the base game and DLC (and the Wet & Cold and Skyrim Immersive Creatures mods), preceded by the `player.sme` command (which stands for 'Stop Magic Effect' on 'player'), and can be executed using the in-game console.
You can find an archive file with these batch files under *Solution 4* on [this page](https://forums.nexusmods.com/index.php?/topic/872861-tutorial-removing-unwanted-magic-effects-from-the-player/). [Here](http://forums.nexusmods.com/index.php?app=core&module=attach§ion=attach&attach_id=40779) is a direct link (you need a (free) account in order to download). The file was created by NexusForums user *LubitelSofta*.
Be sure to take off all your (enchanted) gear beforehand.
Instructions as per the Nexus forum thread:
>
> * Extract the files to your Skyrim root folder (not the data subfolder).
> * Edit the Dawnguard, Dragonborn, or WC or SIC batch files (if necessary) so that every shader or effect ID matches your load order (see above).
> * Start the game.
> * In the console type `bat <filename>` (without quotes), e.g. `bat DBMGEF`.
>
>
>
|
64,731 |
I'm looking add-in a bit more speficity to the WP Cron intervals. To add a "weekly" interval, I've done the following:
```
function re_not_add_weekly( $schedules ) {
$schedules['weekly'] = array(
'interval' => 604800, //that's how many seconds in a week, for the unix timestamp
'display' => __('weekly')
);
return $schedules;
}
add_filter('cron_schedules', 're_not_add_weekly');
```
Which works great, but - the extra sauce here is getting that cron to run on a specific day:
```
if( !wp_next_scheduled( 're_not_mail' ) ) {
wp_schedule_event( time(), 'weekly', 're_not_mail' );
}
```
Anyone have any thoughts on the best way to accomplish this using WP Cron (assuming this isn't per a specific site that we'll have control over their cPanel/CRON area). Thanks!
Update
======
Going at this full-force and found [an article](http://wp.tutsplus.com/articles/insights-into-wp-cron-an-introduction-to-scheduling-tasks-in-wordpress/?search_index=1) that may have clarified things a bit more, but doesn't exactly answer my question. The basic gist of that article states that the WP Cron isn't as flexible (past the "hourly, daily, weekly" params), so extending it to something like *weekly on a certain day* seems a bit farfetched.
The issue (calling it an issue out of confusion/frustration) I have with that is -> sure, I could disable WP CRON and have WP CRON run once a week using the server CRON, BUT, that also means that the items that are normally run, like plugin/theme updates, post deletions/publishes based on CRON are put on a backlog for an entire week (if I wanted CRON to run once a week every Monday for example).
I'd have to assume others have come across this, so anymore insight on this would be a huge help. Thanks!
|
2012/09/10
|
[
"https://wordpress.stackexchange.com/questions/64731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9605/"
] |
WP-Cron is not intended to be that precise, and should not be used if you have to have things scheduled at specific times. WP-Cron is a "best effort" scheduling mechanism, and it cannot guarantee run timing like a real cron system can.
If you need precision of this nature, the only real answer is to not use WP-Cron for it. It's not designed for that, and it cannot do it. Any hacky code you attempt to add to it to make it capable of this won't fix that underlying problem.
Use a real cron system.
|
3,274,167 |
Let's consider the following problem. Imagine there is a tank filled up water (it's volume is equal to $V$). We connect two pumps to out tank. The first one pumps into the tank a mixture of 10% alcohol and water ($s\_1$ liter per minute). The second one pumps out of the tank what's inside (with the speed equal to $s\_2$ liters per minute).
I am to find the function $x(t)$ which describes the concentration of alkohol in a tank at any given time $t$. Of course $x(0) = 0$.
I am a bit stuck here. How should the equation look like? How can I derive it?
|
2019/06/25
|
[
"https://math.stackexchange.com/questions/3274167",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/403569/"
] |
$\{1,i\}$ is a basis for complex numbers $\Bbb C$ as a vector space over real numbers $\Bbb R$; the dimension is $2$.
A basis for $\Bbb C^2$ as a vector space over $\Bbb R$ is $\{(1,0), (i,0), (0, 1), (0,i)\};$ the dimension is $4$.
In general, a complex vector space of dimension $n$ is a real vector space of dimension $2n$.
|
31,165,342 |
Let's consider the following simple program:
```
int main()
{
int *a = new int;
}
```
Is it reliable that the value of `*a` is `0`. I'm **not** sure about that because primitives don't have default-initialization:
>
> To default-initialize an object of type T means:
>
>
> (7.1) — If T is a (possibly cv-qualified) class type (Clause 9),
> constructors are considered. The applicable constructors are
> enumerated (13.3.1.3), and the best one for the initializer () is
> chosen through overload resolution (13.3). The constructor thus
> selected is called, with an empty argument list, to initialize the
> object.
>
>
> (7.2) — If T is an array type, each element is default-initialized.
>
>
> (7.3) — **Otherwise, no initialization is performed**.
>
>
>
I'd say that `*a` is not initializaed so accessing it would lead to UB. Is that correct?
|
2015/07/01
|
[
"https://Stackoverflow.com/questions/31165342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2786156/"
] |
To be absolutely clear, consider
```
int *a = new int;
int *b = new int();
```
`*a` is **not initialised**, `*b` is initialised to 0.
Use of `*a` prior to initialisation is undefined behaviour.
|
54,624,545 |
I am trying to translate this Oracle Scripts to MSSQL:
```
C_LIFECO CONSTANT CHAR(1) := '2';
C_FSUCO CONSTANT CHAR(1 CHAR) := '9';
C_LIFEBR CONSTANT CHAR(2 CHAR) := '10';
C_USR CONSTANT CHAR(10 CHAR) := 'MTLBATCH';
C_JOBNM CONSTANT CHAR(10 CHAR) := 'L2DATAMIGR';
C_INFO CONSTANT ROW_NUMBER(8) := 2;
C_SECTION_CNT CONSTANT ROW_NUMBER(10) := 500000;
```
This is my attempt but it kept giving me syntax error: Incorrect syntax near '1'.
```
C_LIFECO CHAR(1) := '2';
C_FSUCO CHAR(1) := '9';
C_LIFEBR CHAR(2) := '10';
C_USR CHAR(10) := 'MTLBATCH';
C_JOBNM CHAR(10) := 'L2DATAMIGR';
C_INFO BigINT(8) := 2;
C_SECTION_CNT BigINT(10) := 500000;
```
|
2019/02/11
|
[
"https://Stackoverflow.com/questions/54624545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You don't need to specify data size `BigINT(10)/BIGint(8)` in SQL Server just only specify BigINT
```
C_LIFECO CHAR(1) := '2';
C_FSUCO CHAR(1) := '9';
C_LIFEBR CHAR(2) := '10';
C_USR CHAR(10) := 'MTLBATCH';
C_JOBNM CHAR(10) := 'L2DATAMIGR';
C_INFO BIGINT := 2;
C_SECTION_CNT BIgINT := 500000;
```
|
3,770,970 |
In Example 2.39 in Hatcher, he used cellular homology to compute the homology groups of the 3-torus. I am studying for my exam and we did not cover the cellular homology. So I am thinking of using Mayer-Vietoris sequence. So we are considering the standard representation of the 3-torus X as a quotient space of the cube.
I am going take A=small ball inside the cube. $B=X\setminus A'$ (A' small neighborhood of A) so that
$A \cap B $ deformation retracts onto the sphere $S^2$. I know the homology groups of $A$ and of $A \cap B$. I also know that $B$ deformation retracts to the quotient space of the union of all square faces of the cube.
My problem is this: How can I determine the homology groups of B?
And once I do that how can I see the map from $H\_2(S^2)$ to $H\_2(B)$?
PS: One of the answer suggested a really nice other decomposition. However, I might want to need to compute the homology of B first as the problem recommended!
|
2020/07/27
|
[
"https://math.stackexchange.com/questions/3770970",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/752801/"
] |
First, I think Matteo Tesla proposed a great decomposition that simplifies the problem.
Since OP requested to keep the original MV argument, I decided to complete it.
Let $A=D^3,B$ be as what OP stated in the question.
>
> Determine $H\_\*(B)$.
>
>
>
$B$ deformation retracts onto the surface of the cube, which consists of six squares with opposite edges identified, i.e., it consists of six $T^2$, whose homology groups are known. Thus, $H\_2(B)=\bigoplus\_{i=1}^3{H\_2(T^2)}=\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}$ because opposite faces are identified on the edges, which are also generators of the $2$nd homology group of each $T^2$. Similarly, $H\_1(B)=\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}$. You can work out these expressions by drawing a flat diagram of the surface of the cube and labelling all equivalence classes. (I can also edit the post to include my drawing if you want...)
[](https://i.stack.imgur.com/vd8gE.png)
Although all of the six faces are tori, their generators of $H\_1,H\_2$ are identified. A brief way to determine the homology group is just observing this graph, but you can also regard them as different tori and apply MV sequence multiple times, then mod out those identified images, which is more convincing but also more complicated.
>
> Compute $H\_\*(T^3)$:
>
>
>
We compute $H\_3(T^3)$ by a part of MV sequence:
$$0\to H\_3(T^3)\overset{\phi\_3}{\to}\mathbb{Z}\overset{\psi\_3}{\to}\bigoplus\_{i=1}^3\mathbb{Z}\to...$$
Your question specifically asks for how to determine $\psi$, so let's focus on that.
Consider the following commutative diagram similar to that of Seifer-Van Kampen Thm
$$
\require{AMScd}
\begin{CD}
H\_2(S^2)@>i>>H\_2(A)\\
@Vj=\psi VV @VlVV\\
H\_2(B)@>k>>H\_2(T^3)
\end{CD}
$$
We can ignore $H(A)$ because $A\simeq\{\*\}$. And, Let $\alpha,\beta,\gamma$ be the three generators of $H\_2(B)$ that are oriented counterclockwise and $\delta$ the generator of $H\_2(S^2)$.
Then, $\psi(\delta)=\alpha+\beta+\gamma-\alpha-\beta-\gamma=0$ (use the diagram of the flat surface to help you). **Geometrically, the diagram is induced by the chain complex, so $\psi$ actually sends cycles to cycles. $\delta$, as a generator of $H\_2(S^2)$ is mapped into $B$ (observing $\delta$ in $B$) it deformation retracts onto the surface. The surface consists of three pairs of faces with opposite orientation when it is identified (you can try to make one, even though they're all oriented counterclockwise in the diagram), so we get the expression as desired because all groups are abelian.** Thus $\text{im}(\psi)=0,\text{ker}(\psi)=\Bbb{Z}$, which implies $H\_3(T^3)\cong\mathbb{Z}$.
For $H\_2(T^3)$, we already know that the map $\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}\overset{}{\to} H\_2(T^3)$ is surjective because we have $H\_2(T^3)\to H\_1(S^2)=0$. Now because $\text{im}(\psi)=0$, the map $\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}\overset{}{\to} H\_2(T^3)$ is also injective. Hence, $H\_2(T^3)\cong\bigoplus\_{i=1}^3\mathbb{Z}$.
I guess I can stop here to make this post focus on the main problem on that map.
|
24,126,220 |
I'm trying to build an HTML form that accepts a file list, and sends it over to the php script to delete it. I've got a very barebones thing going on here with HTML form to accept the file names:
```
<form method="post" action="unlink.php">
File list<br />
<textarea cols="40" rows="10" name="files"></textarea><br />
<input type="submit" value="Send" />
</form>
```
and the php to retrieve these files and delete it:
```
<?php
$files = $_POST['files'];
$delete = unlink($files);
if ($delete)
{
echo "Successfully deleted files";
}
```
This works great for single files, however, I'm looking to delete multiple files. If for example I pass 1.txt and 2.txt as the file names, it tries to delete: unlink(1.txt 2.txt). I am probably doing this wrongly, but does anyone have any suggestions on how I can get this working? Thanks.
|
2014/06/09
|
[
"https://Stackoverflow.com/questions/24126220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3723380/"
] |
The issue is that the string you are getting back from your database is actually something like `"\\n"`, not `"\n"`. Most likely you have some autoescaping going on somewhere, either before things get saved in the DB or before it gets to where you are using it in your app.
Hacky workaround that isn't a great idea but will probably "work":
```
var myLineBreakFromDatabase = getMyLineBreak().split('\\n').join('\n');
```
|
2,282,020 |
$f$ is a function from $\Bbb R$ to $(0,2)$ defined as
$$f(x)=\frac{e^x-e^{-x}}{e^x+e^{-x}}+1.$$
The function $f$ is invertible and I want to find its inverse.
I tried using methods like taking $\ln$ on both sides but they don't seem to work.
|
2017/05/15
|
[
"https://math.stackexchange.com/questions/2282020",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/255512/"
] |
Here is my go at it. First, observe that we have the two hyperbolic trig functions
$$ \mathrm{sinh}(x)=\dfrac{e^{x}-e^{-x}}{2}, \qquad \mathrm{cosh}(x)=\dfrac{e^{x}+e^{-x}}{2}$$
which defines $\mathrm{tanh}(x):=\mathrm{sinh}(x)/\mathrm{cosh}(x)$. It follows form this that your function $f$ may be written as $f(x)=\mathrm{tanh}(x)+1$. From this, one knows that the inverse function of the hyperbolic tangent is well defined and equal to
$$\mathrm{artanh}(x)=\frac{1}{2}\ln \left(\frac{1+x}{1-x}\right)$$
with domain $(-1,1)$. Thus,
$$\mathrm{tanh}(x)=f(x)-1\qquad\Rightarrow\qquad f^{-1}(x)=\frac{1}{2}\ln \left(\frac{x}{2-x}\right).$$
If your are not satisfied with my use of hyperbolic trig functions, you can always "reverse engineer" the inverse.
I hope this helps!
|
73,175 |
There are two different stories of how King Arthur received his sword, Excalibur. The first is that he pulled it out of an anvil or stone slab (and by doing so confirmed that he was the rightful king of the land). The second is that he received it from the Lady of the Lake (and that he had to return it to her before he died).
Which one of these stories is correct? Or did King Arthur have two different swords that he got different ways?
|
2014/11/21
|
[
"https://scifi.stackexchange.com/questions/73175",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/-1/"
] |
The Excalibur problem is that, over time, people have combined two different Arthurian swords into a single blade. This is a serious pet-peeve of mine.
* **Sword # 1:** "Clarent", the sword in the stone. It was used in Ceremonies (e.g. the dubbing of knights). This sword designates Arthur as being rightful heir of Uthur.
* **Sword # 2:** "Excalibur/Caliburn", given to Arthur by the Lady of the Lake, and Arthur's sword for battle. This sword grants the divine right to rule England.
Most popular depictions (especially in recent years) tend just to use one sword or the other and call it Excalibur. However, some find a way of placing the sword in the position of both: e.g. the Lady of the Lake puts it into the stone, or something to that effect.
Older texts, however, *do* make the distinction clear even if it's a "blink and you miss it" moment. For example, a sentence saying that the sword in the stone was fragile, and couldn't be used for combat, so Arthur went to the Lady of the Lake for a new one.
In the medieval "Alliterative Morte d'Arthur" the roles of Arthur having the two swords is actually really important: Part of Mordred's coup involves stealing Clarent (establishing that he has the mortal right to rule by laws of men) in addition to kidnapping/"marrying" the queen. The final battle involves Arthur, wielding Excalibur (divine right to rule), versus Mordred, wielding Clarent. The two then destroy each other.
I really hope this helped clear things up for you. I'd recommend starting with Geoffrey of Monmouth and working your way through medieval texts to see the evolution of the depiction of Arthur's swords.
|
55,757,089 |
I was playing with below javascript code. Understanding of `Object.defineProperty()` and I am facing a strange issue with it. When I try to execute below code in the browser or in the VS code the output is not as expected whereas if I try to debug the code the output is correct
When I debug the code and evaluate the profile I can see the `name & age` property in the object
But at the time of output, it only shows the `name` property
```js
//Code Snippet
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile, 'age', {
value: 23,
writable: true
})
console.log(profile)
console.log(profile.age)
```
Now expected output here should be
```
{name: "Barry Allen", age: 23}
23
```
but I get the output as.
Note that I am able to access the `age` property defined afterwards.
I am not sure why the `console.log()` is behaving this way.
```
{name: "Barry Allen"}
23
```
|
2019/04/19
|
[
"https://Stackoverflow.com/questions/55757089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6531794/"
] |
You should set `enumerable` to `true`. In `Object.defineProperty` its `false` by default. According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Description).
>
> **enumerable**
>
>
> `true` if and only if this property shows up during enumeration of the properties on the corresponding object.
>
>
> **Defaults to false.**
>
>
>
Non-enumerable means that property will not be shown in `Object.keys()` or `for..in` loop neither in console
```js
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: true
})
console.log(profile)
console.log(profile.age)
```
All the properties and methods on `prototype` object of built-in classes are non-enumerable. Thats is the reason you can call them from instance but they don't appear while iterating.
To get all properties(including non-enumerable)[`Object.getOwnPropertyNames()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames).
```js
let profile = {
name: 'Barry Allen',
}
// I added a new property in the profile object.
Object.defineProperty(profile , 'age', {
value: 23,
writable: true,
enumerable: false
})
for(let key in profile) console.log(key) //only name will be displayed.
console.log(Object.getOwnPropertyNames(profile)) //You will se age too
```
|
40,612,700 |
I have a remote api that gives this data
```
{ "images" :
[
{ "image_link" : "http://example.com/image1.png"},
{ "image_link" : "http://example.com/image2.png"},
]
}
```
I have a class with the functions. I have not included constructor here.
```
componentWillMount() {
var url = 'https://naren.com/images.json';
var that = this;
fetch( url )
.then((response) => response.json())
.then((responseJson) => { that.setState({ images : responseJson.images }); })
.catch((error) => { console.error(error); });
}
render() {
return ( <View>
this.state.images.map(( image, key ) => {
console.log(image);
return (
<View key={key}>
<Image source={{ uri : image.image_link }} />
</View>
);
});
</View>);
}
```
I cannot seem to get the images fetched from the api to loop through the view. If I use a static array without the remote source i.e. `fetch`. THis seems to work perfectly.But when I use the fetch and get data from the api this does not work. I can confirm that I am getting the data because the `console.log(image)` inside the `return` statements consoles the expected data.
|
2016/11/15
|
[
"https://Stackoverflow.com/questions/40612700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2159370/"
] |
I quickly Simulated this, and it does not seem to have an issue to loop over the Image array and Render each Image.
```
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
export default class ImageLoop extends Component {
constructor(props){
super(props)
this.state = {
images : []
}
}
componentWillMount() {
var url = 'https://api.myjson.com/bins/2xu3k';
{/*
or any API that can return the following JSON
{"images":[{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"}]}
*/}
var that = this;
fetch( url )
.then((response) => response.json())
.then((responseJson) => {
console.log('responseJson.images',responseJson.images);
that.setState({ images : responseJson.images });
})
.catch((error) => { console.error(error); });
}
render() {
return (
<View style={{height:100,width:100}}>
{this.state.images.map((eachImage)=>{
console.log('Each Image', eachImage);
return (
<Image key = {Math.random()} style={{height:100,width:100}} source ={{uri:eachImage.image_link}}/>
);
})}
</View>
);
}
}
AppRegistry.registerComponent('ImageLoop', () => ImageLoop);
```
Please see the output Here: <https://rnplay.org/apps/bJcPhQ>
|
10,067 |
For bikes like [these](http://www.herocycles.com/images/octane-recra.jpg), why aren't the rear shocks (the shocks are directly above the pedal) vertical like those of a motorcycle? I don't see how the bike can take shocks when the shock absorber is at such a low angle.
A friend said the mud-guard is so high because there's no other way to attach it to the cycle at a lower height. Is that really the reason why the mud-guard is so high?
|
2012/06/26
|
[
"https://bicycles.stackexchange.com/questions/10067",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/4393/"
] |
From my understanding, one of the major features for bicycle suspension is vertical travel. This is to increase pedal efficiency and rear wheel feel. This is why you see engineers jump through hoops when designing rear suspension for bicycles. For example, take a look at the [Pivot Mach 429](http://www.29eronline.com/wp-content/uploads/2009/01/side-view-pivot-convert.jpg). If I count correctly, this bike has 5 points of rotation to accomplish beter pedal efficiency as well as offering more rear-wheel travel. Some motorcycles do have non-vertical mounted suspension as well; the first to come to mind is the [Kawasaki Ninja 650](http://www.motosavvy.com/_ImageAreas/Kawasaki650R-3.jpg).
As for the "mud-guard", that is often referred to as a [filth prophylactic](http://bikesnobnyc.blogspot.com/search?q=filth%20prophylactic). This isn't intended to do much more than keep mud off your shirt and backside. [Full fenders](http://cdn1.media.cyclingnews.futurecdn.net/2011/02/26/2/cielo_sportif_full_view_600.jpg) can be quite difficult to mount to a full-suspension bike (everything keeps moving, man!) so filth prophylactics are common "good enough" equipment. They also tend to have very little in frame requirements (full fenders require braze-ons for mounting them), so they fit on most any bike.
|
64,367,207 |
I use an app called PDF Lightweight to compress my PDFs (since I have made very good experiences) and Thunderbird to send emails.
I want to write an AppleScript that compresses PDFs before attaching them to an email:
```
set attachment1 to "/Users/username/Desktop/Test.pdf"
do shell script "open -a " & quoted form of ("/Applications/Lightweight PDF.app") & " " & quoted form of attachment1
set email_attachment to "attachment=" & "'file://" & attachment1 & "'"
set thunderbird_bin to "/Applications/Thunderbird.app/Contents/MacOS/thunderbird-bin -compose "
set arguments to email_attachment
do shell script thunderbird_bin & quoted form of arguments & ">/dev/null 2>&1 &"
```
The problem is that the original PDF will be attached before the compression finishes. I tried to work with something like [this](https://stackoverflow.com/questions/20146093/waiting-for-do-shell-script-to-finish) but it does not work either. I suppose because I start PDF Lightweight with an "open" command which is -technically- complete even when the app is still compressing.
Any ideas how get the script waiting for the PDF compression?
Thank you!
|
2020/10/15
|
[
"https://Stackoverflow.com/questions/64367207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2408764/"
] |
You could rewrite your hook to set the [fetch policy](https://www.apollographql.com/docs/react/data/queries/#configuring-fetch-logic) to 'no-cache' or 'network-only'
```
const [getResetLink, { loading, data }] = useLazyQuery(FORGOT_PASSWORD, {fetchPolicy: 'no-cache'})
```
On another note, you should consider using Mutation instead of Query for this operation, as probably there is some change in data. For example, you store the unique hash or link for resetting a password or something similar.
|
3,074,401 |
I have a number 46 which is the result of addition of 12+17+17.
Is there a way, given the result 46 and 12 , 17 as the numbers used to get the result, to find out in what combination 12 and 17 was used to get the result 46
|
2019/01/15
|
[
"https://math.stackexchange.com/questions/3074401",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/634979/"
] |
You could try using modulo algebra:
$$n=\alpha 12 + \beta 17\implies [n]\_{17}=[12]\_{17}[\alpha]\_{17} \implies [\alpha]\_{17}=[n]\_{17}([12]\_{17})^{-1}=[n]\_{17}[5]\_{17}$$
You get $([12]\_{17})^{-1}=[5]\_{17}$ with the [extended euclidean algorithm](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm)
This only works well because 17 is prime (or more specifically gcd(12,17)=1). So then you know $\alpha=5n + m\cdot 17$.
That is already an improvement over brute force trying all whole numbers for alpha. Since 5 is a whole number (and this generalizes) $5n>n>\alpha$ so you know that m is negative and basically walk down the negative integers.
You can try playing with that approach a bit.
So pseudo algorithm:
```
extended euclidean algoritm yields: x,y, gcd(12,17) with 12x+12y=gcd(12,17)
if(gcd(12,17)=1)
loop m=0,1,2...
try alpha=x*n-m*17 (calculate beta - is int?)
```
|
29,584,909 |
now with swift 2.0, IOS 8.3 this code doesn't work anymore.
'Set' does not have a member named 'allObjects'
```
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var touch: UITouch = event.allTouches()?.allObjects.last as UITouch!
}
```
I tried a lot of stuffs but nothing seems to work, any idea ?
Thanks
|
2015/04/12
|
[
"https://Stackoverflow.com/questions/29584909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4544794/"
] |
Swift 1.2 has introduced a native `Set` type, but unlike `NSSet` it doesn't have the `anyObject` method. You have a couple of options. You can use the `first()` method or you can take advantage of the ability to bridge a Swift Set to NSSet -
```
let touch = touches.first() as? UITouch
```
or
```
let touchesSet=touches as NSSet
let touch=touchesSet.anyObject() as? UITouch
```
|
44,760,033 |
I'm just starting out learning Python/Spyder. I have completed a few classes in R for data science.
Below is failing with the error: IOError: File APPL.csv does not exist
However, my script and .csv file are in the same folder. Any thoughts on what I'm doing wrong? Thanks
```
import pandas as pd
def test_run():
df = pd.read_csv("APPL.csv")
print df
if __name__ == "__main__":
test_run()
```
|
2017/06/26
|
[
"https://Stackoverflow.com/questions/44760033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5270921/"
] |
I implemented my own version of k-means on top of spark which uses standard TF-IDF vector representation and (-ve) cosine similarity as the distance metric [code snippet for reference](https://gist.github.com/rajanim/e01d1af591d697202c75ee0a785fa94f). The results from this k-means look right, not as skewed as spark k-means. [figure 1 and 2](https://i.stack.imgur.com/CkcIZ.png)
Additionally, I experimented by plugging in Euclidean distance as a similarity metric (into my own version of k-mean) and results continue to look right, not at all as skewed as spark k-means. Results indicate that its not issue with distance measure but some other case with spark's k-means implementation(scala mllib)
|
20,765,066 |
I have table in which only one td will be empty . Here user can drag and drop the td elements .I am trying to write condition so that empty td accept only its neighbor td elements.
Can you please suggest me the accept condition so that ui.droppable or empty td accept its neighbor td .
Code:
```
$("#dropdiv #c tr td").draggable({
appendTo: "body",
helper: 'clone',
cursor: "move",
revert: "invalid"
});
$('#c tr td').droppable({
accept: function(event, ui) {
return ($(this).html().trim().length == 0)
},
drop:function (event, ui ) {
$(this).append(ui.draggable.text());
$(ui.draggable).empty();
}
});
```
From above code if the td is empty then only the td accept ui.draggable .
Please find the demo here:<http://jsfiddle.net/ggbhat/6JKWp/2/>
In demo the middle(5) td is empty , i want only 2,4,6,8 are accepted by 5 .
|
2013/12/24
|
[
"https://Stackoverflow.com/questions/20765066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2110123/"
] |
You can use something like,
```
$('#c tr td').droppable({
accept: function(ui, item) {
if($(this).html().trim().length != 0)
return false;
if($(ui).index()==$(this).index())
return true;
var next=$(this).next().get(0);
var prev=$(this).prev().get(0);
var me=ui.get(0);
if(me==next||me==prev)
return true;
return false;
},
drop:function (event, ui ) {
$(this).append(ui.draggable.text());
$(ui.draggable).empty();
}
});
```
|
19,347,441 |
i've coded a simple map plotting program but there some error which i can't identify.
1. The bug only occur when X coordinate is positive, its ok when its a negative value.
2. Why is there a last column of dots printed when my range is 11 only?
Here's the code:
```
int xRange = 11;
int yRange = 11;
string _space = " ";
string _star = " * ";
for( int x = xRange; x > 0; x-- )
{
for( int y = 0; y < yRange; y++ )
{
int currentX = x - 6;
int currentY = y - 5;
//demo input
int testX = 2; //<----------ERROR for +ve int, correct for -ve
int testY = -4; //<-------- Y is working ok for +ve and -ve int
//Print x-axis
if( currentY == 0 )
{
if( currentX < 0 )
cout << currentX << " ";
else
cout << " " << currentX << " ";
}
//Print y-axis
if( currentX == 0 )
{
if( currentY < 0 )
cout << currentY << " ";
else
//0 printed in x axis already
if( currentY != 0 )
cout << " " << currentY << " ";
}
else if( currentY == testX and currentX == testY )
cout << _star;
else
cout << " . ";
}
//print new line every completed row print
cout << endl;
}
```
The ouput for demo input (x: 2, y: -4): ( it shows x at 3 which is wrong )
```
. . . . . 5 . . . . . .
. . . . . 4 . . . . . .
. . . . . 3 . . . . . .
. . . . . 2 . . . . . .
. . . . . 1 . . . . . .
-5 -4 -3 -2 -1 0 1 2 3 4 5
. . . . . -1 . . . . . .
. . . . . -2 . . . . . .
. . . . . -3 . . . . . .
. . . . . -4 . . * . . .
. . . . . -5 . . . . . .
```
The output for demo input (x: -2, y: 4):
```
. . . . . 5 . . . . . .
. . . * . 4 . . . . . .
. . . . . 3 . . . . . .
. . . . . 2 . . . . . .
. . . . . 1 . . . . . .
-5 -4 -3 -2 -1 0 1 2 3 4 5
. . . . . -1 . . . . . .
. . . . . -2 . . . . . .
. . . . . -3 . . . . . .
. . . . . -4 . . . . . .
. . . . . -5 . . . . . .
```
Can anyone help to identify the two problem in my code? thanks.
|
2013/10/13
|
[
"https://Stackoverflow.com/questions/19347441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545530/"
] |
`if( currentY == testX and currentX == testY )`
That doesn't look right. Shouldn't you be comparing X to X and Y to Y?
Upon closer look, it's all even stranger. Your outer loop generates rows, but you index them with `x`. Inner loop generates columns for each row, and you index it with `y`. There's general confusion over which axis is the X one and which is the Y one.
**EDIT**: Ah, I see the problem now. When `currentY == 0`, you print the numbers for the axis, and **also** print the dot.
|
17,848 |
I've been researching this on my own for weeks without finding anything useable. I need a list of American-style (not Japanese, anime, etc.) character archetypes in American fiction of any type and the psychology of each archetype. At this point genre doesn't matter. A character archetype example: The villain who secretly yearns to be killed, and "finally" released from being alive. My goal is original character creation and I need lists to show me new things. No anime/manga, absolutely no TV Tropes. No IRL psychology like Jung, absolutely no Greek myths. And I'll buy books if I have to.
|
2015/06/23
|
[
"https://writers.stackexchange.com/questions/17848",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/14276/"
] |
Almost all literary tropes have made it to tv/film except for the small number that don't work visually. On top of that the main characteristic of the english language is theft of which Japanese influence is only the latest (although to be fair a dominant influence for anime/manga and other post ww2 japanese culture is american popular culture). If we also exclude greek, we then also have to exclude latin as the myths only really differ in the names of the gods. And if we ignore Jung we should also ignore yoga (which is a interesting blend of indian religion and traditions, british military tradition including calisthenics and good old American con-arts and cultish thinking) and German (thank god that we don't have to list Nazi influences like Jewish, Socialist, Fascist, and other minor influences). If we follow along that line of thinking we should also probably also exclude Russian and Scandinavian myth. So I have compiled a list of all archetypes that meets this stringent list of restrictions and present it here for your approval:
|
40,070,992 |
I keep getting this error in my code, uninitialized local variable "name" used. I set a variable like this
>
> int name = 0;
>
>
>
then later on in the code,
>
> int name = name + 1;
>
>
>
I am trying to set name to 0 then later on add 1 to it then go back to the beginning and still have it equaling name + 1. the problem is it keeps putting it back to 0.
To make it easier here is the part I am talking about.
```
int main()
{
int w = 0;
int choice;
cout << "1: Register\n2: Login\nYour Choice:"; cin >> choice;
if (choice == 1)
{
string username, password;
cout << "Select A Username: "; cin >> username;
cout << "Select A Password: "; cin >> password;
ofstream file;
file.open("data\\" + username + ".txt");
file << username << endl << password;
file.close();
main();
}
else if (choice == 2)
{
bool status = IsLoggedIn();
if (!status)
{
int w = w + 1;
cout << "Unsuccesfull Login!" << endl;
system("PAUSE");
if (w == 3)
{
return 0;
}
else if (w == 2)
{
main();
}
else if (w == 1)
{
main();
}
else if (w == 0)
{
main();
}
}
else
{
cout << "Succesfully Logged In!" << endl;
system("PAUSE");
return true;
}
}
}`
```
|
2016/10/16
|
[
"https://Stackoverflow.com/questions/40070992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7026833/"
] |
As you do not receive an error of redeclaring the variable `name` it seems like you use your `int name = name + 1;` somewhere in the code when it not see the first declaration. Here the problem is that `int name = name + 1;` second "name" is not declared before and you try to initialize your first "name" with it.
From start is a a bad approach but here the problem is that when you declare `int name = name + 1;` it is not in the scope of `int name = 0`.
So first be sure you are incrementing your `name` in a place where the compiler "sees" the declaration of `int name = 0` and get rid of the type in `int name = name + 1;`
|
37,460,524 |
Given an array `arr` and an array of indices `ind`, I'd like to rearrange `arr` **in-place** to satisfy the given indices. For example:
```
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log(arr); // => ["B", "E", "D", "F", "A", "C"]
```
Here is a possible solution that uses `O(n)` time and `O(1)` space, **but mutates `ind`**:
```
function swap(arr, i, k) {
var temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
function rearrange(arr, ind) {
for (var i = 0, len = arr.length; i < len; i++) {
if (ind[i] !== i) {
swap(arr, i, ind[i]);
swap(ind, i, ind[i]);
}
}
}
```
What would be the optimal solution **if we are limited to `O(1)` space and mutating `ind` is not allowed?**
---
**Edit:** The algorithm above is wrong. See [this question](https://stackoverflow.com/q/37724874/247243).
|
2016/05/26
|
[
"https://Stackoverflow.com/questions/37460524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247243/"
] |
This is the "sign bit" solution.
Given that this is a JavaScript question and the numerical literals specified in the *ind* array are therefore stored as signed floats, there is a sign bit available in the space used by the input.
This algorithm cycles through the elements according to the *ind* array and shifts the elements into place until it arrives back to the first element of that cycle. It then finds the next cycle and repeats the same mechanism.
The *ind* array is modified during execution, but will be restored to its original at the completion of the algorithm. In one of the comments you mentioned that this is acceptable.
The *ind* array consists of signed floats, even though they are all non-negative (integers). The sign-bit is used as an indicator for whether the value was already processed or not. In general, this could be considered extra storage (*n* bits, i.e. *O(n)*), but as the storage is already taken by the input, it is not additional acquired space. The sign bits of the *ind* values which represent the left-most member of a cycle are not altered.
**Edit:** I replaced the use of the `~` operator, as it does not produce the desired results for numbers equal or greater than *231*, while JavaScript should support numbers to be used as array indices up to at least *232 - 1*. So instead I now use *k = -k-1*, which is the same, but works for the whole range of floats that is safe for use as integers. Note that as alternative one could use a bit of the float's fractional part (+/- 0.5).
Here is the code:
```js
var arr = ["A", "B", "C", "D", "E", "F"];
var ind = [4, 0, 5, 2, 1, 3];
rearrange(arr, ind);
console.log('arr: ' + arr);
console.log('ind: ' + ind);
function rearrange(arr, ind) {
var i, j, buf, temp;
for (j = 0; j < ind.length; j++) {
if (ind[j] >= 0) { // Found a cycle to resolve
i = ind[j];
buf = arr[j];
while (i !== j) { // Not yet back at start of cycle
// Swap buffer with element content
temp = buf;
buf = arr[i];
arr[i] = temp;
// Invert bits, making it negative, to mark as visited
ind[i] = -ind[i]-1;
// Visit next element in cycle
i = -ind[i]-1;
}
// dump buffer into final (=first) element of cycle
arr[j] = buf;
} else {
ind[j] = -ind[j]-1; // restore
}
}
}
```
Although the algorithm has a nested loop, it still runs in *O(n)* time: the swap happens only once per element, and also the outer loop visits every element only once.
The variable declarations show that the memory usage is constant, but with the remark that the sign bits of the *ind* array elements -- in space already allocated by the input -- are used as well.
|
2,201,912 |
Does the following series converge or diverge:
$$\sum\_{n=1}^\infty \frac{3^{1/\sqrt{n}}-1}{n}$$
Many thanks!
|
2017/03/24
|
[
"https://math.stackexchange.com/questions/2201912",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/428331/"
] |
Since $a^{1/\sqrt{n}}-1$ is asymptotic to $ \frac{\log a}{ \sqrt{n}},$ the series converges.
|
2,258,556 |
I am reading a proof that narrows down to the following statement:
>
> It is easy to see that the number of solutions of $x^6+x=a$ in $\mathbb{F}\_{2^m}$, where $a\in \mathbb{F}\_{2^m}$ and $m\geq 3$ is odd, is same as number of solutions of $x^2+ax+1=0$ in $\mathbb{F}\_{2^m}$.
>
>
>
Why is this true? They say that $x^7=1$ for $x \neq 0$, which I also don't see. Thank you!
|
2017/04/30
|
[
"https://math.stackexchange.com/questions/2258556",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/104220/"
] |
This is only a proof that $f(x)=x^6+x$ is two-to-one on $\Bbb F\_{2^m}$ when $m$ is odd.
Let $K = \Bbb F\_2(a)$ and $M = \Bbb F\_2(x)$.
Let $L$ be the Galois closure of $M$ over $K$ and $G = Gal(L/K)$
Pick an element in $\Bbb F\_4 \setminus \Bbb F\_2$ and call it $\omega$. It is a primitive third root of unity.
We suspect that $M$ is a curve defined over $\Bbb F\_4$, so first we need to determine the subgroup $G' = Gal(L / F\_4(x)) \subset G$.
By looking at the map $f(x) = x^6+x$ over large-ish fields (say $\Bbb F\_{2^{20}}$) and using the Cebotarev density theorem for function fields,
we can observe that $|G'| = 60$ and it has $20,24,15,1$ elements with respectively $0,1,2,6$ fixed points.
This is enough to determine that it is isomorphic to $A\_5$, and acts on the $6$ roots as $A\_5$ acts by conjugation on its six $C\_5$ subgroups
From this, we get the existence of a bunch of formulas :
If $\{p,q\}$ is any unordered pair of roots of $f(x)-a$, then the remaining four roots split into two pairs :
The pair $\{r,s\}$ with $r+s = \omega(p+q)$ and $rs = p^2+\omega pq+q^2$
And the pair $\{u,v\}$ with $u+v = \omega^2(p+q)$ and $uv = p^2+\omega^2 pq+q^2$.
You can notice that $pq+rs+uv = 0$.
The presence of $\omega$ in those formulas witness the fact that the Galois closure is defined over $\Bbb F\_4$ and not $\Bbb F\_2$, and that the behaviour of $f$ depends so much on the parity of $m$.
Also, since $r$ is a root of $X^2 + \omega(p+q)X + (p^2+\omega pq+q^2)$, you have $\omega = (p^2+q^2+r^2)/(pq+qr+pr)$ so just by knowing $r$ you can recover the knowledge of which pair you are in.
And so, if you know three roots, $p,q,r$ then you know a value for $\omega$, and then you know the remaining three roots
$s = r+\omega(p+q), u = q+\omega(p+r), v = p+\omega(q+r)$
Finally, if you look at a stabilizer in $A\_5$ (or $S\_5$) and pick something in its fixed subfield, you get $\Bbb F\_4((p+q)^3)$ (or $\Bbb F\_2((p+q)^3)$). The expression $(p+q)^3$ has five possible values, and $G$ is exactly the full permutation group on them.
---
Now the most important thing to take away from this is that $\omega = (p+q+r)^2/(pq+qr+pr) \in \Bbb F\_4$,
or equivalently that for any three distinct roots $p,q,r$,
$(p+q+r)^4 + (p+q+r)^2(pq+qr+pr) + (pq+qr+pr)^2 = 0$.
To show this algebraically, multiply the expression with $(p+q)(q+r)(p+r)$ to get $p^6(q+r) + q^6(p+r) + r^6(p+q)$, which is then reduced to $(p+a)(q+r) + (q+a)(p+r) + (r+a)(p+q) = 0$
Since the only elements $y,z \in \Bbb F\_{2^m}$ satisfying $y^2+yz+z^2 = 0$ are $y=z=0$, this implies that any degree $3$ factor over $\Bbb F\_{2^m}$ has the form $(x+p)(x+q)(x+r) = x^3+0x^2+0x+pqr =x^3+pqr$, and so if it had a degree $3$ factor, it would factor as $(x^3+y)(x^3+z)$ for some $y,z \in \Bbb F\_{2^m}$. But this is obviously impossible because the coefficient of $x$ is $1$ in $f$ but $0$ in this product.
This is also valid over $\Bbb F\_{2^{5m}}$ so this also prevents a factorisation into factors of degree $1$ and $5$.
Looking in detail at the action of $S\_5 \setminus A\_5$, their cycle decompositions (and so the possible factorisations into irreducibles) are $(114)$ half the time, $(222)$ a sixth of the time, and $(6)$ a third of the time.
As for recognizing the range of $f$, I don't see a general method. It can't coincide with the image of a degree $2$ rational fraction for all odd $m$ at once (I don't think it's even possible for individual values of $m \neq 3$), because this would correspond to a subgroup of index $2$ in $S\_5$ which is not $A\_5$.
|
56,329,060 |
I have a textbox `Job` in `Form2`, and I have multiple textboxes in `Form1`.
Lets say in `form1` I have `Textbox1` which is `RollFromInventory`, `Textbox2` is `RollFromMachine1`, `Texbox3` is `RollFromMachine2` and so on, assume there are 4 other machines, so four other Textboxes.
When I want to populate the textbox `Job` in `Form2`, I want to write an `If` loop which should look for the textbox which has value populated in it, in `form1` (there will be only one textbox which will have a value among all the available textboxes in `form1`), i.e. either `RollFromInventory` will have a value or `RollFromMachine1` will have a value or `RollFromMachine2`..
I am unsure of the looping logic, so I cant really figure out how to go about it.
Currently the code I have written is mainly for populating concatenated values (I am not providing that code, because it will make the objective seem complicated).
|
2019/05/27
|
[
"https://Stackoverflow.com/questions/56329060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11232616/"
] |
This should work:
```
def validate(num):
try:
n = int(num)
return 2 <= n <= 4094
except:
return False
```
The above function returns `True` if the number is an integer in the specified range, `False` otherwise.
|
53,206,307 |
I would like to change the legend style of the following picture generated in Matlab:
```
x1=-5;
x2=5;
y1=-5;
y2=5;
x = [x1, x2, x2, x1, x1];
y = [y1, y1, y2, y2, y1];
fill(x,y,'b')
legend('A')
```
[](https://i.stack.imgur.com/nsQdo.jpg)
As you can see the legend displays a blue rectangle. What I would like is a **filled blue circle** in place of the rectangle **as if the picture was generated as a scatter plot**. How can I obtain that?
|
2018/11/08
|
[
"https://Stackoverflow.com/questions/53206307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9947624/"
] |
Your idea with `when` is almost there. Read about <https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#register-variables>, then you can do:
```
tasks:
- name: npm config get strict-ssl
command: npm config get strict-ssl
register: npm_strict_ssl
changed_when: false
- name: Setting up NodeJS
command: npm config set strict-ssl false
when: "npm_strict_ssl['stdout'] == 'true'"
```
I will also add that the specific settings you want to disable, strict SSL, smells like a very bad idea. Please consider fixing the root cause of the problem instead of lowering down security.
|
976,665 |
How can I prove that, for $a,b \in \mathbb{Z}$ we have $$ 0 \leq \left \lfloor{\frac{2a}{b}}\right \rfloor - 2 \left \lfloor{\frac{a}{b}}\right \rfloor \leq 1 \, ? $$ Here, $\left \lfloor\,\right \rfloor$ is the [floor](http://mathworld.wolfram.com/FloorFunction.html) function. I tried the following: say that $\frac{2a}{b} = x$, and $ \left \lfloor{\frac{2a}{b}}\right \rfloor = m$, with $0 \leq x - m \leq 1$. I tried the same for $ 2 \left \lfloor{\frac{2a}{b}}\right \rfloor $, and then combining the two inequalities. It did not seem to help, though.
|
2014/10/16
|
[
"https://math.stackexchange.com/questions/976665",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/53283/"
] |
In general
$$
0\le \lfloor 2x\rfloor -2\lfloor x\rfloor\le 1.
$$
Proof. Either $x\in [k,k+1/2)$ or $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$.
If $x\in [k,k+1/2)$, then
$$
\lfloor 2x\rfloor=2k\quad\text{and}\quad 2\lfloor x\rfloor=2k,
$$
while $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$, then
$$
\lfloor 2x\rfloor=2k+1\quad\text{and}\quad 2\lfloor x\rfloor=2k.
$$
So the inequalities hold in both cases.
|
50,248,178 |
I am trying to scan for beacons using [startScan(filters, settings, callbackIntent)](https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner#startScan(java.util.List%3Candroid.bluetooth.le.ScanFilter%3E,%20android.bluetooth.le.ScanSettings,%20android.app.PendingIntent)). I have an implementation that works fine for Sony Xperia XZ, and Nexus 5X. The only other device with Android O I have available is a Samsung Galaxy S8, and what works for the other devices produce nothing on the Samsung. (The bluetooth scan is really imbedded in a library module, but even when creating a dummy app the samsung fails, so I'll use that in this example). I have removed the filter and the settings used for `startScan` since the scan doesn't work without them anyway and these are optional.
```
MainActivity
- checks and asks for permissions (ACCESS_COARSE_LOCATION)
- simplified onStart
override fun onStart() {
super.onStart()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val startScan = bleScanner.startScan(null, null, getPendingIntent())
Log.d("testApp", "Start scan! ${startScan == 0}")
}
}
```
PendingIntent:
```
private fun getPendingIntent(): PendingIntent {
return PendingIntent.getBroadcast(
this, REQ_CODE,
Intent(this.applicationContext, BleReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT)
}
```
**Manifest**
Permissions:
```
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
```
Receiver:
```
<receiver android:name="com.testapp.samsungoscan.BleReceiver" >
<intent-filter>
<action android:name="BluetoothDevice.ACTION_FOUND" />
<action android:name="BluetoothDevice.EXTRA_UUID" />
<action android:name="BluetoothDevice.EXTRA_RSSI" />
</intent-filter>
</receiver>
```
Receiver implementation:
```
class BleReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.e("testApp", "On Receive!")
}
}
```
So! Why is this not working for Samsung, while it works for Sony and Nexus?
Note: If I change the receivers `android:name` to a relative path `.BleReceiver` instead of `com.testapp.samsungoscan.BleReceiver`, then the Nexus stops working, but Sony still works!
By work I mean all classes gets used and the logs are triggered.
What is wrong?
|
2018/05/09
|
[
"https://Stackoverflow.com/questions/50248178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1570640/"
] |
You have registered the broadcast receiver in the AndroidManifest.xml with an Intent Filter name
`<action android:name="BluetoothDevice.ACTION_FOUND" />`
First of all, you may provide there any String. Above suggest that you are using [this constant](https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_FOUND), but in fact you are just using the String as is (`BluetoothDevice.ACTION_FOUND`). I would recommend changing it to some `com.testapp.samsungoscan.ACTION_FOUND`. The Extras are not needed and they suggest they are in fact extras, but they are just another action names with name "extra".
I recommend changing to:
```
<receiver android:name="com.testapp.samsungoscan.BleReceiver">
<intent-filter>
<action android:name="com.testapp.samsungoscan.ACTION_FOUND" />
</intent-filter>
</receiver>
```
Secondly, you have to create the PendingIntent with this action name:
```
private fun getPendingIntent(): PendingIntent {
return PendingIntent.getBroadcast(
this, REQ_CODE,
Intent(this.applicationContext, BleReceiver::class.java).setAction("com.testapp.samsungoscan.ACTION_FOUND"),
PendingIntent.FLAG_UPDATE_CURRENT)
}
```
Creating an intent with providing Component name is required since Oreo to be able to get any broadcasts. I'm not sure, however, will it work after your app has been killed by the system.
Lastly, I recommend requesting FINE\_LOCATION, as this: <https://android-review.googlesource.com/c/platform/packages/apps/Bluetooth/+/848935> change may in the future require fine location permission to scan for Bluetooth devices.
|
186,283 |
Now I am using the pull-down menus to set `:TTarget`, `:TCTarget`, and `:TVTarget` to `pdf`.
I also tried setting `g:Tex_DefaultTargetFormat='pdf'` and `g:tex_flavor='pdflatex'`, but neither worked.
Thanks!
|
2010/09/08
|
[
"https://superuser.com/questions/186283",
"https://superuser.com",
"https://superuser.com/users/45020/"
] |
Set
```
let g:Tex_DefaultTargetFormat = 'pdf'
let g:Tex_MultipleCompileFormats='pdf, aux'
```
in your config file for vim (e.g. `~/.vimrc`). That works well for me here, using vim 7.3.3 on Arch Linux.
|
322,594 |
Hello I'm trying to do something like this but it wont work, can you guys tell me help me out?
```
/usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \
-e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \
awk '{print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin"}' >> /tmp/file1 ;
awk '{print $1":"$5":13753:0:99999:7:::"}'>>/tmp/file2
```
Changing ";" to "&&" doesn't work either.
Both file1 and file2 is created, but only file1 contains data.
So basically what I want to do is using the same variables for two commands
|
2011/10/18
|
[
"https://serverfault.com/questions/322594",
"https://serverfault.com",
"https://serverfault.com/users/97188/"
] |
Try this:
```
/usr/bin/mysql -B -r -h ******** -u******* -p****** -D***** \
-e'SELECT `username`, `uid`, `gid`, `homedir` FROM `some_table`)' | \
awk '{ print $1":x:"$2":"$3"::"$4":/usr/sbin/nologin" >> "/tmp/file1";
print $1":"$5":13753:0:99999:7:::" >> "/tmp/file2" }'
```
|
973,548 |
In Fig.$9.17$ $PQRS$ and $ABRS$ are parallelograms and $X$ is any point on side $BR$. Show that
i) $[PQRS]=[ABRS]$
ii)$[AXS]=1/2\cdot [PQRS]$
I have no clue.
|
2014/10/14
|
[
"https://math.stackexchange.com/questions/973548",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/162079/"
] |
I can already see one mistake in that
$$\ln|y-1|=\int(y-1)^{-1}\;dy\neq-\ln(y-1).$$
Also, you ought to note in the derivation of this technique in solving separable ODE (i.e. an application of the chain rule) that you can incorporate the initial conditions in the integration, avoiding arbitrary constants and making more concrete that you are solving an IVP.
In particular we have for this IVP,
$$\int\_{-3}^{y}(z-1)^{-1}\;dz=\int\_{2}^{t}-3\;du$$
$$\ln|y-1|-\ln|-4|=-3t+6$$
$$y-1=e^{-3t+6+\ln 4}.$$
Therefore (after factoring the exponential and noting $e^{\ln 4}=4$),
$$y=y(t)=1+4e^{6-3t}.$$
|
14,348,930 |
We recently upgraded all of our projects to Visual Studio 2012 and .Net 4.5. Most of our projects have custom MMC snapins that handle product configuration. I've now learned that MMC 3.0 doesn't natively handle the .Net 4.0 runtime, since the runtime shipped long after MMC 3.0 was released.
I'm looking for a way to fix our snapins so that MMC doesn't crash when they are loaded and I've come across a lot of pages that mention adding an mmc.exe.config file. I've tried this, and I can't get it to work.
I've created a file with this as its contents:
```
<configuration>
<startup>
<supportedRuntime version='v4.0.20506' />
<requiredRuntime version='v4.0.20506' safemode='true' />
</startup>
</configuration>
```
I have saved this as mmc.exe.config in both the windows\system32 and windows\sysWOW64 directories, however the presence of this file makes no difference. My snapins still crash with the same error message:
```
Could not load file or assembly 'xxxx, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d62dabb4275ffafc' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
```
What do I need to do to get MMC to load .Net 4.0 runtime assemblies properly?
|
2013/01/15
|
[
"https://Stackoverflow.com/questions/14348930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125882/"
] |
For me it works to tell MMC to use the v4 Framework, I've got v4.0.30319
```
set COMPLUS_version=v4.0.30319
start SomeConsole.msc
```
Check the workarounds:
<http://connect.microsoft.com/VisualStudio/feedback/details/474039/can-not-use-net-4-0-to-create-mmc-snapin>
And this are my debug settings:
I use the 32 bit version of the console, and also had to add the into the "c\Windows\SysWOW64\mmc.exe.config" the following:
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version='v4.0' />
</startup>
</configuration>
```
Hope it helps you. GL
|
17,947,251 |
I have 2 class, classA and classB.
ObjectA have a property which is ObjectB. Now the scenario is-
1. ObjectA call ObjectB method- [ObjectB methodB1].
2. after executing method [ObjectB methodB1], objectB send callback to objectA.
3. getting callback ObjectA release ObjectB. did it following way-
[ObjectB release];
ObjectB = nil;
4. ObjectB has another method ->methodB2, which starts executing [ObjectB methodB2] just after sending callback to objectA and it crashes because ObjectA released ObjectB when it's executing, so there is no object then ObjectB.
So if how to solve this problem?
Thanks for your answer.
|
2013/07/30
|
[
"https://Stackoverflow.com/questions/17947251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168394/"
] |
move your callback to ObjectA just after the execution of [ObjectB methodB2].
Or create two callbacks : one after [ObjectB methodB1] and another after [ObjectB methodB2] and release ObjectB after the second callback
|
51,897,851 |
Lets say I have a method which I decorate with `@property`.
Is there a way to get the underlying name of the decorated method?
How could I for instance print the name of the property when it does not have a `__name__` attribute?
I'm trying to do a RPC call and everything works for methods and static functions but not this.
|
2018/08/17
|
[
"https://Stackoverflow.com/questions/51897851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7917697/"
] |
A property has the following attributes: *fget*, *fset* and *fdel*, which are references to the getter/setter/deleter functions.
So, you can get the `__name__` of each of this functions (if not `None`)
Demo:
```
class Thing(object):
@property
def foo(self):
return "foo"
def get_baz(self):
return "baz"
bar = property(get_baz)
>>> Thing.foo.fget.__name__
'foo'
>>> Thing.bar.fget.__name__
'get_baz'
```
|
8,450,027 |
I have a C app (VStudio 2010, win7 64bit) running on a machine with dual xeon chips, meaning 12 physical and 24 logical cores, and 192 gig of ram.
EDIT: THE OS is win7 (ie, Windows 7, 64 bit).
The app has 24 threads (each thread has its own logical core) doing calculations and filling up a different part of a massive C structure. The structure, when all the threads are finished (and the threads are all perfectly balanced so they complete at the same time), is about 60 gigabytes.
(I have control over the hardware setup, so I am going to be using 6 2tb drives running RAID 0, which means the physical limits on writing will be approximately 6x the average sequential write speed, or about 2 gig/second.)
What is the most efficient way to get this to disk? Obviously, the i/o time will dwarf the compute time. From my research on this topic, it seems like write() (as opposed to fwrite()) is the way to go. But what other optimizations can I do on the software side, in terms of setting buffer sizes, etc. Would mmap be more efficient?
|
2011/12/09
|
[
"https://Stackoverflow.com/questions/8450027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994179/"
] |
It is hard to judge the best thing for your situation.
The first optimization to make is to preallocate the file. That way your file system does not need to keep extending its size. That should optimize some disk operations. However, avoid writing actual zeros to disk. Just set the length.
Then you have choices between mmap and write. This also depends on the operating system you use. On a Unix I would try both mmap and pwrite. pwrite is useful because each of your threads can write into the file at the desired file position without fighting over file offsets.
mmap could be good because instead of making copies into file cache, your threads would be writing directly into file cache. 60 GB is probably too large to mmap the entire file, so each thread will likely need its own mmap window onto the file which it can move around.
In Windows you would probably want to try using overlapped, asynchronous IO. That can only be done with Win32 API calls.
|
2,532,008 |
I'm sure this has been asked before, but I can't seem to find it (or know the proper wording to search for)
Basically I want a regex that matches all non-alphanumeric except hyphens. So basically match \W+ except exclude '-' I'm not sure how to exclude specific ones from a premade set.
|
2010/03/28
|
[
"https://Stackoverflow.com/questions/2532008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23822/"
] |
`\W` is a shorthand for `[^\w]`. So:
```
[^\w-]+
```
A bit of background:
* `[…]` defines a set
* `[^…]` negates a set
* Generally, every `\v` (smallcase) set is negated by a `\V` (uppercase) where V is any letter that defines a set.
* for international characters, you may want to look into `[[:alpha:]]` and `[[:alnum:]]`
|
51,114,273 |
I started coding around last month and am using Atom Text Editor. I can't seem to link my CSS code to my HTML
here's a screenshot
[](https://i.stack.imgur.com/VHUup.png)
The CSS file is in the same folder as the HTML file and I've put in the exact name in the href part.
Here's my CSS.
[](https://i.stack.imgur.com/MPlxQ.png)
```
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
```
|
2018/06/30
|
[
"https://Stackoverflow.com/questions/51114273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014388/"
] |
Try this
`<link rel="stylesheet" type="text/css" href="./index.css">`
|
331,235 |
I can pair my bluetooth headset with my laptop once. But when I disconnect my headset, I cannot reconnect it again. The only way it works is to restart the bluetooth daemon:
```
service bluetooth restart
```
When I do that, I see following in my log:
```
bluetoothd: Terminating
bluetoothd: Stopping hci0 event socket
bluetoothd: Stopping SDP server
bluetoothd: Exit
bluetoothd: Bluetooth daemon 4.99
bluetoothd: Starting SDP server
bluetoothd: Excluding (conf) network
bluetoothd: Excluding (conf) gatt_example
bluetoothd: Excluding (conf) time
bluetoothd: Excluding (conf) alert
bluetoothd: Failed to open RFKILL control device
bluetoothd: Listening for HCI events on hci0
bluetoothd: HCI dev 0 up
bluetoothd: Proximity GATT Reporter Driver: Operation not permitted (1)
bluetoothd: Could not get the contents of DMI chassis type
bluetoothd: Unable to load keys to adapter_ops: Function not implemented (38)
bluetoothd: Adapter /org/bluez/8237/hci0 has been enabled
```
then I can successfully connect my headphones:
```
bluetoothd: Can't open input device: No such file or directory (2)
bluetoothd: AVRCP: failed to init uinput for 44:66:a7:81:3C:84
bluetoothd: Badly formated or unrecognized command: AT+XEVENT=Bose SoundLink,158
bluetoothd: Badly formated or unrecognized command: AT+BIA=0,0,0,1,1,1,0
```
But when I disconnect them and try connecting again, it does not work, and I see nothing in the logs.
**Why can't I reconnect my headphones after disconnecting?
Why do I have to restart bluetooth daemon?
How can I fix this ?**
I am using `bluez 4.99` on Debian.
I am using custom kernel 4.4.
I am using alsa (no pulseaudio).
|
2016/12/18
|
[
"https://unix.stackexchange.com/questions/331235",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/43007/"
] |
It's buggy with certain brands of headsets. I suffer the same problems and this python script to reconnect my bluetooth headset works for me.
Make sure to have at least python 3.5 installed. Directions on how to use the script is self explanatory in the header:
<https://gist.github.com/pylover/d68be364adac5f946887b85e6ed6e7ae>
Edit: I've included the latest code for this script in this answer as a request but I'd recommend getting the latest iteration from the link provided, as the author is always updating the script.
```
#! /usr/bin/env python3.5
"""
Fixing bluetooth stereo headphone/headset problem in ubuntu 16.04 and also debian jessie, with bluez5.
Workaround for bug: https://bugs.launchpad.net/ubuntu/+source/indicator-sound/+bug/1577197
Run it with python3.5 or higher after pairing/connecting the bluetooth stereo headphone.
This will be only fixes the bluez5 problem mentioned above .
Licence: Freeware
See ``python3.5 a2dp.py -h``.
Shorthands:
$ alias speakers="a2dp.py 10:08:C1:44:AE:BC"
$ alias headphones="a2dp.py 00:22:37:3D:DA:50"
$ alias headset="a2dp.py 00:22:37:F8:A0:77 -p hsp"
$ speakers
Check here for the latest updates: https://gist.github.com/pylover/d68be364adac5f946887b85e6ed6e7ae
Thanks to:
* https://github.com/DominicWatson, for adding the ``-p/--profile`` argument.
* https://github.com/IzzySoft, for mentioning wait before connecting again.
* https://github.com/AmploDev, for v0.4.0
* https://github.com/Mihara, for autodetect & autorun service
* https://github.com/dabrovnijk, for systemd service
Change Log
----------
- 0.5.0
* Autodetect & autorun service
- 0.4.1
* Sorting device list
- 0.4.0
* Adding ignore_fail argument by @AmploDev.
* Sending all available streams into selected sink, after successfull connection by @AmploDev.
- 0.3.3
* Updating default sink before turning to ``off`` profile.
- 0.3.2
* Waiting a bit: ``-w/--wait`` before connecting again.
- 0.3.0
* Adding -p / --profile option for using the same script to switch between headset and A2DP audio profiles
- 0.2.5
* Mentioning [mac] argument.
- 0.2.4
* Removing duplicated devices in select device list.
- 0.2.3
* Matching ANSI escape characters. Tested on 16.10 & 16.04
- 0.2.2
* Some sort of code enhancements.
- 0.2.0
* Adding `-V/--version`, `-w/--wait` and `-t/--tries` CLI arguments.
- 0.1.1
* Supporting the `[NEW]` prefix for devices & controllers as advised by @wdullaer
* Drying the code.
"""
import sys
import re
import asyncio
import subprocess as sb
import argparse
__version__ = '0.4.0'
HEX_DIGIT_PATTERN = '[0-9A-F]'
HEX_BYTE_PATTERN = '%s{2}' % HEX_DIGIT_PATTERN
MAC_ADDRESS_PATTERN = ':'.join((HEX_BYTE_PATTERN, ) * 6)
DEVICE_PATTERN = re.compile('^(?:.*\s)?Device\s(?P<mac>%s)\s(?P<name>.*)' % MAC_ADDRESS_PATTERN)
CONTROLLER_PATTERN = re.compile('^(?:.*\s)?Controller\s(?P<mac>%s)\s(?P<name>.*)' % MAC_ADDRESS_PATTERN)
WAIT_TIME = .75
TRIES = 4
PROFILE = 'a2dp'
_profiles = {
'a2dp': 'a2dp_sink',
'hsp': 'headset_head_unit',
'off': 'off'
}
# CLI Arguments
parser = argparse.ArgumentParser(prog=sys.argv[0])
parser.add_argument('-e', '--echo', action='store_true', default=False,
help='If given, the subprocess stdout will be also printed on stdout.')
parser.add_argument('-w', '--wait', default=WAIT_TIME, type=float,
help='The seconds to wait for subprocess output, default is: %s' % WAIT_TIME)
parser.add_argument('-t', '--tries', default=TRIES, type=int,
help='The number of tries if subprocess is failed. default is: %s' % TRIES)
parser.add_argument('-p', '--profile', default=PROFILE,
help='The profile to switch to. available options are: hsp, a2dp. default is: %s' % PROFILE)
parser.add_argument('-V', '--version', action='store_true', help='Show the version.')
parser.add_argument('mac', nargs='?', default=None)
# Exceptions
class SubprocessError(Exception):
pass
class RetryExceededError(Exception):
pass
class BluetoothctlProtocol(asyncio.SubprocessProtocol):
def __init__(self, exit_future, echo=True):
self.exit_future = exit_future
self.transport = None
self.output = None
self.echo = echo
def listen_output(self):
self.output = ''
def not_listen_output(self):
self.output = None
def pipe_data_received(self, fd, raw):
d = raw.decode()
if self.echo:
print(d, end='')
if self.output is not None:
self.output += d
def process_exited(self):
self.exit_future.set_result(True)
def connection_made(self, transport):
self.transport = transport
print('Connection MADE')
async def send_command(self, c):
stdin_transport = self.transport.get_pipe_transport(0)
# noinspection PyProtectedMember
stdin_transport._pipe.write(('%s\n' % c).encode())
async def search_in_output(self, expression, fail_expression=None):
if self.output is None:
return None
for l in self.output.splitlines():
if fail_expression and re.search(fail_expression, l, re.IGNORECASE):
raise SubprocessError('Expression "%s" failed with fail pattern: "%s"' % (l, fail_expression))
if re.search(expression, l, re.IGNORECASE):
return True
async def send_and_wait(self, cmd, wait_expression, fail_expression='fail'):
try:
self.listen_output()
await self.send_command(cmd)
while not await self.search_in_output(wait_expression.lower(), fail_expression=fail_expression):
await wait()
finally:
self.not_listen_output()
async def disconnect(self, mac):
print('Disconnecting the device.')
await self.send_and_wait('disconnect %s' % ':'.join(mac), 'Successful disconnected')
async def connect(self, mac):
print('Connecting again.')
await self.send_and_wait('connect %s' % ':'.join(mac), 'Connection successful')
async def trust(self, mac):
await self.send_and_wait('trust %s' % ':'.join(mac), 'trust succeeded')
async def quit(self):
await self.send_command('quit')
async def get_list(self, command, pattern):
result = set()
try:
self.listen_output()
await self.send_command(command)
await wait()
for l in self.output.splitlines():
m = pattern.match(l)
if m:
result.add(m.groups())
return sorted(list(result), key=lambda i: i[1])
finally:
self.not_listen_output()
async def list_devices(self):
return await self.get_list('devices', DEVICE_PATTERN)
async def list_paired_devices(self):
return await self.get_list('paired-devices', DEVICE_PATTERN)
async def list_controllers(self):
return await self.get_list('list', CONTROLLER_PATTERN)
async def select_paired_device(self):
print('Selecting device:')
devices = await self.list_paired_devices()
count = len(devices)
if count < 1:
raise SubprocessError('There is no connected device.')
elif count == 1:
return devices[0]
for i, d in enumerate(devices):
print('%d. %s %s' % (i+1, d[0], d[1]))
print('Select device[1]:')
selected = input()
return devices[0 if not selected.strip() else (int(selected) - 1)]
async def wait():
return await asyncio.sleep(WAIT_TIME)
async def execute_command(cmd, ignore_fail=False):
p = await asyncio.create_subprocess_shell(cmd, stdout=sb.PIPE, stderr=sb.PIPE)
stdout, stderr = await p.communicate()
stdout, stderr = \
stdout.decode() if stdout is not None else '', \
stderr.decode() if stderr is not None else ''
if p.returncode != 0 or stderr.strip() != '':
message = 'Command: %s failed with status: %s\nstderr: %s' % (cmd, p.returncode, stderr)
if ignore_fail:
print('Ignoring: %s' % message)
else:
raise SubprocessError(message)
return stdout
async def execute_find(cmd, pattern, tries=0, fail_safe=False):
tries = tries or TRIES
message = 'Cannot find `%s` using `%s`.' % (pattern, cmd)
retry_message = message + ' Retrying %d more times'
while True:
stdout = await execute_command(cmd)
match = re.search(pattern, stdout)
if match:
return match.group()
elif tries > 0:
await wait()
print(retry_message % tries)
tries -= 1
continue
if fail_safe:
return None
raise RetryExceededError('Retry times exceeded: %s' % message)
async def find_dev_id(mac, **kw):
return await execute_find('pactl list cards short', 'bluez_card.%s' % '_'.join(mac), **kw)
async def find_sink(mac, **kw):
return await execute_find('pacmd list-sinks', 'bluez_sink.%s' % '_'.join(mac), **kw)
async def set_profile(device_id, profile):
print('Setting the %s profile' % profile)
try:
return await execute_command('pactl set-card-profile %s %s' % (device_id, _profiles[profile]))
except KeyError:
print('Invalid profile: %s, please select one one of a2dp or hsp.' % profile, file=sys.stderr)
raise SystemExit(1)
async def set_default_sink(sink):
print('Updating default sink to %s' % sink)
return await execute_command('pacmd set-default-sink %s' % sink)
async def move_streams_to_sink(sink):
streams = await execute_command('pacmd list-sink-inputs | grep "index:"', True)
for i in streams.split():
i = ''.join(n for n in i if n.isdigit())
if i != '':
print('Moving stream %s to sink' % i)
await execute_command('pacmd move-sink-input %s %s' % (i, sink))
return sink
async def main(args):
global WAIT_TIME, TRIES
if args.version:
print(__version__)
return 0
mac = args.mac
# Hacking, Changing the constants!
WAIT_TIME = args.wait
TRIES = args.tries
exit_future = asyncio.Future()
transport, protocol = await asyncio.get_event_loop().subprocess_exec(
lambda: BluetoothctlProtocol(exit_future, echo=args.echo), 'bluetoothctl'
)
try:
if mac is None:
mac, _ = await protocol.select_paired_device()
mac = mac.split(':' if ':' in mac else '_')
print('Device MAC: %s' % ':'.join(mac))
device_id = await find_dev_id(mac, fail_safe=True)
if device_id is None:
print('It seems device: %s is not connected yet, trying to connect.' % ':'.join(mac))
await protocol.trust(mac)
await protocol.connect(mac)
device_id = await find_dev_id(mac)
sink = await find_sink(mac, fail_safe=True)
if sink is None:
await set_profile(device_id, args.profile)
sink = await find_sink(mac)
print('Device ID: %s' % device_id)
print('Sink: %s' % sink)
await set_default_sink(sink)
await wait()
await set_profile(device_id, 'off')
if args.profile is 'a2dp':
await protocol.disconnect(mac)
await wait()
await protocol.connect(mac)
device_id = await find_dev_id(mac)
print('Device ID: %s' % device_id)
await set_profile(device_id, args.profile)
await set_default_sink(sink)
await move_streams_to_sink(sink)
except (SubprocessError, RetryExceededError) as ex:
print(str(ex), file=sys.stderr)
return 1
finally:
print('Exiting bluetoothctl')
await protocol.quit()
await exit_future
# Close the stdout pipe
transport.close()
if args.profile == 'a2dp':
print('"Enjoy" the HiFi stereo music :)')
else:
print('"Enjoy" your headset audio :)')
if __name__ == '__main__':
sys.exit(asyncio.get_event_loop().run_until_complete(main(parser.parse_args())))
```
|
297,466 |
I am creating my CV in LaTeX with classicthesis-styled CV. Instead of adding publications individually, I would like to add a bibliography file. I tried it with the following code, but couldn't get it working.
**MWE**
```
\documentclass{scrartcl}
\reversemarginpar % Move the margin to the left of the page
\newcommand{\MarginText}[1]{\marginpar{\raggedleft\itshape\small#1}} % New command defining the margin text style
\usepackage[nochapters]{classicthesis} % Use the classicthesis style for the style of the document
\usepackage[LabelsAligned]{currvita} % Use the currvita style for the layout of the document
\renewcommand{\cvheadingfont}{\LARGE\color{Maroon}} % Font color of your name at the top
\usepackage{hyperref} % Required for adding links and customizing them
\hypersetup{colorlinks, breaklinks, urlcolor=Maroon, linkcolor=Maroon} % Set link colors
\newlength{\datebox}\settowidth{\datebox}{Spring 2011} % Set the width of the date box in each block
\newcommand{\NewEntry}[3]{\noindent\hangindent=2em\hangafter=0 \parbox{\datebox}{\small \textit{#1}}\hspace{1.5em} #2 #3 % Define a command for each new block - change spacing and font sizes here: #1 is the left margin, #2 is the italic date field and #3 is the position/employer/location field
\vspace{0.5em}} % Add some white space after each new entry
\newcommand{\Description}[1]{\hangindent=2em\hangafter=0\noindent\raggedright\footnotesize{#1}\par\normalsize\vspace{1em}} % Define a command for descriptions of each entry - change spacing and font sizes here
\addbibresource{bibliography.bib}
%----------------------------------------------------------------------------------------
\begin{document}
\thispagestyle{empty} % Stop the page count at the bottom of the first page
%----------------------------------------------------------------------------------------
% NAME AND CONTACT INFORMATION SECTION
%----------------------------------------------------------------------------------------
\begin{cv}
%----------------------------------------------------------------------------------------
% WORK EXPERIENCE
%----------------------------------------------------------------------------------------
\noindent\spacedlowsmallcaps{Publications}\vspace{1em}
% \section{publications}
\printbibsection{article}{article in peer-reviewed journal} % Print all articles from the bibliography
\printbibsection{book}{books} % Print all books from the bibliography
\begin{refsection} % This is a custom heading for those references marked as "inproceedings" but not containing "keyword=france"
\nocite{*}
\printbibliography[sorting=chronological, type=inproceedings, title={international peer-reviewed conferences/proceedings}, notkeyword={france}, heading=bibheading]
\end{refsection}
\begin{refsection} % This is a custom heading for those references marked as "inproceedings" and containing "keyword=france"
\nocite{*}
\printbibliography[sorting=chronological, type=inproceedings, title={local peer-reviewed conferences/proceedings}, keyword={france}, heading=bibheading]
\end{refsection}
\printbibsection{misc}{other publications} % Print all miscellaneous entries from the bibliography
\printbibsection{report}{research reports} % Print all research reports from the bibliography
\end{cv}
\end{document}
```
How to add bibliography file to classicthesis-styled CV?
|
2016/03/05
|
[
"https://tex.stackexchange.com/questions/297466",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/72911/"
] |
You neglected to load `biblatex` in your MWE.
Furthermore, `\printbibsection` is not a standard `biblatex` command, it is defined in the `friggeri-cv` as
```
\newcommand{\printbibsection}[2]{
\begin{refsection}
\nocite{*}
\printbibliography[sorting=chronological, type={#1}, title={#2}, heading=subbibliography]
\end{refsection}
}
```
But normally you wouldn't need `\printbibsection` and all the `refsections`, you could just go with
```
\documentclass{scrartcl}
\usepackage[sorting=ydnt, tyle=authortitle, backend=biber]{biblatex}
\addbibresource{biblatex-examples.bib}
\nocite{*}
\begin{document}
\printbibliography[type=article, title={Articles}]
\printbibliography[type=book, title={Books}]
\printbibliography[nottype=article,nottype=book, title={Others}]
\end{document}
```
|
88,100 |
I have data set which I would like to fit to the function
$\quad \quad f(r) = A\cos(kr - \pi/4 + \phi\_1)\times\exp(i(-2\log(r) + \phi\_2))$,
where $k$ is a constant I know and $(A,\phi\_1,\phi\_2)$ are the fitting parameters. In fact, if I split my data set into real and imaginary parts and fit these separately to the function above, using a command like
```
solRe = FindFit[ReU, A*Cos[k*x - π/4 + B] Cos[-2 Log[x] + C], {A, B, C}, x]
solIm = FindFit[ImU, A*Cos[k*x - π/4 + B] Sin[-2 Log[x] + C], {A, B, C}, x],
```
everything works well. I get the same value for `B` for the two fits, which is encouraging. However, the values for `A` and `C` are different. Therefore I would like to fit to the complex ansatz. I tried doing this with
```
soltot = FindFit[U, A*Cos[k*x - π/4 + B] Exp[I (-2 Log[x] + C)], {A, B, C}, x]
```
but I get errors. Does anyone have an idea how I could do such a fit?
|
2015/07/13
|
[
"https://mathematica.stackexchange.com/questions/88100",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10713/"
] |
If all you want is a least-squares fit, the easiest way to do might just be to construct a function that is the sum of the squares of the residuals, and then feed it into `FindMinimum`. As a example, let's construct a data set of complex variables as a function of a real variable `x`:
```
data = Table[{x, (0.719) x^(0.907 I) + RandomComplex[{-0.005 (1 + I), 0.005 (1 + I)}]}, {x, 0.1, 1, 0.1}]
{{0.1, -0.352264 - 0.622697 I}, {0.2, 0.0750264 - 0.712474 I},
{0.3, 0.334793 - 0.642127 I}, {0.4, 0.479876 - 0.534359 I},
{0.5, 0.586353 - 0.422211 I}, {0.6, 0.647432 - 0.32101 I},
{0.7, 0.679054 - 0.23206 I}, {0.8, 0.70489 - 0.140092 I},
{0.9, 0.71389 - 0.0680025 I}, {1., 0.719136 - 0.00133755 I}}
```
Let's try to extract the values of `a` and `b` from the data. We can construct a function that gives us the square of the magnitude of the difference between the data points and the model, as a function of `a` and `b` for our model $f(x) = a x^{i b}$:
```
sqres[a_, b_] := Norm[Transpose[data][[2]] - (a x^(b I) /. x -> Transpose[data][[1]])]^2
```
Note that if the data fits the model perfectly, `sqres` should have an exact minimum of 0 at $a = 0.719$ and $b = 0.907$. However, since we threw random complex noise into the data, the minimum of `sqres` will not be zero, and may be somewhere other than the nominal values of `a` and `b`. Still, it gets pretty close:
```
FindMinimum[sqres[a, b], {a, b}]
{0.000190037, {a -> 0.719187, b -> 0.907388}}
```
As usual with non-linear fits, you might have to provide initial "guesses" for the values of `a` and `b` before Mathematica can find a useful minimum of the `sqres` function.
|
553,404 |
I use [Lucene.net](http://incubator.apache.org/lucene.net/) for indexing content & documents etc.. on websites. The index is very simple and has this format:
```
LuceneId - unique id for Lucene (TypeId + ItemId)
TypeId - the type of text (eg. page content, product, public doc etc..)
ItemId - the web page id, document id etc..
Text - the text indexed
Title - web page title, document name etc.. to display with the search results
```
I've got these options to adapt it to serve multi-lingual content:
1. Create a separate index for each language. E.g. Lucene-enGB, Lucene-frFR etc..
2. Keep the one index and add an additional 'language' field to it to filter the results.
Which is the best option - or is there another? I've not used multiple indexes before so I'm leaning toward the second.
|
2009/02/16
|
[
"https://Stackoverflow.com/questions/553404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] |
I do [2], but one problem I have is that I cannot use different analyzers depending on the language. I've combined the stopwords of the languages I want, but I lose the capability of more advanced stuff that the analyzer will offer such as stemming etc.
|
359,448 |
I need to place a Wifi surveillance camera near the entrance of my house where no power outlet is in that area.
I pulled a wire wrapping wire (awg 30) to the target location without thinking about wire resistance. And as you all expected, it didn't able to power the webcam.
The power the camera uses is 5V @ 1A.
I measured the wire resistance of my awg 30 wire to the location is 11 ohms (to and from) which is 6 ohms one way which is around 50 ft.
So my question is what is the minimum gauge I need to use to be able to power my webcam placed 50ft away from the USB power adapter?
Or how many awg30 wires I need to pull to lower the resistance to allow enough power to pass through?
I assume the common practice is that the voltage drop is less than 5% of the required voltage.
So 5% of 5V is 0.25V
R=V/I so to allow 1A to pass through the resistance should be 0.25V/1A = 0.25ohms.
From the chart:
<https://www.cirris.com/learning-center/calculators/133-wire-resistance-calculator-table>?
Therefore I need a minimum of one 14 Gauge wire (or a bundle of fifty awg 30 wires LOL) to power the webcam 50ft way?
|
2018/03/03
|
[
"https://electronics.stackexchange.com/questions/359448",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/179935/"
] |
The short answer is that I'd argue that a spacing change near the start or end point of a differential signal is not that bad. I'd also argue that 6 layers is not that many. But at high speeds, definitely keep all noise sources away from the clock.
For the longer answer, let's look at the reasons given. The Toradex source you cite mentioned an impedance discontinuity, and EMC compliance.
The impedance discontinuity comes from the fact that, if there is a via between traces, the traces are at first have a capacitive coupling with each other, then that coupling is removed and replaced with the via, then they couple together again. Any impedance change will cause a reflection (see [Impedance Mismatch](https://en.wikipedia.org/wiki/Impedance_matching)). The ratio of reflection is:
$$
\Gamma=\frac{Z\_1-Z\_2}{Z\_1+Z\_2}
$$
Where Z is the impedance change. Note that the real impedance is different for different frequencies. So, we get signals reflecting back to the driver, potentially damaging the driver by forcing an over or under voltage condition (not very likely, particularly not with an FPGA's LVDS, which was relatively rugged when I used it, but reliability is important), and then it can reflect back again from the impedance change at the driver, and hit the receiver. Worst case, it destructively interferes with an edge and makes it non-monotonic.
What needs to happen for this worst case scenario? I believe the rule of thumb is that you are in trouble if the reflection distance is over 1/6 the fundamental wavelength. So, if your edge rate (not switching frequency, but the rise time of your edges) is 1 ns, we know electricity travels about 6 inches per ns in copper, so if the reflection distance is over 1 inch, you are on thin ice, and should look at how much the impedance is changing. Similarly, if the via is near the receiving side of the signal, I would argue that the impedance mismatch is going to get lost in the impedance mismatch inherent in reaching the receiver.
The second issue Toradex points to is EMC compliance, which is a bit of a fuzzy term. They could be worried about coupling or trace length mismatch. I don't think coupling is necessarily an issue; these are differential lines so the net coupling should cancel out, unless you are really pushing your voltage margins. Trace length mismatch could be more common if there is an obstruction in your traces, but it is not a necessary outcome.
To go a bit more into coupling, in the ideal case, if you couple the same signal into a differential pair, you would prefer to couple into both. Doing that would bump them both by a few mV, and the differential signal (Vp - Vn) would be unaffected. As long as the absolute voltages of each signal are within spec, you should be fine. At very high speeds you may run into an issue where the signal couples into one line slightly before it would couple into the other. This would be an issue, but I'd argue even here having the noise couple into both lines is better than having it couple into one, because either the noise is reduced by the differential nature, or you have two problems instead of one.
If you are dealing with something very high speed, with edge rates under 1 ns, then you should be explaining the answer to me, and you should probably use a board with more than 4 layers. If you're just trying to drive an 80 MSPS ADC, this advice should be solid. Keep in mind that edge sensitive lines, like clocks, are by far the most important signals to treat correctly.
One final tip: If the going gets tough, look into microvias which may be placed in the BGA pads.
|
6,303,163 |
I've built an interface formed by a ListView and a panel with a few textboxes. In order to make change the context in those textboxes when another ListViewItem is selected, I've captured the SelectionChange event, to change accordingly DataContexts of the textboxes. Something like this:
```
void customersList_SelectItem(object sender, SelectionChangedEventArgs e)
{
Customer customer = (Customer)customersList.Selected;
if (customer != null)
{
addressField.DataContext = customer;
phoneField.DataContext = customer;
mobileField.DataContext = customer;
webField.DataContext = customer;
emailField.DataContext = customer;
faxField.DataContext = customer;
...
}
}
```
Now, I wonder, is this the best the way to do it? Looks like a bit forced, but I can't devise any better.
|
2011/06/10
|
[
"https://Stackoverflow.com/questions/6303163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/667175/"
] |
If the textboxes were all contained in a containing element (e.g. a Grid), then you could just set the DataContext of the Grid element instead. This would be cleaner.
Even better yet would be to use XAML binding and [MVVM](http://www.wintellect.com/cs/blogs/jlikness/archive/2010/04/14/model-view-viewmodel-mvvm-explained.aspx), and this code could be implemented declaratively in XAML.
|
2,749,785 |
Let $\mathcal{B}$ be an orthonormal basis for a finite dimensional complex vector space $V$. Let $U$ be an operator on that space. Show that $U$ is a unitary operator if and only if $[U]\_{\mathcal{B}}$ is a unitary matrix.
I'm stuck on how to even approach this problem.
|
2018/04/23
|
[
"https://math.stackexchange.com/questions/2749785",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/157069/"
] |
There are a couple of things going on here. You have some abstract $\mathbb{C}$-vector space, equipped with an inner product $(-, -)\_V: V \times V \to \mathbb{C}$, which I will consider to be conjugate-linear in the first argument, and $\mathbb{C}$-linear in the second: $(\lambda v, \mu w)\_V = \overline{\lambda} \mu (v, w)\_V$. A *unitary operator* $U: V \to V$ is one which preserves the inner product, in that $(Uv, Uw)\_V = (v, w)\_V$ for all $u, w \in V$. Note that it makes no sense to define the conjugate-transpose of $U$, since it is not a matrix: let's forget about $V$ and $U$ for the moment.
There is another well-known inner product space, which is $\mathbb{C}^n$, the space of length-$n$ column vectors over $\mathbb{C}$, with inner product given by $(x, y)\_{\mathbb{C}^n} := x^\* y$, where $x^\*$ is the conjugate-transpose of $x$. The nice thing about $\mathbb{C}^n$ is that it comes with a distinguished basis, so that every linear transformation $\mathbb{C}^n \to \mathbb{C}^n$ is exactly some $n \times n$ complex matrix. In $\mathbb{C}^n$, we have the same notion of a unitary map $T: \mathbb{C}^n \to \mathbb{C}^n$ (it must satisfy $(Tx, Ty)\_{\mathbb{C}^n} = (x, y)\_{\mathbb{C}^n}$ for all $x, y \in \mathbb{C}^n$), but we may now characterise such matrices:
**Show:** $T \in \operatorname{Mat}\_n(\mathbb{C})$ is unitary if and only if $T T^\* = I$, where $T^\*$ is the conjugate-transpose of the matrix $T$.
It will also be handy to have the following facts:
1. (Definition) An *isomorphism of inner product spaces* $S: V \to W$ is a linear map such that $(Sv\_1, S v\_2)\_U = (v\_1, v\_2)\_V$ for all $v\_1, v\_2 \in V$.
2. (Prove:) If $S$ is an isomorphism of inner product spaces, so is $S^{-1}$.
3. Note that a unitary operator on $V$ is an isomorphism of inner product spaces $V \to V$.
Returning to the original inner product space $V$, a choice of basis $\mathcal{B} = (b\_1, \ldots, b\_n)$ on $V$ amounts to a linear isomorphism $B: \mathbb{C}^n \to V$ (where $n = \dim V$), given by $B e\_i = b\_i$, where by $e\_i$ I mean the column vector in $\mathbb{C}^n$ having a $1$ in the $i$th position and zeros elsewhere.
**Show:** If the basis $\mathcal{B}$ is orthonormal, then $B$ is an isomorphism of inner product spaces.
After all the pieces are in place, the result is easy: the matrix of the operator $U: V \to V$ in the basis $\mathcal{B}$ is $B^{-1} U B \in \operatorname{Mat}\_n(\mathbb{C})$, and all we have to do is verify that this is a unitary operator: for any $x, y \in \mathbb{C}^n$, we have
$$ (B^{-1}UBx, B^{-1}UBy)\_V = (UBx, UBy)\_{\mathbb{C}^n} = (Bx, By)\_V = (x, y)\_{\mathbb{C}^n}$$
where the equalities follow from repeatedly applying the facts that $B$, $U$, and $B^{-1}$ are isomorphisms of inner product spaces. Now the result follows from the characterisation of unitary matrices.
|
66,233,085 |
I have a dataframe values like this:
```
name foreign_name acronym alias
United States États-Unis USA USA
```
I want to merge all those four columns in a row into one single columns 'names', so I do:
```
merge = lambda x: '|'.join([a for a in x.unique() if a])
df['names'] = df[['name', 'foreign_name', 'acronym', 'alias',]].apply(merge, axis=1)
```
The problem with this code is that, it doesn't remove the duplicate 'USA', instead it gets:
```
names = 'United States|États-Unis|USA|USA'
```
Where am I wrong?
|
2021/02/16
|
[
"https://Stackoverflow.com/questions/66233085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3943868/"
] |
MCVE:
```
import pandas as pd
import numpy as np
d= {'name': {0: 'United States'},
'foreign_name': {0: 'États-Unis'},
'acronym': {0: 'USA'},
'alias': {0: 'USA'}}
df = pd.DataFrame(d)
merge = lambda x: '|'.join([a for a in x.unique() if a])
df['names'] = df[['name', 'foreign_name', 'acronym', 'alias',]].apply(merge, axis=1)
print(df)
```
Output:
```
name foreign_name acronym alias names
0 United States États-Unis USA USA United States|États-Unis|USA
```
|
5,479,106 |
OK, so I thought I was solving a problem and I created an even bigger one. I was trying to get rid of a lingering reference to `MySql` and deleted a bunch of files from the Temporary ASP.NET files directory. Now, when I try to run the ASP.NET configuration tool I get this, reprinted in its full glory:
>
> System.InvalidCastException: [A]System.Web.Administration.WebAdminRemotingManager cannot be cast to [B]System.Web.Administration.WebAdminRemotingManager. Type A originates from 'App\_Code.eyfytrpm, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\asp.netwebadminfiles\1f61ecce\354a2473\App\_Code.eyfytrpm.dll'. Type B originates from 'App\_Code.y-perhho, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\asp.netwebadminfiles\1f61ecce\354a2473\App\_Code.y-perhho.dll'. at System.Web.Administration.WebAdminPage.get\_RemotingManager() at System.Web.Administration.WebAdminPage.SaveConfig(Configuration config) at System.Web.Administration.WebAdminPage.VerifyAppValid()
>
>
>
Apparently those temporary files weren't as temporary as I thought they were. Is there any way to regenerate those files, or any other way to work around this.
I really shot myself in the foot this time.. :(
|
2011/03/29
|
[
"https://Stackoverflow.com/questions/5479106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83678/"
] |
To answer my own question...
I wound up changing the Apache file /etc/apache/sites-available/default from AllowOverRide = None to AllowOverRide = All.
|
54,695,113 |
I'm trying to create a filter based that is triggered by checkboxes, which shows and hides options from a list. I have tried to use resources online to put the script together but nothing seems to work.
In order to hide or show list items
I am editing a - class= "marker" parent element
based on wether - class= "condtx" of its child element
is matching the array of checked boxes "value" or not.
I have included comments on how I am proceeding.
Can anyone point me in the right direction please?
```js
function filterCondtn1() {
var i, z;
//"chekedVal" array Keeps returning "undefined" I have no idea why
var chekedVal = document.getElementById("InputOpts").getElementsByTagName("input").checked.value;
//Gathered all <h3> tag options into array to be tested against "chekedVal" for match
var condt1 = document.getElementsByClassName("condtn1").innerHTML;
//Parrent class that will be edited to show <div> or not if True or false.
var parrentClss = document.getElementsByClassName("marker");
//From here it's a blur. I've trying everything I can. I think I should be something of that sort.
for {
(var i = 0; i < condt1.length; i++) &&
(var z = 0; z < parrentClss.length; z++)
RemoveClass(parrentClss[z], "show");
if (condt1[i].indexOf(chekedVal) > -1) AddClass(parrentClss[z], "show");
}
}
//Currently using these two functions in my script and they work
function RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}
function AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {
element.className += " " + arr2[i];
}
}
}
```
```css
.markerA {
display: none;
}
.show {
display: block;
}
```
```html
<div id="InputOpts">
<input type="checkbox" value="option 1" oninput="filterCondtn1();">Option 1
<input type="checkbox" value="option 2" oninput="filterCondtn1();">Option 2
<input type="checkbox" value="option 3" oninput="filterCondtn1();">Option 3
<input type="checkbox" value="option 4" oninput="filterCondtn1();">Option 4
</div>
<div class="marker">
<div class="necessary">
<h3 class="condtn1">Option 1</h3>
</div>
</div>
<div class="marker">
<div class="necessary">
<h3 class="condtn2">Option 3</h3>
</div>
</div>
<div class="marker">
<div class="necessary">
<h3 class="condtn1">Option 2</h3>
</div>
</div>
<div class="marker">
<div class="necessary">
<h3 class="condtn2">Option 4</h3>
</div>
</div>
```
|
2019/02/14
|
[
"https://Stackoverflow.com/questions/54695113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206451/"
] |
Due to the docs: <https://developers.google.com/recaptcha/docs/verify>
invalid-input-secret: **The secret parameter is invalid or malformed.**
Maybe you have mixed the site\_key and the secret\_key.
|
70,369,847 |
In the case of CPUs, the (linux specific) sys calls `getcpu()` or `sched_getcpu()` can be used inside a program to obtain the ID of the core executing them. For example, in the case of a 4 processors system, the logical index returned by the mentionned calls makes it possible to deduce which one of the 4 CPUs is being used (let's say every CPU contains 10 cores, therefore if `sched_getcpu()` returns 20, that means the CPU #2 is being used since the core number 20 is in the 3rd CPU).
How can I achieve a similar thing in the case of GPUs? Is there a way to find which one is being used in real time from inside an application?
|
2021/12/15
|
[
"https://Stackoverflow.com/questions/70369847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9653244/"
] |
Ignoring all of the irrelevant code in the question, the problem is this:
```
class base {};
class derived : base {};
base *ptr = new derived;
```
`derived` inherits **privately** from `base`, so, as the error message says, converting that `derived*` created by `new derived` to a `base*` is not legal. The fix is simply to publicly inherit:
```
class derived : public base {};
```
|
17,358,226 |
I want to fix width of gridview. I am filling gridview as following;
```
sorgu = "select urun.urunId as \"İş No\",urun.modelNo as \"Model No\",modelAd as \"Model Adı\",bedenAd as \"Beden\", adet as \"Adet\""
+ ",aciklama as \"Açıklama\", kesmeTalimat as \"Kesim Talimatı\", atolyeTalimat as \"Atölye Talimatı\", yikamaTalimat as \"Yıkama Talimatı\", utuTalimat as \"Ütü Talimatı\", (k4.ad+' '+k4.soyad) as \"Kesim\", (k1.ad+' '+k1.soyad) as \"Atölye\""
+ ",(k2.ad+' '+k2.soyad) as \"Yıkama\",(k3.ad+' '+k3.soyad) as \"Ütü\", (k5.ad+' '+k5.soyad) as \"Kontrol\" from kullanici k1,kullanici k4,kullanici k5,kullanici k2,kullanici k3,model,beden,urun,fason,isTalimat,durum"
+ " where urun.urunId= fason.urunId and urun.urunId=isTalimat.urunId and urun.urunId=durum.urunId and model.modelNo=urun.modelNo and beden.bedenNo=urun.bedenNo and"
+ " fason.atolye=k1.id and fason.yikama=k2.id and fason.kesimci=k4.id and fason.kontrol=k5.id and fason.utu=k3.id";
connection.Open();
command.Connection = connection;
command.CommandText = sorgu;
dr = command.ExecuteReader();
DataTable dtTumISler = new DataTable();
dtTumISler.Load(dr);
dgvTumIsler.DataSource = dtTumISler;
dgvTumIsler.DataBind();
dr.Close();
connection.Close();
dtTumISler.Dispose();
```
Here dgvTumİsler is my gridview. I have tried the following code to make fixed length. But it does not work;
```
for (int i = 0; i < dgvTumIsler.Columns.Count; i++)
{
dgvTumIsler.Columns[i].ItemStyle.Width = 100;
}
```
Here dgvTumİsler.Columns.Count value is 1. So it does not work. Is there a way to solve this problem or is there another way to make a gridview fixed width.
HTML code:
```
<asp:GridView ID="dgvTumIsler" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" OnSelectedIndexChanged="dgvTumIsler_SelectedIndexChanged">
<Columns>
<asp:CommandField ButtonType="Button" SelectText="Seç" ShowCancelButton="False" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="false" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
```
|
2013/06/28
|
[
"https://Stackoverflow.com/questions/17358226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2511352/"
] |
Instead of using "change" event, the "key" event does fire on the source view.
Thanks for Kicker's hint
|
391,144 |
Why does macOS need to verify LibreOffice each time after a restart? I haven't updated the app in a while, and after the first verification it opens normally the next time. This is annoying and it takes a long time (about a minute). This should happen once, after installing (in the /Applications folder), not repeatedly. This doesn't happen for other apps.
[](https://i.stack.imgur.com/mLnnj.png)
**How can I make macOS stop verifying LO after a restart?**
NB: Saw the same happening to Firefox, but not Thunderbird and Evernote.
---
**Update**
I installed this app several months ago. And I mention that this happens after a restart. So I don't open the app from a DMG, which would be unmounted after a restart anyways.
|
2020/05/14
|
[
"https://apple.stackexchange.com/questions/391144",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/35070/"
] |
* <https://bugs.documentfoundation.org/show_bug.cgi?id=126409>
It is a bug filed on LibreOffice's tracker. So they're aware of it. Please do not flood the tracker with "me too" comments.
|
405,305 |
It is well known that an estimator's MSE can be decomposed into the sum of the variance and the squared bias. I'd like to actually perform this decomposition. Here is some code to set up and train a small model.
```
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.kernel_ridge import KernelRidge
x = np.linspace(0,10,1001).reshape(-1,1)
X = np.random.uniform(low = 0, high =10, size = 2000).reshape(-1,1)
y = 3*np.sin(X) + 2.5*np.random.normal(size = X.shape)
X_train, X_test, y_train, y_test = train_test_split(X,y,train_size = 0.6)
reg = KernelRidge(kernel='rbf', gamma = 1).fit(X,y)
mse = mean_squared_error(y_test, reg.predict(X_test))
print(mse)
```
How can I go about computing the squared bias and the variance for this estimator?
|
2019/04/26
|
[
"https://stats.stackexchange.com/questions/405305",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/111259/"
] |
The MSE and its components (squared bias and variance) are random variables. Therefore, in order to accurately access these statistics you need to iterate the process many times. For this purpose, we generally use bootstrapping.
The procedure for obtaining bias and variance terms is as follows:
1. Generate multiple training data sets by bootstrapping (e.g. K=200).
2. For each set, train your model. You will end up with K=200 models.
3. For each model, predict the targets for the out-of-bag samples (samples which did not appear in the training sets). Now, for each out-of-bag sample $(x\_i,y\_i)$ you can obtain K predictions (say $h^1, h^2,.....,h^k$).
4. Average these predictions to obtain $\bar{h}$
5. Then, the bias of your model (for a single sample) will be $(\bar{h}-y\_i)$
6. The variance will be $\sum\_{k} \frac{(y\_i^k-\bar{h})^2}{K-1}$
7. Do this for all out-of-bag samples and average bias and variance values for better estimates.
|
61,440,245 |
I am collecting data that looks like this:
```
# Data
df <- data.frame("Hospital" = c("Buge Hospital", "Buge Hospital", "Greta Hospital", "Greta Hospital",
"Makor Hospital", "Makor Hospital"),
"Period" = c("Jul-18","Aug-18", "Jul-19","Aug-19", "Jul-20","Aug-20"),
"Medical admissions" = c(12,56,0,40,5,56),
"Surgical admissions" = c(10,2,0,50,20,56),
"Inpatient admissions" = c(9,5,6,0,60,96))
df
```
Now I do want to get total entries per each month hence I need to calculate totals of each month variables in every year and create another column for totals.
I have tried but this is not working
```
df['totals'] = df [sum(2:5)]
```
How do I get sum totals of each row of every month in a year?
|
2020/04/26
|
[
"https://Stackoverflow.com/questions/61440245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11883900/"
] |
In Julia Base, there is a `methods` function which works as follows:
```
julia> methods(rand) # where rand is the the function name in question
# 68 methods for generic function "rand":
[1] rand(rd::Random.RandomDevice, sp::Union{Random.SamplerType{Bool}, Random.SamplerType{Int128}, Random.SamplerType{Int16}, Random.SamplerType{Int32}, Random.SamplerType{Int64}, Random.SamplerType{Int8}, Random.SamplerType{UInt128}, Random.SamplerType{UInt16}, Random.SamplerType{UInt32}, Random.SamplerType{UInt64}, Random.SamplerType{UInt8}}) in Random at /Users/sabae/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.3/Random/src/RNGs.jl:29
[2] rand(::Random._GLOBAL_RNG, x::Union{Random.SamplerType{Int128}, Random.SamplerType{Int64}, Random.SamplerType{UInt128}, Random.SamplerType{UInt64}}) in Random at /Users/sabae/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.3/Random/src/RNGs.jl:337
#...etc
```
This function allows us to see all of the functions matching the name we passed in.
It is also worth noting that the scope of this function can change depending on what packages you are using in the moment. See in the example below where I load in the POMDPs package and the number of available rand functions jumps significantly.
```
julia> using POMDPs
julia> methods(rand)
# 170 methods for generic function "rand":
[1] rand(rd::Random.RandomDevice, sp::Union{Random.SamplerType{Bool}, Random.SamplerType{Int128}, Random.SamplerType{Int16}, Random.SamplerType{Int32}, Random.SamplerType{Int64}, Random.SamplerType{Int8}, Random.SamplerType{UInt128}, Random.SamplerType{UInt16}, Random.SamplerType{UInt32}, Random.SamplerType{UInt64}, Random.SamplerType{UInt8}}) in Random at /Users/sabae/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.3/Random/src/RNGs.jl:29
#.. ETC.
```
[Read more about the `methods` function in the Julia Docs.](https://docs.julialang.org/en/v1/base/base/#Base.methods)
|
10,008,614 |
I've just moved a Joomla 1.7 site to a new server.
Administration back-end works fine. Configuration.php seems fine. Get "The requested document was not found on this server." for every page other than Home.
Must be talking to the database OK or I'd get an error. Could this be a problem with the PHP?
Thanks,
Andy
|
2012/04/04
|
[
"https://Stackoverflow.com/questions/10008614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559152/"
] |
* Did you clear joomla cache ?
* Disable page and/or module caching.
* Disable any plugin that optimizes "loading speed".
* Try removing SEF URLs (Joomla! and any 3rd party extension).
* If you are using a custom .htacess, then use an unmodified joomla one.
* Disable some system plugins.
* Disable modules in the homepage.
* Have you tried using another template (site) ?
|
150,327 |
A lot of universities are expecting not to be able to run in-person exams for at least part of the 2020/21 academic year. I believe, for example, that no UK universities is currently planning to hold in-person exams this coming January. I can see how other forms of assessment might be possible for some subjects. But I can't see how this can work for math.
>
> For those universities which will not run math exams in-person for this
> coming year, what are the plans for how to replace them?
>
>
>
|
2020/06/10
|
[
"https://academia.stackexchange.com/questions/150327",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/37765/"
] |
Here are some examples of how it is done at the University of Copenhagen for the two courses that I have exams in next week.
One course has a written exam: We are given a problem sheet that we write up a solution to and submit to an online portal after a time limit of four hours. We are allowed to use the internet and any other aids we wish, except that we are not allowed to communicate with other people.
Another course has a verbal exam: A verbal exam is performed using Zoom. There is no preparation time.
Both courses were intended to be verbal exams pre-covid-19.
|
15,470,937 |
I have been trying to populate an array using a for loop and taking such values using `document.getElementById("spin " + i).value;`
The `ids` on my html for every input tag go from spin1 to spin18.
Any suggestions on what I am doing wrong? Or what I can change?
```
var nums = [];
for(var i = 1; i <= 18; i++){
var num[i] = parseInt(document.getElementById("spin" + i).value);
nums.push(num[i]);
}
alert(nums.length);
```
|
2013/03/18
|
[
"https://Stackoverflow.com/questions/15470937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1890684/"
] |
What is the problem? You never mention what kind of results being generated or what the front-end html code looks like.
The js looks compilable, but here are some pointers.
**The number 0 is before 1**
----------------------------
It's a good habit to get in this mind set, plus it might save you from making stupid mistakes later on. Anyway, just to reinforce this, below is a number chart.
```
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
```
**Avoid unnecessary variables**
-------------------------------
Having a js compiler that optimizes redundant code is sadly new feature. But still, why have two lines to maintain when you can have one.
```
var nums = [];
for( var i = 0; i < 18; i++ ) {
nums[i] = parseInt( document.getElementById("spin" + i).value );
}
```
**Don't push, insert**
----------------------
The push method has an expensive overhead so use it with caution.
**Loggers**
-----------
The console has a built in logger, why not use that instead of an alert box?
```
console.log( nums.length );
```
|
127,679 |
How can I adjust the placement of `y unit` with `pgfplots`? I'm trying to put it near the top-left corner of the graph box. However, there *may* (but does not have to) be a scientific multiplier. As shown in the professionally type-set picture below, the unit should be displayed just after the multiplier and of course be lined up with it as if written as a whole: `$10^3$[m]`. In case values on `y` axis were smaller and exponential notation wasn't shown, the `[m]` unit should be still rendered above the top-left corner, but preferably closer to the left edge.

I'm aware of the fact that the `[m]` unit in the picture is drawn along with `y` axis label. I don't need to put the whole `y label` near the multiplier, but just the unit. In fact I don't need the axis label at all. Is it possible to control how the scientific multiplier is formatted and append a unit?
I'm not sure whether it's important, but for the sake of completeness, let me add that I have incorporated Jake's tick scaling solution from [here](https://tex.stackexchange.com/a/124268/10662) to have only exponents, which are a multiple of 3.
MWE provided:
```
\documentclass{minimal}
\usepackage{pgfplots}
\usepgfplotslibrary{units}
\makeatletter
\newif\ifpgfplots@scaled@x@ticks@engineering
\pgfplots@scaled@x@ticks@engineeringfalse
\newif\ifpgfplots@scaled@y@ticks@engineering
\pgfplots@scaled@y@ticks@engineeringfalse
\newif\ifpgfplots@scaled@z@ticks@engineering
\pgfplots@scaled@z@ticks@engineeringfalse
\pgfplotsset{
scaled x ticks/engineering/.code=
\pgfplots@scaled@x@ticks@engineeringtrue,
scaled y ticks/engineering/.code=
\pgfplots@scaled@y@ticks@engineeringtrue,
scaled z ticks/engineering/.code=
\pgfplots@scaled@y@ticks@engineeringtrue,
% scaled ticks=engineering % Uncomment this line if you want "engineering" to be on by default
}
\def\pgfplots@init@scaled@tick@for#1{%
\global\def\pgfplots@glob@TMPa{0}%
\expandafter\pgfplotslistcheckempty\csname pgfplots@prepared@tick@positions@major@#1\endcsname
\ifpgfplotslistempty
% we have no tick labels. Omit the tick scale label as well!
\else
\begingroup
\ifcase\csname pgfplots@scaled@ticks@#1@choice\endcsname\relax
% CASE 0 : scaled #1 ticks=false: do nothing here.
\or
% CASE 1 : scaled #1 ticks=true:
%--------------------------------
% the \pgfplots@xmin@unscaled@as@float is set just before the data
% scale transformation is initialised.
%
% The variables are empty if there is no datascale transformation.
\expandafter\let\expandafter\pgfplots@cur@min@unscaled\csname pgfplots@#1min@unscaled@as@float\endcsname
\expandafter\let\expandafter\pgfplots@cur@max@unscaled\csname pgfplots@#1max@unscaled@as@float\endcsname
%
\ifx\pgfplots@cur@min@unscaled\pgfutil@empty
\edef\pgfplots@loc@TMPa{\csname pgfplots@#1min\endcsname}%
\expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}%
\let\pgfplots@cur@min@unscaled=\pgfmathresult
\edef\pgfplots@loc@TMPa{\csname pgfplots@#1max\endcsname}%
\expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}%
\let\pgfplots@cur@max@unscaled=\pgfmathresult
\fi
%
\expandafter\pgfmathfloat@decompose@E\pgfplots@cur@min@unscaled\relax\pgfmathfloat@a@E
\expandafter\pgfmathfloat@decompose@E\pgfplots@cur@max@unscaled\relax\pgfmathfloat@b@E
\pgfplots@init@scaled@tick@normalize@exponents
\ifnum\pgfmathfloat@b@E<\pgfmathfloat@a@E
\pgfmathfloat@b@E=\pgfmathfloat@a@E
\fi
\xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@above@exponent}%
\ifnum\pgfplots@glob@TMPa<\pgfmathfloat@b@E
% ok, scale it:
\expandafter\ifx % Check whether we're using engineering notation (restricting exponents to multiples of three)
\csname ifpgfplots@scaled@#1@ticks@engineering\expandafter\endcsname
\csname iftrue\endcsname
\divide\pgfmathfloat@b@E by 3
\multiply\pgfmathfloat@b@E by 3
\fi
\multiply\pgfmathfloat@b@E by-1
\xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}%
\else
\xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@below@exponent}%
\ifnum\pgfplots@glob@TMPa>\pgfmathfloat@b@E
% ok, scale it:
\expandafter\ifx % Check whether we're using engineering notation (restricting exponents to multiples of three)
\csname ifpgfplots@scaled@#1@ticks@engineering\expandafter\endcsname
\csname iftrue\endcsname
\advance\pgfmathfloat@b@E by -2
\divide\pgfmathfloat@b@E by 3
\multiply\pgfmathfloat@b@E by 3
\fi
\multiply\pgfmathfloat@b@E by-1
\xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}%
\else
% no scaling necessary:
\xdef\pgfplots@glob@TMPa{0}%
\fi
\fi
\or
% CASE 2 : scaled #1 ticks=base 10:
%--------------------------------
\c@pgf@counta=\csname pgfplots@scaled@ticks@#1@arg\endcsname\relax
%\multiply\c@pgf@counta by-1
\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
\or
% CASE 3 : scaled #1 ticks=real:
%--------------------------------
\pgfmathfloatparsenumber{\csname pgfplots@scaled@ticks@#1@arg\endcsname}%
\global\let\pgfplots@glob@TMPa=\pgfmathresult
\or
% CASE 4 : scaled #1 ticks=manual:
\expandafter\global\expandafter\let\expandafter\pgfplots@glob@TMPa\csname pgfplots@scaled@ticks@#1@arg\endcsname
\fi
\endgroup
\fi
\expandafter\let\csname pgfplots@tick@scale@#1\endcsname=\pgfplots@glob@TMPa%
}
\makeatother
\begin{document}
\begin{tikzpicture}
\begin{axis}[scaled ticks=engineering, y unit=m,height=4cm]
\addplot [domain=0:1] {10000*\x};
\end{axis}
\end{tikzpicture}
The multiplier should be printed as $\cdot10^3$[m] instead of merely $\cdot10^3$.
\end{document}
```
|
2013/08/11
|
[
"https://tex.stackexchange.com/questions/127679",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/10662/"
] |
Here's an approach that doesn't use the `units` library, but instead defines a new key `y unit label=<text>` that places the `<text>` behind the scale label (if it exists) or at the position of the scale label (if it doesn't).
If you put the following code in your preamble...
```
\makeatletter
\long\def\ifnodedefined#1#2#3{%
\@ifundefined{pgf@sh@ns@#1}{#3}{#2}%
}
\pgfplotsset{
y unit label/.style={
y tick scale label style={
name=y tick scale label,
inner xsep=0pt
},
after end axis/.append code={
\ifnodedefined{y tick scale label}{%
\tikzset{
every y unit label/.append style={
anchor=base west, at=(y tick scale label.base east)
}
}
}{%
\tikzset{
every y unit label/.append style={
/pgfplots/every y tick scale label
}
}
}
\node [every y unit label] {#1};
}
}
}
\makeatother
```
... you can write the following ...
```
\begin{axis}[
scaled ticks=engineering,
y unit label=m,
height=4cm,
]
\addplot [domain=0:1] {10000*\x};
\end{axis}
```
... to get ...

... or ...
```
\begin{axis}[
scaled ticks=engineering,
y unit label=m,
height=4cm,
]
\addplot [domain=0:1] {10000*\x};
\end{axis}
```
... to get ...

---
Complete code:
```
\documentclass{article}
\usepackage{pgfplots}
\makeatletter
\newif\ifpgfplots@scaled@x@ticks@engineering
\pgfplots@scaled@x@ticks@engineeringfalse
\newif\ifpgfplots@scaled@y@ticks@engineering
\pgfplots@scaled@y@ticks@engineeringfalse
\newif\ifpgfplots@scaled@z@ticks@engineering
\pgfplots@scaled@z@ticks@engineeringfalse
\pgfplotsset{
scaled x ticks/engineering/.code=
\pgfplots@scaled@x@ticks@engineeringtrue,
scaled y ticks/engineering/.code=
\pgfplots@scaled@y@ticks@engineeringtrue,
scaled z ticks/engineering/.code=
\pgfplots@scaled@y@ticks@engineeringtrue,
% scaled ticks=engineering % Uncomment this line if you want "engineering" to be on by default
}
\def\pgfplots@init@scaled@tick@for#1{%
\global\def\pgfplots@glob@TMPa{0}%
\expandafter\pgfplotslistcheckempty\csname pgfplots@prepared@tick@positions@major@#1\endcsname
\ifpgfplotslistempty
% we have no tick labels. Omit the tick scale label as well!
\else
\begingroup
\ifcase\csname pgfplots@scaled@ticks@#1@choice\endcsname\relax
% CASE 0 : scaled #1 ticks=false: do nothing here.
\or
% CASE 1 : scaled #1 ticks=true:
%--------------------------------
% the \pgfplots@xmin@unscaled@as@float is set just before the data
% scale transformation is initialised.
%
% The variables are empty if there is no datascale transformation.
\expandafter\let\expandafter\pgfplots@cur@min@unscaled\csname pgfplots@#1min@unscaled@as@float\endcsname
\expandafter\let\expandafter\pgfplots@cur@max@unscaled\csname pgfplots@#1max@unscaled@as@float\endcsname
%
\ifx\pgfplots@cur@min@unscaled\pgfutil@empty
\edef\pgfplots@loc@TMPa{\csname pgfplots@#1min\endcsname}%
\expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}%
\let\pgfplots@cur@min@unscaled=\pgfmathresult
\edef\pgfplots@loc@TMPa{\csname pgfplots@#1max\endcsname}%
\expandafter\pgfmathfloatparsenumber\expandafter{\pgfplots@loc@TMPa}%
\let\pgfplots@cur@max@unscaled=\pgfmathresult
\fi
%
\expandafter\pgfmathfloat@decompose@E\pgfplots@cur@min@unscaled\relax\pgfmathfloat@a@E
\expandafter\pgfmathfloat@decompose@E\pgfplots@cur@max@unscaled\relax\pgfmathfloat@b@E
\pgfplots@init@scaled@tick@normalize@exponents
\ifnum\pgfmathfloat@b@E<\pgfmathfloat@a@E
\pgfmathfloat@b@E=\pgfmathfloat@a@E
\fi
\xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@above@exponent}%
\ifnum\pgfplots@glob@TMPa<\pgfmathfloat@b@E
% ok, scale it:
\expandafter\ifx % Check whether we're using engineering notation (restricting exponents to multiples of three)
\csname ifpgfplots@scaled@#1@ticks@engineering\expandafter\endcsname
\csname iftrue\endcsname
\divide\pgfmathfloat@b@E by 3
\multiply\pgfmathfloat@b@E by 3
\fi
\multiply\pgfmathfloat@b@E by-1
\xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}%
\else
\xdef\pgfplots@glob@TMPa{\pgfplots@scale@ticks@below@exponent}%
\ifnum\pgfplots@glob@TMPa>\pgfmathfloat@b@E
% ok, scale it:
\expandafter\ifx % Check whether we're using engineering notation (restricting exponents to multiples of three)
\csname ifpgfplots@scaled@#1@ticks@engineering\expandafter\endcsname
\csname iftrue\endcsname
\advance\pgfmathfloat@b@E by -2
\divide\pgfmathfloat@b@E by 3
\multiply\pgfmathfloat@b@E by 3
\fi
\multiply\pgfmathfloat@b@E by-1
\xdef\pgfplots@glob@TMPa{\the\pgfmathfloat@b@E}%
\else
% no scaling necessary:
\xdef\pgfplots@glob@TMPa{0}%
\fi
\fi
\or
% CASE 2 : scaled #1 ticks=base 10:
%--------------------------------
\c@pgf@counta=\csname pgfplots@scaled@ticks@#1@arg\endcsname\relax
%\multiply\c@pgf@counta by-1
\xdef\pgfplots@glob@TMPa{\the\c@pgf@counta}%
\or
% CASE 3 : scaled #1 ticks=real:
%--------------------------------
\pgfmathfloatparsenumber{\csname pgfplots@scaled@ticks@#1@arg\endcsname}%
\global\let\pgfplots@glob@TMPa=\pgfmathresult
\or
% CASE 4 : scaled #1 ticks=manual:
\expandafter\global\expandafter\let\expandafter\pgfplots@glob@TMPa\csname pgfplots@scaled@ticks@#1@arg\endcsname
\fi
\endgroup
\fi
\expandafter\let\csname pgfplots@tick@scale@#1\endcsname=\pgfplots@glob@TMPa%
}
\makeatother
\makeatletter
\long\def\ifnodedefined#1#2#3{%
\@ifundefined{pgf@sh@ns@#1}{#3}{#2}%
}
\pgfplotsset{
y unit label/.style={
y tick scale label style={
name=y tick scale label,
inner xsep=0pt
},
after end axis/.append code={
\ifnodedefined{y tick scale label}{%
\tikzset{
every y unit label/.append style={
anchor=base west, at=(y tick scale label.base east)
}
}
}{%
\tikzset{
every y unit label/.append style={
/pgfplots/every y tick scale label
}
}
}
\node [every y unit label] {#1};
}
}
}
\makeatother
\pgfplotsset{compat=1.8}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
scaled ticks=engineering,
y unit label=m,
height=4cm,
]
\addplot [domain=0:1] {10*\x};
\end{axis}
\end{tikzpicture}
\end{document}
```
|
4,599,321 |
i have a problem with Autotest. In my user model are the username & email address unique. When i start Autotest everything works fine. In the secound round, from autotest, i have a
>
> Validation failed: Email has already been taken, Username has already been taken
>
>
>
error in only two test. I dont understand why, i use factorygirl with an sequenze and this should generate everytime a new username.
This is my rspec2 file:
```
describe User do
specify { Factory.build(:user).should be_valid }
context "unique values" do
before :all do
@user = Factory.create(:user)
end
it "should have an unique email address" do
Factory.build(:user, :email => @user.email).should_not be_valid
end
it "should have an unique username" do
Factory.build(:user, :username => @user.username).should_not be_valid
end
end
context "required attributes" do
it "should be invalid without an email address" do
Factory.build(:user, :email => nil).should_not be_valid
end
it "should be invalid without an username" do
Factory.build(:user, :username => nil).should_not be_valid
end
it "should be invalid without an password" do
Factory.build(:user, :password => nil).should_not be_valid
end
it "should be invalid without an address" do
Factory.build(:user, :address => nil).should_not be_valid
end
end
end
```
The Factory:
```
Factory.sequence :username do |n|
"Outfit#{n}er"
end
Factory.sequence :email do |n|
"user#{n}@example.com"
end
Factory.define :user do |u|
u.username { Factory.next :username }
u.email { Factory.next :email }
u.password 'secret'
u.phone_number '02214565854'
u.association :address, :factory => :address
end
Factory.define :confirmed_user, :parent => :user do |u|
u.after_build { |user| user.confirm! }
end
```
The only two test that are not working are in the "unique values" context. All other test works without an error.
Thanks
|
2011/01/04
|
[
"https://Stackoverflow.com/questions/4599321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/210023/"
] |
This is exactly the problem I had just run into -- and had a strange experience where this problem didn't seem to happen if I was just running "rake spec".
After not finding an obvious answer, I did try something that seems to have solved the problem! It seems like setting a class variable inside a before() block is the culprit, if you're using FactoryGirl.
I had something very similar:
```
factory :widget do
sequence(:name) { |n| "widget#{n}" }
end
```
then:
```
describe Widget do
before(:each) { @widget = FactoryGirl.create(:widget) }
it ...yadda yadda...
@widget.foo()
end
end
```
autotest would find uniqueness constraint problems. I changed the rspect test to this:
```
describe Widget do
let(:widget) { FactoryGirl.create(:widget) }
it ...yadda yadda...
widget.foo()
end
end
```
...and the uniqueness constraint issues went away. Not sure why this happens, and it seems like it *shouldn't* happen, but may be a workable resolution.
|
2,999,058 |
Cutting a 1D Line:
```
We can cut a 1D line via 0D point.
if we want to cut a 1D line via a 1D line.
we have to move 1 dimension up that is in 2D
```
[(Image for 1D Line cut by 0D pt.)](https://i.stack.imgur.com/EE3Fn.png)
[(Image for 1D Line cut by 1D line)](https://i.stack.imgur.com/fTzeS.png)
Cutting a 2d Plane:
```
We can cut a 2D plane via 1D Line.
if we want to cut a 2D plane by a 2D plane
we have to move 1 dimension up that is in 2D
```
[(Image for 2D plane cut by 1D line)](https://i.stack.imgur.com/uADHJ.png)
[(Image for 2D plane cut by 2D plane)](https://i.stack.imgur.com/oLzbN.png)
**Cutting of a 3D Cube:**
```
We can cut a 3D Cube by a 2D Plane
So the question arises that
Can we cut a 3D cube by a 3D cube?
And if yes then how ?
For it we may require 1 more dimension (4th dimension).
```
[(Image for 3D Cube cut by 2D Plane)](https://i.stack.imgur.com/dww3b.png)
**So how can we do that**!
In all the cases sizes doesn't matter:
Size of a Line doesn't matter that if we cut a Line by another Line.
And Size of a Plane doesn't matter that if we cut a Plane by another Plane.
Is it same for Cubes?
Does Cubes size also doesn't matter. Can we cut a Cube by another Cube(Like a Plane cuts a Cube) and that another Cube's size can by 10x, 100x, 1000x etc ?
I think understanding how a 3D Cube is cut by a 3D cube help me to understand (or say visualize) what 4th Dimension is?
|
2018/11/15
|
[
"https://math.stackexchange.com/questions/2999058",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/494766/"
] |
How are you choosing the $s\_j$? The definition in Stephen Abbott's book allows us to choose the $s\_j$ freely so long as $\Delta\_j<\delta$.
Let $P=\{x\_i\}\_1^n$ with $x\_i<x\_{i+1}$ and $\Delta\_i<\delta$ for all $i$. Then if $f$ is bounded on $[x\_i,x\_{i+1}]$, then it is bounded on $[a,b]$, hence if it is unbounded, then there exists $[x\_i,x\_{i+1}]$ such that $f$ is unbounded on $[x\_i,x\_{i+1}]$. Suppose $f$ is unbounded and choose an $i$ such that $f$ is unbounded on $[x\_i,x\_{i+1}]$. For simplicity we assume it is unbounded above (the case for unbounded below is similar).
Now fix $s\_j\in[x\_j,x\_{j+1}]$ for all $j\not=i$. Then we can make $$\sum\_{j=1}^nf(s\_j)\Delta\_j$$
as large as we wish by varying $s\_i$. For if $Q>0$, then choose $s\_i$ such that
$$f(s\_i)>\dfrac{Q-\sum\_{\substack{j=1\\j\not=i}}^nf(s\_j)\Delta\_j}{\Delta\_i}.$$
Then
$$\sum\_{j=1}^nf(s\_j)\Delta\_j>\sum\_{\substack{j=1\\j\not=i}}^nf(s\_j)\Delta\_j+\dfrac{Q-\sum\_{\substack{j=1\\j\not=i}}^nf(s\_j)\Delta\_j}{\Delta\_i}\Delta\_i=Q.$$
This shows for any $\delta$ that there exists no real number $A$ such that for every tagged partition $(P,\{s\_k\})$ with $\Delta\_k<\delta$ we find $\mathcal{R}(f,P)\in(A-\epsilon,A+\epsilon)$. Contrapositively if $f$ is Riemann integrable, then it is bounded.
|
41,759 |
To express "lengthen an essay", should I write "*prolonger la composition*" or "*allonger la composition*"? I found in the dictionary saying these two words both means to lengthen.
My question is "Elle a essayé de/d' \_\_\_\_\_\_\_\_ son article", given the options to fill in the blank are
A prolonger
B longer
C allonger
D accroître.
Thank you so much for your help :)
|
2020/04/18
|
[
"https://french.stackexchange.com/questions/41759",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/22658/"
] |
Bonjour Claire,
"prolonger" est à prendre au sens *"étendre"* dans la durée **(lié au temps)**, par exemple "je *prolonge la durée* du confinement". *"Allonger"* est plus à prendre au **sens physique** ou au **sens spatial (ajouter de la longueur)** : "je m'allonge sur mon lit". Bien entendu, il existe des exceptions. Dans le cas de votre composition, je dirai plutôt (au choix) :
* "poursuivre la composition"
* "continuer la composition"
* "prolonger la composition"
Vous pouvez écrire la phrase qui vous pose problème ici si vous le voulez, je me ferai un plaisir de vous accorder de l'aide supplémentaire.
Bonne journée.
|
164,128 |
Would you be kind enough to explain the nuance between "pitiful" and "pitiable"? My Oxford Advanced Learner's Dictionary shows two similar meanings for the aforementioned words.
1. deserving pity or causing you to feel pity.
2. not deserving respect
I am confused as to why there are two different adjectives with almost the similar meaning and examples.
|
2014/04/16
|
[
"https://english.stackexchange.com/questions/164128",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/70234/"
] |
I'd say that pitiful might be either of those two definitions (you use context to know which is being used), but pitiable is only the first.
A coach might tell his team "Your guys on defense were pitiful today". He's telling them that they did a bad job. But you would never use pitiable there.
|
66,603,998 |
```
drinks = 5
if drinks <= 2:
print("Keep going buddy")
elif drinks == 3:
print("I believe you've had enough, sir")
else:
print("stop")
```
This was the code I was trying to run, and it keeps giving me a syntax error with the "else" and I don't know why.
|
2021/03/12
|
[
"https://Stackoverflow.com/questions/66603998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15384124/"
] |
Your syntax is wrong. Remove the space before the `else:`
|
33,596,145 |
In a bash script I need to compare the first char of two Strings.
To do this, I use the `head` operator like this:
```
var1="foo"
var2="doo"
headVar1=$(head -c1 $var1)
headVar2=$(head -c1 $var2)
if [ $headVar1 == $headVar2 ]
then
#miau
fi
```
But the console says "head: cant open foo for reading: Doesnt exist the file or directorie"
And the same with doo
Some help?
Thanks.
|
2015/11/08
|
[
"https://Stackoverflow.com/questions/33596145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1886172/"
] |
`head` interpreted `foo` as a filename. See `man head` on what options are available for the command.
To store command output in a variable, use command substitution:
```
headVar1=$(printf %s "$var1" | head -c1)
```
which could be shortened using a "here string":
```
headVar1=$(head -c1 <<< "$var1")
```
But parameter expansion is much faster in this case, as it doesn't spawn a subshell:
```
headVar1=${var1:0:1}
```
|
65,036,643 |
There is a page where you can see the details of a user's loan. There is a decorator where I return values using the get () method. In general, there is a partial refund, which returns items of partial payments as shown in the photo. My problem is that I cannot specify all partial payments, only receive one by one.
Loan Details component:
```
<div className="ClientLoanDetails__card__content__inner__wrapper">
{Object.keys(payments[0]).map(val => {
{
[payments[0][val]].map((payment: any, index: number) => (
<div className="ClientLoanDetails__card__content-inner" key={index}>
{paymentsFields.map((item, indexInner) => (
<div className="ClientLoanDetails__card__content-item" key={indexInner}>
<div className="ClientLoanDetails__card__content-item__title">
{item.title}
</div>
<div className="ClientLoanDetails__card__content-item__value">
{payment[item.key]}
</div>
</div>
))}
</div>
));
}}
)
}}
</div>
```
This is code snippet for key & titles from loan.ts:
```
export const repaymentsFields = [
{
key: 'issuedDate',
title: lang.CLIENTS.REPAYMENTS.ISSUED_DATE,
},
{
key: 'period',
title: lang.CLIENTS.REPAYMENTS.PERIOD_IN_DAYS,
},
]
```
JSON of repayments:
```
"partialRepayments": [
{
"orderId": "A11Fz090VT1BmObJ0S-0",
"repaidPrincipalAmount": {
"amount": 250000.0
},
"repaidInterestAmount": {
"amount": 0
},
"repaidOverdueAmount": {
"amount": 0
},
"repaidProlongationAmount": {
"amount": 0
},
"started": "2020-11-09T16:52:08.981+0600",
"completed": "2020-11-09T16:52:21.170+0600",
"period": 25,
"timestamp": "2020-11-09T16:52:21.174+0600"
},
{
"orderId": "A11Fz090VT1BmObJ0S-1",
"repaidPrincipalAmount": {
"amount": 300000.0
},
"repaidInterestAmount": {
"amount": 0
},
"repaidOverdueAmount": {
"amount": 0
},
"repaidProlongationAmount": {
"amount": 0
},
"started": "2020-11-09T16:54:31.923+0600",
"completed": "2020-11-09T16:54:46.313+0600",
"period": 25,
"timestamp": "2020-11-09T16:54:46.317+0600"
}
],
```
the problem is that it is impossible to display the values that come as in the photo (one loan may have several repayments)
I have to return all values from an Object
[IMAGE of console](https://i.stack.imgur.com/hQS1R.png)
|
2020/11/27
|
[
"https://Stackoverflow.com/questions/65036643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14719180/"
] |
For starters the argument of malloc is confusing
```
arr = malloc(sizeof(arr[SIZE]) * 10);
```
It seems you mean
```
arr = malloc(sizeof( *arr ) * 10);
```
That is you are trying to allocate dynamically an array of the type `int[10][SIZE]`.
More precisely the record used as an argument in the call of malloc
```
arr = malloc(sizeof(arr[SIZE]) * 10);
```
is correct but very confusing. It is better not to use such a record for the `sizeof` operator.
The function declaration can look like
```
int ( *allocation( size_t n ) )[SIZE];
```
Or you can introduce a typedef name like
```
typedef int ( *Array2D )[SIZE];
```
and then declare the function like
```
Array2D allocation( size_t n );
```
where `n` corresponds to the used by you value 10. That is using the parameter you can specify any number for the array dimension apart from 10.
|
35,769,134 |
**CONTEXT**
The code is supposed to get a file object and extract information from it using awk.
It uses readlines() with 'pieceSize' as an argument. 'pieceSize' is the number of MBs I want readlines() to work with as it goes through the file. I did this with hopes that my program wont run into trouble if the file that needs to be read is much greater than my computer's memory.
The file being read has many rows and columns.
The code below is trying to read the first field from the first line using awk.
```
import os
from subprocess import Popen, PIPE, STDOUT
def extract_info(file_object):
pieceSize = 16777216 # 16MB
for line in file_object.readlines(pieceSize):
eachline = line.rsplit() # removing extra returns
p = Popen(['awk','{{print `$`1}}'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
pOut = p.communicate(input=eachline)[0]
print(pOut.decode())
```
**THE ERROR MESSAGE**
The error I receive reads something like ...
```
... in _communicate_with_poll(self, input)
chunk = input[input_offset : input_offset + _PIPE_BUF]
try:
-> input_offset += os.write(fd, chunk)
except OSError as e:
if e.errno == errno.EPIPE:
TypeError: must be string or buffer, not list
```
|
2016/03/03
|
[
"https://Stackoverflow.com/questions/35769134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6012406/"
] |
The error occurs because `str.rsplit()` returns a *list*, but `Popen.communicate()` expects a string (or buffer). So you can't pass the result of `eachline` to `communicate()`.
That's the cause of the problem, but I'm not sure why you are splitting the lines. `rsplit()` will split on *all* whitespace, that includes spaces, tabs etc. Is that really what you want?
Also, this code will iterate over the first set of lines returned by `readlines()`. The rest of the file remains unprocessed. You need an outer loop to keep things going until the input file is exhausted (possibly there is in the calling code that you don't show?). And then it is calling `Popen` once for every line of input which is going to be very inefficient.
I suggest that you handle the processing entirely in Python. `line.split()[0]` is effectively giving you the data that you need (the first column of the file) without passing it to awk. Iterating line-by-line is memory efficient.
Perhaps a generator is a better solution:
```
def extract_info(file_object):
for line in file_object:
yield line.split()[0]
```
Then you can iterate over it in the calling code:
```
with open('inputfile') as f:
for first_field in extract_info(f):
print first_field
```
|
50,318,309 |
I use Python 2.7. I'm trying to run my UI-automation script, but I got ImportError.
I have at least 30 Classes with methods. I want to have these methods in each and any class that's why I created BaseClass(MainClass) and created objects of all my classes. Please advise what should I do in this case or how I can solve this problem.
Here the example what similar to my code.
test\_class/baseclass.py
```
from test_class.first_class import FirstClass
from test_class.second_class import SecondClass
class MainClass:
def __init__(self):
self.firstclass = FirstClass()
self.secondclass = SecondClass()
```
test\_class/first\_class.py
```
from test_class.baseclass import MainClass
class FirstClass(MainClass):
def __init__(self):
MainClass.__init__(self)
def add_two_number(self):
return 2 + 2
```
test\_class/second\_class.py
```
from test_class.baseclass import MainClass
class SecondClass(MainClass):
def __init__(self):
MainClass.__init__(self)
def minus_number(self):
return self.firstclass.add_two_number() - 10
if __name__ == '__main__':
print(SecondClass().minus_number())
```
When I run the last file I get this error
```
Traceback (most recent call last):
File "/Users/nik-edcast/git/ui-automation/test_class/second_class.py", line 1, in <module>
from test_class.baseclass import MainClass
File "/Users/nik-edcast/git/ui-automation/test_class/baseclass.py", line 1, in <module>
from test_class.first_class import FirstClass
File "/Users/nik-edcast/git/ui-automation/test_class/first_class.py", line 1, in <module>
from test_class.baseclass import MainClass
ImportError: cannot import name MainClass
```
|
2018/05/13
|
[
"https://Stackoverflow.com/questions/50318309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8687066/"
] |
check this line: from test\_class.baseclass import MainClass -> it seems like all other imports had a '\_' between the names like second\_class. So try maybe to write base\_class. who knows might work
|
1,710,070 |
I know that the solution to the differential equation $\frac{dy}{dt}=y(a-by), a>0, b>0, y(0)=y\_0$ can be derived using integration using partial fractions, and the final result is: $$y=a/(b+ke^{-at})$$ where $k$ is $(a/y\_0)-b$.
My doubt is: Say $y\_0<0$. Then the differential equation itself tells me that $\frac{dy}{dt}<0$ and hence $y$ would just go on falling as $t$ increases, and it would always remain negative. But if you look at the behaviour of the function $y$, there would be a vertical asymptote at some positive value of $t$ (to be precise, where $b+ke^{-at}=0$. Beyond this value of $t$, $y$ would be positive. What am I getting wrong here?
|
2016/03/23
|
[
"https://math.stackexchange.com/questions/1710070",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/325288/"
] |
You got nothing wrong, it is just that the solution ends at the asymptote. Solutions of differential equations are defined over intervals containing the initial point. These intervals can have finite end points even for the so-called "maximal solution". Often these finite end points happen because the trajectory of the solution moves to infinity in finite time, as happens here.
|
72,436,803 |
After in my Laravel 9 project I run `composer update` I faced this error message:
```
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 0 installs, 1 update, 1 removal
- Downloading fruitcake/laravel-cors (v3.0.0)
- Removing asm89/stack-cors (v2.1.1)
- Upgrading fruitcake/laravel-cors (v2.2.0 => v3.0.0): Extracting archive
77 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
In Finder.php line 588:
syntax error, unexpected token ")"
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
```
It seems update was finished, but something went wrong and now in the console I get `syntax error, unexpected token ")"` error on `Finder.php:588`.
I checked this file and it's looks correct.
When I open my project in browser I get this error:
```
Fatal error: Uncaught RuntimeException: A facade root has not been set. in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:334
Stack trace:
#0 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/RegisterErrorViewPaths.php(18): Illuminate\Support\Facades\Facade::__callStatic('replaceNamespac...', Array)
#1 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(626): Illuminate\Foundation\Exceptions\RegisterErrorViewPaths->__invoke()
#2 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(607): Illuminate\Foundation\Exceptions\Handler->registerErrorViewPaths()
#3 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(538): Illuminate\Foundation\Exceptions\Handler->renderHttpException(Object(Symfony\Component\HttpKernel\Exception\HttpException))
#4 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(444): Illuminate\Foundation\Exceptions\Handler->prepareResponse(Object(Illuminate\Http\Request), Object(Symfony\Component\HttpKernel\Exception\HttpException))
#5 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(364): Illuminate\Foundation\Exceptions\Handler->renderExceptionResponse(Object(Illuminate\Http\Request), Object(ParseError))
#6 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(427): Illuminate\Foundation\Exceptions\Handler->render(Object(Illuminate\Http\Request), Object(ParseError))
#7 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(115): Illuminate\Foundation\Http\Kernel->renderException(Object(Illuminate\Http\Request), Object(ParseError))
#8 /var/www/html/public/index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#9 {main}
thrown in /var/www/html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 334
```
I cleared all the caches in `bootstrap/cahce/` and in `storage/framework/cache/data/`, `storage/framework/sessions/`, `storage/framework/views/` folders too.
I use PHP version 8.0.16.
Composer version 2.0.12 2021-04-01 10:14:59.
Any idea how can I fix this?
|
2022/05/30
|
[
"https://Stackoverflow.com/questions/72436803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972828/"
] |
To continue using php 8.0 add these entries to your composer.json
```
"require": {
...
"symfony/console": "6.0.*",
"symfony/error-handler": "6.0.*",
"symfony/finder": "6.0.*",
"symfony/http-foundation": "6.0.*",
"symfony/http-kernel": "6.0.*",
"symfony/mailer": "6.0.*",
"symfony/mime": "6.0.*",
"symfony/process": "6.0.*",
"symfony/routing": "6.0.*",
"symfony/var-dumper": "6.0.*",
"symfony/event-dispatcher": "6.0.*",
"symfony/string": "6.0.*",
"symfony/translation": "6.0.*",
"symfony/translation-contracts": "3.0.*",
"symfony/service-contracts": "3.0.*",
"symfony/event-dispatcher-contracts": "3.0.*",
"symfony/deprecation-contracts": "3.0.*",
...
}
```
Worked for me with php 8.0 and Laravel 9.
|
16,723 |
So I have six eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise. I do not show results and I have become tired of working out for no reason. I have put it all to an end and I am seeking alternative ways to build strength. One person told me he can genetically-alter my muscle cells and fibers to enable more strength without exercise - is this possible?
Another method I heard is heavily taking anabolic steroids, which supposedly can build strength even without exercise. At this point I am considering steroid-abuse if it means possible results I can appreciate.
I have never appreciated or have been satisfied with results from any workout program or routine over any period of time, and do not progress no matter what. I do not even wish to seek an expert as alternative approaches is what I am looking for.
Please let me know on any other possible ways that strength can be increased without exercise, since exercise does not work for me -- I have tried everything you can think of and after 8 years I am still where I started at 14.
A 22 year old man who is out lifted by small teenagers who barely workout ... I am a shame of a man and person overall.
|
2014/06/05
|
[
"https://fitness.stackexchange.com/questions/16723",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/8807/"
] |
Stop Making Excuses
-------------------
>
> "I have six [to] eight years of trial-and-error evidence to show that I am incapable of building strength to any measurable degree from any form of exercise."
>
>
>
Either you have a serious medical issue or I call bullshit. I bet the reason you're not getting results is that you *"have [never] been satisfied with results from any workout program or routine over any period of time".* You try something halfheartedly for a little while, then stop, right? You just lift what you feel like and then go home? [That's not going to work.](http://www.t-nation.com/free_online_article/most_recent/the_biggest_training_fallacy_of_all&cr=)
If you think you have a serious medical issue then see a doctor about your health, particularly any possible hormone issues. Stop making up reasons not to see a medical professional. Address your problem head-on.
Lift, Eat, Repeat
-----------------
You must [lift and eat](https://fitness.stackexchange.com/a/6836/1771) if you want to be big and strong. You must work hard. You must be consistent. There is no other way. There are no excuses. There are no alternative methods. Buck up and be serious about your training.
Stop being concerned about other people's success and focus on your own progress. You know nothing about what they do. What they do has nothing to do with your own success or failure. Stop distracting yourself with fantasies about other people's supposedly quick and easy results and focus on working out hard and consistently.
Follow a Program
----------------
*Originally I asked the OP to detail their workouts. ("If you want help on how to make your workouts effective, describe what you've been doing in as much detail as you possibly can: programs, lifts, sets, reps, rest periods, weights, frequency per week, diet, sleep. If you can't be bothered to even write a short description of your lifting then I seriously doubt your commitment to your project.") They have since responded:*
>
> I do not really follow any programs; I just lift stuff. Plenty get strong this way, so what is wrong with me?
>
>
>
You have [fuckarounditis](http://www.leangains.com/2011/09/fuckarounditis.html). I would sympathize, but it's hard when you seem more interested in whinging about other people than actually doing something productive. There are genetic freaks who can sit on a couch for ten years and still lift 400 pounds. They aren't me, so why would I do what they do? I am me. I do what works for me. You are you. You can do what would work for you.
Some people can get away with not doing a program. Most people can't. Stop making excuses and pick a program. StrongLifts would be fine, as would Starting Strength, as would 5/3/1 or GreySkull Linear Progression. Pick one of those four--it really doesn't matter which--and follow it unerringly for six months. Keep a workout log. Eat and sleep right. If you do that and it doesn't work, then you will *know* why it didn't work, because you will see it in the log. Skipped workouts or failed lifts will be quite evident in the log.
If you are interested in results--and that's a big *if*--then you'll pick a program, follow it, focus on quality sleep, and eat plenty of good food. (You have not described your diet so we can't yet help on that front.)
|
221,568 |
Is there a way in SWT to get a monospaced font simply, that works across various operating systems?
For example. this works on Linux, but not Windows:
```
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
```
or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.
I tried getting the system font from Display, but that wasn't monospaced.
|
2008/10/21
|
[
"https://Stackoverflow.com/questions/221568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17832/"
] |
According to the section on [Font Configuration Files](http://java.sun.com/javase/6/docs/technotes/guides/intl/fontconfig.html) in the JDK documentation of [Internationalization Support](http://java.sun.com/javase/6/docs/technotes/guides/intl/)-related APIs, the concept of **Logical Font**s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files:
>
> The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways.
>
>
>
So in your case, I'd try
`Font mono = new Font(parent.getDisplay(), "Monospaced", 10, SWT.NONE);`
to get a handle to the physical monospaced font of the current platform your code is running on.
**Edit**: It seems that SWT doesn't know anything about logical fonts ([Bug 48055](https://bugs.eclipse.org/bugs/show_bug.cgi?id=48055) on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font...
|
46,599,446 |
I'm seeking some help on how I can click the "Play Activity button" in our Global Productivity Hub in our office using excel VBA. I'm creating an attendance log in tool with lunch and break trackers. Once the employee click Log In with tool that I created, the GPH site will launch and will logged them in, the same thing with Log Out. However, I'm having difficulty in controlling the break and lunch button of GPH site using the tool that I created. I cannot find the correct elements to integrate to my vba code. I hope someone can help me with this. Please see below the HTML code of that particular button and the image.
```html
<tr class="top-five">
<td title="Play Activity" class="glyphicon glyphicon-play-circle play-activity" data-toggle="tooltip" data-team-id="e9575e8b-4682-734c-b28d-b1ee5532a8ce" data-activity-id="e0728017-a4fa-ef4b-91a6-262e5418a134" data-team-name="Technology Team"> </td>
<td>
<span title="Break Activities" class="act-ellipsis" data-toggle="tooltip">
<span class="ellip ellip-line"> Break Activities </span>
</span>
Break
</td>
<td title="Favorite" class="glyphicon glyphicon-star" data-toggle="tooltip" data-activity-id="e0728017-a4fa-ef4b-91a6-262e5418a134"></td>
</tr>
```

|
2017/10/06
|
[
"https://Stackoverflow.com/questions/46599446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8730433/"
] |
You could use a rank analytic function here, e.g.
```
SELECT salary
FROM
(
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) dr
FROM c
) t
WHERE dr = 2;
```
This would return the second highest salary by dense rank, including all ties for second.
|
17,028 |
I have a Canon 550D which I've been using for around a year now. I really love it and have learned a great deal with this and the 18 - 135mm kit lens. But now with experience I feel the need to get some better glass. I won't be buying a new body any time soon because I figure investing in some good glass is more important.
As I have looked around, I see quite a few good used L lenses I can get in ebay for good bargain prices. But I know that the EF lenses don't have the same focal length in the cropped sensors. Is it a wise decision to buy these EF lenses or buy the cropped sensor alternatives?
I have the following lenses in mind that I am looking to buy down the line from the canon range over the next several months.
16-35mm f/2.8L, 24-70mm f/2.8L, 70-200 f/4L.
Are these apt choices for cropped sensors? I know most pros with FFs use these but I am a bit skeptic that they will serve the same purpose for me. If so what are the alternatives for this that have almost as good image quality?
|
2011/11/08
|
[
"https://photo.stackexchange.com/questions/17028",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1924/"
] |
If you have the money, go with the full frame option. The basic reasoning that I would have for that is simple: lenses will stay with you longer than the camera body. That's the nutshell answer.
Longer answer is that today you have a 550D and you're learning. Stay with that camera while you're doing that, until you feel that the photography you want to do is being impeded. Then you're going to look for something else. You might stay cropped sensor, you might not, but if you've shelled out thousands for lenses that are crop, then that may make the decision for you and that isn't ideal. Or you'll need to sell your lenses and you'll lose money in replacing. Also not ideal.
Net effect, if there is ever a real possibility that you'll buy a full frame Canon, new or used, then stick with the full-sized lenses. If this isn't a real possibility, then go crop. Just seriously consider all that first.
|
21,069,530 |
I'm trying to somehow determine based on my interface what type came in and then do some validation on that type. Validation differes based on type that comes in.
```
public static bool RequestIsValid(IPaymentRequest preAuthorizeRequest)
{
switch (preAuthorizeRequest)
{
case
}
}
```
but either I can't do that with an interface or I'm not doing something that will make this work.
If I can't do that on an interface which looks like the probably because I think switch needs a concrete type, then how would I do this? Just regular if statements that check typeof?
Is that the only way?
|
2014/01/12
|
[
"https://Stackoverflow.com/questions/21069530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93468/"
] |
`.myClass/DomElement > .myotherclassinsidethatelement` selects only the direct children of the parent class.
So:
```
<div class='myClass'>
<div class='someOther'>
<div class='myotherclassinsidethatelement'></div>
</div>
</div>
```
In this case, the `>` version won't select it.
See here: <http://jsfiddle.net/RRv7u/1/>
|
5,515 |
I know that mining pool shares have no value on their own, but it should be possible to find an average value based on the pool's average payout per share. [This site](https://en.bitcoin.it/wiki/Mining_pool_reward_FAQ#What_will_be_my_expected_payout_per_share.3F) describes the expected payout per share as `([block reward] - [pool operator's cut]) / [difficulty]`.
It seems to me that a share's "value" would necessarily be related to the difficulty as set by the pool--a pool with shares that are harder to find will have its users find fewer shares, making each share "worth" more. However, the equation above clearly doesn't work with the pool's difficulty, as most pools set difficulty to 1 and a share isn't worth ~48 BTC. How can I reconcile these issues to calculate the expected payout per share of a pool without knowing how many total shares are found?
**Edit:**
Ah, I think I've figured it out. The difficulty in the equation can be the network difficulty, because that's what makes it more or less likely that a given successful hash (earning a share) in a pool solves the block and earns the block reward. Thus, the network difficulty indirectly limits the value of a share. Is this correct?
**Edit Again:**
And now I'm back to being confused. If Pool A sets a higher difficulty than Pool B, Pool A's shares are worth more than Pool B's (assuming the same number of miners at a set hash rate) because they're rarer so each share will earn more at payout. How is this taken into account in the equation?
|
2012/11/27
|
[
"https://bitcoin.stackexchange.com/questions/5515",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/2029/"
] |
If the global network difficulty is D and the difficulty of shares in the pool is d, then the probability that a share will lead to a valid block is d/D. The reward in this case is B, so the average reward per share is B\*(d/D). If the operator's average fee is f (so for example f=0.01 means 1% fee), the average reward miners get per share submitted is (1-f) \* B \* (d/D).
|
81,413 |
I was wondering if tension on both ends of a rope is still the same, even if there is objects with different weights on both sides of the rope.
|
2013/10/20
|
[
"https://physics.stackexchange.com/questions/81413",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/29959/"
] |
I'm assuming there is a pulley involved which allows the tension from both objects to be in the same direction (i.e towards the source of gravity).

Taking this to be the case, yes, the tension in the rope is constant. However, the entire system will accelerate, with the heavier mass moving downwards.
|
3,380,033 |
I'm using xmlwriter to create an xml document. The xml document looks like this:
```
<?xml version="1.0" encoding="utf-8" ?>
<ExceptionsList />
```
How can i prevent the /> and appropriately end the root node?
Because of this, i can't append anything to the root node.
My code for creating the xml file looks like this:
```
string formatDate = DateTime.Now.ToString("d-MMM-yyyy");
XmlTextWriter xmlWriter = new XmlTextWriter(xmlfileName, Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 3;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("ExceptionsList"); // ExceptionsList (Root) Element
xmlWriter.WriteEndElement(); // End of ExceptionsList (Root) Element
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
```
And I append to the root node like this:
```
XDocument xml = XDocument.Load(xmlFileName);
XElement root = xml.Root;
root.Add(new XElement("Exception",
new XElement("Exception Type", exceptionType),
new XElement("Exception Message", exceptionMessage),
new XElement("InnerException", innerException),
new XElement("Comment", comment)));
xml.Save(xmlFileName);
```
This gives me a stackoverflow at runtime error too.
Any help would be appreciated.
Thanks in advance!
|
2010/07/31
|
[
"https://Stackoverflow.com/questions/3380033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/405046/"
] |
Your code is right, and you don't need to change how your `ExceptionsList` element is closed.
```
xmlWriter.WriteStartElement("ExceptionsList"); // ExceptionsList (Root) Element
xmlWriter.WriteStartElement("Exception"); // An Exception element
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement(); // End of ExceptionsList (Root) Element
```
In your second snippet, you need to remove those white spaces from element name, as XML specification forbid that and add your elements into your `XDocument` instance, like this:
```
XDocument xml = new XDocument();
xml.Add(new XElement("Exception",
new XElement("ExceptionType", "Exception"),
new XElement("ExceptionMessage",
new XElement("InnerException", "innerException")),
new XComment("some comment")));
xml.Save("sample2.xml");
```
|
17,578,280 |
When I set the src of an image object, it will trigger an onload function. How can I add parameters to it?
```
x = 1;
y = 2;
imageObj = new Image();
imageObj.src = ".....";
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
x = 3;
y = 4;
```
In here, I want to use the x and y values that were set at the time I set the src of the image (i.e. 1 and 2). In the code above, by the time the onload function would finish, x and y could be 3 and 4.
Is there a way I can pass values into the onload function, or will it automatically use 1, and 2?
Thanks
|
2013/07/10
|
[
"https://Stackoverflow.com/questions/17578280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497454/"
] |
All the other answers are some version of "make a closure". OK, that works. I think closures are cool, and languages that support them are cool...
However: there is a much cleaner way to do this, IMO. Simply use the image object to store what you need, and access it in the load handler via "`this`":
```
imageObj = new Image();
imageObj.x = 1;
imageObj.y = 2;
imageObj.onload = function() {
context.drawImage(this, this.x, this.y);
};
imageObj.src = ".....";
```
This is a very general technique, and I use it all the time in many objects in the DOM. (I especially use it when I have, say, four buttons and I want them to all share an "onclick" handler; I have the handler pull a bit of custom data out of the button to do THAT button's particular action.)
One warning: you have to be careful not to use a property of the object that the object class itself has a special meaning or use. (For example: you can't use `imageObj.src` for any old custom use; you have to leave it for the source URL.) But, in the general case, how are you to know how a given object uses all its properties? Strictly speaking, you can't. So to make this approach as safe as possible:
* Wrap up all your custom data in a single object
* Assign that object to a property that is unusual/unlikely to be used by the object itself.
In that regard, using "x" and "y" are a little risky as some Javascript implementation in some browser may use those properties when dealing with the Image object. But this is probably safe:
```
imageObj = new Image();
imageObj.myCustomData = {x: 1, y: 2};
imageObj.onload = function() {
context.drawImage(this, this.myCustomData.x, this.myCustomData.y);
};
imageObj.src = ".....";
```
Another advantage to this approach: it can save a lot of memory if you are creating a lot of a given object -- because you can now share a single instance of the onload handler. Consider this, using closures:
```
// closure based solution -- creates 1000 anonymous functions for "onload"
for (var i=0; i<1000; i++) {
var imageObj = new Image();
var x = i*20;
var y = i*10;
imageObj.onload = function() {
context.drawImage(imageObj, x, y);
};
imageObj.src = ".....";
}
```
Compare to shared-onload function, with your custom data tucked away in the Image object:
```
// custom data in the object -- creates A SINGLE "onload" function
function myImageOnload () {
context.drawImage(this, this.myCustomData.x, this.myCustomData.y);
}
for (var i=0; i<1000; i++) {
imageObj = new Image();
imageObj.myCustomData = {x: i*20, y: i*10};
imageObj.onload = myImageOnload;
imageObj.src = ".....";
}
```
Much memory saved and may run a skosh faster since you aren't creating all those anonymous functions. (In this example, the onload function is a one-liner.... but I've had 100-line onload functions, and a 1000 of them would surely be considered spending a lot of memory for no good reason.)
*UPDATE*: See [use of 'data-\*' attribute](https://stackoverflow.com/q/17184918/701435) for a standard (and "standards approved") way to do this, in lieu of my ad-hoc suggestion to use `myCustomData`.
|
45,666,502 |
I'm new to this site so hopefully I'm phrasing my question correctly.
I'm working through some introductory Android programming. What allows me to call the `Toast.makeText` method, but I cannot do the same for the `setGravity` method immediately after? Why can I reference the first non-static method, but not the next? I'm also new to using anonymous inner classes.
```
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(quizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT.show();
Toast.setGravity(0, 0 ,0);
}
});
```
|
2017/08/14
|
[
"https://Stackoverflow.com/questions/45666502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8459833/"
] |
You have to create Toast class object
```
public void ShowToast(String message){
Toast t = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
OR
// Toast t = new Toast(getContext()); if custom view require
t.setDuration(Toast.LENGTH_LONG);
t.setText(message);
t.setGravity(Gravity.RIGHT,0,0);
t.show();
}
```
|