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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,574,029 | What does JPA EntityManager.getSingleResult() return for a COUNT query? | <p>What does <code>EntityManager.getSingleResult()</code> return for a COUNT query?</p>
<p>So.. what is the precise runtime type of foo?</p>
<pre><code>Object foo = em.createQuery("SELECT COUNT(t) FROM com.company.Thing t WHERE prop = :param")
.setParameter("param", value).getSingleResult();
</code></pre> | 3,574,683 | 9 | 0 | null | 2010-08-26 10:04:27.223 UTC | 9 | 2022-07-27 05:18:25.88 UTC | 2010-08-26 16:23:48.457 UTC | null | 70,604 | null | 13,935 | null | 1 | 35 | java|orm|jpa | 55,606 | <p>COUNT(t) specifically returns java.lang.Long. When its appears on its own in this context it is returned as-is. </p>
<p>(In other contexts the Long generated by COUNT may be wrapped, but not today.)</p> |
3,870,540 | How to update column with null value | <p>I am using mysql and need to update a column with a null value. I have tried this many different ways and the best I have gotten is an empty string.</p>
<p>Is there a special syntax to do this?</p> | 3,870,553 | 13 | 3 | null | 2010-10-06 08:08:29.823 UTC | 16 | 2020-11-24 14:59:27.94 UTC | 2011-02-07 11:00:53.593 UTC | null | 241,776 | null | 467,716 | null | 1 | 180 | mysql|sql-update | 582,458 | <p>No special syntax:</p>
<pre><code>CREATE TABLE your_table (some_id int, your_column varchar(100));
INSERT INTO your_table VALUES (1, 'Hello');
UPDATE your_table
SET your_column = NULL
WHERE some_id = 1;
SELECT * FROM your_table WHERE your_column IS NULL;
+---------+-------------+
| some_id | your_column |
+---------+-------------+
| 1 | NULL |
+---------+-------------+
1 row in set (0.00 sec)
</code></pre> |
3,825,668 | Checking for NULL pointer in C/C++ | <p>In a recent code review, a contributor is trying to enforce that all <code>NULL</code> checks on pointers be performed in the following manner:</p>
<pre><code>int * some_ptr;
// ...
if (some_ptr == NULL)
{
// Handle null-pointer error
}
else
{
// Proceed
}
</code></pre>
<p>instead of</p>
<pre><code>int * some_ptr;
// ...
if (some_ptr)
{
// Proceed
}
else
{
// Handle null-pointer error
}
</code></pre>
<p>I agree that his way is a little more clear in the sense that it's explicitly saying "Make sure this pointer is not NULL", but I would counter that by saying that anyone who's working on this code would understand that using a pointer variable in an <code>if</code> statement is implicitly checking for <code>NULL</code>. Also I feel the second method has a smaller chance of introducing a bug of the ilk:</p>
<pre><code>if (some_ptr = NULL)
</code></pre>
<p>which is just an absolute pain to find and debug.</p>
<p>Which way do you prefer and why?</p> | 3,825,704 | 14 | 14 | null | 2010-09-29 20:40:26.503 UTC | 49 | 2021-01-13 02:52:45.74 UTC | 2020-05-04 16:50:00.697 UTC | null | 12,139,179 | null | 34,731 | null | 1 | 192 | c++|c|if-statement|null|coding-style | 436,136 | <p>In my experience, tests of the form <code>if (ptr)</code> or <code>if (!ptr)</code> are preferred. They do not depend on the definition of the symbol <code>NULL</code>. They do not expose the opportunity for the accidental assignment. And they are clear and succinct. </p>
<p><strong>Edit:</strong> As SoapBox points out in a comment, they are compatible with C++ classes such as <code>auto_ptr</code> that are objects that act as pointers and which provide a conversion to <code>bool</code> to enable exactly this idiom. For these objects, an explicit comparison to <code>NULL</code> would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the <code>bool</code> conversion implies.</p>
<p>I have a preference for code that says what it means without unneeded text. <code>if (ptr != NULL)</code> has the same meaning as <code>if (ptr)</code> but at the cost of redundant specificity. The next logical thing is to write <code>if ((ptr != NULL) == TRUE)</code> and that way lies madness. The C language is clear that a boolean tested by <code>if</code>, <code>while</code> or the like has a specific meaning of non-zero value is true and zero is false. Redundancy does not make it clearer.</p> |
3,498,382 | Why use binary search if there's ternary search? | <p>I recently heard about ternary search in which we divide an array into 3 parts and compare. Here there will be two comparisons but it reduces the array to n/3. Why don't people use this much?</p> | 3,498,400 | 15 | 5 | null | 2010-08-17 00:09:36.7 UTC | 16 | 2015-10-29 01:22:34.557 UTC | 2011-11-15 21:52:07.47 UTC | null | 111,575 | null | 2,605,095 | null | 1 | 42 | algorithm|data-structures|binary-tree|ternary-tree | 20,789 | <p>Actually, people do use k-ary trees for arbitrary k.</p>
<p>This is, however, a tradeoff.</p>
<p>To find an element in a k-ary tree, you need around k*ln(N)/ln(k) operations (remember the change-of-base formula). The larger your k is, the more overall operations you need.</p>
<p>The logical extension of what you are saying is "why don't people use an N-ary tree for N data elements?". Which, of course, would be an array.</p> |
8,179,485 | Updating nested immutable data structures | <p>I want to update a nested, immutable data structure (I attached a small example of a hypothetical game.) And I wonder whether this can be done a little more elegantly.</p>
<p>Every time something inside the dungeon changes we need a new dungeon. So, I gave it a general update member. The best way to use this, that I could come up with for the general case, is to specify the processing functions for each nesting and than pass the combined function to the update member.</p>
<p>Then, for really common cases (like applying a map to all the monsters on a specific level), I provide extra members (<code>Dungeon.MapMonstersOnLevel</code>). </p>
<p>The whole thing works, I would just like to know, if anyone can think of better ways of doing it. </p>
<p>Thanks!</p>
<pre><code>// types
type Monster(awake : bool) =
member this.Awake = awake
type Room(locked : bool, monsters : Monster list) =
member this.Locked = locked
member this.Monsters = monsters
type Level(illumination : int, rooms : Room list) =
member this.Illumination = illumination
member this.Rooms = rooms
type Dungeon(levels : Level list) =
member this.Levels = levels
member this.Update levelFunc =
new Dungeon(this.Levels |> levelFunc)
member this.MapMonstersOnLevel (f : Monster -> Monster) nLevel =
let monsterFunc = List.map f
let roomFunc = List.map (fun (room : Room) -> new Room(room.Locked, room.Monsters |> monsterFunc))
let levelFunc = List.mapi (fun i (level : Level) -> if i = nLevel then new Level(level.Illumination, level.Rooms |> roomFunc) else level)
new Dungeon(this.Levels |> levelFunc)
member this.Print() =
this.Levels
|> List.iteri (fun i e ->
printfn "Level %d: Illumination %d" i e.Illumination
e.Rooms |> List.iteri (fun i e ->
let state = if e.Locked then "locked" else "unlocked"
printfn " Room %d is %s" i state
e.Monsters |> List.iteri (fun i e ->
let state = if e.Awake then "awake" else "asleep"
printfn " Monster %d is %s" i state)))
// generate test dungeon
let m1 = new Monster(true)
let m2 = new Monster(false)
let m3 = new Monster(true)
let m4 = new Monster(false)
let m5 = new Monster(true)
let m6 = new Monster(false)
let m7 = new Monster(true)
let m8 = new Monster(false)
let r1 = new Room(true, [ m1; m2 ])
let r2 = new Room(false, [ m3; m4 ])
let r3 = new Room(true, [ m5; m6 ])
let r4 = new Room(false, [ m7; m8 ])
let l1 = new Level(100, [ r1; r2 ])
let l2 = new Level(50, [ r3; r4 ])
let dungeon = new Dungeon([ l1; l2 ])
dungeon.Print()
// toggle wake status of all monsters
let dungeon1 = dungeon.MapMonstersOnLevel (fun m -> new Monster(not m.Awake)) 0
dungeon1.Print()
// remove monsters that are asleep which are in locked rooms on levels where illumination < 100 and unlock those rooms
let monsterFunc2 = List.filter (fun (monster : Monster) -> monster.Awake)
let roomFunc2 = List.map(fun (room : Room) -> if room.Locked then new Room(false, room.Monsters |> monsterFunc2) else room)
let levelFunc2 = List.map(fun (level : Level) -> if level.Illumination < 100 then new Level(level.Illumination, level.Rooms |> roomFunc2) else level)
let dungeon2 = dungeon.Update levelFunc2
dungeon2.Print()
</code></pre> | 8,182,877 | 5 | 2 | null | 2011-11-18 08:13:12.263 UTC | 8 | 2019-07-15 08:48:01.16 UTC | 2019-07-15 08:48:01.16 UTC | null | 1,011,722 | null | 650,307 | null | 1 | 21 | f#|functional-programming | 4,071 | <p>I asked a similar question, but about haskell: <a href="https://stackoverflow.com/questions/7365425/is-there-a-haskell-idiom-for-updating-a-nested-data-structure">Is there a Haskell idiom for updating a nested data structure?</a></p>
<p>The excellent answers mentioned a concept known as <strong>functional lenses</strong>. </p>
<hr>
<p><s>Unfortunately, I don't know what the package is, or if it even exists, for F#.</s></p>
<p><strong>Update:</strong> two knowledgeable F#-ists (F#-ers? F#as?) left useful links about this in comments, so I'll post them here:</p>
<ul>
<li><p>@TomasPetricek suggested <code>FSharpX</code> and <a href="http://bugsquash.blogspot.com/2011/11/lenses-in-f.html" rel="nofollow noreferrer">this</a> website describing it</p></li>
<li><p>@RyanRiley gave the <a href="http://nuget.org/List/Packages/FSharpx.Core" rel="nofollow noreferrer">link</a> for the package</p></li>
</ul>
<p>It's awesome that these two guys took the time to read my answer, comment and improve it, as they're both developers of <code>FSharpX</code>!</p>
<hr>
<p>More extraneous information: I was motivated to figure out how to do this by Clojure's <code>assoc-in</code> and <code>update-in</code> functions, which proved to me that it <em>is</em> possible in functional languages! Of course, Clojure's dynamic typing makes it simpler than in Haskell/F#. Haskell's solution involves templating, I believe.</p> |
8,286,037 | The remote host closed the connection Error, how fix? | <p>i am using elmah -> <a href="http://code.google.com/p/elmah/" rel="noreferrer">Elmah.axd</a> in my project for finding errors.<br>
there is an error like this : </p>
<pre><code>System.Web.HttpException: The remote host closed the connection. The error code is 0x800703E3.
Generated: Sun, 27 Nov 2011 13:06:13 GMT
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Web.HttpException (0x800703E3): The remote host closed the connection. The error code is 0x800703E3.
at System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect)
at System.Web.Hosting.IIS7WorkerRequest.ExplicitFlush()
at System.Web.HttpResponse.Flush(Boolean finalFlush)
at System.Web.HttpWriter.TransmitFile(String filename, Int64 offset, Int64 size, Boolean isImpersonating, Boolean supportsLongTransmitFile)
at System.Web.HttpResponse.TransmitFile(String filename, Int64 offset, Int64 length)
at SalarSoft.Utility.SP1.ResumeDownload.ProcessDownload(String fileName, String headerFileName)
at NiceFileExplorer.en.Download.DownloadFile_SalarSoft(String fileName)
at NiceFileExplorer.en.Download.GoForDownloadFile(String filepath)
at NiceFileExplorer.en.Download.MainCodes()
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
</code></pre>
<p>during working with web site, we do n't see this error.<br>
but elmah send this error to me many many times.<br>
what this error mean and how can i fix it? </p>
<p><strong>EDIT 1</strong><br>
{my web site is for downlaod mobile files and some times it's really busy}<br>
{i am using windows server 2008 r2-> remote access} </p>
<p><strong>EDIT 2 after comment</strong><br>
some of windows information and warnings (there is no error) logs for today are like below : </p>
<p>warning </p>
<blockquote>
<p>A process serving application pool 'ASP.NET 4.0 (Integrated)' exceeded
time limits during shut down. The process id was '6764'. </p>
</blockquote>
<p>warning </p>
<blockquote>
<p>A worker process '3232' serving application pool 'ASP.NET 4.0
(Integrated)' failed to stop a listener channel for protocol 'http' in
the allotted time. The data field contains the error number.</p>
</blockquote>
<p>warning </p>
<blockquote>
<p>A process serving application pool 'ASP.NET 4.0 (Integrated)' exceeded
time limits during shut down. The process id was '3928'.</p>
</blockquote> | 8,287,092 | 5 | 5 | null | 2011-11-27 13:52:04.827 UTC | 1 | 2018-08-11 07:25:18.223 UTC | 2011-11-27 17:11:22.073 UTC | null | 172,322 | null | 268,588 | null | 1 | 24 | c#|asp.net|elmah|windows-server-2008-r2 | 76,112 | <p>I see this a lot in the logs of a website I built.</p>
<p>AFAIK that exception means that the client broke the connection (went to another page / closed the browser) before the page had finished loading. If the client is downloading a file this error is even more likely as they have more time to decide to quit / move on.</p>
<p>The error is not visible to the users* - so I have just removed it from the Elmah logs.</p>
<p>*The site allows only authenticated users. I can see from Elmah who experienced the error and when. I've asked the users and not one person has <em>ever</em> reported experiencing this bug in the client.</p> |
7,784,148 | Understanding repr( ) function in Python | <p><code>repr()</code>: evaluatable string representation of an object (can "eval()"
it, meaning it is a string representation that evaluates to a Python
object)</p>
<p>In other words:</p>
<pre><code>>>> x = 'foo'
>>> repr(x)
"'foo'"
</code></pre>
<p>Questions:</p>
<ol>
<li>Why do I get the double quotes when I do <code>repr(x)</code>? (I don't get them
when I do <code>str(x)</code>)</li>
<li>Why do I get <code>'foo'</code> when I do <code>eval("'foo'")</code> and not x which is the
object?</li>
</ol> | 7,784,214 | 5 | 0 | null | 2011-10-16 12:07:55.503 UTC | 67 | 2021-10-26 09:09:38.61 UTC | 2016-04-06 13:01:20.873 UTC | null | 918,959 | null | 799,882 | null | 1 | 159 | python|repr | 199,271 | <pre><code>>>> x = 'foo'
>>> x
'foo'
</code></pre>
<p>So the name <code>x</code> is attached to <code>'foo'</code> string. When you call for example <code>repr(x)</code> the interpreter puts <code>'foo'</code> instead of <code>x</code> and then calls <code>repr('foo')</code>.</p>
<pre><code>>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"
</code></pre>
<p><code>repr</code> actually calls a magic method <code>__repr__</code> of <code>x</code>, which gives the <strong>string</strong> containing the representation of the value <code>'foo'</code> assigned to <code>x</code>. So it returns <code>'foo'</code> inside the string <code>""</code> resulting in <code>"'foo'"</code>. The idea of <code>repr</code> is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to <code>repr</code>.</p>
<pre><code>>>> eval("'foo'")
'foo'
</code></pre>
<p>When we call <code>eval("'foo'")</code>, it's the same as we type <code>'foo'</code> in the interpreter. It's as we directly type the contents of the outer string <code>""</code> in the interpreter.</p>
<pre><code>>>> eval('foo')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eval('foo')
File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
</code></pre>
<p>If we call <code>eval('foo')</code>, it's the same as we type <code>foo</code> in the interpreter. But there is no <code>foo</code> variable available and an exception is raised.</p>
<pre><code>>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>>
</code></pre>
<p><code>str</code> is just the string representation of the object (remember, <code>x</code> variable refers to <code>'foo'</code>), so this function returns string.</p>
<pre><code>>>> str(5)
'5'
</code></pre>
<p>String representation of integer <code>5</code> is <code>'5'</code>.</p>
<pre><code>>>> str('foo')
'foo'
</code></pre>
<p>And string representation of string <code>'foo'</code> is the same string <code>'foo'</code>.</p> |
4,260,882 | Simple Select inside an Oracle Stored Procedure | <p>how do you create a stored procedure with a simple select (SELECT * FROM TABLE) using Oracle? Also, any good tutorials on stored procedures would help tremendously.</p>
<p>Thanks.</p> | 4,260,997 | 3 | 1 | null | 2010-11-23 21:01:52.813 UTC | 1 | 2017-05-26 05:47:43.163 UTC | null | null | null | null | 438,678 | null | 1 | 6 | oracle|stored-procedures | 48,285 | <p>It depends on what you're trying to return from the stored procedure (resultset vs. scalar value) and what version of Oracle you're on (newer versions make this easier).</p>
<p>This question is probably a dupe of <a href="https://stackoverflow.com/questions/1170548/get-resultset-from-oracle-stored-procedure">Get resultset from oracle stored procedure</a>.</p> |
4,432,774 | How do I make 2 comparable methods in only one class? | <p>I've got one class, that I sort it already by one attribute.
Now I need to make another thing, that I need to create another way to sort my data.
How can I make it, so I can choose between the two methods.
The only command I know is Collections.sort that will pick up the method compareTo from the class I want to compare its data.</p>
<p>Is it even possible?</p> | 4,432,795 | 3 | 1 | null | 2010-12-13 19:39:22.907 UTC | 18 | 2010-12-13 19:48:25.373 UTC | 2010-12-13 19:42:03.377 UTC | null | 513,838 | null | 509,865 | null | 1 | 29 | java|sorting|collections|comparable | 29,228 | <p>What you need to do is implement a custom <a href="http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html" rel="noreferrer"><code>Comparator</code></a>. And then use:</p>
<pre><code>Collections.sort(yourList, new CustomComparator<YourClass>());
</code></pre>
<p>Specifically, you could write: (This will create an Anonymous class that implements <code>Comparator</code>.)</p>
<pre><code>Collections.sort(yourList, new Comparator<YourClass>(){
public int compare(YourClass one, YourClass two) {
// compare using whichever properties of ListType you need
}
});
</code></pre>
<p>You could build these into your class if you like:</p>
<pre><code>class YourClass {
static Comparator<YourClass> getAttribute1Comparator() {
return new Comparator<YourClass>() {
// compare using attribute 1
};
}
static Comparator<YourClass> getAttribute2Comparator() {
return new Comparator<YourClass>() {
// compare using attribute 2
};
}
}
</code></pre>
<p>It could be used like so:</p>
<pre><code>Collections.sort(yourList, YourClass.getAttribute2Comparator());
</code></pre> |
4,496,910 | onKeyPress event in Firefox and IE8 | <p>I have the following Javascript code. Here I am using <code>onKeyPress="someFunction( )"</code> in the body tag to get the <code>keyCode</code> of the key that is pressed.</p>
<p>The code is working fine in IE8 but this is <strong>not working in Firefox.</strong></p>
<p>Please give some solution to this.</p>
<pre><code><html>
<head>
<title>onKeyPress( ) event not working in firefox..</title>
<script>
function printDiv()
{
var divToPrint=document.getElementById('prnt');
newWin=window.open(''+self.location,'PrintWin','left=50,top=20,width=590,height=840,toolbar=1,resizable=1,scrollbars=yes');
newWin.document.write(divToPrint.outerHTML);
newWin.print();
//newWin.close();
}
</script>
<script>
function keypress()
{
alert(event.keyCode);
var key=event.keyCode;
if(key==112 || key==80)
printDiv();
else if(key==101 || key==69)
window.location="http://google.com";
else if(key==114 || key==82)
window.reset();
}
</script>
</head>
<body bgcolor="lightblue" onkeypress="keypress()">
</code></pre>
<hr />
<h2><strong>Here is the total code which is working fine in IE8 and not working in Firefox.</strong></h2>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Please help me out</title>
<script type="text/javascript">
function printDiv()
{
var divToPrint=document.getElementById('prnt');
newWin=window.open(''+self.location,'PrintWin','left=50,top=20,width=590,height=840,toolbar=1,resizable=1,scrollbars=yes');
newWin.document.write(divToPrint.outerHTML);
newWin.print();
}
</script>
<script type="text/javascript">
function keypress(val)
{
//-----------------------------------------------------
//alert('nnnn');
//alert(window.event ? event.keyCode : val.which);
//if(val.which != 0 && val.charCode != 0)
// alert('Firefox'+String.fromCharCode(val.which));
//else
// alert('IE');
//-------------------------------------------------------
var key=event.keyCode;
if(key==112 || key==80 || val=="print")
printDiv();
else if(key==101 || key==69 || val=="exit")
window.location="http://google.co.in";
else if(key==114 || key==82 || val=="refresh")
document.forms[0].reset();
else
event.returnValue=true;
}
</script>
</head>
<body bgcolor="lightblue" topmargin="0" leftmargin="0"marginwidth="0px" marginheight="0px" onkeypress="keypress(null)">
<table align="left" border="1" cellpadding="5" cellspacing="0" style="width: 100%;height:100%">
<tbody>
<tr><td width="20%" valign="top">ccccccccccc</td>
<td width="80%" align="center">
<table style="width: 100%" border="0" valign="top">
<tr align="right">
<td valign="top">
<button value="refresh" accesskey="R" onclick="keypress(this.value)">
<b><u>R</u></b>efresh
</button>
<button value="print" accesskey="P" onclick="keypress(this.value)">
&nbsp;&nbsp;<b><u>P</u></b>rint&nbsp;&nbsp;
</button>
<button value="exit" accesskey="E" onclick="keypress(this.value)">
&nbsp;&nbsp;&nbsp;<b><u>E</u></b>xit&nbsp;&nbsp;&nbsp;
</button>
</td></tr>
</table>
<h3>Press the letters P->Print , E->Exit etc....</h3>
<h1>Just a test for keypress event</h1>
<form action="http://google.co.in" method="Post">
<div id="prnt">
zzzzzzzzzzzzzzz
</div>
</form>
</td>
</tr>
</tbody>
</table></body></html>
</code></pre> | 4,498,228 | 4 | 2 | null | 2010-12-21 06:56:07.587 UTC | 2 | 2021-05-26 11:11:19.633 UTC | 2021-05-26 11:11:19.633 UTC | null | 4,370,109 | null | 536,146 | null | 1 | 9 | javascript|firefox|dom-events|onkeypress | 50,546 | <p>When problems like this show up, I start to use any kind of a JavaScript framework. Those frameworks are build to avoid problems with different browsers. </p>
<p>To catch all different <code>keypress()</code> apis, like the link from Emmett shows, can be very difficult. </p>
<p><strong>Example:</strong></p>
<p>In HTML head:</p>
<pre><code><script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</code></pre>
<p>In the JS tag:</p>
<pre><code>$(document).keydown(function(event) {
alert('You pressed '+event.keyCode);
event.preventDefault();
});
</code></pre> |
4,297,534 | How can I execute external commands from the gdb command prompt? | <p>I am debugging a program using gdb. Whenever I miss a breakpoint or decide to add another watchpoint, I have to kill the process and rerun it. In order to attach the existing gdb to it, I use <code>attach <pid></code>. However, I have to find out the pid of the new process.</p>
<p>The way I do that today is to suspend gdb, get the pid with <code>ps -C <program_name></code> and then return to gdb to attach to it.</p>
<p>Is there any way to run a unix command from the gdb command prompt without exiting to the shell, so that I could do something like this from inside gdb:</p>
<pre><code>attach `ps -C <program_name>`
</code></pre>
<p>I am working on linux.</p> | 4,297,549 | 4 | 0 | null | 2010-11-28 15:35:58.597 UTC | 4 | 2017-09-05 14:21:31.17 UTC | null | null | null | null | 1,084 | null | 1 | 34 | gdb | 31,120 | <blockquote>
<p>(gdb) help shell<br>
Execute the rest of
the line as a shell command. With no
arguments, run an inferior shell.</p>
</blockquote>
<p>After finish, you can use 'exit' to return to gdb.</p> |
4,093,029 | How to inherit and extend a list object in Python? | <p>I am interested in using the python list object, but with slightly altered functionality. In particular, I would like the list to be 1-indexed instead of 0-indexed. E.g.:</p>
<pre><code>>> mylist = MyList()
>> mylist.extend([1,2,3,4,5])
>> print mylist[1]
</code></pre>
<p>output should be: 1</p>
<p>But when I changed the <code>__getitem__()</code> and <code>__setitem__()</code> methods to do this, I was getting a <code>RuntimeError: maximum recursion depth exceeded</code> error. I tinkered around with these methods a lot but this is basically what I had in there:</p>
<pre><code>class MyList(list):
def __getitem__(self, key):
return self[key-1]
def __setitem__(self, key, item):
self[key-1] = item
</code></pre>
<p>I guess the problem is that <code>self[key-1]</code> is itself calling the same method it's defining. If so, how do I make it use the <code>list()</code> method instead of the <code>MyList()</code> method? I tried using <code>super[key-1]</code> instead of <code>self[key-1]</code> but that resulted in the complaint <code>TypeError: 'type' object is unsubscriptable</code></p>
<p>Any ideas? Also if you could point me at a good tutorial for this that'd be great!</p>
<p>Thanks!</p> | 4,093,037 | 4 | 3 | null | 2010-11-04 00:54:56.49 UTC | 12 | 2021-09-23 19:40:23.067 UTC | 2015-10-27 18:06:59.18 UTC | null | 2,988,730 | null | 323,874 | null | 1 | 71 | python|list|inheritance | 70,820 | <p>Use the <code>super()</code> function to call the method of the base class, or invoke the method directly:</p>
<pre><code>class MyList(list):
def __getitem__(self, key):
return list.__getitem__(self, key-1)
</code></pre>
<p>or</p>
<pre><code>class MyList(list):
def __getitem__(self, key):
return super(MyList, self).__getitem__(key-1)
</code></pre>
<p>However, this will not change the behavior of other list methods. For example, index remains unchanged, which can lead to unexpected results:</p>
<pre><code>numbers = MyList()
numbers.append("one")
numbers.append("two")
print numbers.index('one')
>>> 1
print numbers[numbers.index('one')]
>>> 'two'
</code></pre> |
4,743,996 | Publicly Available Spam Filter Training Set | <p>I'm new to machine learning, and for my first project I'd like to write a naive Bayes spam filter. I was wondering if there are any publicly available training sets of labeled spam/not spam emails, preferably in plain text and not a dump of a relational database (unless they pretty-print those?). </p>
<p>I know such a publicly available database exists for other kinds of text classification, specifically news article text. I just haven't been able to find the same sort of thing for emails.</p> | 4,770,551 | 6 | 2 | null | 2011-01-20 06:08:54.7 UTC | 18 | 2016-01-28 20:10:47.307 UTC | null | null | null | null | 438,830 | null | 1 | 41 | machine-learning|spam-prevention|training-data | 60,802 | <p>Here is what I was looking for: <a href="http://untroubled.org/spam/">http://untroubled.org/spam/</a></p>
<p>This archive has around a gigabyte of compressed accumulated spam messages dating 1998 - 2011. Now I just need to get non-spam email. So I'll just query my own Gmail for that using the getmail program and the tutorial at <a href="http://www.mattcutts.com/blog/backup-gmail-in-linux-with-getmail/">mattcutts.com</a></p> |
4,791,080 | Delete newline / return carriage in file output | <p>I have a wordlist that contains returns to separate each new letter. Is there a way to programatically delete each of these returns using file I/O in Python? </p>
<p>Edit: I know how to manipulate strings to delete returns. I want to physically edit the file so that those returns are deleted.</p>
<p>I'm looking for something like this:</p>
<pre><code>wfile = open("wordlist.txt", "r+")
for line in wfile:
if len(line) == 0:
# note, the following is not real... this is what I'm aiming to achieve.
wfile.delete(line)
</code></pre> | 4,791,169 | 7 | 6 | null | 2011-01-25 07:51:14.367 UTC | 3 | 2022-01-20 10:49:33.753 UTC | 2015-08-29 17:29:56.393 UTC | null | 4,370,109 | null | 372,526 | null | 1 | 15 | python|file|io | 83,717 | <pre><code>>>> string = "testing\n"
>>> string
'testing\n'
>>> string = string[:-1]
>>> string
'testing'
</code></pre>
<p>This basically says "chop off the last thing in the string" The <code>:</code> is the "slice" operator. It would be a good idea to read up on how it works as it is <em>very</em> useful.</p>
<p><strong>EDIT</strong></p>
<p>I just read your updated question. I think I understand now. You have a file, like this:</p>
<pre><code>aqua:test$ cat wordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
</code></pre>
<p>and you want to get rid of the empty lines. Instead of modifying the file while you're reading from it, create a new file that you can write the non-empty lines from the old file into, like so:</p>
<pre><code># script
rf = open("wordlist.txt")
wf = open("newwordlist.txt","w")
for line in rf:
newline = line.rstrip('\r\n')
wf.write(newline)
wf.write('\n') # remove to leave out line breaks
rf.close()
wf.close()
</code></pre>
<p>You should get:</p>
<pre><code>aqua:test$ cat newwordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
</code></pre>
<p>If you want something like</p>
<pre><code>TestingThisWordlistWithReturnsBetweenLines
</code></pre>
<p>just comment out </p>
<pre><code>wf.write('\n')
</code></pre> |
4,076,912 | ASP.NET page_init event? | <p>I am using ASP.NET 3.5 and i used earlier 1.1 i am having difficulty to find where can i attach/declare the page init event ?</p>
<p>In 1.1 there was auto generated code which used to have initialization code. Where we can add the page init method. So i am confused please help.</p> | 4,076,944 | 7 | 0 | null | 2010-11-02 10:48:03.78 UTC | 8 | 2015-08-17 15:51:31.067 UTC | null | null | null | null | 237,743 | null | 1 | 25 | asp.net | 99,374 | <p>Just declare this in your code behind:</p>
<pre><code>protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
</code></pre> |
4,290,541 | What is the first character in the sort order used by Windows Explorer? | <p>For example, in a Windows folder, if we create some files and name them 1.html, 2.txt, 3.txt, photo.jpg, zen.png the order will be as is. But if we create another file with the name _file.doc it will be placed at the top. (considering we sort by name in descending order)</p>
<p>likewise, what would be the character that would be considered as the first, such that if i use that character, it would place the file on top of the hierarchy?</p> | 4,290,552 | 9 | 3 | null | 2010-11-27 07:07:51.797 UTC | 22 | 2021-11-10 12:24:45.603 UTC | 2010-11-29 08:46:40.223 UTC | null | 71,059 | null | 269,194 | null | 1 | 68 | windows|algorithm|programming-languages|char|special-characters | 142,072 | <p>The first visible character is '!' according to ASCII table.And the last one is '~'
So "!file.doc" or "~file.doc' will be the top one depending your ranking order.
You can check the ascii table here:
<a href="http://www.asciitable.com/" rel="nofollow noreferrer">http://www.asciitable.com/</a></p> |
4,562,734 | Android Starting Service at Boot Time , How to restart service class after device Reboot? | <p>I need to start a service at boot time. I searched a lot. They are talking about Broadcastreceiver. As I am new to android development, I didn't get a clear picture about services on Android. Please provide some source code.</p> | 4,562,804 | 9 | 3 | null | 2010-12-30 12:52:43.363 UTC | 73 | 2021-01-20 15:05:21.61 UTC | 2021-01-20 15:05:21.61 UTC | null | 4,853,133 | null | 244,540 | null | 1 | 115 | android|service|background-service|autostart|bootcompleted | 159,163 | <p>Create a <a href="http://developer.android.com/reference/android/content/BroadcastReceiver.html" rel="noreferrer"><code>BroadcastReceiver</code></a> and register it to receive <a href="http://developer.android.com/reference/android/content/Intent.html#ACTION_BOOT_COMPLETED" rel="noreferrer">ACTION_BOOT_COMPLETED</a>. You also need <a href="http://developer.android.com/reference/android/Manifest.permission.html#RECEIVE_BOOT_COMPLETED" rel="noreferrer">RECEIVE_BOOT_COMPLETED</a> permission.</p>
<p>Read: <a href="https://developer.android.com/guide/components/broadcasts#system-broadcasts" rel="noreferrer">Listening For and Broadcasting Global Messages,</a> <a href="https://developer.android.com/training/scheduling/alarms" rel="noreferrer">and Setting Alarms</a></p> |
4,360,182 | Call PHP function from url? | <p>If I want to execute a php script, i just point the browser to <code>www.something.com/myscript.php</code></p>
<p>But if i want to execute a specific function inside <code>myscript.php</code>, is there a way? something like <code>www.something.com/myscript.php.specificFunction</code></p>
<p>Thanks!</p> | 4,360,202 | 14 | 0 | null | 2010-12-05 17:38:05.537 UTC | 18 | 2017-04-16 13:33:38.917 UTC | 2016-09-15 13:01:49.407 UTC | null | 1,216,451 | null | 162,414 | null | 1 | 34 | php | 97,440 | <p>One <strong>quick way</strong> is to do things like</p>
<pre><code>something.com/myscript.php?f=your_function_name
</code></pre>
<p>then in myscript.php</p>
<pre><code>if(function_exists($_GET['f'])) {
$_GET['f']();
}
</code></pre>
<p>But please, for the love of all kittens, don't abuse this.</p> |
4,367,260 | Creating a recursive method for Palindrome | <p>I am trying to create a Palindrome program using recursion within Java but I am stuck, this is what I have so far:</p>
<pre><code> public static void main (String[] args){
System.out.println(isPalindrome("noon"));
System.out.println(isPalindrome("Madam I'm Adam"));
System.out.println(isPalindrome("A man, a plan, a canal, Panama"));
System.out.println(isPalindrome("A Toyota"));
System.out.println(isPalindrome("Not a Palindrome"));
System.out.println(isPalindrome("asdfghfdsa"));
}
public static boolean isPalindrome(String in){
if(in.equals(" ") || in.length() == 1 ) return true;
in= in.toUpperCase();
if(Character.isLetter(in.charAt(0))
}
public static boolean isPalindromeHelper(String in){
if(in.equals("") || in.length()==1){
return true;
}
}
}
</code></pre>
<p>Can anyone supply a solution to my problem?</p> | 4,367,356 | 21 | 5 | null | 2010-12-06 14:14:56.14 UTC | 6 | 2018-08-22 13:41:05.22 UTC | 2015-06-28 01:17:25.057 UTC | null | 885,189 | null | 508,411 | null | 1 | 5 | java|recursion|palindrome | 126,624 | <p>Here I am pasting code for you:</p>
<p>But, I would strongly suggest you to know how it works,</p>
<p>from your question , you are totally unreadable. </p>
<p>Try understanding this code. <strong>Read the comments from code</strong></p>
<pre><code>import java.util.Scanner;
public class Palindromes
{
public static boolean isPal(String s)
{
if(s.length() == 0 || s.length() == 1)
// if length =0 OR 1 then it is
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
// check for first and last char of String:
// if they are same then do the same thing for a substring
// with first and last char removed. and carry on this
// until you string completes or condition fails
return isPal(s.substring(1, s.length()-1));
// if its not the case than string is not.
return false;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("type a word to check if its a palindrome or not");
String x = sc.nextLine();
if(isPal(x))
System.out.println(x + " is a palindrome");
else
System.out.println(x + " is not a palindrome");
}
}
</code></pre> |
4,425,198 | Can I create links with 'target="_blank"' in Markdown? | <p>Is there a way to create a link in Markdown that opens in a new window? If not, what syntax do you recommend to do this? I'll add it to the markdown compiler I use. I think it should be an option.</p> | 4,425,223 | 23 | 3 | null | 2010-12-13 01:33:05.087 UTC | 75 | 2022-06-29 15:39:09.037 UTC | 2021-10-07 11:14:16.59 UTC | null | 4,905,220 | null | 242,933 | null | 1 | 694 | html|hyperlink|markdown|target|new-window | 373,627 | <p>As far as the Markdown syntax is concerned, if you want to get that detailed, you'll just have to use HTML.</p>
<pre><code><a href="http://example.com/" target="_blank">Hello, world!</a>
</code></pre>
<p>Most Markdown engines I've seen allow plain old HTML, just for situations like this where a generic text markup system just won't cut it. (The StackOverflow engine, for example.) They then run the entire output through an HTML whitelist filter, regardless, since even a Markdown-only document can easily contain XSS attacks. As such, if you or your users want to create <code>_blank</code> links, then they probably still can.</p>
<p>If that's a feature you're going to be using often, it might make sense to create your own syntax, but it's generally not a vital feature. If I want to launch that link in a new window, I'll ctrl-click it myself, thanks.</p> |
14,508,495 | User.Identity.IsAuthenticated returns false after setting cookie and validating | <p>I am having a problem with MVC4 user authorization.</p>
<p><code>System.Web.Security.Membership.ValidateUser</code> returns <code>true</code>.<br>
Then it gets to <code>FormsAuthentication.SetAuthCookie</code> and I see a cookie in my browser.<br>
Then <code>User.Identity.IsAuthenticated</code> still evaluates to <code>false</code> for some reason.<br>
<code>User.Identity.IsAuthenticated</code> is still false after a redirect and stays <code>false</code>.</p>
<pre><code>[AllowAnonymous]
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (System.Web.Security.Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
</code></pre> | 14,508,557 | 3 | 3 | null | 2013-01-24 18:45:13.827 UTC | 2 | 2016-10-20 21:26:41.727 UTC | 2016-10-20 21:26:41.727 UTC | null | 11,683 | null | 1,569,588 | null | 1 | 19 | asp.net-mvc|asp.net-mvc-4 | 39,353 | <p><code>User.Identity.IsAuthenticated</code> won't be set to true until the next request after calling <code>FormsAuthentication.SetAuthCookie()</code>.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/twk5762b.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/twk5762b.aspx</a></p>
<blockquote>
<p>The SetAuthCookie method adds a forms-authentication ticket to either
the cookies collection, or to the URL if CookiesSupported is false.
The forms-authentication ticket supplies forms-authentication
information to the next request made by the browser.</p>
</blockquote> |
14,469,522 | Stop an R program without error | <p>Is there any way to stop an R program without error? </p>
<p>For example I have a big source, defining several functions and after it there are some calls to the functions. It happens that I edit some function, and want the function definitions to be updated in R environment, but they are not actually called. </p>
<p>I defined a variable <code>justUpdate</code> and when it is <code>TRUE</code> want to stop the program just after function definitions.</p>
<pre><code>ReadInput <- function(...) ...
Analyze <- function(...) ...
WriteOutput <- function(...) ...
if (justUpdate)
stop()
# main body
x <- ReadInput()
y <- Analyze(x)
WriteOutput(y)
</code></pre>
<p>I have called <code>stop()</code> function, but the problem is that it prints an error message.</p>
<p><kbd>ctrl</kbd>+<kbd>c</kbd> is another option, but I want to stop the source in specific line.</p>
<p>The problem with <code>q()</code> or <code>quit()</code> is that it terminates R session, but I would like to have the R session still open.</p>
<p>As @JoshuaUlrich proposed <code>browser()</code> can be another option, but still not perfect, because the source terminates in a new environment (i.e. the R prompt will change to <code>Browser[1]></code> rather than <code>></code>). Still we can press <code>Q</code> to quit it, but I am looking for the straightforward way.</p>
<p>Another option is to use <code>if (! justUpdate) { main body }</code> but it's clearing the problem, not solving it.</p>
<p>Is there any better option?</p> | 14,469,555 | 12 | 8 | null | 2013-01-22 22:50:07.497 UTC | 9 | 2022-06-20 15:49:58.577 UTC | 2015-08-19 20:57:01.21 UTC | null | 1,677,912 | null | 1,657,511 | null | 1 | 35 | r|debugging | 17,092 | <p>You're looking for the function <code>browser</code>.</p> |
14,435,520 | Why use HttpClient for Synchronous Connection | <p>I am building a class library to interact with an API. I need to call the API and process the XML response. I can see the benefits of using <code>HttpClient</code> for Asynchronous connectivity, but what I am doing is purely synchronous, so I cannot see any significant benefit over using <code>HttpWebRequest</code>.</p>
<p>If anyone can shed any light I would greatly appreciate it. I am not one for using new technology for the sake of it.</p> | 66,656,039 | 6 | 3 | null | 2013-01-21 09:17:31.323 UTC | 44 | 2022-04-21 14:03:08.72 UTC | 2019-11-07 09:11:12.887 UTC | null | 2,361 | null | 1,343,887 | null | 1 | 228 | c#|asp.net|dotnet-httpclient | 216,914 | <p>For anyone coming across this now, .NET 5.0 has added a synchronous <code>Send</code> method to <code>HttpClient</code>. <a href="https://github.com/dotnet/runtime/pull/34948" rel="noreferrer">https://github.com/dotnet/runtime/pull/34948</a></p>
<p>The merits as to why where discussed at length here: <a href="https://github.com/dotnet/runtime/issues/32125" rel="noreferrer">https://github.com/dotnet/runtime/issues/32125</a></p>
<p>You can therefore use this instead of <code>SendAsync</code>. For example</p>
<pre><code>public string GetValue()
{
var client = new HttpClient();
var webRequest = new HttpRequestMessage(HttpMethod.Post, "http://your-api.com")
{
Content = new StringContent("{ 'some': 'value' }", Encoding.UTF8, "application/json")
};
var response = client.Send(webRequest);
using var reader = new StreamReader(response.Content.ReadAsStream());
return reader.ReadToEnd();
}
</code></pre>
<p>This code is just a simplified example - it's not production ready.</p> |
42,992,911 | React-Router only one child | <p>I keep on getting the error:</p>
<blockquote>
<p>A 'Router' may have only one child element</p>
</blockquote>
<p>when using react-router.</p>
<p>I can't seem to figure out why this is not working, since it's exactly like the code they show in their example: <a href="https://reacttraining.com/react-router/web/guides/quick-start" rel="nofollow noreferrer">Quick Start</a></p>
<p>Here is my code:</p>
<pre><code>import React from 'react';
import Editorstore from './Editorstore';
import App from './components/editor/App';
import BaseLayer from './components/baselayer';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import {render} from 'react-dom';
const root = document.createElement('div');
root.id = 'app';
document.body.appendChild(root);
const store = new Editorstore();
const stylelist = ['https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css', 'https://api.tiles.mapbox.com/mapbox-gl-js/v0.33.1/mapbox-gl.css'];
stylelist.map((link) => {
const a = document.createElement('link');
a.rel = 'stylesheet';
a.href = link;
document.body.appendChild(a);
return null;
});
render((
<Router>
<Route exact path="/" component={BaseLayer} />
<Route path="/editor" component={App} store={store} />
</Router>
), document.querySelector('#app'));
</code></pre> | 42,992,995 | 10 | 1 | null | 2017-03-24 06:33:08.107 UTC | 21 | 2021-11-10 00:09:21.43 UTC | 2021-11-10 00:09:21.43 UTC | null | 15,993,687 | null | 4,145,010 | null | 1 | 75 | javascript|reactjs|react-router | 68,386 | <p>You have to wrap your <code>Route</code>'s in a <code><div></code>(or a <a href="https://reacttraining.com/react-router/web/api/Switch" rel="noreferrer"><code><Switch></code></a>).</p>
<pre><code>render((
<Router>
<Route exact path="/" component={BaseLayer} />
<Route path="/editor" component={App} store={store} />
</Router>
), document.querySelector('#app'));
</code></pre>
<p>should be</p>
<pre><code>render((
<Router>
<div>
<Route exact path="/" component={BaseLayer} />
<Route path="/editor" component={App} store={store} />
</div>
</Router>
), document.querySelector('#app'));
</code></pre>
<p><a href="https://jsfiddle.net/69z2wepo/88077/" rel="noreferrer">jsfiddle</a> / <a href="https://www.webpackbin.com/bins/-Kfz15YMXr44luMuLWLD" rel="noreferrer">webpackbin</a></p> |
44,141,255 | Fiddler 4.6 cannot connect to strong SSL? | <p>Error:</p>
<pre><code>[Fiddler] The connection to '<the site>.com' failed.
System.Security.SecurityException Failed to negotiate HTTPS connection with server.fiddler.network.https> HTTPS handshake to <the site>.com (for #3) failed. System.IO.IOException Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. < An existing connection was forcibly closed by the remote host
</code></pre>
<p>I can hit fine in web browser. I do see it is rather strong SSL (FireFox reports it as TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 256 bit keys, TLS 1.2)</p>
<p>Why isn't Fiddler able to make this connection?</p> | 44,141,846 | 1 | 0 | null | 2017-05-23 17:21:22.72 UTC | 4 | 2020-02-28 17:23:11.037 UTC | null | null | null | null | 147,637 | null | 1 | 46 | fiddler | 12,407 | <p>Seems that your client didn't try to connect via 1.2</p>
<p>Check: Tools > Fiddler Options > HTTPS
It's set to <strong><client>;ssl3;tls1.0</strong></p>
<p>Add "<strong>tls1.2</strong>" to the protocols list</p>
<p><strong>Edit:</strong>
Refer to the image below for where to find the option:
<a href="https://i.stack.imgur.com/ZGu0u.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZGu0u.png" alt="enter image description here"></a></p> |
46,063,374 | Is it really possible for webRTC to stream high quality audio without noise? | <p>I have tested with the highest quality settings and multiple STUN/TURN servers with no luck in finding a real high quality stream. </p>
<p>In my experience webRTC always has a fluctuating and limited bandwidth and a high level of background noise that doesn't reach the quality of mp3/Shoutcast/Icecast radio streams. </p>
<p>Has anyone found a way to provide a real high bandwidth audio stream with webRTC or is it not actually possible at this time?</p> | 46,103,944 | 2 | 1 | null | 2017-09-05 21:08:53.227 UTC | 12 | 2021-05-11 21:56:28.71 UTC | 2017-09-05 23:16:47.92 UTC | null | 1,688,726 | null | 1,688,726 | null | 1 | 9 | javascript|streaming|webrtc|voip|opus | 8,768 | <p>Firstly, its worth saying that Web RTC builds on the underlying network connectivity and if it is poor then there is very little any higher layers can do to avoid this.</p>
<p>Looking at the particular comparison you have highlighted, there are a couple of factors which are key to VoIP voice quality (assuming you are focused on voice from the question):</p>
<ul>
<li>Latency: to avoid delay and echo, voice communication needs a low end to end latency. The target for good quality VoIP systems is usually sub 200 ms latency. </li>
<li>Jitter - this is essentially the variance in the latency one time, i.e. how the end to end delay varies over time.</li>
<li>Packet loss - voice is actually reasonably tolerant to packet loss compared to data. VoIp targets are typically in the 1% or less range.</li>
</ul>
<p>Comparing this with steamed radio etc, the key point is the latency - it is not unusual to wait several seconds for a stream to start playing back.</p>
<p>This allows the receiver to fill a much bigger buffer of packets waiting to be decoded and played back, and makes it much more tolerant of variations in the latency (jitter).</p>
<p>Taking a simple example, if you had a brief half second interruption in your connection, this would immediately impact a two way VoIP call, but it might not impact streamed audio at all, assuming the network recovers fully and the buffer had several seconds worth of content in it at the time.</p>
<p>So the quality difference you are seeing compared to streamed audio are most likely related to the real tine nature of the communication, rather than with inherent WebRTC faults - or maybe more precisely, even if WebRTC was perfect, real time two way VoIP is very susceptible to network conditions.</p>
<p>As. a note, video cleary needs much more bandwidth, and is also impacted by the network but people tend to be more tolerant of video 'stutters' than voice quality issues in multimedia calls (at this time amyay).</p> |
38,511,976 | How can i export socket.io into other modules in nodejs? | <p>I have <code>socket.io</code> working in <code>app.js</code> but when i am trying to call it from other modules its not creating <code>io.connection</code> not sure ?</p>
<p>app.js</p>
<pre><code>var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var ditconsumer = require('./app/consumers/ditconsumer');
ditconsumer.start(io);
server.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
</code></pre>
<p>consumer.js</p>
<pre><code>module.exports = {
start: function (io) {
consumer.on('message', function (message) {
logger.log('info', message.value);
io.on('connection', function (socket) {
socket.on('message', function(message) {
socket.emit('ditConsumer',message.value);
console.log('from console',message.value);
});
});
});
}
}
</code></pre> | 38,514,118 | 8 | 0 | null | 2016-07-21 18:38:34.337 UTC | 20 | 2021-06-28 17:23:09.633 UTC | 2016-07-22 14:38:55.303 UTC | null | 6,014,098 | null | 6,014,098 | null | 1 | 36 | javascript|node.js|socket.io | 34,936 | <p>Since app.js is usually kind of the main initialization module in your app, it will typically both initialize the web server and socket.io and will load other things that are needed by the app.</p>
<p>As such a typical way to share <code>io</code> with other modules is by passing them to the other modules in that module's constructor function. That would work like this:</p>
<pre><code>var server = require('http').createServer(app);
var io = require('socket.io')(server);
// load consumer.js and pass it the socket.io object
require('./consumer.js')(io);
// other app.js code follows
</code></pre>
<p>Then, in consumer.js:</p>
<pre><code>// define constructor function that gets `io` send to it
module.exports = function(io) {
io.on('connection', function(socket) {
socket.on('message', function(message) {
logger.log('info',message.value);
socket.emit('ditConsumer',message.value);
console.log('from console',message.value);
});
});
};
</code></pre>
<hr />
<p>Or, if you want to use a <code>.start()</code> method to initialize things, you can do the same thing with that (minor differences):</p>
<pre><code>// app.js
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// load consumer.js and pass it the socket.io object
var consumer = require('./consumer.js');
consumer.start(io);
// other app.js code follows
</code></pre>
<p>And the start method in consumer.js</p>
<pre><code>// consumer.js
// define start method that gets `io` send to it
module.exports = {
start: function(io) {
io.on('connection', function(socket) {
socket.on('message', function(message) {
logger.log('info',message.value);
socket.emit('ditConsumer',message.value);
console.log('from console',message.value);
});
});
};
}
</code></pre>
<hr />
<p>This is what is known as the "push" module of resource sharing. The module that is loading you pushes some shared info to you by passing it in the constructor.</p>
<p>There are also "pull" models where the module itself calls a method in some other module to retrieve the shared info (in this case the <code>io</code> object).</p>
<p>Often, either model can be made to work, but usually one or the other will feel more natural given how modules are being loaded and who has the desired information and how you intend for modules to be reused in other circumstances.</p> |
55,657,971 | How to mock API calls made within a React component being tested with Jest | <p>I'm trying to mock a fetch() that retrieves data into a component.</p>
<p><a href="https://github.com/kentcdodds/react-testing-library-course/blob/master/src/__tests__/tdd-03-api.js" rel="noreferrer">I'm using this as a model for mocking my fetches</a>, but I'm having trouble getting it to work.</p>
<p>I'm getting this error when I run my tests: <code>babel-plugin-jest-hoist: The module factory of 'jest.mock()' is not allowed to reference any out-of-scope variables.</code></p>
<p>Is there a way I can have these functions return mock data instead of actually trying to make real API calls?</p>
<h1>Code</h1>
<h2>utils/getUsers.js</h2>
<p>Returns users with roles mapped into each user.</p>
<pre><code>const getUsersWithRoles = rolesList =>
fetch(`/users`, {
credentials: "include"
}).then(response =>
response.json().then(d => {
const newUsersWithRoles = d.result.map(user => ({
...user,
roles: rolesList.filter(role => user.roles.indexOf(role.iden) !== -1)
}));
return newUsersWithRoles;
})
);
</code></pre>
<h2>component/UserTable.js</h2>
<pre><code>const UserTable = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
getTableData();
}, []);
const getTableData = () => {
new Promise((res, rej) => res(getRoles()))
.then(roles => getUsersWithRoles(roles))
.then(users => {
setUsers(users);
});
};
return (...)
};
</code></pre>
<h2>component/<strong>tests</strong>/UserTable.test.js</h2>
<pre><code>import "jest-dom/extend-expect";
import React from "react";
import { render } from "react-testing-library";
import UserTable from "../UserTable";
import { getRoles as mockGetRoles } from "../utils/roleUtils";
import { getUsersWithRoles as mockGetUsersWithRoles } from "../utils/userUtils";
const users = [
{
name: "Benglish",
iden: "63fea823365f1c81fad234abdf5a1f43",
roles: ["eaac4d45c3c41f449cf7c94622afacbc"]
}
];
const roles = [
{
iden: "b70e1fa11ae089b74731a628f2a9b126",
name: "senior dev"
},
{
iden: "eaac4d45c3c41f449cf7c94622afacbc",
name: "dev"
}
];
const usersWithRoles = [
{
name: "Benglish",
iden: "63fea823365f1c81fad234abdf5a1f43",
roles: [
{
iden: "eaac4d45c3c41f449cf7c94622afacbc",
name: "dev"
}
]
}
];
jest.mock("../utils/userUtils", () => ({
getUsers: jest.fn(() => Promise.resolve(users))
}));
jest.mock("../utils/roleUtils", () => ({
getRolesWithUsers: jest.fn(() => Promise.resolve(usersWithRoles)),
getRoles: jest.fn(() => Promise.resolve(roles))
}));
test("<UserTable/> show users", () => {
const { queryByText } = render(<UserTable />);
expect(queryByText("Billy")).toBeTruthy();
});
</code></pre> | 55,659,967 | 4 | 0 | null | 2019-04-12 18:58:40.333 UTC | 5 | 2022-01-28 05:34:14.89 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 9,120,501 | null | 1 | 13 | javascript|reactjs|jestjs|react-testing-library | 44,842 | <p>By default <code>jest.mock</code> calls are hoisted by <code>babel-jest</code>...</p>
<p>...this means they run before anything else in your test file, so any variables declared in the test file won't be in scope yet.</p>
<p>That is why the module factory passed to <code>jest.mock</code> can't reference anything outside itself.</p>
<hr>
<p>One option is to move the data <strong>inside</strong> the module factory like this:</p>
<pre><code>jest.mock("../utils/userUtils", () => {
const users = [ /* mock users data */ ];
return {
getUsers: jest.fn(() => Promise.resolve(users))
};
});
jest.mock("../utils/roleUtils", () => {
const roles = [ /* mock roles data */ ];
const usersWithRoles = [ /* mock usersWithRoles data */ ];
return {
getRolesWithUsers: jest.fn(() => Promise.resolve(usersWithRoles)),
getRoles: jest.fn(() => Promise.resolve(roles))
};
});
</code></pre>
<hr>
<p>Another option is to mock the functions using <code>jest.spyOn</code>:</p>
<pre><code>import * as userUtils from '../utils/userUtils';
import * as roleUtils from '../utils/roleUtils';
const users = [ /* mock users data */ ];
const roles = [ /* mock roles data */ ];
const usersWithRoles = [ /* mock usersWithRoles data */ ];
const mockGetUsers = jest.spyOn(userUtils, 'getUsers');
mockGetUsers.mockResolvedValue(users);
const mockGetRolesWithUsers = jest.spyOn(roleUtils, 'getRolesWithUsers');
mockGetRolesWithUsers.mockResolvedValue(usersWithRoles);
const mockGetRoles = jest.spyOn(roleUtils, 'getRoles');
mockGetRoles.mockResolvedValue(roles);
</code></pre>
<hr>
<p>And another option is to auto-mock the modules:</p>
<pre><code>import * as userUtils from '../utils/userUtils';
import * as roleUtils from '../utils/roleUtils';
jest.mock('../utils/userUtils');
jest.mock('../utils/roleUtils');
const users = [ /* mock users data */ ];
const roles = [ /* mock roles data */ ];
const usersWithRoles = [ /* mock usersWithRoles data */ ];
userUtils.getUsers.mockResolvedValue(users);
roleUtils.getRolesWithUsers.mockResolvedValue(usersWithRoles);
roleUtils.getRoles.mockResolvedValue(roles);
</code></pre>
<p>...and add the mocked response to the empty mock functions.</p> |
55,851,918 | How to wrap row items in a card with flutter | <p>I have a card that contains row of items (text and checkbox widgets). The problem is that the card can only fill up limited space each row, but it isn't going to the next line in the row. I tried using the wrap widget but it had no effect. I keep getting this:</p>
<p><a href="https://i.stack.imgur.com/m42iK.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/m42iK.jpg" alt="enter image description here" /></a></p>
<p>As you can see it is not wrapping to the next but trying to fit everything in that one line. Here is my code:</p>
<pre><code>Widget _buildCategories() {
return Card(
margin: const EdgeInsets.only(top: 20.0),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Text(
'Categories',
style: TextStyle(fontFamily: 'MonteSerrat', fontSize: 16.0),
),
Wrap(
children: <Widget>[
Row(
children: <Widget>[
_checkBox('Gaming'),
_checkBox('Sports'),
_checkBox('Casual'),
_checkBox('21 +'),
_checkBox('Adult'),
_checkBox('Food'),
_checkBox('Club'),
_checkBox('Activities'),
_checkBox('Shopping'),
],
)
],
)
],
),
));
}
Widget _checkBox(String category) {
return Expanded(
child: Column(
children: <Widget>[
Text(
'$category',
textAlign: TextAlign.center,
style: TextStyle(fontFamily: 'MonteSerrat'),
),
Checkbox(
value: false,
onChanged: (value) {
// We will update the value to the firebase data here
print('updated value to: $value');
},
)
],
));
}
</code></pre> | 55,852,249 | 1 | 0 | null | 2019-04-25 14:39:36.73 UTC | 1 | 2022-08-12 14:47:28.03 UTC | 2021-04-16 11:31:33.373 UTC | null | 25,282 | null | 3,152,311 | null | 1 | 24 | dart|flutter|row|word-wrap | 56,405 | <p>I fixed your code with the following changes:</p>
<ul>
<li><p>Removed <code>Row</code> widget inside <code>Wrap</code>.</p>
</li>
<li><p>Removed <code>Expanded</code> widget.</p>
</li>
<li><p>Add the property <code>maxLines</code> to your <code>Text</code> widget.</p>
<pre><code> Widget _buildCategories() {
return Card(
margin: const EdgeInsets.only(top: 20.0),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Text(
'Categories',
style: TextStyle(fontFamily: 'MonteSerrat', fontSize: 16.0),
),
Wrap(
children: <Widget>[
_checkBox('Gaming'),
_checkBox('Sports'),
_checkBox('Casual'),
_checkBox('21 +'),
_checkBox('Adult'),
_checkBox('Food'),
_checkBox('Club'),
_checkBox('Activities'),
_checkBox('Shopping')
],
)
],
),
));
}
Widget _checkBox(String category) {
return Column(
children: <Widget>[
Text(
'$category',
maxLines: 1,
textAlign: TextAlign.center,
style: TextStyle(fontFamily: 'MonteSerrat'),
),
Checkbox(
value: false,
onChanged: (value) {
// We will update the value to the firebase data here
print('updated value to: $value');
},
)
],
);
}
}
</code></pre>
</li>
</ul>
<p>Also you can add the properties <code>runSpacing</code> and <code>spacing</code> to your <code>Wrap</code> widget to give more space between your items in horizontal and vertical.</p>
<pre><code> Wrap(
runSpacing: 5.0,
spacing: 5.0,
</code></pre>
<p>More info here: <a href="https://api.flutter.dev/flutter/widgets/Wrap-class.html" rel="nofollow noreferrer">https://api.flutter.dev/flutter/widgets/Wrap-class.html</a></p> |
69,037,481 | Android app won't build -- The minCompileSdk (31) specified in a dependency's androidx.work:work-runtime:2.7.0-beta01 | <p>I'm trying to build a project in my M1,</p>
<p>but I got this error when I run <code>npx react-native run-android</code></p>
<pre><code>FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.work:work-runtime:2.7.0-beta01.
AAR metadata file: /Users/macpro/.gradle/caches/transforms-3/999e9d813832e06d8f1b7de52647a502/transformed/work-runtime-2.7.0-beta01/META-INF/com/android/build/gradle/aar-metadata.properties.
</code></pre>
<p>Android/build.gradle</p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "30.0.0"
minSdkVersion = 21
compileSdkVersion = 30
targetSdkVersion = 30
supportLibVersion = "28.0.0"
}
repositories {
google()
jcenter()
}
dependencies {
classpath('com.android.tools.build:gradle:4.1.2')
classpath('com.google.gms:google-services:4.3.0')
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
}
</code></pre>
<p>gradle-wrapper.properties</p>
<pre><code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
</code></pre> | 69,037,841 | 28 | 0 | null | 2021-09-02 22:03:16.11 UTC | 4 | 2022-09-08 14:28:45.613 UTC | 2021-09-05 13:49:21.66 UTC | null | 3,998,402 | null | 11,848,459 | null | 1 | 39 | android|gradle | 64,367 | <p>The error is being caused because one of your dependencies is internally using <a href="https://developer.android.com/jetpack/androidx/releases/work#version_270_2" rel="noreferrer">WorkManager 2.7.0-beta01</a> that was released today (which needs API 31). In my case it was <a href="https://android.googlesource.com/platform/tools/base/+/studio-master-dev/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/tasks/CheckAarMetadataTask.kt#142" rel="noreferrer"><code>CheckAarMetadata.kt</code></a>.</p>
<p>You can fix it by forcing Gradle to use an older version of Work Manager for the transitive dependency that works with API 30. In your <code>build.gradle</code> file add:</p>
<pre><code>dependencies {
def work_version = "2.6.0"
// Force WorkManager 2.6.0 for transitive dependency
implementation("androidx.work:work-runtime-ktx:$work_version") {
force = true
}
}
</code></pre>
<p>This should fix it.</p> |
40,536,778 | How to workaround "the input device is not a TTY" when using grunt-shell to invoke a script that calls docker run? | <p>When issuing <code>grunt shell:test</code>, I'm getting warning "the input device is not a TTY" & don't want to have to use <code>-f</code>:</p>
<pre><code>$ grunt shell:test
Running "shell:test" (shell) task
the input device is not a TTY
Warning: Command failed: /bin/sh -c ./run.sh npm test
the input device is not a TTY
Use --force to continue.
Aborted due to warnings.
</code></pre>
<p>Here's the <code>Gruntfile.js</code> command:</p>
<pre><code>shell: {
test: {
command: './run.sh npm test'
}
</code></pre>
<p>Here's <code>run.sh</code>:</p>
<pre><code>#!/bin/sh
# should use the latest available image to validate, but not LATEST
if [ -f .env ]; then
RUN_ENV_FILE='--env-file .env'
fi
docker run $RUN_ENV_FILE -it --rm --user node -v "$PWD":/app -w /app yaktor/node:0.39.0 $@
</code></pre>
<p>Here's the relevant <code>package.json</code> <code>scripts</code> with command <code>test</code>:</p>
<pre><code>"scripts": {
"test": "mocha --color=true -R spec test/*.test.js && npm run lint"
}
</code></pre>
<p>How can I get <code>grunt</code> to make <code>docker</code> happy with a TTY? Executing <code>./run.sh npm test</code> outside of grunt works fine:</p>
<pre><code>$ ./run.sh npm test
> [email protected] test /app
> mocha --color=true -R spec test/*.test.js && npm run lint
[snip]
105 passing (3s)
> [email protected] lint /app
> standard --verbose
</code></pre> | 40,536,892 | 2 | 0 | null | 2016-11-10 20:51:35.96 UTC | 6 | 2018-07-21 02:14:23.303 UTC | null | null | null | null | 969,237 | null | 1 | 34 | docker|gruntjs|tty|grunt-shell | 42,487 | <p>Remove the <code>-t</code> from the docker run command:</p>
<pre><code>docker run $RUN_ENV_FILE -i --rm --user node -v "$PWD":/app -w /app yaktor/node:0.39.0 $@
</code></pre>
<p>The <code>-t</code> tells docker to configure the tty, which won't work if you don't have a tty and try to attach to the container (default when you don't do a <code>-d</code>).</p> |
49,844,781 | Uncaught (in promise) TypeError: Request failed | <p>I am creating a Progressive Web App for a university project, but when I checked the console I have this error:</p>
<blockquote>
<p>Uncaught (in promise) TypeError: Request failed - serviceworker.js:1</p>
</blockquote>
<p>I don't understand where this error is coming from. </p>
<p>The HTML and CSS are showing on as expected, but when I do a PWA audit from the Chrome Dev Tools, it's showing <a href="https://i.stack.imgur.com/IjthH.png" rel="noreferrer">these failures. They are 'no service worker', 'no 200 when offline' and 'user not prompted to install web app'.</a></p>
<p>Any help is appreciated! </p>
<p>Thanks in advance!
<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>*{
padding: 0;
margin: 0;
font-family: "Roboto", sans-serif;
color: #4E5863;
}
.indexLogo{
height: 180px;
text-align: center;
padding: 36px 0;
border-bottom: 1px solid #E5E9F2;
}
.intuPotteriesLogo, .manchesterAirportLogo{
width: 252px;
height: auto;
}
.indexTitle{
text-align: center;
padding: 36px 0;
font-weight: 500;
border-bottom: 1px solid #E5E9F2;
font-size: 24px;
}
header{
width: 100%;
text-align: center;
}
#headerStokeCityOfCulture{
width: 100%;
}
#container{
width: 100%;
text-align: center;
}
.hotLinks{
border: 2px solid #ABB5C3;
width: 22%;
margin: 10px 10px;
display: inline-block;
}
.hotLinksLogos{
width: 100%;
}
.hotLinksTitle{
text-align: center;
padding: 10px;
border-top: 2px solid #ABB5C3;
}
.searchBarContainer{
text-align: center;
padding: 20px 0;
border-bottom: 1px solid #E5E9F2;
}
.searchBox{
width: 90%;
height: 30px;
font-size: 18px;
text-align: center;
background-color: #E5E9F2;
border: none;
color: black;
}
.bookingItem{
width: 100%;
padding: 20px 0;
border-bottom: 1px solid #E5E9F2;
text-decoration: none;
font-size: 20px;
}
.bookingItemIcon{
height: 60px;
}
.bookingItemLeft{
width: 25%;
display: inline-block;
text-align: center;
vertical-align: middle;
}
.bookingItemRight{
width: 65%;
display: inline-block;
vertical-align: middle;
padding-left: 15px;
}
.bookingTitle{
font-size: 20px;
font-weight: 500;
}
.bookingAddress{
font-size: 18px;
font-weight: 400;
}
#searchPageContainer{
height: 1200px;
background-color: #F7F8F8;
text-align: center;
}
.searchIdeas{
padding: 10px;
color: #515B64;
}
.searchIdeasFirstItem{
padding-top: 40px;
}
.profileContainer{
border-bottom: 1px solid #E5E9F2;
}
.profilePictureContainer{
text-align: center;
padding: 20px;
display: inline-block;
}
#profilePicture{
height: 100px;
}
#userName{
padding-top: 5px;
}
.profileDetailsContainer{
display: inline-block;
vertical-align: top;
padding: 20px;
width: 55%;
}
#fullUserName{
padding-bottom: 5px;
}
#usersHometown{
padding-bottom: 15px;
}
.tripsFriendsPhotosContainer{
width: 40%;
display: inline-block;
}
.recentTripLogos{
border: 2px solid #ABB5C3;
width: 42%;
margin: 20px 0 0 20px;
display: inline-block;
}
fieldset{
margin: 20px;
border: none;
}
input[type=text]{
width: 80%;
padding: 10px;
margin: 10px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=radio]{
margin: 10px 0;
}
label{
padding-right: 10px;
}
textarea{
width: 80%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
.formTitles{
font-size: 20px;
font-weight: 500;
}
#reviewInstructions{
margin: 20px;
}
#submitButton{
border-radius: 10px;
padding: 10px;
background-color: #48525E;
color: white;
}
footer{
width: 100%;
text-align: center;
border: 2px solid #ABB5C3;
background-color: white;
clear: both;
}
.footerLinks{
display: inline-block;
padding: 20px;
text-decoration: none;
color: black;
}
.footerIcons{
height: 30px;
}
.discoverContainer, .discoverDescription, .discoverDirections, .discoverTitle, .discoverDirectionsTitle, .discoverReviewHeading,
.discoverReview, .discoverReviewTitle, .discoverContentPhotos, .bookingQrCodesContainer, .profileContainer, .container{
width: 90%;
margin: 0 auto;
}
.discoverContainer, .bookingQrCodesContainer, .profileContainer{
text-align: center;
margin-bottom: 20px;
}
.discoverPhotos{
width: 40%;
}
.recentTripsContainer a img{
width: 25%;
}
h1{
font-size: 20px;
padding: 10px 0;
}
h2{
font-size: 16px;
}
@media screen
and (max-width: 600px) {
.profileContainer, .container{
text-align: left;
width: 100%;
}
body{
margin-bottom: 70px;
}
.hotLinks{
border: 2px solid #ABB5C3;
width: 43%;
margin: 20px 10px;
display: inline-block;
}
.footerLinks{
display: inline;
padding: 0;
}
.footerIconsContainer{
display: inline-block;
text-align: center;
width: 24%;
}
.footerIcons{
height: 20px;
padding: 10px 0 0;
}
.footerIconText{
font-size: 16px;
padding: 5px;
}
footer{
width: 100%;
text-align: center;
border: 2px solid #ABB5C3;
background-color: white;
clear: both;
position: fixed;
bottom: 0;
}
.discoverContainer{
width: 100%;
text-align: center;
}
.discoverLogo{
padding: 20px 10px;
width: 40%;
float: left;
}
.discoverAddress{
padding: 20px;
font-size: 20px;
font-weight: 500;
}
.discoverDescription, .discoverDirections, .discoverReview{
clear: both;
padding: 0 20px;
}
.discoverDirectionsTitle, .discoverTitle, .memberSinceTitle, .reviewsTitle{
font-size: 18px;
font-weight: 500;
padding: 20px 20px 0 20px;
}
.discoverReviewTitle{
font-size: 16px;
font-weight: 500;
padding: 10px 20px 0 20px;
}
#map{
width: 90%;
height: 600px;
margin: 20px auto;
background-color: grey;
}
.discoverContentPhotos{
width: 100%;
text-align: center;
}
.discoverTitle{
text-align: left;
}
.discoverPhotos{
width: 46%;
padding-top: 10px;
}
.bookingQrCodesContainer{
text-align: center;
padding-bottom: 30px;
}
.aboutUserTitle{
font-size: 20px;
padding-top: 20px;
}
.aboutUserText, .aboutUserTitle, .usersReview{
padding-left: 20px;
padding-right: 20px;
}
.reviewTitles{
font-size: 16px;
font-weight: 500;
padding: 0 20px;
}
#submitReviewsButton{
margin: 10px 0 0 20px;
border-radius: 10px;
padding: 10px;
background-color: #48525E;
color: white;
}
.reviewForm{
margin-left: 20px;
}
#todaysWeatherTitle{
margin-bottom: 15px;
}
#container-openweathermap-widget-12 > div{
margin: 0 auto 100px;
}
.weather-left-card__wind, .weather-left-card__link, .weather-left-card__links span, .weather-left-card__rising{
font-size: 16px !important;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#000000">
<meta name="description" content="An application to learn about Stoke on Trent's events and places to visit!">
<title>Voyage App</title>
<link rel="stylesheet" href="style.css">
<link rel="manifest" href="manifest.json">
<link rel="icon" type="image/png" href="images/favicons.ico/favicon.ico" />
</head>
<body>
<header>
<h1 class="indexTitle">Discover Stoke-on-Trent</h1>
</header>
<picture id="headerStokeCityOfCulture">
<source class="full-width" media="(min-width: 600px)" srcset="images/cityOfCulture-large.jpg">
<source class="full-width" media="(min-width: 420px)" srcset="images/cityOfCulture-medium.jpg">
<img src="images/cityOfCulture-small.jpg" alt="Stoke City of Culture" style="width:100%;">
</picture>
<div id="container">
<a href="intupotteries.html">
<div class="hotLinks">
<img class="hotLinksLogos" src="images/intuPotteries.jpg" alt="intu Potteries Shopping Centre Logo">
<h4 class="hotLinksTitle">intu Potteries</h4>
</div>
</a>
<a href="emmabridgewater.html">
<div class="hotLinks">
<img class="hotLinksLogos" src="images/emmaBridgewater.jpg" alt="Emma Bridgewater Pottery Logo">
<h4 class="hotLinksTitle">Emma Bridgewater</h4>
</div>
</a>
<a href="altontowers.html">
<div class="hotLinks">
<img class="hotLinksLogos" src="images/altonTowers.jpg" alt="Alton Towers Theme Park Logo">
<h4 class="hotLinksTitle">Alton Towers</h4>
</div>
</a>
<a href="trenthamEstate.html">
<div class="hotLinks">
<img class="hotLinksLogos" src="images/trenthamEstate.jpg" alt="Trentham Estate Logo">
<h4 class="hotLinksTitle">Trentham Estate</h4>
</div>
</a>
<a href="bet365.html">
<div class="hotLinks">
<img class="hotLinksLogos" src="images/bet365.jpg" alt="Bet365 Stadium Logo - The home of Stoke City Football Club">
<h4 class="hotLinksTitle">Bet365 Stadium</h4>
</div>
</a>
<a href="freeportTalke.html">
<div class="hotLinks">
<img class="hotLinksLogos" src="images/freeportTalke.jpg" alt="Freeport Talke Shopping Centre Logo">
<h4 class="hotLinksTitle">Freeport Talke</h4>
</div>
</a>
<h4 id="todaysWeatherTitle">Todays Weather</h4>
<div id="weatherContainer"></div>
</div>
<footer>
<a class="footerLinks" href="index.html">
<div id="discover" class="footerIconsContainer">
<img class="footerIcons" src="images/binoculars.jpg" alt="Binoculars icon">
<p class="footerIconText">Discover</p>
</div>
</a>
<a class="footerLinks" href="bookings.html">
<div id="bookings" class="footerIconsContainer">
<img class="footerIcons" src="images/ticket.jpg" alt="Binoculars icon">
<p class="footerIconText">Bookings</p>
</div>
</a>
<a class="footerLinks" href="search.html">
<div id="search" class="footerIconsContainer">
<img class="footerIcons" src="images/search.jpg" alt="Binoculars icon">
<p class="footerIconText">Search</p>
</div>
</a>
<a class="footerLinks" href="account.html">
<div id="account" class="footerIconsContainer">
<img class="footerIcons" src="images/person.jpg" alt="Binoculars icon">
<p class="footerIconText">Account</p>
</div>
</a>
</footer>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('serviceworker.js').then(function(registration) {
console.log('Service worker registered successfully', registration);
}).catch(function(err) {
console.log('Service worker registration failed: ', err);
});
};
</script>
<script src="https://www.gstatic.com/firebasejs/4.10.0/firebase.js"></script>
<script src="serviceworker.js"></script>
<script src="scripts.js"></script>
</body>
</html></code></pre>
</div>
</div>
</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-js lang-js prettyprint-override"><code>var cache_name = 'gih-cache';
var cached_urls = [
'offline.html',
'fourohfour.html',
'account.html',
'altontowers.html',
'bet365.html',
'booking-altonTowers.html',
'booking-manchesterAirport.html',
'booking-northStaffsHotel.html',
'bookings.html',
'emmabridgewater.html',
'freeportTalke.html',
'index.html',
'intupotteries.html',
'search.html',
'trenthamEstate.html',
'style.css'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cache_name)
.then(function(cache) {
return cache.addAll(cached_urls);
})
);
});
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheName.startsWith('pages-cache-') && staticCacheName !== cacheName) {
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', function(event) {
console.log('Fetch event for ', event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
if (response) {
console.log('Found ', event.request.url, ' in cache');
return response;
}
console.log('Network request for ', event.request.url);
return fetch(event.request).then(function(response) {
if (response.status === 404) {
return caches.match('fourohfour.html');
}
return caches.open(cached_urls).then(function(cache) {
cache.put(event.request.url, response.clone());
return response;
});
});
}).catch(function(error) {
console.log('Error, ', error);
return caches.match('offline.html');
})
);
});</code></pre>
</div>
</div>
</p> | 49,849,504 | 6 | 1 | null | 2018-04-15 17:25:06.837 UTC | 2 | 2020-12-29 20:27:45.7 UTC | 2018-04-15 18:08:29.48 UTC | null | 7,117,003 | null | 9,649,606 | null | 1 | 26 | javascript|html|css|progressive-web-apps|typeerror | 46,205 | <p>Remove this line:</p>
<pre><code><script src="serviceworker.js"></script>
</code></pre>
<p>You're not supposed to include your SW as a script in the page. You're only supposed to interact with it by calling the <code>navigator.serviceWorker.register()</code> as you do in your script above.</p>
<p>Lighthouse is not reporting it but I'm making sure: you're serving the website overt HTTPS right?</p> |
21,108,251 | How to update partition metadata in Hive , when partition data is manualy deleted from HDFS | <p>What is the way to automatically update the metadata of Hive partitioned tables?</p>
<p>If new partition data's were added to HDFS (without alter table add partition command execution) . then we can sync up the metadata by executing the command 'msck repair'.</p>
<p>What to be done if a lot of partitioned data were deleted from HDFS (without the execution of alter table drop partition commad execution).</p>
<p>What is the way to syncup the Hive metatdata?</p> | 45,036,445 | 3 | 0 | null | 2014-01-14 07:43:48.723 UTC | 5 | 2019-04-29 10:43:08.517 UTC | null | null | null | null | 1,753,900 | null | 1 | 29 | hive|partitioning | 55,852 | <p><strong>EDIT</strong> : Starting with <strong>Hive 3.0.0</strong> <code>MSCK</code> can now discover new partitions or remove missing partitions (or both) using the following syntax :</p>
<pre><code>MSCK [REPAIR] TABLE table_name [ADD/DROP/SYNC PARTITIONS]
</code></pre>
<p>This was implemented in <a href="https://issues.apache.org/jira/browse/HIVE-17824" rel="noreferrer">HIVE-17824</a></p>
<hr>
<p>As correctly stated by <a href="https://stackoverflow.com/users/3132181/hakkibuyukcengiz">HakkiBuyukcengiz</a>, <code>MSCK REPAIR</code> doesn't remove partitions if the corresponding folder on HDFS was manually deleted, it only adds partitions if new folders are <strong>created</strong>.</p>
<p>Extract from offical <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-RecoverPartitions(MSCKREPAIRTABLE)" rel="noreferrer">documentation</a> :</p>
<blockquote>
<p>In other words, it will add any partitions that exist on HDFS but not in metastore to the metastore.</p>
</blockquote>
<p>This is what I usually do in the presence of <code>external</code> tables if multiple partitions folders are manually deleted on HDFS and I want to quickly refresh the partitions :</p>
<ul>
<li>Drop the table (<code>DROP TABLE table_name</code>)
(dropping an external table does not delete the underlying partition files)</li>
<li>Recreate the table (<code>CREATE EXTERNAL TABLE table_name ...</code>)</li>
<li>Repair it (<code>MSCK REPAIR TABLE table_name</code>)</li>
</ul>
<p>Depending on the number of partitions this can take a long time. The other solution is to use <code>ALTER TABLE DROP PARTITION (...)</code> for each deleted partition folder but this can be tedious if multiple partitions were deleted.</p> |
31,300,156 | How to use indirect reference to select a single cell or range in vba | <p>I need simply a code for selecting a cell, however that cell to select changes. I have a cell in the workbook that will identify what cell it should be. Cell A1 contains the cell # that should be selected. </p>
<p>In this example cell A1 contains the word "P25", so I want the below code to reference A1 for the indirect cell ref to P25, thus select cell P25. </p>
<p>I tried both of these lines separately:</p>
<pre><code>Sub IndirectCellSelect()
Sheet.Range(INDIRECT(A1)).Select
Range(INDIRECT(A1)).Select
End Sub
</code></pre>
<p>I get the error Sub or Function is not defined, when it gets to the word INDIRECT </p> | 31,301,086 | 3 | 0 | null | 2015-07-08 17:55:40.16 UTC | null | 2016-08-19 09:55:43.787 UTC | 2015-07-08 18:03:03.45 UTC | null | 4,539,709 | null | 4,643,531 | null | 1 | 5 | vba|excel|reference|range|cell | 59,586 | <p>A slight alteration to the posted code works: </p>
<pre><code>Range([indirect("a1")]).Select
</code></pre>
<p>but I would advise to try either of these instead:</p>
<pre><code>Sheet.Range(Sheet.Range("A1").Value).Select
Range(Range("A1")).Select
</code></pre>
<p>the first being more explicit and is recommended in production code.</p> |
5,828,697 | How to retain spaces in DropDownList - ASP.net MVC Razor views | <p>I'm binding my model in the following way in the view:</p>
<pre><code><%=Html.DropDownList("SelectedItem",new SelectList(Model.MyItems,"ItemId","ItemName")) %>
</code></pre>
<p>Issue is my item text is a formatted text with spaces in between words, as below.</p>
<pre><code>#123 First $234.00
#123 AnotherItem $234.00
#123 Second $234.00
</code></pre>
<p>I want to retain the spaces in this item text even after they are added to DropDownList. But unfortunately my DropDownList shows them without spaces as below:</p>
<pre><code>#123 First $234.00
#123 AnotherItem $234.00
#123 Second $234.00
</code></pre>
<p>When I view the source of the page those spaces are intact but in display it is not. I've tried to add '<strong><code>&nbsp;</code></strong>' instead of spaces but SelectList (MVC framework class) internal method is using HtmlEncode before adding them as items in the dropdownlist.</p>
<p>Is there any way I can achieve this?</p> | 5,829,364 | 1 | 0 | null | 2011-04-29 06:30:35.303 UTC | 10 | 2018-09-04 20:15:22.08 UTC | null | null | null | null | 305,818 | null | 1 | 27 | c#|asp.net-mvc|asp.net-mvc-3|drop-down-menu|razor | 11,878 | <p>nbsp in html corresponds to "\xA0" as a C# string, so use this instead of spaces, when HTML encoded it will produce nbsp</p> |
35,395,691 | Understanding the difference between the flex and flex-grow properties | <p>What is the difference in effect between setting <code>flex: 1;</code> and setting <code>flex-grow: 1;</code>? When I set the former in my code, the two columns I have display with equal width, while they do not do so when I set the latter.</p>
<p>This is strange, as I assumed that setting <code>flex: 1;</code> only affects the <code>flex-grow</code> property. </p> | 35,395,869 | 1 | 0 | null | 2016-02-14 18:48:59.34 UTC | 8 | 2016-02-14 19:09:24.597 UTC | 2016-02-14 19:09:24.597 UTC | null | 3,597,276 | null | 3,930,460 | null | 1 | 45 | css|flexbox | 16,916 | <p><code>flex</code> is a shorthand property of <code>flex-grow</code>, <code>flex-shrink</code> and <code>flex-basis</code>.</p>
<p>In this case, <code>flex: 1</code> sets</p>
<ul>
<li><code>flex-grow: 1</code></li>
<li><code>flex-shrink: 1</code></li>
<li><code>flex-basis: 0</code> (in old spec drafts it was <code>flex-basis: 0%</code>)</li>
</ul>
<p>If you only use <code>flex-grow: 1</code>, you will have</p>
<ul>
<li><code>flex-grow: 1</code></li>
<li><code>flex-shrink: 1</code></li>
<li><code>flex-basis: auto</code></li>
</ul>
<p>Then, the difference is that the flex base size will be 0 in the first case, so the flex items will have the same size after distributing free space.</p>
<p>In the second case each flex item will start with the size given by its content, and then will grow or shrink according to free space. Most probably the sizes will end up being different.</p> |
35,423,928 | How do I convert a complex number? | <p>I built a calculator for a bio equation, and I think I've narrowed down the source of my problem, which is a natural log I take:</p>
<pre><code>goldman = ((R * T) / F) * cmath.log(float(top_row) / float(bot_row))
print("Membrane potential: " + str(goldman) + "V"
</code></pre>
<p>My problem is that it will only display the output in a complex form:</p>
<pre><code>Membrane potential: (0.005100608207126714+0j)V
</code></pre>
<p>Is there any way of getting this to print as a floating number? Nothing I've tried has worked.</p> | 35,423,945 | 4 | 0 | null | 2016-02-16 04:43:29.47 UTC | 1 | 2022-03-20 14:11:08.287 UTC | 2016-02-16 07:58:30.637 UTC | null | 2,272,172 | null | 5,921,054 | null | 1 | 11 | python | 40,825 | <p>Complex numbers have a real part and an imaginary part:</p>
<pre><code>>>> c = complex(1, 0)
>>> c
(1+0j)
>>> c.real
1.0
</code></pre>
<p>It looks like you just want the real part... so:</p>
<pre><code>print("Membrane potential: " + str(goldman.real) + "V"
</code></pre> |
25,694,423 | Pass an object between @ViewScoped beans without using GET params | <p>I have a <code>browse.xhtml</code> where I browse a list of <code>cars</code> and I want to view the details of the car in <code>details.xhtml</code> when a "View more" button is pressed. Their backing beans are <code>@ViewScoped</code> and are called <code>BrowseBean</code> and <code>DetailsBean</code>, respectively. </p>
<p>Now, I wouldn't like the user/client to see the car ID in the URL, so I would like to avoid using GET params, as presented <a href="https://stackoverflow.com/questions/8459903/creating-master-detail-pages-for-entities-how-to-link-them-and-which-bean-scope">here</a> and <a href="https://stackoverflow.com/questions/20880027/passing-parameters-to-a-view-scoped-bean-in-jsf">here</a>.</p>
<p>Is there any way to achieve this? I'm using Mojarra 2.2.8 with PrimeFaces 5 and OmniFaces 1.8.1.</p> | 25,697,762 | 1 | 0 | null | 2014-09-05 21:46:24.907 UTC | 18 | 2015-10-19 11:32:25.47 UTC | 2017-05-23 10:31:12.803 UTC | null | -1 | null | 774,513 | null | 1 | 17 | jsf|parameter-passing|jsf-2.2|omnifaces|view-scope | 19,731 | <p>Depends on whether you're sending a redirect or merely navigating.</p>
<p>If you're sending a redirect, then put it in the flash scope:</p>
<pre><code>Faces.setFlashAttribute("car", car);
</code></pre>
<p>This is available in the <code>@PostConstruct</code> of the next bean as:</p>
<pre><code>Car car = Faces.getFlashAttribute("car");
</code></pre>
<p>Or, if you're merely navigating, then put it in the request scope:</p>
<pre><code>Faces.setRequestAttribute("car", car);
</code></pre>
<p>This is available in the <code>@PostConstruct</code> of the next bean as:</p>
<pre><code>Car car = Faces.getRequestAttribute("car");
</code></pre>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/q/14231044">Injecting one view scoped bean in another view scoped bean causes it to be recreated</a></li>
<li><a href="https://stackoverflow.com/q/25467864">How to pass objects from one page to another page in JSF without writing a converter</a></li>
</ul>
<p>Note that I assume that you're very well aware about the design choice of having two entirely separate views which cannot exist (be idempotent) without the other view, instead of having e.g. a single view with conditionally rendered content. And that you already know how exactly the view should behave when it's actually being requested idempotently (i.e. via a bookmark, shared link, by a searchbot, etc). If not, then I strongly recommend to carefully read the answer on this question: <a href="https://stackoverflow.com/q/15521451">How to navigate in JSF? How to make URL reflect current page (and not previous one)</a>.</p>
<hr>
<p><strong>Update:</strong> in case you're not using OmniFaces, use respectively the following:</p>
<pre><code>FacesContext.getCurrentInstance().getExternalContext().getFlash().put("car", car);
</code></pre>
<pre class="lang-java prettyprint-override"><code>Car car = (Car) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("car");
</code></pre>
<pre class="lang-java prettyprint-override"><code>FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("car", car);
</code></pre>
<pre class="lang-java prettyprint-override"><code>Car car = (Car) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("car");
</code></pre> |
43,322,536 | "Could not load credentials from any providers" while using dynamodb locally in Node | <p>im setting up a dynamodb locally to test with my Node app. To set it up i just plain out copied the code from <a href="http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.NodeJs.01.html" rel="noreferrer">here</a> and adjusted it for my needs. <br>This is the code:<br></p>
<pre><code>var AWS = require("aws-sdk");
var config = ({
"apiVersion": "2012-08-10",
"accessKeyId": "abcde",
"secretAccessKey": "abcde",
"region": "us-west-2",
"endpoint": "http://localhost:8001",
});
var dynamodb = new AWS.DynamoDB(config);
var params = {
TableName : "Movies",
KeySchema: [
{ AttributeName: "year", KeyType: "HASH"}, //Partition key
{ AttributeName: "title", KeyType: "RANGE" } //Sort key
],
AttributeDefinitions: [
{ AttributeName: "year", AttributeType: "N" },
{ AttributeName: "title", AttributeType: "S" }
],
ProvisionedThroughput: {
ReadCapacityUnits: 10,
WriteCapacityUnits: 10
}
};
dynamodb.createTable(params, function(err, data) {
if (err) {
console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2));
}
});
</code></pre>
<p>This throws an error though and i have no idea why:</p>
<pre><code>Unable to create table. Error JSON: {
"message": "Missing credentials in config",
"code": "CredentialsError",
"time": "2017-04-10T11:45:26.748Z",
"retryable": true,
"originalError": {
"message": "Could not load credentials from any providers",
"code": "CredentialsError",
"time": "2017-04-10T11:45:26.747Z",
"retryable": true,
"originalError": {
"message": "Connection timed out after 1000ms",
"code": "TimeoutError",
"time": "2017-04-10T11:45:26.747Z",
"retryable": true
}
}
}
</code></pre>
<p>Would be thankful for any help! </p> | 43,324,764 | 8 | 0 | null | 2017-04-10 11:57:14.03 UTC | 6 | 2021-11-25 14:42:12.663 UTC | null | null | null | null | 7,085,194 | null | 1 | 20 | javascript|node.js|amazon-web-services|amazon-dynamodb|aws-sdk | 48,503 | <p>Apparently i figured out the problem. Using a json file to set the credentials still led to the error. Using only the config object without the flag -inMemory caused an error too. The combination of hard coding the credentials in the script and using the -inMemory flag while starting the dynamodb locally seemed to solve this. I really don't understand why though.</p> |
2,538,103 | How to call a function from a shared library? | <p>What is the easiest and safest way to call a function from a shared library / dll? I am mostly interested in doing this on linux, but it would be better if there were a platform-independent way.</p>
<p>Could someone provide example code to show how to make the following work, where the user has compiled his own version of <code>foo</code> into a shared library?</p>
<pre><code>// function prototype, implementation loaded at runtime:
std::string foo(const std::string);
int main(int argc, char** argv) {
LoadLibrary(argv[1]); // loads library implementing foo
std::cout << "Result: " << foo("test");
return 0;
}
</code></pre>
<p>BTW, I know how to compile the shared lib (<code>foo.so</code>), I just need to know an easy way to load it at runtime.</p> | 2,538,216 | 3 | 0 | null | 2010-03-29 13:15:16.58 UTC | 13 | 2011-09-27 13:52:24.923 UTC | null | null | null | null | 60,628 | null | 1 | 16 | c++|linux|dll|shared-libraries|dynamic-linking | 30,461 | <p><strong>NOTE:</strong> You are passing C++ objects (in this case STL strings) around library calls. There is <strong>no standard C++ <a href="http://en.wikipedia.org/wiki/Application_binary_interface" rel="noreferrer">ABI</a> at this level</strong>, so either try to avoid passing C++ objects around, or ensure that both your library and your program have been built with the same compiler (ideally the same compiler on the same machine, to avoid any subtle configuration-related surprises.)</p>
<p>Do not forget to <strong>declare your exported methods <a href="http://www.faqs.org/docs/Linux-mini/C++-dlopen.html#externC" rel="noreferrer"><code>extern "C"</code></a></strong> inside your library code.</p>
<p>The above having been said, here is <strong>some code implementing what you said you want to achieve</strong>:</p>
<pre><code>typedef std::string (*foo_t)(const std::string);
foo_t foo = NULL;
...
# ifdef _WIN32
HMODULE hDLL = ::LoadLibrary(szMyLib);
if (!hDll) { /*error*/ }
foo = (foo_t)::GetProcAddress(hDLL, "foo");
# else
void *pLib = ::dlopen(szMyLib, RTLD_LAZY);
if (!pLib) { /*error*/ }
foo = (foo_t)::dlsym(pLib, "foo");
# endif
if (!foo) { /*error*/ }
...
foo("bar");
...
# ifdef _WIN32
::FreeLibrary(hDLL);
# else
::dlclose(pLib);
# endif
</code></pre>
<p>You can <strong>abstract this further</strong>:</p>
<pre><code>#ifdef _WIN32
#include <windows.h>
typedef HANDLE my_lib_t;
#else
#include <dlfcn.h>
typedef void* my_lib_t;
#endif
my_lib_t MyLoadLib(const char* szMyLib) {
# ifdef _WIN32
return ::LoadLibraryA(szMyLib);
# else //_WIN32
return ::dlopen(szMyLib, RTLD_LAZY);
# endif //_WIN32
}
void MyUnloadLib(my_lib_t hMyLib) {
# ifdef _WIN32
return ::FreeLibrary(hMyLib);
# else //_WIN32
return ::dlclose(hMyLib);
# endif //_WIN32
}
void* MyLoadProc(my_lib_t hMyLib, const char* szMyProc) {
# ifdef _WIN32
return ::GetProcAddress(hMyLib, szMyProc);
# else //_WIN32
return ::dlsym(hMyLib, szMyProc);
# endif //_WIN32
}
typedef std::string (*foo_t)(const std::string);
typedef int (*bar_t)(int);
my_lib_t hMyLib = NULL;
foo_t foo = NULL;
bar_t bar = NULL;
...
if (!(hMyLib = ::MyLoadLib(szMyLib)) { /*error*/ }
if (!(foo = (foo_t)::MyLoadProc(hMyLib, "foo")) { /*error*/ }
if (!(bar = (bar_t)::MyLoadProc(hMyLib, "bar")) { /*error*/ }
...
foo("bar");
bar(7);
...
::MyUnloadLib(hMyLib);
</code></pre> |
2,357,028 | Convert Arraylist into string in vb.net | <p>How do I convert an arraylist into a string of comma delimated values in vb.net</p>
<p>I have an arraylist with ID values</p>
<pre><code>arr(0)=1
arr(1)=2
arr(2)=3
</code></pre>
<p>I want to convert it into a string </p>
<pre><code>Dim str as string=""
str="1,2,3"
</code></pre> | 2,357,032 | 4 | 0 | null | 2010-03-01 15:53:06.963 UTC | null | 2018-07-05 06:06:11.34 UTC | 2010-03-01 16:02:25.273 UTC | null | 20,481 | null | 163,189 | null | 1 | 3 | .net|vb.net | 40,848 | <pre><code>str = string.Join(",", arr.ToArray());
</code></pre>
<p>If you need to convert the List to string[] before the string.Join you can do</p>
<pre><code>Array.ConvertAll<int, string>(str.ToArray(), new Converter<int, string>(Convert.ToString));
</code></pre>
<p>So...</p>
<pre><code>str = string.Join(",", Array.ConvertAll<int, string>(str.ToArray(), new Converter<int, string>(Convert.ToString)));
</code></pre> |
2,906,344 | Servlet.init() and Filter.init() call sequence | <p>In which order are Servlet.init() and Filter.init() methods called in java web application? Which one is called first? Are all Servlet.init() methods called before than any Filter.doFilter method?</p> | 2,906,460 | 4 | 0 | null | 2010-05-25 16:03:32.377 UTC | 10 | 2021-01-19 16:46:14.11 UTC | 2010-05-25 16:10:46.9 UTC | null | 55,036 | null | 55,036 | null | 1 | 31 | java|servlets|jakarta-ee|servlet-filters | 18,158 | <p>The filters are always initialized during webapp's startup in the order as they are defined in the <code>web.xml</code>. </p>
<p>The servlets are by default initialized during the first HTTP request on their url-pattern only. But you can configure them as well to initialize during webapp's startup using the <code><load-on-startup></code> entries wherein you can specify their priority. They will then be loaded in the priority order.<br>
E.g.</p>
<pre><code><servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>mypackage.MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</code></pre>
<p>If there are more servlets with the same priority order, then the loading order for those servlets is unspecified and may be arbitrary. Servlets are however in any way initialized <em>after</em> the initialization of filters, but <em>before</em> invocation of the filters.</p> |
48,906,484 | How to unit test private methods in Typescript | <p>When I tried to do unit testing for <strong>private methods in a Class</strong> getting error as <em>private methods are only accessible inside the class</em>. Here I added sample snippet for my class and mocha test. Kindly provide me solution to implement unit test for private methods.</p>
<p><strong>Class Name: Notification.ts</strong> </p>
<pre><code>class Notification {
constructor() {}
public validateTempalte() {
return true;
}
private replacePlaceholder() {
return true;
}
}
</code></pre>
<p><strong>Unit Test:</strong></p>
<pre><code>import {Notification} from 'Notification';
import * as chai from "chai";
describe("Notification", function(){
describe('#validateTempalte - Validate template', function() {
it('it should return success', function() {
const result = new Notification()
chai.expect(result.validateTempalte()).to.be.equal(true);
});
});
describe('#replacePlaceholder - Replace Placeholder', function() {
it('it should return success', function() {
const result = new Notification()
// As expected getting error "Private is only accessible within class"
chai.expect(result.replacePlaceholder()).to.be.equal(true);
});
});
});
</code></pre>
<p>As a workaround, currently, I am changing access specifier of function <strong>replacePlaceholder</strong> to <strong>public</strong>. But I don't think its a valid approach. </p> | 48,908,067 | 8 | 1 | null | 2018-02-21 12:54:52 UTC | 6 | 2022-08-16 19:31:45.603 UTC | 2018-08-09 11:01:49.447 UTC | null | 6,086,598 | null | 3,087,716 | null | 1 | 45 | unit-testing|typescript|mocha.js | 49,995 | <p><em>Technically</em>, in current versions of TypeScript private methods are only compile-time checked to be private - so you can call them.</p>
<pre><code>class Example {
public publicMethod() {
return 'public';
}
private privateMethod() {
return 'private';
}
}
const example = new Example();
console.log(example.publicMethod()); // 'public'
console.log(example.privateMethod()); // 'private'
</code></pre>
<p>I mention this <em>only</em> because you asked how to do it, and that is how you <em>could</em> do it.</p>
<h1>Correct Answer</h1>
<p><strong>However</strong>, that private method must be called by some other method... otherwise it isn't called at all. If you test the behaviour of that other method, you will cover the private method in the context it is used.</p>
<p>If you specifically test private methods, your tests will become tightly coupled to the implementation details (i.e. a good test wouldn't need to be changed if you refactored the implementation).</p>
<h1>Disclaimer</h1>
<p>If you still test it at the private method level, the compiler <em>might</em> in the future change and make the test fail (i.e. if the compiler made the method "properly" private, or if a future version of ECMAScript added visibility keywords, etc).</p> |
1,207,073 | how to print database diagram sql | <p>I would like to print a SQL Server database diagram. I'm using SQL Server Management Studio, I right clicked on the diagram, and selected "View Page Breaks". </p>
<p>I wanted to have the diagram in A3 Format but when I tried to print it had 4 pages.
Is there a way to print the whole diagram in just one page?</p> | 1,207,099 | 2 | 0 | null | 2009-07-30 14:43:44.48 UTC | 9 | 2016-05-05 10:29:07.46 UTC | 2012-07-03 00:47:52.08 UTC | null | 6,268 | null | 68,348 | null | 1 | 43 | printing|ssms | 39,038 | <p>Set the page zoom level on the print properties page (in addition to setting the page size to A3). </p>
<p>Switching back to the diagram with 'View Page Breaks' selected will show you when you have all the tables positioned properly onto one page.</p> |
2,515,762 | How do I turn off "Automatically Switch to Debug Perspective" mode in eclipse? | <p>Is there a way to turn off this mode? I must have clicked it by accident, and now it's getting really annoying. </p>
<p>I've looked in the preferences and perspectives pane, but can't see anything. Does anyone know where this option is configured?</p> | 2,515,818 | 5 | 1 | null | 2010-03-25 13:15:26.447 UTC | 15 | 2020-12-08 02:19:21.36 UTC | 2020-04-21 11:28:45.64 UTC | null | 1,040,022 | null | 186,868 | null | 1 | 124 | eclipse|debugging|perspective | 67,667 | <p>Preferences -> Run/Debug -> Perspectives -> Open the associated perspective when application suspends</p> |
3,023,649 | Hour from DateTime? in 24 hours format | <p>So i have this DateTime? and what i want to do is to obtain the hour but show it in 24 hours format.<br>
For example:<br>
If the hour is 2:20:23 p.m. i want to convert it to 14:20 and that's it.</p>
<p>I'm working with Visual C#.
Any ideas please, thank you. </p>
<p>I have something like this</p>
<pre><code>public static string FormatearHoraA24(DateTime? fechaHora)
{
if (!fechaHora.HasValue)
return "";
string retornar = "";
//here goes what i need
}
</code></pre> | 3,023,696 | 5 | 1 | null | 2010-06-11 14:34:43.84 UTC | 16 | 2021-03-17 09:31:39.41 UTC | 2019-12-14 10:41:35.703 UTC | null | 665,783 | null | 280,501 | null | 1 | 187 | c#|datetime | 339,114 | <p>You can get the desired result with the code below. Two 'H' in <code>HH</code> is for 24-hour format.</p>
<pre><code>return fechaHora.Value.ToString("HH:mm");
</code></pre> |
2,641,667 | Deleting a file after user download it | <p>I am using this for sending file to user</p>
<pre><code>header('Content-type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
</code></pre>
<p>I want to delete this file after user downloads it, how can i do this?</p>
<p>EDIT: My scenario is like that, when user hits download button, my script will create a temporary zip file and user download it then that temp zip file will be deleted.</p>
<p>EDIT2: OK best way seems running a cron job that will be cleaning temp files once an hour.</p>
<p>EDIT3: I tested my script with <code>unlink</code>, it works unless user cancel the download. If user cancel the download, zip file stays on the server. So that is enough for now. :)</p>
<p>EDIT4: WOW! <code>connection_aborted()</code> made the trick !</p>
<pre><code>ignore_user_abort(true);
if (connection_aborted()) {
unlink($f);
}
</code></pre>
<p>This one will delete the file even if user cancel the download. </p> | 2,641,676 | 7 | 1 | null | 2010-04-14 23:08:18.643 UTC | 23 | 2021-11-23 13:16:53.05 UTC | 2021-11-23 13:16:53.05 UTC | null | 14,807,111 | null | 192,525 | null | 1 | 65 | php | 61,925 | <pre><code>unlink($filename);
</code></pre>
<p>This will delete the file.</p>
<p>It needs to be combined with <a href="http://php.net/function.ignore_user_abort" rel="noreferrer"><code>ignore_user_abort()</code><sup><em>Docs</em></sup></a> so that the <code>unlink</code> is still executed even the user canceled the download.</p>
<pre><code>ignore_user_abort(true);
...
unlink($f);
</code></pre> |
2,681,878 | Associate File Extension with Application | <p>I've written a program that edits a specific filetype , and I want to give the user the option to set my application as the default editor for this filetype (since I don't want an installer) on startup.</p>
<p>I've tried to write a re-useable method that associates a file for me (preferably on any OS, although I'm running Vista) by adding a key to HKEY_CLASSES_ROOT, and am using it with my application, but it doesn't seem to work.</p>
<pre><code>public static void SetAssociation(string Extension, string KeyName, string OpenWith, string FileDescription)
{
RegistryKey BaseKey;
RegistryKey OpenMethod;
RegistryKey Shell;
RegistryKey CurrentUser;
BaseKey = Registry.ClassesRoot.CreateSubKey(Extension);
BaseKey.SetValue("", KeyName);
OpenMethod = Registry.ClassesRoot.CreateSubKey(KeyName);
OpenMethod.SetValue("", FileDescription);
OpenMethod.CreateSubKey("DefaultIcon").SetValue("", "\"" + OpenWith + "\",0");
Shell = OpenMethod.CreateSubKey("Shell");
Shell.CreateSubKey("edit").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
Shell.CreateSubKey("open").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
BaseKey.Close();
OpenMethod.Close();
Shell.Close();
CurrentUser = Registry.CurrentUser.CreateSubKey(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\" + Extension);
CurrentUser = CurrentUser.OpenSubKey("UserChoice", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);
CurrentUser.SetValue("Progid", KeyName, RegistryValueKind.String);
CurrentUser.Close();
}
</code></pre>
<p>Any idea why it doesn't work? An example use might be </p>
<pre><code>SetAssociation(".ucs", "UCS_Editor_File", Application.ExecutablePath, "UCS File");
</code></pre>
<p>The part of the method that uses "CurrentUser" seems to work if I do the same using regedit, but using my application it doesn't.</p> | 2,697,804 | 9 | 5 | null | 2010-04-21 09:59:39.583 UTC | 28 | 2022-01-23 13:36:15.363 UTC | 2017-04-06 11:15:33.777 UTC | null | 254,109 | null | 2,397,839 | null | 1 | 63 | c#|registry|file-association | 51,961 | <p>The answer was a lot simpler than I expected. Windows Explorer has its own override for the open with application, and I was trying to modify it in the last lines of code. If you just delete the Explorer override, then the file association will work.</p>
<p>I also told explorer that I had changed a file association by calling the unmanaged function <code>SHChangeNotify()</code> using P/Invoke</p>
<pre><code>public static void SetAssociation(string Extension, string KeyName, string OpenWith, string FileDescription)
{
// The stuff that was above here is basically the same
// Delete the key instead of trying to change it
var CurrentUser = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\" + Extension, true);
CurrentUser.DeleteSubKey("UserChoice", false);
CurrentUser.Close();
// Tell explorer the file association has been changed
SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
}
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
</code></pre> |
45,532,965 | Django REST framework serializer without a model | <p>I'm working on a couple endpoints which aggregate data. One of the endpoints will for example return an array of objects, each object corresponding with a day, and it'll have the number of comments, likes and photos that specific user posted. This object has a predefined/set schema, but we do not store it in the database, so it doesn't have a model.</p>
<p>Is there a way I can still use Django serializers for these objects without having a model?</p> | 45,534,031 | 1 | 1 | null | 2017-08-06 14:24:07.233 UTC | 23 | 2017-08-06 16:17:02.63 UTC | null | null | null | null | 811,183 | null | 1 | 93 | django|django-rest-framework|django-serializer | 54,314 | <p>You can create a serializer that inherits from <em>serializers.Serializer</em> and pass your data as the first parameter like:</p>
<p>serializers.py</p>
<pre><code>from rest_framework import serializers
class YourSerializer(serializers.Serializer):
"""Your data serializer, define your fields here."""
comments = serializers.IntegerField()
likes = serializers.IntegerField()
</code></pre>
<p>views.py</p>
<pre><code>from rest_framework import views
from rest_framework.response import Response
from .serializers import YourSerializer
class YourView(views.APIView):
def get(self, request):
yourdata= [{"likes": 10, "comments": 0}, {"likes": 4, "comments": 23}]
results = YourSerializer(yourdata, many=True).data
return Response(results)
</code></pre> |
10,405,868 | What does =~ mean in Perl? | <blockquote>
<p><strong>Possible Duplicate:</strong> <br/>
<a href="https://stackoverflow.com/questions/10019049/what-does-this-do-in-perl">What does =~ do in Perl?</a></p>
</blockquote>
<p>In a Perl program I am examining (namly <a href="https://github.com/captn3m0/Scripts/blob/master/plutil.pl" rel="nofollow noreferrer">plutil.pl</a>), I see a lot of <code>=~</code> on the XML parser portion. For example, here is <code>UnfixXMLString</code> (lines <code>159</code> to <code>167</code> on 1.7):</p>
<pre class="lang-perl prettyprint-override"><code>sub UnfixXMLString {
my ($s) = @_;
$s =~ s/&lt;/</g;
$s =~ s/&gt;/>/g;
$s =~ s/&amp;/&/g;
return $s;
}
</code></pre>
<p>From what I can tell, it's taking a string, modifying it with the <code>=~</code> operator, then returning that modified string, but what <em>exactly</em> is it doing?</p> | 10,405,894 | 2 | 0 | null | 2012-05-01 23:43:54.407 UTC | 1 | 2022-08-29 22:41:53.803 UTC | 2022-08-29 22:41:53.803 UTC | null | 1,350,209 | null | 1,350,209 | null | 1 | 15 | perl|operators | 58,030 | <p><code>=~</code> is the Perl <a href="http://perldoc.perl.org/perlop.html#Binding-Operators" rel="noreferrer">binding operator</a>. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern:</p>
<pre><code>if ($string =~ m/pattern/) {
</code></pre>
<p>Or to extract components from a string:</p>
<pre><code>my ($first, $rest) = $string =~ m{^(\w+):(.*)$};
</code></pre>
<p>Or to apply a substitution:</p>
<pre><code>$string =~ s/foo/bar/;
</code></pre> |
10,545,957 | creating pandas data frame from multiple files | <p>I am trying to create a pandas <code>DataFrame</code> and it works fine for a single file. If I need to build it for multiple files which have the same data structure. So instead of single file name I have a list of file names from which I would like to create the <code>DataFrame</code>.</p>
<p>Not sure what's the way to append to current <code>DataFrame</code> in pandas or is there a way for pandas to suck a list of files into a <code>DataFrame</code>.</p> | 14,490,980 | 6 | 0 | null | 2012-05-11 05:36:56.747 UTC | 13 | 2022-02-04 19:37:27.87 UTC | 2017-01-04 22:58:34.987 UTC | null | 2,336,654 | null | 369,541 | null | 1 | 19 | python|pandas | 25,920 | <p>The pandas <code>concat</code> command is your friend here. Lets say you have all you files in a directory, targetdir. You can:</p>
<ol>
<li>make a list of the files </li>
<li>load them as pandas dataframes </li>
<li>and concatenate them together</li>
</ol>
<p>`</p>
<pre><code>import os
import pandas as pd
#list the files
filelist = os.listdir(targetdir)
#read them into pandas
df_list = [pd.read_table(file) for file in filelist]
#concatenate them together
big_df = pd.concat(df_list)
</code></pre> |
10,466,749 | Bash: Colored Output with a Variable | <p>I have the following function:</p>
<pre><code>function pause #for prompted pause until ENTER
{
prompt="$3"
echo -e -n "\E[36m$3" #color output text cyan
echo -e -n '\E[0m' #ends colored output
read -p "$*" #read keys from user until ENTER.
clear
}
pause "Press enter to continue..."
</code></pre>
<p>However, my function refuses to apply the cyan color to the string I pass into the function.</p>
<p>A similar question was asked <a href="https://stackoverflow.com/questions/2829276/bash-color-variable-output">here</a>, but it seems that I'm doing everything correctly...</p> | 10,466,944 | 4 | 0 | null | 2012-05-05 23:16:03.61 UTC | 12 | 2019-07-21 19:50:42.573 UTC | 2017-05-23 12:26:27.26 UTC | null | -1 | null | 1,186,723 | null | 1 | 21 | bash|variables | 27,800 | <p>I've slightly changed your code:</p>
<pre><code>#!/bin/bash
function pause() {
prompt="$1"
echo -e -n "\033[1;36m$prompt"
echo -e -n '\033[0m'
read
clear
}
pause "Press enter to continue..."
</code></pre>
<p>What I've changed:</p>
<ol>
<li>You were initializing prompt to $3, when the correct argument was $1</li>
<li>The ANSI sequence was incorrect. See: <a href="http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html" rel="noreferrer">http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html</a></li>
<li>The call to read was incorrect, you were passing several arguments do to the use of $*. In this particular case you are discarding the input, so it's not even necessary to save the result of read. I suggest you to read the manpage: <a href="http://linux.die.net/man/1/bash" rel="noreferrer">http://linux.die.net/man/1/bash</a> to see how to exactly use read. If you pass in several arguments, those arguments will be mapped to variable names that will contain the different fields inputted in the line.</li>
</ol> |
5,781,449 | Is it possible to emit a Qt signal from a const method? | <p>In particular, I am implementing a QWizardPage ("MyWizardPage") for a QWizard, and I want to emit a signal ("sigLog") from my override of the QWizardPage::nextId virtual method.</p>
<p>Like so:</p>
<pre><code>class MyWizardPage
: public QWizardPage
{
Q_OBJECT
public:
MyWizardPage();
virtual int nextId() const;
Q_SIGNALS:
void sigLog(QString text);
};
int MyWizardPage::nextId() const
{
Q_EMIT sigLog("Something interesting happened");
}
</code></pre>
<p>But when I try this, I get the following compile error on the Q_EMIT line:</p>
<blockquote>
<p>Error 1 error C2662: 'MyWizardPage::sigLog' : cannot convert 'this' pointer from 'const MyWizardPage' to 'MyWizardPage &'</p>
</blockquote> | 5,790,342 | 2 | 0 | null | 2011-04-25 18:04:43.49 UTC | 5 | 2019-04-15 08:03:25.353 UTC | 2019-04-15 08:03:25.353 UTC | null | 1,485,885 | null | 613,482 | null | 1 | 35 | qt|signals-slots | 9,875 | <p>It is possible to emit a signal from a const method by adding "const" to the signal declaration, like so:</p>
<pre><code>void sigLog(QString text) const;
</code></pre>
<p>I tested this and it <strong>does</strong> compile and run, even though you don't actually implement the signal as a normal method yourself (i.e. Qt is okay with it).</p> |
33,496,322 | How does std::end know the end of an array? | <p><code>std::begin</code> and <code>std::end</code> know the beginning and end of a <code>container</code> or an <code>array</code>.</p>
<p>It so easy to know the <code>end</code> and <code>begin</code> of a <code>vector</code> for example because it is a class that gives this information. But, how does it know the end of an <code>array</code> like the following?</p>
<pre><code>int simple_array[5]{1, 2, 3, 4, 5};
auto beg=std::begin(simple_array);
auto en=std::end(simple_array);
</code></pre>
<p><code>std::begin</code> is not that hard to know where the array start. But how does it know where it ends? Will the constant integer <code>5</code> be stored somewhere?</p>
<p>I would appreciate if I got an answer with some low-level information.</p> | 33,496,500 | 3 | 0 | null | 2015-11-03 10:07:53.363 UTC | 13 | 2015-11-05 02:51:51.937 UTC | 2015-11-04 05:34:24.987 UTC | null | 63,550 | null | 4,523,099 | null | 1 | 37 | c++|arrays|c++11 | 9,139 | <blockquote>
<p>is the constant integer 5 will be stored some where?</p>
</blockquote>
<p>Yes, it's part of the type of the array. But no, it's not stored anywhere explicitly. When you have</p>
<pre><code>int i[5] = { };
</code></pre>
<p>the type of <code>i</code> is <code>int[5]</code>. Shafik's answer talks about how this length is used to implement <code>end</code>.</p>
<p>If you've C++11, using <code>constexpr</code> would be the simple way to go</p>
<pre><code>template <typename T, size_t N>
inline constexpr size_t
arrLen(const T (&arr) [N]) {
return N;
}
</code></pre>
<p>If you've a pre-C++11 compiler where <code>constexpr</code> isn't available, the above function may not be evaluated at compile-time. So in such situations, you may use this:</p>
<pre><code>template <typename T, size_t N>
char (&arrLenFn(const T (&arr) [N]))[N];
#define arrLen(arr) sizeof(arrLenFn(arr))
</code></pre>
<p>First we declare a function returning a reference to an array of N <code>char</code>s i.e. <code>sizeof</code> this function would now be the length of the array. Then we've a macro to wrap it, so that it's readable at the caller's end.</p>
<p><strong>Note:</strong> Two arrays of the same base type but with different lengths are still two completely different types. <code>int[3]</code> is not the same as <code>int[2]</code>. <a href="https://stackoverflow.com/q/1461432/183120">Array decay</a>, however, would get you an <code>int*</code> in both cases. Read <a href="https://stackoverflow.com/q/4810664/183120">How do I use arrays in C++?</a> if you want to know more.</p> |
19,430,190 | Python: Where does if-endif-statement end? | <p>I have the following code:</p>
<pre><code>for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
classEnd = dataList.index(breaks[i+1])
classList = dataList[classStart:classEnd+1]
classMean = sum(classList)/len(classList)
print classMean
preSDCM = 0.0
for j in range(0,len(classList)):
sqDev2 = (classList[j] - classMean)**2
preSDCM += sqDev2
SDCM += preSDCM
return (SDAM - SDCM)/SDAM
</code></pre>
<p>I would like to convert this code to VB.NET.</p>
<p>But I am not sure where the if-elseif-statement ends.
Does it end after "classStart += 1"?</p>
<p>I feel it a bit difficult to see where the for-next-loops end as well in Python.</p>
<p>The code is taken from <a href="http://danieljlewis.org/files/2010/06/Jenks.pdf">http://danieljlewis.org/files/2010/06/Jenks.pdf</a></p>
<p>Thank you.</p> | 19,430,231 | 4 | 0 | null | 2013-10-17 14:57:05.247 UTC | 2 | 2022-06-22 10:32:24.213 UTC | null | null | null | null | 1,390,192 | null | 1 | 14 | python|vb.net|vb6|migration | 113,822 | <p>Yes. Python uses indentation to mark blocks. Both the <code>if</code> and the <code>for</code> end there.</p> |
40,926,920 | Reformat Whole Project Files in Android Studio | <p>I need to update my code style. Reformatting the whole project files one by one takes too much effort with the <a href="https://stackoverflow.com/a/16580200/4376058">shortcuts</a> I know.</p>
<blockquote>
<p><kbd>Opt</kbd> + <kbd>Command</kbd> + <kbd>L</kbd></p>
</blockquote>
<h1><strong>My Question?</strong></h1>
<p>Is there any other way to do it for the whole project?</p> | 40,927,082 | 2 | 0 | null | 2016-12-02 07:26:13.727 UTC | 7 | 2021-12-10 08:08:00.99 UTC | 2021-12-10 08:08:00.99 UTC | null | 4,376,058 | null | 4,376,058 | null | 1 | 70 | android|android-studio|formatting|android-studio-2.2 | 12,536 | <p>Use the re-format code shortcut (default: <code>⌘ + Opt + L</code> (Mac) / <code>Ctrl + Alt + L</code> (PC)) in the Project Files View/Explorer on the desired root folder(s) and then check <code>Include subdirectories</code>.</p>
<p><a href="https://i.stack.imgur.com/KbCRV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KbCRV.png" alt="Project File View" /></a></p>
<p><a href="https://i.stack.imgur.com/puyX0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/puyX0.png" alt="Reformat Code Options" /></a></p> |
34,157,900 | How to debug an application running in Docker with IntelliJ? | <p>I have a Jetty application running in docker. I would like to debug this application using my local IntelliJ. I am on v 14.1, so I have installed the Docker Integration plugin.</p>
<p>Under Clouds, I am using the default values that showed up when I click on the '+'. IntelliJ docs say this should be OK. Here the </p>
<pre><code>API URL: http://127.0.0.1:2376
Certificates folder: <empty>
</code></pre>
<p>I'm not sure what these are used for, so I dont know if these values are right.</p>
<p>Under Run/Debug configurations, I am using Docker Deployment, and the following values:</p>
<pre><code>Deployment: Docker Image
Image ID: The docker image ID
Container name: The name of the container
</code></pre>
<p>When I try to run this, I get
javax.ws.rs.ProcessingException: org.apache.http.conn.HttpHostConnectException: Connect to <a href="http://127.0.0.1:2376">http://127.0.0.1:2376</a> [/127.0.0.1] failed: Connection refused</p>
<p>Obviously the API URL value I am using is incorrect. Any suggestions on what that value should be?</p>
<p>My debugging options are: </p>
<pre><code> -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=n -Djava.compiler=NONE
</code></pre> | 34,158,396 | 5 | 0 | null | 2015-12-08 14:03:45.753 UTC | 9 | 2021-09-15 07:48:55.913 UTC | null | null | null | null | 535,060 | null | 1 | 32 | java|intellij-idea|docker|remote-debugging | 38,604 | <p>Sheesh Never mind. I didnt really need the Docker Integration plugin. Seems like that is more for deployment and management of Docker directly through Intellij than for debugging.</p>
<p>To debug my jetty app running inside my docker container, I simply remote debugged:</p>
<p>Run | Edit configurations | + | Remote</p>
<p>The command line args were already OK since I used the default remote debugging options. I only needed to change the Host settings. Here I used the hostname I had set within the docker container</p> |
18,977,187 | How to hide Soft Keyboard when activity starts | <p>I have an Edittext with <code>android:windowSoftInputMode="stateVisible"</code> in Manifest. Now the keyboard will be shown when I start the activity. How to hide it? I cannot use <code>android:windowSoftInputMode="stateHidden</code> because when keyboard is visible then minimize the app and resume it the keyboard should be visible.
I tried with </p>
<p><code>InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);</code></p>
<p>but it did not work.</p> | 59,780,712 | 23 | 0 | null | 2013-09-24 09:03:47.957 UTC | 40 | 2020-02-27 09:05:49.11 UTC | null | null | null | null | 627,182 | null | 1 | 161 | android|android-softkeyboard | 220,850 | <h2>If you don't want to use xml, make a Kotlin Extension to hide keyboard</h2>
<pre><code>// In onResume, call this
myView.hideKeyboard()
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
</code></pre>
<p>Alternatives based on use case:</p>
<pre><code>fun Fragment.hideKeyboard() {
view?.let { activity?.hideKeyboard(it) }
}
fun Activity.hideKeyboard() {
// Calls Context.hideKeyboard
hideKeyboard(currentFocus ?: View(this))
}
fun Context.hideKeyboard(view: View) {
view.hideKeyboard()
}
</code></pre>
<h3>How to <strong><em>show</em></strong> soft keyboard</h3>
<pre><code>fun Context.showKeyboard() { // Or View.showKeyboard()
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY)
}
</code></pre>
<p>Simpler method when simultaneously requesting focus on an edittext</p>
<pre><code>myEdittext.focus()
fun View.focus() {
requestFocus()
showKeyboard()
}
</code></pre>
<h3>Bonus simplification:</h3>
<p>Remove requirement for ever using <code>getSystemService</code>: <a href="https://github.com/LouisCAD/Splitties/tree/master/modules/systemservices" rel="noreferrer">Splitties Library</a></p>
<pre><code>// Simplifies above solution to just
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
</code></pre> |
18,979,300 | How to convert list to string in Emacs Lisp | <p>How can I convert a list to string so I can call <code>insert</code> or <code>message</code> with it? I need to display <code>c-offsets-alist</code> but I got <code>Wrong type argument: char-or-string-p</code> for insert or <code>Wrong type argument: stringp</code> for message.</p> | 18,979,462 | 5 | 0 | null | 2013-09-24 10:38:04.417 UTC | 9 | 2021-10-15 17:29:51.81 UTC | null | null | null | null | 387,194 | null | 1 | 38 | string|list|emacs|elisp | 19,421 | <p>I am not sure of what you are trying to achieve, but <code>format</code> converts "stuff" to strings. For instance:</p>
<pre><code>(format "%s" your-list)
</code></pre>
<p>will return a representation of your list. <code>message</code> uses format internally, so </p>
<pre><code>(message "%s" your-list)
</code></pre>
<p>will print it</p> |
37,038,193 | Exclude Table during pg_restore | <p><strong>UPDATE:</strong>
Was able to exclude the data in the table durning the pg_dump command. Makes it even faster than trying to not load the data because you don't have to wait for that data to be dumped.</p>
<p><code>--exclude-table-data=event_logs</code></p>
<p><code>(PostgreSQL) 9.4.4</code></p>
<p>Anyone know how to exclude a table when doing a <code>pg_restore</code>? I can find how to do it when doing a <code>pg_dump</code>. However I am not the one doing the dump and can't exclude them. </p>
<p>There are 2 tables in the dump that are really big and take forever when I do a restore so I want to skip them.</p> | 37,042,865 | 4 | 0 | null | 2016-05-04 21:17:16.62 UTC | 8 | 2022-06-20 04:35:15.377 UTC | 2018-09-25 17:22:32.347 UTC | null | 634,586 | null | 634,586 | null | 1 | 31 | postgresql|pg-restore | 22,950 | <p><a href="http://www.postgresql.org/docs/9.5/static/app-pgrestore.html" rel="noreferrer">pg_restore</a> does not have an exclude table parameter, what it does have is an include table parameter.</p>
<blockquote>
<p>-t table</p>
<p>--table=table</p>
<p>Restore definition and/or data of named table only. Multiple tables may be specified with multiple -t switches. This can
be combined with the -n option to specify a schema.</p>
</blockquote>
<p>If you have a large number of tables it does call for a litte bit of typing, but it does allow you to exclude specific tables by just leaving their names out of the list.</p> |
8,369,411 | bash script to change directory and execute command with arguments | <p>I am trying to do the following task:
write a shell script called <code>changedir</code> which
takes a directory name, a command name and (optionally) some additional arguments.
The script will then change into the directory indicated, and
executes the command indicated with the arguments provided.</p>
<p>Here an example:</p>
<pre><code>$ sh changedir /etc ls -al
</code></pre>
<p>This should change into the <code>/etc</code> directory and run the command <code>ls -al</code>.</p>
<p>So far I have:</p>
<pre><code>#!/bin/sh
directory=$1; shift
command=$1; shift
args=$1; shift
cd $directory
$command
</code></pre>
<p>If I run the above like <code>sh changedir /etc ls</code> it changes and lists the directory. But if I add arguments to the <code>ls</code> it does not work. What do I need to do to correct it?</p> | 8,369,446 | 2 | 0 | null | 2011-12-03 17:16:27.903 UTC | 1 | 2015-04-28 06:43:15.747 UTC | 2011-12-03 18:58:23.02 UTC | null | 360,899 | null | 1,069,751 | null | 1 | 10 | bash | 40,200 | <p>You seemed to be ignoring the remainder of the arguments to your command.</p>
<p>If I understand correctly you need to do something like this:</p>
<pre><code>#!/bin/sh
cd "$1" # change to directory specified by arg 1
shift # drop arg 1
cmd="$1" # grab command from next argument
shift # drop next argument
"$cmd" "$@" # expand remaining arguments, retaining original word separations
</code></pre>
<p>A simpler and safer variant would be:</p>
<pre><code>#!/bin/sh
cd "$1" && shift && "$@"
</code></pre> |
8,418,184 | Getting index of a character in NSString with offset & using substring in Objective-C | <p>I have a string!</p>
<pre><code> NSString *myString=[NSString stringWithFormat:@"This is my lovely string"];
</code></pre>
<p>What I want to do is:</p>
<ol>
<li>Assuming the first character in the string is at index 0. Go to the 11th character (That is 'l' in the above case), and find the position of first occurring space backwards (In the above string, the position of first occurring space if we go backwards from 'l' is at position 10). Let's call the index of this space 'leSpace' having value 10.</li>
<li><p>Substring the remaining string to a new string using ... </p>
<pre><code>[myString substringFromIndex:leSpace]
</code></pre></li>
</ol>
<p>...I hope I have explained well. Please help, can you write a snippet or something to help me do this task?</p> | 8,418,225 | 1 | 0 | null | 2011-12-07 15:48:51.753 UTC | 3 | 2014-03-02 21:51:42.257 UTC | 2014-03-02 21:51:42.257 UTC | null | 348,796 | null | 493,965 | null | 1 | 22 | objective-c|ios|nsstring|substring|nsrange | 39,603 | <pre><code>- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange
</code></pre>
<p>For the options use: <code>NSBackwardsSearch</code></p>
<pre><code>NSRange range = [myString rangeOfString:@" " options:NSBackwardsSearch range:NSMakeRange(0, 11)];
</code></pre>
<p>Example:</p>
<pre><code>NSString *myString=[NSString stringWithFormat:@"This is my lovely string"];
NSRange range = [myString rangeOfString:@" " options:NSBackwardsSearch range:NSMakeRange(0, 11)];
NSLog(@"range.location: %lu", range.location);
NSString *substring = [myString substringFromIndex:range.location+1];
NSLog(@"substring: '%@'", substring);
</code></pre>
<p>NSLog output:</p>
<pre><code>range.location: 10
substring: 'lovely string'
</code></pre>
<p>Of course there should be error checking that <code>range.location</code> does not equal <code>NSNotFound</code> </p> |
8,995,987 | Is there any way to have one and only one instance of each activity? | <p>I'm finding that in my application, the user can get quite 'nested' in the various activities that are opened while the user is using the application.</p>
<p>For example:</p>
<ol>
<li>Main Menu</li>
<li>Object List</li>
<li>Object Details</li>
<li>Object Edit</li>
<li>Object Details</li>
<li>Object Child Details</li>
<li>Object Child Edit</li>
<li>Object Child Details</li>
</ol>
<p>Now, when the user presses back, it has to go through 'Object Child Details' twice (same object, when it is edited it returns to the detailed page), and the same thing happens for the 'Parent Object Details'.</p>
<p>Is there a way to reuse activities, if they are already open in the stack, and reorder them to the front? The only way I have seen is on activities with the <code>launcher</code> attribute. I believe I saw <code>singleTask</code> and <code>singleTop</code>.</p>
<p>If am supposed to be using these two attributes, <code>singleTask</code> and <code>singleTop</code>, how am I supposed to use them? When I tried to include them in the application, it made no difference. Do I also need to set a flag while launching the intent using <code>startActivity</code>?</p> | 8,998,266 | 10 | 0 | null | 2012-01-24 23:44:22.543 UTC | 11 | 2021-10-28 17:10:27.04 UTC | null | null | null | null | 783,284 | null | 1 | 41 | android|android-manifest|android-activity | 46,616 | <p>in Manifest Activity property you can give this parameter <code>android:launchMode="singleInstance"</code></p>
<p>Read in more detail here <a href="http://developer.android.com/guide/topics/manifest/activity-element.html">http://developer.android.com/guide/topics/manifest/activity-element.html</a></p> |
2,445,092 | Hibernate's Transformers.aliasToBean() method | <pre><code> Query query = getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(
"select proj_employee.employee_no as employeeNo, ...
.setResultTransformer(Transformers.aliasToBean(User.class));
</code></pre>
<p>Inside User.class
does the property employeNo need to be in capital letter?</p>
<pre><code>private String EMPLOYEENO;
//get/set for EMPLOYEENO
</code></pre>
<p><br>
If I change the <code>EMPLOYEENO</code> to <em>small letter</em>, it doesn't work. Can anyone explain why the variable name must be all capital letters?</p> | 2,445,176 | 2 | 6 | null | 2010-03-15 04:33:14.62 UTC | 5 | 2018-02-08 14:46:31.627 UTC | 2018-02-08 14:46:31.627 UTC | null | 814,702 | null | 108,869 | null | 1 | 17 | java|hibernate | 46,038 | <p>See the <a href="http://in.relation.to/2006/03/17/hibernate-32-transformers-for-hql-and-sql/" rel="noreferrer">Hibernate 3.2: Transformers for HQL and SQL</a> blog post:</p>
<blockquote>
<h3>SQL Transformers</h3>
<p>With native sql returning non-entity
beans or Map's is often more useful
instead of basic <code>Object[]</code>. With
result transformers that is now
possible.</p>
<pre><code>List resultWithAliasedBean = s.createSQLQuery(
"SELECT st.name as studentName, co.description as courseDescription " +
"FROM Enrolment e " +
"INNER JOIN Student st on e.studentId=st.studentId " +
"INNER JOIN Course co on e.courseCode=co.courseCode")
.addScalar("studentName")
.addScalar("courseDescription")
.setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
.list();
StudentDTO dto =(StudentDTO) resultWithAliasedBean.get(0);
</code></pre>
<p>Tip: the <code>addScalar()</code> calls were
required on HSQLDB to make it match a
property name since it returns column
names in all uppercase (e.g.
"STUDENTNAME"). This could also be
solved with a custom transformer that
search the property names instead of
using exact match - maybe we should
provide a <code>fuzzyAliasToBean()</code> method
;)</p>
</blockquote>
<p>Maybe you are facing the same situation than the one described in the tip in which case you should try to add calls to <code>addScalar()</code>.</p> |
2,424,718 | How to know if a cell has an error in the formula in C# | <p>In an Excel formula you can use <code>=ISERR(A1)</code> or <code>=ISERROR(A1)</code></p>
<p>In a VBA macro you can use <code>IsError(sheet.Cells(1, 1))</code></p>
<p>But using a VSTO Excel Addin project I did not found similar function under the Microsoft.Office.Interop.Excel API. I only want to know if there is an error in the cell, I'm not really interested in the type of error.</p>
<p>My current workaround is to do this for all the existing error messages.:</p>
<pre><code>if (((Range)sheet.Cells[1, 1]).Text == "#N/A" || ...)
</code></pre>
<p>Is there a better way to do this. Is there a simple function in the API for that?</p> | 2,472,046 | 2 | 2 | null | 2010-03-11 12:06:32.217 UTC | 15 | 2020-08-12 15:21:29.92 UTC | 2010-03-30 08:00:04.25 UTC | null | 289,215 | null | 289,215 | null | 1 | 25 | c#|excel|vsto | 15,791 | <p>You can use the <code>WorksheetFunction</code> method:</p>
<pre><code>Globals.ThisAddIn.Application.WorksheetFunction.IsErr(...)
</code></pre>
<p>or</p>
<pre><code>[Your Excel Object].WorksheetFunction.IsErr(...)
</code></pre>
<p>The <code>IsErr</code> is semantically identical to the Excel worksheet function, only instead of the cell reference pass in the actual value - AFAIK.</p> |
2,348,521 | In Ruby, how do I check if method "foo=()" is defined? | <p>In Ruby, I can define a method foo=(bar):</p>
<pre><code>irb(main):001:0> def foo=(bar)
irb(main):002:1> p "foo=#{bar}"
irb(main):003:1> end
=> nil
</code></pre>
<p>Now I'd like to check if it has been defined,</p>
<pre><code>irb(main):004:0> defined?(foo=)
SyntaxError: compile error
(irb):4: syntax error, unexpected ')'
from (irb):4
from :0
</code></pre>
<p>What is the proper syntax to use here? I assume there must be a way to escape "foo=" such that it is parsed and passed correctly to the defined? operator.</p> | 2,348,524 | 2 | 0 | null | 2010-02-27 18:54:48.913 UTC | 7 | 2021-03-30 16:17:34.05 UTC | null | null | null | null | 199,174 | null | 1 | 87 | ruby|syntax-error | 80,907 | <p>The problem is that the <code>foo=</code> method is designed to be used in assignments. You can use <code>defined?</code> in the following way to see what's going on:</p>
<pre><code>defined?(self.foo=())
#=> nil
defined?(self.foo = "bar")
#=> nil
def foo=(bar)
end
defined?(self.foo=())
#=> "assignment"
defined?(self.foo = "bar")
#=> "assignment"
</code></pre>
<p>Compare that to:</p>
<pre><code>def foo
end
defined?(foo)
#=> "method"
</code></pre>
<p>To test if the <code>foo=</code> method is defined, you should use <a href="http://ruby-doc.org/core/classes/Object.html#M000331" rel="noreferrer"><code>respond_to?</code></a> instead:</p>
<pre><code>respond_to?(:foo=)
#=> false
def foo=(bar)
end
respond_to?(:foo=)
#=> true
</code></pre> |
39,681,046 | Keras - stateful vs stateless LSTMs | <p>I'm having a hard time conceptualizing the difference between stateful and stateless LSTMs in Keras. My understanding is that at the end of each batch, the "state of the network is reset" in the stateless case, whereas for the stateful case, the state of the network is preserved for each batch, and must then be manually reset at the end of each epoch.</p>
<p>My questions are as follows:
1. In the stateless case, how is the network learning if the state isn't preserved in-between batches?
2. When would one use the stateless vs stateful modes of an LSTM?</p> | 43,090,574 | 3 | 0 | null | 2016-09-24 21:16:44.73 UTC | 20 | 2022-06-12 04:56:31.457 UTC | null | null | null | null | 190,894 | null | 1 | 45 | tensorflow|deep-learning|keras|lstm | 14,963 | <p>I recommend you to firstly learn the concepts of BPTT (Back Propagation Through Time) and mini-batch SGD(Stochastic Gradient Descent), then you'll have further understandings of LSTM's training procedure.</p>
<p>For your questions,</p>
<p>Q1. In stateless cases, LSTM updates parameters on batch1 and then, initiate hidden states and cell states (usually all zeros) for batch2, while in stateful cases, it uses batch1's last output hidden states and cell sates as initial states for batch2.</p>
<p>Q2. As you can see above, when two sequences in two batches have connections (e.g. prices of one stock), you'd better use stateful mode, else (e.g. one sequence represents a complete sentence) you should use stateless mode.</p>
<p>BTW, @vu.pham said <code>if we use stateful RNN, then in production, the network is forced to deal with infinite long sequences</code>. This seems not correct, actually, as you can see in Q1, LSTM <strong>WON'T</strong> learn on the whole sequence, it first learns sequence in batch1, updates parameters, and then learn sequence on batch2.</p> |
59,713,224 | Jetpack Compose - Column - Gravity center | <p>I'm creating a layout with Jetpack Compose and there is a column. I would like center items inside this column:</p>
<pre><code> Column(modifier = ExpandedWidth) {
Text(text = item.title)
Text(text = item.description)
}
</code></pre> | 62,152,703 | 16 | 0 | null | 2020-01-13 08:54:03.327 UTC | 9 | 2022-09-02 19:34:37.11 UTC | 2020-01-14 22:02:36.337 UTC | null | 4,312,751 | null | 4,312,751 | null | 1 | 88 | android|kotlin|android-jetpack|android-jetpack-compose | 97,649 | <p>You can use <a href="https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/package-summary#column" rel="noreferrer">these parameters</a>:</p>
<ul>
<li><a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Alignment.Horizontal.html" rel="noreferrer"><strong><code>horizontalAlignment</code></strong></a> = the horizontal gravity of the layout's children.</li>
<li><a href="https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Arrangement.Vertical" rel="noreferrer"><strong><code>verticalArrangement</code></strong></a>= the vertical arrangement of the layout's children</li>
</ul>
<p>Something like:</p>
<pre><code>Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "First item",
modifier = Modifier.padding(16.dp)
)
Text(
text = "Second item",
modifier = Modifier.padding(16.dp)
)
Text(
text = "Third item",
modifier = Modifier.padding(16.dp)
)
}
</code></pre>
<p><a href="https://i.stack.imgur.com/s6ptD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/s6ptD.png" alt="enter image description here" /></a></p>
<p>If you want only to center horizontally just use:</p>
<pre><code>Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Column ( ) { ... }
</code></pre>
<p><a href="https://i.stack.imgur.com/zejNR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zejNR.png" alt="enter image description here" /></a></p> |
23,226,802 | Laravel attach pivot to table with multiple values | <h3>Background</h3>
<p>I'm creating a database revolving around food allergies and I have a many to many relationship between foods and allergies. There is also a pivot value called <code>severity</code> which has a numerical number representing the severity of the allergy for that food item.</p>
<p>This link table looks like this;</p>
<pre><code>food_id|allergy_id|severity
-------|----------|--------
1 | 1 | 3
1 | 4 | 1
2 | 2 | 1
</code></pre>
<h3>The problem</h3>
<p>When trying to update the link table with Eloquent (where <code>$allergy_ids</code> is an array)</p>
<pre><code>$food->allergies()->attach($allergy_ids);
</code></pre>
<p>How would I go about adding multiple values to this pivot table at once along with the pivot values?</p>
<p>I can add all the <code>allergy_id</code>'s for a particular food item in one go using the above line, but how can I also add in the <code>severity</code> column at the same time with an array of various severity values? Maybe something like</p>
<pre><code>$food->allergies()->attach($allergy_ids, $severity_ids);
</code></pre>
<p>Edit: There could be between 0-20 allergies for a specific food item, and a severity rating from 0-4 for each allergy, if this helps at all.</p> | 30,351,384 | 5 | 0 | null | 2014-04-22 17:51:56.107 UTC | 12 | 2022-04-22 03:46:19.887 UTC | 2014-04-22 18:41:30.11 UTC | null | 3,315,756 | null | 3,315,756 | null | 1 | 37 | laravel|laravel-4|eloquent|pivot-table | 86,341 | <p>You can.</p>
<p>From this example in Docs (<a href="http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables">4.2</a>, <a href="http://laravel.com/docs/5.0/eloquent#working-with-pivot-tables">5.0</a>):</p>
<pre><code>$user->roles()->sync(array(1 => array('expires' => true)));
</code></pre>
<p>Hardcoded version for the first two rows:</p>
<pre><code>$food = Food::find(1);
$food->allergies()->sync([1 => ['severity' => 3], 4 => ['severity' => 1]]);
</code></pre>
<p>Dynamically, with your arrays $allergy_ids and $severities in a compatible state (size and sort), you shall prepare your sync data before. Something like:</p>
<pre><code>$sync_data = [];
for($i = 0; $i < count($allergy_ids); $i++))
$sync_data[$allergy_ids[$i]] = ['severity' => $severities[$i]];
$food->allergies()->sync($sync_data);
</code></pre> |
30,786,263 | Only check whether a line present in a file (ansible) | <p>In ansible, I need to check whether a particular line present in a file or not. Basically, I need to convert the following command to an ansible task. My goal is to only check.</p>
<pre><code>grep -Fxq "127.0.0.1" /tmp/my.conf
</code></pre> | 30,788,277 | 8 | 0 | null | 2015-06-11 16:22:16.273 UTC | 15 | 2022-08-30 19:57:59.567 UTC | 2018-07-23 23:28:05.357 UTC | null | 2,815,227 | null | 1,943,282 | null | 1 | 72 | ansible | 105,572 | <pre><code>- name: Check whether /tmp/my.conf contains "127.0.0.1"
command: grep -Fxq "127.0.0.1" /tmp/my.conf
register: checkmyconf
check_mode: no
ignore_errors: yes
changed_when: no
- name: Greet the world if /tmp/my.conf contains "127.0.0.1"
debug: msg="Hello, world!"
when: checkmyconf.rc == 0
</code></pre>
<p><strong>Update 2017-08-28:</strong> Older Ansible versions need to use <code>always_run: yes</code> instead of <code>check_mode: no</code>.</p> |
21,919,156 | How do I copy cookies from Chrome? | <p>I am using bash to to POST to a website that requires that I be logged in first. So I need to send the request with login cookie. So I tried logging in and keeping the cookies, but it doesn't work because the site uses javascript to hash the password in a really weird fashion, so instead I'm going to just take my login cookies for the site from Chrome. How do get the cookies from Chrome and format them for Curl?</p>
<p>I'm trying to do this: </p>
<pre class="lang-bsh prettyprint-override"><code>curl --request POST -d "a=X&b=Y" -b "what goes here?" "site.com/a.php"
</code></pre> | 21,919,431 | 6 | 0 | null | 2014-02-20 20:44:11.4 UTC | 26 | 2022-03-27 09:11:23.917 UTC | null | null | null | null | 1,313,757 | null | 1 | 68 | bash|google-chrome|cookies|curl | 91,998 | <ol>
<li>Hit F12 to open the developer console (Mac: Cmd+Opt+J)</li>
<li>Look at the Network tab.</li>
<li>Do whatever you need to on the web site to trigger the action you're interested in</li>
<li>Right click the relevant request, and select "Copy as cURL"</li>
</ol>
<p>This will give you the curl command for the action you triggered, fully populated with cookies and all. You can of course also copy the flags as a basis for new curl commands.</p> |
40,080,887 | How do I restart Docker for Mac from the terminal? | <p>Docker for Mac has a neat little 'restart' button in the dropdown from the whale icon in the menu bar.</p>
<p>I'd like to be able to restart Docker for Mac from the terminal, though. What command would I need to run?</p> | 44,555,371 | 4 | 0 | null | 2016-10-17 07:40:05.967 UTC | 21 | 2020-12-29 18:07:14.303 UTC | 2016-10-17 09:36:54.04 UTC | null | 1,688,034 | null | 1,688,034 | null | 1 | 84 | docker|docker-for-mac | 63,565 | <p>Specifically for Docker for Mac, because it's a "GUI" app, there's a <a href="http://osxdaily.com/2014/09/05/gracefully-quit-application-command-line/" rel="noreferrer">workaround</a>:</p>
<p><code>osascript -e 'quit app "Docker"'</code></p>
<p>Since you'd want to restart, here's the way to <a href="https://superuser.com/a/1107622/243446">open it from the command line</a>:</p>
<p><code>open -a Docker</code></p>
<p>There's probably a more symmetrical command to open using <code>osascript</code>, but the <code>open</code> command seems more common than the <code>osascript</code> one.</p> |
58,488,535 | What's the purpose of "docker build --pull"? | <p>When building a docker image you normally use <code>docker build .</code>.</p>
<p>But I've found that you can specify <code>--pull</code>, so the whole command would look like <code>docker build --pull .</code></p>
<p>I'm not sure about the purpose of <code>--pull</code>. Docker's <a href="https://docs.docker.com/engine/reference/commandline/build/" rel="noreferrer">official documentation</a> says "Always attempt to pull a newer version of the image", and I'm not sure what this means in this context.</p>
<p>You use <code>docker build</code> to build a new image, and eventually publish it somewhere to a container registry. Why would you want to pull something that doesn't exist yet?</p> | 58,488,653 | 3 | 0 | null | 2019-10-21 14:32:45.29 UTC | 12 | 2021-04-10 22:40:00.76 UTC | 2021-04-10 22:40:00.76 UTC | null | 2,123,530 | null | 2,874,896 | null | 1 | 84 | docker | 25,095 | <p>it will pull the latest version of any base image(s) instead of reusing whatever you already have tagged locally</p>
<p>take for instance an image based on a moving tag (such as <code>ubuntu:bionic</code>). upstream makes changes and rebuilds this periodically but you might have a months old image locally. docker will happily build against the old base. <code>--pull</code> will pull as a side effect so you build against the latest base image</p>
<p>it's ~usually a best practice to use it to get upstream security fixes as soon as possible (instead of using stale, potentially vulnerable images). though you have to trade off breaking changes (and if you use immutable tags then it doesn't make a difference)</p> |
37,078,970 | Sequelize: Using Multiple Databases | <p>Do I need to create multiple instances of Sequelize if I want to use two databases? That is, two databases on the same machine.</p>
<p>If not, what's the proper way to do this? It seems like overkill to have to connect twice to use two databases, to me.</p>
<p>So for example, I have different databases for different functions, for example, let's say I have customer data in one database, and statistical data in another. </p>
<p>So in MySQL:</p>
<pre><code>MySQL [customers]> show databases;
+--------------------+
| Database |
+--------------------+
| customers |
| stats |
+--------------------+
</code></pre>
<p>And I have this to connect with sequelize</p>
<pre><code>// Create a connection....
var Sequelize = require('sequelize');
var sequelize = new Sequelize('customers', 'my_user', 'some_password', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
},
logging: function(output) {
if (opts.log_queries) {
log.it("sequelize_log",{log: output});
}
}
});
// Authenticate it.
sequelize.authenticate().nodeify(function(err) {
// Do stuff....
});
</code></pre>
<p>I tried to "trick" it by in a definition of a model using dot notation</p>
<pre><code>var InterestingStatistics = sequelize.define('stats.interesting_statistics', { /* ... */ });
</code></pre>
<p>But that creates the table <code>customers.stats.interesting_statistics</code>. I need to use an existing table in the stats database.</p>
<p>What's the proper way to achieve this? Thanks.</p> | 37,079,267 | 3 | 0 | null | 2016-05-06 18:18:03.877 UTC | 15 | 2022-09-05 13:46:26.553 UTC | null | null | null | null | 1,681,171 | null | 1 | 36 | javascript|mysql|node.js|sequelize.js | 37,935 | <p>You need to create different instances of sequelize for each DB connection you want to create:</p>
<pre><code>const { Sequelize } = require('sequelize');
const userDb = new Sequelize(/* ... */);
const contentDb = new Sequelize(/* ... */);
</code></pre>
<p>Each instance created from sequelize has its own DB info <em>(db host, url, user, pass, etc...)</em>, and these values are not meant to be changed, so there is no "correct" way to create multiple connections with one instance of sequelize.</p>
<p><a href="https://sequelize.org/docs/v6/getting-started/" rel="nofollow noreferrer"><strong>From their docs</strong></a>:</p>
<blockquote>
<p>Observe that, in the examples above, Sequelize refers to the library itself while sequelize refers to an instance of Sequelize, <strong>which represents a connection to one database</strong>. This is the recommended convention and it will be followed throughout the documentation.</p>
</blockquote>
<p>A "common" approach to do this, is having your databases in a <code>config.json</code> file and loop over it to create connections dinamically, something like this maybe:</p>
<p><strong>config.json</strong></p>
<pre><code>{
/*...*/
databases: {
user: {
path: 'xxxxxxxx'
},
content: {
path: 'xxxxxxxx'
}
}
}
</code></pre>
<p><strong>Your app</strong></p>
<pre><code>const Sequelize = require('sequelize');
const config = require('./config.json');
// Loop through
const db = {};
const databases = Object.keys(config.databases);
for(let i = 0; i < databases.length; ++i) {
let database = databases[i];
let dbPath = config.databases[database];
db[database] = new Sequelize( dbPath );
}
// Sequelize instances:
// db.user
// db.content
</code></pre>
<p>You will need to do a little bit more coding to get it up and running but its a general idea.</p> |
36,730,372 | Extract the text from `p` within `div` with BeautifulSoup | <p>I am very new to web-scraping with Python, and I am really having a hard time with extracting nested text from within HTML (<code>p</code> within <code>div</code>, to be exact). Here is what I got so far:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib
url = urllib.urlopen('http://meinparlament.diepresse.com/')
content = url.read()
soup = BeautifulSoup(content, 'lxml')
</code></pre>
<p>This works fine:</p>
<pre><code>links=soup.findAll('a',{'title':'zur Antwort'})
for link in links:
print(link['href'])
</code></pre>
<p>This extraction works fine:</p>
<pre><code>table = soup.findAll('div',attrs={"class":"content-question"})
for x in table:
print(x)
</code></pre>
<p>This is the output:</p>
<pre><code><div class="content-question">
<p>[...] Die Verhandlungen über die mögliche Visabefreiung für
türkische Staatsbürger per Ende Ju...
<a href="http://meinparlament.diepresse.com/frage/10144/" title="zur
Antwort">mehr »</a>
</p>
</div>
</code></pre>
<p>Now, I want to extract the text within <code>p</code> and <code>/p</code>. This is the code I use:</p>
<pre><code>table = soup.findAll('div',attrs={"class":"content-question"})
for x in table:
print(x['p'])
</code></pre>
<p>However, Python raises a <code>KeyError</code>.</p> | 36,730,457 | 1 | 0 | null | 2016-04-19 22:08:54.67 UTC | 4 | 2017-04-18 21:27:47.55 UTC | 2016-04-19 23:47:42.017 UTC | null | 5,299,236 | null | 4,587,552 | null | 1 | 9 | python|python-3.x|web-scraping|beautifulsoup | 43,090 | <p>The following code finds and prints the text of each <code>p</code> element in the <code>div</code>'s with the <code>class</code> "content-question" </p>
<pre><code>from bs4 import BeautifulSoup
import urllib
url = urllib.urlopen('http://meinparlament.diepresse.com/')
content = url.read()
soup = BeautifulSoup(content, 'lxml')
table = soup.findAll('div',attrs={"class":"content-question"})
for x in table:
print x.find('p').text
# Another way to retrieve tables:
# table = soup.select('div[class="content-question"]')
</code></pre>
<p>The following is the printed text of the first <code>p</code> element in <code>table</code>:</p>
<p>[...] Die Verhandlungen über die mögliche Visabefreiung für türkische Staatsbürger per Ende Juni sind noch nicht abgeschlossen, sodass nicht mit Sicherheit gesagt werden kann, ob es zu diesem Zeitpunkt bereits zu einer Visabefreiung kommt. Auch die genauen Modalitäten einer solchen Visaliberalisierung sind noch nicht ausverhandelt. Prinzipiell ist es jedoch so, dass Visaerleichterungen bzw. -liberalisierungen eine Frage von Reziprozität sind, d.h. dass diese für beide Staaten gelten müssten. [...]</p> |
53,654,310 | What is the difference between UpSampling2D and Conv2DTranspose functions in keras? | <p>Here in this code <code>UpSampling2D</code> and <code>Conv2DTranspose</code> seem to be used interchangeably. I want to know why this is happening. </p>
<pre><code># u-net model with up-convolution or up-sampling and weighted binary-crossentropy as loss func
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, concatenate, Conv2DTranspose, BatchNormalization, Dropout
from keras.optimizers import Adam
from keras.utils import plot_model
from keras import backend as K
def unet_model(n_classes=5, im_sz=160, n_channels=8, n_filters_start=32, growth_factor=2, upconv=True,
class_weights=[0.2, 0.3, 0.1, 0.1, 0.3]):
droprate=0.25
n_filters = n_filters_start
inputs = Input((im_sz, im_sz, n_channels))
#inputs = BatchNormalization()(inputs)
conv1 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(inputs)
conv1 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
#pool1 = Dropout(droprate)(pool1)
n_filters *= growth_factor
pool1 = BatchNormalization()(pool1)
conv2 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(pool1)
conv2 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
pool2 = Dropout(droprate)(pool2)
n_filters *= growth_factor
pool2 = BatchNormalization()(pool2)
conv3 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(pool2)
conv3 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
pool3 = Dropout(droprate)(pool3)
n_filters *= growth_factor
pool3 = BatchNormalization()(pool3)
conv4_0 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(pool3)
conv4_0 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv4_0)
pool4_1 = MaxPooling2D(pool_size=(2, 2))(conv4_0)
pool4_1 = Dropout(droprate)(pool4_1)
n_filters *= growth_factor
pool4_1 = BatchNormalization()(pool4_1)
conv4_1 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(pool4_1)
conv4_1 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv4_1)
pool4_2 = MaxPooling2D(pool_size=(2, 2))(conv4_1)
pool4_2 = Dropout(droprate)(pool4_2)
n_filters *= growth_factor
conv5 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(pool4_2)
conv5 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv5)
n_filters //= growth_factor
if upconv:
up6_1 = concatenate([Conv2DTranspose(n_filters, (2, 2), strides=(2, 2), padding='same')(conv5), conv4_1])
else:
up6_1 = concatenate([UpSampling2D(size=(2, 2))(conv5), conv4_1])
up6_1 = BatchNormalization()(up6_1)
conv6_1 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(up6_1)
conv6_1 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv6_1)
conv6_1 = Dropout(droprate)(conv6_1)
n_filters //= growth_factor
if upconv:
up6_2 = concatenate([Conv2DTranspose(n_filters, (2, 2), strides=(2, 2), padding='same')(conv6_1), conv4_0])
else:
up6_2 = concatenate([UpSampling2D(size=(2, 2))(conv6_1), conv4_0])
up6_2 = BatchNormalization()(up6_2)
conv6_2 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(up6_2)
conv6_2 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv6_2)
conv6_2 = Dropout(droprate)(conv6_2)
n_filters //= growth_factor
if upconv:
up7 = concatenate([Conv2DTranspose(n_filters, (2, 2), strides=(2, 2), padding='same')(conv6_2), conv3])
else:
up7 = concatenate([UpSampling2D(size=(2, 2))(conv6_2), conv3])
up7 = BatchNormalization()(up7)
conv7 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(up7)
conv7 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv7)
conv7 = Dropout(droprate)(conv7)
n_filters //= growth_factor
if upconv:
up8 = concatenate([Conv2DTranspose(n_filters, (2, 2), strides=(2, 2), padding='same')(conv7), conv2])
else:
up8 = concatenate([UpSampling2D(size=(2, 2))(conv7), conv2])
up8 = BatchNormalization()(up8)
conv8 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(up8)
conv8 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv8)
conv8 = Dropout(droprate)(conv8)
n_filters //= growth_factor
if upconv:
up9 = concatenate([Conv2DTranspose(n_filters, (2, 2), strides=(2, 2), padding='same')(conv8), conv1])
else:
up9 = concatenate([UpSampling2D(size=(2, 2))(conv8), conv1])
conv9 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(up9)
conv9 = Conv2D(n_filters, (3, 3), activation='relu', padding='same')(conv9)
conv10 = Conv2D(n_classes, (1, 1), activation='sigmoid')(conv9)
model = Model(inputs=inputs, outputs=conv10)
def weighted_binary_crossentropy(y_true, y_pred):
class_loglosses = K.mean(K.binary_crossentropy(y_true, y_pred), axis=[0, 1, 2])
return K.sum(class_loglosses * K.constant(class_weights))
model.compile(optimizer=Adam(), loss=weighted_binary_crossentropy)
return model
</code></pre> | 53,655,426 | 1 | 0 | null | 2018-12-06 15:08:26.25 UTC | 13 | 2019-10-28 11:33:31.16 UTC | null | null | null | null | 6,143,004 | null | 1 | 45 | machine-learning|computer-vision|conv-neural-network|convolution|deconvolution | 32,251 | <p>UpSampling2D is just a simple scaling up of the image by using nearest neighbour or bilinear upsampling, so nothing smart. Advantage is it's cheap.</p>
<p>Conv2DTranspose is a convolution operation whose kernel is learnt (just like normal conv2d operation) while training your model. Using Conv2DTranspose will also upsample its input but the key difference is the model should learn what is the best upsampling for the job.</p>
<p>EDIT: Link to nice visualization of transposed convolution: <a href="https://towardsdatascience.com/types-of-convolutions-in-deep-learning-717013397f4d" rel="noreferrer">https://towardsdatascience.com/types-of-convolutions-in-deep-learning-717013397f4d</a></p> |
26,555,297 | Arrange a grouped_df by group variable not working | <p>I have a data.frame that contains client names, years, and several revenue numbers from each year.</p>
<pre><code>df <- data.frame(client = rep(c("Client A","Client B", "Client C"),3),
year = rep(c(2014,2013,2012), each=3),
rev = rep(c(10,20,30),3)
)
</code></pre>
<p>I want to end up with a data.frame that aggregates the revenue by client and year. I then want to sort the data.frame by year then by descending revenue.</p>
<pre><code>library(dplyr)
df1 <- df %>%
group_by(client, year) %>%
summarise(tot = sum(rev)) %>%
arrange(year, desc(tot))
</code></pre>
<p>However, when using the code above the <code>arrange()</code> function doesn't change the order of the grouped data.frame at all. When I run the below code and coerce to a normal data.frame it works.</p>
<pre><code> library(dplyr)
df1 <- df %>%
group_by(client, year) %>%
summarise(tot = sum(rev)) %>%
data.frame() %>%
arrange(year, desc(tot))
</code></pre>
<p>Am I missing something or will I need to do this every time when trying to <code>arrange</code> a grouped_df by a grouped variable?</p>
<p>R Version: 3.1.1
dplyr package version: 0.3.0.2</p>
<p><strong>EDIT 11/13/2017:</strong>
As noted by <a href="https://stackoverflow.com/users/1177738/lucacerone">lucacerone</a>, beginning with dplyr 0.5, arrange once again ignores groups when sorting. So my original code now works in the way I initially expected it would.</p>
<blockquote>
<p>arrange() once again ignores grouping, reverting back to the behaviour of dplyr 0.3 and earlier. This makes arrange() inconsistent with other dplyr verbs, but I think this behaviour is generally more useful. Regardless, it’s not going to change again, as more changes will just cause more confusion.</p>
</blockquote> | 26,555,424 | 2 | 0 | null | 2014-10-24 19:54:47.713 UTC | 9 | 2019-03-20 09:36:33.45 UTC | 2019-03-20 09:32:57.02 UTC | null | 680,068 | null | 4,178,877 | null | 1 | 32 | r|dplyr|grouped-table | 31,273 | <p>Try switching the order of your <code>group_by</code> statement:</p>
<pre><code>df %>%
group_by(year, client) %>%
summarise(tot = sum(rev)) %>%
arrange(year, desc(tot))
</code></pre>
<p>I think <code>arrange</code> is ordering within groups; after <code>summarize</code>, the last group is dropped, so this means in your first example it's arranging rows within the <code>client</code> group. Switching the order to <code>group_by(year, client)</code> seems to fix it because the <code>client</code> group gets dropped after <code>summarize</code>.</p>
<p>Alternatively, there is the <code>ungroup()</code> function</p>
<pre><code>df %>%
group_by(client, year) %>%
summarise(tot = sum(rev)) %>%
ungroup() %>%
arrange(year, desc(tot))
</code></pre>
<hr>
<p><strong>Edit, @lucacerone:</strong> since dplyr 0.5 this does not work anymore: </p>
<blockquote>
<p>Breaking changes arrange() once again ignores grouping, reverting back
to the behaviour of dplyr 0.3 and earlier. This makes arrange()
inconsistent with other dplyr verbs, but I think this behaviour is
generally more useful. Regardless, it’s not going to change again, as
more changes will just cause more confusion.</p>
</blockquote> |
38,948,904 | Calculating contentSize for UIScrollView when using Auto Layout | <p>Here is a quick question about something which works, but could be written much better. I have a <code>UIScrollView</code> and a list of objects laid out inside, one under the other. Everything is done during <code>viewDidLoad()</code> and the placement of the objects uses <code>Auto Layout</code>. Here is what I do to set the <code>contentSize</code> height of the <code>UIScrollView</code> to its appropriate value.</p>
<pre><code>override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
globalView.contentSize = CGSize(width: globalView.frame.width,
height: globalView.frame.height * 1.59)
}
</code></pre>
<p>It works, but the arbitrary value 1.59 has obviously been decided by me trying a few possible values. <strong>What is the proper way to compute the contentSize in such a case?</strong> I am doing everything programmatically.
Searching the net didn't lead me to any simple and clear answer, so eventhough it may be a somewhat duplicate question I decided to reformulate it.</p> | 38,969,007 | 6 | 4 | null | 2016-08-15 03:25:40.89 UTC | 22 | 2021-08-06 06:06:09.063 UTC | 2017-08-09 05:11:53.43 UTC | null | 611,201 | null | 611,201 | null | 1 | 22 | ios|swift|uiscrollview|autolayout | 31,430 | <p>Giving content size programatically is not good way. The below solution which will
work using autolayout, dont need to set content size at all. It will calculate as per
how many UI fields added to view.</p>
<p><strong>Step 1 :</strong></p>
<p>Add Scrollview to view in storyboard and add leading, trailing, top and bottom constraints
(All values are zero).</p>
<p><strong>Step 2 :</strong></p>
<p>Don't add directly views which you need on directly scrollview, First add one view
to scrollview (that will be our content view for all UI elements).
Add below constraints to this view. </p>
<p>1) Leading, trailing, top and bottom constraints
(All values are zero).</p>
<p>2) Add equal height, equal width to Main view (i.e. which contains scrollview).
For equal height set priority to low. <em>(This is the important step for setting content size)</em>.</p>
<p>3) Height of this content view will be according to the number of views added to the view.
let say if you added last view is one label and his Y position is 420 and height
is 20 then your content view will be 440.</p>
<p><strong>Step 3</strong> : Add constraints to all of views which you added within content view as per your requirement.</p>
<p>For reference :</p>
<p><a href="https://i.stack.imgur.com/vJVFC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vJVFC.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/9Rmst.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9Rmst.png" alt="enter image description here"></a></p>
<p>I hope this will definitely help you.</p> |
34,655,157 | How to solve liquibase checksum validation fail after liquibase upgrade | <p>In my project I just tried upgrading liquibase from 3.2.2 to 3.4.2 (both the jars and the maven plugin). EDIT: same for upgrade to 3.3.x.
As a consequence, starting the application now gives the following error:</p>
<pre><code>Caused by: liquibase.exception.ValidationFailedException: Validation Failed:
4 change sets check sum
src/main/resources/changelogs/xxx_add_indices_to_event_tables.xml::xxx-add_indices_to_event_tables::xxx is now: 7:0fc8f1faf484a59a96125f3e63431128
</code></pre>
<p>This for 4 changesets out of 50, all of which add indexes, such as:</p>
<pre><code><createIndex indexName="idx_eventtype" tableName="events">
<column name="eventtype" type="varchar(64)"/>
</createIndex>
</code></pre>
<p>While I can fix this locally, this would be a huge pain to manually fix on all running environments. Is this a bug, or is there some workaround?</p> | 34,661,256 | 4 | 0 | null | 2016-01-07 12:28:19.187 UTC | 2 | 2020-07-29 12:12:30.707 UTC | 2018-01-30 07:34:18.31 UTC | null | 2,986,984 | null | 2,986,984 | null | 1 | 11 | java|maven|liquibase|checksum | 45,260 | <p>You could also use the <code><validCheckSum></code> sub-tag of the <a href="http://www.liquibase.org/documentation/changeset.html" rel="noreferrer"><code><changeSet></code></a> to add the new checksums as valid checksums. </p>
<p>Also, checkout the comments on the bug <a href="https://liquibase.jira.com/browse/CORE-1950" rel="noreferrer">CORE-1950</a>. You could put the log level to "debug" on both of your liquibase versions and see if you can find differences in the log output of the checksum creations.</p>
<p>Use subtag something like this</p>
<pre><code><changeSet id="00000000000009" author="system">
<validCheckSum>7:19f99d93fcb9909c7749b7fc2dce1417</validCheckSum>
<preConditions onFail="MARK_RAN">
<sqlCheck expectedResult="0">SELECT COUNT(*) FROM users</sqlCheck>
</preConditions>
<loadData encoding="UTF-8" file="users.csv" separator=";" tableName="users">
<column name="active" type="boolean" />
<column name="deleted" type="boolean" />
</loadData>
</changeSet>
</code></pre>
<p>You should remember that the value of the validCheckSum tag is the new checksum for the changeset.</p> |
22,174,259 | Pick an email using AccountPicker.newChooseAccountIntent | <p>I'm trying to let the user pick an Email account using the following code:</p>
<pre><code>Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"},
false, null, null, null, null);
startActivityForResult(intent, 23);
</code></pre>
<p>This code works great but if the user doesn't have a Gmail account but Yahoo, Hotmail, etc..
How can I show all Email accounts by changing the third parameter:</p>
<pre><code>new String[]{"com.google"}
</code></pre>
<p>Thank you very much</p> | 59,320,088 | 3 | 0 | null | 2014-03-04 14:11:00.33 UTC | 13 | 2019-12-13 09:58:34.553 UTC | 2014-03-05 08:57:35.483 UTC | null | 444,324 | null | 1,039,761 | null | 1 | 24 | android|android-account|accountpicker | 17,932 | <p>It's 2019, and the code does not seem to work anymore. To get all accounts shown in the picker (using Xamarin Android), instead of </p>
<pre><code>Android.Gms.Common.AccountPicker.NewChooseAccountIntent(null, null,
null, false, null, null, null, null);
</code></pre>
<p>you have to use</p>
<pre><code>Android.Accounts.AccountManager.NewChooseAccountIntent(null,null,null,null,null,null,null)
</code></pre> |
37,355,244 | Ignore "cannot find module" error on typescript | <p>Can the Typescript compiler ignore the <code>cannot find module 'x'</code> error on import expressions such as:</p>
<pre><code>//How to tell the compiler that this module does exists
import sql = require('sql');
</code></pre>
<p>There are multiple npm libraries such as <a href="https://github.com/brianc/node-sql">node sql</a> that doesn't have existing typings</p>
<p>Is there a way to tell the compiler to ignore this error other than creating a new definition file with the <code>declare module x ...</code> ?</p> | 37,357,563 | 3 | 0 | null | 2016-05-20 20:22:33.773 UTC | 5 | 2019-06-29 19:04:00.037 UTC | null | null | null | null | 1,064,724 | null | 1 | 38 | import|module|typescript | 36,022 | <p>If you just want to bypass the compiler, you can create a .d.ts file for that module, for instance, you could create a sql.d.ts file and inside have this:</p>
<pre><code>declare module "sql" {
let _sql: any;
export = _sql;
}
</code></pre> |
64,926,174 | Module not found: Can't resolve 'fs' in Next.js application | <p>Unable to identify what's happening in my next.js app. As <strong>fs</strong> is a default file system module of nodejs. It is giving the error of <strong>module not found</strong>.</p>
<p><a href="https://i.stack.imgur.com/5uh8o.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5uh8o.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/87u5o.png" rel="noreferrer"><img src="https://i.stack.imgur.com/87u5o.png" alt="enter image description here" /></a></p> | 68,098,547 | 13 | 4 | null | 2020-11-20 08:34:31.817 UTC | 8 | 2022-07-27 07:24:33.653 UTC | null | null | null | null | 12,567,367 | null | 1 | 53 | node.js|reactjs|next.js|server-side-rendering|fs | 89,473 | <p>If you use <code>fs</code>, be sure it's only within <a href="https://nextjs.org/docs/api-reference/data-fetching/get-initial-props" rel="noreferrer"><code>getInitialProps</code></a> or <a href="https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#getserversideprops-with-typescript" rel="noreferrer"><code>getServerSideProps</code></a>. (anything includes server-side rendering).</p>
<p>You may also need to create a <code>next.config.js</code> file with the following content to get the client bundle to build:</p>
<p>For <code>webpack4</code></p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
webpack: (config, { isServer }) => {
// Fixes npm packages that depend on `fs` module
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config
}
}
</code></pre>
<p>For <code>webpack5</code></p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
webpack5: true,
webpack: (config) => {
config.resolve.fallback = { fs: false };
return config;
},
};
</code></pre>
<p>Note: for other modules such as <code>path</code>, you can add multiple arguments such as</p>
<pre class="lang-js prettyprint-override"><code>{
fs: false,
path: false
}
</code></pre> |
61,522,396 | Module build failed (from ./node_modules/sass-loader/dist/cjs.js) | <p>I'm trying to run my angular 9 app on windows 10 but getting the following error while trying to serve it locally. Have a look at the error below:</p>
<blockquote>
<p>ERROR in ./src/assets/sass/pickandpay.scss (./node_modules/css-loader/dist/cjs.js??ref--13-1!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/dist/cjs.js??ref--13-3!./src/assets/sass/pickandpay.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable: "$white-color".
on line 99 of src/assets/sass/pickandpay/_base.scss
from line 3 of H:\pick&pay_eCommerce\pickandpay-client\src\assets\sass\pickandpay.scss
color: $white-color;
---------^</p>
</blockquote>
<p>pickandpay.scss:</p>
<pre class="lang-css prettyprint-override"><code>// Core CSS
@import "pickandpay/base";
@import "pickandpay/blog-details";
@import "pickandpay/blog-sidebar";
@import "pickandpay/blog";
@import "pickandpay/breadcrumb";
@import "pickandpay/checkout";
@import "pickandpay/contact";
@import "pickandpay/footer";
@import "pickandpay/header";
@import "pickandpay/hero";
@import "pickandpay/home-page";
@import "pickandpay/mixins";
@import "pickandpay/responsive";
@import "pickandpay/shop-details";
@import "pickandpay/shop-grid";
@import "pickandpay/shoping-cart";
@import "pickandpay/sidebar";
@import "pickandpay/variable";
@import "pickandpay/style.scss";
</code></pre>
<p>_base.scss:</p>
<pre class="lang-css prettyprint-override"><code>html,
body {
height: 100%;
font-family: 'Cairo', sans-serif;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
color: #111111;
font-weight: 400;
font-family: 'Cairo', sans-serif;
}
h1 {
font-size: 70px;
}
h2 {
font-size: 36px;
}
h3 {
font-size: 30px;
}
h4 {
font-size: 24px;
}
h5 {
font-size: 18px;
}
h6 {
font-size: 16px;
}
p {
font-size: 16px;
font-family: 'Cairo', sans-serif;
color: #6f6f6f;
font-weight: 400;
line-height: 26px;
margin: 0 0 15px 0;
}
img {
max-width: 100%;
}
input:focus,
select:focus,
button:focus,
textarea:focus {
outline: none;
}
a:hover,
a:focus {
text-decoration: none;
outline: none;
color: $white-color;
}
ul,
ol {
padding: 0;
margin: 0;
}
/*---------------------
Helper CSS
-----------------------*/
.section-title {
margin-bottom: 50px;
text-align: center;
h2 {
color: $normal-color;
font-weight: 700;
position: relative;
&:after {
position: absolute;
left: 0;
bottom: -15px;
right: 0;
height: 4px;
width: 80px;
background: $primary-color;
content: "";
margin: 0 auto;
}
}
}
.set-bg {
background-repeat: no-repeat;
background-size: cover;
background-position: top center;
}
.spad {
padding-top: 100px;
padding-bottom: 100px;
}
.text-white h1,
.text-white h2,
.text-white h3,
.text-white h4,
.text-white h5,
.text-white h6,
.text-white p,
.text-white span,
.text-white li,
.text-white a {
color: #fff;
}
/* buttons */
.primary-btn {
display: inline-block;
font-size: 14px;
padding: 10px 28px 10px;
color: $white-color;
text-transform: uppercase;
font-weight: 700;
background: $primary-color;
letter-spacing: 2px;
}
.site-btn {
font-size: 14px;
color: $white-color;
font-weight: 800;
text-transform: uppercase;
display: inline-block;
padding: 13px 30px 12px;
background: $primary-color;
border: none;
}
/* Preloder */
#preloder {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 999999;
background: #000;
}
.loader {
width: 40px;
height: 40px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -13px;
margin-left: -13px;
border-radius: 60px;
animation: loader 0.8s linear infinite;
-webkit-animation: loader 0.8s linear infinite;
}
@keyframes loader {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
border: 4px solid #f44336;
border-left-color: transparent;
}
50% {
-webkit-transform: rotate(180deg);
transform: rotate(180deg);
border: 4px solid #673ab7;
border-left-color: transparent;
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
border: 4px solid #f44336;
border-left-color: transparent;
}
}
@-webkit-keyframes loader {
0% {
-webkit-transform: rotate(0deg);
border: 4px solid #f44336;
border-left-color: transparent;
}
50% {
-webkit-transform: rotate(180deg);
border: 4px solid #673ab7;
border-left-color: transparent;
}
100% {
-webkit-transform: rotate(360deg);
border: 4px solid #f44336;
border-left-color: transparent;
}
}
</code></pre>
<p>I tried googling it and do everything about it but didn't find any solution.</p>
<p>node -v12.16.1</p>
<p>Angular CLI version 9.1.4</p> | 61,522,703 | 2 | 0 | null | 2020-04-30 11:32:32.043 UTC | 1 | 2021-12-01 20:57:48.89 UTC | 2020-09-29 10:51:14.94 UTC | null | 1,168,786 | null | 12,676,390 | null | 1 | 6 | angular|npm|webpack|sass | 38,009 | <p>It seems like you have not defined the variable <code>$white-color</code>. If you want more in depth help it would help if you provided the <code>pickandpay.scss</code> file.</p> |
36,399,000 | "TypeError: 'module' object is not callable" trying to use pprint | <p>I've tried this code to pretty print a <code>dict</code>:</p>
<pre><code>import pprint
pprint({})
</code></pre>
<p>This throws the following error:</p>
<pre><code>Traceback (most recent call last):
File "temp.py", line 3, in <module>
pprint({})
TypeError: 'module' object is not callable
</code></pre>
<p>Why is it not callable?</p> | 36,399,064 | 1 | 1 | null | 2016-04-04 09:32:56.747 UTC | 3 | 2021-08-17 11:00:49.343 UTC | 2016-04-04 09:42:08.333 UTC | null | 402,884 | user5760871 | null | null | 1 | 31 | python|json | 19,330 | <p>Try importing using:</p>
<pre><code>from pprint import pprint
</code></pre>
<p>The <code>pprint()</code> function is in the <code>pprint</code> module.</p> |
56,364,643 | What's the difference between a Docker image's Image ID and its Digest? | <p>This has been surprisingly confusing for me. I thought Docker's Image ID is its SHA256 hash. However, apparently the result from <code>docker image ls --digests</code> (listed under the column header <code>DIGEST</code>) is different from the <code>IMAGE ID</code> of that image.</p>
<p>For example</p>
<pre><code>docker image ls --digests alpine
REPOSITORY TAG DIGEST IMAGE ID CREATED SIZE
alpine latest sha256:769fddc7cc2f0a1c35abb2f91432e8beecf83916c421420e6a6da9f8975464b6 055936d39205 2 weeks ago 5.53MB
</code></pre>
<p>while </p>
<pre><code>docker image ls --no-trunc
REPOSITORY TAG IMAGE ID CREATED SIZE
...
alpine latest sha256:055936d3920576da37aa9bc460d70c5f212028bda1c08c0879aedf03d7a66ea1 2 weeks ago 5.53MB
</code></pre>
<p>Clearly <code>sha256:055936d3920576da37aa9bc460d70c5f212028bda1c08c0879aedf03d7a66ea1</code> (IMAGE ID) and <code>sha256:769fddc7cc2f0a1c35abb2f91432e8beecf83916c421420e6a6da9f8975464b6</code> (DIGEST) are not the same value. But why? What's the purpose of having two different <code>sha256</code> hashes of the same image. How are they calculated, respectively?</p>
<p>I was confused by this when reading the book <em>Docker Deep Dive</em>, and I haven't been able to find a clear answer either in the book or online.</p> | 56,391,252 | 1 | 2 | null | 2019-05-29 16:07:51.51 UTC | 15 | 2019-05-31 08:15:44.857 UTC | null | null | null | null | 1,460,448 | null | 1 | 79 | docker|hash|sha256 | 18,600 | <p>Thanks for michalk's comment. The short answer is:</p>
<ul>
<li>The "digest" is a hash of the manifest, introduced in Docker registry v2.</li>
<li>The image ID is a hash of the local image JSON configuration.</li>
</ul> |
24,416,847 | How to force GridView to generate square cells in Android | <p>How can I force an android GridView to generate square cells (Cell's height equal to cell's width)
GridView has 10*9 cells and the app must support multiple screens !</p>
<p>I used a Linear Layout:</p>
<p><strong>row_grid.xml</strong></p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="0dp" >
<ImageView
android:id="@+id/item_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/ic_launcher" >
</ImageView>
</LinearLayout>
</code></pre>
<p>and GridView:
<strong>activity_main.xml</strong></p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/katy" >
<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="0dp"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="0dp" >
</GridView>
</RelativeLayout>
</code></pre>
<p>Each cell of GridView contains a image that has same width and height.
images are larger than cells and must stretch to fit in cells.
<img src="https://i.stack.imgur.com/YnSwU.png" alt="enter image description here"></p> | 24,416,992 | 6 | 0 | null | 2014-06-25 19:21:13.957 UTC | 15 | 2021-04-03 18:16:28.193 UTC | 2016-06-24 09:09:27.11 UTC | null | 978,302 | null | 3,046,710 | null | 1 | 33 | android|gridview|layout | 30,922 | <p>First, you're going to want to create a custom View class that you can use instead of the default LinearLayout you're using. Then you want to override the View's onMeasure call, and force it to be square:</p>
<pre><code>public class GridViewItem extends ImageView {
public GridViewItem(Context context) {
super(context);
}
public GridViewItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GridViewItem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec); // This is the key that will make the height equivalent to its width
}
}
</code></pre>
<p>Then you can change your row_grid.xml file to:</p>
<pre><code><path.to.item.GridViewItem xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/ic_launcher" >
</path.to.item.GridViewItem>
</code></pre>
<p>Just be sure to change "path.to.item" to the package where your GridViewItem.java class resides. </p>
<p>I also removed your LinearLayout parent since it wasn't doing anything for you there.</p>
<p>Edit:</p>
<p>Also changed scaleType from fitXY to centerCrop so that your image doesn't stretch itself and maintains its aspect ratio. And, as long as it's a square image, nothing should be cropped, regardless.</p> |
24,251,020 | Write device platform specific code in Xamarin.Forms | <p>I have the following <code>Xamarin.Forms.ContentPage</code> class structure</p>
<pre><code>public class MyPage : ContentPage
{
public MyPage()
{
//do work to initialize MyPage
}
public void LogIn(object sender, EventArgs eventArgs)
{
bool isAuthenticated = false;
string accessToken = string.Empty;
//do work to use authentication API to validate users
if(isAuthenticated)
{
//I would to write device specific code to write to the access token to the device
//Example of saving the access token to iOS device
NSUserDefaults.StandardUserDefaults.SetString(accessToken, "AccessToken");
//Example of saving the access token to Android device
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
var prefsEditor = prefs.Edit();
prefEditor.PutString("AccessToken", accessToken);
prefEditor.Commit();
}
}
}
</code></pre>
<p>I would like to write platform specific code in the <code>MyPage</code> <code>LogIn</code> method to save the access token based on which device OS they are using my application on.</p>
<p>How do I only run device specific code when the user uses my application on their device?</p> | 24,251,871 | 5 | 0 | null | 2014-06-16 19:43:09.827 UTC | 18 | 2020-06-10 00:27:54.17 UTC | null | null | null | null | 26,327 | null | 1 | 32 | c#|xamarin.ios|xamarin|xamarin.android|xamarin.forms | 36,595 | <p>This is a scenario which is easily resolved with dependency injection.</p>
<p>Have a interface with the desired methods on your shared or PCL code, like:</p>
<pre><code>public interface IUserPreferences
{
void SetString(string key, string value);
string GetString(string key);
}
</code></pre>
<p>Have a property on your <code>App</code> class of that interface:</p>
<pre><code>public class App
{
public static IUserPreferences UserPreferences { get; private set; }
public static void Init(IUserPreferences userPreferencesImpl)
{
App.UserPreferences = userPreferencesImpl;
}
(...)
}
</code></pre>
<p>Create platform-specific implementations on your target projects:</p>
<p>iOS:</p>
<pre><code>public class iOSUserPreferences : IUserPreferences
{
public void SetString(string key, string value)
{
NSUserDefaults.StandardUserDefaults.SetString(key, value);
}
public string GetString(string key)
{
(...)
}
}
</code></pre>
<p>Android:</p>
<pre><code>public class AndroidUserPreferences : IUserPreferences
{
public void SetString(string key, string value)
{
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
var prefsEditor = prefs.Edit();
prefEditor.PutString(key, value);
prefEditor.Commit();
}
public string GetString(string key)
{
(...)
}
}
</code></pre>
<p>Then on each platform-specific project create an implementation of <code>IUserPreferences</code> and set it using either <code>App.Init(new iOSUserPrefernces())</code> and <code>App.Init(new AndroidUserPrefernces())</code> methods.</p>
<p>Finally, you could change your code to:</p>
<pre><code>public class MyPage : ContentPage
{
public MyPage()
{
//do work to initialize MyPage
}
public void LogIn(object sender, EventArgs eventArgs)
{
bool isAuthenticated = false;
string accessToken = string.Empty;
//do work to use authentication API to validate users
if(isAuthenticated)
{
App.UserPreferences.SetString("AccessToken", accessToken);
}
}
}
</code></pre> |
42,805,128 | Does Jest reset the JSDOM document after every suite or test? | <p>I'm testing a couple of components that reach outside of their DOM structure when mounting and unmounting to provide specific interaction capability that wouldn't be possible otherwise.</p>
<p>I'm using Jest and the default JSDOM initialization to create a browser-like environment within node. I couldn't find anything in the documentation to suggest that Jest reset JSDOM after every test execution, and there's no explicit documentation on how to do that manually if that is not the case.</p>
<p>My question is, does Jest reset the JSDOM instance after every test, suite or does it keep a single instance of JSDOM across all test runs? If so, how can I control it?</p> | 50,800,473 | 3 | 1 | null | 2017-03-15 09:00:00.317 UTC | 8 | 2022-07-14 17:22:07.09 UTC | 2017-03-15 11:02:11.917 UTC | null | 46,588 | null | 46,588 | null | 1 | 41 | testing|jestjs|jsdom | 18,833 | <p>To correct the (misleading) accepted answer and explicitly underline that very important bit of information from one of the previous comments:</p>
<blockquote>
<p>No. Jest <strong>does not</strong> clean the JSDOM document after each test run! It only clears the DOM after all tests inside an entire file are completed.</p>
</blockquote>
<p>That means that <strong>you have to manually cleanup your resources</strong> created during a test, after every single test run. Otherwise it will cause shared state, which results in very subtle errors that can be incredibly hard to track. </p>
<p>The following is a very simple, yet effective method to cleanup the JSDOM after each single test inside a jest test suite:</p>
<pre><code>describe('my test suite', () => {
afterEach(() => {
document.getElementsByTagName('html')[0].innerHTML = '';
});
// your tests here ...
});
</code></pre> |
19,863,368 | How to change the legend edgecolor and facecolor in matplotlib | <p>Is there while <code>rcParams['legend.frameon'] = 'False'</code> a simple way to fill the legend area background with a given colour. More specifically I would like the grid not to be seen on the legend area because it disturbs the text reading.</p>
<p>The keyword <code>framealpha</code> sounds like what I need but it doesn't change anything.</p>
<pre><code>import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['legend.frameon'] = 'False'
plt.plot(range(5), label = u"line")
plt.grid(True)
plt.legend(loc = best)
plt.show()
</code></pre>
<p>I've also tried: </p>
<pre><code>legend = plt.legend(frameon = 1)
frame = legend.get_frame()
frame.set_color('white')
</code></pre>
<p>but then I need to ask how can I change the background colour while keeping the frame on? Sometimes I want it ON with a background colour other than white. And also, is there a way of changing the colour of the frame? With the above code I was expecting to change the colour of the frame only, not the background.</p> | 19,863,736 | 3 | 0 | null | 2013-11-08 16:00:32.247 UTC | 4 | 2021-05-16 07:04:21.393 UTC | 2021-05-16 07:04:21.393 UTC | null | 7,758,804 | null | 1,850,133 | null | 1 | 50 | python|matplotlib | 65,484 | <p>You can set the edge color and the face color separately like this:</p>
<pre><code>frame.set_facecolor('green')
frame.set_edgecolor('red')
</code></pre>
<p>There's more information under FancyBboxPatch <a href="http://matplotlib.org/api/artist_api.html">here</a>. </p> |
1,492,335 | Read Text file Programmatically using Objective-C | <p>I am new to iPhone Programming</p>
<p>I want to read the content of text file which is in my Resourse folder. i did a lot of googling but failed to get proper way for doing this task.</p>
<p>Please suggest</p> | 1,493,222 | 2 | 0 | null | 2009-09-29 12:47:46.29 UTC | 20 | 2015-02-01 04:38:55.19 UTC | 2012-05-22 12:36:55.76 UTC | null | 219,922 | null | 178,978 | null | 1 | 62 | iphone|text|file | 63,932 | <p>The files in your <em>"Resource folder"</em> are actually the contents of your application bundle. So first you need to get the path of the file within your application bundle.</p>
<pre><code>NSString* path = [[NSBundle mainBundle] pathForResource:@"filename"
ofType:@"txt"];
</code></pre>
<p>Then loading the content into a <code>NSString</code> is even easier.</p>
<pre><code>NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
</code></pre>
<p>As a bonus you can have different localized versions of <em><code>filename.txt</code></em> and this code will fetch the file of the currently selected language correctly.</p> |
1,829,216 | How can I programmatically obtain the max_length of a Django model field? | <p>Say I have a Django class something like this:</p>
<pre><code>class Person(models.Model):
name = models.CharField(max_length=50)
# ...
</code></pre>
<p>How can I programatically obtain the <code>max_length</code> value for the <code>name</code> field?</p> | 1,829,286 | 2 | 0 | null | 2009-12-01 21:56:14.943 UTC | 10 | 2022-02-15 14:44:55.533 UTC | 2009-12-02 11:10:06.273 UTC | null | 63,550 | null | 42,974 | null | 1 | 84 | python|django|django-models|oop | 14,994 | <p><code>Person._meta.get_field('name').max_length</code> will give you this value. <s>But having to use <code>_meta</code> suggests this is something you shouldn't do in normal usage.</s></p>
<p>Edit: as Carl pointed out, this naming is misleading and it does seem quite acceptable to use it: <a href="http://www.b-list.org/weblog/2007/nov/04/working-models/" rel="nofollow noreferrer">http://www.b-list.org/weblog/2007/nov/04/working-models/</a></p>
<p>Read more at Django Docs:
<a href="https://docs.djangoproject.com/en/dev/ref/models/meta/#django.db.models.options.Options.get_field" rel="nofollow noreferrer">https://docs.djangoproject.com/en/dev/ref/models/meta/#django.db.models.options.Options.get_field</a></p> |
63,978,396 | Launch Screen not working on iOS 14 with Xcode 12 | <p>I am very frustrated now. I upgraded Xcode to version 12 and tested my app on iOS 14. Now the problem is, that my launch screen is just showing in black. I tested it with an iOS 13.5 device and it is still working as expected. I tried to remove the launchscreen.storyboard approach and added the Launch Screen key in the info.plist, but then the image is scaled to full size.</p>
<p>Now I tested a little bit with the launchscreen.storyboard and I found a few things.</p>
<ul>
<li>If I remove the Image view, the launch screen is showing as expected. I added just a label and that would work.</li>
<li>If I use an image from the system in the image view, it is working as well. It is just not working when I am using an image from the project.</li>
</ul>
<p>Did you experience issues with iOS 14 and the storyboard approach?</p>
<p>If yes, how did you fix it?</p> | 64,392,586 | 23 | 2 | null | 2020-09-20 11:18:07.697 UTC | 6 | 2022-09-14 01:47:29.11 UTC | 2020-09-21 19:02:56.683 UTC | null | 1,265,393 | null | 10,695,304 | null | 1 | 52 | ios|xcode|launch-screen | 26,687 | <p>So here are a lot of good ideas, but I was able to finally solve the issue - it is more like a workaround. I needed to store the picture outside the Images.xcassets folder and then it started to work again. This is a very weird issue.</p> |
32,192,163 | Python AND operator on two boolean lists - how? | <p>I have two boolean lists, e.g.,</p>
<pre><code>x=[True,True,False,False]
y=[True,False,True,False]
</code></pre>
<p>I want to AND these lists together, with the expected output:</p>
<pre><code>xy=[True,False,False,False]
</code></pre>
<p>I thought that expression <code>x and y</code> would work, but came to discover that it does not: in fact, <code>(x and y) != (y and x)</code></p>
<p>Output of <code>x and y</code>: <code>[True,False,True,False]</code></p>
<p>Output of <code>y and x</code>: <code>[True,True,False,False]</code></p>
<p>Using list comprehension <em>does</em> have correct output. Whew!</p>
<pre><code>xy = [x[i] and y[i] for i in range(len(x)]
</code></pre>
<p>Mind you I could not find any reference that told me the AND operator would work as I tried with x and y. But it's easy to try things in Python.
Can someone explain to me what is happening with <code>x and y</code>?</p>
<p>And here is a simple test program:</p>
<pre><code>import random
random.seed()
n = 10
x = [random.random() > 0.5 for i in range(n)]
y = [random.random() > 0.5 for i in range(n)]
# Next two methods look sensible, but do not work
a = x and y
z = y and x
# Next: apparently only the list comprehension method is correct
xy = [x[i] and y[i] for i in range(n)]
print 'x : %s'%str(x)
print 'y : %s'%str(y)
print 'x and y : %s'%str(a)
print 'y and x : %s'%str(z)
print '[x and y]: %s'%str(xy)
</code></pre> | 32,192,248 | 10 | 1 | null | 2015-08-24 21:38:24.233 UTC | 13 | 2021-10-20 14:15:00.443 UTC | null | null | null | null | 814,719 | null | 1 | 59 | python|list|boolean|operator-keyword | 66,779 | <p><code>and</code> simply returns either the first or the second operand, based on their truth value. If the first operand is considered false, it is returned, otherwise the other operand is returned.</p>
<p>Lists are considered <em>true</em> when <em>not empty</em>, so both lists are considered true. Their contents <em>don't play a role here</em>.</p>
<p>Because both lists are not empty, <code>x and y</code> simply returns the second list object; only if <code>x</code> was empty would it be returned instead:</p>
<pre><code>>>> [True, False] and ['foo', 'bar']
['foo', 'bar']
>>> [] and ['foo', 'bar']
[]
</code></pre>
<p>See the <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="noreferrer"><em>Truth value testing</em> section</a> in the Python documentation:</p>
<blockquote>
<p>Any object can be tested for truth value, for use in an <code>if</code> or <code>while</code> condition or as operand of the Boolean operations below. The following values are considered false:</p>
<p>[...]</p>
<ul>
<li>any empty sequence, for example, <code>''</code>, <code>()</code>, <code>[]</code>.</li>
</ul>
<p>[...]</p>
<p><strong>All other values are considered true</strong> — so objects of many types are always true.</p>
</blockquote>
<p>(emphasis mine), and the <a href="https://docs.python.org/2/library/stdtypes.html#boolean-operations-and-or-not" rel="noreferrer"><em>Boolean operations</em> section</a> right below that:</p>
<blockquote>
<p><code>x and y</code><br>
if <em>x</em> is false, then <em>x</em>, else <em>y</em></p>
<p>This is a short-circuit operator, so it only evaluates the second argument if the first one is <code>True</code>.</p>
</blockquote>
<p>You indeed need to test the values <em>contained</em> in the lists explicitly. You can do so with a list comprehension, as you discovered. You can rewrite it with the <a href="https://docs.python.org/2/library/functions.html#zip" rel="noreferrer"><code>zip()</code> function</a> to pair up the values:</p>
<pre><code>[a and b for a, b in zip(x, y)]
</code></pre> |
5,790,962 | remove all characters after pattern in text file | <p>I have a text file with thousands of lines of text. Each line ends like </p>
<pre><code>\\server\share\file.txt -> information
</code></pre>
<p>I want to remove everything following the space after the end of the file extension. So everything after " ->" (there's a space after the first quote)</p>
<p>How would you do this? I'd like to use vim as I am trying to understand more about it, but any program will do; I'd like to get this done soon. </p> | 5,791,226 | 5 | 1 | null | 2011-04-26 13:19:45.05 UTC | 5 | 2011-04-26 20:13:05.593 UTC | null | null | null | null | 550,779 | null | 1 | 13 | regex|vim | 47,961 | <p>Your description is contradictory.</p>
<ol>
<li>"everything following the space after the end of the file extension"</li>
<li>"So everything after " ->" (there's a space after the first quote)"</li>
</ol>
<p>Did you want to keep the arrow or not?</p>
<p>1 is simply accomplished with:</p>
<pre><code>:%s/ ->.*/
</code></pre>
<p>and actually if you really did want to keep the space before the arrow, like you said, it would be:</p>
<pre><code>:%s/ ->.*/ /
</code></pre>
<p>2 can be done with:</p>
<pre><code>:%s/\( ->\).*/\1/
</code></pre>
<p>If you prefer to view the results of your search before the replace you can build your search first using /:</p>
<pre><code>/\( ->\).*
</code></pre>
<p>This will highlight all results to make sure you are replacing the right thing. You can then execute the replace command with an empty search term to use the last search (the stuff thats highlighted).</p>
<pre><code>:%s//\1/
</code></pre> |
6,062,908 | How can I test an outbound connection to an IP address as well as a specific port? | <p>OK, we all know how to use PING to test connectivity to an IP address. What I need to do is something similar but test if my outbound request to a given IP Address as well as a specif port (in the present case 1775) is successful. The test should be performed preferably from the command prompt.</p> | 6,062,957 | 6 | 2 | null | 2011-05-19 18:03:50.063 UTC | 11 | 2017-08-03 15:45:41.553 UTC | null | null | null | null | 342,994 | null | 1 | 15 | ip | 70,410 | <p>If there is a server running on the target IP/port, you could use Telnet. Any response other than "can't connect" would indicate that you were able to connect.</p> |
6,123,434 | Obtain the Linux UID of an Android App | <p>I would like to be able to get the Linux UID (user ID) of an installed Android application.</p>
<p>Excerpt from <a href="http://developer.android.com/guide/topics/security/security.html">Security and Permissions</a>: "At install time, Android gives each package a distinct Linux user ID. The identity remains constant for the duration of the package's life on that device."</p>
<p>Is there a way to retrieve this UID?</p> | 6,124,626 | 6 | 0 | null | 2011-05-25 11:04:18.047 UTC | 16 | 2020-03-10 13:07:39.003 UTC | null | null | null | null | 609,444 | null | 1 | 32 | android|linux|uid | 34,695 | <p>Use <code>PackageManager</code> and <code>getApplicationInfo()</code>.</p> |
5,622,202 | How to resize AlertDialog on the Keyboard display | <p>I have a <code>AlertDialog</code> box with approximately 10 controls (text and <code>TextView</code>) on it. These controls are in a <code>ScrollView</code> with <code>AlertDialog</code>, plus I got 2 buttons positive and negative. The issue I have is when the soft keyboard pops up the two buttons are hidden behind the keyboard. </p>
<p>I was looking for something like redraw function on my inner View or the dialog box. Below is the screen shot of what I am talking about. </p>
<p><img src="https://i.stack.imgur.com/gRQw3.png" alt="enter image description here"></p> | 7,435,225 | 7 | 0 | null | 2011-04-11 13:43:20.93 UTC | 13 | 2021-04-15 13:25:36.753 UTC | 2018-06-25 09:22:22.09 UTC | null | 6,618,622 | null | 685,754 | null | 1 | 40 | android|view|resize|android-alertdialog|android-softkeyboard | 35,820 | <p>If your dialog was an activity using one of the Dialog themes you could effect this behavior by setting the <code>adjustResize</code> flag for the <code>windowSoftInputMode</code> parameter of the activity.</p>
<p>I'm using:</p>
<pre><code>android:windowSoftInputMode="adjustResize|stateHidden"
</code></pre>
<p>I think you can still use this flag with regular dialogs, but I'm not sure how to apply it. You may have to create your AlertDialog with a custom theme that inherits the right parent theme and also sets that flag, or you might have to use ContextThemeWrappers and stuff.</p>
<p>Or maybe you can just use <a href="http://developer.android.com/reference/android/view/Window.html#setSoftInputMode(int)" rel="noreferrer">Window#setSoftInputMode</a>.</p>
<pre><code>alertDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
</code></pre> |
6,257,131 | Are multiple variable assignments done by value or reference? | <pre><code>$a = $b = 0;
</code></pre>
<p>In the above code, are both <code>$a</code> and <code>$b</code> assigned the value of <code>0</code>, or is <code>$a</code> just referencing <code>$b</code>?</p> | 6,257,203 | 7 | 0 | null | 2011-06-06 19:42:09.947 UTC | 4 | 2015-02-21 18:14:30.733 UTC | 2015-02-21 18:14:30.733 UTC | null | 55,075 | null | 469,437 | null | 1 | 42 | php|variables|variable-assignment | 32,951 | <p>With raw types this is a copy. </p>
<p><strong>test.php</strong></p>
<pre><code>$a = $b = 0;
$b = 3;
var_dump($a);
var_dump($b);
</code></pre>
<p><strong>Output</strong>:</p>
<pre><code>int(0)
int(3)
</code></pre>
<p>With objects though, that is another story (PHP 5)</p>
<p><strong>test.php</strong></p>
<pre><code>class Obj
{
public $_name;
}
$a = $b = new Obj();
$b->_name = 'steve';
var_dump($a);
var_dump($b);
</code></pre>
<p><strong>Output</strong></p>
<pre><code>object(Obj)#1 (1) { ["_name"]=> string(5) "steve" }
object(Obj)#1 (1) { ["_name"]=> string(5) "steve" }
</code></pre> |
6,080,040 | You have already activated rake 0.9.0, but your Gemfile requires rake 0.8.7 | <p>I'm trying to run rails project,
I get </p>
<pre><code>Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
</code></pre>
<p>If I do: "bundle install"</p>
<p>but
I'm getting </p>
<pre><code>You have already activated rake 0.9.0, but your Gemfile requires rake 0.8.7
</code></pre>
<p>while doing</p>
<pre><code>rake db:migrate
</code></pre> | 6,088,381 | 9 | 0 | null | 2011-05-21 06:26:27.45 UTC | 36 | 2017-10-23 11:24:23.84 UTC | 2011-05-21 06:33:02.99 UTC | null | 472,043 | null | 472,043 | null | 1 | 127 | ruby-on-rails|rake | 68,877 | <p>I thank to Dobry Den, cheers dude. but little more I had to do.
here is solution (works for me).
I had added</p>
<pre><code>gem 'rake','0.8.7'
</code></pre>
<p>on Gemfile, which was not there, but my new version of rails automatically install rake(0.9.0).</p>
<p>after I had delete rake0.9.0 by <code>gem uninstall rake</code>
and after doing <code>bundle update rake</code> , I can create and migrate database. </p> |
6,156,639 | X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode | <p>I am quite confused. I should be able to set </p>
<pre class="lang-xml prettyprint-override"><code><meta http-equiv="X-UA-Compatible" content="IE=edge" />
</code></pre>
<p>and IE8 and IE9 should render the page using the latest rendering engine. However, I just tested it, and if Compatibility Mode is turned on elsewhere on our site, it will stay on for <a href="http://wds.semo.edu/help/" rel="noreferrer">our page</a>, even though we should be forcing it not to. </p>
<p>How are you supposed to make sure IE does <strong>not</strong> use Compatibility Mode (even in an intranet)?</p>
<p>FWIW, I am using the HTML5 DocType declaration (<code><!doctype html></code>).</p>
<p>Here are the first few lines of the page:</p>
<pre class="lang-xml prettyprint-override"><code><!doctype html>
<!--[if lt IE 7 ]> <html lang="en" class="innerpage no-js ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="innerpage no-js ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="innerpage no-js ie8"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html lang="en" class="innerpage no-js">
<!--<![endif]-->
<head>
<meta charset="ISO-8859-1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
</code></pre>
<p>EDIT: <a href="https://docs.microsoft.com/archive/blogs/ie/introducing-compatibility-view" rel="noreferrer">I just learned</a> that the default setting on IE8 is to use IE7 compatibility mode for intranet sites. Would this override the X-UA-Compatible meta tag?</p> | 9,338,959 | 18 | 3 | null | 2011-05-27 19:07:32.113 UTC | 143 | 2020-02-24 00:48:33.647 UTC | 2020-02-24 00:48:33.647 UTC | null | 4,415,734 | null | 126,329 | null | 1 | 253 | internet-explorer|ie8-compatibility-mode|x-ua-compatible | 384,851 | <p>If you need to override IE's Compatibility View Settings for intranet sites you can do so in the web.config (IIS7) or through the <a href="http://www.iis.net/configreference/system.webserver/httpprotocol" rel="noreferrer">custom HTTP headers</a> in the web site's properties (IIS6) and set X-UA-Compatible there. The meta tag doesn't override IE's intranet setting in Compatibility View Settings, but if you set it at the hosting server it will override the compatibility.</p>
<p>Example for web.config in IIS7:</p>
<pre class="lang-xml prettyprint-override"><code><system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=EmulateIE8" />
</customHeaders>
</httpProtocol>
</system.webServer>
</code></pre>
<p><strong>Edit</strong>: I removed the <code>clear</code> code from just before the <code>add</code>; it was an unnecessary oversight from copying and pasting. Good catch, commenters!</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.