id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
252,365 | Creating a TCP Client Connection with SSL | <p>I'm trying to create a TCP connection and send/read data that uses SSL, but I haven't been able to successfully accomplish this.</p>
<p>What I'd like to do is something like this:</p>
<pre><code> TcpClient _tcpClient = new TcpClient("host", 110);
BinaryReader reader =
new BinaryReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));
Console.WriteLine(reader.ReadString());
</code></pre>
<p>I haven't had any luck with it though. An exception is thrown when creating the BinaryReader.</p>
<p>Does anyone know of a simple example that does this? I'm not interested in writing the server side of this, just the client.</p> | 252,389 | 2 | 2 | null | 2008-10-31 01:33:59.557 UTC | 9 | 2013-11-28 12:20:46.593 UTC | null | null | null | Mel Green | 32,226 | null | 1 | 11 | c#|.net|ssl|tcp | 18,686 | <p>BinaryReader reads primitive data types as binary values in a specific encoding, is that what your server sends?<br>
If not use StreamReader:</p>
<pre><code>TcpClient _tcpClient = new TcpClient("host", 110);
StreamReader reader =
new StreamReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));
Console.WriteLine(reader.ReadToEnd());
</code></pre> |
626,319 | Add attributes to a simpletype or restriction to a complextype in Xml Schema | <p>The problem is as follows:</p>
<p>I have the following XML snippet:</p>
<pre><code><time format="minutes">11:60</time>
</code></pre>
<p>The problem is that I can't add both the attribute and the restriction at the same time. The attribute format can only have the values minutes, hours and seconds. The time has the restriction pattern <code>\d{2}:\d{2}</code></p>
<pre><code><xs:element name="time" type="timeType"/>
...
<xs:simpleType name="formatType">
<xs:restriction base="xs:string">
<xs:enumeration value="minutes"/>
<xs:enumeration value="hours"/>
<xs:enumeration value="seconds"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="timeType">
<xs:attribute name="format">
<xs:simpleType>
<xs:restriction base="formatType"/>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</code></pre>
<p>If I make a complex type of timeType, I can add an attribute, but not the restriction, and if I make a simple type, I can add the restriction but not the attribute. Is there any way to get around this problem. This is not a very strange restriction, or is it?</p> | 626,385 | 2 | 0 | null | 2009-03-09 13:52:36.933 UTC | 16 | 2020-03-20 22:39:20.213 UTC | 2020-03-20 22:39:20.213 UTC | null | 3,892,615 | Ikke | 20,261 | null | 1 | 68 | xsd|restriction | 60,593 | <p>To add attributes you have to derive by extension, to add facets you have to derive by restriction. Therefore this has to be done in two steps for the element's child content. The attribute can be defined inline:</p>
<pre><code><xsd:simpleType name="timeValueType">
<xsd:restriction base="xsd:token">
<xsd:pattern value="\d{2}:\d{2}"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:complexType name="timeType">
<xsd:simpleContent>
<xsd:extension base="timeValueType">
<xsd:attribute name="format">
<xsd:simpleType>
<xsd:restriction base="xsd:token">
<xsd:enumeration value="seconds"/>
<xsd:enumeration value="minutes"/>
<xsd:enumeration value="hours"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</code></pre> |
315,846 | Why null cast a parameter? | <p>When and why would somebody do the following:</p>
<pre><code>doSomething( (MyClass) null );
</code></pre>
<p>Have you ever done this? Could you please share your experience?</p> | 315,853 | 2 | 3 | null | 2008-11-24 23:16:42.76 UTC | 23 | 2019-09-29 00:34:08.853 UTC | 2019-09-29 00:34:08.853 UTC | null | 2,644 | pek | 2,644 | null | 1 | 82 | java|null | 20,281 | <p>If <code>doSomething</code> is overloaded, you need to cast the null explicitly to <code>MyClass</code> so the right overload is chosen:</p>
<pre><code>public void doSomething(MyClass c) {
// ...
}
public void doSomething(MyOtherClass c) {
// ...
}
</code></pre>
<p>A non-contrived situation where you need to cast is when you call a varargs function:</p>
<pre><code>class Example {
static void test(String code, String... s) {
System.out.println("code: " + code);
if(s == null) {
System.out.println("array is null");
return;
}
for(String str: s) {
if(str != null) {
System.out.println(str);
} else {
System.out.println("element is null");
}
}
System.out.println("---");
}
public static void main(String... args) {
/* the array will contain two elements */
test("numbers", "one", "two");
/* the array will contain zero elements */
test("nothing");
/* the array will be null in test */
test("null-array", (String[])null);
/* first argument of the array is null */
test("one-null-element", (String)null);
/* will produce a warning. passes a null array */
test("warning", null);
}
}
</code></pre>
<p>The last line will produce the following warning:</p>
<blockquote>
<p>Example.java:26: warning: non-varargs
call of varargs method with inexact
argument type for last parameter;<br />
cast to <code>java.lang.String</code> for a varargs
call<br />cast to <code>java.lang.String[]</code> for a
non-varargs call and to suppress this
warning</p>
</blockquote> |
2,919,584 | Override number of parameters of pure virtual functions | <p>I have implemented the following interface:</p>
<pre><code>template <typename T>
class Variable
{
public:
Variable (T v) : m_value (v) {}
virtual void Callback () = 0;
private:
T m_value;
};
</code></pre>
<p>A proper derived class would be defined like this:</p>
<pre><code>class Derived : public Variable<int>
{
public:
Derived (int v) : Variable<int> (v) {}
void Callback () {}
};
</code></pre>
<p>However, I would like to derive classes where <code>Callback</code> accepts different parameters (eg: <code>void Callback (int a, int b))</code>.
Is there a way to do it?</p> | 2,920,576 | 5 | 5 | null | 2010-05-27 08:35:42.147 UTC | 3 | 2010-05-27 14:09:02.2 UTC | 2010-05-27 08:47:53.96 UTC | null | 222,529 | null | 222,529 | null | 1 | 29 | c++|interface|virtual|overloading | 47,503 | <p>This is a problem I ran in a number of times.</p>
<p>This is impossible, and for good reasons, but there are ways to achieve essentially the same thing. Personally, I now use:</p>
<pre><code>struct Base
{
virtual void execute() = 0;
virtual ~Base {}
};
class Derived: public Base
{
public:
Derived(int a, int b): mA(a), mB(b), mR(0) {}
int getResult() const { return mR; }
virtual void execute() { mR = mA + mB; }
private:
int mA, mB, mR;
};
</code></pre>
<p>In action:</p>
<pre><code>int main(int argc, char* argv[])
{
std::unique_ptr<Base> derived(new Derived(1,2));
derived->execute();
return 0;
} // main
</code></pre> |
2,662,508 | HTML 4, HTML 5, XHTML, MIME types - the definitive resource | <p>The topics of HTML vs. XHTML and XHTML as text/html vs. XHTML as XHTML are quite complex. Unfortunately it's hard to get a complete picture, since information is spread mostly in bits and pieces around the web or is buried deep in W3C tech jargon. In addition there's some misinformation being circulated. I propose to make this the definitive SO resource about the topic, describing the most important aspects of:</p>
<ul>
<li>HTML 4</li>
<li>HTML 5</li>
<li>XHTML 1.0 as text/html, application/xml+xhtml</li>
<li>XHTML 1.1 as application/xml+xhtml</li>
</ul>
<p>What are the practical implications of each?<br>
What are common pitfalls?<br>
What is the importance of proper MIME types for each?<br>
How do different browsers handle them?</p>
<p>I'd like to see one answer per technology. I'm making this a community wiki, so rather than contributing redundant answers, please edit answers to complete the picture. Feel free to start with stubs. Also feel free to edit this question.</p> | 2,664,082 | 5 | 17 | 2010-04-18 14:20:49.58 UTC | 2010-04-18 14:20:49.58 UTC | 26 | 2019-05-23 06:45:56.403 UTC | 2010-04-18 22:51:48.757 UTC | null | 476 | null | 476 | null | 1 | 32 | xhtml|html|mime-types | 8,926 | <h2>Contents.</h2>
<ul>
<li>Terminology </li>
<li>Languages and Serializations </li>
<li>Specifications </li>
<li>Browser Parsers and Content (MIME) Types</li>
<li>Browser Support</li>
<li>Validators and Document Type Definitions </li>
<li>Quirks, Limited Quirks, and Standards modes.</li>
</ul>
<h2>Terminology</h2>
<p>One of the difficulties of describing this is clearly that the terminology within the official specifications has changed over the years, since HTML was first introduced. What follows below is based on HTML5 terminology. Also, "file" is used as a generic term to mean a file, document, input stream, octet stream, etc to avoid having to make fine distinctions.</p>
<h2>Languages and Serializations</h2>
<p>HTML and XHTML are defined in terms of a language and a serialization. </p>
<p>The language defines the vocabulary of the elements and attributes, and their content model, i.e. which elements are permitted inside which other elements, which attributes are allowed on which element, along with the purpose and meaning of each element and attribute.</p>
<p>The serialization defines how mark-up is used to describe these elements and attributes within a text document. This includes which tags are required and which can be inferred, and the rules for those inferences. It describes such things as how void elements should be marked up (e.g. “>” vs “/>”) and when attribute values need to be quoted. </p>
<h2>Specifications</h2>
<p>The HTML 4.01 specification is the current specification that defines both the HTML language and the HTML serialization.</p>
<p>The XML 1.0 specification defines a serialization but leaves the language to be defined by other specifications, which are termed “XML applications”</p>
<p>The XHTML 1.0 and 1.1 specifications are both in use. Essentially, they use the same language as HTML 4.01 but use a different serialization, one that is compatible with the XML 1.0 specification. i.e. XHTML is an XML application.</p>
<p>The HTML5 (as of 2010-04-18, draft) specification describes a new language for both HTML and XHTML. This language is mostly a superset of the HTML 4.01 language, but is intended to only be backward compatible with existing web tools, (e.g. browsers, search engines and authoring tools) and not with previous specifications, where differences arise. So the meaning of some elements are occasionally changed from the earlier specifications. Similarly, each of the serializations are backward compatible with the current tools.</p>
<h2>Browser Parsers and Content (MIME) Types</h2>
<p>When a text file is sent to a browser, it is parsed into its internal memory structure (object model). To do so it uses a parser which follows either the HTML serialization rules or XML serialization rules. Which parser it uses depends on what it deduces the content type to be, based for non-local files on the “content-type” HTTP header. Internally, once the file has been parsed, the browser treats the object model in almost the same way, regardless of whether it was originally supplied using an HTML or XHTML serialization.</p>
<p>For a browser to use its XHTML parser, the content type HTTP header must be one of the XML content types. Most commonly, this is either <code>application/xml</code> or <code>application/xhtml+xml</code>. Any non XML content type will mean that the file, regardless of whether it meets all the XHTML language and serialization rules or not, will not be processed by the browser as XHTML.</p>
<p>Using a HTTP content type of <code>text/html</code> (or in most fallback scenarios, where the content type is missing or any other non-XML type) will cause the browser to use its HTML serialization parser.</p>
<p>One key difference between the two parsers is that the HTML serialization parser performs error recovery. If the input file to the parser does not meet the HTML serialization rules, the parser will recover in ways reverse engineered from previous browsers and carry on building its object model until it reaches the end of the file. HTML5 contains the first normative definition of the recovery but no mainstream browser has shipped an implementation of the algorithm enabled in a release version as of 2010-04-26.</p>
<p>In contrast, the XML serialization parser, will stop when it encounters anything that it cannot interpret as XML (i.e. when it discovers that the file is not XML well-formed). This is required of parsers by the XML 1.0 specification.</p>
<h2>Browser Support</h2>
<p>Most modern browsers contain support for both an HTML parser and an XML parser. However, in Microsoft Internet Explorer versions 8.0 and earlier, the XML parser cannot directly create an object model for rendering as an HTML page. The XML structure can, however be processed with an XSLT file to create a stream which in turn be parsed using the HTML parser to create a object model that can be rendered.</p>
<p>Starting with Internet Explorer 9 Platform Preview, XHTML supplied using an XML content type can be parsed directly in the same way as the other modern browsers.</p>
<p>When their XML parsers detect that their input files are not XML well-formed, some browsers display an error message, and others show the page as constructed up to the point where the error was detected and some offer the user the opportunity to have the file re-parsed using their HTML parser.</p>
<h2>Validators and Document Type Definitions</h2>
<p>HTML and XHTML files can begin with a Document Type Definition (DTD) declaration which indicates the language and serialization that is being used in the document. Validators, such as the one at <a href="http://validator.w3.org/" rel="noreferrer">http://validator.w3.org/</a> use this information to match the language and serialization used within the file against the rules defined in the DTD. It then reports errors based on where the rules in the DTD are violated by mark up in the file.</p>
<p>Not all HTML serialization and language rules can be described in a DTD, so validators only test for a subset of all the rules described by the specifications. </p>
<p>HTML 4.01 and XHTML 1.0 define Strict, Transitional, and Frameset DTDs which differ in the language elements and attributes that are permitted in compliant files.</p>
<p>Validators based on HTML5 such as <a href="http://validator.nu/" rel="noreferrer">validator.nu</a> behave more like browsers, processing the page according to the HTTP content type and using a non DTD-based rule set so that they catch errors that cannot be described by DTDs.</p>
<h2>Quirks, Limited Quirks, and Standards modes.</h2>
<p>Browsers do not validate the files sent to them. Nor do they use any DTD declaration to determine the language or serialization of the file. However, they do use it to guess the era in which the page was created, and therefore the likely parsing and rendering behaviour the author would have expected of a browser at that time. Accordingly, they define three parsing and rendering modes, known as Quirks mode, Limited Quirks (or Almost Standards) mode and Standards mode.</p>
<p>Any file served using an XML content type is always processed in standards mode. For files parsed using the HTML parser, if there is no DTD provided or the DTD is determined to be very old, browsers use their quirks mode. Broadly speaking, HTML 4.01 and XHTML files processed as text/html will be processed with limited quirks mode if they contain a transitional DTD and with standards mode if using a strict DTD. </p>
<p>Where the DTD is not recognised, the mode is determined by a complex set of rules. One special case is where the public and system identifiers are omitted and the declaration is simply <!DOCTYPE html>. This is known to be the shortest doctype declaration where current browsers will treat the file as standards mode. For that reason, it is the declaration specified to be used for HTML5 compliant files.</p> |
2,452,694 | JTable with horizontal scrollbar | <p>Is there any way to enable horizontal scroll-bar whenever necessary?</p>
<p>The situation was as such: I've a <code>JTable</code>, one of the cells, stored a long length of data. Hence, I need to have horizontal scroll-bar. </p>
<p>Anyone has idea on this?</p> | 2,452,758 | 5 | 0 | null | 2010-03-16 07:28:38.607 UTC | 8 | 2021-07-14 19:50:32.993 UTC | 2014-06-02 11:24:08.203 UTC | null | 418,556 | null | 188,384 | null | 1 | 45 | java|swing|jtable|jscrollpane|jscrollbar | 99,816 | <p>First, add your <code>JTable</code> inside a <code>JScrollPane</code> and set the policy for the existence of scrollbars:</p>
<pre><code>new JScrollPane(myTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
</code></pre>
<p>Then, indicate that your JTable must not auto-resize the columns by setting the <code>AUTO_RESIZE_OFF</code> mode:</p>
<pre><code>myJTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
</code></pre> |
2,943,556 | Static Block in Java | <p>I was looking over some code the other day and I came across:</p>
<pre><code>static {
...
}
</code></pre>
<p>Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?</p> | 2,943,575 | 7 | 0 | null | 2010-05-31 12:38:30.95 UTC | 98 | 2019-03-19 06:23:24.773 UTC | null | null | null | null | 200,477 | null | 1 | 335 | java|static | 206,912 | <p>It's a <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.7" rel="noreferrer">static initializer</a>. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).</p>
<p>It can be thought of as a <strong>"class constructor"</strong>.</p>
<p>Note that there are also <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.6" rel="noreferrer">instance initializers</a>, which look the same, except that they don't have the <code>static</code> keyword. Those are run <em>in addition to</em> the code in the constructor when a new instance of the object is created.</p> |
2,983,483 | create table from another table in different database in sql server 2005 | <p>I have a database "temp" with table "A". I created new database "temp2".
I want to copy table "A" from "temp" to a new table in "temp2" . I tried this statement but it says I have incorrect syntax, here is the statement:</p>
<pre><code>CREATE TABLE B IN 'temp2'
AS (SELECT * FROM A IN 'temp');
</code></pre>
<p>Here is the error:</p>
<p>Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'IN'.
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'IN'.</p>
<p>Anyone knows whats the problem?</p>
<p>Thanks in advance,</p>
<p>Greg</p> | 2,983,487 | 8 | 1 | null | 2010-06-06 07:38:07.523 UTC | 1 | 2017-08-15 10:04:26.103 UTC | 2010-06-06 10:22:16.393 UTC | null | 13,302 | null | 342,288 | null | 1 | 8 | sql-server|sql-server-2005|select|create-table | 54,307 | <p>I've not seen that syntax before. This is what I normally use.</p>
<pre><code>SELECT *
INTO temp2.dbo.B
FROM temp.dbo.A
</code></pre> |
2,963,742 | Empty constructor or no constructor | <p>I think it is not mandatory to have a default constructor in a class (C#). </p>
<p>So, in that situation shall I have an empty constructor in the class or can I skip it?</p>
<p>Is it a best practice to have an empty default constructor?</p>
<pre><code>Class test
{
public test()
{
}
......
}
</code></pre>
<p>or</p>
<pre><code>Class test
{
......
}
</code></pre> | 2,964,104 | 8 | 0 | null | 2010-06-03 06:30:43.067 UTC | 24 | 2017-02-01 15:07:20.3 UTC | 2017-02-01 15:07:20.3 UTC | null | 4,090,370 | null | 275,807 | null | 1 | 76 | c# | 59,075 | <p>If the class won't be used by third parties and you don't need an overloaded constructor, don't write an empty constructor.</p>
<p>But...</p>
<p>Imagine you already shipped the product, and third parties use your class. A few months later there's a new requirement that makes you add a constructor with an argument.</p>
<p>Now, by doing so, the C# compiler no longer generates a default constructor. If you don't add an empty constructor explicitly, the third party code will be break.</p>
<p>In my opinion, you should always define empty constructors (one liner) for public classes used by third parties.</p> |
2,493,749 | How to set a JVM TimeZone Properly | <p>I am trying to run a Java program, but it is taking a default GMT timezone instead of an OS defined timezone. My JDK version is 1.5 and the OS is Windows Server Enterprise (2007)</p>
<p>Windows has a Central timezone specified, but when I run the following program, it gives me a GMT time.</p>
<pre><code>import java.util.Calendar;
public class DateTest
{
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
System.out.println(now.getTimeZone());
System.out.println(now.getTime());
}
}
</code></pre>
<p>Here is the output</p>
<pre><code>sun.util.calendar.ZoneInfo[id="GMT",
offset=0,
dstSavings=0,
useDaylight=false,
transitions=0,
lastRule=null]
Mon Mar 22 13:46:45 GMT 2010
</code></pre>
<p>Please note that I do not want to set the timezone from the application. I want that the timezone used by JVM should be the one specified in the OS. (I am not finding this issues with other servers that have version 1.4 of JDK and Microsoft Server 2003).</p>
<p>Any thoughts would be highly appreciated.</p> | 2,493,805 | 8 | 4 | null | 2010-03-22 16:03:24.917 UTC | 32 | 2020-10-18 15:33:13.257 UTC | 2016-06-03 11:54:02.983 UTC | null | 2,405,040 | null | 197,680 | null | 1 | 151 | java|jvm|windows-server-2008|timezone|java-5 | 260,246 | <p>You can pass the JVM this param</p>
<pre><code>-Duser.timezone
</code></pre>
<p>For example</p>
<pre><code>-Duser.timezone=Europe/Sofia
</code></pre>
<p>and this should do the trick.
Setting the environment variable TZ also does the trick on Linux.</p> |
3,038,190 | Is the Windows dev environment worth the cost? | <p>I recently made the move from Linux development to Windows development. And as much of a Linux enthusiast that I am, I have to say - C# is a beautiful language, Visual Studio is terrific, and now that I've bought myself a <a href="https://rads.stackoverflow.com/amzn/click/com/B00005NIMJ" rel="noreferrer" rel="nofollow noreferrer">trackball</a> my wrist has stopped hurting from using the mouse so much.</p>
<p>But there's one thing I can't get past: the cost. Windows 7, Visual Studio, SQL Server, Expression Blend, ViEmu, Telerik, MSDN - we're talking thousands for each developer on the project! You're definitely getting something for your money - my question is, is it worth it? [Not every developer needs all the aforementioned tools - but have you ever heard of anyone writing C# code without Visual Studio? I've worked on pretty large software projects in Linux without having to pay for any development tool whatsoever.] </p>
<p>Now obviously, if you're already a Windows shop, it doesn't pay to retrain all your developers. And if you're looking to develop a Windows desktop app, you just can't do that in Linux. But if you were starting a new web application project and could hire developers who are experts in whatever languages you want, would you still choose Windows as your development platform despite the high cost? And if yes, why?</p>
<hr>
<p>UPDATE: I did not intend to start any arguments. And I gained some valuable insights from the answers/comments:</p>
<ol>
<li>The cost of setting up a dev environment in Windows does not have to be so great.</li>
<li>The cost of the dev environment is really just a drop in the bucket when compared to the cost of the developers themselves. (This doesn't help a small startup or a freelance programmer, though).</li>
</ol> | 3,038,318 | 13 | 22 | 2010-06-15 02:17:48.36 UTC | 2010-06-14 14:47:29.933 UTC | 5 | 2011-02-20 20:07:22.257 UTC | 2010-06-15 15:25:58.297 UTC | null | 1,094,969 | null | 1,094,969 | null | 1 | 48 | c#|windows|linux|development-environment | 6,074 | <p>The cost of the tools is <em>tiny</em> compared to what you spend on the developers themselves. For example, most of the tools you've mentioned are included in <a href="http://msdn.microsoft.com/en-us/subscriptions/subscriptionschart.aspx" rel="noreferrer">Visual Studio Professional with MSDN</a>, which runs about $800/year.</p>
<p>The real question, then, is whether you get any benefit from that cost. That's harder to answer, and I suspect depends on your developers and what kind(s) of software you develop. As such, it's impossible to give a blanket answer. Nonetheless, from the employer's viewpoint there's hardly enough difference between the two to notice.</p> |
2,851,015 | Convert data.frame columns from factors to characters | <p>I have a data frame. Let's call him <code>bob</code>:</p>
<pre><code>> head(bob)
phenotype exclusion
GSM399350 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399351 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399352 3- 4- 8- 25- 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399353 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399354 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
GSM399355 3- 4- 8- 25+ 44+ 11b- 11c- 19- NK1.1- Gr1- TER119-
</code></pre>
<p>I'd like to concatenate the rows of this data frame (this will be another question). But look:</p>
<pre><code>> class(bob$phenotype)
[1] "factor"
</code></pre>
<p><code>Bob</code>'s columns are factors. So, for example:</p>
<pre><code>> as.character(head(bob))
[1] "c(3, 3, 3, 6, 6, 6)" "c(3, 3, 3, 3, 3, 3)"
[3] "c(29, 29, 29, 30, 30, 30)"
</code></pre>
<p>I don't begin to understand this, but I guess these are indices into the levels of the factors of the columns (of the court of king caractacus) of <code>bob</code>? Not what I need.</p>
<p>Strangely I can go through the columns of <code>bob</code> by hand, and do</p>
<pre><code>bob$phenotype <- as.character(bob$phenotype)
</code></pre>
<p>which works fine. And, after some typing, I can get a data.frame whose columns are characters rather than factors. So my question is: how can I do this automatically? How do I convert a data.frame with factor columns into a data.frame with character columns without having to manually go through each column? </p>
<p>Bonus question: why does the manual approach work?</p> | 2,851,213 | 18 | 1 | null | 2010-05-17 16:52:02.603 UTC | 157 | 2020-08-20 10:13:49.193 UTC | 2013-01-10 22:26:57.347 UTC | null | 967,840 | null | 270,572 | null | 1 | 392 | r|dataframe | 727,544 | <p>Just following on Matt and Dirk. If you want to recreate your existing data frame without changing the global option, you can recreate it with an apply statement:</p>
<pre><code>bob <- data.frame(lapply(bob, as.character), stringsAsFactors=FALSE)
</code></pre>
<p>This will convert all variables to class "character", if you want to only convert factors, see <a href="https://stackoverflow.com/a/2853231/180892">Marek's solution below</a>.</p>
<p>As @hadley points out, the following is more concise. </p>
<pre><code>bob[] <- lapply(bob, as.character)
</code></pre>
<p>In both cases, <code>lapply</code> outputs a list; however, owing to the magical properties of R, the use of <code>[]</code> in the second case keeps the data.frame class of the <code>bob</code> object, thereby eliminating the need to convert back to a data.frame using <code>as.data.frame</code> with the argument <code>stringsAsFactors = FALSE</code>.</p> |
25,223,407 | Max length UITextField | <p>When I've tried <a href="https://stackoverflow.com/questions/24641982/how-to-you-set-the-maximum-number-of-characters-that-can-be-entered-into-a-uitex">How to you set the maximum number of characters that can be entered into a UITextField using swift?</a>, I saw that if I use all 10 characters, I can't erase the character too.</p>
<p>The only thing I can do is to cancel the operation (delete all the characters together).</p>
<p>Does anyone know how to not block the keyboard (so that I can't add other letters/symbols/numbers, but I can use the backspace)?</p> | 25,224,331 | 20 | 0 | null | 2014-08-09 21:51:01.077 UTC | 46 | 2021-11-26 10:29:49.237 UTC | 2017-05-23 12:26:20.52 UTC | null | -1 | null | 3,842,100 | null | 1 | 141 | ios|swift|uitextfield|character|max | 152,249 | <p>With Swift 5 and iOS 12, try the following implementation of <a href="https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-textfield" rel="noreferrer"><code>textField(_:shouldChangeCharactersIn:replacementString:)</code></a> method that is part of the <code>UITextFieldDelegate</code> protocol:</p>
<pre><code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 10
}
</code></pre>
<ul>
<li>The most important part of this code is the conversion from <code>range</code> (<code>NSRange</code>) to <code>rangeOfTextToReplace</code> (<code>Range<String.Index></code>). See this <a href="https://talk.objc.io/episodes/S01E80-swift-string-vs-nsstring?t=6" rel="noreferrer">video tutorial</a> to understand why this conversion is important.</li>
<li>To make this code work properly, you should also set the <code>textField</code>'s <a href="https://developer.apple.com/documentation/uikit/uitextinputtraits/2865828-smartinsertdeletetype" rel="noreferrer"><code>smartInsertDeleteType</code></a> value to <code>UITextSmartInsertDeleteType.no</code>. This will prevent the possible insertion of an (unwanted) extra space when performing a paste operation.</li>
</ul>
<hr>
<p>The complete sample code below shows how to implement <code>textField(_:shouldChangeCharactersIn:replacementString:)</code> in a <code>UIViewController</code>:</p>
<pre><code>import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField! // Link this to a UITextField in Storyboard
override func viewDidLoad() {
super.viewDidLoad()
textField.smartInsertDeleteType = UITextSmartInsertDeleteType.no
textField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 10
}
}
</code></pre> |
45,292,517 | How do I use the "group_by_window" function in TensorFlow | <p>In TensorFlow's new set of input pipeline functions, there is an ability to group sets of records together using the "group_by_window" function. It is described in the documentation here:</p>
<p><a href="https://www.tensorflow.org/api_docs/python/tf/contrib/data/Dataset#group_by_window" rel="noreferrer">https://www.tensorflow.org/api_docs/python/tf/contrib/data/Dataset#group_by_window</a></p>
<p>I don't fully understand the explanation here used to describe the function, and I tend to learn best by example. I can't find any example code anywhere on the internet for this function. Could someone please whip up a barebones and runnable example of this function to show how it works, and what to give this function?</p> | 46,252,964 | 1 | 0 | null | 2017-07-25 01:42:12.643 UTC | 8 | 2018-10-21 15:47:49.253 UTC | 2018-02-18 21:45:55.663 UTC | null | 5,098,368 | null | 5,834,938 | null | 1 | 13 | python|tensorflow|tensorflow-datasets | 4,492 | <p>For tensorflow version 1.9.0
Here is a quick example I could come up with:</p>
<pre><code>import tensorflow as tf
import numpy as np
components = np.arange(100).astype(np.int64)
dataset = tf.data.Dataset.from_tensor_slices(components)
dataset = dataset.apply(tf.contrib.data.group_by_window(key_func=lambda x: x%2, reduce_func=lambda _, els: els.batch(10), window_size=100)
iterator = dataset.make_one_shot_iterator()
features = iterator.get_next()
sess = tf.Session()
sess.run(features) # array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18], dtype=int64)
</code></pre>
<p>The first argument <code>key_func</code> maps every element in the dataset to a key.</p>
<p>The <code>window_size</code> defines the bucket size that is given to the <code>reduce_fund</code>.</p>
<p>In the <code>reduce_func</code> you receive a block of <code>window_size</code> elements. You can shuffle, batch or pad however you want.</p>
<p>EDIT for dynamic padding and bucketing using the group_by_window fucntion <a href="https://github.com/maximedb/InstaCorrect/blob/master/Model/input_functions.py" rel="noreferrer">more here</a> :</p>
<p>If you have a <code>tf.contrib.dataset</code> which holds <code>(sequence, sequence_length, label)</code> and sequence is a tensor of tf.int64:</p>
<pre><code>def bucketing_fn(sequence_length, buckets):
"""Given a sequence_length returns a bucket id"""
t = tf.clip_by_value(buckets, 0, sequence_length)
return tf.argmax(t)
def reduc_fn(key, elements, window_size):
"""Receives `window_size` elements"""
return elements.shuffle(window_size, seed=0)
# Create buckets from 0 to 500 with an increment of 15 -> [0, 15, 30, ... , 500]
buckets = [tf.constant(num, dtype=tf.int64) for num in range(0, 500, 15)
window_size = 1000
# Bucketing
dataset = dataset.group_by_window(
lambda x, y, z: bucketing_fn(x, buckets),
lambda key, x: reduc_fn(key, x, window_size), window_size)
# You could pad it in the reduc_func, but I'll do it here for clarity
# The last element of the dataset is the dynamic sentences. By giving it tf.Dimension(None) it will pad the sencentences (with 0) according to the longest sentence.
dataset = dataset.padded_batch(batch_size, padded_shapes=(
tf.TensorShape([]), tf.TensorShape([]), tf.Dimension(None)))
dataset = dataset.repeat(num_epochs)
iterator = dataset.make_one_shot_iterator()
features = iterator.get_next()
</code></pre> |
39,899,839 | Alexa Skills Kit trigger not available on drop down in AWS Lambda | <p>I'm trying to build a simple AWS Lambda function that is triggered by the Alexa Skills Kit. I am following an Amazon made tutorial on creating the skill, etc. Unfortunately, Alexa Skills Kit is not an option on the drop down menu for the "Configure Triggers" window. I've attached a photo of what is available.</p>
<p>Is there anyway to get the Alexa Skills Kit to display? Is there something wrong with my account? Any suggestions would be very helpful. I am stuck at a spot that really shouldn't be causing me any issues. I have a basic account and therefore cannot get support from Amazon.</p>
<p><img src="https://i.stack.imgur.com/XyE90.jpg" alt="Configure Triggers"></p> | 39,902,555 | 5 | 0 | null | 2016-10-06 15:19:12.293 UTC | 1 | 2018-06-25 08:23:09.95 UTC | 2017-12-29 13:11:41.987 UTC | null | 1,562,662 | null | 6,932,825 | null | 1 | 43 | amazon-web-services|triggers|aws-lambda | 16,034 | <p>I figured it out. For some reason my location defaulted to Oregon, which is not supported for ASK. Changing it to N. Virginia did the trick.</p> |
10,663,446 | POST method always return 403 Forbidden | <p>I have read <a href="https://stackoverflow.com/questions/4547639/django-csrf-verification-failed">Django - CSRF verification failed</a> and several questions (and answers) related to django and POST method. One of the best-but-not-working-for-me answer is <a href="https://stackoverflow.com/a/4707639/755319">https://stackoverflow.com/a/4707639/755319</a></p>
<p>All of the approved answers suggest at least 3 things:</p>
<ol>
<li>Use RequestContext as the third parameter of render_to_response_call</li>
<li>Add {% csrf_token %} in every form with POST method</li>
<li>Check the MIDDLEWARE_CLASSES in settings.py</li>
</ol>
<p>I've done exactly as suggested, but the error still appeared. I use django 1.3.1 (from ubuntu 12.04 repository) and python 2.7 (default from ubuntu)</p>
<p>This is my View:</p>
<pre><code># Create your views here.
from django.template import RequestContext
from django.http import HttpResponse
from django.shortcuts import render_to_response
from models import BookModel
def index(request):
return HttpResponse('Welcome to the library')
def search_form(request):
return render_to_response('library/search_form.html')
def search(request):
if request.method=='POST':
if 'q' in request.POST:
q=request.POST['q']
bookModel = BookModel.objects.filter(title__icontains=q)
result = {'books' : bookModel,}
return render_to_response('library/search.html', result, context_instance=RequestContext(request))
else:
return search_form(request)
else:
return search_form(request)
</code></pre>
<p>and this is my template (search_form.html):</p>
<pre><code>{% extends "base.html" %}
{% block content %}
<form action="/library/search/" method="post">
{% csrf_token %}
<input type="text" name="q">
<input type="submit" value="Search">
</form>
{% endblock %}
</code></pre>
<p>I've restarted the server, but the 403 forbidden error is still there, telling that CSRF verification failed.</p>
<p>I've 2 questions:</p>
<ol>
<li>How to fix this error?</li>
<li>Why is it so hard to make a "POST" in django, I mean is there any specific reason to make it so verbose (I come from PHP, and never found such a problem before)?</li>
</ol> | 10,663,500 | 8 | 0 | null | 2012-05-19 08:01:43.053 UTC | 2 | 2021-03-27 18:57:10.563 UTC | 2017-05-23 12:16:27 UTC | null | -1 | null | 755,319 | null | 1 | 20 | django|post|csrf|django-csrf | 62,869 | <p>Try putting RequestContext in the search_form view's render_to_response: </p>
<pre><code>context_instance=RequestContext(request)
</code></pre> |
10,588,644 | How can I see the entire HTTP request that's being sent by my Python application? | <p>In my case, I'm using the <code>requests</code> library to call PayPal's API over HTTPS. Unfortunately, I'm getting an error from PayPal, and PayPal support cannot figure out what the error is or what's causing it. They want me to "Please provide the entire request, headers included".</p>
<p>How can I do that?</p> | 16,630,836 | 9 | 0 | null | 2012-05-14 18:03:10.063 UTC | 128 | 2022-08-19 10:58:28.793 UTC | 2014-10-07 15:37:17.29 UTC | null | 815,724 | null | 9,161 | null | 1 | 358 | python|debugging|https|python-requests | 283,213 | <p>A simple method: enable logging in recent versions of Requests (1.x and higher.) </p>
<p>Requests uses the <code>http.client</code> and <code>logging</code> module configuration to control logging verbosity, as described <a href="https://requests.readthedocs.io/en/master/api/#api-changes" rel="noreferrer">here</a>. </p>
<h2>Demonstration</h2>
<p>Code excerpted from the linked documentation:</p>
<pre><code>import requests
import logging
# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
import http.client as http_client
except ImportError:
# Python 2
import httplib as http_client
http_client.HTTPConnection.debuglevel = 1
# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
requests.get('https://httpbin.org/headers')
</code></pre>
<h2>Example Output</h2>
<pre><code>$ python requests-logging.py
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org
send: 'GET /headers HTTP/1.1\r\nHost: httpbin.org\r\nAccept-Encoding: gzip, deflate, compress\r\nAccept: */*\r\nUser-Agent: python-requests/1.2.0 CPython/2.7.3 Linux/3.2.0-48-generic\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: application/json
header: Date: Sat, 29 Jun 2013 11:19:34 GMT
header: Server: gunicorn/0.17.4
header: Content-Length: 226
header: Connection: keep-alive
DEBUG:requests.packages.urllib3.connectionpool:"GET /headers HTTP/1.1" 200 226
</code></pre> |
31,438,112 | Bash / Docker exec: file redirection from inside a container | <p>I can't figure out how to read content of a file from a Docker container. I want to execute content of a SQL file into my PGSQL container. I tried:</p>
<pre><code>docker exec -it app_pgsql psql --host=127.0.0.1 --username=foo foo < /usr/src/app/migrations/*.sql
</code></pre>
<p>My application is mounted in <code>/usr/src/app</code>. But I got an error:</p>
<blockquote>
<p>bash: /usr/src/app/migrations/*.sql: No such file or directory</p>
</blockquote>
<p>It seems that Bash interprets this path as an host path, not a guest one. Indeed, executing the command in two times works perfectly:</p>
<pre><code>docker exec -it app_pgsql
psql --host=127.0.0.1 --username=foo foo < /usr/src/app/migrations/*.sql
</code></pre>
<p>I think that's more a Bash issue than a Docker one, but I'm still stuck! :)</p> | 31,438,298 | 4 | 1 | null | 2015-07-15 18:17:42.553 UTC | 5 | 2019-12-30 19:37:41.36 UTC | null | null | null | null | 828,414 | null | 1 | 37 | bash|docker | 24,723 | <p>Try and use a shell to execute that command </p>
<pre><code>sh -c 'psql --host=127.0.0.1 --username=foo foo < /usr/src/app/migrations/*.sql'
</code></pre>
<p>The full command would be:</p>
<pre><code>docker exec -it app_pgsql sh -c 'psql --host=127.0.0.1 --username=foo foo < /usr/src/app/migrations/*.sql'
</code></pre> |
23,317,342 | Pandas Dataframe: split column into multiple columns, right-align inconsistent cell entries | <p>I have a pandas dataframe with a column named 'City, State, Country'. I want to separate this column into three new columns, 'City, 'State' and 'Country'.</p>
<pre><code>0 HUN
1 ESP
2 GBR
3 ESP
4 FRA
5 ID, USA
6 GA, USA
7 Hoboken, NJ, USA
8 NJ, USA
9 AUS
</code></pre>
<p>Splitting the column into three columns is trivial enough:</p>
<pre><code>location_df = df['City, State, Country'].apply(lambda x: pd.Series(x.split(',')))
</code></pre>
<p>However, this creates left-aligned data:</p>
<pre><code> 0 1 2
0 HUN NaN NaN
1 ESP NaN NaN
2 GBR NaN NaN
3 ESP NaN NaN
4 FRA NaN NaN
5 ID USA NaN
6 GA USA NaN
7 Hoboken NJ USA
8 NJ USA NaN
9 AUS NaN NaN
</code></pre>
<p>How would one go about creating the new columns with the data right-aligned? Would I need to iterate through every row, count the number of commas and handle the contents individually?</p> | 23,317,595 | 3 | 0 | null | 2014-04-26 22:49:49.937 UTC | 26 | 2020-04-01 08:28:48.737 UTC | null | null | null | null | 3,186,581 | null | 1 | 59 | python|split|pandas | 114,836 | <p>I'd do something like the following:</p>
<pre><code>foo = lambda x: pd.Series([i for i in reversed(x.split(','))])
rev = df['City, State, Country'].apply(foo)
print rev
0 1 2
0 HUN NaN NaN
1 ESP NaN NaN
2 GBR NaN NaN
3 ESP NaN NaN
4 FRA NaN NaN
5 USA ID NaN
6 USA GA NaN
7 USA NJ Hoboken
8 USA NJ NaN
9 AUS NaN NaN
</code></pre>
<p>I think that gets you what you want but if you also want to pretty things up and get a City, State, Country column order, you could add the following:</p>
<pre><code>rev.rename(columns={0:'Country',1:'State',2:'City'},inplace=True)
rev = rev[['City','State','Country']]
print rev
City State Country
0 NaN NaN HUN
1 NaN NaN ESP
2 NaN NaN GBR
3 NaN NaN ESP
4 NaN NaN FRA
5 NaN ID USA
6 NaN GA USA
7 Hoboken NJ USA
8 NaN NJ USA
9 NaN NaN AUS
</code></pre> |
23,287,462 | Spring boot fails to load DataSource using PostgreSQL driver | <p>I have successfully developed a prototype using Spring Boot 1.0.2.RELEASE (was 1.0.1.RELEASE until today).</p>
<p>I have searched and searched and tried solutions like:
<a href="https://stackoverflow.com/questions/20854585/spring-boot-jdbc-datasource-autoconfiguration-fails-on-standalone-tomcat">Spring Boot jdbc datasource autoconfiguration fails on standalone tomcat</a>
<a href="https://stackoverflow.com/questions/21422664/spring-boot-spring-data-import-sql-doesnt-run-spring-boot-1-0-0-rc1">Spring Boot / Spring Data import.sql doesn't run Spring-Boot-1.0.0.RC1</a></p>
<p>They all suggests to let Spring Boot do the job.
When using H2, everything works, but when I try to switch to PostgreSQL, i get:</p>
<pre><code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.entityManagerFactory(org.springframework.orm.jpa.JpaVendorAdapter)] threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined
</code></pre>
<p>My build.gradle is as follow:</p>
<pre><code>loadConfiguration()
def loadConfiguration() {
def environment = hasProperty('env') ? env : 'dev'
project.ext.envrionment = environment
println "Environment is set to $environment"
def configFile = file('config.groovy')
def config = new ConfigSlurper("$environment").parse(configFile.toURL())
project.ext.config = config
}
buildscript {
ext {
springBootVersion = '1.0.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle- plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'
apply plugin: 'groovy'
war {
baseName = 'test'
version = '0.0.1-SNAPSHOT'
}
configurations {
providedRuntime
}
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
compile("org.springframework.boot:spring-boot-starter-thymeleaf:${springBootVersion}")
compile("org.springframework.boot:spring-boot-starter-jdbc:${springBootVersion}")
compile("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}")
compile("postgresql:postgresql:9.1-901.jdbc4")
//compile("com.h2database:h2")
testCompile("org.springframework.boot:spring-boot-starter-test:${springBootVersion}")
}
task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}
</code></pre>
<p>application.properties:</p>
<pre><code>spring.jpa.database=POSTGRESQL
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
spring.database.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost/cms
spring.datasource.username=cms
spring.datasource.password=NA
</code></pre>
<p>Removing application.properties and changing the dependency back to H2 and everything is OK. </p>
<p>I can't find where I am doing wrong :-(</p> | 23,288,174 | 5 | 0 | null | 2014-04-25 08:02:47.603 UTC | 0 | 2021-12-29 12:31:58.733 UTC | 2017-05-23 12:32:26.04 UTC | null | -1 | null | 569,897 | null | 1 | 35 | postgresql|spring-data-jpa|spring-jdbc|spring-boot | 104,171 | <p>Where did this come from: <code>database.driverClassName=org.postgresql.Driver</code>? Don't you mean <code>spring.datasource.driverClassName</code>?</p> |
41,082,702 | How to center the editor window back on the cursor in VSCode? | <p>I'm using VSCode as my text editor. I'm curious, is there a keybinding for centering the editor window on the cursor, when the window is a lot of lines below/above it such that it's not visible on the screen? I've tried looking at the default keybindings by going to <em>FIle > Preferences > Keyboard Shortcuts</em>, but I see no such options for centering the window.</p> | 41,095,414 | 4 | 0 | null | 2016-12-11 03:30:30.103 UTC | 7 | 2021-01-15 21:24:04.57 UTC | null | null | null | null | 4,077,294 | null | 1 | 29 | keyboard-shortcuts|visual-studio-code|text-editor | 10,452 | <p>There is no such keybinding / command built-in. </p>
<p>I couldn't stand that either, so I created a VSCode extension. You can find it and install it <a href="https://marketplace.visualstudio.com/items?itemName=kaiwood.center-editor-window" rel="noreferrer">here on the marketplace</a>. The default shortcut is <code>CTRL</code> + <code>L</code>.</p> |
1,851,103 | How to save a GIF on the iPhone? | <p>how can I save a GIF on the iPhone? The SDK includes only UIImageJPEGRepresentation and UIImagePNGRepresentation but nothing for GIFs or other image formats, is there a way to convert a UIImage to a GIF and save it?</p>
<p>GM</p> | 5,354,890 | 2 | 0 | null | 2009-12-05 04:04:05.657 UTC | 1 | 2011-03-18 16:21:18.823 UTC | null | null | null | null | 225,254 | null | 1 | 1 | iphone|image|image-manipulation|uiimage | 43,129 | <p>This is a library I wrote for encoding GIF images on the iPhone, if anyone reading this is interested:</p>
<p><a href="http://jitsik.com/wordpress/?p=208" rel="nofollow">http://jitsik.com/wordpress/?p=208</a></p> |
32,471,009 | What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml? | <p>While working with the android layout xml I came across <code>backgroundTint</code> attribute . I don't understand what is for. </p>
<p>Also what is <code>backgroundTintMode</code> ??</p> | 38,080,463 | 5 | 0 | null | 2015-09-09 04:39:23.96 UTC | 30 | 2020-02-16 20:49:44.08 UTC | 2016-07-10 12:12:30.527 UTC | null | 2,818,583 | null | 3,839,641 | null | 1 | 133 | android|android-layout | 159,992 | <p>I tested various combinations of <code>android:background</code>, <code>android:backgroundTint</code> and <code>android:backgroundTintMode</code>. </p>
<p><code>android:backgroundTint</code> applies the color filter to the resource of <code>android:background</code> when used together with <code>android:backgroundTintMode</code>.</p>
<p>Here are the results:</p>
<p><a href="https://i.stack.imgur.com/AlRwr.png"><img src="https://i.stack.imgur.com/AlRwr.png" alt="Tint Check"></a></p>
<p>Here's the code if you want to experiment further:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:background="#37AEE4"
android:text="Background" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:backgroundTint="#FEFBDE"
android:text="Background tint" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:background="#37AEE4"
android:backgroundTint="#FEFBDE"
android:text="Both together" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:background="#37AEE4"
android:backgroundTint="#FEFBDE"
android:backgroundTintMode="multiply"
android:text="With tint mode" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:text="Without any" />
</LinearLayout>
</code></pre> |
52,109,471 | Typescript in vue - Property 'validate' does not exist on type 'Vue | Element | Vue[] | Element[]'. | <p>I created <code>v-form</code> like this</p>
<pre><code><v-form ref="form" v-model="valid" lazy-validation>
...
<v-btn
:disabled="!valid"
@click="submit"
>
submit
</v-btn>
</v-form>
</code></pre>
<p>script:</p>
<pre><code>if (this.$refs.form.validate()) // Error is in here
</code></pre>
<p>If i just <code>console.log(this.$ref.form)</code> the validate() function is available. But why this error is coming while building?</p> | 52,109,899 | 5 | 0 | null | 2018-08-31 06:13:30.367 UTC | 22 | 2020-12-30 22:04:06.043 UTC | null | null | null | null | 7,746,570 | null | 1 | 34 | typescript|vue.js|vuetify.js | 40,378 | <h2>Solutions:</h2>
<p>Simple:</p>
<pre><code>(this.$refs.form as Vue & { validate: () => boolean }).validate()
</code></pre>
<p>Alternative <em>(use this if you reference <code>this.$refs.form</code> multiple times in your component)</em>:</p>
<pre><code>computed: {
form(): Vue & { validate: () => boolean } {
return this.$refs.form as Vue & { validate: () => boolean }
}
} // Use it like so: this.form.validate()
</code></pre>
<p>Reusable <em>(use this if you use the <code>v-form</code> component multiple times across your application)</em>:</p>
<pre><code>// In a TS file
export type VForm = Vue & { validate: () => boolean }
// In component, import `VForm`
computed: {
form(): VForm {
return this.$refs.form as VForm
}
}
</code></pre>
<hr>
<h2>Explanation:</h2>
<p>In the <code>Vue</code> template syntax, we can use the <code>ref</code> attribute on a <code>Vue</code> instance or a DOM element. If <code>ref</code> is used in a <code>v-for</code> loop, an array of <code>Vue</code> instances or DOM elements is retreived.</p>
<p>This is why <code>this.$refs</code> can either return <code>Vue | Element | Vue[] | Element[]</code>.</p>
<p>In order for <code>TypeScript</code> to know which type is being used, we need to cast the value.</p>
<p>We can either do:</p>
<p><code>(this.$refs.form as Vue).validate()</code> or <code>(<Vue>this.$refs.form).validate()</code></p>
<p>We cast it to <code>Vue</code> because <code>v-form</code> is a <code>Vue</code> instance (component) and not an <code>Element</code>.</p>
<p>My personal preference is to create a computed property which returns the <code>Vue</code> instance(s) or DOM element(s) already casted.</p>
<p>ie.</p>
<pre><code>computed: {
form(): Vue {
return this.$refs.form as Vue
}
}
</code></pre>
<hr>
<p>The <code>v-form</code> instance has a <code>validate</code> method that returns a boolean, so we need to use an intersection type literal:</p>
<pre><code>computed: {
form(): Vue & { validate: () => boolean } {
return this.$refs.form as Vue & { validate: () => boolean }
}
}
</code></pre>
<p>Then we can use it like so: <code>this.form.validate()</code></p>
<hr>
<p>A better solution would be to create a type with the intersection so that it can be reused across multiple components.</p>
<pre><code>export type VForm = Vue & { validate: () => boolean }
</code></pre>
<p>Then import it in the component:</p>
<pre><code>computed: {
form(): VForm {
return this.$refs.form as VForm
}
}
</code></pre> |
21,364,313 | Signal EOF in mac osx terminal | <p>I am stumped by the 1.5.2 question in K&R. I googled for sometime and found out that I have to supply the EOF input after entering the characters.</p>
<pre><code>long nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
return 0;
</code></pre>
<p>I tried both command-D and control-D as EOF inputs but nothing worked. Any idea how to supply the EOF for Mac OS X?</p> | 21,365,313 | 3 | 1 | null | 2014-01-26 14:02:41.687 UTC | 17 | 2022-05-13 15:47:14.083 UTC | 2021-10-21 02:36:47.793 UTC | null | 15,497,888 | null | 886,357 | null | 1 | 42 | c|kernighan-and-ritchie | 46,365 | <p>By default, macOS (formerly OS X and Mac OS X) software recognizes <code>EOF</code> when <kbd>Control-D</kbd> is pressed at the beginning of a line. (I believe this behavior is similar for other versions of Unix as well.)</p>
<p>In detail, the actual operation is that, when <kbd> Control-D</kbd> is pressed, all bytes in the terminal’s input buffer are sent to the attached/foreground process using the terminal. At the start of a line, no bytes are in the buffer, so the process is told there are zero bytes available, and this acts as an <code>EOF</code> indicator.</p>
<p>This procedure doubles as a method of delivering input to the process before the end of a line: The user may type some characters and press <kbd> Control-D</kbd>, and the characters will be sent to the process immediately, without the usual wait for enter/return to be pressed. After this “send all buffered bytes immediately” operation is performed, no bytes are left in the buffer. So, when <kbd> Control-D</kbd> is pressed a second time, it is the same as the beginning of a line (no bytes are sent, and the process is given zero bytes), and it acts like an <code>EOF</code>.</p>
<p>You can learn more about terminal behavior by using the command “man 4 tty” in Terminal. The default line discipline is termios. You can learn more about the termios line discipline by using the command <code>man termios</code>.</p> |
35,528,119 | Pandas recalculate index after a concatenation | <p>I have a problem where I produce a pandas dataframe by concatenating along the row axis (stacking vertically). </p>
<p>Each of the constituent dataframes has an autogenerated index (ascending numbers). </p>
<p>After concatenation, my index is screwed up: it counts up to n (where n is the shape[0] of the corresponding dataframe), and restarts at zero at the next dataframe. </p>
<p>I am trying to "re-calculate the index, given the current order", or "re-index" (or so I thought). Turns out that isn't exactly what <code>DataFrame.reindex</code> seems to be doing. </p>
<hr>
<p>Here is what I tried to do:</p>
<pre><code>train_df = pd.concat(train_class_df_list)
train_df = train_df.reindex(index=[i for i in range(train_df.shape[0])])
</code></pre>
<p>It failed with "cannot reindex from a duplicate axis." I don't want to change the order of my data... just need to delete the old index and set up a new one, with the order of rows preserved. </p> | 35,528,185 | 3 | 0 | null | 2016-02-20 19:41:46.3 UTC | 15 | 2016-02-20 19:53:27.973 UTC | null | null | null | null | 3,834,415 | null | 1 | 66 | python|pandas | 82,316 | <p>After vertical concatenation, if you get an index of <em>[0, n)</em> followed by <em>[0, m)</em>, all you need to do is call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>reset_index</code></a>:</p>
<pre><code>train_df.reset_index(drop=True)
</code></pre>
<p>(you can do this in place using <code>inplace=True</code>).</p>
<hr>
<pre><code>import pandas as pd
>>> pd.concat([
pd.DataFrame({'a': [1, 2]}),
pd.DataFrame({'a': [1, 2]})]).reset_index(drop=True)
a
0 1
1 2
2 1
3 2
</code></pre> |
29,909,330 | Microsoft Visual C++ Compiler for Python 3.4 | <p>I know that there is a <a href="http://www.microsoft.com/en-gb/download/details.aspx?id=44266">"Microsoft Visual C++ Compiler for Python 2.7"</a> but is there, currently or planned, a Microsoft Visual C++ Compiler for Python 3.4 or eve Microsoft Visual C++ Compiler for Python 3.x for that matter? It would be supremely beneficial if I didn't have to install a different version of visual studio on my entire lab.</p> | 29,910,249 | 3 | 1 | null | 2015-04-28 02:38:09.427 UTC | 26 | 2017-06-21 05:42:02.84 UTC | 2015-07-03 21:40:13.383 UTC | null | 284,795 | null | 1,470,373 | null | 1 | 52 | python|windows|python-3.x|compilation | 129,159 | <p>Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:</p>
<ul>
<li><p>Visual Studio 2008 for Python 2.7.
See: <a href="https://docs.python.org/2.7/using/windows.html#compiling-python-on-windows" rel="noreferrer">https://docs.python.org/2.7/using/windows.html#compiling-python-on-windows</a></p></li>
<li><p>Visual Studio 2010 for Python 3.4.
See: <a href="https://docs.python.org/3.4/using/windows.html#compiling-python-on-windows" rel="noreferrer">https://docs.python.org/3.4/using/windows.html#compiling-python-on-windows</a></p></li>
</ul>
<p>Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.</p>
<p>See: <a href="https://docs.python.org/2/install/#gnu-c-cygwin-MinGW" rel="noreferrer">https://docs.python.org/2/install/#gnu-c-cygwin-MinGW</a> or <a href="https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw" rel="noreferrer">https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw</a></p>
<p>This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.</p> |
51,706,314 | Extract meter levels from audio file | <p>I need to extract audio meter levels from a file so I can render the levels before playing the audio. I know <code>AVAudioPlayer</code> can get this information while playing the audio file through </p>
<pre><code>func averagePower(forChannel channelNumber: Int) -> Float.
</code></pre>
<p>But in my case I would like to obtain an <code>[Float]</code> of meter levels beforehand.</p> | 52,280,271 | 3 | 0 | null | 2018-08-06 11:12:51.047 UTC | 15 | 2021-09-01 21:42:43.46 UTC | 2018-09-11 11:37:38.767 UTC | null | 1,317,394 | null | 294,661 | null | 1 | 25 | ios|swift|audio|avaudioplayer|audiotoolbox | 7,589 | <h2>Swift 4</h2>
<p>It takes on an iPhone:</p>
<ul>
<li><p><strong>0.538s</strong> to process an <code>8MByte</code> mp3 player with a <code>4min47s</code> duration, and <code>44,100</code> sampling rate</p>
</li>
<li><p><strong>0.170s</strong> to process an <code>712KByte</code> mp3 player with a <code>22s</code> duration, and <code>44,100</code> sampling rate</p>
</li>
<li><p><strong>0.089s</strong> to process <code>caf</code>file created by converting the file above using this command <code>afconvert -f caff -d LEI16 audio.mp3 audio.caf</code> in the terminal.</p>
</li>
</ul>
<p>Let's begin:</p>
<p><strong>A)</strong> Declare this class that is going to hold the necessary information about the audio asset:</p>
<pre><code>/// Holds audio information used for building waveforms
final class AudioContext {
/// The audio asset URL used to load the context
public let audioURL: URL
/// Total number of samples in loaded asset
public let totalSamples: Int
/// Loaded asset
public let asset: AVAsset
// Loaded assetTrack
public let assetTrack: AVAssetTrack
private init(audioURL: URL, totalSamples: Int, asset: AVAsset, assetTrack: AVAssetTrack) {
self.audioURL = audioURL
self.totalSamples = totalSamples
self.asset = asset
self.assetTrack = assetTrack
}
public static func load(fromAudioURL audioURL: URL, completionHandler: @escaping (_ audioContext: AudioContext?) -> ()) {
let asset = AVURLAsset(url: audioURL, options: [AVURLAssetPreferPreciseDurationAndTimingKey: NSNumber(value: true as Bool)])
guard let assetTrack = asset.tracks(withMediaType: AVMediaType.audio).first else {
fatalError("Couldn't load AVAssetTrack")
}
asset.loadValuesAsynchronously(forKeys: ["duration"]) {
var error: NSError?
let status = asset.statusOfValue(forKey: "duration", error: &error)
switch status {
case .loaded:
guard
let formatDescriptions = assetTrack.formatDescriptions as? [CMAudioFormatDescription],
let audioFormatDesc = formatDescriptions.first,
let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(audioFormatDesc)
else { break }
let totalSamples = Int((asbd.pointee.mSampleRate) * Float64(asset.duration.value) / Float64(asset.duration.timescale))
let audioContext = AudioContext(audioURL: audioURL, totalSamples: totalSamples, asset: asset, assetTrack: assetTrack)
completionHandler(audioContext)
return
case .failed, .cancelled, .loading, .unknown:
print("Couldn't load asset: \(error?.localizedDescription ?? "Unknown error")")
}
completionHandler(nil)
}
}
}
</code></pre>
<p>We are going to use its asynchronous function <code>load</code>, and handle its result to a completion handler.</p>
<p><strong>B)</strong> Import <code>AVFoundation</code> and <code>Accelerate</code> in your view controller:</p>
<pre><code>import AVFoundation
import Accelerate
</code></pre>
<p><strong>C)</strong> Declare the noise level in your view controller (in dB):</p>
<pre><code>let noiseFloor: Float = -80
</code></pre>
<p>For example, anything less than <code>-80dB</code> will be considered as silence.</p>
<p><strong>D)</strong> The following function takes an audio context and produces the desired dB powers. <code>targetSamples</code> is by default set to 100, you can change that to suit your UI needs:</p>
<pre><code>func render(audioContext: AudioContext?, targetSamples: Int = 100) -> [Float]{
guard let audioContext = audioContext else {
fatalError("Couldn't create the audioContext")
}
let sampleRange: CountableRange<Int> = 0..<audioContext.totalSamples
guard let reader = try? AVAssetReader(asset: audioContext.asset)
else {
fatalError("Couldn't initialize the AVAssetReader")
}
reader.timeRange = CMTimeRange(start: CMTime(value: Int64(sampleRange.lowerBound), timescale: audioContext.asset.duration.timescale),
duration: CMTime(value: Int64(sampleRange.count), timescale: audioContext.asset.duration.timescale))
let outputSettingsDict: [String : Any] = [
AVFormatIDKey: Int(kAudioFormatLinearPCM),
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsBigEndianKey: false,
AVLinearPCMIsFloatKey: false,
AVLinearPCMIsNonInterleaved: false
]
let readerOutput = AVAssetReaderTrackOutput(track: audioContext.assetTrack,
outputSettings: outputSettingsDict)
readerOutput.alwaysCopiesSampleData = false
reader.add(readerOutput)
var channelCount = 1
let formatDescriptions = audioContext.assetTrack.formatDescriptions as! [CMAudioFormatDescription]
for item in formatDescriptions {
guard let fmtDesc = CMAudioFormatDescriptionGetStreamBasicDescription(item) else {
fatalError("Couldn't get the format description")
}
channelCount = Int(fmtDesc.pointee.mChannelsPerFrame)
}
let samplesPerPixel = max(1, channelCount * sampleRange.count / targetSamples)
let filter = [Float](repeating: 1.0 / Float(samplesPerPixel), count: samplesPerPixel)
var outputSamples = [Float]()
var sampleBuffer = Data()
// 16-bit samples
reader.startReading()
defer { reader.cancelReading() }
while reader.status == .reading {
guard let readSampleBuffer = readerOutput.copyNextSampleBuffer(),
let readBuffer = CMSampleBufferGetDataBuffer(readSampleBuffer) else {
break
}
// Append audio sample buffer into our current sample buffer
var readBufferLength = 0
var readBufferPointer: UnsafeMutablePointer<Int8>?
CMBlockBufferGetDataPointer(readBuffer, 0, &readBufferLength, nil, &readBufferPointer)
sampleBuffer.append(UnsafeBufferPointer(start: readBufferPointer, count: readBufferLength))
CMSampleBufferInvalidate(readSampleBuffer)
let totalSamples = sampleBuffer.count / MemoryLayout<Int16>.size
let downSampledLength = totalSamples / samplesPerPixel
let samplesToProcess = downSampledLength * samplesPerPixel
guard samplesToProcess > 0 else { continue }
processSamples(fromData: &sampleBuffer,
outputSamples: &outputSamples,
samplesToProcess: samplesToProcess,
downSampledLength: downSampledLength,
samplesPerPixel: samplesPerPixel,
filter: filter)
//print("Status: \(reader.status)")
}
// Process the remaining samples at the end which didn't fit into samplesPerPixel
let samplesToProcess = sampleBuffer.count / MemoryLayout<Int16>.size
if samplesToProcess > 0 {
let downSampledLength = 1
let samplesPerPixel = samplesToProcess
let filter = [Float](repeating: 1.0 / Float(samplesPerPixel), count: samplesPerPixel)
processSamples(fromData: &sampleBuffer,
outputSamples: &outputSamples,
samplesToProcess: samplesToProcess,
downSampledLength: downSampledLength,
samplesPerPixel: samplesPerPixel,
filter: filter)
//print("Status: \(reader.status)")
}
// if (reader.status == AVAssetReaderStatusFailed || reader.status == AVAssetReaderStatusUnknown)
guard reader.status == .completed else {
fatalError("Couldn't read the audio file")
}
return outputSamples
}
</code></pre>
<p><strong>E)</strong> <code>render</code> uses this function to down-sample the data from the audio file, and convert to decibels:</p>
<pre><code>func processSamples(fromData sampleBuffer: inout Data,
outputSamples: inout [Float],
samplesToProcess: Int,
downSampledLength: Int,
samplesPerPixel: Int,
filter: [Float]) {
sampleBuffer.withUnsafeBytes { (samples: UnsafePointer<Int16>) in
var processingBuffer = [Float](repeating: 0.0, count: samplesToProcess)
let sampleCount = vDSP_Length(samplesToProcess)
//Convert 16bit int samples to floats
vDSP_vflt16(samples, 1, &processingBuffer, 1, sampleCount)
//Take the absolute values to get amplitude
vDSP_vabs(processingBuffer, 1, &processingBuffer, 1, sampleCount)
//get the corresponding dB, and clip the results
getdB(from: &processingBuffer)
//Downsample and average
var downSampledData = [Float](repeating: 0.0, count: downSampledLength)
vDSP_desamp(processingBuffer,
vDSP_Stride(samplesPerPixel),
filter, &downSampledData,
vDSP_Length(downSampledLength),
vDSP_Length(samplesPerPixel))
//Remove processed samples
sampleBuffer.removeFirst(samplesToProcess * MemoryLayout<Int16>.size)
outputSamples += downSampledData
}
}
</code></pre>
<p><strong>F)</strong> Which in turn calls this function that gets the corresponding dB, and clips the results to <code>[noiseFloor, 0]</code>:</p>
<pre><code>func getdB(from normalizedSamples: inout [Float]) {
// Convert samples to a log scale
var zero: Float = 32768.0
vDSP_vdbcon(normalizedSamples, 1, &zero, &normalizedSamples, 1, vDSP_Length(normalizedSamples.count), 1)
//Clip to [noiseFloor, 0]
var ceil: Float = 0.0
var noiseFloorMutable = noiseFloor
vDSP_vclip(normalizedSamples, 1, &noiseFloorMutable, &ceil, &normalizedSamples, 1, vDSP_Length(normalizedSamples.count))
}
</code></pre>
<p><strong>G)</strong> Finally you can get the waveform of the audio like so:</p>
<pre><code>guard let path = Bundle.main.path(forResource: "audio", ofType:"mp3") else {
fatalError("Couldn't find the file path")
}
let url = URL(fileURLWithPath: path)
var outputArray : [Float] = []
AudioContext.load(fromAudioURL: url, completionHandler: { audioContext in
guard let audioContext = audioContext else {
fatalError("Couldn't create the audioContext")
}
outputArray = self.render(audioContext: audioContext, targetSamples: 300)
})
</code></pre>
<p>Don't forget that <code>AudioContext.load(fromAudioURL:)</code> is asynchronous.</p>
<p>This solution is synthesized from <a href="https://github.com/fulldecent/FDWaveformView" rel="noreferrer">this repo</a> by <strong>William Entriken</strong>. All credit goes to him.</p>
<hr />
<h2>Swift 5</h2>
<p>Here is the same code updated to Swift 5 syntax:</p>
<pre><code>import AVFoundation
import Accelerate
/// Holds audio information used for building waveforms
final class AudioContext {
/// The audio asset URL used to load the context
public let audioURL: URL
/// Total number of samples in loaded asset
public let totalSamples: Int
/// Loaded asset
public let asset: AVAsset
// Loaded assetTrack
public let assetTrack: AVAssetTrack
private init(audioURL: URL, totalSamples: Int, asset: AVAsset, assetTrack: AVAssetTrack) {
self.audioURL = audioURL
self.totalSamples = totalSamples
self.asset = asset
self.assetTrack = assetTrack
}
public static func load(fromAudioURL audioURL: URL, completionHandler: @escaping (_ audioContext: AudioContext?) -> ()) {
let asset = AVURLAsset(url: audioURL, options: [AVURLAssetPreferPreciseDurationAndTimingKey: NSNumber(value: true as Bool)])
guard let assetTrack = asset.tracks(withMediaType: AVMediaType.audio).first else {
fatalError("Couldn't load AVAssetTrack")
}
asset.loadValuesAsynchronously(forKeys: ["duration"]) {
var error: NSError?
let status = asset.statusOfValue(forKey: "duration", error: &error)
switch status {
case .loaded:
guard
let formatDescriptions = assetTrack.formatDescriptions as? [CMAudioFormatDescription],
let audioFormatDesc = formatDescriptions.first,
let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(audioFormatDesc)
else { break }
let totalSamples = Int((asbd.pointee.mSampleRate) * Float64(asset.duration.value) / Float64(asset.duration.timescale))
let audioContext = AudioContext(audioURL: audioURL, totalSamples: totalSamples, asset: asset, assetTrack: assetTrack)
completionHandler(audioContext)
return
case .failed, .cancelled, .loading, .unknown:
print("Couldn't load asset: \(error?.localizedDescription ?? "Unknown error")")
}
completionHandler(nil)
}
}
}
let noiseFloor: Float = -80
func render(audioContext: AudioContext?, targetSamples: Int = 100) -> [Float]{
guard let audioContext = audioContext else {
fatalError("Couldn't create the audioContext")
}
let sampleRange: CountableRange<Int> = 0..<audioContext.totalSamples
guard let reader = try? AVAssetReader(asset: audioContext.asset)
else {
fatalError("Couldn't initialize the AVAssetReader")
}
reader.timeRange = CMTimeRange(start: CMTime(value: Int64(sampleRange.lowerBound), timescale: audioContext.asset.duration.timescale),
duration: CMTime(value: Int64(sampleRange.count), timescale: audioContext.asset.duration.timescale))
let outputSettingsDict: [String : Any] = [
AVFormatIDKey: Int(kAudioFormatLinearPCM),
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsBigEndianKey: false,
AVLinearPCMIsFloatKey: false,
AVLinearPCMIsNonInterleaved: false
]
let readerOutput = AVAssetReaderTrackOutput(track: audioContext.assetTrack,
outputSettings: outputSettingsDict)
readerOutput.alwaysCopiesSampleData = false
reader.add(readerOutput)
var channelCount = 1
let formatDescriptions = audioContext.assetTrack.formatDescriptions as! [CMAudioFormatDescription]
for item in formatDescriptions {
guard let fmtDesc = CMAudioFormatDescriptionGetStreamBasicDescription(item) else {
fatalError("Couldn't get the format description")
}
channelCount = Int(fmtDesc.pointee.mChannelsPerFrame)
}
let samplesPerPixel = max(1, channelCount * sampleRange.count / targetSamples)
let filter = [Float](repeating: 1.0 / Float(samplesPerPixel), count: samplesPerPixel)
var outputSamples = [Float]()
var sampleBuffer = Data()
// 16-bit samples
reader.startReading()
defer { reader.cancelReading() }
while reader.status == .reading {
guard let readSampleBuffer = readerOutput.copyNextSampleBuffer(),
let readBuffer = CMSampleBufferGetDataBuffer(readSampleBuffer) else {
break
}
// Append audio sample buffer into our current sample buffer
var readBufferLength = 0
var readBufferPointer: UnsafeMutablePointer<Int8>?
CMBlockBufferGetDataPointer(readBuffer,
atOffset: 0,
lengthAtOffsetOut: &readBufferLength,
totalLengthOut: nil,
dataPointerOut: &readBufferPointer)
sampleBuffer.append(UnsafeBufferPointer(start: readBufferPointer, count: readBufferLength))
CMSampleBufferInvalidate(readSampleBuffer)
let totalSamples = sampleBuffer.count / MemoryLayout<Int16>.size
let downSampledLength = totalSamples / samplesPerPixel
let samplesToProcess = downSampledLength * samplesPerPixel
guard samplesToProcess > 0 else { continue }
processSamples(fromData: &sampleBuffer,
outputSamples: &outputSamples,
samplesToProcess: samplesToProcess,
downSampledLength: downSampledLength,
samplesPerPixel: samplesPerPixel,
filter: filter)
//print("Status: \(reader.status)")
}
// Process the remaining samples at the end which didn't fit into samplesPerPixel
let samplesToProcess = sampleBuffer.count / MemoryLayout<Int16>.size
if samplesToProcess > 0 {
let downSampledLength = 1
let samplesPerPixel = samplesToProcess
let filter = [Float](repeating: 1.0 / Float(samplesPerPixel), count: samplesPerPixel)
processSamples(fromData: &sampleBuffer,
outputSamples: &outputSamples,
samplesToProcess: samplesToProcess,
downSampledLength: downSampledLength,
samplesPerPixel: samplesPerPixel,
filter: filter)
//print("Status: \(reader.status)")
}
// if (reader.status == AVAssetReaderStatusFailed || reader.status == AVAssetReaderStatusUnknown)
guard reader.status == .completed else {
fatalError("Couldn't read the audio file")
}
return outputSamples
}
func processSamples(fromData sampleBuffer: inout Data,
outputSamples: inout [Float],
samplesToProcess: Int,
downSampledLength: Int,
samplesPerPixel: Int,
filter: [Float]) {
sampleBuffer.withUnsafeBytes { (samples: UnsafeRawBufferPointer) in
var processingBuffer = [Float](repeating: 0.0, count: samplesToProcess)
let sampleCount = vDSP_Length(samplesToProcess)
//Create an UnsafePointer<Int16> from samples
let unsafeBufferPointer = samples.bindMemory(to: Int16.self)
let unsafePointer = unsafeBufferPointer.baseAddress!
//Convert 16bit int samples to floats
vDSP_vflt16(unsafePointer, 1, &processingBuffer, 1, sampleCount)
//Take the absolute values to get amplitude
vDSP_vabs(processingBuffer, 1, &processingBuffer, 1, sampleCount)
//get the corresponding dB, and clip the results
getdB(from: &processingBuffer)
//Downsample and average
var downSampledData = [Float](repeating: 0.0, count: downSampledLength)
vDSP_desamp(processingBuffer,
vDSP_Stride(samplesPerPixel),
filter, &downSampledData,
vDSP_Length(downSampledLength),
vDSP_Length(samplesPerPixel))
//Remove processed samples
sampleBuffer.removeFirst(samplesToProcess * MemoryLayout<Int16>.size)
outputSamples += downSampledData
}
}
func getdB(from normalizedSamples: inout [Float]) {
// Convert samples to a log scale
var zero: Float = 32768.0
vDSP_vdbcon(normalizedSamples, 1, &zero, &normalizedSamples, 1, vDSP_Length(normalizedSamples.count), 1)
//Clip to [noiseFloor, 0]
var ceil: Float = 0.0
var noiseFloorMutable = noiseFloor
vDSP_vclip(normalizedSamples, 1, &noiseFloorMutable, &ceil, &normalizedSamples, 1, vDSP_Length(normalizedSamples.count))
}
</code></pre>
<hr />
<h2>Old solution</h2>
<p>Here is a function you could use to pre-render the meter levels of an audio file without playing it:</p>
<pre><code>func averagePowers(audioFileURL: URL, forChannel channelNumber: Int, completionHandler: @escaping(_ success: [Float]) -> ()) {
let audioFile = try! AVAudioFile(forReading: audioFileURL)
let audioFilePFormat = audioFile.processingFormat
let audioFileLength = audioFile.length
//Set the size of frames to read from the audio file, you can adjust this to your liking
let frameSizeToRead = Int(audioFilePFormat.sampleRate/20)
//This is to how many frames/portions we're going to divide the audio file
let numberOfFrames = Int(audioFileLength)/frameSizeToRead
//Create a pcm buffer the size of a frame
guard let audioBuffer = AVAudioPCMBuffer(pcmFormat: audioFilePFormat, frameCapacity: AVAudioFrameCount(frameSizeToRead)) else {
fatalError("Couldn't create the audio buffer")
}
//Do the calculations in a background thread, if you don't want to block the main thread for larger audio files
DispatchQueue.global(qos: .userInitiated).async {
//This is the array to be returned
var returnArray : [Float] = [Float]()
//We're going to read the audio file, frame by frame
for i in 0..<numberOfFrames {
//Change the position from which we are reading the audio file, since each frame starts from a different position in the audio file
audioFile.framePosition = AVAudioFramePosition(i * frameSizeToRead)
//Read the frame from the audio file
try! audioFile.read(into: audioBuffer, frameCount: AVAudioFrameCount(frameSizeToRead))
//Get the data from the chosen channel
let channelData = audioBuffer.floatChannelData![channelNumber]
//This is the array of floats
let arr = Array(UnsafeBufferPointer(start:channelData, count: frameSizeToRead))
//Calculate the mean value of the absolute values
let meanValue = arr.reduce(0, {$0 + abs($1)})/Float(arr.count)
//Calculate the dB power (You can adjust this), if average is less than 0.000_000_01 we limit it to -160.0
let dbPower: Float = meanValue > 0.000_000_01 ? 20 * log10(meanValue) : -160.0
//append the db power in the current frame to the returnArray
returnArray.append(dbPower)
}
//Return the dBPowers
completionHandler(returnArray)
}
}
</code></pre>
<p>And you can call it like so:</p>
<pre><code>let path = Bundle.main.path(forResource: "audio.mp3", ofType:nil)!
let url = URL(fileURLWithPath: path)
averagePowers(audioFileURL: url, forChannel: 0, completionHandler: { array in
//Use the array
})
</code></pre>
<p>Using instruments, this solution makes high cpu usage during 1.2 seconds, takes about 5 seconds to return to the main thread with the <code>returnArray</code>, and up to 10 seconds when on <em>low battery mode</em>.</p> |
8,463,543 | Grouping elements of a list into sublists (maybe by using guava) | <p>I want to group elements of a list. I'm currently doing it this way: </p>
<pre><code>public static <E> List<List<E>> group(final List<E> list, final GroupFunction<E> groupFunction) {
List<List<E>> result = Lists.newArrayList();
for (final E element : list) {
boolean groupFound = false;
for (final List<E> group : result) {
if (groupFunction.sameGroup(element, group.get(0))) {
group.add(element);
groupFound = true;
break;
}
}
if (! groupFound) {
List<E> newGroup = Lists.newArrayList();
newGroup.add(element);
result.add(newGroup);
}
}
return result;
}
public interface GroupFunction<E> {
public boolean sameGroup(final E element1, final E element2);
}
</code></pre>
<p>Is there a better way to do this, preferably by using guava?</p> | 8,464,106 | 4 | 0 | null | 2011-12-11 11:21:52.643 UTC | 15 | 2018-01-05 15:42:16.03 UTC | 2017-05-10 02:04:55.48 UTC | null | 1,905,949 | null | 342,947 | null | 1 | 38 | java|list|function|grouping|guava | 49,195 | <p>Sure it is possible, and even easier with Guava :) Use <a href="https://google.github.io/guava/releases/23.0/api/docs/com/google/common/collect/Multimaps.html#index-java.lang.Iterable-com.google.common.base.Function-" rel="noreferrer"><code>Multimaps.index(Iterable, Function)</code></a>:</p>
<pre><code>ImmutableListMultimap<E, E> indexed = Multimaps.index(list, groupFunction);
</code></pre>
<p>If you give concrete use case it would be easier to show it in action.</p>
<p>Example from docs:</p>
<pre><code>List<String> badGuys =
Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde");
Function<String, Integer> stringLengthFunction = ...;
Multimap<Integer, String> index =
Multimaps.index(badGuys, stringLengthFunction);
System.out.println(index);
</code></pre>
<p>prints</p>
<pre><code>{4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]}
</code></pre>
<p>In your case if GroupFunction is defined as:</p>
<pre><code>GroupFunction<String> groupFunction = new GroupFunction<String>() {
@Override public String sameGroup(final String s1, final String s2) {
return s1.length().equals(s2.length());
}
}
</code></pre>
<p>then it would translate to:</p>
<pre><code>Function<String, Integer> stringLengthFunction = new Function<String, Integer>() {
@Override public Integer apply(final String s) {
return s.length();
}
}
</code></pre>
<p>which is possible <code>stringLengthFunction</code> implementation used in Guava's example.</p>
<hr>
<p>Finally, in Java 8, whole snippet could be even simpler, as lambas and method references are concise enough to be inlined:</p>
<pre><code>ImmutableListMultimap<E, E> indexed = Multimaps.index(list, String::length);
</code></pre>
<p>For pure Java 8 (no Guava) example using <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-" rel="noreferrer"><code>Collector.groupingBy</code></a> see <a href="https://stackoverflow.com/a/25953796/708434">Jeffrey Bosboom's answer</a>, although there are few differences in that approach:</p>
<ul>
<li>it doesn't return <code>ImmutableListMultimap</code> but rather <code>Map</code> with <code>Collection</code> values,</li>
<li><blockquote>
<p><em>There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned</em> (<a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-java.util.stream.Collector-" rel="noreferrer">source</a>),</p>
</blockquote></li>
<li>it's a bit more verbose than Guava + method reference.</li>
</ul>
<hr>
<p><strong>EDIT</strong>: If you don't care about indexed keys you can fetch grouped values:</p>
<pre><code>List<List<E>> grouped = Lists.transform(indexed.keySet().asList(), new Function<E, List<E>>() {
@Override public List<E> apply(E key) {
return indexed.get(key);
}
});
// or the same view, but with Java 8 lambdas:
List<List<E>> grouped = Lists.transform(indexed.keySet().asList(), indexed::get);
</code></pre>
<p>what gives you <code>Lists<List<E>></code> view which contents can be easily copied to <code>ArrayList</code> or just used as is, as you wanted in first place. Also note that <code>indexed.get(key)</code> is <code>ImmutableList</code>.</p>
<pre><code>// bonus: similar as above, but not a view, instead collecting to list using streams:
List<List<E>> grouped = indexed.keySet().stream()
.map(indexed::get)
.collect(Collectors.toList());
</code></pre>
<p><strong>EDIT 2</strong>: As Petr Gladkikh mentions <a href="https://stackoverflow.com/questions/8463543/grouping-elements-of-a-list-into-sublists-maybe-by-using-guava/8464106#comment28969950_8464106">in comment below</a>, if <code>Collection<List<E>></code> is enough, above example could be simpler:</p>
<pre><code>Collection<List<E>> grouped = indexed.asMap().values();
</code></pre> |
48,216,929 | How to configure ASP.net Core server routing for multiple SPAs hosted with SpaServices | <p>I have an Angular 5 application that I want to host with Angular Universal on ASP.net Core using the latest <a href="https://docs.microsoft.com/en-us/aspnet/core/spa/angular" rel="noreferrer">Angular template RC</a>. I've followed the docs and have the application up and running. The problem is that I am also using Angular's <a href="https://angular.io/guide/i18n" rel="noreferrer">i18n tools</a>, which produce multiple compiled applications, 1 per locale. I need to be able to host each from <code>https://myhost.com/{locale}/</code>.</p>
<p>I know that I can spin up an instance of the ASP.net Core app for each locale, and set up hosting in the webserver to have the appropriate paths route to the associated app, but this seems excessive to me.</p>
<p>Routes are configured with:</p>
<pre class="lang-cs prettyprint-override"><code>// app is an instance of Microsoft.AspNetCore.Builder.IApplicationBuilder
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
</code></pre>
<p>SpaServices are configured with:</p>
<pre class="lang-cs prettyprint-override"><code>app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
spa.UseSpaPrerendering(options =>
{
options.BootModulePath = $"{spa.Options.SourcePath}/dist-server/main.bundle.js";
options.BootModuleBuilder = env.IsDevelopment()
? new AngularCliBuilder(npmScript: "build:ssr:en")
: null;
options.ExcludeUrls = new[] { "/sockjs-node" };
options.SupplyData = (context, data) =>
{
data["foo"] = "bar";
};
});
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
</code></pre>
<p>I've looked through the documentation and the source on Github, and I cannot find how to configure ASP.net Core to associate a specific route with a given SPA. Anyone have any ideas?</p> | 48,465,664 | 1 | 1 | null | 2018-01-11 22:37:43.7 UTC | 18 | 2019-11-20 02:33:15.5 UTC | null | null | null | null | 613,559 | null | 1 | 40 | asp.net-core|asp-net-core-spa-services | 23,878 | <p>Thanks to <a href="https://github.com/SteveSandersonMS" rel="noreferrer">SteveSandersonMS</a> and <a href="https://github.com/chris5287" rel="noreferrer">chris5287</a> over on Github for pointing me towards the solution on this.</p>
<p><code>IApplicationBuilder.Map</code> can segregate paths into different areas of concern. If you wrap a call to <code>app.UseSpa</code> in a call to <code>app.Map</code>, the SPA will be handled only for the path specified by the <code>Map</code> call. The <code>app.UseSpa</code> call ends up looking like:</p>
<pre class="lang-cs prettyprint-override"><code>app.Map("/app1", app1 =>
{
app1.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
spa.UseSpaPrerendering(options =>
{
options.BootModulePath = $"{spa.Options.SourcePath}/dist-server/main.bundle.js";
options.BootModuleBuilder = env.IsDevelopment()
? new AngularCliBuilder(npmScript: "build:ssr:en")
: null;
options.ExcludeUrls = new[] { "/sockjs-node" };
options.SupplyData = (context, data) =>
{
data["foo"] = "bar";
};
});
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start --app=app1 --base-href=/app1/ --serve-path=/");
}
});
});
</code></pre>
<p>You can make as many calls to <code>app.Map</code> as necessary to configure your SPAs. Also note the modification to the <code>spa.UseAngularCliServer</code> call at the end: you will need to set <code>--base-href</code> and <code>--serve-path</code> to match your particular config.</p> |
26,482,149 | Synchronizing on local variable | <p>I noticed a weird construct in <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/concurrent/ConcurrentHashMap.java#1847"><code>ConcurrentHashMap</code>'s <code>compute</code> and <code>computeIfAbsent</code> methods</a>:</p>
<pre><code>Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
//...
}
</code></pre>
<p>What is the point of synchronizing on a local object considering that the JIT will most likely treat it as a no-op?</p> | 26,482,906 | 1 | 0 | null | 2014-10-21 08:28:43.833 UTC | 9 | 2014-10-21 09:17:21.97 UTC | 2014-10-21 08:52:48.02 UTC | null | 829,571 | null | 829,571 | null | 1 | 28 | java|multithreading|java-8|synchronized|concurrenthashmap | 2,425 | <p>Right after the code has acquired the object’s monitor, the reference to the object is stored into the <code>tab</code> which is the globally visible array of nodes which make up the contents of the <code>ConcurrentHashMap</code>:</p>
<pre><code>Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
if (casTabAt(tab, i, null, r)) {
</code></pre>
<p>Right at this point, other threads executing other modification methods on the same <code>ConcurrentHashMap</code> might encounter this incomplete node while traversing the global array, in other words, the <code>Node</code> reference has escaped.</p>
<p>While at the point where the <code>ReservationNode</code> has been constructed, there is no possibility for contention on a newly created object, in the other methods, which are synchronizing on <code>Node</code>s found in the array, there might be contention for exactly that <code>Node</code>.</p>
<p>It’s like a “priority-synchronization”. The creator is synchronizing at a point where the reference has not been escaped yet therefore it is guaranteed to succeed while at the point where the reference escapes, all other threads will have to wait, in the unlikely (but still possible) event that they access exactly that <code>Node</code>.</p> |
30,743,038 | align AlertDialog buttons to center | <p>I use this codes for Android (Java) programming:</p>
<pre><code>public static MessageBoxResult showOk(
Context context, String title, String message, String okMessage)
{
okDialogResult = MessageBoxResult.Closed;
// make a handler that throws a runtime exception when a message is received
final Handler handler = new Handler()
{
@Override
public void handleMessage(Message mesg)
{
throw new RuntimeException();
}
};
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(title);
alert.setMessage(message);
alert.setPositiveButton(okMessage, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
okDialogResult = MessageBoxResult.Positive;
handler.sendMessage(handler.obtainMessage());
}
});
AlertDialog dialog = alert.show();
// align button to center
Button b = (Button) dialog.findViewById(android.R.id.button1);
b.setGravity(Gravity.CENTER_HORIZONTAL);
// loop till a runtime exception is triggered.
try { Looper.loop(); }
catch(RuntimeException e2) {}
return okDialogResult;
}
</code></pre>
<p>My problem is how make center the button? As you see I try to align button to cnenter using <code>Gravity.CENTER_HORIZONTAL</code> (also <code>.CENTER</code>) but nothing changes. The button is almost in right position.</p> | 34,001,525 | 10 | 0 | null | 2015-06-09 21:20:39.593 UTC | 2 | 2021-08-03 07:55:15.39 UTC | 2015-06-10 01:31:51.423 UTC | null | 2,227,834 | null | 2,672,788 | null | 1 | 33 | android|button|alignment|android-alertdialog | 42,627 | <p>This worked for me : </p>
<pre><code> final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show(); //show() should be called before dialog.getButton().
final Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
LinearLayout.LayoutParams positiveButtonLL = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
positiveButtonLL.gravity = Gravity.CENTER;
positiveButton.setLayoutParams(positiveButtonLL);
</code></pre> |
458,482 | REST and authentication variants | <p>I am currently working on a REST library for .net, and I would like to hear some opinions about an open point I have: REST and authentication.</p>
<p>Here is an example of an RESTful interface used with the library:</p>
<pre><code>[RestRoot("/user")]
public interface IUserInterface
{
[RestPut("/")]
void Add(User user);
[RestGet("/")]
int[] List();
[RestGet("/get/{id}")]
User Get(int id);
[RestDelete("/delete/{id}")]
void Delete(int id);
}
</code></pre>
<p>The server code then just implements the interface and the clients can obtain the same interface through a factory. Or if the client is not using the library a standard HTTP request also works.</p>
<p>I know that there are the major ways of either using HTTP Basic Auth or sending a token to requests requiring authenticated users.</p>
<p>The first method (HTTP Basic Auth), has the following issues (partly web browser specific):</p>
<ul>
<li>The password is transmitted with every request - even with SSL this has some kind of "bad feeling".</li>
<li>Since the password is transmitted with a request header, it would be easy for an local attacker to look at the transmitted headers to gain the password.</li>
<li>The password is available in the browsers memory.</li>
<li>No standard way to expire user "sessions".</li>
<li>Login with a browser interrupts the look and feel of a page.</li>
</ul>
<p>The issues for the second method are more focused on implementation and library use:</p>
<ul>
<li>Each request URI which needs authentication must have a parameter for the token, which is just very repetitive.</li>
<li>There is a lot more code to write if each method implementation needs to check if a token is valid.</li>
<li>The interface will become less specific e.g. <code>[RestGet("/get/{id}")]</code> vs. <code>[RestGet("/get/{id}/{token}")]</code>.</li>
<li>Where to put the token: at the end of the URI? after the root? somewhere else?</li>
</ul>
<hr>
<p>My idea was to pass the token as parameter to the URL like <code>http:/server/user/get/1234?token=token_id</code>.</p>
<p>Another possibility would be to send the parameter as an HTTP header, but this would complicate usage with plain HTTP clients I guess.</p>
<p>The token would get passed back to the client as a custom HTTP header ("X-Session-Id") on each request.</p>
<p>This then could be completely abstracted from the interface, and any implementation needing authentication could just ask which user the token (if given) belongs to.</p>
<p>Do you think this would violate REST too much or do you have any better ideas?</p> | 466,806 | 3 | 0 | null | 2009-01-19 17:47:55.237 UTC | 51 | 2011-07-13 09:49:02.507 UTC | 2010-03-31 14:08:02.647 UTC | Tomalak | 4,023 | Fionn | 21,566 | null | 1 | 70 | authentication|rest | 53,864 | <p>I tend to believe that authentication details belong in the header, not the URI. If you rely on a token being placed on the URI, then every URI in your application will need to be encoded to include the token. It would also negatively impact caching. Resources with a token that is constantly changing will no longer be able to be cached. Resource related information belongs in the URI, not application related data such as credentials.</p>
<p>It seems you must be targeting web browsers as a client? If so you could investigate using <a href="http://en.wikipedia.org/wiki/Digest_access_authentication" rel="noreferrer" title="HTTP Digest access authentication">HTTP Digest access authentication</a> or issuing clients their own SSL certificates to uniquely identify and authenticate them. Also, I don't think that session cookies are necessarily a bad thing. Especially when having to deal with a browser. As long as you isolate the cookie handling code and make the rest of the application not rely on it you would be fine. The key is only store the user's identity in the session, nothing else. Do not abuse server side session state.</p>
<p>If you are targeting clients other than the browser then there are a number of approaches you can take. I've had luck with using Amazon's <a href="http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/index.html?RESTAuthentication.html" rel="noreferrer" title="Amazon S3 Authentication">S3 Authentication</a> mechanism.</p>
<p>This is all very subjective of course. Purity and following REST to the letter can sometimes be impractical. As long as you minimize and isolate such behavior, the core of your application can still be RESTful. I highly recommend <a href="http://oreilly.com/catalog/9780596529260/" rel="noreferrer" title="RESTful Web Services">RESTful Web Services</a> as a great source of REST information and approaches.</p> |
39,628,930 | Why do I always get Whitelabel Error Page with status "404" while running a simple Spring Boot Application | <p><strong>My Controller</strong></p>
<pre><code>@Controller
//@RequestMapping("/")
//@ComponentScan("com.spring")
//@EnableAutoConfiguration
public class HomeController {
@Value("${framework.welcomeMessage}")
private String message;
@RequestMapping("/hello")
String home(ModelMap model) {
System.out.println("hittin the controller...");
model.addAttribute("welcomeMessage", "vsdfgfgd");
return "Hello World!";
}
@RequestMapping(value = "/indexPage", method = RequestMethod.GET)
String index(ModelMap model) {
System.out.println("hittin the index controller...");
model.addAttribute("welcomeMessage", message);
return "welcome";
}
@RequestMapping(value = "/indexPageWithModel", method = RequestMethod.GET)
ModelAndView indexModel(ModelMap model) {
System.out.println("hittin the indexPageWithModel controller...");
model.addAttribute("welcomeMessage", message);
return new ModelAndView("welcome", model);
}
}
</code></pre>
<p><strong>My JSP (welcome.jsp) inside /WEB-INF/jsp</strong> (parent folder is WebContent)</p>
<pre><code><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to Spring Boot</title>
</head>
<body>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Message: ${message}
</body>
</html>
</code></pre>
<p><strong>My pom.xml</strong></p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringBootPlay</groupId>
<artifactId>SpringBootPlay</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-log</artifactId>
<version>0.17</version>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
<start-class>com.spring.play.BootLoader</start-class>
<main.basedir>${basedir}/../..</main.basedir>
<m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p><strong>My App Initializer</strong></p>
<pre><code>@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan({ "com.spring.controller" })
@PropertySources(value = { @PropertySource("classpath:/application.properties") })
public class BootLoader extends SpringBootServletInitializer {
final static Logger logger = Logger.getLogger(BootLoader.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(BootLoader.class);
}
public static void main(String[] args) {
SpringApplication.run(BootLoader.class, args);
}
}
</code></pre>
<p>I even added <code>thymeleaf</code> dependency to my pom. It still didn't work. When ever I hit <code>localhost:8080/hello or /indexPage or /indexPageWithModel</code> it always says</p>
<p>Whitelabel Error Page</p>
<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>
<p>Wed Sep 21 21:34:18 EDT 2016
There was an unexpected error (type=Not Found, status=404).
]/WEB-INF/jsp/welcome.jsp</p>
<p><strong>My application.properties</strong></p>
<pre><code>spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
framework.welcomeMessage=Welcome to Dashboard
</code></pre>
<p>Please help me. Thanks!</p> | 39,629,506 | 6 | 1 | null | 2016-09-22 01:37:03.243 UTC | null | 2022-06-20 20:59:25.583 UTC | 2016-09-22 02:07:32.507 UTC | null | 1,629,109 | null | 1,629,109 | null | 1 | 4 | java|spring|jsp|spring-mvc|spring-boot | 51,001 | <p>Figured it out myself.</p>
<p>When I converted my dynamic webproject into maven project it did not create the folder structure this way</p>
<p><code>src/main/java</code></p>
<p>and </p>
<p><code>src/main/resources</code></p>
<p>and</p>
<p><code>src/main/webapp</code></p>
<p>I manually created myself and moved the jsp files from <code>WebContent/WEB-INF/jsp</code> to <code>src/main/webapp/WEB-INF/jsp</code> and modified the <code>Java build path</code> in the project properties.</p>
<p>Then I restarted the <code>embedded tomcat</code> and tried it again. It worked.</p> |
34,952,528 | Using .StartsWith in a Switch statement? | <p>I'm working on a Switch statement and with two of the conditions I need to see if the values start with a specific value. The Switch statement does like this. The error says "cannot covert type bool to string". </p>
<p>Anyone know if I can use the StartsWith in a Switch or do I need to use If...Else statements?</p>
<pre><code>switch(subArea)
{
case "4100":
case "4101":
case "4102":
case "4200":
return "ABC";
case "600A":
return "XWZ";
case subArea.StartsWith("3*"):
case subArea.StartsWith("03*"):
return "123";
default:
return "ABCXYZ123";
}
</code></pre> | 34,952,580 | 9 | 2 | null | 2016-01-22 17:22:06.81 UTC | 4 | 2022-04-26 22:08:59.793 UTC | null | null | null | null | 5,216,651 | null | 1 | 36 | c#|asp.net|.net | 39,861 | <p>EDIT: If you are using C# >= 7, take a look at <a href="https://stackoverflow.com/a/63618064/5686352">this</a> answer first.</p>
<hr />
<p>You are switching a <code>String</code>, and <code>subArea.StartsWith()</code> returns a <code>Boolean</code>, that's why you can't do it. I suggest you do it like this:</p>
<pre><code>if (subArea.StartsWith("3*") || subArea.StartsWith("03*"))
return "123";
switch(subArea)
{
case "4100":
case "4101":
case "4102":
case "4200":
return "ABC";
case "600A":
return "XWZ";
default:
return "ABCXYZ123";
}
</code></pre>
<p>The result will be the same.</p> |
20,060,553 | How do I deploy a file to Artifactory using the command line? | <p>I've spent far more time on this than I care to admit. I am trying to just deploy one file into my Artifactory server from the command line. I'm doing this using gradle because that is how we manage our java builds. However, this artifact is an NDK/JNI build artifact, and does not use gradle.</p>
<p>So I just need the simplest gradle script to do the deploy. Something equivalent to:</p>
<pre><code>scp <file> <remote>
</code></pre>
<p>I am currently trying to use the <code>artifactory</code> plugin, and am having little luck in locating a reference for the plugin.</p> | 24,010,929 | 7 | 0 | null | 2013-11-19 00:03:59.977 UTC | 12 | 2022-08-22 17:07:44.73 UTC | 2015-12-29 00:15:27.05 UTC | null | 132,401 | null | 132,401 | null | 1 | 36 | command-line|gradle|artifactory | 74,935 | <p>curl POST did not work for me . PUT worked correctly . The usage is </p>
<pre><code>curl -X PUT $SERVER/$PATH/$FILE --data-binary @localfile
</code></pre>
<p>example : </p>
<pre><code>$ curl -v --user username:password --data-binary @local-file -X PUT "http://<artifactory server >/artifactory/abc-snapshot-local/remotepath/remotefile"
</code></pre> |
6,242,296 | Conversion function for error checking considered good? | <p>I'd like to have a simple way of checking for an object to be valid. I thought of a simple conversion function, something like this: </p>
<pre><code>operator bool() const { return is_valid; }
</code></pre>
<p>Checking for it to be valid would be very simple now</p>
<pre><code>// is my object invalid?
if (!my_object) std::cerr << "my_object isn't valid" << std::endl;
</code></pre>
<p>Is this considered a good practise? </p> | 6,242,355 | 3 | 0 | null | 2011-06-05 10:18:14.247 UTC | 24 | 2016-09-17 20:54:32.847 UTC | null | null | null | null | 211,359 | null | 1 | 50 | c++|error-handling | 3,516 | <p>In C++03, you need to use the <a href="http://www.artima.com/cppsource/safebool.html" rel="noreferrer">safe bool idiom</a> to avoid evil things:</p>
<pre><code>int x = my_object; // this works
</code></pre>
<p>In C++11 you can use an explicit conversion:</p>
<pre><code>explicit operator bool() const
{
// verify if valid
return is_valid;
}
</code></pre>
<p>This way you need to be explicit about the conversion to bool, so you can no longer do crazy things by accident (in C++ you can always do crazy things on purpose):</p>
<pre><code>int x = my_object; // does not compile because there's no explicit conversion
bool y = bool(my_object); // an explicit conversion does the trick
</code></pre>
<p>This still works as normal in places like <code>if</code> and <code>while</code> that require a boolean expression, because the condition of those statements is <em>contextually converted</em> to bool:</p>
<pre><code>// this uses the explicit conversion "implicitly"
if (my_object)
{
...
}
</code></pre>
<p>This is documented in <strong>§4[conv]</strong>:</p>
<blockquote>
<p>An expression <code>e</code> can be <em>implicitly
converted</em> to a type <code>T</code> if and only if
the declaration <code>T t=e;</code> is well-formed,
for some invented temporary variable <code>t</code>
(§8.5). Certain language constructs
require that an expression be
converted to a Boolean value. An
expression <code>e</code> appearing in such a
context is said to be <em>contextually converted to <code>bool</code></em> and is well-formed
if and only if the declaration <code>bool t(e);</code> is well-formed, for some
invented temporary variable <code>t</code> (§8.5). The effect of either
implicit conversion is the same as performing the
declaration and initialization and then using the temporary
variable as the result of the conversion.</p>
</blockquote>
<p>(What makes the difference is the use of <code>bool t(e);</code> instead of <code>bool t = e;</code>.)</p>
<p>The places were this contextual conversion to bool happens are:</p>
<ul>
<li>the conditions of <code>if</code>, <code>while</code>, and <code>for</code> statements;</li>
<li>the operators of logical negation <code>!</code>, logical conjunction <code>&&</code>, and logical disjunction <code>||</code>;</li>
<li>the conditional operator <code>?:</code>;</li>
<li>the condition of <code>static_assert</code>;</li>
<li>the optional constant expression of the <code>noexcept</code> exception specifier;</li>
</ul> |
6,023,419 | What is the difference between ".class element" and "element.class"? | <p>Is there a difference between <code>.class element</code> and <code>element.class</code> in a CSS selector? </p>
<p>I had always been shown <code>element.class</code> but just the other day came across a CSS file at work that had <code>.class element</code> and wanted to know if this was just a style choice (in which case I would make my changes match), or if there was a specific reason (in which case I would not necessarily want to make my changes match).</p> | 6,023,440 | 4 | 0 | null | 2011-05-16 21:04:55.047 UTC | 23 | 2018-08-01 22:50:56.353 UTC | 2018-08-01 22:50:56.353 UTC | null | 3,924,118 | null | 338,618 | null | 1 | 44 | css | 20,519 | <p><code>element.class</code> selects all <code><element /></code>s with that class. <code>.class element</code> selects all <code><element /></code>s that are descendants of elements that have that class.</p>
<p>For example, HTML:</p>
<pre><code><div class='wrapper'>
<div class='content'></div>
<div></div>
<div class='footer'></div>
</div>
</code></pre>
<p>For example, CSS:</p>
<pre><code>div.wrapper {
background-color: white; /* the div with wrapper class will be white */
}
.wrapper div {
background-color: red; /* all 3 child divs of wrapper will be red */
}
</code></pre> |
1,425,937 | jQuery - Select first cell of a given row? | <p>I have a table with images in one column. When I click the image, would like to get the text value of the first column in that row.</p>
<p>I can get the whole row with this:</p>
<pre><code>var a = $(this).parents('tr').text();
</code></pre>
<p>However, I cannot isolate the first cell of the row.</p>
<p>I've tried </p>
<pre><code>var a = $(this).parents('tr td:first').text();
</code></pre>
<p>But that just returns the first cell of the entire table.</p>
<p>Can anyone help me out?</p>
<p>Thanks.</p> | 1,425,955 | 2 | 0 | null | 2009-09-15 08:42:59.633 UTC | 5 | 2017-08-21 14:18:57.443 UTC | 2014-05-19 17:06:56.13 UTC | null | 775,283 | null | 146,989 | null | 1 | 37 | jquery|jquery-selectors | 51,076 | <p>How about?</p>
<pre><code>var a = $('td:first', $(this).parents('tr')).text();
</code></pre> |
5,931,572 | How is programming an Arduino different than standard C? | <p>I have a background in programming embedded systems (TI <a href="http://en.wikipedia.org/wiki/TI_MSP430" rel="noreferrer">MSP430</a>, Atmel <a href="http://en.wikipedia.org/wiki/Atmel_AVR#Device_overview" rel="noreferrer">ATxmega</a>). How is programming an Arduino different than those? What knowledge about C can I take in to programming the Arduino?</p> | 5,931,887 | 5 | 4 | null | 2011-05-09 01:22:58.52 UTC | 13 | 2016-09-06 18:21:35.24 UTC | 2014-05-29 09:31:33.593 UTC | null | 1,459,079 | null | 325,193 | null | 1 | 27 | c++|c|arduino | 33,224 | <p>While I don't know about the ATXMega, the 8-bit AVR chips like the ATmega328 used on the newer Arduinos use the AVR-GCC compiler. This allows for compiling C and even C++ to an AVR chip. One level above the AVR-GCC is the <a href="http://www.nongnu.org/avr-libc/" rel="nofollow noreferrer">AVR Libc</a>, a C library that makes programming for the AVR a higher level task (no longer have to refer to registers directly, and so on).</p>
<p>The Arduino IDE uses AVR-GCC and AVR libc library in the backend. In addition, the Arduino IDE makes <a href="https://github.com/arduino/Arduino/tree/master/hardware/arduino/cores/arduino" rel="nofollow noreferrer">other libraries available</a>, like a nice Serial interface.</p>
<p>Finally, the Arduino comes with a bootloader burned on the AVR chip. The bootloader simply makes it possible to program the AVR using a serial connection (from USB) instead of an In-Sytem Programmer or Development Board.</p>
<p>Enough backstory, to answer your question: The Arduino can be programmed in C and even C++. The libraries available are written in C and everything will compiled using AVR-GCC. The Arduino IDE isn't even required.</p>
<p><strong>Edit</strong></p>
<p>There seems to be a decent amount of interest in this topic. I wrote a blog post to try and give <a href="https://gist.github.com/baalexander/8530398" rel="nofollow noreferrer">more in-depth details on the AVR, Arduino, and AVR-GCC</a>.</p> |
6,070,505 | Android: how to create a transparent dialog-themed activity | <p>My original goal here was a modal dialog, but you know, Android didn't support this type of dialog. Alternatively, building a dialog-themed activity would possibly work.<br>
Here's code,</p>
<pre><code>public class DialogActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(android.R.style.Theme_Dialog);
super.onCreate(savedInstanceState);
requestWindowFeature (Window.FEATURE_NO_TITLE);
Button yesBtn = new Button(this);
yesBtn.setText("Yes");
yesBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogActivity.this.finish();
}
});
this.setContentView(yesBtn);
}
</code></pre>
<p>However, the background was always black, that really confusing. People got same problem,<br>
<a href="http://code.google.com/p/android/issues/detail?id=4394" rel="noreferrer">http://code.google.com/p/android/issues/detail?id=4394</a><br>
I just wanna make it look more dialog-like for user. So, how to get this DialogActivity transparent and never cover underlying screen?<br>
Thanks.</p>
<p>This was how I created the style</p>
<pre><code><style name="CustomDialogTheme" parent="android:Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">false</item>
</style>
</code></pre> | 6,583,428 | 6 | 0 | null | 2011-05-20 10:20:51.96 UTC | 6 | 2021-02-02 15:56:06.833 UTC | 2011-05-23 02:15:01.093 UTC | null | 663,948 | null | 663,948 | null | 1 | 19 | android|android-activity|dialog | 38,322 | <p>You can create a tranparent dialog by this.</p>
<pre><code>public class DialogActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(" ");
alertDialog.setMessage("");
alertDialog.setIcon(R.drawable.icon);
alertDialog.setButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setButton2("Deny", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
</code></pre>
<p>After this just put a line in AndroidManifest.xml, where you define your activity in manifest.</p>
<pre><code>android:theme="@android:style/Theme.Translucent.NoTitleBar"
</code></pre> |
5,891,888 | piping data into command line php? | <p>It is possible to pipe data using unix pipes into a command-line php script? I've tried</p>
<pre><code>$> data | php script.php
</code></pre>
<p>But the expected <code>data</code> did not show up in <code>$argv</code>. Is there a way to do this?</p> | 5,891,900 | 9 | 1 | null | 2011-05-05 02:03:03.227 UTC | 6 | 2020-01-01 12:09:49.203 UTC | null | null | null | null | 151,841 | null | 1 | 33 | php|command-line|pipe | 30,090 | <p>As I understand it, <code>$argv</code> will show the arguments of the program, in other words:</p>
<pre><code>php script.php arg1 arg2 arg3
</code></pre>
<p>But if you pipe data into PHP, you will have to read it from standard input. I've never tried this, but I think it's something like this:</p>
<pre><code>$fp = readfile("php://stdin");
// read $fp as if it were a file
</code></pre> |
5,756,256 | Trim spaces from end of a NSString | <p>I need to remove spaces from the end of a string. How can I do that?
Example: if string is <code>"Hello "</code> it must become <code>"Hello"</code></p> | 5,756,341 | 14 | 1 | null | 2011-04-22 14:06:11.64 UTC | 69 | 2020-02-13 04:38:05.75 UTC | 2015-01-30 17:14:15.22 UTC | null | 2,738,262 | null | 588,967 | null | 1 | 371 | nsstring|whitespace|trim | 178,735 | <p>Taken from this answer here: <a href="https://stackoverflow.com/a/5691567/251012">https://stackoverflow.com/a/5691567/251012</a></p>
<pre><code>- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
options:NSBackwardsSearch];
if (rangeOfLastWantedCharacter.location == NSNotFound) {
return @"";
}
return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}
</code></pre> |
39,266,747 | Image overflowing div advice | <p>Im sure this is really easy but i have been looking at this issue for a little while and my brain has gone blank. I have a div that then has an image inside of it. The image seems to just overflow the div border and its driving me mad. I have an image below to show you what is happening along with the css.</p>
<p><img src="https://i.imgur.com/dkzoNCc.png" alt="image"></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#avatar {
float: left;
width: 50%;
height: 300px;
border: 1px solid black;
}
#avatar img {
width: 100%;
height: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="avatar">
<img src="http://i.imgur.com/dkzoNCc.png"></div></code></pre>
</div>
</div>
</p>
<p>I have a border on the main div #avatar just so i can see the whole size of the div. All i want is for the image to scale to the size of the div. If i set the height to 100% it goes into the div just fine but when resizing it it starts to overflow the div. I want the image to resize on the width not height.</p>
<p>Am i missing something really simple here? I dont want to use overflow hidden on the image as that will just cut some of it off i believe.</p>
<p>Thanks everyone</p> | 39,267,265 | 4 | 2 | null | 2016-09-01 08:44:30.13 UTC | 2 | 2016-09-01 10:49:12.94 UTC | 2016-09-01 10:45:58.25 UTC | user6768630 | null | null | 6,527,939 | null | 1 | 16 | html|css | 40,293 | <p>Try below css for <code>img</code>. </p>
<ul>
<li>use <code>height: 100%;</code> for maximum height</li>
<li><code>display: block;margin: auto;</code> for centering</li>
<li><code>max-width: 100%;</code> to fit large images</li>
</ul>
<p>Please check the example with large and small images.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#avatar {
float: left;
width: 50%;
height: 300px;
border: 1px solid black;
}
#avatar img {
height: 100%;
max-width: 100%;
display: block;
margin: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="avatar">
<img src="http://www.baraodasfestas.com.br/Assets/Produtos/SuperZoom/0431_MICKEY_635703672330071491.jpg" alt="">
</div>
<div id="avatar">
<img src="https://upload.wikimedia.org/wikipedia/en/d/d4/Mickey_Mouse.png" alt="">
</div></code></pre>
</div>
</div>
</p> |
5,157,265 | Is it OK to query a MongoDB multiple times per request? | <p>Coming from an RDBMS background, I was always under the impression "Try as hard as you can to use one query, assuming it's efficient," meaning that it's costly for every request you make to the database. When it comes to MongoDB, it seems like this might not be possible because you can't join tables.</p>
<p>I understand that it's not supposed to be relational, but they're also pushing it for purposes like blogs, forums, and things I'd find an RDBMS easier to approach with.</p>
<p>There are some hang ups I've had trying to understand the efficiency of MongoDB or NoSQL in general. If I wanted to get all "posts" related to certain users (as if they were grouped)... using MySQL I'd probably do some joins and get it with that.</p>
<p>In MongoDB, assuming I need the collections separate, would it be efficient to use a large $in: ['user1', 'user2', 'user3', 'user4', ...] ? </p>
<p>Does that method get slow after a while? If I include 1000 users?
And if I needed to get that list of posts related to users X,Y,Z, would it be efficient and/or fast using MongoDB to do:</p>
<ul>
<li>Get users array</li>
<li>Get Posts IN users array</li>
</ul>
<p>2 queries for one request. Is that bad practice in NoSQL?</p> | 5,157,425 | 1 | 0 | null | 2011-03-01 16:25:40.22 UTC | 14 | 2017-07-11 08:53:53.707 UTC | 2017-09-22 18:01:22.247 UTC | null | -1 | null | 639,679 | null | 1 | 24 | mysql|mongodb|database|nosql | 7,132 | <p>To answer the Q about $in....</p>
<p>I did some performance tests with the following scenario:</p>
<p>~24 million docs in a collection<br/>
Lookup 1 million of those documents based on a key (indexed)<br/>
Using CSharp driver from .NET<br/></p>
<p><b>Results:</b><br/>
Querying 1 at a time, single threaded : 109s<br/>
Querying 1 at a time, multi threaded : 48s<br/>
Querying 100K at a time using $in, single threaded=20s<br/>
Querying 100K at a time using $in, multi threaded=9s<br/></p>
<p>So noticeably better performance using a large $in (restricted to max query size).</p>
<p><b>Update:</b>
Following on from comments below about how $in performs with different chunk sizes (queries multi-threaded):</p>
<p>Querying 10 at a time (100000 batches) = 8.8s <br/>
Querying 100 at a time (10000 batches) = 4.32s<br/>
Querying 1000 at a time (1000 batches) = 4.31s<br/>
Querying 10000 at a time (100 batches) = 8.4s<br/>
Querying 100000 at a time (10 batches) = 9s (per original results above)</p>
<p>So there does look to be a sweet-spot for how many values to batch up in to an $in clause vs. the number of round trips</p> |
49,707,830 | Angular: How to correctly implement APP_INITIALIZER | <p>I have a <strong>Angular 5.2.0</strong> application.
I looked up how to implement <code>APP_INITIALIZER</code> to load configuration information before the app starts.
Here an extract of the <code>app.module</code>:</p>
<pre><code>providers: [
ConfigurationService,
{
provide: APP_INITIALIZER,
useFactory: (configService: ConfigurationService) =>
() => configService.loadConfigurationData(),
deps: [ConfigurationService],
multi: true
}
],
</code></pre>
<p>Here the <code>configuration.service</code>:</p>
<pre><code>import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Configuration } from './configuration';
@Injectable()
export class ConfigurationService {
private readonly configUrlPath: string = 'Home/Configuration';
private configData: Configuration;
constructor(
private http: HttpClient,
@Inject('BASE_URL') private originUrl: string) { }
loadConfigurationData() {
this.http
.get<Configuration>(`${this.originUrl}${this.configUrlPath}`)
.subscribe(result => {
this.configData = {
test1ServiceUrl: result["test1ServiceUrl"],
test2ServiceUrl: result["test2ServiceUrl"]
}
});
}
get config(): Configuration {
return this.configData;
}
}
</code></pre>
<p>Here is an example of a constructor of a component where the <code>configData</code> is used:</p>
<pre><code>export class TestComponent {
public test1ServiceUrl: string;
constructor(public configService: ConfigurationService) {
this.test1ServiceUrl = this.configService.config.test1ServiceUrl;
}
}
</code></pre>
<p>It works fine with all the components which are defined within the <code><router-outlet></router-outlet></code>. But the same implementation in a component outside the <code><router-outlet></router-outlet></code> does not work.<br>
When I debug the respective constructor of the component where it does not work it says that <code>configService</code> is <code>null</code>.<br>
Why is the <code>APP_INITIALIZER</code> executed before the constructor of a component inside the <code><router-outlet></router-outlet></code> is called but not before the constructor of a component outside the <code><router-outlet></router-outlet></code>?</p> | 49,707,898 | 3 | 1 | null | 2018-04-07 13:24:48.093 UTC | 3 | 2021-03-13 15:02:16.49 UTC | 2019-08-13 19:50:13.377 UTC | null | 826,983 | null | 4,070,724 | null | 1 | 31 | angular|typescript | 54,209 | <p>Due to how <code>APP_INTIALIZER</code> <a href="https://github.com/angular/angular/blob/5.2.9/packages/core/src/application_init.ts#L62" rel="noreferrer">works</a>, it's expected that asynchronous initializers return promises, but your implementation of <code>APP_INTIALIZER</code> multiprovider doesn't because <code>loadConfigurationData</code> function doesn't return anything.</p>
<p>It should be something like:</p>
<pre><code>loadConfigurationData(): Promise<Configuration> {
return this.http.get<Configuration>(`${this.originUrl}${this.configUrlPath}`)
.do(result => {
this.configData = result;
})
.toPromise();
}
</code></pre> |
44,380,771 | When the dereference operator (*) is overloaded, is the usage of *this affected? | <p>For example,</p>
<pre><code>class Person{
string name;
public:
T& operator*(){
return name;
}
bool operator==(const Person &rhs){
return this->name == rhs.name;
}
bool operator!=(const Person &rhs){
return !(*this == rhs); // Will *this be the string name or the Person?
}
}
</code></pre>
<p>If <code>*this</code> ends up dereferencing <code>this</code> to a <code>string</code> instead of a <code>Person</code>, is there a workaround that maintains the usage of <code>*</code> as a dereference operator outside the class?</p>
<p>It would be quite a hindrance if I couldn't overload <code>*</code> without giving up usage of <code>*this</code>.</p> | 44,380,818 | 2 | 2 | null | 2017-06-06 03:07:15.693 UTC | 2 | 2017-06-06 14:39:16.19 UTC | 2017-06-06 11:00:28.147 UTC | null | 3,982,001 | user7547935 | null | null | 1 | 28 | c++|pointers|operator-overloading|this|dereference | 4,572 | <blockquote>
<p>If <code>*this</code> ends up dereferencing <code>this</code> to a string instead of a <code>Person</code>, is there a workaround that maintains the usage of <code>*</code> as a dereference operator outside the class?</p>
</blockquote>
<p>No. <code>*this</code> will be <code>Person&</code> or <code>Person const&</code> depending on the function. The overload applies to <code>Person</code> objects, not pointers to <code>Person</code> objects. <code>this</code> is a pointer to a <code>Person</code> object.</p>
<p>If you use:</p>
<pre><code> Person p;
auto v = *p;
</code></pre>
<p>Then, the <code>operator*</code> overload is called.</p>
<p>To call the <code>operator*</code> overload using <code>this</code>, you'll have to use <code>this->operator*()</code> or <code>**this</code>.</p> |
21,422,029 | How to handle date conversion error in SQL? | <p>So I'm trying to convert strings in an SQL databse into datetime values.</p>
<p>I have some dates in a table like this:</p>
<pre><code>23/12/2013 16:34:32
24/12/2013 07:53:44
24/12/2013 09:59:57
24/12/2013 12:57:14
24/12/2013 12:48:49
24/12/2013 13:04:17
24/12/2013 13:15:47
24/12/2013 13:21:02
24/12/2013 14:01:28
24/12/2013 14:02:22
24/12/2013 14:02:51
</code></pre>
<p>They are stored as strings unfortunately </p>
<p>And I want to convert them to datetime</p>
<pre><code>SELECT CONVERT(datetime, analysed, 103 )
FROM OIL_SAMPLE_UPLOAD
</code></pre>
<p>However I get this message when I run the query</p>
<blockquote>
<p>The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.</p>
</blockquote>
<p>Presumably because some values are badly formed (although I am yet to spot any of these)</p>
<p>It's ok if some values don't convert, I just need a way of handling this situation. </p>
<p>Something like ISNULL(CONVERT(datetime, analysed, 103 )) would be good except that the convert function does not return NULL when it fails. </p> | 21,422,078 | 3 | 1 | null | 2014-01-29 04:20:52.937 UTC | null | 2016-05-13 09:00:38.553 UTC | null | null | null | null | 2,040,876 | null | 1 | 12 | sql|string|tsql|error-handling|type-conversion | 57,458 | <p>For SQL Server you can use <a href="http://technet.microsoft.com/en-us/library/ms187347.aspx" rel="noreferrer"><strong>ISDATE()</strong></a> function to check whether value is valid date</p>
<pre><code>SELECT CASE WHEN ISDATE(analysed)=1 THEN CONVERT(datetime, analysed, 103 )
ELSE '' END
FROM OIL_SAMPLE_UPLOAD
</code></pre> |
21,681,084 | Decoding YouTube's error 500 page | <p>This is YouTube's 500 page. Can anyone help decode this information?</p>
<pre><code><p>500 Internal Server Error<p>
Sorry, something went wrong.
<p>A team of highly trained monkeys has been dispatched to deal with this situation.<p>
If you see them, show them this information:
AB38WENgKfeJmWntJ8Y0Ckbfab0Fl4qsDIZv_fMhQIwCCsncG2kQVxdnam35
TrYeV6KqrEUJ4wyRq_JW8uFD_Tqp-jEO82tkDfwmnZwZUeIf1xBdHS_bYDi7
6Qh09C567MH_nUR0v93TVBYYKv9tHiJpRfbxMwXTUidN9m9q3sRoDI559_Uw
FVzGhjH5-Rd1GPLDrEkjcIaN_C3xZW80hy0VbJM3UI5EKohX35gZNK2aNi_8
Toi9z3L8lzpFTvz5GyHygFFBFEJpoRRJSu3CbH5S2OxXEVo4HgaaBTV7Dx_1
Zs1HZvPqhPIvXg9ifd4KZJiUJDFS8grPLE7bypFsRamyZw-OCVyUHsGQKBwu
77pTtRwpF3hOxYLxM4KnAyiY1N6yrASSWyaeumRDENAoEEe8i8MRxzifqHuR
leatvNMiwsg1pbSl7IIiaKljZaD9UkRms4Kvz1uYUNk4AwXnJ9-Wq44ufMPl
syiHp_LwaeqyuxXykJMl-SA9p05VrJc4kCETUW3Ybp0yTYvVrqggo56A0ofC
OiyAmifQA9pdYVGeumrQtbFlFyDyG9VKNpzn5lqutxFZPsS8xjiILfF3bETD
H4aUb5fT4iERFsEL7S-ClsXiA4yAJdAcNH-OhGg9ipAaIxRRTOR5P1MYx6s6
-OrqgpT5VEaEx2hMpS1afaMd2_F21sxvcz2d8sCpEceHHSfsntTth6talYeD
4l63aUTbbCKV1lHxKWxdUjACFKRobeAvIpcJPcdHSN3CNQI-LlIWIx9jeyBU
tDcL6S6GpRG_Z2of9fmw0LHpVU5hKlQ3lCPd4pVP6J02yrsBi0S9OLoE9jmM
T2FfCvU1sWUCsrZu4-UPflXMyRnFK8aN8DYiwWWE8OvnLQ-LIaRDhjp29u9a
LT6Lh4KxEmWF5XeZTwrzJxtuDLVomxVD5mpwFvK0YSoaz9dnPGXb0Fm2txSL
BvGssSrWBJ4FeR6eEEkd_UkQ-aUnPv2W-POox17n54wzTwLugYjslRenMzmk
I4_jlXcx9NpKmUg7Pa0qJuaElt-ZymPv6h0cXRUlyZtS0iT9-CQOHWLYMi3I
kKrYa6bKUCAj058JEderSnbXqGEMvwBeZ_xgJpAjJiSgMOxJPokhbS6ezIv4
1JNr_dvQyvu4vh-YQNZ37fNTqQcoDZtYflBsJjuGrJlmIcqBYufB9g6nUaOE
xPAKjPdvZ_z1Rn_8sWVf8NHNBBKGe5lgDgBxypsV0kIwVa9QOlehivOaieBI
tmqHNdQIfdob0XUTEBPSeLj9hmw3Bqplc3gqUfFhIvpHml6dOTbjBhfkq0TE
5yCRHL2VSe2Xt9_i8SPQA2yCtJVO8HP6pnohmxqlBWSTE8Xj87PI6quX7f9i
0W6PdtkMYaGJsd_Ly_4Ag-KmGNHN585tF9eC5HeQ8Gz-vHZWOUiM4OQAG9UA
31ENOAjHtYb--ketbUcdX_FdjGiPtI_GxYeBqEShICotcd-S-E3bEGO-77M2
CuUUdB1AUYVDZR81XejVG5kSWsrz-p1qZ-6sSpSHCp114C6PheQPCwRHEr_1
AS-DkZfIuZ-w8XAo6pHIwvnv0dORSo-hPFgw1rw2VE4aKsgeMc7ZoPUxby1d
Zr-o-0X4ZMgxoQHw_Ub27rTTHxS5Czt_vgBPq7k5OK5dm6b7JCs6Dbn2dsIA
AakPL26t4smr8IiPAnqNC2sn7vxSiAe9mTJ670eNc6C9dCSGwqzqSURiLHmT
kFyLhNSOdipttECmSSA1qh_E0K4LUhiOq7MFDEzg9CLD8kuJrqpEGgltYpD-
8lk7KEpyjMqbWFs-qeD8uJpsVfY2ac1C67OmyGzkERVoC245-YXuNCP8KUZH
LGzRm9jXwUP_piDETX0N5xj34VOCfUTffT1WlWHmB9WRPhwjIsYYy_kgR-uT
kIEDQ23NVUEGgDoryl-ymysIfwifjq-lPB3e85dz1PajNxawsCrKNeR_4hhq
zE_E4ete1EgXeAYoeH4UIgrPGXDD-KfoNoB6viNs0GzNU9czD9Avr-tDtARO
HBLSLIVRYq8caMA-jvpplTOMoDdmUMUWytf4Y_F5tKTpNtLPaAe1py1IgZBl
lfAGY9L_k5slelh_9gUBEkURxS2oMGf2gdSeDdRBxKKx5tF1b-cuMLK6JYZJ
vbGFYSsSENOkHrHEo9NdTwTi7NON9ZgRJgh7OaENK4TFCXrhKc4C6cyJs-V_
HZ0Q-B8XDyjL0qudg_0rJbjTNpNZajT_1WGsnhsTTAgMCGtTsj1T8vNx2LuX
lPQV30nUKpukdCP3zuiE9_aeJQ-nzf3dMQ-KnZU5APmGcIP_u2be6blieMWH
qVax1asKmuIjslh49ceM6lRt3Ia2bHUB8b1TMSjU4I79KPqc3clDnD8quNnU
cRkgfJ_8LCEoH7jml_2TNV0fLuH_9IOXF3jKjhT9K5f-e5N06GmPQLzdqzeQ
MnEtHuDcf4IizyKnB5GUXoNfQxbScQEzztQ_nHMYfF-E8KqoxxlK-Z0wfEDv
dJpL3mcNfFu_vz-_LJ0oI4dE0-vthsxbpTxVQkdI0E5XSi4nYfLqhXompk4j
gpxcHBjsXVbWcnelWhhQP15gCApj6Gz_ddRtk_uxiyiqZ44oUUDcl1KeWMTf
yhKDj7jgGNzTOkUsXZRPb9M77-ZYPuL2wR68E3b9PC_mS6HBHiUxQ7pXvkwS
Bi2CoFgd9SqBXk2O5I_BPaEoA8Aorazw4OvDrmTQrCk4OkGPKRukE4Ci2RMq
TZIYbBz-v3QxmOKHJoMXPNOfj93TRWpmlAd6iHCH6BVlSdfgfjdbHeD0b0ct
qXC_-S5fr1XFBuaZwaUTrBPxU-3IxWLp-dx7wpKcFykqKnByYpkzR3twKEXc
z--CZV79Qk3ZTMY9ATia4HbyhoAqY_hV9GKAHQdU_C-9qwYt0rliNUcizlBc
RHcwzoMyx30ciwbE8e9QsEH_AMa3E2ezuhjTqQlAG33_Gy5Bwe7fj6zNR0ud
jjpcNVf-wprWHEYxMcKwjCQvEHBtv6TnCHkgi_AOtPzzm3aYkMc_ysdNAnI7
DE_T9S5Mkcs6VdT2DWgUN_UC-oAw27xej0aTIn0GckXPDcLBgvrUhUPU3FRn
lW65syvFvxFmBOiCAEHD1q6Is1XhIf8vE6y0FMdNEWSMUW5rQG8f3KP_pjqG
XlUHnGrQPQysylrczHOj4E3WTT918xg2vrXVraDJbCYnJpaWp8m94iqZw2gJ
I_0UWOAZJMCYWz5jYf2DanCOBaGeZIO-UsWorP6YV3yHehirZ_Lc6KtaUorb
bm_BnnCqGVZypL4k6cDy-4GyO2GNohXzN-VWqbAIUQIat9w6RsDpzpS2DIap
96aMBDg24D73RhFTEgCSunPpbbGrDVU3GFkuTGFFBQWNfAU_F22XtoPr_ZB0
1zZPrBVXrEhebvrzp0Z31_sIT8zLop_oaSRvykbyJKKxucARfPee-d0xlgWN
WwKKtl49WVMhhu0OfDScH3knAVdv0LDAyt1fo3WF8jxdp7J9Hn3OWF3rcn0p
zw0gt6YV_6FRy_UbZmpLBvEhZQKUfKuxp6LK-SfHOilT29ERg9LJZhnyluTV
HELRtkJIcHzvphXupCIaIgZispYxHNSmAfze2cshWBYizGTBSKXWgrJeo7Q6
kEjim72yKaJ8JaLzMQFPxtQxhtvHRw94dCuXcajg3nE_r_9t7D8RicqF-CVV
tvp-rHMPhhizlgfixHWXrPB7reTtftT64pOSl5vUop8gTlbeW5Kg7WQAPNfp
zUH8YcAo0xDLJHA-FgTM4mYGih41rKaKKteWRFGU-fIyEzeO1s35tbGzlZ7R
btUG_fCpIbaJmucMZK9OzVBSfBgTBtFSesqKq6hIc8HctGcj5LPUfP9DRqqe
CrBi6bPjTlzrjaxJoU6oRq4ZtiBG38skOAaCUk61tpjilkq1fmWe2ByvLXhp
O2furZoiwNrizYmUmAW3ak3iSneScA64M-9apdZwhhEgpqyw5mUMYNT5SOOf
xZePlgXxhlL81t3KlofdbzT0w6tlbbT0NSbj9Q_zNkeZ8ar5aeMgTR-pJACg
baB20YVezziX-yboCF-uIptCTFNV
</code></pre>
<p>(Source: <a href="https://news.ycombinator.com/item?id=7210750" rel="noreferrer">this post on HN</a>)</p> | 21,685,027 | 5 | 1 | null | 2014-02-10 15:24:11.047 UTC | 18 | 2017-06-16 18:29:19.433 UTC | 2014-03-14 11:09:56.353 UTC | null | 247,441 | null | 247,441 | null | 1 | 68 | youtube | 63,889 | <p>The debug information contained in the (urlsafe-)base64 blob is likely encrypted.</p>
<p>Think about it from Google's perspective: You would want to display a stack trace, relevant headers of the http request and possibly some internal state of the user session to help a developer debug the situation. On the other hand all that information might contain sensitive information that you don't want the general public to see or that might endanger the user if he copy'n pastes it in a public support forum.</p>
<p>If I was to take a guess of the format I would imagine:</p>
<ul>
<li>A public identifier of the key used for encryption (their servers could use different keys then)</li>
<li>The debug data encrypted using an authenticated encryption scheme</li>
<li>Additional data for error correction when <a href="https://news.ycombinator.com/item?id=7211569" rel="noreferrer">OCR has to be used</a></li>
</ul>
<p>For statistical analysis of the format it would be interesting to sample a lot of these error messages and see if some parts of the message are less random than you would expect from encrypted data (symmetrical encrypted data should follow a uniform distribution).</p> |
42,381,557 | Changing source branch for PR on Github | <p>I accidentally created a pull request from the master-branch of my fork of a repo.</p>
<p>While trying to rebase it I noticed that all of these changes were pushed into that pull request — due to the fact that you can simply <code>Add more commits by pushing to the master branch on username/repo</code></p>
<ul>
<li><strong>Can you change the source branch of a pull request <em>after</em> the pull request has been submitted?</strong></li>
</ul>
<p>I see you can edit the base branch, but that's obviously not what I'm after.</p> | 42,381,583 | 3 | 1 | null | 2017-02-22 02:22:30.053 UTC | 3 | 2021-05-28 10:09:43.7 UTC | null | null | null | null | 2,171,758 | null | 1 | 36 | git|github | 17,868 | <p>AFAIK, you cannot change the source branch after creating a Pull Request. You have to create a new one instead.</p>
<p>For future reference, the established best practice is to create a new branch before making any commits. You should not commit directly to master, especially when contributing to team projects.</p>
<p><strong>Side note:</strong></p>
<blockquote>
<p>you can simply Add more commits by pushing to the master branch on username/repo</p>
</blockquote>
<p>More correctly, any changes to the target branch of a PR are automatically included in the PR.</p> |
42,183,672 | How to implement a Navbar Dropdown Hover in Bootstrap v4? | <p>I am a bit confused on the new bootstrap version since they changed dropdown menus to divs:</p>
<pre><code><nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown link
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
</ul>
</div>
</nav>
</code></pre>
<p>Do you guys have any idea to get a hover dropdown in the Dropdown link in that snippet without adding additional script code (only css and script from bootstrap)? I already saw the bootstrap css classes and I can't relate with the ones in bootstrap V3 (I accomplish this without adding jquery in V3). </p> | 42,183,824 | 22 | 2 | null | 2017-02-12 02:41:17.503 UTC | 36 | 2021-08-13 07:27:57.96 UTC | 2018-11-19 19:04:18.577 UTC | null | 4,802,075 | null | 4,712,672 | null | 1 | 61 | html|css|twitter-bootstrap | 166,663 | <p><strong>Simple, CSS only</strong> solution: </p>
<pre><code>.dropdown:hover>.dropdown-menu {
display: block;
}
</code></pre>
<p>When clicked, it will still get the class <code>show</code> toggled to it (and will remain open when no longer hovered).</p>
<hr>
<p>To get around this <strong><em>properly</em></strong> is to use events and properties reserved to pointer based devices: jQuery's <code>mouseenter</code>, <code>mouseleave</code> and <code>:hover</code>. Should work smoothly, intuitively, while not interfering <strong><em>at all</em></strong> with how the dropdown works on touch based devices. Try it out, let me know if it works for you:</p>
<p>Complete <strong>jQuery solution</strong> (<em>touch</em> untouched):</p>
<p>Pre v4.1.2 solution (<strong><em>deprecated</em></strong>):</p>
<pre class="lang-js prettyprint-override"><code>$('body').on('mouseenter mouseleave','.dropdown',function(e){
var _d=$(e.target).closest('.dropdown');
if (e.type === 'mouseenter')_d.addClass('show');
setTimeout(function(){
_d.toggleClass('show', _d.is(':hover'));
$('[data-toggle="dropdown"]', _d).attr('aria-expanded',_d.is(':hover'));
},300);
});
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('body').on('mouseenter mouseleave','.dropdown',function(e){
var _d=$(e.target).closest('.dropdown');
if (e.type === 'mouseenter')_d.addClass('show');
setTimeout(function(){
_d.toggleClass('show', _d.is(':hover'));
$('[data-toggle="dropdown"]', _d).attr('aria-expanded',_d.is(':hover'));
},300);
});
/* this is not needed, just prevents page reload when a dd link is clicked */
$('.dropdown a').on('click tap', e => e.preventDefault())</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href>Navbar</a>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href>Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href>Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href>Pricing</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown link
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href>Action</a>
<a class="dropdown-item" href>Another action</a>
<a class="dropdown-item" href>Something else here</a>
</div>
</li>
</ul>
</div>
</nav></code></pre>
</div>
</div>
</p>
<hr>
<p><a href="https://github.com/twbs/bootstrap/issues/26423" rel="noreferrer">v4.1.2 shiplist</a> introduced <a href="https://github.com/twbs/bootstrap/pull/26756" rel="noreferrer">this change</a> to how dropdowns work, making the solution above no longer work.<br>
Here's the <strong><em>up to date</em></strong> solution for having the dropdown open on hover in <strong>v4.1.2</strong> and above:</p>
<pre class="lang-js prettyprint-override"><code>function toggleDropdown (e) {
const _d = $(e.target).closest('.dropdown'),
_m = $('.dropdown-menu', _d);
setTimeout(function(){
const shouldOpen = e.type !== 'click' && _d.is(':hover');
_m.toggleClass('show', shouldOpen);
_d.toggleClass('show', shouldOpen);
$('[data-toggle="dropdown"]', _d).attr('aria-expanded', shouldOpen);
}, e.type === 'mouseleave' ? 300 : 0);
}
$('body')
.on('mouseenter mouseleave','.dropdown',toggleDropdown)
.on('click', '.dropdown-menu a', toggleDropdown);
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function toggleDropdown (e) {
const _d = $(e.target).closest('.dropdown'),
_m = $('.dropdown-menu', _d);
setTimeout(function(){
const shouldOpen = e.type !== 'click' && _d.is(':hover');
_m.toggleClass('show', shouldOpen);
_d.toggleClass('show', shouldOpen);
$('[data-toggle="dropdown"]', _d).attr('aria-expanded', shouldOpen);
}, e.type === 'mouseleave' ? 300 : 0);
}
$('body')
.on('mouseenter mouseleave','.dropdown',toggleDropdown)
.on('click', '.dropdown-menu a', toggleDropdown);
/* not needed, prevents page reload for SO example on menu link clicked */
$('.dropdown a').on('click tap', e => e.preventDefault())</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav></code></pre>
</div>
</div>
</p>
<hr>
<p><em>Important note:</em> If using the jQuery solution, it is important to remove the CSS one (or the dropdown won't close when <code>.dropdown-toggle</code> is clicked or when an menu option is clicked).</p> |
7,644,968 | HttpSession - how to get the session.setAttribute? | <p>I'm creating HttpSession container this way:</p>
<pre><code>@SessionScoped
@ManagedBean(name="userManager")
public class UserManager extends Tools
{
/* [private variables] */
...
public String login()
{
/* [find user] */
...
FacesContext context = FacesContext.getCurrentInstance();
session = (HttpSession) context.getExternalContext().getSession(true);
session.setAttribute("id", user.getID());
session.setAttribute("username", user.getName());
...
System.out.println("Session id: " + session.getId());
</code></pre>
<p>And I have SessionListener which should gives me info about session created: </p>
<pre><code>@WebListener
public class SessionListener implements HttpSessionListener
{
@Override
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
System.out.println("Session id: " + session.getId());
System.out.println("New session: " + session.isNew());
...
}
}
</code></pre>
<p>How can I get the <code>username</code> attribute? </p>
<p>If I'm trying it using <code>System.out.println("User name: " + session.getAttribute("username"))</code> it throws <code>java.lang.NullPointerException</code>..</p> | 7,645,160 | 2 | 3 | null | 2011-10-04 08:15:26.907 UTC | 3 | 2011-10-04 13:08:47.753 UTC | 2011-10-04 13:08:47.753 UTC | null | 731,696 | null | 731,696 | null | 1 | 9 | java|jsf|jakarta-ee|listener | 99,135 | <p>The <code>HttpSessionListener</code> interface is used to monitor when sessions are created and destroyed on the application server. The <code>HttpSessionEvent.getSession()</code> returns you a session that is newly created or destroyed (depending if it's called by <code>sessionCreated</code>/<code>sessionDestroyed</code> respectively).</p>
<p>If you want an existing session, you will have to get the session from the request.</p>
<pre><code>HttpSession session = request.getSession(true).
String username = (String)session.getAttribute("username");
</code></pre> |
7,082,997 | Does int.class equal Integer.class or Integer.TYPE in Java? | <p>Let's imagine one retrieves the declaring type of a <code>Field</code> using reflection.</p>
<p>Which of the following tests will correctly indicate whether one is dealing with an <code>int</code> or an <code>Integer</code>?</p>
<pre><code>Field f = ...
Class<?> c = f.getDeclaringClass();
boolean isInteger;
isInteger = c.equals(Integer.class);
isInteger = c.equals(Integer.TYPE);
isInteger = c.equals(int.class);
isInteger = ( c == Integer.class);
isInteger = ( c == Integer.TYPE);
isInteger = ( c == int.class);
</code></pre> | 7,083,456 | 2 | 2 | null | 2011-08-16 18:16:38.86 UTC | 9 | 2014-09-21 08:34:46.953 UTC | null | null | null | null | 520,957 | null | 1 | 24 | java|reflection|primitive-types|boxing | 31,525 | <p>Based on <code>Field.getType()</code> (instead of <code>f.getDeclaringClass()</code>), I get the following:</p>
<pre><code>Type: java.lang.Integer
equals(Integer.class): true
equals(int.class) : false
equals(Integer.TYPE) : false
== (Integer.class) : true
== (int.class) : false
== (Integer.TYPE) : false
Type: int
equals(Integer.class): false
equals(int.class) : true
equals(Integer.TYPE) : true
== (Integer.class) : false
== (int.class) : true
== (Integer.TYPE) : true
Type: java.lang.Object
equals(Integer.class): false
equals(int.class) : false
equals(Integer.TYPE) : false
== (Integer.class) : false
== (int.class) : false
== (Integer.TYPE) : false
</code></pre>
<p>Meaning the following is true:</p>
<pre><code>Integer.TYPE.equals(int.class)
Integer.TYPE == int.class
</code></pre>
<p>Meaning if I want to find out whether I am dealing with an <code>int</code> or an <code>Integer</code>, I can use any of the following tests:</p>
<pre><code>isInteger = c.equals(Integer.class) || c.equals(Integer.TYPE);
isInteger = c.equals(Integer.class) || c.equals(int.class);
isInteger = (c == Integer.class) || (c == Integer.TYPE);
isInteger = (c == Integer.class) || (c == int.class );
</code></pre>
<p>Is there a corner case I am missing? If yes, please comment.</p> |
23,436,711 | Generate download link for a single folder in GitHub | <p>I have a repository that has several folders of code. I'd like to be able to provide a link to the code in a single folder so another user could download just the relevant bits of code without being bloated by the rest of the codebase and without requiring that they have git installed on their machine. </p>
<p>Of course, they can browse the code files inside of the folder online, but that isn't very helpful if they want to run a single project.</p>
<p>Here are several other similar questions, and why I don't think they address my particular issues:</p>
<ul>
<li><a href="https://stackoverflow.com/q/2751227/1366033">How to download source in .zip format from GitHub?</a>
<ul>
<li>Only provides a way to download the entire project, otherwise perfect.</li>
</ul></li>
<li><a href="https://stackoverflow.com/q/14293829/1366033">Github download folder as zip</a>
<ul>
<li>This answer is for build artifacts. I don't want to upload the source code twice just so I can provide a download link to it.</li>
</ul></li>
<li><a href="https://stackoverflow.com/q/7106012/1366033">Download a single folder or directory from a GitHub repo</a>
<ul>
<li>Requires using git commands to get a single folder. I'd rather have the link accessible to multiple people without requiring they have git installed.</li>
</ul></li>
<li><a href="https://stackoverflow.com/q/4604663/1366033">GitHub - Download single files</a>
<ul>
<li>Only provides mechanism for downloading single files, not folders</li>
</ul></li>
</ul>
<p>In case it helps provide a concrete example, here's a folder that I would like to be able to download via a link:<br>
<a href="https://github.com/KyleMit/CodingEverything/tree/master/MVCBootstrapNavbar/Source%20Code" rel="noreferrer">https://github.com/KyleMit/CodingEverything/tree/master/MVCBootstrapNavbar/Source%20Code</a></p>
<p>Is there any way to do this?</p> | 23,440,333 | 4 | 1 | null | 2014-05-02 20:48:52.907 UTC | 5 | 2021-06-17 15:23:44.433 UTC | 2017-05-23 10:31:20.16 UTC | null | -1 | null | 1,366,033 | null | 1 | 14 | github|github-api | 40,171 | <p>no, not through a direct link.</p>
<p>"Loading" a folder from a git repo only means <strong><a href="https://stackoverflow.com/a/13738951/6309">sparse checkout</a></strong> (partial clone).</p>
<p>Any other solution would indeed mean building an artifact and upload it.</p>
<p>Update August 2016 (2 years later): you can have a look at <a href="https://stackoverflow.com/a/38879691/6309">this answer</a> and the <a href="https://minhaskamal.github.io/DownGit/#/home" rel="nofollow noreferrer">DownGit project</a>, by <a href="https://stackoverflow.com/users/4684058/minhas-kamal">Minhas Kamal</a>.</p> |
31,708,832 | How to reference a dll to Visual Studio without lib file | <p>I needed to add a third party library to my project, and they only supply a .dll file (no .lib)</p>
<p>I have added the dll to the project by going to the project Property Page under Common Properties -> References -> Add New Reference</p>
<p>I can see the dll under the External Dependencies folder in the Solution Explorer, so I guess it was included correctly.</p>
<p>But how do I reference the dll?
When I try to add an instance variable (For example, MCC::iPort::ASCII iPort) to access the dll class, I get Error: name followed by '::' must be a class or namespace name, but I know thats the class name I can see it in the dll info under External Dependencies.</p> | 31,710,797 | 2 | 1 | null | 2015-07-29 18:53:26.383 UTC | 12 | 2021-01-17 10:12:00.653 UTC | 2018-06-12 15:04:13.547 UTC | null | 13,860 | null | 4,708,080 | null | 1 | 20 | c++|dll|visual-studio-2013 | 26,164 | <p>The only way to access a bare DLL without a .lib file is to load the DLL explicitly with <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175.aspx" rel="noreferrer"><code>LoadLibrary()</code></a>, get pointers to the exported functions you want to access with <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms683212.aspx" rel="noreferrer"><code>GetProcAddress()</code></a>, and then cast those pointers to the proper function signature. If the library exports C++ functions, the names you have to pass to <code>GetProcAddress()</code> will be mangled. You can list the exported names with <a href="https://msdn.microsoft.com/en-us/library/c1h23y6c.aspx" rel="noreferrer"><code>dumpbin /exports your.dll</code></a>.</p>
<pre><code>extern "C" {
typedef int (*the_func_ptr)( int param1, float param2 );
}
int main()
{
auto hdl = LoadLibraryA( "SomeLibrary.dll" );
if (hdl)
{
auto the_func = reinterpret_cast< the_func_ptr >( GetProcAddress( hdl, "the_func" ) );
if (the_func)
printf( "%d\n", the_func( 17, 43.7f ) );
else
printf( "no function\n" );
FreeLibrary( hdl );
}
else
printf( "no library\n" );
return 0;
}
</code></pre>
<p>As has been noted by others, a LIB file can be created. Get the list of exported functions from <code>dumpbin /exports your.dll</code>:</p>
<pre><code>ordinal hint RVA name
1 0 00001000 adler32
2 1 00001350 adler32_combine
3 2 00001510 compress
(etc.)
</code></pre>
<p>Put the names into a DEF file:</p>
<pre><code>EXPORTS
adler32
adler32_combine
compress
(etc.)
</code></pre>
<p>Now make the LIB file:</p>
<pre><code>lib /def:your.def /OUT:your.lib
</code></pre>
<p>For cases where the name has been decorated, either by C++ name mangling or 32-bit <code>stdcall</code> calling convention, simply copy and paste whatever names <code>dumpbin</code> reported, mangling and all.</p> |
31,681,715 | Passing multiple parameters to controller in Laravel 5 | <p>In my application, a user has the ability to remind another user about an event invitation. To do that, I need to pass both the IDs of the event, and of the user to be invited.</p>
<p>In my route file, I have:</p>
<pre><code>Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController@remindHelper']);
</code></pre>
<p>In my view, I have:</p>
<pre><code>{!!link_to_route('remindHelper', 'Remind User', $parameters = array($eventid = $event->id, $userid = $invitee->id) )!!}
</code></pre>
<p>In my controller, I have:</p>
<pre><code> public function remindHelper($eventid, $userid)
{
$event = Events::findOrFail($eventid);
$user = User::findOrFail($userid);
$invitees = $this->user->friendsOfMine;
$invited = $event->helpers;
$groups = $this->user->groupOwner()->get();
return view('events.invite_groups', compact('event', 'invitees', 'invited', 'groups'));
}
</code></pre>
<p>However, when I hit that route, I receive the following error:</p>
<pre><code>Missing argument 2 for App\Http\Controllers\EventsController::remindHelper()
</code></pre>
<p>I'm sure I have a formatting error in my view, but I've been unable to diagnose it. Is there a more efficient way to pass multiple arguments to a controller?</p> | 31,682,421 | 5 | 2 | null | 2015-07-28 16:08:45.463 UTC | 5 | 2021-11-11 18:03:50.983 UTC | 2015-07-28 16:55:22.487 UTC | null | 4,357,745 | null | 4,357,745 | null | 1 | 29 | php|laravel|laravel-5|laravel-blade | 133,415 | <p>When you define this route:</p>
<pre><code>Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController@remindHelper']);
</code></pre>
<p>You are saying that a single URI argument will be passed to the method.</p>
<p>Try passing the two arguments, like:</p>
<pre><code>Route::get('events/{event}/remind/{user}', [
'as' => 'remindHelper', 'uses' => 'EventsController@remindHelper']);
</code></pre>
<p>View:</p>
<pre><code>route('remindHelper',['event'=>$eventId,'user'=>$userId]);
</code></pre> |
19,288,900 | ImportError: No module named redis | <p>I have installed redis using <code>sudo apt-get install redis-server</code> command but I am receiving this error when I run my Python program:
<code>ImportError: No module named redis</code></p>
<p>Any idea what's going wrong or if I should install any other package as well? I am using Ubuntu 13.04 and I have Python 2.7.</p> | 19,288,952 | 3 | 1 | null | 2013-10-10 06:48:45.69 UTC | 7 | 2018-10-04 07:30:18.17 UTC | null | null | null | null | 2,414,957 | null | 1 | 36 | python|ubuntu|redis|installation|package | 83,299 | <p>To install redis-py, simply:</p>
<pre><code>$ sudo pip install redis
</code></pre>
<p>or alternatively (you really should be using pip though):</p>
<pre><code>$ sudo easy_install redis
</code></pre>
<p>or from source:</p>
<pre><code>$ sudo python setup.py install
</code></pre>
<p>Getting Started</p>
<pre><code>>>> import redis
>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
'bar'
</code></pre>
<p>Details:<a href="https://pypi.python.org/pypi/redis" rel="noreferrer">https://pypi.python.org/pypi/redis</a></p> |
37,655,393 | how to set multiple CSS style properties in typescript for an element? | <p>Please consider the below snippet. i need to set multiple CSS properties in typescript. for that i have tried the below code.</p>
<pre><code>public static setStyleAttribute(element: HTMLElement, attrs: { [key: string]: Object }): void {
if (attrs !== undefined) {
Object.keys(attrs).forEach((key: string) => {
element.style[key] = attrs[key];
});
}
}
</code></pre>
<p>for the above code i need to pass the parameters as</p>
<pre><code>let elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {font-size:'12px', color : 'red' , margin-top: '5px'});
</code></pre>
<p>But the above code throws error(tslint) as Element implicitly has an 'any' type because index expression is not of type 'number'.
(property) HTMLElement.style: CSSStyleDeclaration.</p>
<p>Please help me !!!</p> | 44,147,914 | 7 | 1 | null | 2016-06-06 10:44:54.107 UTC | 3 | 2022-04-08 08:20:40.703 UTC | null | null | null | null | 6,280,446 | null | 1 | 28 | css|typescript|tslint | 102,220 | <p>Try using <code>setAttribute</code>. TypeScript does not have the <code>style</code> property on <code>Element</code>.</p>
<pre><code>element.setAttribute("style", "color:red; border: 1px solid blue;");
</code></pre>
<p>Some related discussion in this GitHub issue:
<a href="https://github.com/Microsoft/TypeScript/issues/3263" rel="noreferrer">https://github.com/Microsoft/TypeScript/issues/3263</a></p> |
11,546,177 | How to read lines of text from file and put them into an array | <p>I created a text file <code>love.txt</code>:</p>
<pre><code>i love you
you love me
</code></pre>
<p>How do I store them into separate array, namely <code>line1</code> and <code>line2</code> and then display them out in console?</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line1[30];
string line2[30];
ifstream myfile("love.txt");
int a = 0;
int b = 0;
if(!myfile)
{
cout<<"Error opening output file"<<endl;
system("pause");
return -1;
}
while(!myfile.eof())
{
getline(myfile,line1[a],' ');
cout<<"1."<<line1[a]<<"\n";
getline(myfile,line2[b],' ');
cout<<"2."<<line2[b]<<"\n";
}
}
</code></pre> | 11,546,490 | 4 | 4 | null | 2012-07-18 16:36:26.27 UTC | 6 | 2022-02-18 00:56:26.63 UTC | 2012-09-30 08:48:07.653 UTC | null | 635,608 | null | 1,526,669 | null | 1 | 1 | c++|arrays | 79,118 | <p>Try specifying the last argument as <b>'\n' </b> in both <code>getline()</code> functions:</p>
<pre><code>getline(myfile, line1[a], '\n');
</code></pre>
<p>instead of</p>
<pre><code>getline(myfile, line1[a], ' ');
</code></pre> |
36,977,223 | how should i read a csv file without the 'unnamed' row with pandas? | <p>I am writing to a .csv file with:</p>
<pre><code>my_data_frame.to_cav("some_path")
</code></pre>
<p>When trying to read the file with:</p>
<pre><code>pd.read_csv("some_path")
</code></pre>
<p>I can tell that an unnamed column was added.
How can i fix that?</p> | 36,977,268 | 1 | 1 | null | 2016-05-02 07:32:01.037 UTC | 3 | 2016-05-02 07:34:23.223 UTC | null | null | null | null | 6,275,292 | null | 1 | 18 | python|csv|pandas | 39,256 | <p><code>to_csv()</code> writes an index per default, so you can either disable index when saving your CSV:</p>
<pre><code>df.to_csv('file.csv', index=False)
</code></pre>
<p>or specify an index column when reading:</p>
<pre><code>df = pd.read_csv('file.csv', index_col=0)
</code></pre> |
36,770,716 | MINGW64 "make build" error: "bash: make: command not found" | <p>I am working on Windows 10. I want to run a "make build" in MINGW64 but following error comes up:</p>
<pre><code>$ make build
bash: make: command not found
</code></pre>
<p>I want to build <a href="https://github.com/Masterminds/glide" rel="noreferrer" title="Glide for Golang">Glide for Golang</a></p>
<p>I tried following:</p>
<pre><code>$ sudo yum install build-essential
bash: sudo: command not found
</code></pre>
<p>As well as:</p>
<pre><code>$ yum install build-essential
bash: yum: command not found
</code></pre>
<p>And:</p>
<pre><code>$ apt-cyg build-essential
bash: apt-cyg: command not found
</code></pre>
<p>How can I "work-around" this problem?</p> | 36,771,170 | 7 | 1 | null | 2016-04-21 13:13:04.41 UTC | 15 | 2022-08-31 12:33:44.393 UTC | 2019-03-24 14:51:55.36 UTC | user5845158 | 6,296,561 | user5845158 | null | null | 1 | 66 | bash|go|makefile|mingw|glide-golang | 164,985 | <p>You have to install mingw-get and after that you can run <code>mingw-get install msys-make</code> to have the command make available.</p>
<p>Here is a link for what you want <a href="http://www.mingw.org/wiki/getting_started" rel="noreferrer">http://www.mingw.org/wiki/getting_started</a></p> |
3,265,640 | Why ThreadGroup is being criticised? | <p>I'm aware of current practice of using Executors instead of ThreadGroup:</p>
<ul>
<li>generally preferred way to deal with Threads</li>
<li>catching exceptions from threads, etc...</li>
</ul>
<p>However, what are the inherent <strong>flaws of ThreadGroup</strong> as such (I've heard a vague criticism for that class)?</p>
<p>Thanks for answer.</p>
<p>PS. <a href="https://stackoverflow.com/questions/1649133/what-is-the-benefit-of-threadgroup-in-java-over-creating-separate-threads">this</a> does not seem to answer this question.</p> | 3,265,726 | 1 | 5 | 2010-07-16 14:03:47.93 UTC | 2010-07-16 14:03:47.93 UTC | 9 | 2010-07-16 14:14:41.227 UTC | 2017-05-23 11:46:41.763 UTC | null | -1 | null | 336,184 | null | 1 | 26 | java|multithreading|concurrency|thread-safety | 10,061 | <p>This is explained in <a href="http://www.amazon.co.uk/Effective-Java-Second-Joshua-Bloch/dp/0321356683" rel="noreferrer">Effective Java 2nd Ed.</a>, Item 73.</p>
<blockquote>
<p>Thread groups were originally envisioned as a mechanism
for isolating applets for security purposes. They never really fulfilled this
promise, and their security importance has waned to the extent that they aren’t
even mentioned in the standard work on the Java security model [Gong03].</p>
<p>[...] In an ironic twist, the <code>ThreadGroup</code> API is weak from a thread safety
standpoint. To get a list of the active threads in a thread group, you must invoke
the <code>enumerate</code> method, which takes as a parameter an array large enough to hold
all the active threads. The <code>activeCount</code> method returns the number of active
threads in a thread group, but there is no guarantee that this count will still be
accurate once an array has been allocated and passed to the <code>enumerate</code> method. If
the thread count has increased and the array is too small, the <code>enumerate</code> method
silently ignores any threads for which there is no room in the array.</p>
<p>The API that lists the subgroups of a thread group is similarly flawed. While
these problems could have been fixed with the addition of new methods, they
haven’t, because there is no real need: <strong>thread groups are obsolete</strong>.</p>
<p>Prior to release 1.5, there was one small piece of functionality that was available
only with the <code>ThreadGroup</code> API: the <code>ThreadGroup.uncaughtException</code>
method was the only way to gain control when a thread threw an uncaught exception.
This functionality is useful, for example, to direct stack traces to an application-
specific log. As of release 1.5, however, the same functionality is available
with <code>Thread</code>’s <code>setUncaughtExceptionHandler</code> method.</p>
<p>To summarize, thread groups don’t provide much in the way of useful functionality,
and much of the functionality they do provide is flawed. Thread groups
are best viewed as an unsuccessful experiment, and you should simply ignore their
existence. If you design a class that deals with logical groups of threads, you
should probably use thread pool executors (Item 68).</p>
</blockquote> |
1,536,396 | Adding values to a dropdown <select> box using JQuery | <p>I have a issue with populating values in a box using JQuery.</p>
<p>Instead of adding it underneath each other it adds it next to all other elements</p>
<p>my code</p>
<pre><code>$('#pages option').append($('#t1').val());
</code></pre> | 1,536,405 | 3 | 0 | null | 2009-10-08 08:23:33.533 UTC | 1 | 2014-11-12 09:45:54.08 UTC | null | null | null | null | 131,637 | null | 1 | 5 | jquery | 46,388 | <p>I think you want </p>
<pre><code>$('#pages').append($('#t1').val());
</code></pre>
<p>assuming pages is the id of your <code><select></code>. Also, <code>$('#t1').val()</code> should be an <code><option></code> element, not a value. Something like this</p>
<pre><code> var newOption = $('<option value="'+val+'">'+val+'</option>');
$('#pages').append(newOption);
</code></pre>
<p>or</p>
<pre><code>var newOption = $('<option>');
newOption.attr('value',val).text(val);
$('#pages').append(newOption);
</code></pre>
<p>whichever is easier for you to read.</p>
<p>Here's a <strong><a href="http://jsbin.com/uwevo" rel="noreferrer">Working Demo</a></strong></p> |
1,557,371 | Visual Studio Command Window | <p>What is the usefulness of the Command Window in Visual Studio (menu <em>View</em> -> <em>Other Windows</em> -> <em>Command Window</em>)?</p>
<p>I know that the Visual Studio <a href="http://msdn.microsoft.com/en-us/library/c785s0kz.aspx" rel="noreferrer">Command Window</a> is used to execute commands or aliases directly in the IDE. The MSDN article <em><a href="http://msdn.microsoft.com/en-us/library/c785s0kz.aspx" rel="noreferrer">Command Window</a></em> explains how one can use the command window to print debug statements, but I feel that these can be easier executed in the Immediate Window.</p>
<p>What is the Command Window for?</p> | 1,557,436 | 3 | 3 | null | 2009-10-12 22:50:18.677 UTC | 13 | 2021-08-01 12:44:28.837 UTC | 2012-10-22 15:53:51.353 UTC | null | 63,550 | null | 113,535 | null | 1 | 32 | visual-studio | 24,636 | <p>The Immediate window is mostly used for debugging, variable evaluation, etc. You sound familiar with it, so I won't belabor its usage. For more information on it, check out the MSDN article <em><a href="https://msdn.microsoft.com/en-us/library/f177hahy(v=vs.140).aspx" rel="noreferrer">Immediate Window</a></em>.</p>
<p>The Command window allows you to execute a variety of commands using their aliases. You'll notice that the command window prompt has a <code>></code> character. You can open a file in your solution using <code>of Class1.cs</code>, hit enter, and open it up. In the Find dialog and Immediate window you would need to include the >, making it <code>>of Class1.cs</code>.</p>
<p>Nonetheless, you can do exactly the same thing in the Immediate window by prefixing a command with <code>></code> as well. The Command window saves you an extra keystroke and is ready to go whenever you drop a command alias.</p>
<p>Check out these links for some commands:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/c3a0kd3x.aspx" rel="noreferrer">Predefined Visual Studio Command Aliases</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms171362.aspx" rel="noreferrer">Immediate Window Commands</a></li>
</ul>
<p>For example, to open the Quick Watch window, type <code>??</code> in the command window. Try that in the Immediate window and you'll get:</p>
<pre><code>??
Invalid expression term '?'
</code></pre>
<p>Type <code>>??</code> in the Immediate window, and it'll work.</p> |
8,915,772 | How does Facebook show browser loading progress during AJAX Page Loads? | <p>In order to keep the IM Client logged in at all times Facebook avoids full page loads by using AJAX to load its pages before inserting them into the document.</p>
<p>However, during Facebook AJAX requests the browser appears to be visibly loading; the reload button changes to an X, and the progress indicator built into the browser indicates loading/waiting etc)</p>
<p>I've been able to implement AJAX based navigation successfully, but my browser doesn't show any indication of loading (since the requests are asynchronous) how do Facebook do it?</p> | 8,915,851 | 3 | 1 | null | 2012-01-18 19:02:17.547 UTC | 10 | 2012-01-30 18:18:24.36 UTC | null | null | null | null | 166,303 | null | 1 | 28 | javascript|ajax|facebook|html|pushstate | 5,422 | <p>The browser displays the loading state when there is an element in the document which is loading. Ajax requests are made entirely from within JavaScript; the document is not affected and so the loading state isn't triggered.</p>
<p>On the other hand, most of Facebook's requests are made by inserting a <code><script></code> tag into the document, pointing to a JavaScript file containing the data they want. (Essentially JSONP, except they use a different format.) The browser will displaying its loading state because the <code><script></code> tag is an unloaded element in the document.</p>
<p>This technique/JSONP can expose your site to security risks if you're not careful, because cross-site requests are allowed. Facebook deals with this by generating random URLs for each resource, which are sent to the browser in the initial page load.</p> |
19,467,449 | How to speed up cURL in php? | <p>I'm trying to get embed tweet from Twitter. So, I'm using cURL to get the json back. I wrote a little test but the test takes around 5 seconds as well as when I run locally. So, I'm not sure what am I doing wrong here.</p>
<pre><code>public function get_tweet_embed($tw_id) {
$json_url = "https://api.twitter.com/1/statuses/oembed.json?id={$tw_id}&align=left&omit_script=true&hide_media=false";
$ch = curl_init( $json_url );
$start_time = microtime(TRUE);
$JSON = curl_exec($ch);
$end_time = microtime(TRUE);
echo $end_time - $start_time; //5.7961111068726
return $this->get_html($JSON);
}
private function get_html($embed_json) {
$JSON_Data = json_decode($embed_json,true);
$tw_embed_code = $JSON_Data["html"];
return $tw_embed_code;
}
</code></pre>
<p>When I paste the link and test it from the browser it's really fast. </p> | 19,469,307 | 7 | 0 | null | 2013-10-19 15:03:03.71 UTC | 7 | 2020-08-03 22:38:44.43 UTC | null | null | null | null | 635,162 | null | 1 | 19 | php|rest|twitter | 41,726 | <p>With respect to environment, I've observed in PHP that cURL typically runs very fast in most environments except in places where there is low CPU and there is slower network performance. For example, on localhost on my MAMP installation, curl is fast, on a larger amazon instance, curl is fast. But on a small crappy hosting, i've seen it have performance issues where it is noticeably slower to connect. Though, i'm not sure exactly <em>why</em> that is slower. Also, it sure wasn't 5 seconds slower.</p>
<p>to help determine if its PHP or your environment, you should try interacting with curl via the command line. At least that you'll be able to rule out PHP code being the problem if its still 5 seconds.</p> |
19,507,096 | Python error "import: unable to open X server" | <p>I am getting the following errors when trying to run a piece of python code:</p>
<pre><code>import: unable to open X server `' @ error/import.c/ImportImageCommand/366.
from: can't read /var/mail/datetime
./mixcloud.py: line 3: syntax error near unexpected token `('
./mixcloud.py: line 3: `now = datetime.now()'
</code></pre>
<p>The code:</p>
<pre><code>import requests
from datetime import datetime,date,timedelta
now = datetime.now()
</code></pre>
<p>I really lack to see a problem. Is this something that my server is just having a problem with and not the code itself?</p> | 19,507,173 | 4 | 1 | null | 2013-10-22 00:32:51.803 UTC | 6 | 2022-04-23 03:08:28.39 UTC | 2015-06-22 23:57:58.9 UTC | null | 68,587 | null | 1,044,984 | null | 1 | 61 | python | 88,861 | <p>those are errors from your command shell. you are running code through the shell, not python.</p>
<p>try from a python interpreter ;)</p>
<pre><code>$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> from datetime import datetime,date,timedelta
>>>
>>> now = datetime.now()
>>>
</code></pre>
<p>if you are using a script, you may invoke directly with python:</p>
<pre><code>$ python mixcloud.py
</code></pre>
<p>otherwise, ensure it starts with the proper shebang line:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>... and then you can invoke it by name alone (assuming it is marked as executable):</p>
<pre><code>$ ./mixcloud.py
</code></pre> |
48,722,834 | How to use html datalist with bootstrap? | <p>Given</p>
<pre><code><input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</code></pre>
<p>How to apply bootstrap css to this? I would except just to add <code>class="form-control"</code> and it would be layouted in the same fasion as a select element? But that did not work. Is this tag not supported?</p> | 53,210,095 | 3 | 1 | null | 2018-02-10 16:16:23.207 UTC | 4 | 2021-10-13 22:00:59.44 UTC | null | null | null | null | 1,228,951 | null | 1 | 25 | twitter-bootstrap|bootstrap-4 | 42,267 | <p>I cannot confirm, that bootstrap 4 does generally not work with the <code><input></code>/<code><datalist></code> element. Basically you only apply the <code>select</code> field bootstrap classes to the <code>input</code> field, which then gets the look of a select/dropdown with input functionality, e.g.:</p>
<pre><code><input list="encodings" value="" class="col-sm-6 custom-select custom-select-sm">
<datalist id="encodings">
<option value="ISO-8859-1">ISO-8859-1</option>
<option value="cp1252">ANSI</option>
<option value="utf8">UTF-8</option>
</datalist>
</code></pre>
<p>Looks like that on recent Firefox:</p>
<p><a href="https://i.stack.imgur.com/pL4va.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pL4va.gif" alt="enter image description here" /></a></p> |
38,363,566 | Trouble with UTF-8 characters; what I see is not what I stored | <p>I tried to use UTF-8 and ran into trouble.</p>
<p>I have tried so many things; here are the results I have gotten:</p>
<ul>
<li><code>????</code> instead of Asian characters. Even for European text, I got <code>Se?or</code> for <code>Señor</code>.</li>
<li>Strange gibberish (Mojibake?) such as <code>Señor</code> or <code>新浪新闻</code> for <code>新浪新闻</code>.</li>
<li>Black diamonds, such as Se�or.</li>
<li>Finally, I got into a situation where the data was lost, or at least truncated: <code>Se</code> for <code>Señor</code>.</li>
<li>Even when I got text to <em>look</em> right, it did not <em>sort</em> correctly.</li>
</ul>
<p>What am I doing wrong? How can I fix the <em>code</em>? Can I recover the <em>data</em>, if so, how?</p> | 38,363,567 | 5 | 0 | null | 2016-07-14 00:04:19.833 UTC | 69 | 2022-08-01 10:49:06.807 UTC | 2017-09-03 00:15:46.653 UTC | null | 63,550 | null | 1,766,831 | null | 1 | 99 | mysql|unicode|utf-8|character-encoding|mariadb | 84,506 | <p>This problem plagues the participants of this site, and many others.</p>
<p>You have listed the five main cases of <code>CHARACTER SET</code> troubles.</p>
<p><strong>Best Practice</strong></p>
<p>Going forward, it is best to use <code>CHARACTER SET utf8mb4</code> and <code>COLLATION utf8mb4_unicode_520_ci</code>. (There is a newer version of the Unicode collation in the pipeline.)</p>
<p><code>utf8mb4</code> is a superset of <code>utf8</code> in that it handles 4-byte utf8 codes, which are needed by Emoji and some of Chinese.</p>
<p>Outside of MySQL, "UTF-8" refers to all size encodings, hence effectively the same as MySQL's <code>utf8mb4</code>, not <code>utf8</code>.</p>
<p>I will try to use those spellings and capitalizations to distinguish inside versus outside MySQL in the following.</p>
<p><strong>Overview of what you <em>should</em> do</strong></p>
<ul>
<li>Have your editor, etc. set to UTF-8.</li>
<li>HTML forms should start like <code><form accept-charset="UTF-8"></code>.</li>
<li>Have your bytes encoded as UTF-8.</li>
<li>Establish UTF-8 as the encoding being used in the client.</li>
<li>Have the column/table declared <code>CHARACTER SET utf8mb4</code> (Check with <code>SHOW CREATE TABLE</code>.)</li>
<li><code><meta charset=UTF-8></code> at the beginning of HTML</li>
<li>Stored Routines acquire the current charset/collation. They may need rebuilding.</li>
</ul>
<p><em><a href="https://stackoverflow.com/questions/279170/how-to-support-utf-8-completely-in-a-web-application">UTF-8 all the way through</a></em></p>
<p><a href="http://mysql.rjweb.org/doc.php/charcoll#python" rel="noreferrer">More details for computer languages</a> (and its following sections)</p>
<p><strong>Test the data</strong></p>
<p>Viewing the data with a tool or with <code>SELECT</code> cannot be trusted.
Too many such clients, especially browsers, try to compensate for incorrect encodings, and show you correct text even if the database is mangled.
So, pick a table and column that has some non-English text and do</p>
<pre><code>SELECT col, HEX(col) FROM tbl WHERE ...
</code></pre>
<p>The HEX for correctly stored UTF-8 will be</p>
<ul>
<li>For a blank space (in any language): <code>20</code></li>
<li>For English: <code>4x</code>, <code>5x</code>, <code>6x</code>, or <code>7x</code></li>
<li>For most of Western Europe, accented letters should be <code>Cxyy</code></li>
<li>Cyrillic, Hebrew, and Farsi/Arabic: <code>Dxyy</code></li>
<li>Most of Asia: <code>Exyyzz</code></li>
<li>Emoji and some of Chinese: <code>F0yyzzww</code></li>
<li><a href="http://mysql.rjweb.org/doc.php/charcoll#diagnosing_charset_issues" rel="noreferrer">More details</a></li>
</ul>
<p><strong>Specific causes and fixes of the problems seen</strong></p>
<p><strong>Truncated</strong> text (<code>Se</code> for <code>Señor</code>):</p>
<ul>
<li>The bytes to be stored are not encoded as utf8mb4. Fix this.</li>
<li>Also, check that the connection during reading is UTF-8.</li>
</ul>
<p><strong>Black Diamonds</strong> with question marks (<code>Se�or</code> for <code>Señor</code>);
one of these cases exists:</p>
<p>Case 1 (original bytes were <em>not</em> UTF-8):</p>
<ul>
<li>The bytes to be stored are not encoded as utf8. Fix this.</li>
<li>The connection (or <code>SET NAMES</code>) for the <code>INSERT</code> <em>and</em> the <code>SELECT</code> was not utf8/utf8mb4. Fix this.</li>
<li>Also, check that the column in the database is <code>CHARACTER SET utf8</code> (or utf8mb4).</li>
</ul>
<p>Case 2 (original bytes <em>were</em> UTF-8):</p>
<ul>
<li>The connection (or <code>SET NAMES</code>) for the <code>SELECT</code> was not utf8/utf8mb4. Fix this.</li>
<li>Also, check that the column in the database is <code>CHARACTER SET utf8</code> (or utf8mb4).</li>
</ul>
<p>Black diamonds occur only when the browser is set to <code><meta charset=UTF-8></code>.</p>
<p><strong>Question Marks</strong> (regular ones, not black diamonds) (<code>Se?or</code> for <code>Señor</code>):</p>
<ul>
<li>The bytes to be stored are not encoded as utf8/utf8mb4. Fix this.</li>
<li>The column in the database is not <code>CHARACTER SET utf8</code> (or utf8mb4). Fix this. (Use <code>SHOW CREATE TABLE</code>.)</li>
<li>Also, check that the connection during reading is UTF-8.</li>
</ul>
<p><strong>Mojibake</strong> (<code>Señor</code> for <code>Señor</code>):
(This discussion also applies to <strong>Double Encoding</strong>, which is not necessarily visible.)</p>
<ul>
<li>The bytes to be stored need to be UTF-8-encoded. Fix this.</li>
<li>The connection when <code>INSERTing</code> and <code>SELECTing</code> text needs to specify utf8 or utf8mb4. Fix this.</li>
<li>The column needs to be declared <code>CHARACTER SET utf8</code> (or utf8mb4). Fix this.</li>
<li>HTML should start with <code><meta charset=UTF-8></code>.</li>
</ul>
<p>If the data looks correct, but won't sort correctly, then
either you have picked the wrong collation,
or there is no collation that suits your need,
or you have <strong>Double Encoding</strong>.</p>
<p><strong>Double Encoding</strong> can be confirmed by doing the <code>SELECT .. HEX ..</code> described above.</p>
<pre><code>é should come back C3A9, but instead shows C383C2A9
The Emoji should come back F09F91BD, but comes back C3B0C5B8E28098C2BD
</code></pre>
<p>That is, the hex is about twice as long as it should be.
This is caused by converting from latin1 (or whatever) to utf8, then treating those
bytes as if they were latin1 and repeating the conversion.
The sorting (and comparing) does not work correctly because it is, for example,
sorting as if the string were <code>Señor</code>.</p>
<p><strong>Fixing the Data, where possible</strong></p>
<p>For <strong>Truncation</strong> and <strong>Question Marks</strong>, the data is lost.</p>
<p>For <strong>Mojibake</strong> / <strong>Double Encoding</strong>, ...</p>
<p>For <strong>Black Diamonds</strong>, ...</p>
<p>The <strong>Fixes</strong> are listed here. (5 different fixes for 5 different situations; pick carefully): <a href="http://mysql.rjweb.org/doc.php/charcoll#fixes_for_various_cases" rel="noreferrer">http://mysql.rjweb.org/doc.php/charcoll#fixes_for_various_cases</a></p> |
38,114,761 | ASP.NET Core configuration for .NET Core console application | <p>ASP.NET Core support a new configuration system as seen here:
<a href="https://docs.asp.net/en/latest/fundamentals/configuration.html">https://docs.asp.net/en/latest/fundamentals/configuration.html</a></p>
<p>Is this model also supported in .NET Core console applications?</p>
<p>If not what is alternate to the previous <code>app.config</code> and <code>ConfigurationManager</code> model?</p> | 40,481,272 | 11 | 0 | null | 2016-06-30 05:39:50.757 UTC | 41 | 2021-03-05 16:09:15.573 UTC | 2020-06-08 11:56:07.56 UTC | null | 3,082,718 | null | 386,287 | null | 1 | 169 | c#|.net-core|configuration|console-application | 161,070 | <p>You can use this code snippet. It includes Configuration and DI.</p>
<pre><code>public class Program
{
public static ILoggerFactory LoggerFactory;
public static IConfigurationRoot Configuration;
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (String.IsNullOrWhiteSpace(environment))
throw new ArgumentNullException("Environment not found in ASPNETCORE_ENVIRONMENT");
Console.WriteLine("Environment: {0}", environment);
var services = new ServiceCollection();
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json", optional: true);
if (environment == "Development")
{
builder
.AddJsonFile(
Path.Combine(AppContext.BaseDirectory, string.Format("..{0}..{0}..{0}", Path.DirectorySeparatorChar), $"appsettings.{environment}.json"),
optional: true
);
}
else
{
builder
.AddJsonFile($"appsettings.{environment}.json", optional: false);
}
Configuration = builder.Build();
LoggerFactory = new LoggerFactory()
.AddConsole(Configuration.GetSection("Logging"))
.AddDebug();
services
.AddEntityFrameworkNpgsql()
.AddDbContext<FmDataContext>(o => o.UseNpgsql(connectionString), ServiceLifetime.Transient);
services.AddTransient<IPackageFileService, PackageFileServiceImpl>();
var serviceProvider = services.BuildServiceProvider();
var packageFileService = serviceProvider.GetRequiredService<IPackageFileService>();
............
}
}
</code></pre>
<p>Oh, and don't forget to add in the project.json</p>
<pre><code>{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true,
"copyToOutput": {
"includeFiles": [
"appsettings.json",
"appsettings.Integration.json",
"appsettings.Production.json",
"appsettings.Staging.json"
]
}
},
"publishOptions": {
"copyToOutput": [
"appsettings.json",
"appsettings.Integration.json",
"appsettings.Production.json",
"appsettings.Staging.json"
]
},
...
}
</code></pre> |
41,467,894 | No property found for type... custom Spring Data repository | <p>I'm trying to implement a custom Spring repository. I have the interface:</p>
<pre><code>public interface FilterRepositoryCustom {
List<User> filterBy(String role);
}
</code></pre>
<p>the implementation:</p>
<pre><code>public class FilterRepositoryImpl implements FilterRepositoryCustom {
...
}
</code></pre>
<p>and the "main" repository, extending my custom repository:</p>
<pre><code>public interface UserRepository extends JpaRepository<User, String>, FilterRepositoryCustom {
...
}
</code></pre>
<p>I'm using Spring Boot and, according to the <a href="https://spring.io/guides/gs/accessing-data-jpa/" rel="noreferrer">docs</a>:</p>
<blockquote>
<p>By default, Spring Boot will enable JPA repository support and look in
the package (and its subpackages) where @SpringBootApplication is
located.</p>
</blockquote>
<p>When I run my application, I get this error:</p>
<blockquote>
<p>org.springframework.data.mapping.PropertyReferenceException: No property filterBy found for type User!</p>
</blockquote> | 41,490,008 | 9 | 0 | null | 2017-01-04 15:48:52.39 UTC | 10 | 2022-01-09 21:26:49.127 UTC | null | null | null | null | 3,026,283 | null | 1 | 60 | spring|spring-boot|spring-data | 103,982 | <p>The problem here is that you are creating <strong><code>FilterRepositoryImpl</code></strong> but you are using it in <strong><code>UserRepository</code></strong>. You need to create <strong><code>UserRepositoryImpl</code></strong> to make this work.</p>
<p><a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations" rel="noreferrer">Read this doc for more detail</a></p>
<p>Basically</p>
<pre><code>public interface UserRepositoryCustom {
List<User> filterBy(String role);
}
public class UserRepositoryImpl implements UserRepositoryCustom {
...
}
public interface UserRepository extends JpaRepository<User, String>, UserRepositoryCustom {
...
}
</code></pre>
<p><strong>Spring Data 2.x update</strong><br>
This answer was written for Spring 1.x. As <a href="https://stackoverflow.com/questions/41467894/no-property-found-for-type-custom-spring-data-repository/41490008?noredirect=1#comment82037254_41490008">Matt Forsythe</a> pointed out, the naming expectations changed with Spring Data 2.0. The implementation changed from <code>the-final-repository-interface-name-with-an-additional-Impl-suffix</code> to <code>the-custom-interface-name-with-an-additional-Impl-suffix</code>.</p>
<p>So in this case, the name of the implementation would be: <code>UserRepositoryCustomImpl</code>. </p> |
30,826,769 | How to disable checkbox with jquery? | <p>I searched more time with it but it's not work, I want to checkbox is disabled, user not check and can check it if some condition. Ok, now, I tried disabled them. I use jquery 2.1.3</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U01" />Banana
<input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U02" />Orange
<input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U03" />Apple
<input type="checkbox" class="checkbox1" id="chk" name="check[]" value="U04" />Candy</code></pre>
</div>
</div>
</p>
<pre><code>$(window).load(function () {
$('#chk').prop('disabled', true);
});
</code></pre> | 30,826,783 | 3 | 0 | null | 2015-06-14 07:01:47.093 UTC | 2 | 2016-12-12 11:57:26.787 UTC | 2015-06-26 19:45:45.713 UTC | null | 4,370,109 | null | 4,972,085 | null | 1 | 7 | javascript|jquery|checkbox | 54,562 | <p><code>id</code> should be unique. You cannot have four checkboxes with the same id. </p>
<p>You can try other selectors to select the whole range of checkboxes, like <code>.checkbox1</code> (by class), <code>input[type="checkbox"]</code> (by tag/attribute). Once you've fixed the ids, you could even try <code>#chk1, #chk2, #chk3, #chk4</code>. </p>
<p>The snippet below uses the classname 'chk' instead of the id 'chk'. Also, it uses <code>attr</code> to set the attribute although it did work for me using <code>prop</code> as well.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(window).load(function() {
$('.chk').attr('disabled', true);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="chk" name="check[]" value="U01" />Banana
<input type="checkbox" class="chk" name="check[]" value="U02" />Orange
<input type="checkbox" class="chk" name="check[]" value="U03" />Apple
<input type="checkbox" class="chk" name="check[]" value="U04" />Candy</code></pre>
</div>
</div>
</p> |
47,128,903 | Errors "This action is unauthorized." using Form Request validations in Laravel 5/6/7/8/9 | <p>I make some gate like this:</p>
<pre class="lang-php prettyprint-override"><code>Gate::define('update-post', function ($user, Post $post) {
return $user->hasAccess(['update-post']) or $user->id == $post->user_id;
});
</code></pre>
<p>I checked my database and it has update-post access and the user id is same as in the post. but I got:</p>
<blockquote>
<p>This action is unauthorized.</p>
</blockquote>
<p>errors. so am I do some mistake here? thanks.</p> | 47,129,765 | 8 | 0 | null | 2017-11-06 02:29:52.18 UTC | 4 | 2022-08-22 12:26:45.413 UTC | 2022-02-10 23:23:25.603 UTC | null | 7,117,697 | null | 4,687,904 | null | 1 | 35 | php|laravel|validation|laravel-5|authorization | 70,696 | <p>I had a similar problem some time ago when starting to use <a href="https://laravel.com/docs/validation#form-request-validation" rel="nofollow noreferrer">Form Request</a> classes for data validation. I noticed the following:</p>
<p>If you are using <a href="https://laravel.com/docs/validation#form-request-validation" rel="nofollow noreferrer">Form Requests</a> to validate data, then first of all, <strong>check that you set properly the authorization rule that will allow it to pass</strong>. This is handled by the <code>authorize()</code> method that must return a <code>boolean</code>, <strong>that by default is set to</strong> <code>false</code>:</p>
<pre class="lang-php prettyprint-override"><code>namespace App\Http\Requests\Users;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class UpdateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
/**
* By default it returns false, change it to
* something like this if u are checking authentication
*/
return Auth::check(); // <-------
/**
* You could also use something more granular, like
* a policy rule or an admin validation like this:
* return auth()->user()->isAdmin();
*
* Or just return true if you handle the authorisation
* anywhere else:
* return true;
*/
}
public function rules()
{
// your validations...
}
}
</code></pre> |
30,130,553 | What's the vim way to select multiple instances of current word and change them? | <p>Anyone familiar with Sublime Text's multiple cursor feature will recognize the pattern of doing the following: press a hotkey multiple times to select multiple instances of the word under the cursor and automatically create a new cursor for each of those instances; then edit each instance simultaneously, e.g. by replacing the current word with another word or whatever you want.</p>
<p>The multiple cursors feature is available for vim via <a href="https://github.com/terryma/vim-multiple-cursors" rel="noreferrer">plugin</a>. Before using that plugin, I want (as a new vim user), to check whether there is a more natively vim-like way to achieve the same task.</p>
<p>For instance, I know I could use the <code>:s</code> command to do a search and replace (per instructions <a href="http://vim.wikia.com/wiki/Search_and_replace" rel="noreferrer">here</a>), but that requires me to (1) type in the word I want to replace (or use the <code><C-r><C-a></code> shortcut to do so), as opposed to simply using the current word and (2) define a range. Perhaps this is the native vim way to do it, perhaps (likely!) there's another way I don't know.</p>
<p>So what is the native vim way?</p> | 30,130,714 | 3 | 0 | null | 2015-05-08 18:29:01.95 UTC | 10 | 2020-11-01 15:06:48.473 UTC | null | null | null | null | 848,235 | null | 1 | 22 | vim|sublimetext2 | 18,825 | <p>I use the <code>*</code>, <code>gn</code>, and the <code>.</code> to make changes.</p>
<ul>
<li>Select current word with <code>*</code> (go back with <code>N</code>)</li>
<li>Change word with <code>gn</code> motion. e.g. <code>cgnfoo<esc></code></li>
<li>Repeat via <code>.</code> command</li>
</ul>
<p>Note: If you have many changes then using a substitution command would probably be better.</p>
<p>There is a nice <a href="http://vimcasts.org/" rel="noreferrer">Vimcasts</a> episode about the <code>gn</code> motion: <a href="http://vimcasts.org/episodes/operating-on-search-matches-using-gn/" rel="noreferrer">Operating on search matches using gn</a>.</p>
<p>For more help see:</p>
<pre><code>:h *
:h gn
:h .
</code></pre> |
40,206,232 | Delete worksheet if it exists and create a new one | <p>I want to look through my Excel worksheets and find a sheet with a certain name and delete that sheet if it is found. Afterwards I want to create a sheet after all existing sheets with that name. My code is as follows:</p>
<pre><code>For Each ws In Worksheets
If ws.Name = "asdf" Then
Application.DisplayAlerts = False
Sheets("asdf").Delete
Application.DisplayAlerts = True
End
End If
Next
Sheets.Add(After:=Sheets(Sheets.count)).Name = "asdf"
</code></pre>
<p>However this doesn't do both of these actions in one run of the code. If the sheet already exists it will simply delete the sheet and not make a new one like I want it to. I need to run it again for it to create a new one.</p>
<p>How do I fix my code to delete the old sheet if it exists and create a new one?</p> | 40,206,286 | 3 | 0 | null | 2016-10-23 18:09:04.407 UTC | 2 | 2022-04-26 15:53:21.347 UTC | 2018-09-05 14:59:21.313 UTC | null | 3,357,935 | null | 7,025,145 | null | 1 | 11 | vba|excel | 60,456 | <p>Remove the <code>End</code> statement, your code terminates after finding and deleting the worksheet <code>asdf</code>.</p>
<pre><code>For Each ws In Worksheets
If ws.Name = "asdf" Then
Application.DisplayAlerts = False
Sheets("asdf").Delete
Application.DisplayAlerts = True
End If
Next
Sheets.Add(After:=Sheets(Sheets.count)).Name = "asdf"
</code></pre> |
18,858,337 | Sequelize use camel case in JS but underscores in table names | <p>Is it possible to have column names be underscored (postgres) but have the JavaScript getters be camelCase per language standards?</p> | 18,916,005 | 4 | 0 | null | 2013-09-17 19:29:47.827 UTC | 5 | 2020-06-22 08:47:12.13 UTC | null | null | null | null | 1,612,277 | null | 1 | 37 | sequelize.js | 31,046 | <p>Not directly in your column definition, but you could take a look at getters and setters:</p>
<p><a href="http://sequelizejs.com/documentation#models-getters---setters-defining-as-part-of-the-model-options" rel="nofollow noreferrer">http://sequelizejs.com/documentation#models-getters---setters-defining-as-part-of-the-model-options</a></p>
<p>Although this options requires you to define a getter and setter for each column manually, it cannot be automated. Furthermore, both your getters and the actual column names will then be available on the object.</p>
<p>I think there is an issue for this functionality on github, but I cannot find it right now</p>
<hr>
<p>actual link
<a href="https://sequelize.org/master/manual/models-definition.html#getters--amp--setters" rel="nofollow noreferrer">https://sequelize.org/master/manual/models-definition.html#getters--amp--setters</a></p> |
30,378,249 | UIModalPresentationPopover for iPhone 6 Plus in landscape doesn't display popover | <p>I want to always present a <code>ViewController</code> in a popover on all devices and all orientations. I tried to accomplish this by adopting the <code>UIPopoverPresentationControllerDelegate</code> and setting the <code>sourceView</code> and <code>sourceRect</code>. </p>
<p>This works very well for all devices and orientations, except the iPhone 6 Plus in landscape. In that case the view controller slides up from the bottom of the screen in a form sheet. How can I prevent that so that it will always appear in a popover?</p>
<pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let popoverPresentationController = segue.destinationViewController.popoverPresentationController
popoverPresentationController?.delegate = self
popoverPresentationController?.sourceView = self.titleLabel!.superview
popoverPresentationController?.sourceRect = self.titleLabel!.frame }
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None }
</code></pre>
<p>All device are under iOS 8.2 or higher</p> | 30,481,565 | 4 | 0 | null | 2015-05-21 15:34:21.573 UTC | 4 | 2019-11-05 16:23:35.753 UTC | 2015-05-26 23:30:37.787 UTC | null | 3,036,593 | null | 3,036,593 | null | 1 | 35 | ios|iphone|ios8|iphone-6-plus|uimodalpresentationstyle | 7,168 | <p>Implement the new <code>adaptivePresentationStyleForPresentationController:traitCollection:</code> method of <code>UIAdaptivePresentationControllerDelegate</code>:</p>
<pre><code>- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller traitCollection:(UITraitCollection *)traitCollection {
// This method is called in iOS 8.3 or later regardless of trait collection, in which case use the original presentation style (UIModalPresentationNone signals no adaptation)
return UIModalPresentationNone;
}
</code></pre>
<p><code>UIModalPresentationNone</code> tells the presentation controller to use the original presentation style which in your case will display a popover.</p> |
35,827,863 | Remove Outliers in Pandas DataFrame using Percentiles | <p>I have a DataFrame df with 40 columns and many records. </p>
<p>df:</p>
<pre><code>User_id | Col1 | Col2 | Col3 | Col4 | Col5 | Col6 | Col7 |...| Col39
</code></pre>
<p>For each column except the user_id column I want to check for outliers and remove the whole record, if an outlier appears.</p>
<p>For outlier detection on each row I decided to simply use 5th and 95th percentile (I know it's not the best statistical way):</p>
<p>Code what I have so far:</p>
<pre><code>P = np.percentile(df.Col1, [5, 95])
new_df = df[(df.Col1 > P[0]) & (df.Col1 < P[1])]
</code></pre>
<p><strong>Question</strong>: How can I apply this approach to all columns (except <code>User_id</code>) without doing this by hand? My goal is to get a dataframe without records that had outliers.</p>
<p>Thank you!</p> | 35,828,995 | 5 | 0 | null | 2016-03-06 14:09:01.207 UTC | 27 | 2021-11-07 16:21:24.573 UTC | 2019-04-25 08:00:24.263 UTC | null | 4,512,948 | null | 1,472,537 | null | 1 | 27 | python|pandas|outliers | 91,553 | <p>The initial dataset.</p>
<pre><code>print(df.head())
Col0 Col1 Col2 Col3 Col4 User_id
0 49 31 93 53 39 44
1 69 13 84 58 24 47
2 41 71 2 43 58 64
3 35 56 69 55 36 67
4 64 24 12 18 99 67
</code></pre>
<p>First removing the <code>User_id</code> column</p>
<pre><code>filt_df = df.loc[:, df.columns != 'User_id']
</code></pre>
<p>Then, computing percentiles.</p>
<pre><code>low = .05
high = .95
quant_df = filt_df.quantile([low, high])
print(quant_df)
Col0 Col1 Col2 Col3 Col4
0.05 2.00 3.00 6.9 3.95 4.00
0.95 95.05 89.05 93.0 94.00 97.05
</code></pre>
<p>Next filtering values based on computed percentiles. To do that I use an <code>apply</code> by columns and that's it !</p>
<pre><code>filt_df = filt_df.apply(lambda x: x[(x>quant_df.loc[low,x.name]) &
(x < quant_df.loc[high,x.name])], axis=0)
</code></pre>
<p>Bringing the <code>User_id</code> back.</p>
<pre><code>filt_df = pd.concat([df.loc[:,'User_id'], filt_df], axis=1)
</code></pre>
<p>Last, rows with <code>NaN</code> values can be dropped simply like this.</p>
<pre><code>filt_df.dropna(inplace=True)
print(filt_df.head())
User_id Col0 Col1 Col2 Col3 Col4
1 47 69 13 84 58 24
3 67 35 56 69 55 36
5 9 95 79 44 45 69
6 83 69 41 66 87 6
9 87 50 54 39 53 40
</code></pre>
<h2>Checking result</h2>
<pre><code>print(filt_df.head())
User_id Col0 Col1 Col2 Col3 Col4
0 44 49 31 NaN 53 39
1 47 69 13 84 58 24
2 64 41 71 NaN 43 58
3 67 35 56 69 55 36
4 67 64 24 12 18 NaN
print(filt_df.describe())
User_id Col0 Col1 Col2 Col3 Col4
count 100.000000 89.000000 88.000000 88.000000 89.000000 89.000000
mean 48.230000 49.573034 45.659091 52.727273 47.460674 57.157303
std 28.372292 25.672274 23.537149 26.509477 25.823728 26.231876
min 0.000000 3.000000 5.000000 7.000000 4.000000 5.000000
25% 23.000000 29.000000 29.000000 29.500000 24.000000 36.000000
50% 47.000000 50.000000 40.500000 52.500000 49.000000 59.000000
75% 74.250000 69.000000 67.000000 75.000000 70.000000 79.000000
max 99.000000 95.000000 89.000000 92.000000 91.000000 97.000000
</code></pre>
<h2>How to generate the test dataset</h2>
<pre><code>np.random.seed(0)
nb_sample = 100
num_sample = (0,100)
d = dict()
d['User_id'] = np.random.randint(num_sample[0], num_sample[1], nb_sample)
for i in range(5):
d['Col' + str(i)] = np.random.randint(num_sample[0], num_sample[1], nb_sample)
df = DataFrame.from_dict(d)
</code></pre> |
27,438,169 | How to insert multiple select statements into a temp table | <p>I am having three tables with different data and i need to insert into one TEMP table and return that table in StoredProcedure.</p>
<p>I tried as:</p>
<pre><code>-- To get last 10 Days Letters count
SELECT col1,col2,1 AS Type, LettersCount
INTO #temp FROM tblData
-- To get last 4 weeks Letters count
SELECT col1,col2,2 AS Type, LettersCount
INTO #temp FROM tblData
-- To get month wise Letters count
SELECT col1,col2,3 AS Type, LettersCount
INTO #temp FROM tblData
</code></pre>
<p>Showing Error as</p>
<pre><code>Msg 2714, Level 16, State 1, Line 16
There is already an object named '#temp ' in the database.
Msg 102, Level 15, State 1, Line 24
Incorrect syntax near 'T'.
Msg 2714, Level 16, State 1, Line 32
There is already an object named '#temp ' in the database.
</code></pre> | 27,438,286 | 5 | 0 | null | 2014-12-12 06:36:37.023 UTC | 1 | 2014-12-12 07:35:10.027 UTC | 2014-12-12 06:45:57.807 UTC | null | 3,732,514 | null | 3,732,514 | null | 1 | 12 | sql|sql-server|database|sql-server-2008|select | 61,915 | <p>You can Check it Already Exists or NOT</p>
<pre><code>IF OBJECT_ID ('tempdb..#TempLetters') is not null
drop table #TempLetters
SELECT col1,col2,1 AS Type, LettersCount
INTO #TempLetters FROM tblData
-- To get last 4 weeks Letters count
INSERT INTO #TempLetters
SELECT col1,col2,2 AS Type, LettersCount
FROM tblData
-- To get month wise Letters count
INSERT INTO #TempLetters
SELECT col1,col2,3 AS Type, LettersCount
FROM tblData
</code></pre> |
44,614,301 | Implement a read receipt feature in Firebase group messaging app | <p>I'd like to implement a 'Seen' feature in my Firebase group messaging app. Can you kindly advise the best and most efficient approach to take (working code will be appreciated)? For example, the app would show "<strong>Seen by 6</strong>" or "<strong>Seen by 15</strong>" on a group message.</p>
<p>Here's my project: <a href="https://github.com/firebase/friendlychat/tree/master/android" rel="nofollow noreferrer">https://github.com/firebase/friendlychat/tree/master/android</a></p>
<p>Here's the MainActivity: <a href="https://github.com/firebase/friendlychat/blob/master/android/app/src/main/java/com/google/firebase/codelab/friendlychat/MainActivity.java" rel="nofollow noreferrer">https://github.com/firebase/friendlychat/blob/master/android/app/src/main/java/com/google/firebase/codelab/friendlychat/MainActivity.java</a></p> | 44,758,152 | 2 | 0 | null | 2017-06-18 11:02:50.697 UTC | 11 | 2017-12-06 18:55:28.507 UTC | 2017-06-26 19:05:49.693 UTC | user7889746 | null | user7889746 | null | null | 1 | 11 | java|android|firebase|firebase-realtime-database|firebase-cloud-messaging | 6,563 | <p>To achieve this, you need to add another node in your Firebase database named <code>seenBy</code> which must be nested under each <code>messageId</code> in <code>meassage</code> section. Your database should look like this:</p>
<pre><code>Firebase-root
|
---- messages
|
---- messageId1
|
---- meessage: "Hello!"
|
---- timestamp: 1498472455940
|
---- seenBy
|
---- userUid1: John
|
---- userUid2: Mary
|
---- userUid3: George
</code></pre>
<p>Every time a new user opens a meesage, just add the <code>uid</code> and the <code>name</code> as explained above.</p>
<p>To implement <code>Seen by 6</code> option, it's very easy. You just need to create a <code>listener</code> and use <code>getChildrenCount()</code> method like this:</p>
<pre><code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference seenByRef = rootRef.child("messages").child(messageId).child("seenBy");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long seenBy = dataSnapshot.getChildrenCount();
Lod.d("TAG", "Seen by: " + seenBy);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
seenByRef.addListenerForSingleValueEvent(eventListener);
</code></pre>
<p>To know whether a message has been opened or not, you need to add another field to your user section in which you need to add a <code>boolean</code> with the default value of <code>false</code>. This new section should look like this:</p>
<pre><code>Firebase-root
|
---- users
|
---- userId1
|
---- meessages
|
---- messageId1: false
|
---- messageId2: false
|
---- messageId3: false
</code></pre>
<p>When a users opens that message, just set the value of that particular message from <code>false</code> to <code>true</code>, which means that the particular message has been opened. This is the code:</p>
<pre><code>DatabaseReference openedRef = rootRef.child("users").child(userId).child("meessages").child("messageId1");
openedRef.setValue(true);
</code></pre>
<p>When you create a message, use <code>push()</code> method on the reference like this:</p>
<pre><code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messageRef = rootRef.child("meessages").push();
String messageKey = messageRef.getKey();
</code></pre>
<p>Having this key, you can use it in your <code>DatabaseReference</code>. In the same way you can use for the userId.</p>
<p>Hope it helps.</p> |
44,369,117 | Receiving Location even when app is not running in Swift | <p>Still very new to Swift. I have come from an Android background where there is BroadcastReceiver that can deliver location info to a service even though the app isn't running.</p>
<p>So I was looking for something similar in iOS/Swift and it appears that before this wasn't possible but it may be now. I am developing for iOS 10 but would be great if it was backwards compatible.</p>
<p>I found </p>
<pre><code>startMonitoringSignificantLocationChanges
</code></pre>
<p>which I can execute to start delivering location updates, although this raises a few questions. Once I call this and my app is NOT running, are the updates still being sent ? And how would the app wake up to respond ?</p>
<p>Also restarting the phone and when it return, does this mean I still need call startMonitoringSignificantLocationChanges again meaning that I would have to wait for the user to execute my app. Or does it remember the setting after reboot ?</p>
<p>Still a little confused how to get around this, here's a brief explanation of what I am trying to do.</p>
<p>I would like to update the location of the phone even though the app is not running, this would be sent to a rest service every so often.</p>
<p>This way on the backend services I could determine if somebody is within X meters of somebody also and send them a push notification.</p> | 44,371,982 | 1 | 0 | null | 2017-06-05 12:38:31.043 UTC | 11 | 2020-03-24 20:23:57.057 UTC | 2018-05-14 10:10:14.833 UTC | null | 472,495 | null | 457,172 | null | 1 | 8 | ios|swift|swift3|geolocation | 13,346 | <p>It may or may not be a good solution but if I were you I would have used both <code>startMonitoringSignificantLocationChanges</code> and <code>regionMonitoring</code>.</p>
<p><a href="https://drive.google.com/file/d/19Ih1mU17XQn_SoyujtmW-uZTBt5mLCXj/view" rel="noreferrer">Here</a> is the sample I made which worked well with iOS 13.</p>
<p>Lets take <code>regionMonitoring</code> first. We have certainly no problems when the app is in foreground state and we can use the <strong>CLLocationManager's</strong> <code>didUpdate</code> delegate to get the location and send it to the server.</p>
<p>Keep latest current location in AppDelegate's property, lets say:</p>
<pre><code>var lastLocation:CLLocation?
//And a location manager
var locationManager = CLLocationManager()
</code></pre>
<p>We have two <code>UIApplicationDelegates</code> </p>
<pre><code>func applicationDidEnterBackground(_ application: UIApplication) {
//Create a region
}
func applicationWillTerminate(_ application: UIApplication) {
//Create a region
}
</code></pre>
<p>So whenever the user kills the app or makes the app go to background, we can certainly create a region around the latest current location fetched. Here is an example to create a region.</p>
<pre><code>func createRegion(location:CLLocation?) {
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
let coordinate = CLLocationCoordinate2DMake((location?.coordinate.latitude)!, (location?.coordinate.longitude)!)
let regionRadius = 50.0
let region = CLCircularRegion(center: CLLocationCoordinate2D(
latitude: coordinate.latitude,
longitude: coordinate.longitude),
radius: regionRadius,
identifier: "aabb")
region.notifyOnExit = true
region.notifyOnEntry = true
//Send your fetched location to server
//Stop your location manager for updating location and start regionMonitoring
self.locationManager?.stopUpdatingLocation()
self.locationManager?.startMonitoring(for: region)
}
else {
print("System can't track regions")
}
}
</code></pre>
<p>Make use of RegionDelegates</p>
<pre><code>func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
print("Entered Region")
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
print("Exited Region")
locationManager?.stopMonitoring(for: region)
//Start location manager and fetch current location
locationManager?.startUpdatingLocation()
}
</code></pre>
<p>Grab the location from <code>didUpdate</code> method</p>
<pre><code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if UIApplication.shared.applicationState == .active {
} else {
//App is in BG/ Killed or suspended state
//send location to server
// create a New Region with current fetched location
let location = locations.last
lastLocation = location
//Make region and again the same cycle continues.
self.createRegion(location: lastLocation)
}
}
</code></pre>
<p>Here I have made a 50m region radius circle. I have tested this and it is called generally after crossing 100m from your center point.</p>
<p>Now the second approach can me using <code>significantLocationChanges</code></p>
<p>On making the app go background or terminated, we can just stop location manager for further updating locations and can call the <code>startMonitoringSignificantLocationChanges</code> </p>
<pre><code>self.locationManager?.stopUpdatingLocation()
self.locationManager?.startMonitoringSignificantLocationChanges()
</code></pre>
<p>When the app is killed, the location is grabbed from <code>didFinishLaunching</code> method's <code>launchOptions?[UIApplicationLaunchOptionsKey.location]</code></p>
<pre><code>if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {
//You have a location when app is in killed/ not running state
}
</code></pre>
<p>Make sure to keep <strong>BackgroundModes</strong> On for <strong>Location Updates</strong>
<a href="https://i.stack.imgur.com/wlCEK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wlCEK.png" alt="enter image description here"></a></p>
<p>Also make sure to ask for <code>locationManager?.requestAlwaysAuthorization()</code> by using the key </p>
<pre><code><key>NSLocationAlwaysUsageDescription</key>
<string>Allow location</string>
</code></pre>
<p>in your <strong>Info.plist</strong></p>
<p>There can be a third solution by taking <strong>2 LocationManagers</strong> simultaneously.</p>
<ol>
<li>For region<br></li>
<li>Significant Location Changes</li>
</ol>
<p>As using <code>significantLocationChanges</code></p>
<blockquote>
<p>Apps can expect a notification as soon as the device moves 500 meters
or more from its previous notification. It should not expect
notifications more frequently than once every five minutes. If the
device is able to retrieve data from the network, the location manager
is much more likely to deliver notifications in a timely manner.</p>
</blockquote>
<p>as per the give <a href="https://developer.apple.com/reference/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati" rel="noreferrer">Apple Doc</a></p>
<p>So it totally depends on your requirements as the location fetching depends on many factors like the number of apps opened, battery power, signal strength etc when the app is not running.</p>
<p>Also keep in mind to always setup a region with good accuracy.</p>
<p>I know that this will not solve your problem completely but you will get an idea to move forward as per your requirements.</p> |
45,085,567 | How to append dynamic DOM elements from a directive in Angular 2? | <p>I have an Angular 1.x directive that appends an element. In short:</p>
<pre class="lang-ts prettyprint-override"><code>app.directive('mydirective', function() {
template: '<ng-transclude></ng-transclude>',
link: function(el) {
var child = angular.element("<div/>");
el.append(child);
}
</code></pre>
<p>I can migrate this directive to Angular 2 like this:</p>
<pre class="lang-ts prettyprint-override"><code>@Directive({
selector: '[mydirective']
})
export class MyDirective implements OnInit {
constructor(private elementRef: ElementRef) { }
ngOnit() {
var child = angular.element("<div/>");
this.elementRef.nativeElement.append(child);
}
}
</code></pre>
<p>What's troubling me is this remark in the <code>nativeElement</code> official documentation:</p>
<blockquote>
<p>Use this API as the last resource when direct access to DOM is needed.</p>
</blockquote>
<p>My question is - how could I properly migrate this directive to Angular 2? My only requirement is to build an element dynamically and append it to the element with the directive.</p> | 45,085,659 | 1 | 0 | null | 2017-07-13 15:47:34.487 UTC | 8 | 2021-07-29 10:33:58.067 UTC | 2021-02-04 16:02:11.847 UTC | null | 5,764,320 | null | 4,811,392 | null | 1 | 30 | angular|angular2-directives | 49,860 | <p>Use <a href="https://angular.io/api/core/Renderer2" rel="noreferrer"><code>Renderer</code></a> provided by Angular to manipulate the DOM:</p>
<pre class="lang-ts prettyprint-override"><code>import { DOCUMENT } from '@angular/common';
export class MyDirective implements OnInit {
constructor(
private elementRef: ElementRef,
private renderer: Renderer2,
@Inject(DOCUMENT) private document: Document) { }
ngOnInit() {
const child = this.document.createElement('div');
this.renderer.appendChild(this.elementRef.nativeElement, child);
}
}
</code></pre>
<p>This doesn't depend on the native DOM API like <code>appendChild()</code>, so in a way it's a platform-independent approach.</p> |
50,496,783 | Extract the second element of a tuple in a pipeline | <p>I want to be able to extract the Nth item of a tuple in a pipeline, without using <code>with</code> or otherwise breaking up the pipeline. <code>Enum.at</code> would work perfectly except for the fact that a tuple is not an enum.</p>
<p>Here's a motivating example:</p>
<pre><code>colors = %{red: 1, green: 2, blue: 3}
data = [:red, :red, :blue]
data
|> Enum.map(&Map.fetch(colors, &1))
|> Enum.unzip
</code></pre>
<p>This returns <code>{[:ok, :ok, :ok], [1, 1, 3]}</code> and let's say I just want to extract <code>[1, 1, 3]</code></p>
<p>(For this specific case I could use <code>fetch!</code> but for my actual code that doesn't exist.)</p>
<p>I could add on</p>
<pre><code>|> Tuple.to_list
|> Enum.at(1)
</code></pre>
<p>Is there a better way of doing this that doesn't require creating a temporary list out of each tuple?</p> | 50,496,881 | 2 | 0 | null | 2018-05-23 20:16:28.72 UTC | 2 | 2018-05-24 16:18:15.08 UTC | 2018-05-23 20:21:54.55 UTC | null | 3,029,173 | null | 3,029,173 | null | 1 | 30 | tuples|elixir|pipeline | 18,076 | <p>Use <a href="https://hexdocs.pm/elixir/Kernel.html#elem/2" rel="noreferrer"><code>Kernel.elem/2</code></a>:</p>
<pre><code>iex(1)> {[:ok, :ok, :ok], [1, 1, 3]} |> elem(1)
[1, 1, 3]
</code></pre> |
808,669 | Convert a CERT/PEM certificate to a PFX certificate | <p>I've seen a couple questions about how to convert a PFX to a cert file, but I need to go the other way.</p>
<p>I have two files:</p>
<blockquote>
<p>bob_cert.cert</p>
<p>bob_key.pem</p>
</blockquote>
<p>I'd like to convert them to a single .pfx file. Is there a tool that does this?</p> | 808,742 | 4 | 2 | null | 2009-04-30 19:30:16.097 UTC | 100 | 2018-03-29 13:44:19.423 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 37,881 | null | 1 | 258 | certificate | 585,024 | <pre><code>openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx
</code></pre> |
217,111 | ASP.NET MVC and WCF | <p>I'm working my way into MVC at the moment, but on my "To learn at some point" list, I also have WCF.</p>
<p>I just wonder if WCF is something that should/could be used in an MVC Application or not? The Background is that I want a Desktop Application (.NET 3.5, WPF) interact with my MVC Web Site, and I wonder what the best way to transfer data between the two is. Should I just use special Views/have the controllers return JSON or XML (using the ContentResult)?</p>
<p>And maybe even more important, for the other way round, could I just call special controllers? Not sure how Authorization would work in such a context. I can either use Windows Authentication or (if the Site is running forms authentication) have the user store his/her credentials in the application, but I would then essentially create a HTTP Client in my Application. So while MVC => Application seems really easy, Application => MVC does seem to be somewhat tricky and a possible use for WCF?</p>
<p>I'm not trying to brute-force WCF in this, but I just wonder if there is indeed a good use case for WCF in an MVC application.</p> | 218,386 | 4 | 0 | null | 2008-10-19 22:53:37.74 UTC | 27 | 2011-12-27 07:01:07.55 UTC | 2010-04-01 03:13:02.387 UTC | Michael Stum | 63,550 | Michael Stum | 91 | null | 1 | 27 | .net|asp.net-mvc|wcf | 24,882 | <p>WCF services might make sense in this situation, but don't create services that align with your UI, create services that align with the business processes. ie. you won't have a service that returns the view data for each page, you will have a service that exposes logical operations. Then, your site can call the same services that the windows client calls, but you don't have to couple the design of the windows client to the design of the web site. </p>
<p>Instead of this:</p>
<p>Windows Client -> Services -> Web Site </p>
<p>It should be:</p>
<p>Windows Client -> Services</p>
<p>Web Site -> Services</p> |
427,262 | Can I just make up attributes on my HTML tags? | <p>Am I allowed to add whatever attributes I want to HTML tags such that I can retrieve their value later on using javascript? For example:</p>
<pre><code><a href="something.html" hastooltip="yes" tipcolour="yellow">...</a>
</code></pre>
<p>If that's not going to work, how would you store arbitrary pieces of information like this?</p>
<p><strong>Edit:</strong> Since it appears that making up HTML attributes isn't technically valid, I've rephrased the second part of this question into its own question here: <a href="https://stackoverflow.com/questions/432174/">How to store arbitrary data for some HTML tags</a></p> | 431,101 | 4 | 1 | null | 2009-01-09 06:49:16.133 UTC | 14 | 2017-06-30 15:52:25.927 UTC | 2017-05-23 12:10:19.847 UTC | nickf | -1 | nickf | 9,021 | null | 1 | 44 | javascript|html | 15,264 | <p>In HTML5, yes. You just have to prefix them with <code>data-</code>. See <a href="https://www.w3schools.com/tags/att_global_data.asp" rel="nofollow noreferrer">the spec</a>.</p>
<p>Of course, this implies you should be using the HTML5 doctype (<code><!doctype html></code>), even though browsers don't care.</p> |
45,600,891 | Reactjs: how to put the html template in a separate file? | <p>I'm new to React. I'm much more familiar with Angular2+. In Angular, every component has a separate html file. However, in React, I see that render function itself includes the html template. For example, </p>
<pre><code>import React, { Component } from 'react';
class HelloWorld extends Component {
render() {
return (
<h2> Hello World </h2>
);
}
}
export default HelloWorld;
</code></pre>
<p>Well I want to take</p>
<pre><code><h2> Hello World </h2>
</code></pre>
<p>outside the js file and put it in a separate html and import the html file to render function, for example</p>
<pre><code> render() {
return (
import content of helloworld.html
);
}
</code></pre>
<p>Do you know how to do it?</p> | 45,601,141 | 4 | 2 | null | 2017-08-09 21:27:27.88 UTC | 13 | 2021-07-19 09:58:27.42 UTC | null | null | null | null | 5,402,618 | null | 1 | 49 | reactjs | 51,327 | <hr>
<p>In React you would typically make a child component and import it into the parent component.</p>
<hr>
<p>Since your child component here would just be static markup <em>i.e</em> <code><h2>Hello World</h2></code>, you don't need to worry about component state. </p>
<p>Therefore, you could do the following: </p>
<ol>
<li><p>make a <strong>functional</strong> (aka <em>stateless</em> or <em>dumb</em>) component for your text. You could name it <code>HelloWorldText</code> as an example. </p></li>
<li><p>import this <strong>functional</strong> component into your parent component <code>HelloWorld</code>.</p></li>
</ol>
<hr>
<p>Your functional component would look something like this:</p>
<p><strong>HelloWorldText.js</strong></p>
<pre class="lang-js prettyprint-override"><code>const HelloWorldText = () => ( <h2> Hello World </h2> );
export default HelloWorldText;
</code></pre>
<hr>
<p>Then you would import this functional component <code>HelloWorldText</code> into your parent component <code>HelloWorld</code> like so:</p>
<p><strong>HelloWorld.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import React, { Component } from 'react';
import HelloWorldText from './path/to/HelloWorldText';
class HelloWorld extends Component {
render() {
return (
<HelloWorldText />
);
}
}
export default HelloWorld;
</code></pre>
<hr>
<p>Here's a <strong><a href="https://codepen.io/dankreiger5/pen/yobQge" rel="noreferrer">CodePen Demo</a></strong> with this code. </p>
<p>Unfortunately on <em>CodePen</em> you can't export and import components, but hopefully it still gives you an idea on how to use a child component inside a parent component.</p>
<hr>
<hr>
<p><strong>Note:</strong> In React you want your components to be as general as possible. You would probably end up making a <code>Text</code> component instead of a <code>HelloWorldText</code> component.</p>
<p>Then you would pass text dynamically into the <code>Text</code> component using <code>props</code>.</p>
<p>Here is a <strong><a href="https://codepen.io/dankreiger5/pen/ayWQRq?editors=1010" rel="noreferrer">CodePen Demo</a></strong> of this in action.</p> |
20,812,835 | set decimal places of sum in sql | <p>I have a database I use for a debating competition I am trying to sort the standings out to see which schools will play off in the finals at the end of the semester.</p>
<p>I have this working as shown below however I am not able to round the ptc field, it currently returns up to 4 decimal places eg 0.6667 if they have won 2 out of 3 debates.</p>
<pre><code> SELECT t.id,
t.name AS name,
SUM(t.id = d.winnerid) AS w,
SUM(t.id != d.winnerid) AS l,
SUM(t.id = d.winnerid)/(SUM(t.id = d.winnerid)+SUM(t.id != d.winnerid)) AS ptc
FROM debates AS d
JOIN teams AS t ON t.id IN (d.hostid, d.visitid)
WHERE d.visitid != -1
AND d.debatedate < CURDATE()
GROUP BY t.id
ORDER BY ptc DESC
</code></pre>
<p>I believe I have to use decimal(2,2) here however I am not able to get the syntax right I have tried a few diferent things like</p>
<pre><code>SUM(t.id = d.winnerid)/(SUM(t.id = d.winnerid)+SUM(t.id != d.winnerid)) AS ptc decimal (2,2)
</code></pre>
<p>Am happy to provide more information about the tables if required but I don't think it is required?</p> | 20,812,856 | 2 | 1 | null | 2013-12-28 09:13:28.727 UTC | 2 | 2021-05-12 10:02:30.913 UTC | null | null | null | null | 737,114 | null | 1 | 13 | mysql|sql|sum|decimal | 64,738 | <p>try this.</p>
<pre><code>SELECT ROUND(SUM(cash), 2)
FROM <tablename>
</code></pre>
<p>If you are getting no results, then there must be a null value, try this instead.</p>
<pre><code>SELECT ROUND(SUM(cash), 2)
FROM<tablename> a
WHERE cash IS NOT NULL
</code></pre>
<p>Here is a simple demo of it :</p>
<p><strong>Update :</strong> </p>
<pre><code> SELECT round( ROUND(SUM(p.prod_price = l.prod_unit_price), 2)
/ROUND(SUM(p.prod_id = l.prod_id), 2),2)
FROM b2b.product_master p
join b2b.move_cart_item_master l;
</code></pre> |
29,465,666 | How do you draw an ellipse/oval in turtle graphics (python)? | <p>How do you draw an ellipse/oval in turtle graphics (python)? I want to be able to draw an ellipse and part of an ellipse using the circle() function or similar. I can stamp one using #turtlesize(stretch_wid=None, stretch_len=10, outline=None). But I don't want it to be color filled.</p> | 29,465,742 | 5 | 2 | null | 2015-04-06 05:06:01.22 UTC | 2 | 2021-09-30 04:47:36.277 UTC | 2015-04-06 05:31:14.257 UTC | null | 1,307,905 | null | 4,672,205 | null | 1 | 2 | python|turtle-graphics | 49,821 | <p>You can use shapesize() function of turtle to make an ellipse.</p>
<pre><code>shape("circle")
shapesize(5,4,1)
fillcolor("white")
</code></pre> |
54,896,998 | how to process fetch response from an 'opaque' type? | <p>I'm trying to correctly interpret the response from a fetch call to an URL, that I think is a json string. I've tried a many variations based on similar posts here, but nothing is getting me useful data to work with. Here is one attempt:</p>
<pre><code>fetch('http://serverURL/api/ready/', {method: "POST", mode: "no-cors"})
.then(function(response) {
response.json().then(function(data) {
console.log('data:' + data);
});
})
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
</code></pre>
<p>This returns a syntax error in the console:</p>
<blockquote>
<p>SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data</p>
</blockquote>
<p>So maybe its not JSON...if I put in a breakpoint on the console.log line, and hover over response (line above), I see the response object (?) with various fields:</p>
<p><a href="https://i.stack.imgur.com/W9nbB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W9nbB.png" alt="Response object from debugger hover"></a></p>
<p>Not sure how to interpret that...status:0 suggests it did not get a valid response. However, if I check the Network tab in the developer tools, and click on the fetch line, status there is 200, and the Response window/JSON section shows the message info that you also see if you just put the URL into the browser URL bar directly. As does the "Response payload" section, which shows the JSON string:</p>
<blockquote>
<p>{"msg": "API is ready.", "success": true}</p>
</blockquote>
<p>So...it looks like json, no? But fetch is unable to ingest this as json?</p>
<p>Here's another variation, but using response.text() instead of response.json()</p>
<pre><code>fetch('http://serverURL/api/ready/', {method: "POST", mode: "no-cors"})
.then((response) => {
console.log(response);
response.text().then((data) => {
console.log("data:" + data);
});
});
</code></pre>
<p>This prints the response object in the console (same as above: ok: false, status:0, type:opaque etc). The second console.log file prints nothing after data:. If I use response.json, again I get the syntax error about end of data as above.</p>
<p>Any ideas? I realize the server may not be providing what fetch needs or wants, but, it does provide some info (at least when using the URL directly in the browser), which is what I need to then deal with, as json or text or whatever.</p> | 54,906,434 | 1 | 5 | null | 2019-02-27 02:12:03.59 UTC | 4 | 2022-03-15 16:23:05.663 UTC | 2022-03-15 16:23:05.663 UTC | null | 3,689,450 | null | 5,753,077 | null | 1 | 32 | javascript|json|fetch-api | 42,412 | <p>Essentially, you <strong>cannot</strong> access response body from an opaque request.</p>
<blockquote>
<p>Adding mode: 'no-cors' won’t magically make things work. Browsers by
default block frontend code from accessing resources cross-origin. If
a site sends Access-Control-Allow-Origin in its responses, then
browsers will relax that blocking and allow your code to access the
response.</p>
<p>But if a site doesn’t send the Access-Control-Allow-Origin header in
its responses, then there’s no way your frontend JavaScript code can
directly access responses from that site. In particular, specifying
mode: 'no-cors' won’t fix that (in fact it’ll just make things worse).</p>
</blockquote>
<p>From <a href="https://stackoverflow.com/a/43268098/1666071">https://stackoverflow.com/a/43268098/1666071</a></p>
<p>And also from <code>fetch</code> documentation:</p>
<blockquote>
<p>no-cors — Prevents the method from being anything other than HEAD, GET
or POST, and the headers from being anything other than simple
headers. If any ServiceWorkers intercept these requests, they may not
add or override any headers except for those that are simple headers.
<strong>In addition, JavaScript may not access any properties of the resulting
Response.</strong> This ensures that ServiceWorkers do not affect the semantics
of the Web and prevents security and privacy issues arising from
leaking data across domains.</p>
</blockquote>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Request/mode" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Request/mode</a></p> |
39,024,354 | ASP.NET Core API only returning first result of list | <p>I have created a teams web api controller and trying to call the GET method to get the json result of all the teams in the database. But when I make the call I am only getting the first team back in the json but when I set a breakpoint on the return statement it has all 254 teams along with all of the games.</p>
<p>These are the two models that I am dealing with:</p>
<pre><code>public class Team
{
public string Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public string Mascot { get; set; }
public string Conference { get; set; }
public int NationalRank { get; set; }
public List<Game> Games { get; set; }
}
public class Game
{
public string Id { get; set; }
public string Opponent { get; set; }
public string OpponentLogo { get; set; }
public string GameDate { get; set; }
public string GameTime { get; set; }
public string TvNetwork { get; set; }
public string TeamId { get; set; }
public Team Team { get; set; }
}
</code></pre>
<p>When I do this:</p>
<pre><code>[HttpGet]
public async Task<List<Team>> Get()
{
var teams = await _context.Teams.ToListAsync();
return teams;
}
</code></pre>
<p>I get all 254 teams but Game property is null because EF Core does not support lazy loading. So what I really want to do is add the .Include() like this:</p>
<pre><code>[HttpGet]
public async Task<List<Team>> Get()
{
var teams = await _context.Teams.Include(t => t.Games).ToListAsync();
return teams;
}
</code></pre>
<p>This returns the first team with the first game but nothing else. Here is the json:</p>
<pre><code>[
{
"id": "007b4f09-d4da-4040-be3a-8e45fc0a572b",
"name": "New Mexico",
"icon": "lobos.jpg",
"mascot": "New Mexico Lobos",
"conference": "MW - Mountain",
"nationalRank": null,
"games": [
{
"id": "1198e6b1-e8ab-48ab-a63f-e86421126361",
"opponent": "vs Air Force*",
"opponentLogo": "falcons.jpg",
"gameDate": "Sat, Oct 15",
"gameTime": "TBD ",
"tvNetwork": null,
"teamId": "007b4f09-d4da-4040-be3a-8e45fc0a572b"
}
]
}
]
</code></pre>
<p>When I set a break point on the return statement it shows that there are 254 teams and every team has their games populated correctly...but the json result does not reflect. Here is an image:</p>
<p><a href="https://i.stack.imgur.com/MxPcV.png"><img src="https://i.stack.imgur.com/MxPcV.png" alt="enter image description here"></a></p>
<p>I have tried doing this both synchronously and asynchronously but getting the same result. Do you know why I am only getting one result back in the json but at the breakpoint it has all of the results? </p> | 39,024,972 | 2 | 6 | null | 2016-08-18 17:37:52.617 UTC | 8 | 2020-03-25 19:49:44.733 UTC | null | null | null | null | 2,382,635 | null | 1 | 35 | c#|json|entity-framework|asp.net-web-api|asp.net-core | 14,926 | <p>Add this to <code>Startup.cs</code> inside the <code>public void ConfigureServices(IServiceCollection services)</code> method:</p>
<pre><code>services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
</code></pre>
<p>The issue was discussed <a href="https://github.com/aspnet/Mvc/issues/4160" rel="nofollow noreferrer">https://github.com/aspnet/Mvc/issues/4160</a> and <a href="https://github.com/aspnet/EntityFramework/issues/4646" rel="nofollow noreferrer">https://github.com/aspnet/EntityFramework/issues/4646</a> also see <a href="https://benohead.com/c-circular-reference-detected-serializing-object/" rel="nofollow noreferrer">circular reference</a></p> |
26,846,738 | zsh history is too short | <p>When I run <code>history</code> in Bash, I get a load of results (1000+). However, when I run <code>history</code> the zsh shell I only get 15 results. This makes grepping history in zsh mostly useless.
My <code>.zshrc</code> file contains the following lines:</p>
<pre><code>HISTFILE=~/.zhistory
HISTSIZE=SAVEHIST=10000
setopt sharehistory
setopt extendedhistory
</code></pre>
<p>How can I fix zsh to make my shell history more useful?</p>
<hr>
<p>UPDATE</p>
<p>If in zsh I call <code>history 1</code> I get all of my history, just as I do in Bash with <code>history</code>. I could alias the command to get the same result, but I wonder why does <code>history</code> behave differently in zsh and in Bash.</p> | 26,848,769 | 3 | 2 | null | 2014-11-10 15:07:39.337 UTC | 23 | 2021-01-02 02:24:51.263 UTC | 2014-11-10 16:01:00.94 UTC | null | 1,815,288 | null | 1,815,288 | null | 1 | 103 | zsh|history | 37,133 | <p>NVaughan (the OP) has already stated the answer in an update to the question: <strong><code>history</code> behaves differently in <code>bash</code> than it does in <code>zsh</code></strong>:</p>
<p>In short:</p>
<ul>
<li><strong>zsh</strong>:
<ul>
<li><code>history</code> lists only the <strong>15 most recent</strong> history entries</li>
<li><code>history 1</code> lists <strong>all</strong> - see below.</li>
</ul></li>
<li><strong>bash</strong>:
<ul>
<li><code>history</code> lists <strong>all</strong> history entries.</li>
</ul></li>
</ul>
<p>
Sadly, passing a <strong>numerical operand</strong> to <code>history</code> behaves differently, too:</p>
<ul>
<li><strong>zsh</strong>:
<ul>
<li><code>history <n></code> shows all entries <strong><em>starting with</em> <code><n></code></strong> - therefore, <code>history 1</code> shows <em>all</em> entries.</li>
<li>(<code>history -<n></code> - note the <code>-</code> - shows the <strong><code><n></code> <em>most recent</em></strong> entries, so the default behavior is effectively <code>history -15</code>)</li>
</ul></li>
<li><strong>bash</strong>:
<ul>
<li><code>history <n></code> shows the <strong><code><n></code> <em>most recent</em></strong> entries.</li>
<li>(bash's <code>history</code> doesn't support listing <em>from</em> an entry number; you can use <code>fc -l <n></code>, but a <em>specific entry <code><n></code> must exist</em>, otherwise the command fails - see below.)</li>
</ul></li>
</ul>
<hr>
<p>Optional background info:</p>
<ul>
<li>In zsh, <code>history</code> is effectively (not actually) an alias for <code>fc -l</code>: see <code>man zshbuiltins</code>
<ul>
<li>For the many history-related features, see <code>man zshall</code></li>
</ul></li>
<li>In bash, <code>history</code> is its own command whose syntax differs from <code>fc -l</code>
<ul>
<li>See: <code>man bash</code></li>
</ul></li>
<li>Both bash and zsh support <code>fc -l <fromNum> [<toNum>]</code> to list a given <em>range</em> of history entries:
<ul>
<li>bash: specific entry <code><fromNum></code> must exist.</li>
<li>zsh: command succeeds as long as least 1 entry falls in the (explicit or implied) range.</li>
<li>Thus, <code>fc -l 1</code> works in zsh to return all history entries, whereas in bash it generally won't, given that entry #1 typically no longer exists (but, as stated, you can use <code>history</code> without arguments to list all entries in bash).</li>
</ul></li>
</ul> |
57,344,571 | How does shared_ptr<void> know which destructor to use? | <p>I wrote the following code to see how a <code>shared_ptr<void></code> would behave when it is the last reference to a <code>shared_ptr<Thing></code> and is itself destroyed. </p>
<pre><code>#include <iostream>
#include <string>
#include <memory>
using namespace std;
struct Thing{
~Thing(){
cout<<"Destroyed\n";
}
int data;
};
int main(){
{
shared_ptr<void> voidPtr;
{
shared_ptr<Thing> thingPtr = make_shared<Thing>();
voidPtr = thingPtr;
}
cout<<"thingPtr is dead\n";
}
cout<<"voidPtr is dead\n";
return 0;
}
</code></pre>
<p>Which outputs:</p>
<pre><code>thingPtr is dead
Destroyed
voidPtr is dead
</code></pre>
<p>It behaves in a way I <em>like</em>, but it's totally unexpected and I'd like to understand what's going on here. The initial shared pointer no longer exists, it's just a <code>shared_ptr<void></code> in the end. So I would expect this shared pointer to act like it's holding a <code>void*</code> and have no idea about <code>Thing::~Thing()</code>, yet it calls it. This is by design, right? How is the void shared pointer accomplishing this?</p> | 57,344,701 | 2 | 2 | null | 2019-08-04 07:08:00.09 UTC | 5 | 2019-08-04 23:55:41.657 UTC | 2019-08-04 07:15:13.523 UTC | null | 620,863 | null | 620,863 | null | 1 | 35 | c++|shared-ptr|void | 1,982 | <p>The shared state co-owned by shared pointers also contains a deleter, a function like object that is fed the managed object at the end of its lifetime in order to release it. We can even specify our own deleter by using the <a href="https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr" rel="noreferrer">appropriate constructor</a>. How the deleter is stored, as well as any type erasure it undergoes is an implementation detail. But suffice it to say that the shared state contains a function that knows exactly how to free the owned resource.</p>
<p>Now, when we create an object of a concrete type with <code>make_shared<Thing>()</code> and don't provide a deleter, the shared state is set to hold some default deleter that can free a <code>Thing</code>. The implementation can generate one from the template argument alone. And since its stored as part of the shared state, it doesn't depend on the type <code>T</code> of any <code>shared_pointer<T></code> that may be sharing ownership of the state. It will always know how to free the <code>Thing</code>.</p>
<p>So even when we make <code>voidPtr</code> the only remaining pointer, the deleter remains unchanged, and still knows how to free a <code>Thing</code>. Which is what it does when the <code>voidPtr</code> goes out of scope.</p> |
7,281,760 | In Python, how do you find the index of the first value greater than a threshold in a sorted list? | <p>In Python, how do you find the index of the first value greater than a threshold in a sorted list?</p>
<p>I can think of several ways of doing this (linear search, hand-written dichotomy,..), but I'm looking for a clean an reasonably efficient way of doing it. Since it's probably a pretty common problem, I'm sure experienced SOers can help!</p>
<p>Thanks!</p> | 7,281,797 | 3 | 0 | null | 2011-09-02 09:49:38.88 UTC | 9 | 2020-08-24 17:40:46.407 UTC | 2011-09-02 09:58:50.043 UTC | null | 164,171 | null | 164,171 | null | 1 | 33 | python|algorithm|search|bisection | 19,583 | <p>Have a look at <a href="http://docs.python.org/library/bisect.html">bisect</a>.</p>
<pre><code>import bisect
l = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
bisect.bisect(l, 55) # returns 7
</code></pre>
<p>Compare it with linear search:</p>
<pre><code>timeit bisect.bisect(l, 55)
# 375ns
timeit next((i for i,n in enumerate(l) if n > 55), len(l))
# 2.24us
timeit next((l.index(n) for n in l if n > 55), len(l))
# 1.93us
</code></pre> |
7,262,137 | What is DataContext for? | <p>As a continuation of the question <a href="https://stackoverflow.com/questions/7235403/linking-datacontext-with-another-property-in-wpf">Linking DataContext with another property in WPF</a>.</p>
<p>At the very end of the research I was very surprised to find out that when one writes something like that:</p>
<pre><code><Label Content="{Binding Path=Name}" />
</code></pre>
<p>The <code>DataContext</code> against which the <code>Content</code> property is binded is of the <code>Label</code> control itself! The fact that it still works is due to the default inheritance of the DataContext value from the nearest parent.</p>
<p>But if you have this label wrapped in a custom control, and you don't want to bind your data to the <code>DataContext</code> property of that control, you would more likely love to have:</p>
<pre><code><Controls:SearchSettings Settings="{Binding Path=Settings}" />
</code></pre>
<p>And here you are. Now you need to set <code>Settings</code> as the <code>DataContext</code> for the <code>SearchSettings</code> control, for <code>Label</code> inside to bind against, but you can't, because that will trigger re-binding of <code>Settings</code> property.</p>
<p>I can't see the point in mixing binding properties using different sources: <code>DataContext</code>, by <code>ElementName</code>, etc.
So why would I ever use <code>DataContext</code>?</p> | 7,262,322 | 4 | 0 | null | 2011-08-31 19:10:22.947 UTC | 20 | 2015-07-11 12:53:27.017 UTC | 2017-05-23 11:47:19.767 UTC | null | -1 | null | 354,507 | null | 1 | 39 | wpf|data-binding | 66,832 | <p>When you write</p>
<pre><code><Label name="myLabel" Content="{Binding Path=Name}" />
</code></pre>
<p>you are binding to <code>myLabel.DataContext.Name</code>, and not <code>myLabel.Name</code>.</p>
<p>The XAML in WPF is just a pretty user interface to display and interact with the actual data, otherwise known as the <code>DataContext</code>. The purpose of other binding sources (<code>RelativeSource</code>, <code>ElementName</code>, etc) is to point to another property that doesn't exist in the current control's <code>DataContext</code>
<hr>
So suppose you have a Window. Without setting the DataContext, the window still displays but there is no data behind it.</p>
<p>Now suppose to set <code>myWindow.DataContext = new ClassA();</code>. Now the data that the window is displaying is <code>ClassA</code>. If <code>ClassA</code> has a property called <code>Name</code>, I could write a label and bind it to <code>Name</code> (such as your example), and whatever value is stored in <code>ClassA.Name</code> would get displayed.</p>
<p>Now, suppose <code>ClassA</code> has a property of <code>ClassB</code> and both classes have a property called <code>Name</code>. Here is a block of XAML which illustrates the purpose of the DataContext, and an example of how a control would refer to a property not in it's own DataContext</p>
<pre><code><Window x:Name="myWindow"> <!-- DataContext is set to ClassA -->
<StackPanel> <!-- DataContext is set to ClassA -->
<!-- DataContext is set to ClassA, so will display ClassA.Name -->
<Label Content="{Binding Name}" />
<!-- DataContext is still ClassA, however we are setting it to ClassA.ClassB -->
<StackPanel DataContext="{Binding ClassB}">
<!-- DataContext is set to ClassB, so will display ClassB.Name -->
<Label Content="{Binding Name}" />
<!-- DataContext is still ClassB, but we are binding to the Window's DataContext.Name which is ClassA.Name -->
<Label Content="{Binding ElementName=myWindow, Path=DataContext.Name}" />
</StackPanel>
</StackPanel>
</Window>
</code></pre>
<p>As you can see, the DataContext is based on whatever data is behind the UI object.</p>
<p><strong>Update:</strong> I see this question so often from new WPF users that I expanded this answer into a post on my blog: <a href="http://rachel53461.wordpress.com/2012/07/14/what-is-this-datacontext-you-speak-of/" rel="noreferrer">What is this “DataContext” you speak of?</a></p> |
8,252,440 | Adding items to a JList from ArrayList using DefaultListModel | <p>I'm trying to add items that are in an <code>ArrayList</code> to a <code>JList</code> which is working when I use the following code:</p>
<pre><code>private void UpdateJList(){
DefaultListModel<String> model = new DefaultListModel<String>();
for(Person p : personList){
model.addElement(p.ToString());
}
clientJList.setModel(model);
clientJList.setSelectedIndex(0);
}
</code></pre>
<p>However, If I declare the <code>DefaultListModel</code> outside of the method, the adding increments each item, IE instead of adding one of each item, it adds multiple items. I was just wondering why this happens?</p> | 8,253,910 | 1 | 4 | null | 2011-11-24 05:06:04.31 UTC | 3 | 2015-03-28 05:39:37.083 UTC | 2013-05-29 16:58:42.277 UTC | null | 2,296,199 | null | 985,264 | null | 1 | 7 | java|swing|arraylist|jlist|defaultlistmodel | 45,227 | <p>If you define <code>DefaultListModel</code> outside your update method then it becomes <em>Instance variable</em> so it will be having same value for one instance. Thus if you call this method over and over from same instance it will simply add more values to the existing list. Thus it shows multiple items.</p>
<p><strong>NOTE</strong> : declaring <code>DefaultListModel</code> outside function does not cause any problem, making its object outside function is the problem. You can do the following without any problem :</p>
<pre><code>DefaultListModel<String> model;
private void UpdateJList(){
model = new DefaultListModel<String>();
for(Person p : personList){
model.addElement(p.ToString());
}
clientJList.setModel(model);
clientJList.setSelectedIndex(0);
}
</code></pre>
<p>or you can try clearing the previous values from your model and then adding new values.</p> |
2,066,905 | How do I get all the variables defined in a Django template? | <p>I'm new to Django and I wonder if there is a way to dump all the variables available to a template for debugging purposes. In Python I might use something like <code>locals()</code>, is there something equivalent for the default template engine?</p>
<p>Note: suppose I don't have access to the view for the purposes of this question.</p> | 4,051,941 | 4 | 0 | null | 2010-01-14 19:25:35.91 UTC | 15 | 2018-04-20 03:56:09.027 UTC | 2010-04-11 20:23:36.53 UTC | null | 63,550 | null | 113,440 | null | 1 | 52 | django|django-templates | 27,929 | <p>Both Ned's and blaine's answers are good, but if you really want to achieve exactly what you ask for there's a template tag for it:</p>
<p><code>{% debug %}</code></p>
<p><a href="http://docs.djangoproject.com/en/stable/ref/templates/builtins/#debug" rel="noreferrer">Builtins:debug</a></p>
<p>More information in the <a href="https://docs.djangoproject.com/en/stable/ref/templates/api/#django-template-context-processors-debug" rel="noreferrer">context_processor.debug</a> including:</p>
<blockquote>
<p>If this processor is enabled, every RequestContext will contain <strong>debug</strong>
and and <strong>sql_queries</strong> variables – but only if your DEBUG setting
is set to True and the request’s IP address (<code>request.META['REMOTE_ADDR']</code>)
is in the <strong>INTERNAL_IPS</strong> setting</p>
</blockquote>
<p>Similar to Peter G suggestion, I often use a <code><div id="django-debug"><pre>{% debug|escape %}</pre></div></code> block at the end of the page that has <code>display:none</code> but that I can inspect to debug.</p> |
1,806,445 | cancelling queued performSelector:afterDelay calls | <p>does anybody know if it is possible to cancel already queued selector events from the event stack or timer stack (or whatever mechanism it is that is utilized by the API) when you call <code>performSelector:withObject:afterDelay</code>?</p>
<p>I was using this event stack to alter the attributes of an image within a TabBar tab, and would sometimes queue up to 10 seconds worth of changes in one quickly executed for loop... maybe 5 milliseconds or so.</p>
<p>the problem arises if the user switches tabs... like say I have the image alterations queued for an image that is displayed as soon as Tab #4 is enabled, and then the user quickly switches to Tab #3 and then right back to Tab #4... this would then re-queue another 10 seconds worth of alterations while the old queue was still playing, probably around 2 or 3 seconds in to the queue if switched quick enough... but even arriving at 5 seconds in to the stream was a problem.</p>
<p>so I needed some way to cancel the old stack of changes before putting a new stack on...</p>
<p>I'm writing this query in the past tense because I already came up with an alternative solution to this problem by adding a hawk-eyed event filter on the playback function. however I am still curious if event cancellation is possible, because I have a feeling such knowledge will come in handy in the future. thank you for any assistance rendered :)</p> | 1,806,523 | 4 | 1 | null | 2009-11-27 01:51:38.823 UTC | 22 | 2018-05-28 13:14:31.583 UTC | 2014-05-18 05:43:29.25 UTC | null | 775,283 | null | 219,470 | null | 1 | 118 | objective-c|selector | 34,728 | <pre><code>[NSObject cancelPreviousPerformRequestsWithTarget:]
</code></pre>
<p>or </p>
<pre><code>[NSObject cancelPreviousPerformRequestsWithTarget:selector:object:]
</code></pre>
<p>The <code>target</code> is the original object on which <code>performSelector:afterDelay:</code> was called.</p>
<p>For example:</p>
<pre><code>// schedule the selector
[self performSelector:@selector(mySel:) withObject:nil afterDelay:5.0];
// cancel the above call (and any others on self)
[NSObject cancelPreviousPerformRequestsWithTarget:self];
</code></pre>
<p>See <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelector:withObject:afterDelay:" rel="noreferrer">apple docs</a>, it's right at the end of the <code>performSelector:withObject:afterDelay:</code> description.</p> |
10,445,760 | How to change the default icon on the SearchView, to be use in the action bar on Android? | <p>I'm having a bit of trouble customizing the search icon in the SearchView. On my point of view, the icon can be changed in the Item attributes, right? Just check the code bellow..</p>
<p>Can someone tell me what I'm doing wrong? </p>
<p>This is the menu I'm using, with my custom search icon <strong>icn_lupa</strong>. But when I run the app, I always get the default search icon...</p>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_search"
android:title="@string/menu_search"
android:icon="@drawable/icn_lupa"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView" />
</menu>
</code></pre>
<p>Thanks in advance.</p> | 10,445,948 | 19 | 2 | null | 2012-05-04 08:58:09.097 UTC | 24 | 2022-01-07 06:55:24.353 UTC | null | null | null | null | 766,150 | null | 1 | 59 | android|android-actionbar | 83,802 | <p>It looks like the actionViewClass overides the icon and it doesn't look like you can change it from <a href="https://developer.android.com/reference/android/widget/SearchView.html" rel="nofollow noreferrer">this class</a>.</p>
<p>You got two solutions:</p>
<ul>
<li>Live with it and I think it's the best option in terms of user experience and platform conformity.</li>
<li><a href="https://stackoverflow.com/questions/5446126/custom-action-view-cant-be-clicked">Define your own actionViewClass</a></li>
</ul> |
7,372,972 | How do I parse a HTML page with Node.js | <p>I need to parse (server side) big amounts of HTML pages.<br>
We all agree that regexp is not the way to go here.<br>
It seems to me that javascript is the native way of parsing a HTML page, but that assumption relies on the server side code having all the DOM ability javascript has inside a browser.</p>
<p>Does Node.js have that ability built in?<br>
Is there a better approach to this problem, parsing HTML on the server side?</p> | 7,373,003 | 6 | 0 | null | 2011-09-10 16:18:08.07 UTC | 40 | 2020-11-17 18:54:38.4 UTC | 2015-05-26 14:14:31.903 UTC | null | 1,480,391 | null | 67,153 | null | 1 | 106 | node.js|html-parsing|server-side | 147,317 | <p>You can use the <a href="http://npmjs.org/" rel="noreferrer">npm</a> modules <a href="https://www.npmjs.org/package/jsdom" rel="noreferrer">jsdom</a> and <a href="https://www.npmjs.org/package/htmlparser" rel="noreferrer">htmlparser</a> to create and parse a DOM in Node.JS.</p>
<p>Other options include:</p>
<ul>
<li><a href="http://pypi.python.org/pypi/BeautifulSoup/3.2.0" rel="noreferrer">BeautifulSoup</a> for python</li>
<li>you can convert you <a href="https://github.com/jfisteus/html2xhtml" rel="noreferrer">html to xhtml</a> and use XSLT</li>
<li><a href="http://html-agility-pack.net/?z=codeplex" rel="noreferrer">HTMLAgilityPack</a> for .NET</li>
<li><a href="https://github.com/jamietre/CsQuery" rel="noreferrer">CsQuery</a> for .NET (my new favorite)</li>
<li>The spidermonkey and rhino JS engines have native E4X support. This may be useful, only if you convert your html to xhtml.</li>
</ul>
<p>Out of all these options, I prefer using the Node.js option, because it uses the standard W3C DOM accessor methods and I can reuse code on both the client and server. I wish BeautifulSoup's methods were more similar to the W3C dom, and I think converting your HTML to XHTML to write XSLT is just plain sadistic.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.