INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Add a "became hot meta question" timeline event
As I understand, per-site meta questions can become "hot". For example:
> ">
</test>
in Firefox, it complains
XML Parsing Error: not well-formed
Location: file:///C:/tmp/dump2.xml
Line Number 2, Column 27:
<test key="blah('foo=1&bar=2')">
--------------------------^
Why is this? What do I need to escape? | <?xml version='1.0'?>
<test key="blah('foo=1&bar=2')">
</test>
is not well-formed XML. Use:
<?xml version='1.0'?>
<test key="blah('foo=1&bar=2')">
</test>
**EDIT:**
Error message in Oxygen XML Editor:
> F [Xerces] The reference to entity "bar" must end with the ';' delimiter.
That means `&bar` is parsed as _entity reference_, but here is syntax error, that is, missing `;`. You need to escape `&` character using predefined entity (one of five) `&`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "xml"
} |
Why do most websites have their HTML in just a few lines?
I searched for this question-- both in Google and Stackoverflow-- but couldn't find what I wanted.
Now, whenever I see the source code of a website, like Facebook or Google, their HTML code is spanned in just one line? Why do they do it? What is the significance of doing it? Do I need to do it for small websites as well, say maybe a school website? | The main Google page server millions of page views every hour. If it's one byte longer, that means gigabytes of additional data are transferred over the Internet every day.
That's why big sites with lots of traffic really squeeze every bit out of their HTML code. For small sites, this isn't really an issue. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "html"
} |
How can I get number between specific words in string?
I want to extract phone number from xml using regex.
....
<address>phone number</address>
....
ex)<address>1234567890</address>
But sometimes that phone number gets prefixed with some unnecessary characters.
ex) <address>tel+1234567890</address>
I only need phone number.
I used `<address>.+?(\d+)</address>`
But this does not work properly.
How can I always get number regardless of the case when there is prefix word? | Basically, your regex doesn't work because you don't make the `.+?` optional.
You can fix it like this `.*?` or do something like below:
Regex:
@"<address>[^>\d]*(\d+)[^>]*</address>"
Formatted:
<address> [^>\d]*
( \d+ ) # (1)
[^>]* </address>
Output:
** Grp 0 - ( pos 51 , len 29 )
<address>1234567890</address>
** Grp 1 - ( pos 60 , len 10 )
1234567890
---------------
** Grp 0 - ( pos 169 , len 33 )
<address>tel+1234567890</address>
** Grp 1 - ( pos 182 , len 10 )
1234567890 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, .net, regex"
} |
How to display "loading" image near text view
I need a way to show "loading" image near text view. In my app, some data receives from server periodically and while these processes executing I need to show to user loading(wait) image like this image below.
sample image
Then, when executing finished, I want loading image to disappear from screen. Some time later when asyn task start to receive some data again. This image will show again. This all process will go periodically. I don't use ProgressDialog. Because it cover all screen and keep user waiting.
Important point: when image disappeared, its area in layout will used by text view and no blank will be there. | This tutorial is answer of my question. When we apply this xml code where we want to show rotating circle progress bar in layout,
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Small"
android:layout_marginRight="5dp" />
it seems just I want.
And then using java code to start and stop it. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android"
} |
Duplicate key exception from Entity Framework?
I'm trying to catch the exception thrown when I insert a already existing user with the given username into my database. As the title says then I'm using EF. The only exception that's thrown when I try to insert the user into to db is a "UpdateException" - How can I extract this exception to identify whether its a duplicate exception or something else? | catch (UpdateException ex)
{
SqlException innerException = ex.InnerException as SqlException;
if (innerException != null && innerException.Number == ??????)
{
// handle exception here..
}
else
{
throw;
}
}
Put the correct number at `??????` that corresponds to unique constraint violation (I don't know it from the top of my head). | stackexchange-stackoverflow | {
"answer_score": 42,
"question_score": 36,
"tags": "c#, entity framework, exception"
} |
Equals Method with two integers
I want to override the equals method. But in my class are two integers. I want to ask you if the equalsMethode is correct.
like this?
thank you
edit 1: my problem is, i want to remove an object of typ field of a | Other than a couple of syntax errors, the implementation is not incorrect. However, the conversions to string are unnecessary:
return other.getRow() == getRow() && other.getColumn() == getColumn();
Other points:
1. The `if (this == obj)` check is redundant.
2. The `if (getClass() != obj.getClass())` check may or may not be desirable, depending on whether you intend to ever subclass `Field` (I note that it is not declared `final`).
Last but not least, having overridden `equals()`, you should also override `hashCode()`. See What issues should be considered when overriding equals and hashCode in Java? for a discussion. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "java, equals"
} |
Slicing to remove item in the middle of the list
I want to write code that uses slicing to get rid of the the second 8 so that here are only two 8’s in the list bound to the variable nums. The nums are as below:
nums = [4, 2, 8, 23.4, 8, 9, 545, 9, 1, 234.001, 5, 49, 8, 9 , 34, 52, 1, -2, 9.1, 4]
This is my code:
nums=[0:4:-1]
nums=[:4]+[5:]
but slicing seems to remove the front or bottom part, how can we remove the middle part? | If you know the index then this should work:
del nums[4:5] | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "python, slice"
} |
How does comparison work if the __lt__ protocol isn't implemented?
I am mostly interested in terms of what is happening but lets say I have a custom class with __eq__ implemented and nothing else.
How do the other comparisons get resolved? What is the default behaviour? Every time I run the comparison I get a different result. I know that I need to implement these and that I can also use `@total_ordering` to simplify the job.
What is actually happening behind the scenes? This is mostly out curiosity. | If `__lt__` isn't defined, comparisons use `__cmp__` instead. If that's not defined, it uses a default comparator. And it appears that the default comparator compares by "object identity (address)".
See the docs for `__cmp__` for details. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "python, python 2.7, comparison"
} |
Why the sum of $n$ seems equals the period of the binary expansion of $1/n$?
The sum of $n$(suppose $n$ is positive odd,using $n=23$ as an example):
Step 1 : Get the odd part of $23 + ~~1 $, which is $~~3$,$~~3\times2^3=23 + ~~ 1$,get $s_1 = 3$
Step 2 : Get the odd part of $23 + ~~3 $, which is $13$,$13\times2^1=23 + ~~ 3$,get $s_2 = 1$
Step 3 : Get the odd part of $23 + 13 $, which is $~~9$,$~~9\times2^2=23 + 13$,get $s_3 = 2$
Step 4 : Get the odd part of $23 + ~~9 $, which is $~~1$,$~~1\times2^5=23 + ~~9$,get $s_4 = 5$
Continuing this operation (with $23 + 1$) repeats the same steps as above. There are $4$ steps in the cycle, so the cycle length of $23$ is $4$and the sum of $23$ is $s_1 + s_2 + s_3 + s_4 = 11$.
The period of the binary expansion of $1/23$ is $11$,so why the sum of $23$ seems equals the period of the binary expansion of $1/23$? | Consider the sequence $a_i = 2^{-i} \pmod{23}$ $$ \begin{array}{l} a_0 = 1,~a_1=12,~a_2=6 \\\ a_3 = 3 \\\ a_4 = 13, ~ a_5=18, \\\ a_6=9, ~ a_7 = 16, a_8=8, a_9=4, a_{10}=2 \\\ a_{11} = 1 = a_0 \end{array} $$ Your steps of "get the odd part" are precisely finding the next odd number in this sequence, your $s_i$ are counting all of the steps, and the sum $\sum s_i$ is the order of 2 modulo 23.
Let $n=\operatorname{ord}_p 2$ be the order of 2 modulo a prime $p$ and $m$ the period of the binary expansion of $1/p$. Then for some positive integer $k$ $$ 2^n = pk+1 \\\ 2^n\frac{1}{p} = k + \frac{1}{p} $$ That is, the binary representation of $1/p$ repeats after $n$ bits, so $n\mid m$. Similarly, for some positive integer $j$ $$ 2^m \frac{1}{p} = j + \frac{1}{p} \\\ 2^m = jp + 1 $$ so also $m\mid n$ and hence $n=m$. | stackexchange-math | {
"answer_score": 6,
"question_score": 11,
"tags": "number theory, elementary number theory"
} |
Calling php scripts from windows phone 8 (C#)
I'm working on a **windows phone 8** project. I want to connect to the database (MongoDB) which is hosted somewhere. **with out calling directly** to the database, I'm **calling through a php API**.(basically each operation has separate php scripts).
So I want to make C# send a request to PHP scripts running at the webserver and make PHP return data to windows phone application through internet.
Can anybody please tell me how to do this.
Please suggest any online links or tutorials or your own idea. | You can have Reference from here : How to call a PHP based web service in windows phone 8. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, php, api, windows phone 8"
} |
How can I create an index based on the year and month of a timestamp?
I'm trying to create an index based on the year-month of a timestamp field (e.g. `2018-03`).
Initially I tried doing:
create index tmp_year_mo on my_table
((to_char(DATE(ts_field AT TIME zone 'utc'), 'YYYY-MM')))
But unfortunately you get `ERROR: functions in index expression must be marked IMMUTABLE` because the function apparently has mutable output. This doesn't quite make sense to me as I thought I removed the variability of the output by setting the timezone to UTC (?).
Everyone else doing this who's posted about it has had a simpler problem like just converting using the `::DATE` cast, which is fine, but I need the year-month.
I guess a solution could be to create a whole new column in the table and then populate it with this value, and then index off it, but is there an expression that will work within the CREATE INDEX realm? | this should work:
create index tmp_year_mo on my_table
((date_trunc('month',ts_field at time zone 'utc')))
<
> you can shift your timestamptz to a fixed timezone
< | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "sql, postgresql, indexing"
} |
Geometry of number
This question seems not very hard, but it is starting to embarrass me. So I thought I can use your ideas to solve it, and I would be thankful in advance.
Let $K/\mathbb{Q}$ be a number field of degree $n$ with the discriminant $D$. For $\alpha\in\mathcal{O}_K$ define $$||\alpha||:=\max\\{|\sigma(\alpha)|:\mbox{over all euclidean place} \\}$$
I want to show that there exists an $0\neq\alpha\in\mathcal{O}_K$ such that $Tr_{K/\mathbb{Q}}(\alpha)=0$ and $||\alpha||\ll|D|^{\frac{1}{2(n-1)}}$, where the implied constant depends only on $n$.
I was trying to use geometry of number, then it is easy to find an $0\neq\alpha\in\mathcal{O}_K$ such that and $||\alpha||\ll|D|^{\frac{1}{2(n-1)}}$ but I could not prove this $\alpha$ can be choosen so that $Tr(\alpha)=0$. | If $\beta\ne\alpha$ is a conjugate of $\alpha$ then $\alpha-\beta$ has trace zero. If as you say $\|\alpha-\beta\|\le\|\alpha\|+\|\beta\|$, then you're done. | stackexchange-math | {
"answer_score": 2,
"question_score": 4,
"tags": "algebraic number theory"
} |
How to change the text of a BarButtonItem on the NavigationBar?
I am trying to create a list of items that can be edited. Something like this:
!enter image description here
To that end, I added a NavigationBar to the top of the view, then added 2 Bar Button Items in XCode designer. I set the identifier for the button on the left to Add, for the button on the right to Edit.
When I click the Edit, I want to change the text to Done. I've tried various ways, e.g. `btnEdit.Title = "Done"`, but it simply doesn't take.
I've seen several blog posts recommending .SetTitle, but UIButtonBarItem doesn't have that method (at least in MonoTouch).
So, how can I change the title of the Edit button? | I resolved it. The key was I was setting the identifier of the Edit button to a system value (e.g. UIBarButtonSystemItemEdit) and you can't change the text of those (makes sense now). I changed the identifier back to Custom and setting .Title worked fine. | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 11,
"tags": "ios, xamarin.ios, uinavigationbar, uibuttonbaritem"
} |
Sending request with PHP witout getting response
Maybe this is a simple question, but I didn't find answer in web.
I have remote script that works when I'm opening
I can't include it, cause this page can give fatal errors, can take too long to load.
I need to load that page from php in the fastest and the easyest way.
Now I'm doing
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,$withReturn);
$execute = curl_exec($ch);
But this script get response, so consequently it will take more time than script that returns only headers, or not returns anything.
That is the better way to do it?
If it will help `do_it.php` is in same server from where I need to call it. | I think the possible solutions for executing the request and not waiting for a response would be to use php.net/curl_multi_exec and then avoid parsing the response. Another approach would be to use sockets, open a connection to the script, write the request then close the connection without readying the response.
A example curl script: <
An example usage of the socket method:
$fp = fsockopen('example.com', 80, $errno, $errstr, 30);
$out = "GET /do_it.php HTTP/1.1\r\n";
$out.= "Host: example.com\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fclose($fp);
Above example is untested and is provided as a starting point. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "php, performance, curl"
} |
'FeedItem' schema type undefined in Trigger
I am trying to dynamically create an sObject in APEX based on the following code.
Schema.SObjectType targetType = Schema.getGlobalDescribe().get('FeedItem');
system.debug(targetType);
sObject chatterUpdate = targetType.newSObject();
chatterUpdate.put('ParentId', '00QU000000ARlWG');
chatterUpdate.put('Body','New update!');
insert chatterUpdate;
Where the `ParentId` is from a Lead Record.
In the _execute anonymous environment_ the code executes fine, and the chatter update is created. The `Schema.SObjectTpe targetType` is defined (with Chatter enabled obviously) but in the context of an `AfterUpdate` trigger on a custom sObject...the `TargetType` is `null`??? | This is kind of a wild guess but is the api version of the trigger or trigger handler fairly old?
I believe that feeditems only came out in 23 so a globaldescribe with an older api version will return null. | stackexchange-salesforce | {
"answer_score": 3,
"question_score": 1,
"tags": "chatter, dynamic dml"
} |
Adding tasks to Windows scheduler with PHP
I'm unable to find any information on adding tasks to Windows Task Scheduler with PHP. I can use exec().
This has to work on IIS. | Windows Schedule Task has a command line utility called Schtasks you can use this utility to add your task to Scheduled task list.
Please go thru the URL for syntax of Schtasks < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "php, exec, scheduled tasks"
} |
Have there been any credible reports of unidentified flying objects?
A unidentified flying object is just that--a flying object that has not been identified. There need not be evidence of alien hi-jinx.
My criteria for a credible UFO report would include:
* Verified by authentic photographic evidence or several eyewitness reports.
* Insufficiently explained by natural or human-caused phenomena.
* Furthermore, such an explanation must not be scientifically suspect, and also must be substantiated. There probably could be a reasonable explanation for all such events, but there must be some underlying evidence that the stated cause was, in fact, in effect at the time. For instance, if it is explained by some human-made aircraft, there must be evidence that such aircraft was flying in the vicinity of the sighting.
Of course, as reasoned skeptics, you are free to apply any criteria you deem relevant. | No UFO has ever been revealed to be an alien spacecraft. That said, we can't explain all UFOs through natural phenomena. In some cases the sightings remain mysterious.
From 1947 to 1969 a project called "Blue Book" was run by the USAF to investigate UFO sightings. The results are the following:
> From 1947 to 1969, the Air Force investigated Unidentified Flying Objects under Project Blue Book. The project, headquartered at Wright-Patterson Air Force Base, Ohio, was terminated Dec. 17, 1969. **Of a total of 12,618 sightings reported to Project Blue Book, 701 remained "unidentified."**
> \-- source
As such, I would say that, yes, unidentified flying phenomena that cannot readily be explained away are quite common, 1 every 11 days on average (in the United States alone).
You can now browse the Project Blue Book files online as they have been disclosed. | stackexchange-skeptics | {
"answer_score": 39,
"question_score": 23,
"tags": "astronomy, aviation, ufo"
} |
How can I make auto completion in netbeans include both variables as well as methods?
I was curious if anyone knows a way (by using a setting or a plugin or something), that would allow me to select variable names on the fly in netbeans, in the same way that Visual Studio 2008 does using an automatic popup window? At the moment I can access them by pressing Ctrl + Space, but I wondered if there is a way that I could avoid this and just have them come up automatically as I type, and the methods would come up with the '.' operator as normal?
The settings in 'Tools->Options->Editor->Code Completion' doesn't seem to have the Ctrl + Space setting I'm looking for, only a tickbox for toggling the normal '.' code completion of method names on or off..
(if it helps, the version of Netbeans is 6.9.1, and I'm writing in Java for Glassfish) | I tried to get the desired feature by **adding** the alphabet to the completion selectors. It worked somewhat, you can always try it.
Goto:
> Tools -> Options -> Editor -> Code Completion
Select
> Language: [Java]
Check:
[X] Auto Popup on Typing Any Java Identifier Part
Completion Selectors for Java:
[.,;:([+-=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ]
Good Luck! | stackexchange-stackoverflow | {
"answer_score": 70,
"question_score": 25,
"tags": "java, netbeans, autocomplete"
} |
Select2 dropdown css modification
I have this situation:
. As you can see, I already added a `top` to it, but it doesn't work for the other properties.
I use the last version of the plugin.
I added an example. Do you see that hr? I'd like the dropdown to start from the left and be full width like the rule.
jsFiddle | Here you go: <
This is css you need:
span.select2-dropdown.select2-dropdown--below {
top: 30px !important;
width:100vw !important;
transform:translate(-100px,0) !important;
}
100vw means `viewport width`, and it will use 100% of the window width. Another problem was that `span.select2-dropdown.select2-dropdown--below` is child of `select2` class (which is moved by 100px from the left). It was not possible before to change its left position without changing child element to `position:fixed` but with `transform` it is possible. First parametar is 100px is because whole select2 is moved `-100px`, so we have to translate child by 100px to the left to match window left position. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, css, jquery select2"
} |
Go error: non-constant array bound
I'm trying to calculate the necessary length for an array in a merge sort implementation I'm writing in `go`. It looks like this:
func merge(array []int, start, middle, end int) {
leftLength := middle - start + 1
rightLength := end - middle
var left [leftLength]int
var right [rightLength]int
//...
}
I then get this complaint when running `go test`:
./mergesort.go:6: non-constant array bound leftLength
./mergesort.go:7: non-constant array bound rightLength
I assume `go` does not enjoy users instantiating an Array's length with a calculated value. It only accepts _constants_. Should I just give up and use a slice instead? I expect a _slice_ is a dynamic array meaning it's either a linked list or copies into a larger array when it gets full. | You can't instantiate an array like that with a value calculated at runtime. Instead use make to initialize a slice with the desired length. It would look like this;
left := make([]int, leftLength) | stackexchange-stackoverflow | {
"answer_score": 165,
"question_score": 88,
"tags": "go"
} |
MYSQL returning the max value per group
I have a bit problem returning the max value of a group using mysql
this is my columns
id | date | time | tran
--------+----------------+----------+----------
1 | 2014/03/31 | 17:23:00 | 1234
1 | 2014/03/31 | 17:24:00 | 3467
2 | 2014/03/31 | 17:26:00 | 2345
My query
SELECT id, max(date), MAX(time) , tran
FROM table
GROUP BY id
RESULT
id | date | time | tran
--------+----------------+----------+----------
1 | 2014/03/31 | 17:26:00 | 1234
2 | 2014/03/31 | 17:24:00 | 2345
Expected answer should be
id | date | time | tran
--------+----------------+----------+----------
1 | 2014/03/31 | 17:26:00 | 3467
2 | 2014/03/31 | 17:24:00 | 2345 | You can do this by using self join on the maxima from same table
SELECT t.* FROM
Table1 t
JOIN (
SELECT id, max(date) date, MAX(time) time , tran
FROM Table1
GROUP BY id) t2
ON(t.id=t2.id AND t.date=t2.date AND t.time=t2.time)
## Fiddle
There may be differences between maxima of date and time so you should use a single field for saving date and time for you current schema this one is optimal
SELECT t.* FROM
Table1 t
JOIN (
SELECT id,
max(concat(date,' ',time)) `date_time`
FROM Table1
GROUP BY id) t2
ON(t.id=t2.id AND (concat(t.date,' ',t.time))=t2.date_time )
## Fiddle | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "mysql, sql, greatest n per group"
} |
Opportunity Layout Does in a Record Type is not Updating automatically on existing Opportunities
I have two record types for Opportunities, Record Type 1 utilizing Layout 1 and Record Type 2 utilizing Layout 2. Historically when a Layout update is made to Layout 1 (say a field is added), the change is updated and included in that Record Type on all existing Opportunities using Layout 1. All I do is go to Opportunity Layouts, choose Layout 1 and add that field, click save.
When I update Layout 2 the same way, and add another value to a picklist to be used in Layout 2, that Picklist does not get updated in Record Type 2 Opportunities utilizing Layout 2. I have to delete the record type and reassign it to the layout that has includes this updated picklist every single time. Is there any reason why the field wouldn't just automatically update on Record Type 2 utilizing Layout 2?
Thank you for any help in advance. Please let me know if any screen caps or other information is necessary. | As mentioned in the comment my guess is that the picklist value is not added for your record type 2 and that it is not related to any issue with layouts.
To validate this assumption you can check the following:
To check existing picklist values:
Go to the record type definition, for example:
My record type for account ;`?? | Take a look at this upgraded extension for WriteHTML with text alignment: <
Example (from the link):
<?php
define('FPDF_FONTPATH', 'font/');
require('WriteHTML.php');
$pdf=new PDF_HTML();
$pdf->Open();
$pdf->AddPage();
$pdf->SetFont('Arial');
$pdf->WriteHTML('You can<BR><P ALIGN="center">center a line</P>and add a horizontal rule <BR><HR>');
$pdf->Output();
?> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, html, fpdf"
} |
Is it possible to load and unload jdk and custom modules dynamically in Java 9?
I am beginner in JPMS and can't understand its dynamism. For example, in current JVM instance `moduleA.jar` is running. `moduleA` requires only `java.base` module. Now, I want
1. to load dynamically `moduleB.jar` that needs `java.sql` module and `moduleC.jar`
2. execute some code from `moduleB`
3. unload `moduleB`, `java.sql`, `moduleC` from JVM and release all resources.
Can it be done in Java 9 module system? | This is an advanced topic. At a high-level, the module system is not dynamic in the sense that individual modules can not be unloaded or replaced in a running VM. However, you can use the API, specifically `java.lang.module.Configuration` and `java.lang.ModuleLayer` to create dynamic configurations of modules and instantiate them in a running VM as a layer of modules. In your scenario, then you may create a layer of modules with modules B and C. This layer of modules will be GC'ed/unloaded once there are no references to them.
As I said, this is an advanced topic and it's probably better to spend time mastering the basics, including services, before getting into dynamic configurations and module layers. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 26,
"tags": "java, java 9"
} |
List of apps written in MonoTouch
Does anyone know if there exists a gallery of iPhone/iPad apps written in MonoTouch similar to <
Thank you,
Rich | there is a selection here < | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "xamarin.ios"
} |
Command-C in vim on macOS is not copying even with "+clipboard" flag
Let's take a look at the _clipboard_ flags:
vim --version | grep clip
+clipboard +keymap +printer +vertsplit
+eval -mouse_jsbterm -sun_workshop -xterm_clipboard
Looks ok to me .. Highlighting some text in `vim` _does_ turn on `Visual` mode. But then hitting `Command``C` results in an annoyed "beep" and nothing more than that.
So I added the following to the default `.vimrc`
set clipboard=unnamed
Still no dice. What needs to be done?
**Update**. `+y` does work.. but I've seen `Command``C` work on other mac laptops i've owned. The last one right here (that does work) did not have anything special done afaict: there's not even any `~/.vimrc` file. | My confusion stems from "which" _terminal_ is being used. I had not installed _iTerm2_ yet: and _that_ is the critical difference between the two laptops. With _mouse reporting_ enabled we do have the desired `CMD-C` for copying text. For plain old _terminal_ there are various options to get the functionality of copying but I did not see any for `CMD-C`. I settled for `+y` to yank the content. | stackexchange-apple | {
"answer_score": 3,
"question_score": 2,
"tags": "copy paste, vi, macvim"
} |
Add .c files in a package using Autotools without compiling them
I have some .c files that get included in some unit tests (like _#include "foo.c"_ ). I don't want the build system to try to build those. It will fail. I just want to call 'make dist' and get those .c files included in the generated package.
How do I do that? I've tried **noinst_** prefix and **_DATA** suffix without effect.
Also, a link to the specific documentation would be great. I'm running in circles reading GNU's documentation on this. It's huge (as it should be)! | Have you tried:
EXTRA_DIST = foo.c | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "build, automake"
} |
how customize the dataTableOutput in shiny app
I want to see only three records in each page of my dataTableOutput. I have set page length to (`pageLength = 3`) but it does not show 3 rows in my table. The code is as following:
> server.r :
# display table
output$responses <- DT::renderDataTable({
(options = list(pageLength = 3))
#update after submit is clicked
input$submit
#update after delete is clicked
input$delete
ReadData()
}
> ui.r :
box(
title = "KPIs", status = "primary", solidHeader = TRUE,
collapsible = TRUE,
DT::dataTableOutput("responses"), tags$hr()
)) | Try
output$responses <- DT::renderDataTable({
#update after submit is clicked
input$submit
#update after delete is clicked
input$delete
DT::datatable(ReadData(), options = list(pageLength=3))}) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "shiny, shinydashboard, dt"
} |
Custom exception in C++ for invalid input to a function
I would like to write a custom Error class in C++. I am mostly used to Java (not used them a lot) so I would like to check here if my thought process on how to do this in C++ is correct.
Currently I got the following code:
class InvalidInput : public std::runtime_error {
public:
InvalidInput(const char* msg) : std::runtime_error(msg) {
}
};
I plan on using the cutsom error in a function as so:
myFunc(int x) {
if (valueIsInvalid(x)) {
throw InvalidInput ("invalid input");
}
}
Before implementing it I would like to know if I am on the right track on how this should be done in C++ (as well as best practice). If there is a better way feel free to tell me as well. | For your solution as below.
> create custome exception
class InvalidInput : public std::exception{
public:
InvalidInput(std::string msg):errorMsg_(msg){}
virtual const char* what() const throw()
{
return errorMsg_;
}
private:
std::string errorMsg_;
};
> use of that custome excetion
myFunc(int x) {
if (valueIsInvalid(x)) {
throw InvalidInput ("invlaid input");
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, c++11, error handling"
} |
How can I display image of dynamic field in drupal 8?
I am new to learning Drupal 8.
I need your help in how can i display dynamic images using Twig template. Also I have tried with below syntax.
{{ file_url(market.getFieldCollectionItem().field_turnpike_image.entity.uri.value|e) }}
{{ file_url(media.entity.field_image.entity.uri.value) }}
Using above syntax I could not display images using in twig template. Also with this syntax I have got some errors.
Please any one help me out to how can i display images using twig template.
Thank you. | Use the following snippet to get the image if you are in `node twig template`
{{ file_url(node.field_image['#items'].entity.uri.value) }}
even
{{ node.field_image.entity.url }} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "drupal, drupal 8"
} |
MQTT broker на роутере
Есть некоторое количество устройств на базе _ESP8266_ , которые нужно подружить с сервисами амазона посредством протокола MQTT. Роутер хочу использовать _Xiaomi Mi WiFi Router 3G_ , опционально с прошивкой от Padavan.
Возможно ли установить на вышеуказанный роутер MQTT broker по типу Mosquitto?
Кто-то так уже делал? | Xiaomi Mi WiFi Router с прошивкой от **Padavan** поддерживает пакеты **Entware**
Вот пакет **Entware Mosquitto MQTT broker** <
Установка на Mi Mini прошла успешно. Вот лог запуска:
Feb 4 06:46:50 mosquitto[527]: mosquitto version 1.4.14 starting
Feb 4 06:46:50 mosquitto[527]: Config loaded from /opt/etc/mosquitto/mosquitto.conf.
Feb 4 06:46:50 mosquitto[527]: Opening ipv6 listen socket on port 1884.
Feb 4 06:46:50 mosquitto[527]: Opening ipv4 listen socket on port 1884.
Feb 4 06:46:55 mosquitto[527]: New connection from 192.168.1.65 on port 1884
;
Is it legal to erase a non-existing key? i.e. is the snippet below ok?
map<char,int> mymap;
mymap['c']=30;
mymap.erase('c');
mymap.erase('c');
mymap.erase('D');
Cheers | Yes, in fact, `std::map::erase()` returns a size_type which indicates the number of keys erased. Thus it returns 0 for nothing erased and 1 for something erased for a map. | stackexchange-stackoverflow | {
"answer_score": 84,
"question_score": 64,
"tags": "c++, stl, dictionary, key, erase"
} |
Element not found in the cache - perhaps the page has changed since it was looked up c#
I was advised to try to use 'StaleElementReferenceException' to handle this, but am not sure how to incorporate it. If someone could provide some hints that would be much appreciated. Thank you
[Then(@"I select the following list item '(.*)' from my search")]
public static void PreSelectedListOptions(string value)
{
var suggestedList = Driver.Instance.FindElements(By.CssSelector(".list-reset li"));
foreach (IWebElement suggestion in suggestedList)
{
if (value.Equals(suggestion.Text))
{
suggestion.Click();
}
}
} | You should add `break;` if the value is found it clicks and then it changes the `dom` which cause a problem for the next iteration.
[Then(@"I select the following list item '(.*)' from my search")]
public static void PreSelectedListOptions(string value)
{
var suggestedList = Driver.Instance.FindElements(By.CssSelector(".list-reset li"));
foreach (IWebElement suggestion in suggestedList)
{
if (value.Equals(suggestion.Text))
{
suggestion.Click();
break;
}
}
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c#, .net, selenium, selenium webdriver"
} |
console.dir(this) not producing any output
I have this:
<body>
<script>
console.log(this);
console.dir(this);
console.dirxml(this);
</script>
</body>
Why does console.dir(this) not produce any output? | It should show the console object as it would in the DOM panel. But it will pay attention to your settings. Go to the DOM tab panel and click the triangle menu thing and be sure it is showing user properties and user functions. Then try again. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 6,
"tags": "javascript, firefox, firebug"
} |
I've reviewed the same post twice
I made this review in Triage, and then this other one concerning the same post. I thought it was a test, so I reviewed it the second time too, but it was not a test.
How is it possible? Maybe it went back to the triage for some reason? Or is it a bug? | Looking at the review-items you provided, both times there were three for "Looks Ok" interspersed with two for "Should Be Improved".
Thus, it went into triage the first time probably due to the system selecting it, and the second time because someone outside triage flagged it as VLQ.
Now, should you be allowed to triage it a second time?
I don't think so, but whether it's common enough to explicitly disallow, and whether it's really a bug, I doubt that. | stackexchange-meta_stackoverflow | {
"answer_score": 14,
"question_score": 20,
"tags": "bug, review queues, review audits, triage"
} |
Objective-C - pass reference of self to child object
I'm working on an Objective-C where I need to pass a reference of `self` to a child object. For instance in Java if I was to do this within a method I could say `room.place(this);` How can I do something like this in Objective-C. I know I can pass `self` as a method parameter but the child object needs to `#import` the other class and when they both import each other then I start to get errors. Any help would be appreciated. | If two classes need to import each others header files, you can use forward declarations.
The way this works is in the child header file you would set it up like so:
@class MyParentClass; // This is the forward declaration.
@interface MyChildClass
@property (nonatomic, strong) MyParentClass *parent;
@end
In the child .m file, you would `#import "MyParentClass.h"` as usual. In MyParentClass.h, you can then just `#import "MyChildClass.h"` | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "ios, objective c, macos, reference"
} |
How to save multiple check box into database in rails 6
I want to save multiple check box category[] into database :-
<label><%= f.check_box :category,{class: 'chk'},1,0%>Apple</label>
<label><%= f.check_box :category,{class: 'chk'},1,0%>Orange</label>
<label><%= f.check_box :category,{class: 'chk'},1,0%>Banana</label>
Here my create form Edit form
controller
database structure | There is a :multiple option, if that's what you need? It's hard to understand exactly what you want
check_box("puppy", "commands", {:multiple => true}, "sit", nil)
check_box("puppy", "commands", {:multiple => true}, "fetch", nil)
check_box("puppy", "commands", {:multiple => true}, "roll_over", nil)
Further examples here: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, ruby on rails 6"
} |
Performance Impact of Triggers and MultiTriggers
At work, a question arose in regards to the performance impact of having a MultiTrigger in the ListBoxItem ControlTemplate.
The situation goes a bit like this: we have a custom styling for the ListBox control that defines an animation and color for the selected ListBoxItem. The issue arose because when the ListBox is disabled, we do not want the selected ListBoxItem to show the selected "background" highlight. This led us to add a set of triggers in the ControlTemplate of ListBoxItems to disable this custom highlighting when the ListBoxItem is disabled and selected. This is where the worry for a negative performance impact originated:
If every ListBoxItem needs to check for triggers and activate for triggers, would this generate a **noticeable** performance impact if there were a lot of items. This could be an issue because this code runs on **older** computers. | Number one WPF does not support "older computers".
Number two if your `ListBox` is Virtualized (which is the default behavior unless you break it by not using a `VirtualizingStackPanel` or by putting the `ListBox` in and infinite container (such as another `StackPanel`) the `ListBoxItems` are NOT created until they are scrolled into view by the user, in which case regardless of having 1000000000 items in the ListBox only the ones that fit into the screen are actually created and consuming memory + CPU. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c#, .net, wpf, performance"
} |
adding numpy arrays to specific indices of a list
I have a list of numpy arrays and want to add two more arrays as the first (0) and last (-1) indices of the list. These are my list and arrays:
import numpy as np
first_arr = np.array([1,1,1])
last_arr = np.array([9,9,9])
middle_arr = [np.array ([4,4,4]), np.array ([6,6,6])]
Then, I want to have a `complete_arr` which is:
complete_arr = [np.array ([1,1,1]), np.array ([4,4,4]), np.array ([6,6,6]), np.array ([9,9,9])]
I tried the following method but it did not give me what I want:
insert_at = 0
middle_arr[insert_at:insert_at] = first_arr
I very much appreciate if anyone help me to do it in python. | You can use `*` (unpacking) operator:
first_arr = np.array([1,1,1])
last_arr = np.array([9,9,9])
middle_arr = [np.array ([4,4,4]), np.array ([6,6,6])]
complete_arr = [first_arr, *middle_arr, last_arr] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, list, numpy, insert, append"
} |
Zend Framework 2 Checkbox setValue for unchecked not work
I tried set checkbox value in false:
$form->add(array(
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'test_checkbox',
'options' => array(
'label' => 'Test checkbox',
'use_hidden_element' => false,
'checked_value' => 1,
'unchecked_value' => 0,
),
'attributes' => array(
'value' => 0,
),
));
But as a result of this page contains:
<input type="checkbox" name="test_checkbox" value="1">
The value does not change and I can not understand why.
Other PHP and JS script not change this value.
Maybe I misunderstood how "checked_value", "unchecked_value" and "value" works? | The code you have is almost correct. It should be:
$form->add(array(
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'test_checkbox',
'options' => array(
'label' => 'Test checkbox',
'use_hidden_element' => false,
'checked_value' => 1,
'unchecked_value' => 0,
)
));
But I think you misunderstand how HTML checkboxes work. The value attribute should _always_ contain _only_ the checked value. Browsers only submit this value if the checkbox is ticked. So when the page loads, the checkbox will correctly appear in the source as:
<input type="checkbox" name="test_checkbox" value="1">
To achieve the unchecked value, ZF (and all other frameworks I know of) add it to a hidden form field _above_ the checkbox. If the checkbox is not ticked, the browser will submit the hidden form field instead. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "php, zend framework, checkbox, zend framework2"
} |
24hr & uiDatePicker
I need the time from my uiDatePicker to be in 24hr format, I understand you can't force this mode if the device is set to display AM/PM? If thats the case, how can I detect the device is in 24hr mode (or not) so I can add 12 to my PM times? Many thanks for any help... | Wel you can, you need to set the local:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"NL"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[formatter setTimeZone:timeZone];
[formatter setLocale:locale];
[locale release], locale = nil; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "iphone, nsdate, uidatepicker"
} |
mysql: updating record gives "Truncated incorrect DOUBLE value" error
Not sure why it's happening:
mysql_query("update items set photoids=photoids+',$newphotoid' where id='$row[id]'");
photoids cell is initially empty, but command is going through the cycle to populate with photoids red through scandir().
$newphotoid for sure exists and always unique as well as $row[id].
Completely lost. Please help! | What is the field type of the `photoids` field? Right now it appears you're trying to assign a STRING to that field, by adding multiple comma-separated values to it. If it's a float/double field, then this "string" value will be truncated/invalid.
e.g if the photoids is a float and contains "3.14159265", then you're trying to do
photoids = photoids + ',1234567'
photoids = 3.14159265 + ',1234567'
photoids = 3.14159265 + 0
resulting in:
photoids = 3.14159265 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "php, mysql"
} |
How do I name a list while generating numbers on the fly?
I use this code in python37 and it generates numbers in the list, but I would also like it to create this name along with it for the list name.
The code just does this:
[1,2,3,4]
This is the name I hoping for to add it to it on the fly:
lst1z
Here is the result for what I hope someone can edit the code to make it do this:
lst1z = [1,2,3,4]
So here is my code Thanks:
composites=[]
n = int(input("Enter any number : "))
positive_n = abs(n)
for num in range(positive_n+1):
if num > 1:
for i in range(1, num,1):
if (num % i) == 0:
if n > 0:
composites.append(num)
else:
composites.append(-num)
break
print ("\ncomposites from", int(positive_n / n), " to ", n, "\n", composites) | composites=[]
n = int(input("Enter any number : "))
positive_n = abs(n)
for i,num in enumerate(range(positive_n+1)):
if num > 1:
for i in range(1, num,1):
if (num % i) == 0:
if n > 0:
composites.append(num)
else:
composites.append(-num)
break
#If all you need is to create vairalble and print, you can simply do it as follows:
list1z = composites
print("\ncomposites from {} to {} \n list1z = {}".format(int(positive_n/n), n, list1z))
print ("\ncomposites from", int(positive_n / n), " to ", n, "\n", composites) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "python, list"
} |
How can i switch on LED on STM32F1 GPIO pin PA2?
How can i switch on the LED on PA2 GPIO (STM32F103C8T6), using standard registry configuration.
RCC-> APB2ENR |= (1<<2);
GPIOA->CRL |= (1<<9);
GPIOA->ODR |= (1<<3);
Does not work for me. Could you please advice where i make mistake? | As per the reference manual, the GPIOA CRL registers resets as 0x4444 4444 (See section 9.2.1 of the reference manual). When you execute the following command:
GPIOA->CRL |= (1<<9);
you are setting the MODE bits of PA2 to 10 (Output mode, max speed 2 MHz). But due to the inital register initialization, the CNF2 bits are 01, which is open-drain configuration. You should initialize PA2 with the following instead
GPIOA->CRL &= ~(0b0000<<8);
GPIOA->CRL |= (0b0010<<8);
This ensures that both MODE2 and CNF2 are both set so the pin acts as an output with a push-pull configuration | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "stm32"
} |
Printing HTTP status code with requestsed url
I am using a tool called waybackurls which is returning a list of URLs.
waybackurls api.target.com | grep "url"
Output
Now I am trying to validate the return URL through curl. Because it returns lot of false-positive results. I am able get the http status code only
waybackurls api.target.com | grep "url" | xargs -n 1 curl -s -o /dev/null -w "%{http_code}"
Output
200
what I want output is using curl
200 >
404 >
Is it possible to get this formate with curl request?
thanks | Just check curl manual. You already put http_code, the same for url:
waybackurls api.target.com | grep "url" | xargs -n 1 curl -s -o /dev/null -w "%{http_code} > %{url_effective}\n" | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "curl"
} |
difference between context.xml and server.xml?
what is the difference between `context.xml` of Tomcat and `server.xml` of Tomcat ? If I want to add a tag like :
<Resource name="jdbc/MyDs" auth="Container" type="javax.sql.DataSource"
driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/my_database;create=true"
username="me" password="me" maxActive="20" maxIdle="10" maxWait="-1" />
where should I add it ? | The server.xml is used for server and context.xml is for application that runs on that server. There may be several context.xml files (per application) on a server but only one server.xml. | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 10,
"tags": "java, jakarta ee, tomcat"
} |
global variables in php not working
As per example below, I would expect the ouput to be "test value", why do I get "0" instead?
_File main.php_
<?php
include_once 'functions.php';
$var = '0';
test();
echo $var;
?>
_File functions.php_
<?php
function test()
{
global $var;
$var = 'test value';
}
?> | This is an alternative example. Ian commented on CappY's answer that the real function already returns a value. I assume that is why he thinks he needs a global valriable.
You don't need to (ab)use global variable to return multiple values from a function. Two alternative (and better) options are returning an array, or passing variables by reference.
Example on returning arrays:
function test() {
return array('value 1', 'value 2');
}
// Example usage
list($var1, $var2) = test();
var_dump($var1); // outputs "value 1"
var_dump($var2); // outputs "value 2"
example passing by reference
function test(&$var2) {
$var2 = 'value 2';
return 'value 1';
}
// Example usage
$var1 = test($var2);
var_dump($var1); // outputs "value 1"
var_dump($var2); // outputs "value 2" | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php, include, global variables"
} |
How to modify the precision of a datetimeoffset column?
In a sql-server database with data I have several columns with type `datetimeoffset(7)`. Now I would like to change the precision part of the type to `datetimeoffset(0)`.
Is this possible without creating a new column of the desired type/precision and renaming the column?
I take solutions using SQL Server Management Studio as well as code (or also a no it's not possible). | This should be a straightforward
alter table tab
alter column x datetimeoffset(0); | stackexchange-dba | {
"answer_score": 6,
"question_score": 1,
"tags": "sql server, sql server 2008 r2"
} |
How to prove divisibility of the difference between two numbers.
Recently I have come across a statement saying that if $x$ and $y$ are divisible by $a$, then $x - y$ is also divisible by $a$.
How can I prove this? Does it also apply to sum of $x$ and $y$ ? | If $x=aq$ and $y=ap$ then $x-y=aq-ap=a(q-p)$ by the distributive law. | stackexchange-math | {
"answer_score": 5,
"question_score": 3,
"tags": "divisibility"
} |
Exclude abandoned Code Review Response from My Work query
If a TFS Code Review was closed by the requester before the requestee(s) have a chance to respond, the Code Review Response item seems to be stuck in State=Requested, Assigned To = @Requestee.
If we have a work item query that is showing all work in the requestee's queue, the response for the abandoned code review should not appear. However, we do want to see Code Review Response items that are in State=Requested for Code Reviews that have not yet been closed.
Is there a way to modify my work item query to distinguish Code Review Response items between those that belong to active or closed Code Reviews? In both cases, their State=Requested. | We cannot change the sate, it's by design. However you can use the type of query : `Work items and direct links` to distinguish Code Review Response which the State=Requested:
* Query the `Code Review Response` items that belong to **Closed** Code Reviews :
 Code Reviews :

return value and 1 or 0
end | stackexchange-stackoverflow | {
"answer_score": 21,
"question_score": 10,
"tags": "lua, boolean"
} |
Determine file extension for image urls
Is there a reliable and fast way to determine the file extension of an image url? THere are a few options I see but none of them work consistently for images of the below format
I have tried:
new MimetypesFileTypeMap().getContentType(url)
Results in the generic "application/octet-stream" in which case I use the below two:
Files.getFileExtension
FilenameUtils.getExtension
I would like to avoid regex when possible so is there another utility that properly gets past links that have args (.jpeg?blahblah). I would also like to avoid downloading the image or connection to the url in anyway as this should be a performant call | If you can trust that the URLs are not malformed, how about this:
FilenameUtils.getExtension(URI.create(url).getPath()) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "java, java 8"
} |
ASP.NET MVC hits outputcache for every action
We are running quite a large site build with ASP.NET MVC 3 and AppFabric as a distributed caching solution. We have implemented a custom OutputCacheAdapter to use our AppFabric cluster.
We are seeing that ASP.NET calls the OutputCacheProvider.Get() method for every action, even if that action is NOT decorated with a @OutputCacheAttribute.
That isn't much of a problem if you use the default outputcacheprovider but it is when you are running an outputcacheprovider that resides on seperate machines. | It is by design that the the output cache is checked first for a cached copy of the page. If there is a cached copy, it's returned and nothing further is executed. In particular, no controller and no controller action is derived, inspected or executed. This happens only if the page is not cached.
You will need to change your cache provider so that it can quickly determine if a page can potentially be cached. Only if it is a cachable page, then it should go and check the distributed cache. This check cannot based on the `OutputCacheAttribute` as they are not available during this part of the request processing. Instead, the quick check must be made with the URL, the cookies and other HTML header information. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 7,
"tags": "asp.net mvc, outputcache"
} |
SQL Query in Apache Ignite Cache
I just started using Apache Ignite as an in-memory cache for my web application. I created a Cache and added a few key/value pairs. I didn't create any table or anything. I used the name "Content" to create the cache. I can access the data using the API get/put operations, but I was wondering whether I can use SQL to get the data. I tried to execute a few sentences but I'm not sure what table name should I use. I tried using "Content" (the name of my cache) but I get "Table does not exist" error.
"SELECT * FROM Content"
Any ideas whether this is possible or do I need to explicitly create a Table? Would that be different than creating a cache? | Yes, you need to configure SQL schema in order to run SQL queries against a cache: <
Or you can create tables using DDL (underlying caches will be created automatically in this case): < | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "ignite"
} |
access violation error when reading from 4-dimentional array
I'm storing some arrays like this:
uint8_t a[2][4][4] = {
{
{ 1, 1, 1, 1 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
},
{
{ 1, 1, 1, 0 },
{ 1, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
},
};
and, then I store an array of this arrays:
uint8_t ***data[5] = { 0, 0, (uint8_t ***)a, (uint8_t ***)b, (uint8_t ***)c};
so when I try to `cout<<data[2][0][0][1];` it should print 1 but an read access violation exception occurs. why this doesn't work? | `(uint8_t ***)a` has the compiler interpret what is pointed by (pointer converted from) `a` as `uint8_t**`, but what there actually is data in the array, say, `0x01010101` if pointers are 4-byte long. There are little chance to the number to be a valid address, so dereferencing the "pointer" will lead to Segmentation Fault.
Use correct type.
uint8_t (*data[5])[4][4] = { 0, 0, a, b, c};
Also the statement to print should be
cout<<(int)data[2][0][0][1];
otherwise, the number may be interpreted as character and something not readable may be printed. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, arrays, segmentation fault, access violation"
} |
Cocoa: How to force open a website via Safari (NOT default browser)
I know I can use `-openURL` method in NSWorkspace class to open a URL. But because of some reason, I want to open a website via Safari instead of system default browser.
How can I achieve that?
BTW, this question is about OS X, not iOS.
thank you at advance! | NSURL* url = [NSURL URLWithString: @"
[[NSWorkspace sharedWorkspace] openURLs:@[url]
withAppBundleIdentifier:@"com.apple.Safari"
options:NSWorkspaceLaunchDefault
additionalEventParamDescriptor:nil
launchIdentifiers:nil]; | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "macos, cocoa, url, safari"
} |
$(a, b) = \left\{x \in \mathbb{R}: a < x < b\right\}$ has neither minimum nor maximum.
How does one prove that $(a, b) = \left\\{x \in \mathbb{R}: a < x < b\right\\}$ has neither minimum nor maximum?
My attempt: Suppose that $\mu$ is the minimum of the set. Then $a < \mu < x < b$, since $a$ does not belong to the set. Which contradicts the minimality of $\mu$. Does this make any sense? | No, this is not good. Suppose $\mu$ is the minimum of $(a,b)$. Then look at the element $(a+\mu)/2$. Check that this element is in $(a,b)$, and that it is less than $\mu$. This contradicts the minimality of $\mu$. Try to copy this reasoning for proving that $(a,b)$ doesn't have a maximum. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "real analysis, analysis, real numbers"
} |
Send a 'Stream' over a PutAsync request
I'm trying my hand at .NET Core but I'm stuck trying to convert multipart/form-data to an application/octet-stream to send via a PUT request. Anybody have any expertise I could borrow?
[HttpPost("fooBar"), ActionName("FooBar")]
public async Task<IActionResult> PostFooBar() {
HttpResponseMessage putResponse = await _httpClient.PutAsync(url, HttpContext.Request.Body);
}
**Update:** I think I might have two issues here:
1. My input format is multipart/form-data so I need to split out the file from the form data.
2. My output format must be application-octet stream but PutAsync expects `HttpContent`. | Turns out Request has a Form property that contains a Files property that has an `OpenReadStream()` function on it to convert it into a stream. How exactly I was supposed to know that, I'm not sure.
Either way, here's the solution:
StreamContent stream = new StreamContent(HttpContext.Request.Form.Files[0].OpenReadStream());
HttpResponseMessage putResponse = await _httpClient.PutAsync(url, stream); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net core"
} |
prevent file copying not via permissions
Is there any way I can prevent a file from being copied?
I don't mean via the file system, but I mean by somthing that must change if the file was copied, like some sum or timestamp
My goal is to create an ssh key that cannot be duplicated (yes I know, use a smart card... I'm looking for an alternative).
I don't mean to actually prevent the copying, but only to be able to varify that the file is a copy | The short answer is "no".
Depending on your environment/OS/architecture/level of expertise, it may be possible to use something like Apparmour or SELinux to frustrate attempts to copy it or for it to be read except with specific programs.
If you need a private key which can't (easily) be copied, you will need to imbed it in silicon along with logic to do decryption such that the private key is never exposed – and even then it can be copied if someone is skilled enough and has access to the silicon and some very specialist hardware (that's how some Pay TV systems were hacked). | stackexchange-superuser | {
"answer_score": 2,
"question_score": 0,
"tags": "filesystems, ssh keys, timestamp, checksum"
} |
Markov Decision Process representation
I'm attempting to model a simple process using a Markov Decision Process.
Let $A$ be a set of $3$ actions : $ A \in \\{b,s\\}$. $T(s,a,s')$ represents the probability of if in state $s$ , take action $a$ and end up in state $s'$
Notation for the MDP diagram is as follows :
 = .7 $
$T(1,b,3) = .3 $
$T(1,s,4) = .9 $
$T(1,s,5) = .05 $
$T(1,s,6) = .05 $
I've tried to keep this as simple as possible to check my understanding. Are my representations & probabilities correct ? | Looks 'correct' to me, in the sense that it satisfies the requirements for being an MDP. Whether it models the underlying real-world problem correctly cannot be validated with the information given here. | stackexchange-datascience | {
"answer_score": 1,
"question_score": 2,
"tags": "machine learning, reinforcement learning, q learning, markov process"
} |
Transform Property Unsupported by Cordova
I'm building an Apache Cordova app with the Ionic framework, and building with Phonegap Build. On the main page of my app I have a couple rows of icons that look like this:
;` doesn't work on older devices. It seems like other people have the same issue.
How do I do this transform effect so that it is supported by all devices/webviews/browsers? | The problem is not with Cordova, but with the rendering engine of the webview. Try with a vendor prefixed version:
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, android, css, cordova, ionic framework"
} |
How to look for different types of files in a directory?
public List<string> MapMyFiles()
{
List<FileInfo> batchaddresses = new List<FileInfo>();
foreach (object o in lstViewAddresses.Items)
{
try
{
string[] files = Directory.GetFiles(o.ToString(), "*-E.esy");
files.ToList().ForEach(f => batchaddresses.Add(new FileInfo(f)));
}
catch
{
if(MessageBox.Show(o.ToString() + " does not exist. Process anyway?",
"Continue?", MessageBoxButtons.YesNo)
== DialogResult.Yes) { }
else
{
Application.Exit();
}
}
}
return batchaddresses.OrderBy(f => f.CreationTime)
.Select(f => f.FullName).ToList();
}
i would like to add to the array not only
> .ESY
but also
> "p-.csv"
how do i do this? | Assuming that your code works for one set of wildcards...
Then after these lines:
string[] files = Directory.GetFiles(o.ToString(), "*-E.esy");
files.ToList().ForEach(f => batchaddresses.Add(new FileInfo(f)));
Add these:
files = Directory.GetFiles(o.ToString(), "*p-.csv");
files.ToList().ForEach(f => batchaddresses.Add(new FileInfo(f))); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c#, filesystems"
} |
two or more data types in declaration
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
struct student
{
char name[30];
int roll_no;
char add[40];
char subject[15];
}
struct student p;
printf("Enter the name of student:\t");
scanf("%s",p.name);
printf("Enter the roll no. of student:\t");
scanf("%d",&p.roll_no);
printf("Enter the address of student:\t");
scanf("%s",p.add);
printf("Enter student's subject:\t");
scanf("%s",p.subject);
printf("\nThus the name of student is:%s \nHis/her roll no is :%d \n He/she lives at:%s \t and his subject is:%s",p.name,p.roll_no,p.add,p.subject);
getch();
}
The error message is---
13error: two or more data types in declaration of `p'
i am using code blocks | Put a `;` after the structure definition... | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 3,
"tags": "c, struct"
} |
I am getting error in my MYSQL stored procedure with input parameter in phpmyadmin?
I am trying to execute the following MYSQL stored procedure in SQL window in phpmyadmin:
CREATE PROCEDURE searchtoy (IN toy_no INT)
BEGIN
SELECT * FROM Toy
WHERE Toy_ID = toy_no;
END;
But I am getting the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4
Where is the mistake I am making ? It would be really helpful if the solution code is provided to fix this error. | try changing the delimiter to // or something else and it will work fine the code stops compiling after getting confused over the ; of select as the delimiter enter image description here | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, stored procedures, phpmyadmin"
} |
"417: Expectation Failed" on HTTPPost
Very similarly to the Expect Continue problem C# described here, HTTP POST Returns Error: 417 "Expectation Failed.", I was getting an "Expectation Failed" error from the server I was trying to POST to with a HttpPost object in Android. | The equivalent fix to prevent the request from using "expect continue" seems to be this:
httpPostInstance.getParams().setParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE,
Boolean.FALSE);
I found this at < under 1.6.1. | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 4,
"tags": "android, http post"
} |
db2 stored procedure format
I'm using db2 and SQuirreL SQL
I'm trying to create a stored procedure with a simple select statement inside of it. When I omit the select statement in the following below and run the code, the procedure is created. Also this procedure can be dropped and called.
CREATE PROCEDURE test_procedure
LANGUAGE SQL
BEGIN
END
When I add in the select statement, I get Error: DB2 SQL Error: SQLCODE=-102, SQLSTATE=42601,...
CREATE PROCEDURE test_procedure
LANGUAGE SQL
BEGIN
SELECT column_name FROM table_name
END
If you go to IBM iseries information center is says:
SQL0104 SQLCODE -104 SQLSTATE 42601
Explanation: Token &1 was not valid. Valid tokens: &2\. | It appears that I wasn't given the right permissions to execute the stored procedure. SQL0551N This link explains more about the issue. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "sql, stored procedures, db2, squirrel sql"
} |
Python - Same if statement multiple times in one code block
Consider this code:
def say_hi(english: bool, name: str) -> str:
if name != "":
if english:
greeting = f"Hi, {name}!"
else:
if english:
greeting = "Hey there!"
if english:
greeting = greeting + "foo bar"
if not english:
greeting = "I speak only English, sorry."
return greeting
What is the best way to optimize this code to not have 3 times the same if statmenet (`if english:`) in one block of code? Or, perhaps a different question - does this repetitive if statement code match Python PEP standards? | Why not just reverse the order of `if` statements?
def say_hi(english: bool, name: str) -> str:
if english:
if name != "":
greeting = f"Hi, {name}!"
else:
greeting = "Hey there!"
greeting = greeting + "foo bar"
else:
greeting = "I speak only English, sorry."
return greeting | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -3,
"tags": "python"
} |
a formal way of creating a UI from a set of functions?
I am working on an application that has a number of functions and features with the intention of launching it first on Android and then on iOS.
Coming from a development background with minimal design experience, I found it really hard to visualize how the application would work as a whole.
I have an idea about how each function would look on its own but when it comes to moving between screens and how to connect them is puzzling me. Is there a formal guideline or rules to help ? | There should be a couple of documents that guide you in this process, or if not then a UX designer will be quite handy.
I have found that a comprehensive "Design Framework" will cover all of the applicable standards and guidelines that are required for you to implement the functional requirements, but if not then someone will have to do the interpretation. But if it is not documented then the next person might interpret it in a completely different way (remember agile means document what you need, not that you can do without).
^2=25-z(z-1)$. The LHS is non-negative, so $z(z-1)\le25$, so $z=0,1,2,3,4$ or 5 giving LHS$=25,25,23,19,13,5$ respectively. But the LHS is a square, so the only solutions are that the number is 0 or 1. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "algebra precalculus, elementary number theory, contest math"
} |
Projecting on a std::map with std::ranges::min
Is it possible to project on a std::map? I tried to use std::ranges::min with a projection, but it seems to throw errors that I can't interpret why its not liking things.
#include <set>
#include <iostream>
#include <ranges>
#include <vector>
#include <iostream>
#include <map>
#include <algorithm>
int main()
{
std::map<int, int> usage_table;
auto lowest = std::ranges::min( std::move(usage_table),
{},
&std::map<int,int>::value_type::second );
}
I could work around it, but it would be nice if this one liner worked.
Best | Instead of `std::ranges::min` you can use `std::ranges::min_element` like this:
auto lowest = *std::ranges::min_element(std::move(usage_table),
{},
&std::map<int,int>::value_type::second);
Also, it's unclear why you are `move`ing the `map`, it doesn't seem to do anything useful. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 2,
"tags": "c++, c++20, std ranges"
} |
Require a library with configuration in CoffeeScript?
I'd like to use CoffeeScript with Nano.js, a minimalistic CouchDB module. In JavaScript, the requirements are:
var nano = require('nano')('
However, there is no documentation on how to write this in CoffeeScript?
nano = require 'nano', '
Results in:
nano = require('nano', '
Which doesn't work. | Since you are calling a function which calls a function, doing what you tried is ambiguous. Parentheses are required in CoffeeScript to resolve ambiguity. Have you tried this:
nano = require('nano')('
Or, if you really want to go without parens, you could do this:
nano = require 'nano'
nano = nano '
Or just
nano = require('nano') ' | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "javascript, coffeescript, couchdb, couchdb nano"
} |
How to get Data from specified 'Year' where the 'Year' is DATETIME Column
I would like to get every data from a table where the year is specified. But the problem is i put my date in DATETIME type.
I'm trying something like:
SELECT
*
FROM
table
WHERE
entrytime = 2017 //entrytime is datetime type.
But, it's wrong.
Is there any way to get the data or maybe a better approach ?
Thank you. | You can use year function on datetime:
SELECT *
FROM table
WHERE year(entrytime) = 2017
or better:
SELECT *
FROM table
WHERE entrytime >= '2017-01-01'
AND entrytime < '2018-01-01'
The latter can make use of index if present on the entrytime column, which can make your query run faster. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "mysql, sql, date, datetime"
} |
How do we know logistic loss is a non convex and log of logistic loss in convex?
I'm currently learning machine learning logistic regression and I'm really confused with logistic loss. I know the formula for logistic loss is $\displaystyle g(z)=\frac{1}{1+e^{-z}}$ here $z = W^TX_i$
But I've read that this is a non convex function. So we usually take logarithm of logistic loss to make it a convex function for optimization techniques like gradient descent etc..
$$J(\theta) =-\frac{1}{m}\sum_{i=1}^{m}y^{i}\log(h_\theta(x^{i}))+(1-y^{i})\log(1-h_\theta(x^{i}))$$ $$h_\theta(x^i) = \frac{1}{1+e^{-z}}$$
How can we know if a functions/loss is convex or non convex? Why are we taking log for logistic loss? How can that makes the loss function convex? | $g$ is not convex: consider the points $0,1,N$ where $N$ is a positive integer $>1$. We have $1=\frac 1 N (N)+(1-\frac 1 N) 0$. If $g$ is convex then we would have $g(1) \leq \frac 1 N g(N)+(1-\frac 1 N)g(0)$. If you let $N \to \infty$ in this you get the contradiction that $e \leq 1$.
$\log g$ is also not convex. It is concave. So $-\log\, g$ is convex. To see this write $-\log\, g$ as $-\log \, \frac {e^{x}} {1+e^{x}}=-x +\log \, (1+e^{x})$. it is easy to calculate the second derivative of the function and show that it is positive. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "optimization, convex optimization, partial derivative, machine learning, logistic regression"
} |
C# - How to manage ProgressEvent while Reading(iterating through) a MemoryStream?
I am writing a ClassLibrary which will Read a `MemoryStream` and again on the next Method it will Write to Another `MemoryStream`..
What I am trying to do is to provide `"something"` which will Handle Progress Events while performing both the Reading and Writing loops...
the Reading and Writing are not handled by the Form.. So, there is no way of updating the ProgressBar during reading
I am not sure where to start..
So I am asking for some suggestions and explanation! | Have you looked at the `BackgroundWorker` class yet? You could wrap your read/write functionality in a `BackgroundWorker` and devise a way to raise a `ProgressChanged` event (every so many bytes read/written, etc.). Your form (UI) can subscribe to the `OnProgressChanged` event that would update the progress of a progress bar or something.
**EDIT:** This is a very generalized description of the actual work you would need to complete. But all of the tiny things needed to set up an asynchronous background worker are pretty well explained in the above link. The hardest part for you will be incorporating the reading/writing of `MemoryStream`s, and figuring out the calculation of progress. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, progress bar, memorystream"
} |
React: How to inject React component into body?
I have a React component that I want to inject into the DOM. This is because my JS will be loaded through a script tag by other website owners, not loaded onto a SPA under my control.
What I want to do is append my `Root` component into the `body` of the webpage.
If I do something like this, then it replaces all the contents of my body, which is not what I want.
import React from "react";
import ReactDOM from "react-dom";
class Root extends React.Component {
render() {
return <div>heyyyyyyy</div>;
}
}
if (!module.parent) {
ReactDOM.render(<Root />, document.querySelector("body")); // <-- wrong
}
I want something like `document.querySelector("body").appendChild(<Root />)`. Is this possible? | If you opt for a one-liner :
ReactDOM.render(
<Root />,
document.body.appendChild(document.createElement("DIV"))
)
* * *
## Running Example:
class Root extends React.Component {
render() {
return <div>It works!</div>;
}
}
ReactDOM.render(
<Root />,
document.body.appendChild(document.createElement("DIV"))
)
<script src="
<script src="
<body></body> | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 11,
"tags": "javascript, reactjs"
} |
How did Drago Bludvist tame a Bewilderbeast?
In the sequel, Drago was
> controlling an Alpha dragon.
AFAIK, he kind of had a scary aura that could tame smaller dragons, and dragons only respond to those with significant power.
**So how did he tame that gigantic beast when it was shown that**
> **it takes an Alpha to take an Alpha down?** | From HTTYD Website:
> Found as a hatchling during one of Drago Bludvist's earliest conquests, this particular Bewilderbeast suffered the misfortune of being raised by a madman. | stackexchange-scifi | {
"answer_score": 10,
"question_score": 7,
"tags": "how to train your dragon"
} |
How can I check whether my RDD or dataframe is cached or not?
I have created a dataframe say df1. I cached this by using df1.cache(). How can I check whether this has been cached or not? Also is there a way so that I am able to see all my cached RDD's or dataframes. | You can call `getStorageLevel.useMemory` on the Dataframe and the RDD to find out if the dataset is in memory.
For the Dataframe do this:
scala> val df = Seq(1, 2).toDF()
df: org.apache.spark.sql.DataFrame = [value: int]
scala> df.storageLevel.useMemory
res1: Boolean = false
scala> df.cache()
res0: df.type = [value: int]
scala> df.storageLevel.useMemory
res1: Boolean = true
For the RDD do this:
scala> val rdd = sc.parallelize(Seq(1,2))
rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[1] at parallelize at <console>:21
scala> rdd.getStorageLevel.useMemory
res9: Boolean = false
scala> rdd.cache()
res10: rdd.type = ParallelCollectionRDD[1] at parallelize at <console>:21
scala> rdd.getStorageLevel.useMemory
res11: Boolean = true | stackexchange-stackoverflow | {
"answer_score": 21,
"question_score": 22,
"tags": "apache spark"
} |
Fixed points of an involution
Let $V=\mathbb C^{2n}$ with the standard basis $\\{e_1,e_2, \cdots , e_{2n}\\}$ and let $\sigma$ be the involution $e_i \mapsto -e_{2n+1-i}$. This induces an involution of the Grassmannian $G(n,2n)$ of $n$ dimensional subspaces of $\mathbb C^{2n}$. Then what are the fixed points of this involution ? Does it have a nice structure as a projective variety ? | In general, the fixed points of any map of the Grassmannian induced by a diagonalizable linear transformation is just a union of products of Grassmannians in the eigenspaces. Any subspace $V$ fixed by a diagonalizable transformation $A$ is the sum of the intersections of $V$ with the eigenspaces of $A$ (since the projection to each eigenspace is a polynomial in $A$). If we fix the dimension of each of these intersections, we get a map to the product of Grassmannians of the eigenspaces, which is obviously an isomorphism.
In this case, $\mathbb{R}^{2n}$ is the sum of the 1 and -1 eigenspaces, both having dimension $n$. Thus, the fixed points are a disjoint union of $Gr(k,n)\times Gr(n-k,n)$ for all $0\leq k\leq n$. | stackexchange-mathoverflow_net_7z | {
"answer_score": 9,
"question_score": 9,
"tags": "ag.algebraic geometry, dg.differential geometry, rt.representation theory, projective geometry"
} |
How can i play a sound via to AS3?
What is the ActionScript 3 code that will play a sound from the library when a function is executed? | soundClip = new Sound();
soundClip.load(new URLRequest("path"));
soundClip.addEventListener(Event.COMPLETE, soundLoaded);
soundClip.addEventListener(ProgressEvent.PROGRESS, soundLoading);
function soundLoaded(e:Event) {
soundClip.play();
}
function soundLoading(e:Event) {
//do something else
}
it's like a movieclip . | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "actionscript 3, audio"
} |
Remove row only if all values are 0 or NA
If I have a row which consists of say:
0 NA 0 NA 0 NA NA
0 1 0 0 0 1 0
0 NA 1 0 0 0 0
I want to get rid of only the first row and not the second or third ones, which have at least one non-zero character. How would I do this?
I've checked for subsetting with the `is.na` function, but that removes any row which has a `NA` value. I also can't change the dataset itself, because 0 sometimes means something. | I'd avoid `apply(m,1,...)` as it will be slow on any reasonably large data. `rowSums` is usually good for these kind of tasks:
m[rowSums(m != 0, na.rm=TRUE) > 0,]
# V1 V2 V3 V4 V5 V6 V7
#[1,] 0 1 0 0 0 1 0
#[2,] 0 NA 1 0 0 0 0
Where `m` was:
m <- as.matrix(read.table(text="0 NA 0 NA 0 NA NA
0 1 0 0 0 1 0
0 NA 1 0 0 0 0")) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "r"
} |
Entity object to connect to 2 databases
Is it possible for an entity object to connect to 2 databases? | No, the model is based on a single database. If you need data from another database (assuming SQL Server), create a view against the other database and import the view into your model. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, entity framework"
} |
Compiler errors: Installing odeint properly
I am trying to get the package odeint working. I am on ubuntu using g++.
I found this question: How to install a header-only (odeint) library in linux?
I downloaded the boost libraries that include odeint, and extract the boost map to /usr/include. When I compile any of the examples on the odeinit website, I get a huge list of errors. What am I doing wrong?
There was no boost map previously present in /usr/include, and as far as I know, boost wasn't installed. | I was able to fix this by removing the odeint folder and odeint.hpp file from the boost installation and replacing them with those from the odeint page. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c++"
} |
Firebase Authentication Trigger : How to get the domain name
I am using a **Firebase Auth widget** on two different domains - abc.com and abc.in . When a new user is created, I am using a trigger to create a db entry. I want to store the domain information to know through which website did the user sign up (abc.com or abc.in).
exports.createAccountDocument = functions.auth.user().onCreate((user,context) => {
// Find whether user signed up on abc.com or abc.in
}) | I don't believe the originating URL is built into the onCreate method. See the documentation:
* <
But you could write your own function that passes `window.location.href` from the front end to get the URL from the browser when your user signs up, and attach that information to the user's database entry. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "firebase, firebase authentication, google cloud functions"
} |
javascript: toggle a button's behavior after click
I have a timer. I want one but could use to Start/Pause/Resume. Here is the code
Is it something like
toggleButton.click(function(){
if (){
Clock.start();
self.click(function(){
Clock.pause();
});
} else if (){
Clock.pause();
self.click(function(){
Clock.resume();
})
} else{
Clock.resume();
self.click(function(){
Clock.pause();
})
}
});
It seems working, but I get error in Firebug:
`TypeError: self.click is not a function`
`self.click(function(){` | `**Fiddle Demo**`
replace `self` with `$(this)`
Read this keyword | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "javascript, jquery"
} |
How to configure jmf in net beans
I am doing video capturing through webcam using jmf. i am very new to this and dont know how to use jmf.
I downloaded and installed jmf,it detects my video devise but now i want to run java code to detect the same.
Please help. | You have to download the jar files of JMF ,and add these jar at the library .Here is the Link of example code for detecting the webcam using java code :
Click Here
Please Check this, it works.I have tried this example it is very good. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, netbeans, jmf"
} |
What do these two C warnings mean exactly?
have the following C code:
typedef void*(m3_func)(void);
#define NULL ((void*)0)
char* lolinfo()
{
return "You got the additional info! :D";
}
m3_func** m3_funcs() {
return (m3_func**) {
(m3_func*)(&lolinfo), // warning #1
NULL
}; // warning #2
}
I'm getting these warnings:
* /home/lk/proj/m3/m3_lolauncher/lolauncher.c(0,0): Warning: **initialization from incompatible pointer type** (m3_lolauncher)
* /home/lk/proj/m3/m3_lolauncher/lolauncher.c(0,0): Warning: **excess elements in scalar initializer** (m3_lolauncher)
I dont understand the first one as i cast correctly?
I've never seen the second one... | it seems your sample code is not valid C.
if i understand your code, the `m3_funcs()` function should return a NULL terminated array of function pointers. you are actually trying to use an initializer (`{...}`) to declare an array and return it right away. but i don't think you can use an initializer outside of a variable declaration... also, note that this "variable" would exists only in the context of the `m3_funcs()` call, so the address that might eventually be returned would no more be valid after the function has returned.
the correct way to implement such a feature is to have a static global variable, and return its address:
static m3_func *m3_funcs_array[] = {(m3_func *)&lolinfo, NULL};
m3_func ** m3_funcs()
{
return &m3_funcs_array;
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c, warnings, function pointers"
} |
Ordering queryset by distance relative to a given position
I have a model containing latitude and longitude information as FloatFields.
class Trader(models.Model):
latitude = models.FloatField()
longitude = models.FloatField()
I would like to order this model by an increasing distance from a given position(lat, lon) but can't seem to do so using F() expressions (using haversine library, I haven't succeeded in transforming them into float numbers)
Trader.objects.all().annotate(distance=haversine((lat, lon), (float(F('latitude')), float(F('longitude'))))).order_by('distance')
This query throws the following TypeError :
float() argument must be a string or a number
I have also tried using ExpressionWrapper with a FloatField() as output_field argument, without success.
How could I achieve that ?
Thank you in advance for any help ! | Func is new in Django 1.8.
from django.db.models import Func, F
class Sin(Func):
function = 'SIN'
class Cos(Func):
function = 'COS'
class Acos(Func):
function = 'ACOS'
class Radians(Func):
function = 'RADIANS'
radlat = Radians(latitude) # given latitude
radlong = Radians(longitude) # given longitude
radflat = Radians(F('latitude'))
radflong = Radians(F('longitude'))
Expression = 3959.0 * Acos(Cos(radlat) * Cos(radflat) *
Cos(radflong - radlong) +
Sin(radlat) * Sin(radflat))
Trader.objects.annotate(distance=Expression).order_by('distance')
Based on this post. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 6,
"tags": "python, mysql, django, orm, geospatial"
} |
Is it possible to change the window title bar of your installer using Inno Setup?
Is it possible to change the title bar of your installer using Inno Setup?
By default is:
AppName=My Program
and when you run the setup in the title bar appears:
> Setup - My Program
Is it possible to hide the word _"Setup"_? | In the InnoSetup installation folder there's a `default.isl` file, open that file in a text editor, find the `SetupWindowTitle` entry and change the right side from `Setup - %1` to only `%1`. Also repeat the process for additional languages you use in the setup, you'll find the matching '.isl' files in the 'Languages' folder. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 11,
"tags": "inno setup, titlebar"
} |
Setting up Data Level Application Alerts in SQL Server
Solutions are available for providing alerts when any job fails in SQL Server.
Is there any solution available for setting up data level alerts - for e.g.
1. if data hasn't updated in USER tables for lets say 2 hours, we get an ALERT
2. if any USER table, specific column lets say has aggregate of more than 100% (which is not right) then we get an alert
3. if any specific column which should not have value (lets say greater than 10), then we get an alert
We can create a table for this type of alerts and then run may be any SSIS package or TSQL every 15 mins - and anything which doesnt match the benchmark value set for alerts we get email.
Is any aware of any solution developed for this type of need
Regards | No, there is not any built-in feature that does exactly this. I'm also not aware of an off-the-shelf product that does what you're looking for.
However, based on the description of your requirements, it seems like a SQL Server Agent job would work really well!
Set up an agent job that runs every 15 minutes, has steps that run the different checks you're interested in, and sends emails to your support team using `sp_send_dbmail`.
To get started, find the "SQL Server Agent" node in SSMS, right click on "Jobs," and choose "New Job." There's a detailed walkthrough of all the options here: Create a Job | Microsoft Docs | stackexchange-dba | {
"answer_score": 0,
"question_score": 0,
"tags": "sql server"
} |
iOS8 Cannot hide cancel button on search bar in UISearchController
My goal is to prevent the cancel button from appearing in a search bar in a UISearchController. I started with Apple's Table Search with UISearchController sample code and hid the cancel button as seen in the code snip below. However, when the user taps in the text field, the cancel button still appears. Any help?
override func viewDidLoad() {
super.viewDidLoad()
resultsTableController = ResultsTableController()
searchController = UISearchController(searchResultsController: resultsTableController)
searchController.searchResultsUpdater = self
searchController.searchBar.sizeToFit()
tableView.tableHeaderView = searchController.searchBar
searchController.searchBar.delegate = self
//Hide cancel button - added by me
searchController.searchBar.showsCancelButton = false
... | I think there are three ways of achieving that:
1. Override **searchDisplayControllerDidBeginSearch** and use the following code:
> `searchController.searchBar.showsCancelButton = false`
2. Subclass UISearchBar and override the layoutSubviews to change that var when the system attempts to draw it.
3. Register for keyboard notification **UIKeyboardWillShowNotification** and apply the code in point **1.**
Of course can always implement your search bar. | stackexchange-stackoverflow | {
"answer_score": 21,
"question_score": 22,
"tags": "ios, swift, ios8, uisearchbar, uisearchcontroller"
} |
Install [java library] in Eclipse
I just downloaded Eclipse several hours ago, and needed to add Java3D to the classpath. Installing it went without a hitch, but Eclipse can't seem to find the documentation folders so that it can give super-IDE functionality, such as autocomplete and method signatures.
While I know how I would add them individually, this lead me to the question; what is the "correct" way to install a Java library in Eclipse? Is there a special directory format I should follow? Is there a plugin that already did this for me? (The answer to that is yes, but I don't know how to use it, or whether or not it's appropriate).
Thanks!
**Edit 1:** It seems to me that someone down-voted the question. May I ask why?
**Edit 2:** So after monkeying around with the JARs, it seems that manually setting the doc path for each JAR in the library seems to be the least-error prone way. | when you add a .JAR(library) to your project in the LIBRARIES tab for your project, you have the option of attaching the javadoc directory for the jar.
So, go to the LIBRARIES tab of the "java build path" for your projects. select your jar. expand the (+) sign and you will see that you can set the javadoc. path.
good luck, | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 9,
"tags": "java, eclipse, configuration"
} |
beginBitmapFill and optimization as3, flash
Sorry for the broken English - Google translator. As written in the optimization tips - rasterized vector objects preferable. If you create multiple bitmaps and invest in them a link to a bitmapData, the memory does not increase. What happens when beginBitmapFill repeat option is set to true? All repeats refer to a single cell with the pixels in the memory? And another question - in terms of optimization, beginBitmapFill considered as a bitmap? | If you instantiate any object it will consume some amount of memory. If you are creating new Bitmaps and reusing the same `BitmapData`, it will consume some amount of memory. When `beginBitmapFill` `repeat` option is set to true, it copies the passed bitmap data to fill empty space. That bitmap data is stored alongside the object, and is reused whenever you transform your object to fill accordingly.
When you use `beginBitmapFill` the object is still treated and rendered as a vector. You can change it to `sprite.cacheAsBitmap = true;` if you want it to be rendered as a bitmap.
* * *
Adobe on `cacheAsBitmap`:
> If set to true, Flash runtimes cache an internal bitmap representation of the display object. This caching can increase performance for display objects that contain complex vector content. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "actionscript 3, flash"
} |
Swift: Trying to update NSTextField in a loop, but it only gets the last value
My very simple program is looping through an array to export several files. While it's in the loop, I'd like it to update a text field to tell the user which file is currently exporting. Code looks like this:
for item in filesArray {
var fileName = item["fileName"]
fileNameExportLabel.stringValue = "Exporting \(fileName).ext"
println("Exporting \(fileName).ext")
//--code to save the stuff goes here--
}
What happens is: `println` works correctly, throwing out a message for each file, but the label called `fileNameExportLabel` is only updated when the last file has been exported, so it's blank during the whole loop and gets the last file name once the loop reaches the end.
Any Idea? I'm a total noob here, I'm wondering if the NSTextField needs a command to be updated, similarly to a table view.
Thanks in advance! | Your loop is running on the main thread. The UI updates won't happen until your function finishes. Since this is taking a long time, you should do this on a background thread and then update the textfield on the main thread.
Try this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
for item in filesArray {
var fileName = item["fileName"]
// Update the text field on the main queue
dispatch_async(dispatch_get_main_queue()) {
fileNameExportLabel.stringValue = "Exporting \(fileName).ext"
}
println("Exporting \(fileName).ext")
//--code to save the stuff goes here--
}
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "cocoa, for loop, swift, nstextfield"
} |
не отображаются русские буквы в pandas IPython и Jupyter Notebook
здравствуйте. прошу подсказать. ввожу
df = pd.read_csv(r'C:\1.csv',encoding='utf-8')
и после
df.head()
выводит крякозябры как это исправить? | **UPDATE:** ваш "CSV" файл является XLSX файлом на самом деле:
In [122]: pd.read_excel(r'D:\download\1.csv').loc[:1]
Out[122]:
Дата покупки Сумма заказа, $ Адрес покупателя Категория товара Unnamed: 4 Unnamed: 5 \
0 Fri Jun 03 2016 17:15:15 GMT+0000 (UTC) 4.0 Обл. Ростовский Р-он д., RU Часы NaN NaN
1 NaN NaN NaN NaN NaN NaN
Unnamed: 6
0 NaN
1 NaN
* * *
Попробуйте другие кодировки:
df = pd.read_csv(r'C:\1.csv',encoding='cp1251')
или
df = pd.read_csv(r'C:\1.csv',encoding='cp866') | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "python, кодировка, pandas, кириллица"
} |
What is a word meaning "to ask"?
I've needed to use a word "to ask" recently, and the word I decided on was []{}. But I have strong doubts that this is actually the right word to use in a situation such as this:
> I would like to ask you something. (e.g. about my name, about what time it is)
Is there a better word to use than []{} for "ask" in this case? I've heard of []{}, but in both cases I can't find anything on how to use either of them in an actual sentence. | Without a doubt, the single most natural verb choice among us native speakers is:
> []{} (sometimes written as )
= "Can I ask you a question?" More literally, "There is something I want to ask, OK?"
= "Can I ask you a question?" (Literally.)
[]{}[]{} = "Ask me anything!"
, though some J-learners seem to use it as if it were the default verb, is actually too big a word for everyday conversations. They should know that it sounds pretty formal.
is used much more often than by native speakers but we definitely use more often than in informal situations. | stackexchange-japanese | {
"answer_score": 11,
"question_score": 4,
"tags": "word choice"
} |
Looking for instructions to Mega Bloks “Blok Bots” 9356 set
I need instructions for Mega Bloks "Blok Bots" set 9356. Can't find it on <

It has a link to a zip file with instructions from the old mega bloks site.
It contains instructions for 9356 and 9528. | stackexchange-bricks | {
"answer_score": 6,
"question_score": 2,
"tags": "instructions, clone brands"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.