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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,168,961 | how to deserialize an xml node with a value and an attribute using asp.net serialization | <p>I have 4 small classes to deserialize xml from an incomming xml poll, to usable classes to build up the poll.</p>
<p>now, i know how to set a property from a class, to match a certain attribute or element in the xml, and if that element is just a string thats easy
but what if the element also has an attribute like in the following example?</p>
<pre><code><Questions>
<Question id="a guid">
<AnswerItems>
<AnswerItem Id="a guid">3</AnswerItem>
<AnswerItem Id="a guid">2</AnswerItem>
<AnswerItem Id="a guid">5</AnswerItem>
</AnswerItems>
</Question>
</Questions>
</code></pre>
<p>the question class would look like this:</p>
<pre><code>[Serializable()]
public class Question
{
[XmlAttribute("Id")]
public Guid QuestionId { get; set; }
[XmlArray("AnswerItems")]
[XmlArrayItem("AnswerItem", typeof(AnswerItem))]
public AnswerItem[] AnswerItems { get; set; }
}
[Serializable()]
public class AnswerItem
{
[XmlAttribute("Id")]
public Guid QuestionId { get; set; }
// how do i fetch the value of this node?
// its not a XmlElement and it's not an XmlValue
}
</code></pre>
<p>Ok, so the value of an AnswerItem node, that is what i want to get as well.
i could easily not use the AnswerItem class, and just use an XmlArray AnswerItems of the type String and put the values in the array, but then i would lose the AnswerItem's Id Attribute.</p> | 6,169,042 | 1 | 0 | null | 2011-05-29 16:40:03.81 UTC | 4 | 2011-05-29 16:54:39.277 UTC | null | null | null | null | 109,341 | null | 1 | 29 | c#|xml|c#-4.0|xml-serialization | 24,328 | <p>In <code>AnswerItem</code>, make a property called <code>Value</code> and mark it with the <code>XmlText</code> attribute. This setting will cause the <code>XmlSerializer</code> to read the text in the <code>AnswerItem</code> element into the <code>Value</code> property.</p>
<pre><code>[Serializable()]
public class AnswerItem
{
[XmlAttribute("Id")]
public Guid QuestionId { get; set; }
[XmlText]
public string Value { get; set; }
}
</code></pre> |
53,151,340 | MUI and TypeScript: How to use !important? | <p>I'm building a React application and I'm using MUI for my components. I wonder how I can give an <code>!important</code> property to a style?</p>
<p>I tried this:</p>
<pre><code><Paper className="left"...>
</code></pre>
<p>I'm using <a href="https://mui.com/guides/typescript/#usage-of-withstyles" rel="noreferrer"><code>withStyles</code> and <code>WithStyles</code></a>.
Then in my <code>styles.ts</code>:</p>
<pre><code>left: {
display: "block",
float: "left!important",
},
</code></pre>
<p>But this throws the error:</p>
<pre><code>[ts] Type '"left!important"' is not assignable to type '"right" | "none" | "left" | "-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "inline-end" | "inline-start" | undefined'.
index.d.ts(1266, 3): The expected type comes from property 'float' which is declared here on type 'CSSProperties'
(property) StandardLonghandProperties<TLength = string | 0>.float?: "right" | "none" | "left" | "-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "inline-end" | "inline-start" | undefined
</code></pre>
<p>How would one assign an <code>!important</code> flag when using material-ui with TypeScript?</p> | 54,261,141 | 4 | 0 | null | 2018-11-05 09:13:22.683 UTC | 1 | 2022-01-25 18:44:28.453 UTC | 2021-11-04 02:27:14.913 UTC | null | 9,449,426 | null | 8,331,756 | null | 1 | 30 | reactjs|typescript|material-ui|jss | 28,516 | <p>You can just cast it. For example:</p>
<pre><code>left: {
display: "block",
float: "left!important" as any,
},
</code></pre>
<p>or</p>
<pre><code>left: {
display: "block",
float: "left!important" as "left",
},
</code></pre>
<p>Here's a <a href="http://www.typescriptlang.org/play/#src=type%20CSSProps%20%3D%20%7B%0A%20%20%20%20display%3A%20%22block%22%20%7C%20%22inline%22%0A%20%20%20%20float%3A%20%22left%22%20%7C%20%22right%22%0A%7D%0A%0Aconst%20test1%3A%20CSSProps%20%3D%20%7B%0A%20%20%20%20display%3A%20%22block%22%2C%0A%20%20%20%20float%3A%20%22left%20!important%22%2C%20%2F%2F%20this%20is%20the%20problem.%0A%7D%0A%0Aconst%20test2%3A%20CSSProps%20%3D%20%7B%0A%20%20%20%20display%3A%20%22block%22%2C%0A%20%20%20%20float%3A%20%22left%20!important%22%20as%20any%2C%20%2F%2F%20works%0A%7D%0A%0Aconst%20test3%3A%20CSSProps%20%3D%20%7B%0A%20%20%20%20display%3A%20%22block%22%2C%0A%20%20%20%20float%3A%20%22left%20!important%22%20as%20%22left%22%2C%20%2F%2F%20works%0A%7D" rel="noreferrer">playground example</a>.</p> |
35,540,885 | Display the contents of a log file as it is updated | <p>I have external programs such as ffmpeg and gstreamer running in the background and writing to a log file. I want to display the contents of this log with my Flask application, so that the user can watch the log update, like <code>tail -f job.log</code> would do in the terminal.</p>
<p>I tried to use <code><object data="/out.log" type="text/plain"></code> to point at the log file, but that failed to show the data, or the browser told me I needed a plugin.</p>
<p>How can I embed and update the log file in an HTML page?</p> | 35,541,970 | 3 | 0 | null | 2016-02-21 19:27:31.307 UTC | 18 | 2021-09-24 17:09:01.343 UTC | 2016-02-21 21:04:27.287 UTC | null | 400,617 | null | 4,857,864 | null | 1 | 28 | javascript|python|flask|stream | 31,071 | <p>Use a Flask view to continuously read from the file forever and stream the response. Use JavaScript to read from the stream and update the page. This example sends the entire file, you may want to truncate that at some point to save bandwidth and memory. This example sleeps between reads to reduce cpu load from the endless loop and allow other threads more active time.</p>
<pre><code>from time import sleep
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/stream')
def stream():
def generate():
with open('job.log') as f:
while True:
yield f.read()
sleep(1)
return app.response_class(generate(), mimetype='text/plain')
app.run()
</code></pre>
<pre class="lang-html prettyprint-override"><code><pre id="output"></pre>
<script>
var output = document.getElementById('output');
var xhr = new XMLHttpRequest();
xhr.open('GET', '{{ url_for('stream') }}');
xhr.send();
setInterval(function() {
output.textContent = xhr.responseText;
}, 1000);
</script>
</code></pre>
<p>This is almost the same as <a href="https://stackoverflow.com/a/31951077/400617">this answer</a>, which describes how to stream and parse messages, although reading from an external file forever was novel enough to be it's own answer. The code here is simpler because we don't care about parsing messages or ending the stream, just tailing the file forever.</p> |
28,727,919 | Angularjs Uncaught Error: [$injector:modulerr] when migrating to V1.3 | <p>I am learning Angular.js and I am not able to figure out whats wrong with this simple code. It seems to look fine but giving me following error.</p>
<pre class="lang-none prettyprint-override"><code>**Error**: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A17%3A381)
</code></pre>
<p>And before adding <code>ng-app=<strong>"app"</strong></code> (I was just keeping it as <code>ng-app</code>) it was giving me following errors. Why is that?</p>
<pre class="lang-none prettyprint-override"><code>Error: [ng:areq] http://errors.angularjs.org/1.3.14/ng/areq?p0=Ctrl&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:6:417
at Sb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:19:510)
at tb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:20:78)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:75:331)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:57:65
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:7:408)
at A (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:56:443)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:51:299)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:51:316)
</code></pre>
<pre><code><!doctype html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
<input ng-model="name">
<h1>{{name}}</h1>
<h2>{{age}}</h2>
</div>
<script>
var Ctrl = function($scope)
{
$scope.age = 24;
};
</script>
</body>
</html>
</code></pre> | 28,728,380 | 5 | 0 | null | 2015-02-25 19:29:29.687 UTC | 2 | 2021-08-27 08:21:07.847 UTC | 2017-11-16 01:32:04.987 UTC | null | 5,535,245 | null | 1,820,739 | null | 1 | 14 | javascript|angularjs|angularjs-scope|angularjs-service|angularjs-controller | 60,722 | <p>After AngularJS version 1.3 global controller function declaration is disabled</p>
<p>You need to first create an AngularJS module & then attach all the components to that specific module.</p>
<p><strong>CODE</strong></p>
<pre><code>function Ctrl($scope) {
$scope.age = 24;
}
angular.module('app', [])
.controller('Ctrl', ['$scope', Ctrl]);
</code></pre>
<p>Specifically for your case, there is some issue with AngularJS <strong><code>1.3.14</code></strong> (downgrade it to <strong><code>1.3.13</code></strong> works fine). Though I'd prefer you to use <strike>angular 1.2.27</strike> AngularJS 1.6.X, Which is more stable version & latest release of AngularJS.</p>
<p><a href="http://plnkr.co/edit/2QhTn6sAX2fMyX7rpRRb?p=preview" rel="nofollow noreferrer"><strong>Working Plunkr</strong></a></p>
<p><strong>UPDATE:</strong></p>
<p>You could do your current code to working state by allow global controller declaration inside <code>angular.config</code>. But this isn't the correct way to run angular application.</p>
<pre><code>function Ctrl($scope) {
$scope.age = 24;
}
angular.module('app', [])
.config(['$controllerProvider',
function ($controllerProvider) {
$controllerProvider.allowGlobals();
}
]);
</code></pre> |
56,675,652 | Proper TypeScript type for creating JSX element from string | <p>I have a component that I want to default to being rendered as an <code>h2</code>. I'd like the consumer to be able to specify a different element if they desire. The code below results in the error:</p>
<p><code>TS2604 - JSX element type 'ElementType' does not have any construct or call signatures</code></p>
<p>I think I understand why it fails, TS is expecting to render a React node. For clarity, React <em>is</em> able to render elements referenced as strings as long as the variable begins with a capital letter (this being a JSX requirement). I've done this before successfully in vanilla JS + React, I just don't know how to satisfy TypeScript.</p>
<p>How can I get TypeScript to render this without resorting to <code>elementType?: any</code></p>
<pre><code>import React, {ReactNode} from 'react'
interface Props {
children: ReactNode;
elementType?: string;
}
export default function ({children, elementType: ElementType = 'h2'}: Props): JSX.Element {
return (
<ElementType>{children}</ElementType>
);
}
</code></pre> | 56,677,879 | 8 | 0 | null | 2019-06-19 20:50:35.787 UTC | 5 | 2022-09-22 16:38:49.923 UTC | 2020-10-08 12:18:59.12 UTC | null | 3,383,693 | null | 2,124,039 | null | 1 | 25 | javascript|reactjs|typescript | 49,399 | <p>First, a bit about JSX. It is just a syntactic sugar for <code>React.createElement</code>, which is a JavaScript expression.</p>
<p>With this knowledge in mind, now let's take a look at why TypeScript complains. You define <code>elementType</code> as <code>string</code>, however, when you actually use it, it becomes a JavaScript expression. <code>string</code> type of course doesn't have any construct or call signature.</p>
<p>Now we know the root cause. In React, there is a type called <code>FunctionComponent</code>. As you can guess, it is a function expression, which is what we want. So you can define <code>elementType</code> as <code>string | FunctionComponent</code>. This should make TypeScript happy :)</p>
<p>FYI: the recommended way to define prop typing is by doing this:</p>
<pre><code>const MyComponent: FunctionComponent<Props> = (props) => {}
</code></pre> |
49,147,475 | Decoding a JSON without keys in Swift 4 | <p>I'm using an API that returns this pretty horrible JSON:</p>
<pre><code>[
"A string",
[
"A string",
"A string",
"A string",
"A string",
…
]
]
</code></pre>
<p>I'm trying to decode the nested array using JSONDecoder, but it doesn't have a single key and I really don't know where to start… Do you have any idea?</p>
<p>Thanks a lot!</p> | 49,149,416 | 3 | 0 | null | 2018-03-07 08:43:03.483 UTC | 10 | 2018-03-07 10:22:05.09 UTC | 2018-03-07 09:25:10.86 UTC | null | 2,058,242 | null | 2,185,649 | null | 1 | 32 | arrays|json|swift|swift4|jsondecoder | 14,017 | <p>If the structure stays the same, you can use this <a href="https://developer.apple.com/documentation/swift/encoding_decoding_and_serialization" rel="noreferrer">Decodable</a> approach.</p>
<p>First create a decodable Model like this:</p>
<pre><code>struct MyModel: Decodable {
let firstString: String
let stringArray: [String]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
firstString = try container.decode(String.self)
stringArray = try container.decode([String].self)
}
}
</code></pre>
<p>Or if you really want to keep the JSON's structure, like this:</p>
<pre><code>struct MyModel: Decodable {
let array: [Any]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let firstString = try container.decode(String.self)
let stringArray = try container.decode([String].self)
array = [firstString, stringArray]
}
}
</code></pre>
<p>And use it like this</p>
<pre><code>let jsonString = """
["A string1", ["A string2", "A string3", "A string4", "A string5"]]
"""
if let jsonData = jsonString.data(using: .utf8) {
let myModel = try? JSONDecoder().decode(MyModel.self, from: jsonData)
}
</code></pre> |
532,447 | How do you use WiX to deploy VSTO 3.0 addins? | <p>I want to deploy a VSTO 3 Application Level Word 2007 addin that I've written with Visual Studio 2008. I see that WiX has an extension named WixOfficeExtension that looks like it might have this functionality, but I can't find any documentation for it, and I can't discern it's purpose from the source code.</p>
<p>Has anyone attempted this before, and were you able to pull it off successfully?</p> | 678,290 | 2 | 0 | null | 2009-02-10 14:01:31.847 UTC | 18 | 2016-01-13 10:14:08.707 UTC | 2016-01-13 10:14:08.707 UTC | null | 274,535 | Jacob | 22,107 | null | 1 | 20 | wix|vsto|ms-office|add-in|wix3 | 9,952 | <p>This is the code I ended up using. I basically ported the examples from <a href="http://msdn.microsoft.com/en-us/library/cc563937.aspx" rel="noreferrer">MSDN</a> to use WiX.</p>
<p><strong>Note:</strong> This specific solution is only for a Word 2007 addin, but the case for Excel is very similar. Simply modify the registry/component checks and keys/values according to the aforementioned <a href="http://msdn.microsoft.com/en-us/library/cc563937.aspx" rel="noreferrer">MSDN Article</a>.</p>
<h2>Inclusion List Custom Action</h2>
<p>In order to run addins with full trust, it must be added to the Inclusion List for the current user. The only way to do this reliably is with a custom action. This is a port of the custom action in the <a href="http://msdn.microsoft.com/en-us/library/cc563937.aspx" rel="noreferrer">article</a> to the new <a href="http://blog.deploymentengineering.com/2008/05/deployment-tools-foundation-dtf-custom.html" rel="noreferrer">Deployment Tools Foundation</a> included with WiX.</p>
<p>To use it, create a new DTF project called VSTOCustomAction and add CustomAction.cs.</p>
CustomAction.cs
<pre><code>using System;
using System.Security;
using System.Security.Permissions;
using Microsoft.Deployment.WindowsInstaller;
using Microsoft.VisualStudio.Tools.Office.Runtime.Security;
namespace VSTOCustomActions
{
public class CustomActions
{
private static string GetPublicKey(Session session)
{
return session["VSTOCustomAction_PublicKey"];
}
private static string GetManifestLocation(Session session)
{
return session["VSTOCustomAction_ManifestLocation"];
}
private static void ErrorMessage(string message, Session session)
{
using (Record r = new Record(message))
{
session.Message(InstallMessage.Error, r);
}
}
[CustomAction]
public static ActionResult AddToInclusionList(Session session)
{
try
{
SecurityPermission permission =
new SecurityPermission(PermissionState.Unrestricted);
permission.Demand();
}
catch (SecurityException)
{
ErrorMessage("You have insufficient privileges to " +
"register a trust relationship. Start Excel " +
"and confirm the trust dialog to run the addin.", session);
return ActionResult.Failure;
}
Uri deploymentManifestLocation = null;
if (Uri.TryCreate(GetManifestLocation(session),
UriKind.RelativeOrAbsolute, out deploymentManifestLocation) == false)
{
ErrorMessage("The location of the deployment manifest is missing or invalid.", session);
return ActionResult.Failure;
}
AddInSecurityEntry entry = new AddInSecurityEntry(deploymentManifestLocation, GetPublicKey(session));
UserInclusionList.Add(entry);
session.CustomActionData.Add("VSTOCustomAction_ManifestLocation", deploymentManifestLocation.ToString());
return ActionResult.Success;
}
[CustomAction]
public static ActionResult RemoveFromInclusionList(Session session)
{
string uriString = session.CustomActionData["VSTOCustomAction_ManifestLocation"];
if (!string.IsNullOrEmpty(uriString))
{
Uri deploymentManifestLocation = new Uri(uriString);
UserInclusionList.Remove(deploymentManifestLocation);
}
return ActionResult.Success;
}
}
}
</code></pre>
<h2>Wix Fragment</h2>
<p>We obviously need the actual WiX file to install the addin. Reference it from your main .wcs file with</p>
<pre><code><FeatureRef Id="MyAddinComponent"/>
</code></pre>
Addin.wcs
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Fragment Id="Word2007Fragment">
<!-- Include the VSTO Custom action -->
<Binary Id="VSTOCustomAction" SourceFile="path\to\VSTOCustomAction.dll"/>
<CustomAction Id="AddToInclusionList" BinaryKey="VSTOCustomAction" DllEntry="AddToInclusionList" Execute="immediate"/>
<CustomAction Id="RemoveFromInclusionList" BinaryKey="VSTOCustomAction" DllEntry="RemoveFromInclusionList" Execute="immediate"/>
<!-- Set the parameters read by the Custom action -->
<!--
The public key that you used to sign your dll, looks something like <RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent></RSAKeyValue>
Take note: There should be no whitespace in the key!
-->
<Property Id="VSTOCustomAction_PublicKey"><![CDATA[Paste you public key here]]></Property>
<CustomAction Id="PropertyAssign_ManifestLocation" Property="VSTOCustomAction_ManifestLocation" Value="[INSTALLDIR]MyAddin.MyAddin.vsto" />
<!-- Properties to check prerequisites -->
<Property Id="VSTORUNTIME">
<RegistrySearch Id="RegistrySearchVsto"
Root="HKLM"
Key="SOFTWARE\Microsoft\vsto runtime Setup\v9.0.30729"
Name="SP"
Type="raw"/>
</Property>
<Property Id="HASWORDPIA">
<ComponentSearch Id="ComponentSearchWordPIA"
Guid="{816D4DFD-FF7B-4C16-8943-EEB07DF989CB}"/>
</Property>
<Property Id="HASSHAREDPIA">
<ComponentSearch Id="ComponentSearchSharedPIA"
Guid="{FAB10E66-B22C-4274-8647-7CA1BA5EF30F}"/>
</Property>
<!-- Feature and component to include the necessary files -->
<Feature Id="MyAddinComponent" Title ="Word 2007 Addin" Level="1" AllowAdvertise="no">
<ComponentRef Id="MyAddinComponent"/>
<Condition Level="0"><![CDATA[NOT ((VSTORUNTIME="#1") AND HASSHAREDPIA AND HASWORDPIA)]]></Condition>
</Feature>
<DirectoryRef Id="INSTALLDIR">
<Component Id="MyAddinComponent" Guid="your component guid here">
<File Name="MyAddin.dll" Source="path\to\MyAddin.dll" />
<File Name="MyAddin.dll.manifest" Source="path\to\MyAddin.dll.manifest" />
<File Name="MyAddin.vsto" Source="path\to\MyAddin.vsto" />
<RegistryKey Root="HKCU"
Key="Software\Microsoft\Office\Word\Addins\MyAddin"
Action="createAndRemoveOnUninstall">
<RegistryValue Type="string" Name="FriendlyName" Value="MyAddin Word 2007 Addin" />
<RegistryValue Type="string" Name="Description" Value="MyAddin Word 2007 Addin" />
<RegistryValue Type="string" Name="Manifest" Value="[INSTALLDIR]MyAddin.vsto|vstolocal" KeyPath="yes"/>
<RegistryValue Type="integer" Name="LoadBehavior" Value="3"/>
</RegistryKey>
</Component>
</DirectoryRef>
<!-- Modify the install sequence to call our custom action -->
<InstallExecuteSequence>
<Custom Action="AddToInclusionList" After="InstallFinalize"><![CDATA[(&MyAddinComponent = 3) AND NOT (!MyAddinComponent = 3)]]></Custom>
<Custom Action="PropertyAssign_ManifestLocation" Before="AddToInclusionList"><![CDATA[(&MyAddinComponent = 3) AND NOT (!MyAddinComponent = 3)]]></Custom>
<Custom Action="RemoveFromInclusionList" After="InstallFinalize"><![CDATA[(&MyAddinComponent = 2) AND NOT (!MyAddinComponent = 2)]]></Custom>
</InstallExecuteSequence>
</Fragment>
</Wix>
</code></pre>
<p>Hope that this saves some time for someone out there.</p> |
751,736 | How to get java Logger output to file by default | <p>Netbeans thoughtfully sprinkles Logger.getLogger(this.getClass().getName()).log(Level. [...]
statements into catch blocks. Now I would like to point them all to a file (and to console).</p>
<p>Every logging tutorial and such only me tells how to get a specific logger to output into a file, but I assume there is a better way than fixing every automatically generated logging statement? Setting a handler for some sort of root logger or something?</p> | 751,827 | 2 | 1 | null | 2009-04-15 13:39:00.247 UTC | 14 | 2012-12-21 17:11:37.39 UTC | null | null | null | null | 26,595 | null | 1 | 28 | java|logging|java.util.logging | 58,672 | <p>I just add the following at startup</p>
<pre><code>Handler handler = new FileHandler("test.log", LOG_SIZE, LOG_ROTATION_COUNT);
Logger.getLogger("").addHandler(handler);
</code></pre>
<p>You can specify your own values for <code>LOG_SIZE</code> and <code>LOG_ROTATION_COUNT</code></p>
<p>You may need adjust the logging level to suit.</p> |
2,705,607 | Sorting a Dictionary in place with respect to keys | <p>I have a dictionary in C# like</p>
<pre><code>Dictionary<Person, int>
</code></pre>
<p>and I want to sort that dictionary <em>in place</em> with respect to keys (a field in class Person). How can I do it? Every available help on the internet is that of lists with no particular example of in place sorting of Dictionary. Any help would be highly appreciated!</p> | 2,705,623 | 7 | 2 | null | 2010-04-24 18:18:18.33 UTC | 11 | 2018-03-02 10:54:04.82 UTC | 2013-11-05 05:58:24.933 UTC | null | 661,933 | null | 302,047 | null | 1 | 89 | c#|sorting|dictionary | 131,658 | <p>You can't sort a <code>Dictionary<TKey, TValue></code> - it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific. You shouldn't rely on it working the same way between versions, as ordering isn't part of its designed functionality.)</p>
<p>You <em>can</em> use <a href="http://msdn.microsoft.com/en-us/library/ms132319.aspx" rel="noreferrer"><code>SortedList<TKey, TValue></code></a> or <a href="http://msdn.microsoft.com/en-us/library/f7fta44c(v=VS.100).aspx" rel="noreferrer"><code>SortedDictionary<TKey, TValue></code></a>, both of which sort by the key (in a configurable way, if you pass an <code>IEqualityComparer<T></code> into the constructor) - might those be of use to you?</p>
<p>Pay little attention to the word "list" in the name <code>SortedList</code> - it's still a dictionary in that it maps keys to values. It's <em>implemented</em> using a list internally, effectively - so instead of looking up by hash code, it does a binary search. <code>SortedDictionary</code> is similarly based on binary searches, but via a tree instead of a list.</p> |
2,813,505 | Get last 5 characters in a string | <p>I want to get the last 5 digits/characters from a string. For example, from <code>"I will be going to school in 2011!"</code>, I would like to get <code>"2011!"</code>.</p>
<p>Any ideas? I know Visual Basic has <code>Right(string, 5)</code>; this didn't work for me and gave me an error.</p> | 2,813,523 | 8 | 4 | null | 2010-05-11 18:44:32.06 UTC | 4 | 2019-09-17 07:50:41.887 UTC | 2014-08-22 23:02:15.923 UTC | null | 707,111 | null | 255,391 | null | 1 | 33 | vb.net | 183,920 | <pre><code>str.Substring(str.Length - 5)
</code></pre> |
2,913,415 | How add class='active' to html menu with php | <p>I want to put my html navigation in a separate php file so when I need to edit it, I only have to edit it once. The problem starts when I want to add the class active to the active page. </p>
<p>I've got three pages and one common file.</p>
<p><strong><em>common.php :</em></strong></p>
<pre><code><?php
$nav = <<<EOD
<div id="nav">
<ul>
<li><a <? if($page == 'one'): ?> class="active"<? endif ?> href="index.php">Tab1</a>/</li>
<li><a href="two.php">Tab2</a></li>
<li><a href="three.php">Tab3</a></li>
</ul>
</div>
EOD;
?>
</code></pre>
<p><strong><em>index.php :</em></strong>
All three pages are identical except their $page is different on each page.</p>
<pre><code> <?php
$page = 'one';
require_once('common.php');
?>
<html>
<head></head>
<body>
<?php echo $nav; ?>
</body>
</html>
</code></pre>
<p>This simply won't work unless I put my nav on each page, but then the whole purpose of separating the nav from all pages is ruined.</p>
<p>Is what I want to accomplish even possible? What am I doing wrong?</p>
<p>Thanks</p>
<p>EDIT: When doing this, the php code inside the li don't seem to run, it's just being printed as if it was html </p> | 2,913,677 | 14 | 3 | null | 2010-05-26 13:34:28.75 UTC | 13 | 2022-03-30 13:40:01.423 UTC | 2010-05-26 14:00:00.727 UTC | null | 214,029 | null | 214,029 | null | 1 | 21 | php | 110,429 | <p>Your index.php code is correct. I am including the updated code for common.php below then I will explain the differences.</p>
<pre><code><?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = <<<EOD
<div id="nav">
<ul>
<li><a $class href="index.php">Tab1</a>/</li>
<li><a href="two.php">Tab2</a></li>
<li><a href="three.php">Tab3</a></li>
</ul>
</div>
EOD;
?>
</code></pre>
<p>The first issue is that you need to make sure that the end declaration for your heredoc -- <code>EOD;</code> -- is not indented at all. If it is indented, then you will get errors.</p>
<p>As for your issue with the PHP code not running within the heredoc statement, that is because you are looking at it wrong. Using a heredoc statement is not the same as closing the PHP tags. As such, you do not need to try reopening them. That will do nothing for you. The way the heredoc syntax works is that everything between the opening and closing is displayed exactly as written with the exception of variables. Those are replaced with the associated value. I removed your logic from the heredoc and used a tertiary function to determine the class to make this easier to see (though I don't believe any logical statements will work within the heredoc anyway)</p>
<p>To understand the heredoc syntax, it is the same as including it within double quotes ("), but without the need for escaping. So your code could also be written like this:</p>
<pre><code><?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = "<div id=\"nav\">
<ul>
<li><a $class href=\"index.php\">Tab1</a>/</li>
<li><a href=\"two.php\">Tab2</a></li>
<li><a href=\"three.php\">Tab3</a></li>
</ul>
</div>";
?>
</code></pre>
<p>It will do exactly the same thing, just is written somewhat differently. Another difference between heredoc and the string is that you can escape out of the string in the middle where you can't in the heredoc. Using this logic, you can produce the following code:</p>
<pre><code><?php
$nav = "<div id=\"nav\">
<ul>
<li><a ".(($page == 'one') ? 'class="active"' : '')." href=\"index.php\">Tab1</a>/</li>
<li><a href=\"two.php\">Tab2</a></li>
<li><a href=\"three.php\">Tab3</a></li>
</ul>
</div>";
?>
</code></pre>
<p>Then you can include the logic directly in the string like you originally intended.</p>
<p>Whichever method you choose makes very little (if any) difference in the performance of the script. It mostly boils down to preference. Either way, you need to make sure you understand how each works.</p> |
2,679,865 | Return a value if no rows are found in Microsoft tSQL | <p>Using a <em>Microsoft</em> version of SQL, here's my simple query. If I query a record that doesn't exist then I will get nothing returned. I'd prefer that false (0) is returned in that scenario. Looking for the simplest method to account for no records.</p>
<pre><code>SELECT CASE
WHEN S.Id IS NOT NULL AND S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1) THEN 1
ELSE 0
END AS [Value]
FROM Sites S
WHERE S.Id = @SiteId
</code></pre> | 2,679,890 | 16 | 0 | null | 2010-04-21 02:10:12.647 UTC | 24 | 2022-04-18 17:43:42.747 UTC | 2020-04-17 23:49:56.88 UTC | null | 606,371 | null | 158,958 | null | 1 | 111 | tsql | 448,127 | <pre><code>SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END AS [Value]
FROM Sites S
WHERE S.Id = @SiteId and S.Status = 1 AND
(S.WebUserId = @WebUserId OR S.AllowUploads = 1)
</code></pre> |
3,184,197 | What's a good name for a method that gets or creates an object? | <p>Say you have a cache, and a method that will do something like the following:</p>
<pre><code>if (wanted Foo is not in cache)
cache.Add(new Foo())
Return Foo from cache
</code></pre>
<p>What would you call that method? <code>GetFoo()</code>, <code>GetOrCreateFoo()</code> or something else (and better)? Or should this really be divided into two methods?</p> | 3,184,297 | 21 | 1 | null | 2010-07-06 07:09:29.683 UTC | 4 | 2022-06-24 14:43:47.273 UTC | null | null | null | null | 367,665 | null | 1 | 81 | naming-conventions | 26,337 | <p>In most cases a simple <code>GetFoo</code> suffices as the caller doesn't need to know that you are creating and caching it. That's what encapsulation is all about.</p>
<p>However, in some circumstances, creating is an expensive operation, so it's useful to know that you may be creating something on demand and in some cases it will be slow. In this case, a different naming convention makes it clearer to the caller. <code>GetOrCreate()</code> or <code>Get(Options.CreateIfMissing)</code> is a good hint to the caller.</p>
<p>(The behaviour should of course be noted in the documentation, but it's good to use a method name that reminds people about side effects while they are reading the code, without them having to bring up and read the documentation for every method that is called)</p>
<p>The sort of case I find this happening in most often is (for example) when finding a tree node (e.g. in an XML document) you might have <code>CreateNode</code> (to create a node without adding it to the tree) and <code>AddNode</code> (to add an existing node to the tree). In this case, an "Add a node if it doesn't already exist" needs to have a different, descriptive name, so I will use something like <code>EnsureNodeExists</code> to differentiate it and make the purpose clear.</p> |
2,944,294 | How do I auto size a UIScrollView to fit its content | <p>Is there a way to make a <code>UIScrollView</code> auto-adjust to the height (or width) of the content it's scrolling?</p>
<p>Something like:</p>
<pre><code>[scrollView setContentSize:(CGSizeMake(320, content.height))];
</code></pre> | 17,283,653 | 23 | 0 | null | 2010-05-31 14:54:47.587 UTC | 74 | 2022-06-10 08:48:56.997 UTC | 2018-12-30 22:26:48.03 UTC | null | 503,099 | null | 203,708 | null | 1 | 138 | iphone|ios|objective-c|cocoa-touch|uiscrollview | 186,197 | <p>The best method I've ever come across to update the content size of a <code>UIScrollView</code> based on its contained subviews:</p>
<blockquote>
<p><strong>Objective-C</strong></p>
</blockquote>
<pre><code>CGRect contentRect = CGRectZero;
for (UIView *view in self.scrollView.subviews) {
contentRect = CGRectUnion(contentRect, view.frame);
}
self.scrollView.contentSize = contentRect.size;
</code></pre>
<blockquote>
<p><strong>Swift</strong></p>
</blockquote>
<pre><code>let contentRect: CGRect = scrollView.subviews.reduce(into: .zero) { rect, view in
rect = rect.union(view.frame)
}
scrollView.contentSize = contentRect.size
</code></pre> |
2,374,957 | ASP.NET MVC on IIS 7.5 - Error 403.14 Forbidden | <p>I'm running Windows 7 Ultimate (64 bit) using Visual Studio 2010 RC. I recently decided to have VS run/debug my apps on IIS rather than the dev server that comes with it.</p>
<p>However, every time I try to run an MVC app, I get the following error:</p>
<blockquote>
<p>HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory. Detailed</p>
</blockquote>
<blockquote>
<p>Error Information</p>
</blockquote>
<blockquote>
<p>Module DirectoryListingModule</p>
</blockquote>
<blockquote>
<p>Notification ExecuteRequestHandler</p>
</blockquote>
<blockquote>
<p>Handler StaticFile Error</p>
</blockquote>
<blockquote>
<p>Code 0x00000000 Requested</p>
</blockquote>
<blockquote>
<p>URL http://localhost:80/mySite/</p>
</blockquote>
<blockquote>
<p>Physical
Path C:\myProject\mySite\</p>
</blockquote>
<blockquote>
<p>Logon Method Anonymous Logon</p>
</blockquote>
<blockquote>
<p>User Anonymous</p>
</blockquote>
<p>I placed a <code>default.aspx</code> file in the directory and I received the following error:</p>
<blockquote>
<p>HTTP Error 500.21 - Internal Server
Error Handler
"PageHandlerFactory-Integrated" has a
bad module "ManagedPipelineHandler" in
its module list</p>
</blockquote>
<p>Are there any other steps I forgot to take to get this working?</p>
<p>Notes: I installed IIS 7.5 after installing VS 2010 RC. I used the built-in "Create Virtual Directory" button under the "Web" tab in the MVC project's "Properties" in Visual Studio 2010. I made sure that the application is using the ASP.NET 4 App Pool.</p>
<p>Below are the installed features of IIS I have.</p>
<p><a href="https://i.stack.imgur.com/26HZw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/26HZw.png" alt="enter image description here" /></a></p> | 2,376,484 | 28 | 10 | null | 2010-03-03 21:06:17.573 UTC | 131 | 2022-08-09 21:55:48.43 UTC | 2022-08-09 21:54:13.05 UTC | null | 2,756,409 | null | 160,823 | null | 1 | 339 | asp.net|iis|.net-4.0|iis-7.5 | 309,308 | <p>ASP.NET 4 was not registered in IIS. Had to run the following command in the command line/run</p>
<p>32bit (x86) Windows</p>
<blockquote>
<p>%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir</p>
</blockquote>
<p>64bit (x64) Windows</p>
<blockquote>
<p>%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir</p>
</blockquote>
<p>Note from David Murdoch's comment: </p>
<blockquote>
<p>That the .net version has changed
since this Answer was posted. Check
which version of the framework is in
the %windir%\Microsoft.NET\Framework64
directory and change the command
accordingly before running (it is
currently v4.0.30319) </p>
</blockquote> |
45,515,421 | Which versions of node.js are available on Azure Web Sites? | <p>I already know how to <a href="https://stackoverflow.com/q/34746480/27581">change the version of Node.js running on an Azure website</a>, but how do I see what the available Node.js version are that can be used in Azure?</p>
<p>This is similar to <a href="https://stackoverflow.com/q/12697113/27581">this question</a>, but the asker there explicitly wants to know the version that is currently running, not what versions are available.</p> | 64,758,529 | 6 | 0 | null | 2017-08-04 21:00:01.61 UTC | 4 | 2020-11-09 20:04:39.65 UTC | null | null | null | null | 27,581 | null | 1 | 37 | node.js|azure|azure-web-app-service | 22,978 | <p>Or go to <code>Configuration</code> and then <code>General settings</code>. Thank goodness they made that easier.
<a href="https://i.stack.imgur.com/NGHzm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NGHzm.png" alt="Microsoft Azure Configuration Screen" /></a></p> |
10,752,484 | How to read integer values from text file | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/303913/java-reading-integers-from-a-file-into-an-array">Java: Reading integers from a file into an array</a> </p>
</blockquote>
<p>I want to read integer values from a text file say contactids.txt. in the file i have values like</p>
<pre><code>12345
3456778
234234234
34234324234
</code></pre>
<p>i Want to read them from a text file...please help</p> | 10,752,555 | 6 | 0 | null | 2012-05-25 10:09:18.96 UTC | 1 | 2013-02-04 11:30:18.03 UTC | 2017-05-23 12:10:04.807 UTC | null | -1 | null | 1,353,232 | null | 1 | 11 | java | 127,034 | <p>You might want to do something like this (if you're using java 5 and more) </p>
<pre><code>Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
tall[i++] = scanner.nextInt();
}
</code></pre>
<p>Via <a href="https://stackoverflow.com/users/23051/julien-grenier">Julian Grenier</a> from <a href="https://stackoverflow.com/questions/303913/java-reading-integers-from-a-file-into-an-array/304061#304061">Reading Integers From A File In An Array</a></p> |
6,111,043 | MS Access Database locked by Unknown user | <p>I have an access database that is on a network drive that multiple users can access. The database corrupted this morning and I am in the process of trying to fix it. The problem I am having is when I attempt to rename the database it says it is currently in use by someone. There is no .ldb file associated with this file so at this point and am dead in the water because I can't rename it, compact it or anything.</p>
<p>Does anyone have any suggestions?</p>
<p>Thanks</p> | 6,111,634 | 3 | 6 | null | 2011-05-24 13:18:12.203 UTC | 1 | 2021-02-18 10:36:05.663 UTC | null | null | null | null | 426,671 | null | 1 | 2 | ms-access|unlock | 66,449 | <p>Copy the database to another location. The copy wont be locked. Then you can work in ways to save your work until you solve the lock problem in the original file. If your problem is due to VB code file corruption, try to open the database with the "/decompile" option:</p>
<p>Start-Run:</p>
<p>"C:\Program Files\Microsoft Office\Office\msaccess.exe" "C:\example.mdb" /decompile </p>
<p>If you haven't any ldb file associated with the mdb, it will be difficult to discover what user is locking your database. If you have few users, you should restart their machines. It would be prehistoric but should be fastest than trying to unlock the file through other ways.</p> |
33,299,202 | Could not cast value of type 'NSTaggedPointerString' to 'NSNumber' | <p>I have a Swift struct like this.</p>
<pre><code>struct Usage {
var totalData: Double
var remainingTotalData: Double
init(jsonData: NSData) {
var jsonDict = [String: AnyObject]()
do {
jsonDict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String: AnyObject]
} catch {
print("Error occurred parsing data: \(error)")
}
totalData = jsonDict["totalfup"] as! Double
remainingTotalData = jsonDict["totalrem"] as! Double
}
}
</code></pre>
<p>From an API, I get the following JSON response. This is the println of the <code>jsonDict</code> variable.</p>
<pre><code>[
"totalfup": 96.340899,
"totalrem": 3548710948
]
</code></pre>
<p>When I try to assign the value of the <code>totalfup</code> to the property <code>totalData</code>, I get this error.</p>
<p><strong>Could not cast value of type 'NSTaggedPointerString' to 'NSNumber'</strong></p>
<p>Anyone knows why? I tried changing the property type to <code>float</code> and then the whole struct to class but still the issue occurs.</p> | 33,299,324 | 7 | 0 | null | 2015-10-23 09:37:33.27 UTC | 7 | 2021-07-10 22:00:18.76 UTC | 2018-12-12 03:06:31.437 UTC | null | 5,210,045 | null | 1,077,789 | null | 1 | 77 | ios|swift|double|nsjsonserialization | 60,135 | <p>The reason of the error is <code>jsonDict["totalfup"]</code> is a String (<code>NSTaggedPointerString</code> is a subclass of <code>NSString</code>) , so you should convert String to Double.</p>
<p><strong>Please make sure, catch exception and check type before force-unwrap !</strong></p>
<pre><code>totalData = (jsonDict["totalfup"] as! NSString).doubleValue
</code></pre>
<p>For <strong>safety</strong>, using <code>if let</code>:</p>
<pre><code>// check dict["totalfup"] is a String?
if let totalfup = (dict["totalfup"] as? NSString)?.doubleValue {
// totalfup is a Double here
}
else {
// dict["totalfup"] isn't a String
// you can try to 'as? Double' here
}
</code></pre> |
34,237,218 | User is not authorized to perform: cloudformation:CreateStack | <p>I'm trying out <a href="http://serverless.com" rel="noreferrer">Serverless</a> to create AWS Lambdas and while creating a project using the command <code>serverless project create</code> I'm getting the following error.</p>
<pre><code>AccessDenied: User: arn:aws:iam::XXXXXXXXX:user/XXXXXXXXX is not authorized to perform: cloudformation:CreateStack on resource: arn:aws:cloudformation:us-east-1:XXXXXXXXX:stack/XXXXXXXXX-development-r/*
</code></pre>
<p>I have created a user and granted the following permissions to the user. </p>
<ol>
<li>AWSLambdaFullAccess</li>
<li>AmazonS3FullAccess</li>
<li>CloudFrontFullAccess</li>
<li>AWSCloudFormationReadOnlyAccess ( There was no <code>AWSCloudFormationFullAccess</code> to grant )</li>
</ol>
<p>How can I proceed? What else permissions I have to grant? </p> | 34,237,333 | 13 | 1 | null | 2015-12-12 06:55:50.13 UTC | 13 | 2021-05-31 18:06:38.197 UTC | null | null | null | null | 1,190,184 | null | 1 | 81 | amazon-web-services|amazon-iam|amazon-cloudformation | 79,164 | <p>The closest one that you've mentioned is <code>AWSCloudFormationReadOnlyAccess</code>, but obviously that's for readonly and you need <code>cloudformation:CreateStack</code>. Add the following as a <strong>user policy</strong>.</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1449904348000",
"Effect": "Allow",
"Action": [
"cloudformation:CreateStack"
],
"Resource": [
"*"
]
}
]
}
</code></pre>
<p>It's entirely possible you'll need more permissions- for instance, to launch an EC2 instance, to (re)configure security groups, etc.</p> |
52,434,165 | Dagger2: Unable to inject dependencies in WorkManager | <p>So from what I read, Dagger doesn't have support for inject in Worker yet. But there are some workarounds as people suggest. I have tried to do it a number of ways following examples online but none of them work for me. </p>
<p>When I don't try to inject anything into the Worker class, the code works fine, only that I can't do what I want because I need access to some DAOs and Services. If I use @Inject on those dependencies, the dependencies are either null or the worker never starts i.e the debugger doesn't even enter the Worker class.</p>
<p>For eg I tried doing this:</p>
<pre><code>@Component(modules = {Module.class})
public interface Component{
void inject(MyWorker myWorker);
}
@Module
public class Module{
@Provides
public MyRepository getMyRepo(){
return new myRepository();
}
}
</code></pre>
<p>And in my worker</p>
<pre><code>@Inject
MyRepository myRepo;
public MyWorker() {
DaggerAppComponent.builder().build().inject(this);
}
</code></pre>
<p>But then the execution never reaches the worker. If I remove the constructor, the myRepo dependency remains null.</p>
<p>I tried doing many other things but none work. Is there even a way to do this? Thanks!!</p> | 53,377,279 | 4 | 1 | null | 2018-09-20 22:24:49.473 UTC | 15 | 2021-10-12 14:35:40.227 UTC | null | null | null | null | 3,825,975 | null | 1 | 24 | android|dagger-2|android-workmanager | 12,401 | <h1>Overview</h1>
<p>You need to look at <a href="https://developer.android.com/reference/androidx/work/WorkerFactory" rel="nofollow noreferrer">WorkerFactory</a>, available from <code>1.0.0-alpha09</code> onwards.</p>
<p>Previous workarounds relied on being able to create a <code>Worker</code> using the default 0-arg constructor, but as of <code>1.0.0-alpha10</code> that is no longer an option.</p>
<h1>Example</h1>
<p>Let's say that you have a <code>Worker</code> subclass called <code>DataClearingWorker</code>, and that this class needs a <code>Foo</code> from your Dagger graph.</p>
<pre><code>class DataClearingWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
lateinit var foo: Foo
override fun doWork(): Result {
foo.doStuff()
return Result.SUCCESS
}
}
</code></pre>
<p>Now, you can't just instantiate one of those <code>DataClearingWorker</code> instances directly. So you need to define a <code>WorkerFactory</code> subclass that can create one of them for you; and not just create one, but also set your <code>Foo</code> field too.</p>
<pre><code>class DaggerWorkerFactory(private val foo: Foo) : WorkerFactory() {
override fun createWorker(appContext: Context, workerClassName: String, workerParameters: WorkerParameters): ListenableWorker? {
val workerKlass = Class.forName(workerClassName).asSubclass(Worker::class.java)
val constructor = workerKlass.getDeclaredConstructor(Context::class.java, WorkerParameters::class.java)
val instance = constructor.newInstance(appContext, workerParameters)
when (instance) {
is DataClearingWorker -> {
instance.foo = foo
}
// optionally, handle other workers
}
return instance
}
}
</code></pre>
<p>Finally, you need to create a <code>DaggerWorkerFactory</code> which has access to the <code>Foo</code>. You can do this in the <em>normal</em> Dagger way.</p>
<pre><code>@Provides
@Singleton
fun workerFactory(foo: Foo): WorkerFactory {
return DaggerWorkerFactory(foo)
}
</code></pre>
<h2>Disabling Default WorkManager Initialization</h2>
<p>You'll also need to disable the default <code>WorkManager</code> initialization (which happens automatically) and initialize it manually.</p>
<p>How you do this depends on the version of <code>androidx.work</code> that you're using:</p>
<h3>2.6.0 and onwards:</h3>
<p>In <code>AndroidManifest.xml</code>, add:</p>
<pre><code><provider
android:name="androidx.startup.InitializationProvider"
android:authorities="YOUR_APP_PACKAGE.androidx-startup"
android:exported="false"
tools:node="merge">
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
</code></pre>
<h3>Pre 2.6.0:</h3>
<p>In <code>AndroidManifest.xml</code>, add:</p>
<pre><code> <provider
android:name="androidx.work.impl.WorkManagerInitializer"
android:authorities="YOUR_APP_PACKAGE.workmanager-init"
android:enabled="false"
android:exported="false"
tools:replace="android:authorities" />
</code></pre>
<p>Be sure to replace <strong>YOUR_APP_PACKAGE</strong> with your actual app's package. The <code><provider</code> block above goes <strong>inside</strong> your <code><application</code> tag.. so it's a sibling of your <code>Activities</code>, <code>Services</code> etc...</p>
<p>In your <code>Application</code> subclass, (or somewhere else if you prefer), you can manually initialize <code>WorkManager</code>.</p>
<pre><code>@Inject
lateinit var workerFactory: WorkerFactory
private fun configureWorkManager() {
val config = Configuration.Builder()
.setWorkerFactory(workerFactory)
.build()
WorkManager.initialize(this, config)
}
</code></pre> |
32,648,371 | Why does this PDO statement silently fail? | <p>This is my PHP SQL statement and it's returning false while var dumping</p>
<pre><code>$sql = $dbh->prepare('INSERT INTO users(full_name, e_mail, username, password) VALUES (:fullname, :email, :username, :password)');
$result = $sql->execute(array(
':fullname' => $_GET['fullname'],
':email' => $_GET['email'],
':username' => $_GET['username'],
':password' => $password_hash));
</code></pre> | 32,648,423 | 1 | 1 | null | 2015-09-18 09:20:28.077 UTC | 16 | 2022-04-05 06:04:39.077 UTC | 2022-03-03 13:23:17.403 UTC | null | 1,839,439 | null | 3,821,713 | null | 1 | 52 | php|pdo | 16,900 | <h3>TL;DR</h3>
<ol>
<li>Always have set <code>PDO::ATTR_ERRMODE</code> to <code>PDO::ERRMODE_EXCEPTION</code> in your PDO connection code. It will let the database tell you what the actual problem is, be it with query, server, database or whatever.</li>
<li>Always replace every PHP variable in the SQL query with a question mark, and execute the query using <a href="https://phpdelusions.net/pdo_examples/select#prepare" rel="nofollow noreferrer"><strong>prepared statement</strong></a>. It will help to avoid syntax errors of all sorts.</li>
</ol>
<h3>Explanation</h3>
<p>Sometimes your PDO code produces an error like <code>Call to a member function execute()</code> or similar. Or even without any error but the query doesn't work all the same. It means that your query failed to execute.</p>
<p>Every time a query fails, MySQL has an error message that <strong>explains the reason</strong>. Unfortunately, by default such errors are not transferred to PHP, and all you have is a silence or a cryptic error message mentioned above. Hence it is very important to configure PHP and PDO to report you MySQL errors. And once you get the error message, it will be a no-brainer to fix the issue.</p>
<p>In order to get the detailed information about the problem, either put the following line in your code right after connect</p>
<pre><code>$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
</code></pre>
<p>(where <code>$dbh</code> is the name of your PDO instance variable) or - better - add this parameter as a <a href="https://phpdelusions.net/pdo_examples/connect_to_mysql#example" rel="nofollow noreferrer">connection option</a>. After that all database errors will be translated into PDO exceptions which, if left alone, would act just as regular PHP errors.</p>
<p>After getting the error message, you have to read and comprehend it. It sounds too obvious, but learners often overlook the <em>meaning</em> of the error message. Yet most of time it explains the problem pretty straightforward:</p>
<ul>
<li>Say, if it says that a particular table doesn't exist, you have to check spelling, typos, letter case. Also you have to make sure that your PHP script connects to a correct database</li>
<li>Or, if it says there is an error in the SQL syntax, then you have to examine your SQL. And the problem spot is right <strong>before</strong> the query part cited in the error message.</li>
</ul>
<p>You have to also <em>trust</em> the error message. If it says that number of tokens doesn't match the number of bound variables then it <em>is</em> so. Same goes for absent tables or columns. Given the choice, whether it's your own mistake or the error message is wrong, always stick to the former. Again it sounds condescending, but hundreds of questions on this very site prove this advice extremely useful.</p>
<hr />
<p>Note that in order to see PDO errors, you have to be able to see PHP errors in general. To do so, you have to configure PHP depends on the site environment:</p>
<ul>
<li><p>on a <strong>development</strong> server it is very handy to have errors right on the screen, for which displaying errors have to be turned on:</p>
<pre><code> error_reporting(E_ALL);
ini_set('display_errors',1);
</code></pre>
</li>
<li><p>while on a <strong>live</strong> site, all errors have to be <strong>logged, but never shown</strong> to the client. For this, configure PHP this way:</p>
<pre><code> error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
</code></pre>
</li>
</ul>
<p>Note that <code>error_reporting</code> should be set to <code>E_ALL</code> all the time.</p>
<p>Also note that despite the common delusion, <strong>no try-catch have to be used for the error reporting</strong>. PHP will report you PDO errors already, and in a way better form. An uncaught exception is very good for development, yet if you want to show a customized error page, still don't use try catch for this, but just set a <a href="https://phpdelusions.net/articles/error_reporting" rel="nofollow noreferrer">custom error handler</a>. In a nutshell, you don't have to treat PDO errors as something special but regard them as any other error in your code.</p>
<p><strong>P.S.</strong><br />
Sometimes there is no error but no results either. Then it means, <em>there is no data to match your criteria</em>. So you have to admit this fact, even if you can swear the data and the criteria are all right. They are not. You have to check them again. I've short answer that would help you to pinpoint the matching issue, <a href="https://stackoverflow.com/a/57986043/285587">Having issue with matching rows in the database using PDO</a>. Just follow this instruction, and the linked tutorial step by step and either have your problem solved or have an answerable question for Stack Overflow.</p> |
32,918,666 | Example of Navigation between views in React Native Android? | <p>After check the React Native documentation, I still don't understand the best way to create views and navigate between different components.</p>
<p>I don't want to use any external components like:</p>
<p><a href="https://github.com/Kureev/react-native-navbar/">https://github.com/Kureev/react-native-navbar/</a></p>
<p><a href="https://github.com/23c/react-native-transparent-bar">https://github.com/23c/react-native-transparent-bar</a></p>
<p><a href="https://github.com/superdami/react-native-custom-navigation">https://github.com/superdami/react-native-custom-navigation</a></p>
<p>I don't need a Navigation bar, i just want to set views and slide left, right o pop a view, nothing more.</p>
<p>I know is something basic, but I can't find any helpful example.</p>
<p>Please, anyone can help me? Any functional example in <a href="https://rnplay.org/">https://rnplay.org/</a>?</p>
<p>Thank you.</p> | 33,019,808 | 3 | 1 | null | 2015-10-03 03:39:59.493 UTC | 3 | 2018-04-22 14:51:54.993 UTC | null | null | null | null | 1,097,284 | null | 1 | 32 | javascript|react-native | 54,548 | <p><strong>UPDATE 04/2018 :</strong></p>
<p>Things have change since my first answer, and today two massive libraries are relevant for navigation : react-navigation and react-native-navigation.</p>
<p>I will wrote an example for react-navigation which is an easy to use library and full JS maintain by serious people from the community.</p>
<p>First install the library :</p>
<pre><code>yarn add react-navigation
</code></pre>
<p>or</p>
<pre><code>npm install --save react-navigation
</code></pre>
<p>Then in your app entry point (index.js) :</p>
<pre><code>import Config from './config';
import { AppRegistry } from 'react-native';
import { StackNavigator } from 'react-navigation';
export const AppNavigator = StackNavigator(Config.navigation);
AppRegistry.registerComponent('appName', () => AppNavigator);
</code></pre>
<p>You can see that we pass an object to the StackNavigator, it's all ours screens configuration, here is an example of configuration :</p>
<pre><code>import HomeScreen from "./HomeScreen";
import SettingsScreen from "./SettingsScreen";
const Config = {
navigation: {
Home: {
screen: HomeScreen
},
Settings: {
screen: SettingsScreen,
}
}
}
</code></pre>
<p>Now the app know each screen we got. We can simply tell the "navigate" function to go to our Setting Screen.
Let's watch our Home Screen :</p>
<pre><code>class HomeScene extends Component {
constructor(props) {
super(props);
}
render () {
return (
<View>
<Button
title="Go to Settings"
onPress={() => this.props.navigation.navigate('Settings')}
/>
</View>
);
}
}
</code></pre>
<p>As you can see, the navigation will hydrate the props. And from here you can make what you want.</p>
<p>Go to the library documentation to see all you can do : change the header type, the title, navigation type, ... </p>
<p><strong>PREVIOUS ANSWER :</strong></p>
<p>Watch this example:
<a href="https://github.com/h87kg/NavigatorDemo" rel="nofollow noreferrer">https://github.com/h87kg/NavigatorDemo</a></p>
<p>It's useful and a well written Navigator example, better than the one above you just wrote, I think.</p>
<p>Mainly watch the relationship between <code>LoginPage.js</code> and <code>MainPage.js</code></p> |
35,502,079 | Custom converter for Retrofit 2 | <p>I have to handle a dynamic JSON responses.</p>
<p>Before, I was using classes and annotations as follows:</p>
<pre><code>public class ChatResponse {
@SerializedName("status")
private int status;
@SerializedName("error")
private String error;
@SerializedName("response")
private Talk response;
public int getStatus() {
return status;
}
public String getError() {
return error;
}
public Talk getResponse() {
return response;
}
}
</code></pre>
<p>When the status is 1 (success) the <code>onResponse</code> is fired and I can get a ChatResponse object. But, when the status is 0, the response is false in the JSON representation and it fails (<code>onFailure</code> is fired).</p>
<p>I want to create my custom converter, and <a href="https://stackoverflow.com/questions/24279245/how-to-handle-dynamic-json-in-retrofit">this question</a> has a good example, but that example is for Retrofit 1.</p>
<p><a href="http://square.github.io/retrofit/" rel="noreferrer">I have to</a> create a class that extends <code>Converter.Factory</code>, but I don't know how to override the methods of this class.</p>
<p>Actually I have the next:</p>
<pre><code>@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
return super.fromResponseBody(type, annotations);
}
@Override
public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
return super.toRequestBody(type, annotations);
}
</code></pre>
<p>How I can parse the JSON response by my own at this point?</p>
<p>Thanks in advance.</p> | 35,518,822 | 4 | 1 | null | 2016-02-19 09:44:28.193 UTC | 10 | 2020-06-01 04:27:12.15 UTC | 2017-05-23 12:10:28.68 UTC | null | -1 | null | 3,692,788 | null | 1 | 26 | android|json|converter|retrofit2 | 44,343 | <p>I was looking for a simple example about how to implement a custom converter for Retrofit 2. Unfortunately found none. </p>
<p>I found <a href="https://github.com/segmentio/retrofit-jsonrpc/blob/master/jsonrpc/src/main/java/com/segment/jsonrpc/JsonRPCConverterFactory.java" rel="noreferrer">this example</a> but, at least for me, it's too complicated for my purpose.</p>
<p>Happilly, I found a solution. </p>
<p>This solution is to use <code>GSON deserializers</code>.</p>
<p>We don't need to create a custom converter, we just have to customize the <code>GSON converter</code>.</p>
<p>Here is a great <a href="http://www.javacreed.com/gson-deserialiser-example/" rel="noreferrer">tutorial</a>. And here is the code I used to parse the JSON described in my question:</p>
<ul>
<li><p><a href="https://gist.github.com/JCarlosR/20a6770eb5ef3d8df312611baac8794d#file-logindeserializer-java" rel="noreferrer">Login Deserializer</a>: Defines how to parse the JSON as an object of our target class (using conditionals and whatever we need).</p></li>
<li><p><a href="https://gist.github.com/JCarlosR/20a6770eb5ef3d8df312611baac8794d#file-apiadapter-java" rel="noreferrer">Custom GSON converter</a>: Builds a GSON converter that uses our custom deserializer.</p></li>
</ul> |
53,253,879 | ansible vars_files vs include_vars | <p>What is the difference between</p>
<ul>
<li><p><code>vars_files</code> directive</p>
<p><strong>and</strong></p>
</li>
<li><p><code>include_vars</code> module</p>
</li>
</ul>
<p>Which should be used when, is any of above deprecated, discouraged?</p> | 53,257,820 | 3 | 0 | null | 2018-11-11 22:28:02.81 UTC | 4 | 2021-07-18 19:00:26.163 UTC | 2021-07-18 19:00:26.163 UTC | null | 2,123,530 | null | 1,423,685 | null | 1 | 38 | ansible | 45,239 | <p>Both <em>vars_files</em> and <em>include_vars</em> are labeled as stable interfaces so neither of them are deprecated. Both of them have some commonalities but they solve different purposes.</p>
<p><strong>vars_files:</strong></p>
<p><em>vars_file</em> directive can only be used when defining a play to specify variable files. The variables from those files are included in the playbook. Since it is used in the start of the play, it most likely implies that some other play(before this play) created those vars files or they were created statically before running the configuration; means they were kind of configuration variables for the play.</p>
<p><strong>include_vars:</strong></p>
<p><em>vars_files</em> serves one purpose of including the vars from a set of files but it cannot handle the cases if</p>
<ul>
<li>the vars files were created dynamically and you want to include them in play</li>
<li>include vars in a limited scope.</li>
<li>You have multiple vars files and you want to include them based on certain criteria e.g. if the local database exists then include configuration of local database otherwise include configuration of a remotely hosted database.</li>
<li><em>include_vars</em> have higher <a href="https://docs.ansible.com/ansible/2.7/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable" rel="noreferrer">priority</a> than <strong>vars_files</strong> so, it can be used to override default configuration(vars).</li>
<li><em>include_vars</em> are evaluated lazily(evaluated at the time when they are used).</li>
<li>You want to include vars dynamically using a <em>loop</em>.</li>
<li>You want to read a file and put all those variables in a named dictionary instead of reading all variables in the global variable namespace.</li>
<li>You want to include all files in a directory or some subset of files in a directory(based on prefix or exclusion list) without knowing the exact names of the vars file(s).</li>
</ul>
<p>These are some of the cases which I can think of and if you want to use any of the above cases then you need <em>include_vars</em>.</p> |
53,140,913 | Querying by a field with type 'reference' in Firestore | <p>I have a collection called 'categories' containing a single document with ID: 5gF5FqRPvdroRF8isOwd.</p>
<p>I have another collection called 'tickets'. Each ticket has a reference field which assigns the ticket to a particular category.</p>
<p>The field in the tickets collection is called 'category' and has a field type of <code>reference</code>.</p>
<p>In the code below, <code>categoryDocId</code> is the document ID of the category I want to query by.</p>
<pre><code>const categoryDocID = `5gF5FqRPvdroRF8isOwd`;
const files = await firebase
.firestore()
.collection('tickets')
.where('category', '==', categoryDocID)
.get();
</code></pre>
<p>Why does <code>files.length</code> return 0?</p>
<p>For testing, I changed the <code>category</code> field type to string, and set it to the category ID instead of a direct reference. This correctly returned tickets assigned to the category, which leads me to believe it's something about how I'm querying a <code>reference</code> field.</p> | 53,141,199 | 3 | 1 | null | 2018-11-04 12:40:38.213 UTC | 14 | 2022-03-27 13:23:18.887 UTC | 2021-12-15 17:01:40.06 UTC | null | 8,172,439 | null | 2,273,902 | null | 1 | 45 | javascript|node.js|firebase|google-cloud-platform|google-cloud-firestore | 27,989 | <p>As you will read <a href="https://firebase.google.com/docs/firestore/manage-data/data-types" rel="noreferrer">here</a> in the doc, the Reference Data Type is used to store <a href="https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference" rel="noreferrer">DocumentReferences</a>.</p>
<p>If you want to use it in a query, you cannot use a simple string, neither the UID of the document (i.e. <code>'5gF5FqRPvdroRF8isOwd'</code>), nor the string value that is stored in the field (i.e. <code>'/categories/5gF5FqRPvdroRF8isOwd'</code>).</p>
<p>You have to build a DocumentReference and use it in your query, as follows:</p>
<pre><code>const categoryDocRef = firebase.firestore()
.collection('categories')
.doc('5gF5FqRPvdroRF8isOwd');
const files = await firebase
.firestore()
.collection('tickets')
.where('category', '==', categoryDocRef)
.get();
</code></pre> |
29,993,660 | How to set default path (route prefix) in express? | <p>Instead of doing <code>path + '..'</code> foreach route - how can I prefix every route?</p>
<p>My route shall be</p>
<pre><code>/api/v1/user
</code></pre>
<p>What I don't want to do </p>
<pre><code>var path = '/api/v1';
app.use(path + '/user', user);
</code></pre>
<p>What I want to do </p>
<pre><code> var app = express();
app.setPath('/api/v1');
app.use(..);
</code></pre> | 29,993,694 | 2 | 1 | null | 2015-05-01 19:21:51.533 UTC | 3 | 2021-01-24 02:44:25.773 UTC | null | null | null | null | 3,450,580 | null | 1 | 56 | node.js|express | 47,277 | <p>Using Express 4 you can use <a href="http://expressjs.com/guide/routing.html#express-router"><code>Router</code></a></p>
<pre><code>var router = express.Router();
router.use('/user', user);
app.use('/api/v1', router);
</code></pre> |
8,932,313 | how can i access a parent view controller's view from a child view controller? | <p>I have a main view controller that takes care of the drawing for my 2D opengl ES view, and a child view controller buttonManager that determines what buttons to load and draw during launch.</p>
<p>Once the user presses on one of these buttons, this view controller is created and its view is supposed to come up, but the view never gets added but has been tested to work. Heres my code from the main view controller:</p>
<pre><code> buttonManager=[[ButtonManager alloc] init];
[self addChildViewController:buttonManager];
[self.view addSubview:buttonManager.view];
</code></pre>
<p>and heres my code to launch this view:</p>
<pre><code>-(void)launchStopDialog: (NSString*)stopName {
NSLog(@"stopdialog should be launched.");
if (stopDialogController == nil)
stopDialogController = [[StopDialogController alloc] initWithNibName:@"StopDialog" bundle:nil];
if (stopDialogController)
[stopDialogController presentWithSuperview:self.view.superview withStopName:stopName];
}
</code></pre> | 8,932,772 | 5 | 0 | null | 2012-01-19 19:47:13.6 UTC | 3 | 2020-04-01 04:46:37.717 UTC | null | null | null | null | 385,051 | null | 1 | 19 | ios|uiviewcontroller|ios5 | 56,973 | <p>To access the parent View controller you can use <code>self.parentViewController</code>. Once you have it you can access its view simply by using its <code>view</code> property</p> |
8,469,112 | Hide ICS back home task switcher buttons | <p>Just wondering how to hide the ICS back/home/etc software buttons programmatically. Just like the Youtube apps does when playing a video. I want to hide them while a video is playing, but bring them up if the user taps the screen.</p>
<p>I can't seem to find it anywhere on the web, or in Google's documentation.</p> | 8,469,190 | 6 | 0 | null | 2011-12-12 01:50:44.547 UTC | 17 | 2017-02-07 12:55:28.907 UTC | 2017-02-07 12:55:28.907 UTC | null | 5,696,554 | null | 6,044 | null | 1 | 29 | android|fullscreen|android-4.0-ice-cream-sandwich | 28,867 | <p>try to setup a Full screen window with flag SYSTEM_UI_FLAG_HIDE_NAVIGATION </p> |
8,645,184 | Version vs Distrib number of MySQL | <p>Typing the</p>
<pre class="lang-none prettyprint-override"><code>mysql --version
</code></pre>
<p>command in a Linux shell, I got the following:</p>
<pre class="lang-none prettyprint-override"><code>mysql Ver 14.12 Distrib 5.0.77, for redhat-linux-gnu (i686) using readline 5.1
</code></pre>
<p>The number 5.0.77 obviously refers to the known version number of MySQL. What does 14.12 mean?</p>
<p>Is this documented/explained anywhere?</p> | 8,663,766 | 1 | 0 | null | 2011-12-27 13:30:40.397 UTC | 3 | 2021-10-18 17:03:12.653 UTC | 2021-10-18 17:03:12.653 UTC | user719662 | 63,550 | null | 1,117,676 | null | 1 | 34 | mysql | 22,243 | <p><strong>Ver</strong> refers to the version of the mysql command line client - what you are envoking by typing 'mysql'<br>
<strong>Distrib</strong> refers to the mysql server version your client was <em>built with</em>. This is not to be confused with the mysql server you are connected to, which can be obtained with <code>SELECT VERSION();</code></p>
<p>The mysql client (what you are evoking) is distributed with the server, and, AFAIK, there is no easy way to build it on it's own.</p>
<p>I can't find any documentation for this either, so the source is the only 'source' of documentation.</p>
<p>First stop: client/mysql.cc: the mysql client.</p>
<pre><code> static void usage(int version)
{
...
printf("%s Ver %s Distrib %s, for %s (%s) using %s %s\n",
my_progname, VER, MYSQL_SERVER_VERSION, SYSTEM_TYPE, MACHINE_TYPE,
readline, rl_library_version);
</code></pre>
<p>As you see, it uses the constants VER for "14.12" and MYSQL_SERVER_VERSION for "5.0.77"</p>
<p>Where are these constants defined?, is the question.</p>
<p>VER is defined near the top (line 51 in my source) of client/mysql.cc as a constant at run time.</p>
<pre><code>const char *VER= "14.14";
</code></pre>
<p>And I would assume, updated by hand or by a checkin process. This is very likely the version of the 'client' because it's right there in the client code.</p>
<p>MYSQL_SERVER_VERSION is defined in include/mysql_version.h (line 12) which is used for both the client and server (mysql / mysqld)</p>
<pre><code>#define MYSQL_SERVER_VERSION "5.1.56"
</code></pre>
<p>(it's actually set in the configure script and substituted in at configure time)</p> |
27,046,544 | Building a p2 repository by resolving Tycho features from a Maven repository | <p>I'm trying to build a p2 repository from Tycho feature artifacts which are deployed in a remote Maven repository, without having to install the artifacts into the local Maven repository first (as in <a href="https://stackoverflow.com/questions/7345708/tycho-cant-resolve-eclipse-feature-of-another-reactor-build">Tycho fails to resolve reference from product to eclipse-feature from a different reactor build</a>), and without having to build all features and the repository together in a single reactor build.</p>
<p><strong>Background</strong></p>
<p>I have a multi-module Tycho project that builds several Eclipse plugins and features.</p>
<p>So that I can build each module separately - and so that I can reference OSGI artifacts in our Nexus Maven repository - I have enabled <code><pomDependencies>consider</pomDependencies></code> in my target platform, and added Maven dependencies between the modules or to the repository artifacts as usual with <code><dependency/></code> elements.</p>
<p>This works well - I can build the features or run the plugin tests without their dependant plugins being either in my local Maven repository or in the same reactor build. For example, when I run <code>mvn test</code> on a plugin test project, the relevant dependencies will be downloaded from Nexus and Tycho will happily resolve the <code>Import-Package</code>s in my manifest against these, build everything and run the tests. So far so good.</p>
<p>I would like to generate a p2 repository from these features so that I can install them in Eclipse from an update site, and the advertised way to do this is with the <code>eclipse-repository</code> packaging type. But here the plan falls down - Tycho doesn't seem to be able to resolve feature dependencies when building repositories in the same way as it can resolve plugin dependencies when building features. All attempts yield:</p>
<pre><code>[ERROR] Cannot resolve project dependencies:
[ERROR] Software being installed: my.eclipse.repository raw:0.0.1.'SNAPSHOT'/format(n[.n=0;[.n=0;[-S]]]):0.0.1-SNAPSHOT
[ERROR] Missing requirement: my.eclipse.repository raw:0.0.1.'SNAPSHOT'/format(n[.n=0;[.n=0;[-S]]]):0.0.1-SNAPSHOT requires 'my.prj.eclipse.project.feature.feature.group 0.0.0' but it could not be found
</code></pre>
<p>There are two ways I have successfully built the p2 repository:</p>
<ul>
<li><strong>As part of the same reactor build</strong>. If I make the <code>eclipse-repository</code> a module within the Tycho multi-module project, and build the whole project at once with e.g. <code>mvn verify</code>, the features are resolved fine. But I don't want to do this. I would prefer to build modules individually. This means our CI can have an indicator for each module, and we can immediately see what module tests have failed in; it gives us opportunities for parallelising builds; and we avoid having to be constantly running builds on modules that haven't changed. It would be a shame to have to use a monolithic Maven build.</li>
<li><strong>If I install the Tycho project into my local Maven repository</strong>, by running <code>mvn install</code> on the dependency. But I don't want to do this either, because this would mean the build is inherently irreproducable, as it would be sensitive to the state of the local repository. Our CI is currently set up to maintain a Maven repository per job and to completely wipe it at the start of execution, to shield us from this potential messiness.</li>
</ul>
<p>So my question is: is there a third way? Is there any way I can get the Tycho plugin responsible for building <code>eclipse-repository</code> packaging types to download features from a remote Maven repository? Or any other way I can build the p2 repository from plugins that have been individually built and deployed to the Maven repository?</p>
<p>Things I've tried include:</p>
<ul>
<li>specifiying the Maven feature depedencies as both <code>jar</code> and <code>eclipse-feature</code></li>
<li><p>explicitly adding the features to the target platform, like</p>
<p><code>...
<artifactId>target-platform-configuration</artifactId>
<version>${tycho.version}</version>
<configuration>
<dependency-resolution>
<extraRequirements>
<requirement>
<type>eclipse-feature</type>
<id>my.prj.eclipse.project.feature</id>
<versionRange>0.0.0</versionRange>
</requirement>
...</code></p></li>
</ul>
<hr>
<p>The <strong>closest</strong> thing I've found to a decent solution is have a multi-module Tycho project that just contains the repository and features.</p>
<pre><code>feature-project
|- feature1 (eclipse-feature)
|- feature2 (eclipse-feature)
|- repository (eclipse-repository)
</code></pre>
<p>Building this <strong>works</strong> - all plugins added to the top-level POM are downloaded from Nexus, available for inclusion in each feature and included in the generated repository.</p>
<p>However this is far from ideal because I can no longer store my features logically alongside my plugins; they need to be in separate project hierarchies. Attempting to build the features and repository separately, like with <code>mvn clean verify -pl :feature1,feature2,repository</code>, fails presumably due to <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=380152" rel="nofollow noreferrer">Bug 380152</a>.</p>
<p>Is there a better way? Any help would be gratefully received.</p>
<p>Many thanks</p>
<hr>
<p>(As an aside: building the repository with <code>mvn clean verify -Dtycho.localArtifacts=ignore</code> will <strong>succeed</strong> if the features are present in the local Maven repository, and won't show you the warning that artifacts are being resolved from the local repo... is this a bug?)</p> | 27,173,059 | 1 | 1 | null | 2014-11-20 18:08:23.447 UTC | 8 | 2021-05-27 20:26:37.033 UTC | 2018-01-10 17:28:27.097 UTC | null | 119,775 | null | 1,143,427 | null | 1 | 13 | maven|eclipse-plugin|tycho | 3,709 | <p>I am pretty impressed by your thorough analysis. You've almost got everything covered which is possible with the current Tycho version (0.22.0) - except for the solution which is so unintuitive that I wouldn't have expected anyone to be able to guess it (see below). Note however that there is a small fix required to also make the solution work for SNAPSHOT artifacts.</p>
<p>But first, I'd like to provide some technical (and historical) background for what you have observed:</p>
<p><em>pomDependencies=consider only works for plug-ins</em>: The use case for this functionality was to allow referencing plug-ins (or more precisely OSGi bundles) from Maven repositories. So when the flag is set and the project has dependencies to JARs, Tycho will check if they are OSGi bundles, generate the p2 metadata for them on-the-fly, and add them to the target platform. There is no similar support for feature JARs because these usually don't exist in Maven repositories.</p>
<p><em>But what about Tycho-built projects? These may deploy into Maven repositories!</em> Yes, this is true, and this is why I tried to extend the pomDependencies concept to allow for what you are trying to do. The idea was that every time Tycho considers a POM dependency for the target platform, it also checks if the p2 index files <code>...-p2metadata.xml</code> and <code>...-p2artifacts.xml</code> exist. However this turned out to infer a massive performance penalty because it generally takes very long for a Maven repository server to figure out that an artifact does not exist. So the remote download was disabled, and replaced with a look-up in the <em>local</em> Maven repository. In this way, two Tycho builds could set <code>-Dtycho.localArtifacts=ignore</code> and would still be able to exchange the artifacts specified in the POM via the local Maven repository.</p>
<p>Knowing these implementation details, we get to the following solution: Instead of only adding a POM dependency from the repository to the feature artifact, you also need to add dependencies to the p2metadata and p2artifacts files. Example:</p>
<pre><code><dependencies>
<dependency>
<groupId>myproject</groupId>
<artifactId>myproject.feature</artifactId>
<version>0.1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>myproject</groupId>
<artifactId>myproject.feature</artifactId>
<version>0.1.0-SNAPSHOT</version>
<classifier>p2metadata</classifier>
<type>xml</type>
</dependency>
<dependency>
<groupId>myproject</groupId>
<artifactId>myproject.feature</artifactId>
<version>0.1.0-SNAPSHOT</version>
<classifier>p2artifacts</classifier>
<type>xml</type>
</dependency>
</dependencies>
</code></pre>
<p>This makes Maven also download these p2 index files, so Tycho recognizes the main artifact as Tycho artifact. In this way, you can also get an eclipse-feature into the target platform via POM dependencies - at least almost: With 0.22.0, the repository build passes, but the feature.jar artifact is missing. I already debugged this issue, and it is <a href="https://git.eclipse.org/r/#/c/37186/" rel="noreferrer">easy to fix</a>.</p>
<p>Obviously the syntax with three <code><dependency></code> elements for every actual dependency is not nice. It should be possible to boil this down to a single <code>p2artifacts</code> element - but this is more work. In case you are interested in this feature, you could <a href="https://bugs.eclipse.org/bugs/enter_bug.cgi?product=Tycho" rel="noreferrer">open an enhancement request in Tycho's issue tracker</a>.</p> |
30,578,998 | string array literal ? How do I code it simply? | <p>Though that may be a silly question, I can't figure out how to declare an array literal grouping some string literals.</p>
<p>For example, let's assume I want the java array <code>["January", "February", "March"]</code>.
How can I translate this into the latest kotlin version <code>(today, 12.0.0)</code>?</p>
<p>What have I tried?</p>
<pre><code>stringArray("January", "February", "March")
</code></pre> | 30,581,197 | 2 | 0 | null | 2015-06-01 16:53:30.797 UTC | 3 | 2018-10-30 19:31:43.367 UTC | 2018-10-30 19:31:43.367 UTC | null | 317,522 | null | 662,618 | null | 1 | 58 | arrays|kotlin | 31,738 | <p>You can use arrayOf(), as in</p>
<pre><code>val literals = arrayOf("January", "February", "March")
</code></pre> |
43,678,408 | How to create a conditional task in Airflow | <p>I would like to create a conditional task in Airflow as described in the schema below. The expected scenario is the following:</p>
<ul>
<li>Task 1 executes</li>
<li>If Task 1 succeed, then execute Task 2a</li>
<li>Else If Task 1 fails, then execute Task 2b</li>
<li>Finally execute Task 3</li>
</ul>
<p><a href="https://i.stack.imgur.com/VS1Wm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VS1Wm.png" alt="Conditional Task"></a>
All tasks above are SSHExecuteOperator.
I'm guessing I should be using the ShortCircuitOperator and / or XCom to manage the condition but I am not clear on how to implement that. Could you please describe the solution?</p> | 43,680,277 | 2 | 0 | null | 2017-04-28 10:49:32.153 UTC | 29 | 2020-04-28 15:04:46.49 UTC | 2018-01-12 17:36:41.227 UTC | null | 6,283,849 | null | 6,283,849 | null | 1 | 71 | python|conditional-statements|airflow | 75,673 | <p>You have to use <a href="https://airflow.incubator.apache.org/concepts.html#trigger-rules" rel="noreferrer">airflow trigger rules</a></p>
<p>All operators have a trigger_rule argument which defines the rule by which the generated task get triggered. </p>
<p>The trigger rule possibilities:</p>
<pre><code>ALL_SUCCESS = 'all_success'
ALL_FAILED = 'all_failed'
ALL_DONE = 'all_done'
ONE_SUCCESS = 'one_success'
ONE_FAILED = 'one_failed'
DUMMY = 'dummy'
</code></pre>
<p>Here is the idea to solve your problem: </p>
<pre><code>from airflow.operators.ssh_execute_operator import SSHExecuteOperator
from airflow.utils.trigger_rule import TriggerRule
from airflow.contrib.hooks import SSHHook
sshHook = SSHHook(conn_id=<YOUR CONNECTION ID FROM THE UI>)
task_1 = SSHExecuteOperator(
task_id='task_1',
bash_command=<YOUR COMMAND>,
ssh_hook=sshHook,
dag=dag)
task_2 = SSHExecuteOperator(
task_id='conditional_task',
bash_command=<YOUR COMMAND>,
ssh_hook=sshHook,
dag=dag)
task_2a = SSHExecuteOperator(
task_id='task_2a',
bash_command=<YOUR COMMAND>,
trigger_rule=TriggerRule.ALL_SUCCESS,
ssh_hook=sshHook,
dag=dag)
task_2b = SSHExecuteOperator(
task_id='task_2b',
bash_command=<YOUR COMMAND>,
trigger_rule=TriggerRule.ALL_FAILED,
ssh_hook=sshHook,
dag=dag)
task_3 = SSHExecuteOperator(
task_id='task_3',
bash_command=<YOUR COMMAND>,
trigger_rule=TriggerRule.ONE_SUCCESS,
ssh_hook=sshHook,
dag=dag)
task_2.set_upstream(task_1)
task_2a.set_upstream(task_2)
task_2b.set_upstream(task_2)
task_3.set_upstream(task_2a)
task_3.set_upstream(task_2b)
</code></pre> |
1,011,814 | Storing hierarchical data in Google App Engine Datastore? | <p>Can someone illustrate how I can store and easily query hierarchical data in google app engine datastore? </p> | 1,013,567 | 3 | 0 | null | 2009-06-18 09:46:27.177 UTC | 20 | 2016-09-02 22:57:34.39 UTC | 2016-09-02 22:57:34.39 UTC | null | 153,407 | null | 2,578,925 | null | 1 | 24 | google-app-engine|hierarchical-data|google-cloud-datastore | 6,967 | <p>The best option depends on your requirements. Here's a few solutions (I'm assuming you're using Python, since you didn't specify):</p>
<ol>
<li>If you need to do transactional updates on an entire tree, and you're not going to have more than about 1QPS of sustained updates to any one tree, you can use the built in support for heirarchial storage. When creating an entity, you can pass the "parent" attribute to specify a parent entity or key, and when querying, you can use the .ancestor() method (or 'ANCESTOR IS' in GQL to retrieve all descendants of a given entity.</li>
<li>If you don't need transactional updates, you can replicate the functionality of entity groups without the contention issues (and transaction safety): Add a db.ListProperty(db.Key) to your model called 'ancestors', and populate it with the list of ancestors of the object you're inserting. Then you can easily retrieve everything that's descended from a given ancestor with MyModel.all().filter('ancestors =', parent_key).</li>
<li>If you don't need transactions, and you only care about retrieving the direct children of an entity (not all descendants), use the approach outlined above, but instead of a ListProperty just use a ReferenceProperty to the parent entity. This is known as an Adjacency List.</li>
</ol>
<p>There are other approaches available, but those three should cover the most common cases.</p> |
1,177,020 | Android: How to make all elements inside LinearLayout same size? | <p>I would like to create a dialog to display a video title and tags. Below text I would like to add buttons View, Edit and Delete and make these elements same size. Does anyone know how to modify .xml layout file in order to make elements inside LinearView same size?</p>
<p>The current layout file looks like this:</p>
<pre><code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtTitle" android:text="[Title]" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtTags"
android:text="[Tags]" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnPlay"
android:text="View">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnEdit"
android:text="Edit">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnDelete"
android:text="Delete">
</Button>
</LinearLayout>
</LinearLayout>
</code></pre>
<p>I would appreciate if anyone could show the solution by modifying the pasted file content.</p>
<p>Thanks!</p> | 1,177,076 | 3 | 0 | null | 2009-07-24 11:15:15.07 UTC | 21 | 2016-06-24 10:04:13.233 UTC | 2013-12-13 21:21:38.213 UTC | null | 812,948 | null | 22,996 | null | 1 | 81 | android|layout | 81,061 | <p>Use <code>android:layout_width="0px"</code> and <code>android:layout_weight="1"</code> on the three <code>Button</code>s. That says the buttons should take up no more than 0 pixels, but the three of them should split any extra space between them. That should give you the visual effect you wish.</p> |
6,520,439 | How to configure MongoDB Java driver MongoOptions for production use? | <p>I've been searching the web looking for best practices for configuring MongoOptions for the MongoDB Java driver and I haven't come up with much other than the API. This search started after I ran into the "com.mongodb.DBPortPool$SemaphoresOut: Out of semaphores to get db
connection" error and by increasing the connections/multiplier I was able to solve that problem. I'm looking for links to or your best practices in configuring these options for production.</p>
<p>The options for the 2.4 driver include:
<a href="http://api.mongodb.org/java/2.4/com/mongodb/MongoOptions.html">http://api.mongodb.org/java/2.4/com/mongodb/MongoOptions.html</a></p>
<ul>
<li>autoConnectRetry</li>
<li>connectionsPerHost</li>
<li>connectTimeout</li>
<li>maxWaitTime</li>
<li>socketTimeout</li>
<li>threadsAllowedToBlockForConnectionMultiplier</li>
</ul>
<p>The newer drivers have more options and I would be interested in hearing about those as well.</p> | 6,521,704 | 1 | 0 | null | 2011-06-29 12:12:38.33 UTC | 82 | 2016-11-07 12:00:13.197 UTC | 2013-09-08 14:00:58.893 UTC | null | 150,992 | null | 43,365 | null | 1 | 103 | mongodb|production-environment|database-performance|database-tuning | 63,118 | <p>Updated to 2.9 :</p>
<ul>
<li><p><strong>autoConnectRetry</strong> simply means the driver will automatically attempt to reconnect to the server(s) after unexpected disconnects. In production environments you usually want this set to true.</p></li>
<li><p><strong>connectionsPerHost</strong> are the amount of physical connections a single Mongo instance (it's singleton so you usually have one per application) can establish to a mongod/mongos process. At time of writing the java driver will establish this amount of connections eventually even if the actual query throughput is low (in order words you will see the "conn" statistic in mongostat rise until it hits this number per app server). </p>
<p>There is no need to set this higher than 100 in most cases but this setting is one of those "test it and see" things. Do note that you will have to make sure you set this low enough so that the total amount of connections to your server do not exceed </p>
<p><code>db.serverStatus().connections.available</code></p>
<p>In production we currently have this at 40.</p></li>
<li><p><strong>connectTimeout</strong>. As the name suggest number of milliseconds the driver will wait before a connection attempt is aborted. Set timeout to something long (15-30 seconds) unless there's a realistic, expected chance this will be in the way of otherwise succesful connection attempts. Normally if a connection attempt takes longer than a couple of seconds your network infrastructure isn't capable of high throughput.</p></li>
<li><p><strong>maxWaitTime</strong>. Number of ms a thread will wait for a connection to become available on the connection pool, and raises an exception if this does not happen in time. Keep default.</p></li>
<li><p><strong>socketTimeout</strong>. Standard socket timeout value. Set to 60 seconds (60000).</p></li>
<li><p><strong>threadsAllowedToBlockForConnectionMultiplier</strong>. Multiplier for connectionsPerHost that denotes the number of threads that are allowed to wait for connections to become available if the pool is currently exhausted. This is the setting that will cause the "com.mongodb.DBPortPool$SemaphoresOut: Out of semaphores to get db connection" exception. It will throw this exception once this thread queue exceeds the threadsAllowedToBlockForConnectionMultiplier value. For example, if the connectionsPerHost is 10 and this value is 5 up to 50 threads can block before the aforementioned exception is thrown.</p>
<p>If you expect big peaks in throughput that could cause large queues temporarily increase this value. We have it at 1500 at the moment for exactly that reason. If your query load consistently outpaces the server you should just improve your hardware/scaling situation accordingly.</p></li>
<li><p><strong>readPreference</strong>. <strong>(UPDATED, 2.8+)</strong> Used to determine the default read preference and replaces "slaveOk". Set up a ReadPreference through one of the class factory method. <strong><em>A full description of the most common settings can be found at the end of this post</em></strong></p></li>
<li><p><strong>w</strong>. <strong>(UPDATED, 2.6+)</strong> This value determines the "safety" of the write. When this value is -1 the write will not report any errors regardless of network or database errors. WriteConcern.NONE is the appropriate predefined WriteConcern for this. If w is 0 then network errors will make the write fail but mongo errors will not. This is typically referred to as "fire and forget" writes and should be used when performance is more important than consistency and durability. Use WriteConcern.NORMAL for this mode. </p>
<p>If you set w to 1 or higher the write is considered safe. Safe writes perform the write and follow it up by a request to the server to make sure the write succeeded or retrieve an error value if it did not (in other words, it sends a getLastError() command after you write). Note that until this getLastError() command is completed the connection is reserved. As a result of that and the additional command the throughput will be signficantly lower than writes with w <= 0. With a w value of exactly 1 MongoDB guarantees the write succeeded (or verifiably failed) on the instance you sent the write to. </p>
<p>In the case of replica sets you can use higher values for w whcih tell MongoDB to send the write to at least "w" members of the replica set before returning (or more accurately, wait for the replication of your write to "w" members). You can also set w to the string "majority" which tells MongoDB to perform the write to the majority of replica set members (WriteConcern.MAJORITY). Typicall you should set this to 1 unless you need raw performance (-1 or 0) or replicated writes (>1). Values higher than 1 have a considerable impact on write throughput.</p></li>
<li><p><strong>fsync</strong>. Durability option that forces mongo to flush to disk after each write when enabled. I've never had any durability issues related to a write backlog so we have this on false (the default) in production.</p></li>
<li><p><strong>j</strong> *<em>(NEW 2.7+)</em>*. Boolean that when set to true forces MongoDB to wait for a successful journaling group commit before returning. If you have journaling enabled you can enable this for additional durability. Refer to <a href="http://www.mongodb.org/display/DOCS/Journaling">http://www.mongodb.org/display/DOCS/Journaling</a> to see what journaling gets you (and thus why you might want to enable this flag).</p></li>
</ul>
<p><strong>ReadPreference</strong>
The ReadPreference class allows you to configure to what mongod instances queries are routed if you are working with replica sets. The following options are available :</p>
<ul>
<li><p><strong>ReadPreference.primary()</strong> : All reads go to the repset primary member only. Use this if you require all queries to return consistent (the most recently written) data. This is the default.</p></li>
<li><p><strong>ReadPreference.primaryPreferred()</strong> : All reads go to the repset primary member if possible but may query secondary members if the primary node is not available. As such if the primary becomes unavailable reads become eventually consistent, but only if the primary is unavailable.</p></li>
<li><p><strong>ReadPreference.secondary()</strong> : All reads go to secondary repset members and the primary member is used for writes only. Use this only if you can live with eventually consistent reads. Additional repset members can be used to scale up read performance although there are limits to the amount of (voting) members a repset can have.</p></li>
<li><p><strong>ReadPreference.secondaryPreferred()</strong> : All reads go to secondary repset members if any of them are available. The primary member is used exclusively for writes unless all secondary members become unavailable. Other than the fallback to the primary member for reads this is the same as ReadPreference.secondary().</p></li>
<li><p><strong>ReadPreference.nearest()</strong> : Reads go to the nearest repset member available to the database client. Use only if eventually consistent reads are acceptable. The nearest member is the member with the lowest latency between the client and the various repset members. Since busy members will eventually have higher latencies this <em>should</em> also automatically balance read load although in my experience secondary(Preferred) seems to do so better if member latencies are relatively consistent.</p></li>
</ul>
<p>Note : All of the above have tag enabled versions of the same method which return TaggableReadPreference instances instead. A full description of replica set tags can be found here : <a href="http://docs.mongodb.org/manual/reference/replica-configuration/#tag-sets">Replica Set Tags</a></p> |
42,102,496 | Testing a gRPC service | <p>I'd like to test a gRPC service written in Go. The example I'm using is the Hello World server example from the <a href="https://github.com/grpc/grpc-go/blob/master/examples/helloworld/greeter_server/main.go" rel="noreferrer">grpc-go repo</a>.</p>
<p>The protobuf definition is as follows:</p>
<pre><code>syntax = "proto3";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
</code></pre>
<p>And the type in the <code>greeter_server</code> main is:</p>
<pre><code>// server is used to implement helloworld.GreeterServer.
type server struct{}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}
</code></pre>
<p>I've looked for examples but I couldn't find any on how to implement tests for a gRPC service in Go.</p> | 52,080,545 | 8 | 2 | null | 2017-02-08 00:22:29.407 UTC | 32 | 2021-06-07 03:27:31.563 UTC | null | null | null | null | 1,691,515 | null | 1 | 87 | go|grpc | 119,413 | <p>I think you're looking for the <code>google.golang.org/grpc/test/bufconn</code> package to help you avoid starting up a service with a real port number, but still allowing testing of streaming RPCs.</p>
<pre><code>import "google.golang.org/grpc/test/bufconn"
const bufSize = 1024 * 1024
var lis *bufconn.Listener
func init() {
lis = bufconn.Listen(bufSize)
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
go func() {
if err := s.Serve(lis); err != nil {
log.Fatalf("Server exited with error: %v", err)
}
}()
}
func bufDialer(context.Context, string) (net.Conn, error) {
return lis.Dial()
}
func TestSayHello(t *testing.T) {
ctx := context.Background()
conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
if err != nil {
t.Fatalf("Failed to dial bufnet: %v", err)
}
defer conn.Close()
client := pb.NewGreeterClient(conn)
resp, err := client.SayHello(ctx, &pb.HelloRequest{"Dr. Seuss"})
if err != nil {
t.Fatalf("SayHello failed: %v", err)
}
log.Printf("Response: %+v", resp)
// Test for output here.
}
</code></pre>
<p>The benefit of this approach is that you're still getting network behavior, but over an in-memory connection without using OS-level resources like ports that may or may not clean up quickly. And it allows you to test it the way it's actually used, and it gives you proper streaming behavior.</p>
<p>I don't have a streaming example off the top of my head, but the magic sauce is all above. It gives you all of the expected behaviors of a normal network connection. The trick is setting the WithDialer option as shown, using the bufconn package to create a listener that exposes its own dialer. I use this technique all the time for testing gRPC services and it works great.</p> |
35,005,261 | How to check if a map is empty in Golang? | <p>When the following code:</p>
<pre><code>m := make(map[string]string)
if m == nil {
log.Fatal("map is empty")
}
</code></pre>
<p>is run, the log statement is not executed, while <code>fmt.Println(m)</code> indicates that the map is empty:</p>
<pre><code>map[]
</code></pre> | 35,005,294 | 2 | 1 | null | 2016-01-26 00:51:18.413 UTC | 9 | 2022-03-14 16:01:41.797 UTC | 2022-03-14 16:00:13.387 UTC | null | 2,777,965 | null | 2,777,965 | null | 1 | 85 | go|hashmap | 95,646 | <p>You can use <code>len</code>:</p>
<pre><code>if len(m) == 0 {
....
}
</code></pre>
<p>From <a href="https://golang.org/ref/spec#Length_and_capacity" rel="noreferrer">https://golang.org/ref/spec#Length_and_capacity</a></p>
<blockquote>
<p>len(s) map[K]T map length (number of defined keys)</p>
</blockquote> |
66,389,043 | How can I use Vite env variables in vite.config.js? | <p>With the following <code>.env</code> in my Vite project:</p>
<pre class="lang-sh prettyprint-override"><code># To prevent accidentally leaking env variables to the client, only
# variables prefixed with VITE_ are exposed to your Vite-processed code
VITE_NAME=Wheatgrass
VITE_PORT=8080
</code></pre>
<p>How can I use <code>VITE_PORT</code> in my <code>vite.config.js</code>?</p> | 66,389,044 | 2 | 0 | null | 2021-02-26 16:01:20.67 UTC | 8 | 2022-08-26 23:57:43.303 UTC | 2022-08-26 23:57:43.303 UTC | null | 62,076 | null | 1,428,653 | null | 1 | 31 | javascript|vuejs3|vite | 31,707 | <p>You can load the <code>app level</code> env variables and add them to the <code>Node level</code> env variables:</p>
<pre class="lang-js prettyprint-override"><code>import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
export default ({ mode }) => {
process.env = {...process.env, ...loadEnv(mode, process.cwd())};
// import.meta.env.VITE_NAME available here with: process.env.VITE_NAME
// import.meta.env.VITE_PORT available here with: process.env.VITE_PORT
return defineConfig({
plugins: [vue()],
server: {
port: process.env.VITE_PORT,
},
});
}
</code></pre> |
41,239,028 | Switch vs. SwitchCompat | <p><em>A <a href="https://developer.android.com/reference/android/widget/Switch.html" rel="noreferrer">Switch</a> is a two-state toggle switch widget that can select between two options</em> and a <em><a href="https://developer.android.com/reference/android/support/v7/widget/SwitchCompat.html" rel="noreferrer">SwitchCompat</a> is a version of the Switch widget which on devices back to API v7. It does not make any attempt to use the platform provided widget on those devices which it is available normally.</em></p>
<p>Given that both are available to any modern Android 4+ app developer, what are the reasons to use one or another? What are the core differences?</p> | 41,239,389 | 1 | 1 | null | 2016-12-20 09:36:27.593 UTC | 5 | 2016-12-21 09:34:35.057 UTC | null | null | null | null | 2,013,738 | null | 1 | 32 | android|material-design|android-support-library | 10,274 | <p>There is a huge difference. <code>Switch</code> is platform dependent. It can look differently on different version systems. On post-lollipop devices it inherits from Material Design styles, on pre-lollipop it inherits from holo styles.</p>
<p><code>SwitchCompat</code> inherits from Material Design on every system version.</p>
<p>Of course context <code>Activity</code> must be <code>AppCompat</code> one.</p>
<p>Using components from support libraries you ensure the same behaviour on all system versions.</p>
<p><a href="https://i.stack.imgur.com/hr6nk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nGv0q.png" alt="SwitchCompat and Switch image on Android 4 and Android 7"></a></p> |
5,794,047 | What is thread safe (C#) ? (Strings, arrays, ... ?) | <p>I'm quite new to C# so please bear with me. I'm a bit confused with the thread safety. When is something thread safe and when something isn't?</p>
<p>Is <strong>reading</strong> (just reading from something that was initialized before) from a field always thread safe? </p>
<pre><code>//EXAMPLE
RSACryptoServiceProvider rsa = new RSACrytoServiceProvider();
rsa.FromXmlString(xmlString);
//Is this thread safe if xml String is predifined
//and this code can be called from multiple threads?
</code></pre>
<p>Is <strong>accessing</strong> an object from an array or list always thread safe (in case you use a for loop for enumeration)?</p>
<pre><code>//EXAMPLE (a is local to thread, array and list are global)
int a = 0;
for(int i=0; i<10; i++)
{
a += array[i];
a -= list.ElementAt(i);
}
</code></pre>
<p>Is <strong>enumeration</strong> always/ever thread safe?</p>
<pre><code>//EXAMPLE
foreach(Object o in list)
{
//do something with o
}
</code></pre>
<p>Can <strong>writing and reading</strong> to a particular field ever result in a corrupted read (half of the field is changed and half is still unchanged) ?</p>
<p>Thank you for all your answers and time.</p>
<p><strong>EDIT:</strong> I meant if all threads are only reading & using (not writing or changing) object. (except for the last question where it is obvious that I meant if threads both read and write). Because I do not know if plain access or enumeration is thread safe.</p> | 5,794,114 | 5 | 0 | null | 2011-04-26 17:23:07.08 UTC | 12 | 2013-04-02 15:54:14.09 UTC | 2013-04-02 15:54:14.09 UTC | null | 200,449 | null | 603,245 | null | 1 | 24 | c#|arrays|string|thread-safety|enumeration | 13,251 | <p>It's different for different cases, but in general, reading is safe if all threads are reading. If any are writing, neither reading or writing is safe unless it can be done atomically (inside a synchronized block or with an atomic type).</p>
<p>It isn't definite that reading is ok -- you never know what is happening under the hoods -- for example, a getter might need to initialize data on first usage (therefore writing to local fields).</p>
<p>For Strings, you are in luck -- they are immutable, so all you can do is read them. With other types, you will have to take precautions against them changing in other threads while you are reading them.</p> |
6,074,683 | Display datepicker on tapping on textfield | <p>How can I display a datetimepicker control on tap of a textbox? </p>
<p>I have a user interface that has arrival and departure text fields, and when a user clicks on arrival textbox it should bring up a datetimepicker control up instead of a keyboard and the same with the departure textbox.</p> | 6,075,062 | 5 | 0 | null | 2011-05-20 16:07:31.023 UTC | 18 | 2017-06-28 05:07:33.713 UTC | 2011-06-01 01:24:16.537 UTC | null | 63,550 | null | 644,936 | null | 1 | 24 | ios4|xcode4|uitextfield|uidatepicker | 48,032 | <p>You can use <code>inputView</code> and <code>inputAccessoryView</code> properties of the text field for this. Create the date picker and set it to the input views of the two text fields. Also create another view for the <code>Done</code> button and it as their accessory view. You will need that button to dismiss the input view. </p>
<p>The <code>Done</code> button must be wired up to function which basically does this –</p>
<pre><code>if ( [textField1 isFirstResponder] ) {
[textField1 resignFirstResponder];
} else if ( [textField2 isFirstResponder] ) {
[textField2 resignFirstResponder];
}
</code></pre>
<p>Another option would be to subclass <code>UITextField</code> and override <code>inputView</code> and <code>inputAccessoryView</code>. This is the way to go when there are loads of them.</p>
<p><strong>Example</strong></p>
<pre><code>@interface CustomKeyboardAppDelegate : NSObject <UIApplicationDelegate> {
...
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITextField *textField;
@property (nonatomic, retain) IBOutlet UIToolbar *accessoryView;
@property (nonatomic, retain) IBOutlet UIDatePicker *customInput;
- (IBAction)dateChanged:(id)sender;
- (IBAction)doneEditing:(id)sender;
@end
</code></pre>
<p>In the XIB, Pull out a <code>UIToolbar</code> and a <code>UIDatePicker</code> but don't attach it to the view. Connect the outlets appropriately. <code>dateChanged:</code> responds to changes in the date picker and <code>doneEditing:</code> is called when the <code>Done</code> button in the tool bar is clicked. Connect them too. The methods are implemented as listed below.</p>
<pre><code>@implementation CustomKeyboardAppDelegate
@synthesize window=_window;
@synthesize textField = _textField;
@synthesize accessoryView = _accessoryView;
@synthesize customInput = _customInput;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.textField.inputView = self.customInput;
self.textField.inputAccessoryView = self.accessoryView;
...
}
...
- (IBAction)dateChanged:(id)sender {
UIDatePicker *picker = (UIDatePicker *)sender;
self.textField.text = [NSString stringWithFormat:@"%@", picker.date];
}
- (IBAction)doneEditing:(id)sender {
[self.textField resignFirstResponder];
}
@end
</code></pre>
<p>The last two methods will bloat up as more text fields depend on this picker.</p> |
6,006,017 | Is there a way to prevent the keyboard from dismissing? | <p>I realize that this is the inverse of most posts, but I would like for the keyboard to remain up <strong>even if the 'keyboard down' button is pressed</strong>.</p>
<p>Specifically, I have a view with two <code>UITextField</code>s. With the following delegate method</p>
<pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)textField {
return NO;
}
</code></pre>
<p>I am able to keep the keyboard up even if the user presses the <code>Done</code> button on the keyboard or taps anywhere else on the screen EXCEPT for that pesky keyboard down button on the bottom right of the keyboard. </p>
<p>I am using this view like a modal view (though the view is associated with a ViewController that gets pushed in a UINavigationController), so it really works best from a user perspective to keep the keyboard up all of the time. If anyone knows how to achieve this, please let me know! Thanks!</p>
<p><strong>UPDATE</strong> Still no solution! When <code>Done</code> is pressed, it triggers <code>textFieldShouldReturn</code>, but when the <code>Dismiss</code> button is pressed, it triggers <code>textFieldDidEndEditing</code>. I cannot block the <code>textField</code> from ending editing or it <strong>never</strong> goes away. Somehow, I really want to have a method that detects the <code>Dismiss</code> button and ignores it. If you know a way, please enlighten me!</p> | 6,040,273 | 6 | 9 | null | 2011-05-15 01:57:37.193 UTC | 5 | 2017-02-23 11:17:26.747 UTC | 2011-05-21 17:52:22.287 UTC | null | 544,050 | null | 544,050 | null | 1 | 28 | iphone|ios|ipad|uitextfield|uikeyboard | 18,834 | <p><em><strong>There IS a way to do this.</em></strong> Because <code>UIKeyboard</code> subclasses <code>UIWindow</code>, the only thing big enough to get in <code>UIKeyboard</code>'s way is another <code>UIWindow</code>.</p>
<pre><code>- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(coverKey) name:UIKeyboardDidShowNotification object:nil];
[super viewDidLoad];
}
- (void)coverKey {
CGRect r = [[UIScreen mainScreen] bounds];
UIWindow *myWindow = [[UIWindow alloc] initWithFrame:CGRectMake(r.size.width - 50 , r.size.height - 50, 50, 50)];
[myWindow setBackgroundColor:[UIColor clearColor]];
[super.view addSubview:myWindow];
[myWindow makeKeyAndVisible];
}
</code></pre>
<p>This works on iPhone apps. Haven't tried it with iPad. You may need to adjust the size of <code>myWindow</code>. Also, I didn't do any mem management on <code>myWindow</code>. So, consider doing that, too.</p> |
6,049,207 | Convert UTC to current locale time | <p>I am downloading some JSON data from a webservice. In this JSON I've got some Date/Time values. Everything in UTC.
How can I parse this date string so the result Date object is in the current locale?</p>
<p>For example: the Server returned "2011-05-18 16:35:01" and my device should now display "2011-05-18 18:35:01" (GMT +2)</p>
<p>My current code:</p>
<pre>
<code>SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));</code>
</pre> | 6,049,385 | 7 | 1 | null | 2011-05-18 18:15:49.787 UTC | 18 | 2018-01-24 14:57:58.057 UTC | 2011-05-18 18:21:05.277 UTC | null | 759,724 | null | 759,724 | null | 1 | 39 | java|android|utc | 64,496 | <p>It has a set timezone method:</p>
<pre><code>SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));
</code></pre>
<p>all done!</p> |
5,706,548 | How do I create a release build in Xcode? | <p>Why is it that when I build an application, Xcode creates a debug build? I want to create a release build. How can I do this?</p> | 5,706,563 | 7 | 0 | null | 2011-04-18 17:26:51.197 UTC | 24 | 2022-07-21 12:35:03.893 UTC | 2017-01-05 23:51:32.313 UTC | null | 3,681,880 | null | 630,412 | null | 1 | 93 | ios|xcode|macos|build|release | 109,202 | <p>It is done over building an Archive version.</p>
<p>First connect a iOS device to your Mac. Then select that device as target in Xcode.</p>
<p>Now click on the tab "Product" and click on "Archive"</p> |
5,625,436 | How can I remove just the Maximize button from a JFrame? | <p>I have a <a href="http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html" rel="noreferrer">JFrame</a> and want to remove the <strong>maximize</strong> button from that.</p>
<p>I wrote the code below, but it removed maximize, <em>minimize, and close</em> from my <code>JFrame</code>.</p>
<pre><code>JFrame frame = new JFrame();
frame.add(kart);
frame.setUndecorated(true);
frame.setVisible(true);
frame.setSize(400, 400);
</code></pre>
<p>I want to only remove the maximize button from the <code>JFrame</code>.</p> | 5,625,661 | 9 | 1 | null | 2011-04-11 18:00:23.817 UTC | 6 | 2019-12-11 16:45:39.237 UTC | 2011-04-11 18:22:00.953 UTC | null | 513,838 | null | 578,462 | null | 1 | 38 | java|swing|jframe|titlebar|maximize-window | 69,337 | <p>Make it not resizable:</p>
<pre><code>frame.setResizable(false);
</code></pre>
<p>You will still have the minimize and close buttons.</p> |
17,944,931 | CSS 100% height on width | <p>Is it even possible to make my width 100% of height using only CSS? Without using Javascript or the like.</p>
<pre><code>{
width: /*100% of height*/
}
</code></pre> | 17,944,984 | 2 | 1 | null | 2013-07-30 10:47:26.873 UTC | 8 | 2013-07-30 11:06:23.597 UTC | 2013-07-30 10:55:33.357 UTC | null | 441,387 | null | 1,314,444 | null | 1 | 9 | css | 6,661 | <p>There are new css units for this</p>
<pre><code>width: 100vh;
</code></pre>
<p>This means that the width of the element will be 100% of the viewport height.</p>
<blockquote>
<p>CSS3 has some new values for sizing things relative to the current
viewport size: vw, vh, and vmin.
One unit on any of the three values is 1% of the viewport axis.
"Viewport" == browser window size == window object. If the viewport is
40cm wide, 1vw == 0.4cm.</p>
<p>1vw = 1% of viewport width 1vh = 1% of viewport height 1vmin = 1vw or
1vh, whichever is smaller 1vmax = 1vw or 1vh, whichever is larger (<a href="http://css-tricks.com/viewport-sized-typography/" rel="noreferrer">css-tricks post</a>)</p>
</blockquote>
<p>Reference: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/length" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/length</a></p>
<p>PS: Support for these new properties is actually quite good in modern browsers. <a href="http://caniuse.com/viewport-units" rel="noreferrer">See here</a></p> |
39,246,498 | Compiler vs Interpreter vs Transpiler | <p>During a reactJS session that I was attending, the presenter used a term transpiler for some code conversion/porting happening. I've always used and heard the terms compiler and interpreter when it comes to converting a language code to a runnable form on a computer system/machine. Transpiler is new to me. How is a transpiler different from a compiler or an interpreter and why it is really needed?</p> | 39,246,810 | 7 | 2 | null | 2016-08-31 10:00:07.94 UTC | 20 | 2020-08-02 10:34:56.27 UTC | 2020-08-02 10:34:56.27 UTC | null | 465,053 | null | 465,053 | null | 1 | 63 | compiler-construction|language-agnostic|terminology|interpreter|transpiler | 18,309 | <p>As is mentioned in this <a href="https://en.wikipedia.org/wiki/Source-to-source_compiler">Wiki article</a>, it is a type of compiler which <em>translates</em> source code from one programming language to another programming language. The source code might be in some language no longer used, or doesn't support latest hardware/software advancements, or as per programmer's convenience/favoritism.</p>
<p>A VB6 to VB.NET converter can be thought of as a Transpiler. I might think of <em>COBOL to C# / C++ / Java</em> tool as a transpiler.</p> |
43,931,538 | How to load es6, react, babel code in html with cdn? | <p>I have <a href="https://codepen.io/iamanoopc/pen/vmdQGX" rel="noreferrer">Codepen</a> code that I'm trying to replicate on an web page using just three files, index.html, main.js, and style.css. I tried loading these scripts on the head tag of HTML file.<br></p>
<pre><code><script src="https://npmcdn.com/[email protected]/dist/btib.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.min.js"></script>
</code></pre>
<p>However, it's not working. All I get is this error</p>
<pre><code>Uncaught SyntaxError: Unexpected token <
</code></pre>
<p>what are necessary CDN script files to load this react-code to HTML?</p> | 43,931,595 | 4 | 0 | null | 2017-05-12 07:12:28.4 UTC | 9 | 2019-06-27 17:18:35.367 UTC | null | null | null | null | 4,531,869 | null | 1 | 14 | javascript|reactjs|babeljs | 27,070 | <p>You need to use <code>babel standalone</code> script to transcompile the code, and you need to include the script for <code>react and react-dom</code>, use these it will work:</p>
<pre><code><script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</code></pre>
<p><strong>Reason why it is working with codepen:</strong> check the setting/javascript, there you will find the babel is selected as <strong>JavaScript Preprocessor</strong>, codepen is including the script automatically, but to run these files locally you need to include the <code>standalone script</code>.</p>
<p><strong>Update:</strong></p>
<p>1- You need to define the script after the div in which you are rendering the react code, otherwise it will throw the error. like this:</p>
<pre><code><body>
<div id="root"></div>
<script type="text/babel" src="pomodoro.js"></script>
</body>
</code></pre>
<p>2- Use <code>ReactDOM.render</code> instead of <code>React.render</code>.</p>
<p>Check the working code:</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-html lang-html prettyprint-override"><code><html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js'></script>
</head>
<body>
<div id='root'></div>
<script type='text/babel'>
class SetTimer extends React.Component{
render(){
return (
<div className="set-timer">work <br/> session
<div className="minus-add">
<button className="setting-button" id="minus-timer" onClick={this.props.minus}>-</button>
<button className="setting-button" id="add-timer" onClick={this.props.add}>+</button>
</div>
</div>
);
}
}
class SetBreak extends React.Component{
render(){
return (
<div className="set-break"> break<br/> session
<div className="minus-add">
<button className="setting-button" id="minus-break" onClick={this.props.minusbreak}>-</button>
<button className="setting-button" id="add-break" onClick={this.props.addbreak}>+</button>
</div>
</div>
);
}
}
const leftPad = (time)=>{
return (time<10)? '0'+time :time
}
const TimerDisplay = (props) => (
<div className="timer-display"><span className="worklabel">Work session time</span><br/>
{props.currentTime}
<div className="breaktime"><span className="breaklabel">break session time</span><br/>{props.breakTime}</div>
</div>
);
// let baseTime= 25;
class App extends React.Component {
constructor(){
super();
this.state = {
baseTime:25,
breakTime:5,
currentTime: moment.duration(25,'minutes'),
timer:null,
startbuttonvisible:true,
pausebuttonvisible:false,
resumebuttonvisible:false,
stopbuttonvisible:false,
}
this.minus =this.minus.bind(this);
this.add =this.add.bind(this);
this.minusbreak =this.minusbreak.bind(this);
this.addbreak =this.addbreak.bind(this);
this.startTimer = this.startTimer.bind(this);
this.pauseTimer = this.pauseTimer.bind(this);
this.resumeTimer = this.resumeTimer.bind(this);
this.stopTimer = this.stopTimer.bind(this);
this.reduceTimer = this.reduceTimer.bind(this);
}
add(){
this.setState({
baseTime:this.state.baseTime+1
});
}
minus(){
this.setState({
baseTime:this.state.baseTime-1
});
}
addbreak(){
this.setState({
breakTime:this.state.breakTime+1
});
}
minusbreak(){
this.setState({
breakTime:this.state.breakTime-1
});
}
startTimer(){
this.setState({
timer: setInterval(this.reduceTimer, 1000),
startbuttonvisible:false,
pausebuttonvisible:true,
stopbuttonvisible:true,
});
}
pauseTimer(){
clearInterval(this.state.timer);
this.setState({
pausebuttonvisible:false,
resumebuttonvisible:true,
});
}
resumeTimer(){
this.setState({
timer: setInterval(this.reduceTimer, 1000),
startbuttonvisible:false,
pausebuttonvisible:true,
stopbuttonvisible:true,
resumebuttonvisible:false,
});
}
stopTimer(){
clearInterval(this.state.timer);
this.setState({
baseTime:25,
timer: null,
startbuttonvisible:true,
pausebuttonvisible:false,
stopbuttonvisible:false,
resumebuttonvisible:false,
});
}
reduceTimer(){
if(this.state.baseTime === 0) return;
const newTime = this.state.baseTime - 1;
this.setState({
baseTime: newTime,
});
}
render() {
return (
<div className="container">
<div className="timebox">
<div className="header">
Pomodoro Clock
</div>
<TimerDisplay currentTime={this.state.baseTime} breakTime={this.state.breakTime}/>
<div id="action-title">
<small>SETTINGS</small>
</div>
<div className="actions">
<SetTimer minus={this.minus} add={this.add}/>
<SetBreak minusbreak={this.minusbreak} addbreak={this.addbreak}/>
</div>
<div className="timer-control">
{this.state.startbuttonvisible ? <button id="start-timer" onClick={this.startTimer}>
START
</button> : null}
{this.state.pausebuttonvisible ? <button id="pause-timer" onClick={this.pauseTimer}>
PAUSE
</button>: null}
{this.state.resumebuttonvisible ? <button id="resume-timer" onClick={this.resumeTimer}>
RESUME
</button>: null}
{this.state.stopbuttonvisible ? <button id="stop-timer" onClick={this.stopTimer}>
STOP
</button>: null}
</div>
</div>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
</script>
</body>
</html></code></pre>
</div>
</div>
</p> |
44,128,959 | Multiple components within a file | <p>Says I have component A</p>
<p>like </p>
<pre><code>export default class ComponentA extends components {
render(){
return() //use componentB here?
}
}
class ComponentB extends components {
}
</code></pre>
<p>how can I create another component and use it within ComponentA?</p> | 44,128,989 | 3 | 0 | null | 2017-05-23 07:55:32.397 UTC | 2 | 2018-02-19 09:18:29.94 UTC | 2018-02-19 08:58:15.877 UTC | null | 5,185,595 | null | 7,934,660 | null | 1 | 16 | javascript|reactjs | 42,735 | <blockquote>
<p>How can I create another component and use it within ComponentA?</p>
</blockquote>
<p>There are two possible ways of doing that:</p>
<p><strong>1-</strong> Define the component in the same file, exporting of that component will be not required because you will use that component in the same file.</p>
<p><strong>2-</strong> Define the component in another file then export that component. Importing of component will be required in this case.</p>
<hr>
<p>We can create as many components as we want in the same file, and we can use those components in the same way as we use HTML tags <code>div, span, p</code> etc.</p>
<p><strong>Example:</strong></p>
<p>Using <code>ComponentB</code> inside another component <code>ComponentA</code>:</p>
<pre><code>export default class ComponentA extends components {
render(){
return(
<div>
{/*other code*/}
<ComponentB /> // notice here, rendering ComponentB
</div>
)
}
}
</code></pre>
<p>Define <code>ComponentB</code> in same file like this:</p>
<pre><code>class ComponentB extends components {
}
</code></pre>
<p>Define <code>ComponentB</code> like this in another file:</p>
<pre><code>export default class ComponentB extends components {
}
</code></pre> |
49,512,099 | AKS. Can't pull image from an acr | <p>I try to pull image from an ACR using a secret and I can't do it.</p>
<p>I created resources using azure cli commands:</p>
<pre><code>az login
az provider register -n Microsoft.Network
az provider register -n Microsoft.Storage
az provider register -n Microsoft.Compute
az provider register -n Microsoft.ContainerService
az group create --name aksGroup --location westeurope
az aks create --resource-group aksGroup --name aksCluster --node-count 1 --generate-ssh-keys -k 1.9.2
az aks get-credentials --resource-group aksGroup --name aksCluster
az acr create --resource-group aksGroup --name aksClusterRegistry --sku Basic --admin-enabled true
</code></pre>
<p>After that I logged in and pushed image successfully to created ACR from local machine.</p>
<pre><code>docker login aksclusterregistry.azurecr.io
docker tag jetty aksclusterregistry.azurecr.io/jetty
docker push aksclusterregistry.azurecr.io/jetty
</code></pre>
<p>The next step was creating a secret:</p>
<pre><code>kubectl create secret docker-registry secret --docker-server=aksclusterregistry.azurecr.io --docker-username=aksClusterRegistry --docker-password=<Password from tab ACR/Access Keys> [email protected]
</code></pre>
<p>And eventually I tried to create pod with image from the ACR:</p>
<pre><code>#pod.yml
apiVersion: v1
kind: Pod
metadata:
name: jetty
spec:
containers:
- name: jetty
image: aksclusterregistry.azurecr.io/jetty
imagePullSecrets:
- name: secret
kubectl create -f pod.yml
</code></pre>
<p>In result I have a pod with status ImagePullBackOff:</p>
<pre><code>>kubectl get pods
NAME READY STATUS RESTARTS AGE
jetty 0/1 ImagePullBackOff 0 1m
> kubectl describe pod jetty
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 2m default-scheduler Successfully assigned jetty to aks-nodepool1-62963605-0
Normal SuccessfulMountVolume 2m kubelet, aks-nodepool1-62963605-0 MountVolume.SetUp succeeded for volume "default-token-w8png"
Normal Pulling 2m (x2 over 2m) kubelet, aks-nodepool1-62963605-0 pulling image "aksclusterregistry.azurecr.io/jetty"
Warning Failed 2m (x2 over 2m) kubelet, aks-nodepool1-62963605-0 Failed to pull image "aksclusterregistry.azurecr.io/jetty": rpc error: code = Unknown desc = Error response from daemon: Get https://aksclusterregistry.azurecr.io/v2/jetty/manifests/latest: unauthorized: authentication required
Warning Failed 2m (x2 over 2m) kubelet, aks-nodepool1-62963605-0 Error: ErrImagePull
Normal BackOff 2m (x5 over 2m) kubelet, aks-nodepool1-62963605-0 Back-off pulling image "aksclusterregistry.azurecr.io/jetty"
Normal SandboxChanged 2m (x7 over 2m) kubelet, aks-nodepool1-62963605-0 Pod sandbox changed, it will be killed and re-created.
Warning Failed 2m (x6 over 2m) kubelet, aks-nodepool1-62963605-0 Error: ImagePullBackOff
</code></pre>
<p>What's wrong? Why does approach with secret not work?
Please don't advice me approach with service principal, because I would like to understand why this aproach doesn't work. I think it must be working. </p> | 49,518,263 | 3 | 3 | null | 2018-03-27 11:48:34.913 UTC | 3 | 2020-06-17 14:46:17.427 UTC | null | null | null | null | 1,762,235 | null | 1 | 33 | azure|docker|kubernetes|azure-cli2 | 24,125 | <p>This looks good to me as well. That said, the recommendation is not to use the admin account, rather a service principle. With the SP you gain some granular control over access rights to the ACR instance (read, contributor, owner). </p>
<p>This doc includes two methods for authentication between AKS and ACR using service principles. </p>
<p><a href="https://docs.microsoft.com/en-us/azure/container-registry/container-registry-auth-aks" rel="noreferrer">https://docs.microsoft.com/en-us/azure/container-registry/container-registry-auth-aks</a></p> |
24,607,339 | Lollipop RippleDrawable vs Selector for Pre-Lollipop | <p>I have buttons with different draw9patch <code>png</code> as background. Currently the buttons are controlled by <code>selector</code> which look something like this:</p>
<pre><code><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/disabled" android:state_enabled="false"/>
<item android:drawable="@drawable/focused" android:state_focused="true"/>
<item android:drawable="@drawable/default"/>
</selector>
</code></pre>
<p>For the <strong>Android Lollipop</strong> they have a <code>RippleDrawable</code> for the touch effect, which goes something like this:</p>
<pre><code><ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="?android:colorControlHighlight">
<item>
...
</item>
</ripple>
</code></pre>
<p>Regarding the new touch ripple effect:</p>
<p><strong>1:</strong> Can I set draw9patch as background for <code>RippleDrawable</code>?</p>
<p><strong>2:</strong> How do I accomodate the above two different xml's I want to follow Material design? Do I have to fork out a new folder/layout xml for the new <code>RippleDrawable</code>?</p> | 24,621,606 | 1 | 1 | null | 2014-07-07 09:32:16.617 UTC | 23 | 2020-02-02 07:19:57.27 UTC | 2020-02-02 07:19:57.27 UTC | null | 6,782,707 | null | 1,919,013 | null | 1 | 38 | android|material-design|android-5.0-lollipop|ripple|rippledrawable | 32,032 | <p>1) Yes. See the documentation for RippleDrawable for more details on how layers are composited, but basically you want:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:attr/colorControlHighlight">
<item android:drawable="@drawable/yourninepatch" />
</ripple>
</code></pre>
<p>Or to also handle the disabled state in a clean way, you might want:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:attr/colorControlHighlight">
<item>
<selector>
<item android:state_enabled="false">
<nine-patch
android:src="@drawable/yourninepatch"
android:alpha="?android:attr/disabledAlpha" />
</item>
<item>
<nine-patch android:src="@drawable/yourninepatch" />
</item>
</selector>
</item>
</ripple>
</code></pre>
<p>2) Yes, you should place your ripple XML in drawable-v21.</p> |
21,633,537 | Javascript: How to read a hand held barcode scanner best? | <p>I'd like to be able to scan barcodes via a hand held scanner and handle the results with Javascript.</p>
<p>A barcode-scanner works almost like a keyboard. It outputs the scanned/translated (barcode->number) data raw (right?). Actually I just need to catch the output and proceed. But how?</p>
<p>Here's some pseudocode I'd like to make work:</p>
<pre><code>$(document).on("scanButtonDown", "document", function(e) {
// get scanned content
var scannedProductId = this.getScannedContent();
// get product
var product = getProductById(scannedProductId);
// add productname to list
$("#product_list").append("<li>" + product.name + "</li>");
});
</code></pre>
<ul>
<li>Any ideas (frameworks, plugins, snippets)?</li>
<li>Any barcode-scanner (hardware) recommendation?</li>
</ul>
<p>Thanks in advance!</p>
<p><em>I found <a href="https://stackoverflow.com/questions/3435561/reading-from-barcode-scanner">this</a> and <a href="https://stackoverflow.com/questions/10665392/jquery-barcode-scanner-integration">this</a> good questions but I'd like to get more information about the handling. Just to focus a textarea may be not enough in my case.</em></p> | 21,633,799 | 13 | 0 | null | 2014-02-07 16:57:15.8 UTC | 32 | 2022-08-09 09:18:14.9 UTC | 2017-05-23 12:17:45.237 UTC | null | -1 | null | 1,792,858 | null | 1 | 64 | javascript|jquery|ajax|angularjs|barcode-scanner | 125,946 | <p>Your pseudo code won't work, because you don't have access to the scanner to catch events like <code>scanButtonDown</code>. Your only option is a HID scanner, which behaves exactly like a keyboard. To differentiate scanner input from keyboard input you have two options: Timer-based or prefix-based.</p>
<p><strong>Timer-based</strong></p>
<p>The scanner is likely to input characters much quicker than a user can (sensibly) with a keyboard. Calculate how quickly keystrokes are being received and buffer fast input into a variable to pass to your <code>getProductsId</code> function. @Vitall wrote a <a href="https://stackoverflow.com/a/15354814/44816">reusable jQuery solution for catching barcode scanner input</a>, you would just need to catch the onbarcodescanned event.</p>
<p><strong>Prefix-based</strong></p>
<p>Most scanners can be configured to prefix all scanned data. You can use the prefix to start intercepting all input and once you've got your barcode you stop intercepting input.</p>
<p><em>Full disclosure</em>: I work as a consultant to Socket Mobile, Inc. who make handheld scanners.</p> |
51,343,828 | How to parse Chrome bookmarks "date_added" value to a Date | <p>The Chrome bookmarks file is JSON which contains a "date_added" value that represents a particular date and time, e.g.</p>
<pre><code>{
"checksum": "05b8bba8b5f0e9ad1cc8034755557735",
"roots": {
"bookmark_bar": {
"children": [ {
"children": [ {
"date_added": "13170147422089597",
"id": "121",
"name": "NativeScript: Getting Started Guide",
"type": "url",
"url": "https://docs.nativescript.org/tutorial/chapter-0"
} ],
...
</code></pre>
<p>I have tried treating the value as nanoseconds and passing to the Date constructor:</p>
<pre><code>new Date(13170147422089597 / 1000); // 2387-05-07T06:17:02.089Z
</code></pre>
<p>but that doesn't seem correct.</p>
<p>How should the value "13170147422089597" be converted to a Date or date string?</p> | 51,343,829 | 5 | 1 | null | 2018-07-14 22:20:43.723 UTC | 8 | 2021-06-14 08:29:04.817 UTC | null | null | null | null | 257,182 | null | 1 | 12 | javascript|google-chrome|date | 5,882 | <p>The Chrome bookmarks time value is microseconds from an epoch of 1601-01-01T00:00:00Z. To convert to a Date:</p>
<ol>
<li>Divide by 1,000 to get milliseconds</li>
<li>Adjust to an epoch of 1970-01-01T00:00:00Z</li>
<li>Pass the resulting value to the Date constructor</li>
</ol>
<p>E.g.</p>
<pre><code>var timeValue = '13170147422089597';
new Date(Date.UTC(1601,0,1) + timeValue / 1000); // 2018-05-07T06:17:02.089Z
</code></pre>
<p>Storing the value Date.UTC(1601,0,1) as a constant (-11644473600000) and converting to a function gives:</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>function chromeTimeValueToDate(tv) {
var epoch = -11644473600000;
return new Date(epoch + tv / 1000);
}
// Example
['13170147422089597',
'13150297844686316',
'13115171381595644'].forEach( tv => {
console.log(chromeTimeValueToDate(tv))
});</code></pre>
</div>
</div>
</p> |
9,026,069 | Python lightweight database wrapper for SQLite | <p>Is there a lightweight database wrapper in Python that I can use for SQLite. I would like something like Django's ORM, but that I can just point to a database file and it'll make the required API for me (i.e handle all the CRUD). </p> | 9,027,726 | 7 | 0 | null | 2012-01-26 22:03:48.483 UTC | 9 | 2020-09-21 22:17:53.747 UTC | null | null | null | null | 377,327 | null | 1 | 43 | python|sqlite | 37,631 | <p>Yeah, SQLAlchemy is great, but there are also other options. One of them is Peewee.
Very lightweight and it may fits perfectly with what you are looking for.</p>
<p><a href="https://github.com/coleifer/peewee" rel="noreferrer">https://github.com/coleifer/peewee</a></p> |
9,054,731 | Avoiding lift with monad transformers | <p>I have a problem to which a stack of monad transformers (or even one monad transformer) over <code>IO</code>. Everything is good, except that using lift before every action is terribly annoying! I suspect there is really nothing to do about that, but I thought I'd ask anyway.</p>
<p>I am aware of lifting entire blocks, but what if the code is really of mixed types? Would it not be nice if GHC threw in some syntactic sugar (for example, <code><-$</code> = <code><- lift</code>)?</p> | 9,054,805 | 2 | 0 | null | 2012-01-29 16:32:41.567 UTC | 29 | 2018-03-25 21:51:10.893 UTC | 2018-03-25 21:51:10.893 UTC | null | 2,751,851 | null | 955,679 | null | 1 | 53 | haskell|monads|monad-transformers | 8,891 | <p>For all the standard <a href="http://hackage.haskell.org/package/mtl">mtl</a> monads, you don't need <code>lift</code> at all. <code>get</code>, <code>put</code>, <code>ask</code>, <code>tell</code> — they all work in any monad with the right transformer somewhere in the stack. The missing piece is <code>IO</code>, and even there <code>liftIO</code> lifts an arbitrary IO action down an arbitrary number of layers.</p>
<p>This is done with typeclasses for each "effect" on offer: for example, <a href="http://hackage.haskell.org/packages/archive/mtl/latest/doc/html/Control-Monad-State-Class.html"><code>MonadState</code></a> provides <code>get</code> and <code>put</code>. If you want to create your own <code>newtype</code> wrapper around a transformer stack, you can do <code>deriving (..., MonadState MyState, ...)</code> with the <code>GeneralizedNewtypeDeriving</code> extension, or roll your own instance:</p>
<pre><code>instance MonadState MyState MyMonad where
get = MyMonad get
put s = MyMonad (put s)
</code></pre>
<p>You can use this to selectively expose or hide components of your combined transformer, by defining some instances and not others.</p>
<p>(You can easily extend this approach to all-new monadic effects you define yourself, by defining your own typeclass and providing boilerplate instances for the standard transformers, but all-new monads are rare; most of the time, you'll get by simply composing the standard set offered by mtl.)</p> |
34,250,282 | Flexbox wraps last column of the first row in Safari | <p>The last column of the first row is wrapped to the next line when viewing in Safari, and some other iOS based browsers.</p>
<p><strong>Safari:</strong></p>
<p><a href="https://i.stack.imgur.com/FhYyn.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/FhYyn.jpg" alt="enter image description here"></a></p>
<p><strong>Chrome / Others:</strong></p>
<p><a href="https://i.stack.imgur.com/Vkvr0.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Vkvr0.jpg" alt="enter image description here"></a></p>
<p><strong>Code:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flexthis {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.flexthis .col-md-4 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row flexthis">
<div class="col-md-4 col-sm-6 text-center">
<div class="product">
<img src="img.jpg" alt="" class="img-responsive">
<h3>Name</h3>
<p>Description</p>
</div>
</div>
</div></code></pre>
</div>
</div>
</p> | 48,225,271 | 12 | 2 | null | 2015-12-13 10:50:43.487 UTC | 30 | 2019-10-24 11:26:47.323 UTC | 2018-06-06 15:43:37.967 UTC | null | 6,331,369 | null | 4,015,016 | null | 1 | 69 | twitter-bootstrap|css|twitter-bootstrap-3|flexbox | 42,581 | <p>Just to update on my question</p>
<p>This is the solution I go with, this is obviously fixed for Bootstrap4, which is flexbox compatible. So this is only for bootstrap3.</p>
<pre><code>.row.flexthis:after, .row.flexthis:before{
display: none;
}
</code></pre> |
57,917,622 | What does NGX stand for, what is it used for? | <p>In general what is NGX.
I always see it with module names in Angular,
what is it and what does it do.</p> | 57,917,675 | 3 | 0 | null | 2019-09-13 05:13:01.427 UTC | 3 | 2020-04-30 14:58:52.513 UTC | null | null | null | null | 9,599,565 | null | 1 | 30 | angular | 15,026 | <blockquote>
<p>ng = Angular like original <code>ng-bootstrap</code> </p>
<p>ngx = Angular + x
(redefined/modern/new/next-gen) update like <code>ngx-bootstrap</code></p>
</blockquote>
<p>Also, many ng packages are running from the old AngularJS (i.e. 1.x) era. ngx packages are designed mostly post that time for Angular 2+.</p> |
18,135,866 | Configuring DAHDI channels | <p>I installed dahdi 2.7 and asterisk 11 on Ubuntu 12.04.2 LTS. I'm having a hard time configuring a DAHDI channel. I have a AEX 808 card from Digium, the one with 8 FXO ports by my phone line is plugged into port 1 of the card.</p>
<p>I followed the exact same steps in <a href="http://www.voip-info.org/wiki/view/DAHDI" rel="nofollow">http://www.voip-info.org/wiki/view/DAHDI</a>
under the Sample Installation section except I edited dahdi_channels.conf to point to the same group number as the channel number for channels 2-8 as I thought asterisk was trying to make a call from a channel other than channel 1 since they were all previously in group=0. </p>
<p>Here are my config files:</p>
<p>chan_dahdi.conf:</p>
<pre><code>[trunkgroups]
; No trunk groups are needed in this configuration.
[channels]
#include /etc/asterisk/dahdi-channels.conf
; The channels context is used when defining channels using the
; older deprecated method. Don't use this as a section name.
;[phone](!)
;
; A template to hold common options for all phones.
;
usecallerid = yes
hidecallerid = no
callwaiting = no
;threewaycalling = yes
transfer = yes
echocancel = yes
echotraining = yes
immediate = no
</code></pre>
<p>dahdi_channels.conf:</p>
<pre><code>; Autogenerated by /usr/sbin/dahdi_genconf on Thu Aug 8 15:55:40 2013
; If you edit this file and execute /usr/sbin/dahdi_genconf again,
; your manual changes will be LOST.
; Dahdi Channels Configurations (chan_dahdi.conf)
;
; This is not intended to be a complete chan_dahdi.conf. Rather, it is intended
; to be #include-d by /etc/chan_dahdi.conf that will include the global settings
;
; Span 1: WCTDM/0 "Wildcard AEX800" (MASTER)
;;; line="1 WCTDM/0/0 FXSKS (In use) (EC: VPMOCT032 - INACTIVE)"
signalling=fxs_ks
callerid=asreceived
group=0
context=from-pstn
channel => 1
callerid=
group=
context=default
;;; line="2 WCTDM/0/1 FXSKS (In use) (EC: VPMOCT032 - INACTIVE)"
signalling=fxs_ks
callerid=asreceived
group=2
context=from-pstn
channel => 2
callerid=
group=
context=default
;;; line="3 WCTDM/0/2 FXSKS (In use) (EC: VPMOCT032 - INACTIVE)"
signalling=fxs_ks
callerid=asreceived
group=3
context=from-pstn
channel => 3
callerid=
group=
context=default
;;; line="4 WCTDM/0/3 FXSKS (In use) (EC: VPMOCT032 - INACTIVE)"
signalling=fxs_ks
callerid=asreceived
group=4
context=from-pstn
channel => 4
callerid=
group=
context=default
;;; line="5 WCTDM/0/4 FXSKS (In use) (EC: VPMOCT032 - INACTIVE)"
signalling=fxs_ks
callerid=asreceived
group=5
context=from-pstn
channel => 5
callerid=
group=
context=default
;;; line="6 WCTDM/0/5 FXSKS (In use) (EC: VPMOCT032 - INACTIVE)"
signalling=fxs_ks
callerid=asreceived
group=6
context=from-pstn
channel => 6
callerid=
group=
context=default
;;; line="7 WCTDM/0/6 FXSKS (In use) (EC: VPMOCT032 - INACTIVE)"
signalling=fxs_ks
callerid=asreceived
group=7
context=from-pstn
channel => 7
callerid=
group=
context=default
;;; line="8 WCTDM/0/7 FXSKS (In use) (EC: VPMOCT032 - INACTIVE)"
signalling=fxs_ks
callerid=asreceived
group=8
context=from-pstn
channel => 8
callerid=
group=
context=default
</code></pre>
<p>/etc/dahdi/system.conf:</p>
<pre><code># Autogenerated by /usr/sbin/dahdi_genconf on Thu Aug 8 15:55:40 2013
# If you edit this file and execute /usr/sbin/dahdi_genconf again,
# your manual changes will be LOST.
# Dahdi Configuration File
#
# This file is parsed by the Dahdi Configurator, dahdi_cfg
#
# Span 1: WCTDM/0 "Wildcard AEX800" (MASTER)
fxsks=1
echocanceller=mg2,1
fxsks=2
echocanceller=mg2,2
fxsks=3
echocanceller=mg2,3
fxsks=4
echocanceller=mg2,4
fxsks=5
echocanceller=mg2,5
fxsks=6
echocanceller=mg2,6
fxsks=7
echocanceller=mg2,7
fxsks=8
echocanceller=mg2,8
</code></pre>
<p>With these config files, when I start asterisk, I get the following DAHDI related errors:</p>
<pre><code>[Aug 8 15:56:26] WARNING[25198] chan_dahdi.c: Unable to specify channel 1: Device or resource busy
[Aug 8 15:56:26] ERROR[25198] chan_dahdi.c: Unable to open channel 1: Device or resource busy
[Aug 8 15:56:26] ERROR[25198] chan_dahdi.c: Unable to register channel '1'
</code></pre>
<p>This is the result of lsdahdi from the unix terminal:</p>
<pre><code>### Span 1: WCTDM/0 "Wildcard AEX800" (MASTER)
1 FXO FXSKS (In use) (EC: VPMOCT032 - INACTIVE)
2 FXO FXSKS (In use) (EC: VPMOCT032 - INACTIVE) RED
3 FXO FXSKS (In use) (EC: VPMOCT032 - INACTIVE) RED
4 FXO FXSKS (In use) (EC: VPMOCT032 - INACTIVE) RED
5 FXO FXSKS (In use) (EC: VPMOCT032 - INACTIVE) RED
6 FXO FXSKS (In use) (EC: VPMOCT032 - INACTIVE) RED
7 FXO FXSKS (In use) (EC: VPMOCT032 - INACTIVE) RED
8 FXO FXSKS (In use) (EC: VPMOCT032 - INACTIVE) RED
</code></pre>
<p>I'm not sure why it says "In use" as there are no calls currently being processed. I'm not sure if this is the default output for an AEX808 card. How can I get my DAHDI working with asterisk? What am I doing wrong?</p>
<p>Result of dahdi show status in asterisk:</p>
<pre><code> astersik*CLI> dahdi show status
No such command 'dahdi show status' (type 'core show help dahdi show' for other possible commands)
</code></pre>
<p>Output of dahdi_cfg -vvvv:</p>
<pre><code>DAHDI Tools Version - 2.7.0-rc1
DAHDI Version: 2.7.0-rc1
Echo Canceller(s): HWEC
Configuration
======================
Channel map:
Channel 01: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 01)
Channel 02: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 02)
Channel 03: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 03)
Channel 04: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 04)
Channel 05: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 05)
Channel 06: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 06)
Channel 07: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 07)
Channel 08: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 08)
8 channels to configure.
Setting echocan for channel 1 to mg2
Setting echocan for channel 2 to mg2
Setting echocan for channel 3 to mg2
Setting echocan for channel 4 to mg2
Setting echocan for channel 5 to mg2
Setting echocan for channel 6 to mg2
Setting echocan for channel 7 to mg2
Setting echocan for channel 8 to mg2
</code></pre>
<p>Any help would be appreciated.</p>
<p>Thanks in advance!</p> | 18,337,930 | 2 | 3 | null | 2013-08-08 20:50:59.84 UTC | null | 2019-06-03 13:09:47.383 UTC | 2019-06-03 13:09:47.383 UTC | null | 926,639 | null | 897,121 | null | 1 | 4 | asterisk|voip|dahdi | 41,800 | <p>After much investigation, I realized that DAHDI wasn't installed properly. I removed DAHDI and asterisk from the system and reinstalled everything to make it work.</p> |
18,029,614 | DCF77 decoder vs. noisy signal | <p>I have almost completed my open source DCF77 decoder project. It all started out when I noticed that the standard (Arduino) DCF77 libraries perform very poorly on noisy signals. Especially I was never able to get the time out of the decoders when the antenna was close to the computer or when my washing machine was running.</p>
<p>My first approach was to add a (digital) exponential filter + trigger to the incoming signal.</p>
<p>Although this improved the situation significantly, it was still not really good. Then I started to read some standard books on digital signal processing and especially the original works of Claude Elwood Shannon. My conclusion was that the proper approach would be to not "decode" the signal at all because it is (except for leap seconds) completely known a priori. Instead it would be more appropriate to match the received data to a locally synthesized signal and just determine the proper phase. This in turn would reduce the effective bandwidth by some orders of magnitude and thus reduce the noise significantly.</p>
<p>Phase detection implies the need for fast convolution. The standard approach for efficient convolution is of course the fast Fourier transform. However I am implementing for the Arduino / Atmega 328. Thus I have only 2k RAM. So instead of the straightforward approach with FFT, I started stacking matched phase locked loop filters. I documented the different project stages here:</p>
<ul>
<li><a href="http://blog.blinkenlight.net/experiments/dcf77/binary-clock/" rel="nofollow noreferrer">First try: exponential filter</a></li>
<li><a href="http://blog.blinkenlight.net/experiments/dcf77/phase-detection/" rel="nofollow noreferrer">Start of the better apprach: phase lock to the signal / seconds ticks</a></li>
<li><a href="http://blog.blinkenlight.net/experiments/dcf77/second-decoder/" rel="nofollow noreferrer">Phase lock to the minutes</a></li>
<li><a href="http://blog.blinkenlight.net/experiments/dcf77/decoding-time-data//" rel="nofollow noreferrer">Decoding minute and hour data</a></li>
<li><a href="http://blog.blinkenlight.net/experiments/dcf77/decoding-everything/" rel="nofollow noreferrer">Decoding the whole signal</a></li>
<li><a href="http://blog.blinkenlight.net/experiments/dcf77/local-clock/" rel="nofollow noreferrer">Adding a local clock to deal with signal loss</a></li>
<li><a href="http://blog.blinkenlight.net/experiments/dcf77/the-clock/" rel="nofollow noreferrer">Using local synthesized signal for faster lock reacquisition after signal loss</a></li>
</ul>
<p>I searched the internet quite extensively and found no similar approach. Still I wonder if there are similar (and maybe better) implementations. Or if there exist research on this kind of signal reconstruction.</p>
<p>What I am not searching for: designing optimized codes for getting close to the Shannon limit. I am also not searching for information on the superimposed PRNG code on DCF77. I also do not need hints on "matched filters" as my current implementation is an approximation of a matched filter. Specific hints on Viterbi Decoders or Trellis approaches are not what I am searching for - unless they address the issue of tight CPU and RAM constraints. </p>
<p>What I am searching for: are there any descriptions / implementations of other non-trivial algorithms for decoding signals like DCF77, with <strong>limited CPU and RAM</strong> in the presence of significant noise? Maybe in some books or papers from the pre internet era?</p> | 19,208,558 | 2 | 6 | null | 2013-08-03 05:27:05.903 UTC | 10 | 2014-07-06 13:54:08.823 UTC | 2014-02-14 12:34:52.673 UTC | null | 2,036,917 | null | 2,036,917 | null | 1 | 19 | algorithm|language-agnostic|arduino|signal-processing|dcf77 | 5,782 | <p>The reference to matched filters by Ollie B. is not what I was asking for. I already covered this before in my blog. </p>
<p>However by now I received a very good hint by private mail. There exists a paper <a href="http://caxapa.ru/thumbs/417284/Engeler_DCF77.pdf" rel="nofollow">"Performance Analysis and
Receiver Architectures of DCF77 Radio-Controlled Clocks"</a> by Daniel Engeler. This is the kind of stuff I am searching for.</p>
<p>With further searches starting from the Engeler paper I found the following German patents <a href="https://register.dpma.de/DPMAregister/pat/PatSchrifteneinsicht?docId=DE3733966A1" rel="nofollow">DE3733966A1 - Anordnung zum Empfang stark gestoerter Signale des Senders dcf-77</a> and <a href="https://register.dpma.de/DPMAregister/pat/PatSchrifteneinsicht?docId=DE4219417C2" rel="nofollow">DE4219417C2 - Schmalbandempfänger für Datensignale</a>.</p> |
35,458,737 | Implement HTTP Cache (ETag) in ASP.NET Core Web API | <p>I am working on ASP.NET Core (ASP.NET 5) Web API application and have to implement HTTP Caching with the help of Entity Tags. Earlier I used CacheCow for the same but it seems it does not support ASP.NET Core as of now. I also didn't find any other relevant library or framework support details for the same.</p>
<p>I can write custom code for the same but before that I want to see if anything is already available. Kindly share if something is already available and what is the better way to implement that.</p> | 40,455,004 | 6 | 2 | null | 2016-02-17 13:59:26.027 UTC | 12 | 2021-06-04 16:09:32.457 UTC | 2019-09-30 11:55:11.917 UTC | null | 2,874,896 | null | 1,344,435 | null | 1 | 35 | asp.net-web-api|asp.net-core | 25,964 | <p>After a while trying to make it work with middleware I figured out that <a href="https://docs.asp.net/en/latest/mvc/controllers/filters.html#action-filters" rel="noreferrer">MVC action filters</a> are actually better suited for this functionality.</p>
<pre class="lang-cs prettyprint-override"><code>public class ETagFilter : Attribute, IActionFilter
{
private readonly int[] _statusCodes;
public ETagFilter(params int[] statusCodes)
{
_statusCodes = statusCodes;
if (statusCodes.Length == 0) _statusCodes = new[] { 200 };
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.HttpContext.Request.Method == "GET")
{
if (_statusCodes.Contains(context.HttpContext.Response.StatusCode))
{
//I just serialize the result to JSON, could do something less costly
var content = JsonConvert.SerializeObject(context.Result);
var etag = ETagGenerator.GetETag(context.HttpContext.Request.Path.ToString(), Encoding.UTF8.GetBytes(content));
if (context.HttpContext.Request.Headers.Keys.Contains("If-None-Match") && context.HttpContext.Request.Headers["If-None-Match"].ToString() == etag)
{
context.Result = new StatusCodeResult(304);
}
context.HttpContext.Response.Headers.Add("ETag", new[] { etag });
}
}
}
}
// Helper class that generates the etag from a key (route) and content (response)
public static class ETagGenerator
{
public static string GetETag(string key, byte[] contentBytes)
{
var keyBytes = Encoding.UTF8.GetBytes(key);
var combinedBytes = Combine(keyBytes, contentBytes);
return GenerateETag(combinedBytes);
}
private static string GenerateETag(byte[] data)
{
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(data);
string hex = BitConverter.ToString(hash);
return hex.Replace("-", "");
}
}
private static byte[] Combine(byte[] a, byte[] b)
{
byte[] c = new byte[a.Length + b.Length];
Buffer.BlockCopy(a, 0, c, 0, a.Length);
Buffer.BlockCopy(b, 0, c, a.Length, b.Length);
return c;
}
}
</code></pre>
<p>And then use it on the actions or controllers you want as an attribute:</p>
<pre class="lang-cs prettyprint-override"><code>[HttpGet("data")]
[ETagFilter(200)]
public async Task<IActionResult> GetDataFromApi()
{
}
</code></pre>
<p>The important distinction between Middleware and Filters is that your middleware can run before and after MVC middlware and can only work with HttpContext. Also once MVC starts sending the response back to the client it's too late to make any changes to it.</p>
<p>Filters on the other hand are a part of MVC middleware. They have access to the MVC context, with which in this case it's simpler to implement this functionality. <a href="https://docs.asp.net/en/latest/mvc/controllers/filters.html" rel="noreferrer">More on Filters</a> and their pipeline in MVC.</p> |
20,889,460 | How do I run the preprocessor on local headers only? | <p>I want the preprocessor to read in the includes of local headers, but ignore the includes of system headers. To put it another way, how do I get the preprocessor to skip over preprocessing directives of the form:</p>
<pre><code>#include <h-char-sequence> new-line
</code></pre>
<p>but still process directives of the form:</p>
<pre><code>#include "q-char-sequence" new-line
</code></pre>
<hr>
<p>As a code example, observe the following file:</p>
<pre><code>#include <iostream> //system
#include "class_a.hpp" //local
#include <string> //system
#include "class_b.hpp" //local
int main() {}
</code></pre>
<p>how can I get the output of the preprocessor to be:</p>
<pre><code>#include <iostream>
class A{};
#include <string>
class B{};
int main() {}
</code></pre>
<hr>
<p>Local include files may include other local include files, and the preprocessor would recursively bring them all in; much like it normally does. It would still print all of the system file headers, but it would not bring in their contents.</p>
<hr>
<p>on gcc, my call looks like this so far: <code>g++ -E -P main.cpp</code>, where <code>-E</code> stops after preprocessing, and <code>-P</code> excludes the generation of line markers.<br>
I can't seem to find a flag that excludes the processing of system headers.</p> | 38,163,793 | 4 | 2 | null | 2014-01-02 18:33:42.227 UTC | 5 | 2019-03-10 13:36:06.777 UTC | 2016-07-02 18:26:14.693 UTC | null | 4,370,109 | null | 908,939 | null | 1 | 29 | c++|gcc|clang|c-preprocessor|header-files | 6,811 | <p>How much effort are you willing to go to? There's an obnoxiously obscure way to do it but it requires you to set up a dummy directory to hold surrogates for the system headers. OTOH, it doesn't require any changes in any of your source code. The same technique works equally well for C code.</p>
<h3>Setup</h3>
<p>Files:</p>
<pre><code>./class_a.hpp
./class_b.hpp
./example.cpp
./system-headers/iostream
./system-headers/string
</code></pre>
<p>The 'system headers' such as <code>./system-headers/iostream</code> contain a single line (there is no <code>#</code> on that line!):</p>
<pre><code>include <iostream>
</code></pre>
<p>The class headers each contain a single line like:</p>
<pre><code>class A{};
</code></pre>
<p>The contents of <code>example.cpp</code> are what you show in the question:</p>
<pre><code>#include <iostream> //system
#include "class_a.hpp" //local
#include <string> //system
#include "class_b.hpp" //local
int main() {}
</code></pre>
<h3>Running the C preprocessor</h3>
<p>Running the C preprocessor like this produces the output shown:</p>
<pre><code>$ cpp -Dinclude=#include -I. -Isystem-headers example.cpp
# 1 "example.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "example.cpp"
# 1 "system-headers/iostream" 1
#include <iostream>
# 2 "example.cpp" 2
# 1 "class_a.hpp" 1
class A{};
# 3 "example.cpp" 2
# 1 "system-headers/string" 1
#include <string>
# 4 "example.cpp" 2
# 1 "class_b.hpp" 1
class B{};
# 5 "example.cpp" 2
int main() {}
$
</code></pre>
<p>If you eliminate the <code># n</code> lines, that output is:</p>
<pre><code>$ cpp -Dinclude=#include -I. -Isystem-headers example.cpp | grep -v '^# [0-9]'
#include <iostream>
class A{};
#include <string>
class B{};
int main() {}
$
</code></pre>
<p>which, give or take the space at the beginning of the lines containing <code>#include</code>, is what you wanted.</p>
<h3>Analysis</h3>
<p>The <code>-Dinclude=#include</code> argument is equivalent to <code>#define include #include</code>. When the preprocessor generates output from a macro, even if it looks like a directive (such as <code>#include</code>), it is not a preprocessor directive. Quoting the C++11 standard ISO/IEC 14882:2011 (not that this has changed between versions AFAIK — and is, verbatim, what it says in the C11 standard, ISO/IEC 9899:2011 too, in §6.10.3):</p>
<blockquote>
<h3>§16.3 Macro replacement</h3>
<p>¶8 If a <code>#</code> preprocessing token, followed by an identifier, occurs lexically at the point at which a preprocessing directive could begin, the identifier is not subject to macro replacement.</p>
<p>§16.3.4 Rescanning and further replacement</p>
<p>¶2 If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. …</p>
<p>¶3 The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, …</p>
</blockquote>
<p>When the preprocessor encounters <code>#include <iostream></code>, it looks in the current directory and finds no file, then looks in <code>./system-headers</code> and finds the file <code>iostream</code> so it processes that into the output. It contains a single line, <code>include <iostream></code>. Since <code>include</code> is a macro, it is expanded (to <code>#include</code>) but further expansion is prevented, and the <code>#</code> is not processed as a directive because of §16.3.4 ¶3. Thus, the output contains <code>#include <iostream></code>.</p>
<p>When the preprocessor encounters <code>#include "class_a.hpp"</code>, it looks in the current directory and finds the file and includes its contents in the output.</p>
<p>Rinse and repeat for the other headers. If <code>class_a.hpp</code> contained <code>#include <iostream></code>, then that ends up expanding to <code>#include <iostream></code> again (with the leading space). If your <code>system-headers</code> directory is missing any header, then the preprocessor will search in the normal locations and find and include that. If you use the compiler rather than <code>cpp</code> directly, you can prohibit it from looking in the system directories with <code>-nostdinc</code> — so the preprocessor will generate an error if <code>system-headers</code> is missing a (surrogate for a) system header.</p>
<pre><code>$ g++ -E -nostdinc -Dinclude=#include -I. -Isystem-headers example.cpp | grep -v '^# [0-9]'
#include <iostream>
class A{};
#include <string>
class B{};
int main() {}
$
</code></pre>
<p>Note that it is very easy to generate the surrogate system headers:</p>
<pre><code>for header in algorithm chrono iostream string …
do echo "include <$header>" > system-headers/$header
done
</code></pre>
<p>JFTR, testing was done on Mac OS X 10.11.5 with GCC 6.1.0. If you're using GCC (the GNU Compiler Collection, with leading example compilers <code>gcc</code> and <code>g++</code>), your mileage shouldn't vary very much with any plausible alternative version.</p>
<p>If you're uncomfortable using the macro name <code>include</code>, you can change it to anything else that suits you — <code>syzygy</code>, <code>apoplexy</code>, <code>nadir</code>, <code>reinclude</code>, … — and change the surrogate headers to use that name, and define that name on the preprocessor (compiler) command line. One advantage of <code>include</code> is that it's improbable that you have anything using that as a macro name.</p>
<h3>Automatically generating surrogate headers</h3>
<p><a href="https://stackoverflow.com/users/196561/osgx">osgx</a> <a href="https://stackoverflow.com/questions/20889460/how-do-i-run-the-preprocessor-on-local-headers-only#comment63755844_38163793">asks</a>:</p>
<blockquote>
<p>How can we automate the generation of mock system headers?</p>
</blockquote>
<p>There are a variety of options. One is to analyze your code (with <code>grep</code> for example) to find the names that are, or might be, referenced and generate the appropriate surrogate headers. It doesn't matter if you generate a few unused headers — they won't affect the process. Note that if you use <code>#include <sys/wait.h></code>, the surrogate must be <code>./system-headers/sys/wait.h</code>; that slightly complicates the shell code shown, but not by very much. Another way would look at the headers in the system header directories (<code>/usr/include</code>, <code>/usr/local/include</code>, etc) and generate surrogates for the headers you find there.
For example, <code>mksurrogates.sh</code> might be:</p>
<pre><code>#!/bin/sh
sysdir="./system-headers"
for header in "$@"
do
mkdir -p "$sysdir/$(dirname $header)"
echo "include <$header>" > "$sysdir/$header"
done
</code></pre>
<p>And we can write <code>listsyshdrs.sh</code> to find the system headers referenced in source code under a named directory:</p>
<pre><code>#!/bin/sh
grep -h -e '^[[:space:]]*#[[:space:]]*include[[:space:]]*<[^>]*>' -r "${@:-.}" |
sed 's/^[[:space:]]*#[[:space:]]*include[[:space:]]*<\([^>]*\)>.*/\1/' |
sort -u
</code></pre>
<p>With a bit of formatting added, that generated a list of headers like this when I scanned the source tree with my answers to SO questions:</p>
<pre><code>algorithm arpa/inet.h assert.h cassert
chrono cmath cstddef cstdint
cstdlib cstring ctime ctype.h
dirent.h errno.h fcntl.h float.h
getopt.h inttypes.h iomanip iostream
limits.h locale.h map math.h
memory.h netdb.h netinet/in.h pthread.h
semaphore.h signal.h sstream stdarg.h
stdbool.h stddef.h stdint.h stdio.h
stdlib.h string string.h sys/ipc.h
sys/mman.h sys/param.h sys/ptrace.h sys/select.h
sys/sem.h sys/shm.h sys/socket.h sys/stat.h
sys/time.h sys/timeb.h sys/times.h sys/types.h
sys/wait.h termios.h time.h unistd.h
utility vector wchar.h
</code></pre>
<p>So, to generate the surrogates for the source tree under the current directory:</p>
<pre><code>$ sh mksurrogatehdr.sh $(sh listsyshdrs.sh)
$ ls -lR system-headers
total 344
-rw-r--r-- 1 jleffler staff 20 Jul 2 17:27 algorithm
drwxr-xr-x 3 jleffler staff 102 Jul 2 17:27 arpa
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 assert.h
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 cassert
-rw-r--r-- 1 jleffler staff 17 Jul 2 17:27 chrono
-rw-r--r-- 1 jleffler staff 16 Jul 2 17:27 cmath
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 cstddef
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 cstdint
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 cstdlib
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 cstring
-rw-r--r-- 1 jleffler staff 16 Jul 2 17:27 ctime
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 ctype.h
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 dirent.h
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 errno.h
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 fcntl.h
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 float.h
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 getopt.h
-rw-r--r-- 1 jleffler staff 21 Jul 2 17:27 inttypes.h
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 iomanip
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 iostream
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 limits.h
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 locale.h
-rw-r--r-- 1 jleffler staff 14 Jul 2 17:27 map
-rw-r--r-- 1 jleffler staff 17 Jul 2 17:27 math.h
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 memory.h
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 netdb.h
drwxr-xr-x 3 jleffler staff 102 Jul 2 17:27 netinet
-rw-r--r-- 1 jleffler staff 20 Jul 2 17:27 pthread.h
-rw-r--r-- 1 jleffler staff 22 Jul 2 17:27 semaphore.h
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 signal.h
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 sstream
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 stdarg.h
-rw-r--r-- 1 jleffler staff 20 Jul 2 17:27 stdbool.h
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 stddef.h
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 stdint.h
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 stdio.h
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 stdlib.h
-rw-r--r-- 1 jleffler staff 17 Jul 2 17:27 string
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 string.h
drwxr-xr-x 16 jleffler staff 544 Jul 2 17:27 sys
-rw-r--r-- 1 jleffler staff 20 Jul 2 17:27 termios.h
-rw-r--r-- 1 jleffler staff 17 Jul 2 17:27 time.h
-rw-r--r-- 1 jleffler staff 19 Jul 2 17:27 unistd.h
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 utility
-rw-r--r-- 1 jleffler staff 17 Jul 2 17:27 vector
-rw-r--r-- 1 jleffler staff 18 Jul 2 17:27 wchar.h
system-headers/arpa:
total 8
-rw-r--r-- 1 jleffler staff 22 Jul 2 17:27 inet.h
system-headers/netinet:
total 8
-rw-r--r-- 1 jleffler staff 23 Jul 2 17:27 in.h
system-headers/sys:
total 112
-rw-r--r-- 1 jleffler staff 20 Jul 2 17:27 ipc.h
-rw-r--r-- 1 jleffler staff 21 Jul 2 17:27 mman.h
-rw-r--r-- 1 jleffler staff 22 Jul 2 17:27 param.h
-rw-r--r-- 1 jleffler staff 23 Jul 2 17:27 ptrace.h
-rw-r--r-- 1 jleffler staff 23 Jul 2 17:27 select.h
-rw-r--r-- 1 jleffler staff 20 Jul 2 17:27 sem.h
-rw-r--r-- 1 jleffler staff 20 Jul 2 17:27 shm.h
-rw-r--r-- 1 jleffler staff 23 Jul 2 17:27 socket.h
-rw-r--r-- 1 jleffler staff 21 Jul 2 17:27 stat.h
-rw-r--r-- 1 jleffler staff 21 Jul 2 17:27 time.h
-rw-r--r-- 1 jleffler staff 22 Jul 2 17:27 timeb.h
-rw-r--r-- 1 jleffler staff 22 Jul 2 17:27 times.h
-rw-r--r-- 1 jleffler staff 22 Jul 2 17:27 types.h
-rw-r--r-- 1 jleffler staff 21 Jul 2 17:27 wait.h
$
</code></pre>
<p>This assumes that header file names contain no spaces, which is not unreasonable — it would be a brave programmer who created header file names with spaces or other tricky characters.</p>
<p>A full production-ready version of <code>mksurrogates.sh</code> would accept an argument specifying the surrogate header directory.</p> |
21,132,692 | Java unchecked: unchecked generic array creation for varargs parameter | <p>I have set Netbeans to show unchecked warnings in my Java code, but I am failing to understand the error on the following lines:</p>
<pre><code>private List<String> cocNumbers;
private List<String> vatNumbers;
private List<String> ibans;
private List<String> banks;
...
List<List<String>> combinations = Utils.createCombinations(cocNumbers, vatNumbers, ibans);
</code></pre>
<p>Gives:</p>
<p><code>[unchecked] unchecked generic array creation for varargs parameter of type List<String>[]</code></p>
<p>Method source:</p>
<pre><code>/**
* Returns a list of all possible combinations of the entered array of lists.
*
* Example: [["A", "B"], ["0", "1", "2"]]
* Returns: [["A", "0"], ["A", "1"], ["A", "2"], ["B", "0"], ["B", "1"], ["B", "2"]]
*
* @param <T> The type parameter
* @param elements An array of lists
* @return All possible combinations of the entered lists
*/
public static <T> List<List<T>> createCombinations(List<T>... elements) {
List<List<T>> returnLists = new ArrayList<>();
int[] indices = new int[elements.length];
for (int i = 0; i < indices.length; i++) {
indices[i] = 0;
}
returnLists.add(generateCombination(indices, elements));
while (returnLists.size() < countCombinations(elements)) {
gotoNextIndex(indices, elements);
returnLists.add(generateCombination(indices, elements));
}
return returnLists;
}
</code></pre>
<p>What is exactly going wrong and how would I fix it, as I suppose leaving unchecked warnings in the code is not a good idea?</p>
<p><em>Forgot to mention, but I am using Java 7.</em></p>
<p><strong>Edit</strong>: Also I see now that the method has the following:</p>
<pre><code>[unchecked] Possible heap pollution from parameterized vararg type List<T>
where T is a type-variable:
T extends Object declared in method <T>createCombinations(List<T>...)
</code></pre> | 21,150,650 | 2 | 2 | null | 2014-01-15 08:46:16.583 UTC | 16 | 2018-04-16 13:46:29.587 UTC | null | null | null | null | 2,057,294 | null | 1 | 133 | java|generics|variadic-functions | 77,541 | <p>As janoh.janoh mentioned above, varargs in Java is just a syntactic sugar for arrays plus the implicit creation of an array at the calling site. So</p>
<pre><code>List<List<String>> combinations =
Utils.createCombinations(cocNumbers, vatNumbers, ibans);
</code></pre>
<p>is actually</p>
<pre><code>List<List<String>> combinations =
Utils.createCombinations(new List<String>[]{cocNumbers, vatNumbers, ibans});
</code></pre>
<p>But as you may know, <code>new List<String>[]</code> is not allowed in Java, for reasons that have been covered in many other questions, but mainly have to do with the fact that arrays know their component type at runtime, and check at runtime whether elements added match its component type, but this check is not possible for parameterized types.</p>
<p>Anyway, rather than failing, the compiler still creates the array. It does something similar to this:</p>
<pre><code>List<List<String>> combinations =
Utils.createCombinations((List<String>[])new List<?>[]{cocNumbers, vatNumbers, ibans});
</code></pre>
<p>This is potentially unsafe, but not necessarily unsafe. Most varargs methods simply iterate over the varargs elements and read them. In this case, it doesn't care about the runtime type of the array. This is the case with your method. Since you are on Java 7, you should add the <code>@SafeVarargs</code> annotation to your method, and you won't get this warning anymore. This annotation basically says, this method only cares about the types of the elements, not the type of the array.</p>
<p>However, there are some varargs methods that do use the runtime type of the array. In this case, it is potentially unsafe. That's why the warning is there.</p> |
47,705,036 | In JShell, how to import classpath from a Maven project | <p>I have a local Maven project under development. How can I launch <code>jshell</code> with the project class path with all the dependencies, so that I can test project or dependency classes inside JShell. </p> | 47,715,029 | 5 | 4 | null | 2017-12-07 22:40:25.583 UTC | 15 | 2022-02-22 08:26:09.36 UTC | 2017-12-08 01:46:39.817 UTC | null | 1,746,118 | null | 2,817,457 | null | 1 | 31 | maven|classpath|java-9|jshell | 6,648 | <p>I wrote a simple shell script put in the execution search path: </p>
<p>Shell script file: <strong>mshell</strong> (for *inux)</p>
<pre><code>mvn dependency:build-classpath -DincludeTypes=jar -Dmdep.outputFile=.cp.txt
jshell --class-path `cat .cp.txt`:target/classes
</code></pre>
<p>Shell script file: <strong>mshell</strong> (for Windows cmd.exe)</p>
<pre><code>mvn dependency:build-classpath -DincludeTypes=jar -Dmdep.outputFile=.cp.txt
for /F %i in (.cp.txt) do jshell --class-path "%i;target/classes"
</code></pre>
<p>Then in the maven project directory (for multi-module project, make sure in the module directory instead of parent directory), run: </p>
<pre><code>$ cd $MAVEN_PROJECT_HOME #make sure module folder for multi-module project
$ mshell
</code></pre>
<p><a href="https://gist.github.com/jianwu/9b36a3c9b47edd9c2304ccbf9ace081b" rel="noreferrer">gist link</a></p>
<p><em>Thanks Jay for pointing out -DincludeTypes=jar maven option.</em></p> |
40,795,840 | Swift 3 - dynamic vs @objc | <p>What's the difference between marking a method as @objc vs dynamic, when would you do one vs the other?</p>
<p>Below is Apple's definition for dynamic.</p>
<blockquote>
<p>dynamic Apply this modifier to any member of a class that can be
represented by Objective-C. When you mark a member declaration with
the dynamic modifier, access to that member is always dynamically
dispatched using the Objective-C runtime. Access to that member is
never inlined or devirtualized by the compiler.</p>
<p>Because declarations marked with the dynamic modifier are dispatched
using the Objective-C runtime, they’re implicitly marked with the objc
attribute.</p>
</blockquote> | 40,796,924 | 3 | 1 | null | 2016-11-24 23:40:29.617 UTC | 10 | 2021-12-03 17:55:49.29 UTC | 2019-07-30 07:22:05.87 UTC | null | 4,770,877 | null | 66,814 | null | 1 | 50 | ios|objective-c|dynamic|swift3 | 14,949 | <p>A function/variable declared as <code>@objc</code> is accessible from Objective-C, but Swift will continue to access it directly via static or virtual dispatch.
This means if the function/variable is swizzled via the Objective-C framework, like what happens when using Key-Value Observing or the various Objective-C APIs to modify classes, calling the method from Swift and Objective-C will produce different results.</p>
<p>Using <code>dynamic</code> tells Swift to always refer to Objective-C dynamic dispatch.
This is required for things like Key-Value Observing to work correctly. When the Swift function is called, it refers to the Objective-C runtime to dynamically dispatch the call.</p> |
1,895,092 | unit test in rails - model with paperclip | <p>I'm trying to write a test for a model with a picture, using paperclip. I'm using the test framework default, no shoulda or rspec. In this context, how should I test it? Should I really upload a file? How should I add a file to the fixture?</p> | 1,895,945 | 3 | 0 | null | 2009-12-12 23:51:03.453 UTC | 10 | 2016-07-06 01:02:58.387 UTC | 2009-12-13 15:48:16.39 UTC | null | 123,527 | null | 18,642 | null | 1 | 33 | ruby-on-rails|ruby|unit-testing|paperclip | 14,341 | <p>Adding file to a model is dead simple. For example:</p>
<pre><code>@post = Post.new
@post.attachment = File.new("test/fixtures/sample_file.png")
# Replace attachment= with the name of your paperclip attachment
</code></pre>
<p>In that case you should put the file into your <code>test/fixtures</code> dir.</p>
<p>I usually make a little helper in my test_helper.rb</p>
<pre><code>def sample_file(filename = "sample_file.png")
File.new("test/fixtures/#{filename}")
end
</code></pre>
<p>Then</p>
<pre><code>@post.attachment = sample_file("filename.txt")
</code></pre>
<p>If you use something like <a href="http://github.com/thoughtbot/factory_girl/" rel="noreferrer">Factory Girl</a> instead of fixtures this becomes even easier.</p> |
8,520,732 | I don't want my Excel Add-In to return an array (instead I need a UDF to change other cells) | <p>I've created an Excel Add-In, and one of the functions of this Add-In, lets say <code>New_Years</code> currently takes in 2 years and outputs every New Years day between those 2 years as an array in Excel. So <code>New_Years(2000,2002)</code> would return Jan 1st 2000, Jan 1st 2001, and Jan 1st 2002 in the last cell.</p>
<p>The problem is that I have to know there are going to be 3 dates in that time, select 3 cells, enter my formula in the top cell, and then hit <code>Ctrl + Shift + Enter</code> to fill out the array.</p>
<p>I use XLW version 5 to convert my C++ code to an .xll file. I would really like it if there was some way I could just fill in one square with my formula, and Excel would fill in the squares below as needed with the appropriate dates. Anyone know if this is possible? Or impossible?</p>
<p>Many thanks!</p> | 8,711,582 | 2 | 1 | null | 2011-12-15 13:17:40.887 UTC | 11 | 2020-09-12 08:20:42.66 UTC | 2012-01-04 09:55:39.393 UTC | null | 641,067 | null | 929,195 | null | 1 | 6 | c++|arrays|excel|add-in|excel-addins | 10,737 | <p>It is actually possible albeit complex. I am reposting this piece of magic from <a href="https://mvp.support.microsoft.com/profile=7E428211-E8AB-4F68-AEB1-FDD5C3DB5433" rel="nofollow noreferrer">Kevin Jones aka Zorvek</a> as it sits <a href="http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/Excel/Q_22095686.html" rel="nofollow noreferrer">behind the EE Paywall</a> (link attached if anyone has access)</p>
<blockquote>
<p>While Excel strictly forbids a UDF from changing any cell, worksheet,
or workbook properties, there is a way to effect such changes when a
UDF is called using a Windows timer and an Application.OnTime timer in
sequence. The Windows timer has to be used within the UDF because
Excel ignores any Application.OnTime calls inside a UDF. But, because
the Windows timer has limitations (Excel will instantly quit if a
Windows timer tries to run VBA code if a cell is being edited or a
dialog is open), it is used only to schedule an Application.OnTime
timer, a safe timer which Excel only allows to be fired if a cell is
not being edited and no dialogs are open.</p>
<p>The example code below illustrates how to start a Windows timer from
inside a UDF, how to use that timer routine to start an
Application.OnTime timer, and how to pass information known only to
the UDF to subsequent timer-executed routines. The code below must be
placed in a regular module.</p>
</blockquote>
<pre class="lang-vb prettyprint-override"><code>Private Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, _
ByVal nIDEvent As Long, _
ByVal uElapse As Long, _
ByVal lpTimerFunc As Long _
) As Long
Private Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, _
ByVal nIDEvent As Long _
) As Long
Private mCalculatedCells As Collection
Private mWindowsTimerID As Long
Private mApplicationTimerTime As Date
Public Function AddTwoNumbers( _
ByVal Value1 As Double, _
ByVal Value2 As Double _
) As Double
' This is a UDF that returns the sum of two numbers and starts a windows timer
' that starts a second Appliction.OnTime timer that performs activities not
' allowed in a UDF. Do not make this UDF volatile, pass any volatile functions
' to it, or pass any cells containing volatile formulas/functions or
' uncontrolled looping will start.
AddTwoNumbers = Value1 + Value2
' Cache the caller's reference so it can be dealt with in a non-UDF routine
If mCalculatedCells Is Nothing Then Set mCalculatedCells = New Collection
On Error Resume Next
mCalculatedCells.Add Application.Caller, Application.Caller.Address
On Error GoTo 0
' Setting/resetting the timer should be the last action taken in the UDF
If mWindowsTimerID <> 0 Then KillTimer 0&, mWindowsTimerID
mWindowsTimerID = SetTimer(0&, 0&, 1, AddressOf AfterUDFRoutine1)
End Function
Public Sub AfterUDFRoutine1()
' This is the first of two timer routines. This one is called by the Windows
' timer. Since a Windows timer cannot run code if a cell is being edited or a
' dialog is open this routine schedules a second safe timer using
' Application.OnTime which is ignored in a UDF.
' Stop the Windows timer
On Error Resume Next
KillTimer 0&, mWindowsTimerID
On Error GoTo 0
mWindowsTimerID = 0
' Cancel any previous OnTime timers
If mApplicationTimerTime <> 0 Then
On Error Resume Next
Application.OnTime mApplicationTimerTime, "AfterUDFRoutine2", , False
On Error GoTo 0
End If
' Schedule timer
mApplicationTimerTime = Now
Application.OnTime mApplicationTimerTime, "AfterUDFRoutine2"
End Sub
Public Sub AfterUDFRoutine2()
' This is the second of two timer routines. Because this timer routine is
' triggered by Application.OnTime it is safe, i.e., Excel will not allow the
' timer to fire unless the environment is safe (no open model dialogs or cell
' being edited).
Dim Cell As Range
' Do tasks not allowed in a UDF...
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Do While mCalculatedCells.Count > 0
Set Cell = mCalculatedCells(1)
mCalculatedCells.Remove 1
Cell.Offset(0, 1).Value = Cell.Value
Loop
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
</code></pre> |
19,702,361 | Octave error filename undefined near line x column y | <p>I am trying to run an Octave file which is in the working directory, but I get an error. Octave does not seem to recognize that it should run the file.</p>
<pre><code>unknown@unknown> dir
. ex1data1.txt plotData.m
.. ex1data2.txt submit.m
computeCost.m featureNormalize.m submitWeb.m
computeCostMulti.m gradientDescent.m warmUpExercise.m
ex1.m gradientDescentMulti.m
ex1_multi.m normalEqn.m
unknown@unknown> ex1
error: `ex1' undefined near line 21 column 1
unknown@unknown> ex1.m
error: `ex1' undefined near line 22 column 1
</code></pre>
<p>Can anyone advise how I can run the ex1 file?</p> | 19,706,961 | 5 | 2 | null | 2013-10-31 09:11:25.537 UTC | 4 | 2020-01-11 12:33:46.147 UTC | null | null | null | null | 190,791 | null | 1 | 19 | octave | 79,879 | <p>This fixed the problem [at least for me, on <strong>Windows</strong>]:</p>
<p>Entering the following command in Octave:</p>
<pre><code>>addpath(pwd)
</code></pre>
<p>before calling the script:</p>
<pre><code>>ex1
</code></pre>
<p>There is more info <a href="https://stackoverflow.com/questions/7936457/how-do-you-get-your-path-in-octave-on-windows">here</a>.</p> |
1,223,194 | Loading Subrecords in the Repository Pattern | <p>Using LINQ TO SQL as the underpinning of a Repository-based solution. My implementation is as follows:</p>
<p>IRepository</p>
<pre><code>FindAll
FindByID
Insert
Update
Delete
</code></pre>
<p>Then I have extension methods that are used to query the results as such:</p>
<pre><code>WhereSomethingEqualsTrue() ...
</code></pre>
<p>My question is as follows:</p>
<p>My Users repository has N roles. Do I create a Roles repository to manage Roles? I worry I'll end up creating dozens of Repositories (1 per table almost except for Join tables) if I go this route. Is a Repository per Table common?</p> | 1,258,816 | 4 | 0 | null | 2009-08-03 16:07:38.217 UTC | 23 | 2010-02-16 15:36:58.357 UTC | 2010-02-16 15:36:58.357 UTC | null | 56,145 | null | 135,952 | null | 1 | 13 | c#|linq-to-sql|repository|domain-driven-design|design-patterns | 9,352 | <p>If you are building your Repository to be specific to one Entity (table), such that each Entity has the list of methods in your IRepository interface that you listed above, then what you are really doing is an implementation of the <a href="http://en.wikipedia.org/wiki/Active_record_pattern" rel="noreferrer">Active Record</a> pattern.</p>
<p>You should <em>definitely not</em> have one Repository per table. You need to identify the Aggregates in your domain model, and the operations that you want to perform on them. Users and Roles are usually tightly related, and generally your application would be performing operations with them in tandem - this calls for a single repository, centered around the User and it's set of closely related entities. </p>
<p>I'm guessing from your post that you've <a href="http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/10/08/the-repository-pattern.aspx" rel="noreferrer">seen this example</a>. The problem with this example is that all the repositories are sharing the same CRUD functionality at the base level, but he doesn't go beyond this and implement any of the domain functions. All the repositories in that example look the same - but in reality, real repositories don't all look the same (although they should still be interfaced), there will be specific domain operations associated with each one.</p>
<p>Your repository domain operations should look more like:</p>
<pre><code>userRepository.FindRolesByUserId(int userID)
userRepository.AddUserToRole(int userID)
userRepository.FindAllUsers()
userRepository.FindAllRoles()
userRepository.GetUserSettings(int userID)
</code></pre>
<p>etc...</p>
<p>These are specific operations that your application wants to perform on the underlying data, and the Repository should provide that. Think of it as the Repository represents the set of atomic operations that you would perform on the domain. If you choose to share some functionality through a generic repository, and extend specific repositories with extension methods, that's one approach that may work just fine for your app.</p>
<p>A good rule of thumb is that it should be <em>rare</em> for your application to need to instantiate multiple repositories to complete an operation. The need does arise, but if every event handler in your app is juggling six repositories just to take the user's input and correctly instantiate the entities that the input represents, then you probably have design problems.</p> |
634,662 | Non-static const member, can't use default assignment operator | <p>A program I'm expanding uses <code>std::pair<></code> a lot.</p>
<p>There is a point in my code at which the compiler throws a rather large:</p>
<blockquote>
<p>Non-static const member, 'const Ptr std::pair, const double*>::first' can't use default assignment operator</p>
</blockquote>
<p>I'm not really sure what this is referring to?
Which methods are missing from the Ptr class?</p>
<p>The original call that causes this problem is as follows:</p>
<pre><code>vector_of_connections.pushback(pair(Ptr<double,double>,WeightValue*));
</code></pre>
<p>Where it's putting an <code>std::Pair<Ptr<double,double>, WeightValue*></code> onto a vector, where <code>WeightValue*</code> is a const variable from about 3 functions back, and the <code>Ptr<double,double></code> is taken from an iterator that works over another vector.</p>
<p>For future reference, <code>Ptr<double,double></code> is a pointer to a <code>Node</code> object.</p> | 634,705 | 4 | 6 | null | 2009-03-11 14:08:47.347 UTC | 13 | 2018-08-11 14:58:57.283 UTC | 2018-08-11 14:58:57.283 UTC | Ed Woodcock | 1,000,551 | Ed Woodcock | 70,847 | null | 1 | 49 | c++|constants | 42,986 | <p>You have a case like this:</p>
<pre><code>struct sample {
int const a; // const!
sample(int a):a(a) { }
};
</code></pre>
<p>Now, you use that in some context that requires <code>sample</code> to be assignable - possible in a container (like a map, vector or something else). This will fail, because the implicitly defined copy assignment operator does something along this line:</p>
<pre><code>// pseudo code, for illustration
a = other.a;
</code></pre>
<p>But <code>a</code> is const!. You have to make it non-const. It doesn't hurt because as long as you don't change it, it's still logically const :) You could fix the problem by introducing a suitable <code>operator=</code> too, making the compiler <em>not</em> define one implicitly. But that's bad because you will not be able to change your const member. Thus, having an operator=, but still not assignable! (because the copy and the assigned value are not identical!):</p>
<pre><code>struct sample {
int const a; // const!
sample(int a):a(a) { }
// bad!
sample & operator=(sample const&) { }
};
</code></pre>
<p><strong>However</strong> in your case, the apparent problem apparently lies within <code>std::pair<A, B></code>. Remember that a <code>std::map</code> is sorted on the keys it contains. Because of that, you <em>cannot</em> change its keys, because that could easily render the state of a map invalid. Because of that, the following holds:</p>
<pre><code>typedef std::map<A, B> map;
map::value_type <=> std::pair<A const, B>
</code></pre>
<p>That is, it forbids changing its keys that it contains! So if you do</p>
<pre><code>*mymap.begin() = make_pair(anotherKey, anotherValue);
</code></pre>
<p>The map throws an error at you, because in the pair of some value stored in the map, the <code>::first</code> member has a const qualified type!</p> |
57,439,743 | PreferenceScreen has been deprecated by API 29 | <p>I did create preferences XML then I see the <code>PreferenceScreen</code> has been deprecated by API 29. What is the replacement?</p>
<p>And you can see depreciation message here:</p>
<p><a href="https://i.stack.imgur.com/RuqUi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RuqUi.png" alt="enter image description here"></a></p> | 57,443,578 | 3 | 0 | null | 2019-08-10 06:06:54.417 UTC | 5 | 2022-07-03 17:31:33.717 UTC | 2019-08-10 06:20:16.55 UTC | null | 9,290,612 | null | 9,290,612 | null | 1 | 30 | android | 11,624 | <p>It's deprecated in API level 29 base on <a href="https://developer.android.com/reference/android/preference/Preference" rel="noreferrer">Google Document</a> and also by the Google recommendation you should use <a href="https://developer.android.com/reference/androidx/preference/package-summary.html" rel="noreferrer">AndroidX Preference Library</a> instead.</p>
<p>You can check AndroidX Preference guide in this <a href="https://developer.android.com/guide/topics/ui/settings.html" rel="noreferrer">link</a></p>
<p>If you still have the problem after <code>Migrate to Androidx</code> you can use</p>
<pre><code><androidx.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
</androidx.preference.PreferenceScreen>
</code></pre>
<p>instead of</p>
<pre><code><PreferenceScreen
xmlns:app="http://schemas.android.com/apk/res-auto">
</PreferenceScreen>
</code></pre>
<p>It's not necessary but you can add this implementation into your Gradle too.</p>
<pre><code>implementation 'androidx.preference:preference:X.Y.Z'
</code></pre> |
60,098,005 | FastAPI (starlette) get client real IP | <p>I have an API on FastAPI and i need to get the client real IP address when he request my page.</p>
<p>I'm ty to use starlette Request. But it returns my server IP, not client remote IP.</p>
<p>My code:</p>
<pre><code>@app.post('/my-endpoint')
async def my_endpoint(stats: Stats, request: Request):
ip = request.client.host
print(ip)
return {'status': 1, 'message': 'ok'}
</code></pre>
<p>What i'm doing wrong? How to get real IP (like in Flask request.remote_addr)?</p> | 60,120,975 | 11 | 0 | null | 2020-02-06 15:06:45.893 UTC | 10 | 2022-09-05 02:10:50.63 UTC | 2020-02-06 17:41:39.943 UTC | null | 400,617 | null | 7,827,388 | null | 1 | 29 | python|fastapi|x-forwarded-for|starlette | 26,176 | <p><code>request.client</code> should work, unless you're running behind a proxy (e.g. nginx) in that case use uvicorn's <code>--proxy-headers</code> flag to accept these incoming headers and make sure the proxy forwards them.</p> |
23,061,702 | Is it possible to declare variables procedurally using Rust macros? | <p>Basically, there are two parts to this question:</p>
<ol>
<li><p>Can you pass an unknown identifier to a macro in <a href="http://www.rust-lang.org/" rel="noreferrer">Rust</a>?</p></li>
<li><p>Can you combine strings to generate new variable names in a Rust macro?</p></li>
</ol>
<p>For example, something like:</p>
<pre class="lang-rust prettyprint-override"><code>macro_rules! expand(
($x:ident) => (
let mut x_$x = 0;
)
)
</code></pre>
<p>Calling expand!(hi) obvious fails because hi is an unknown identifier; but can you somehow do this?</p>
<p>ie. The equivalent in C of something like:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#define FN(Name, base) \
int x1_##Name = 0 + base; \
int x2_##Name = 2 + base; \
int x3_##Name = 4 + base; \
int x4_##Name = 8 + base; \
int x5_##Name = 16 + base;
int main() {
FN(hello, 10)
printf("%d %d %d %d %d\n", x1_hello, x2_hello, x3_hello, x4_hello, x5_hello);
return 0;
}
</code></pre>
<p>Why you say, what a terrible idea. Why would you ever want to do that?</p>
<p>I'm glad you asked!</p>
<p>Consider this rust block:</p>
<pre class="lang-rust prettyprint-override"><code>{
let marker = 0;
let borrowed = borrow_with_block_lifetime(data, &marker);
unsafe {
perform_ffi_call(borrowed);
}
}
</code></pre>
<p>You now have a borrowed value with an explicitly bounded lifetime (marker) that isn't using a structure lifetime, but that we can guarantee exists for the entire scope of the ffi call; at the same time we don't run into obscure errors where a <code>*</code> is de-referenced unsafely inside an unsafe block and so the compiler doesn't catch it as an error, despite the error being made <em>inside a safe block</em>. </p>
<p>(see also <a href="https://stackoverflow.com/questions/23053398/why-are-all-my-pointers-pointing-to-the-same-place-with-to-c-str-in-rust">Why are all my pointers pointing to the same place with to_c_str() in rust?</a>) </p>
<p>The use a macro that can declare temporary variables for this purpose would considerably ease the troubles I have fighting with the compiler. That's why I want to do this.</p> | 23,063,866 | 4 | 0 | null | 2014-04-14 13:41:23.21 UTC | 5 | 2020-11-27 14:01:23.553 UTC | 2018-04-30 02:03:08.05 UTC | null | 6,352,597 | null | 353,820 | null | 1 | 29 | macros|rust | 8,458 | <p>Yes however this is only available as a nightly-only experimental API which may be removed.</p>
<p>You can pass arbitrary identifier into a macro and yes, you can concatenate identifiers into a new identifier using <a href="https://doc.rust-lang.org/std/macro.concat_idents.html" rel="noreferrer"><code>concat_idents!()</code></a> macro:</p>
<pre class="lang-rust prettyprint-override"><code>#![feature(concat_idents)]
macro_rules! test {
($x:ident) => ({
let z = concat_idents!(hello_, $x);
z();
})
}
fn hello_world() { }
fn main() {
test!(world);
}
</code></pre>
<p>However, as far as I know, because <code>concat_idents!()</code> itself is a macro, you can't use this concatenated identifier <em>everywhere</em> you could use plain identifier, only in certain places like in example above, and this, in my opinion, is a HUGE drawback. Just yesterday I tried to write a macro which could remove a lot of boilerplate in my code, but eventually I was not able to do it because macros do not support arbitrary placement of concatenated identifiers.</p>
<p>BTW, if I understand your idea correctly, you don't really need concatenating identifiers to obtain unique names. Rust macros, contrary to the C ones, are <a href="https://en.wikipedia.org/wiki/Hygienic_macro" rel="noreferrer">hygienic</a>. This means that all names of local variables introduced inside a macro won't leak to the scope where this macro is called. For example, you could assume that this code would work:</p>
<pre class="lang-rust prettyprint-override"><code>macro_rules! test {
($body:expr) => ({ let x = 10; $body })
}
fn main() {
let y = test!(x + 10);
println!("{}", y);
}
</code></pre>
<p>That is, we create a variable <code>x</code> and put an expression after its declaration. It is then natural to think that <code>x</code> in <code>test!(x + 10)</code> refers to that variable declared by the macro, and everything should be fine, but in fact this code won't compile:</p>
<pre><code>main3.rs:8:19: 8:20 error: unresolved name `x`.
main3.rs:8 let y = test!(x + 10);
^
main3.rs:3:1: 5:2 note: in expansion of test!
main3.rs:8:13: 8:27 note: expansion site
error: aborting due to previous error
</code></pre>
<p>So if all you need is uniqueness of locals, then you can safely do nothing and use any names you want, they will be unique automatically. This is <a href="https://doc.rust-lang.org/book/first-edition/macros.html#hygiene" rel="noreferrer">explained</a> in macro tutorial, though I find the example there somewhat confusing.</p> |
23,107,613 | get original element from ng-click | <p>I have a list of items in my view with <code>ng-click</code> attached to them:</p>
<pre><code><ul id="team-filters">
<li ng-click="foo($event, team)" ng-repeat="team in teams">
<img src="{{team.logoSmall}}" alt="{{team.name}}" title="{{team.name}}">
</li>
</ul>
</code></pre>
<p>I'm handling the click events in the <code>foo</code> function in my directive, passing <code>$event</code> as a reference to the object that's been clicked, but I'm getting a reference to the <code>img</code> tag, rather than the <code>li</code> tag. I then have to do stuff like this to get the <code>li</code>:</p>
<pre><code>$scope.foo = function($event, team) {
var el = (function(){
if ($event.target.nodeName === 'IMG') {
return angular.element($event.target).parent(); // get li
} else {
return angular.element($event.target); // is li
}
})();
</code></pre>
<p>Is there a simple way to get the reference to the element that <code>ng-click</code> is bound to, without doing DOM operations in my directive?</p> | 23,107,800 | 2 | 0 | null | 2014-04-16 11:05:08.717 UTC | 33 | 2015-09-07 07:28:17.757 UTC | 2015-09-07 07:28:17.757 UTC | null | 2,264,626 | null | 1,016,371 | null | 1 | 212 | angularjs|angularjs-directive | 230,426 | <p>You need <code>$event.currentTarget</code> instead of <code>$event.target</code>.</p> |
31,017,393 | SQL Server latitude and longitude data type | <p>I want to ask about what SQL Server data type to use for storing latitude and longitude.</p>
<p>Here's an example:</p>
<pre><code>Latitude: -7.39755000
Longitude: 107.80627000
</code></pre>
<p>If data type <code>decimal</code>, it won't save because SQL Server said: </p>
<blockquote>
<p>cannot convert numeric data to numeric</p>
</blockquote>
<p>as I remembered.</p>
<p>But if type data was <code>float</code>, SQL Server will convert <code>0</code> so the latitude will be <code>-7.39755000</code>. So I figure it out replace the last <code>0</code> with <code>1 - 9</code>. is it the location will be not accurate? </p>
<p>Or maybe stick with <code>decimal</code>, but how to avoid the warning?</p> | 31,017,505 | 1 | 0 | null | 2015-06-24 04:01:49.657 UTC | 7 | 2018-12-10 00:28:55.783 UTC | 2017-07-23 23:19:23.91 UTC | null | 2,840,103 | null | 4,729,116 | null | 1 | 43 | sql-server|google-maps | 56,395 | <p><code>DECIMAL(9,6)</code> is what I normally use for both. If you need more precision, then try <code>DECIMAL(12,9)</code>.</p>
<p>You could also use the <code>GEOGRAPHY</code> data type, but it will take more space, and I would only recommend this if you need SQL Servers spatial features (indexing etc).</p>
<p>For the actual conversion, try this:</p>
<pre><code>CAST(@YourLat AS DECIMAL(12,9))
</code></pre> |
19,923,877 | Django orm get latest for each group | <p>I am using Django 1.6 with Mysql.</p>
<p>I have these models:</p>
<pre><code>class Student(models.Model):
username = models.CharField(max_length=200, unique = True)
class Score(models.Model)
student = models.ForeignKey(Student)
date = models.DateTimeField()
score = models.IntegerField()
</code></pre>
<p>I want to get the latest score record for each student.<br>
I have tried:</p>
<pre><code>Score.objects.values('student').annotate(latest_date=Max('date'))
</code></pre>
<p>and:</p>
<pre><code>Score.objects.values('student__username').annotate(latest_date=Max('date'))
</code></pre>
<p>as described <a href="https://stackoverflow.com/questions/17887075/django-orm-get-latest-record-for-group">Django ORM - Get the latest record for the group</a>
but it did not help.</p> | 19,930,802 | 4 | 0 | null | 2013-11-12 08:04:18.647 UTC | 18 | 2020-10-23 21:56:27.463 UTC | 2019-11-16 19:56:46.777 UTC | null | 9,926,721 | null | 486,209 | null | 1 | 69 | python|django|django-queryset|django-orm | 31,253 | <p>This should work on Django 1.2+ and MySQL:</p>
<pre><code>Score.objects.annotate(
max_date=Max('student__score__date')
).filter(
date=F('max_date')
)
</code></pre> |
20,333,435 | pandas comparison raises TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool] | <p>I have the following structure to my dataFrame:</p>
<pre><code>Index: 1008 entries, Trial1.0 to Trial3.84
Data columns (total 5 columns):
CHUNK_NAME 1008 non-null values
LAMBDA 1008 non-null values
BETA 1008 non-null values
HIT_RATE 1008 non-null values
AVERAGE_RECIPROCAL_HITRATE 1008 non-null values
chunks=['300_321','322_343','344_365','366_387','388_408','366_408','344_408','322_408','300_408']
lam_beta=[(lambda1,beta1),(lambda1,beta2),(lambda1,beta3),...(lambda1,beta_n),(lambda2,beta1),(lambda2,beta2)...(lambda2,beta_n),........]
my_df.ix[my_df.CHUNK_NAME==chunks[0]&my_df.LAMBDA==lam_beta[0][0]]
</code></pre>
<p>I want to get the rows of the DataFrame for a particular chunk lets say <code>chunks[0]</code> and particular <code>lambda</code> value. So in this case, the output should be all rows in the DataFrame having <code>CHUNK_NAME='300_321'</code> and <code>LAMBDA=lambda1</code>. There would be n rows one for each <code>beta</code> value that would be returned. But instead I get the following error. Any help in solving this problem would be appreciated.</p>
<pre><code>TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
</code></pre> | 20,333,894 | 2 | 0 | null | 2013-12-02 16:47:03.267 UTC | 13 | 2022-04-07 00:49:33.457 UTC | 2022-04-06 20:50:20.84 UTC | user7864386 | null | null | 1,009,091 | null | 1 | 61 | python|pandas|typeerror|dataframe | 102,227 | <p><code>&</code> has higher precedence than <code>==</code>. Write:</p>
<pre><code>my_df.ix[(my_df.CHUNK_NAME==chunks[0])&(my_df.LAMBDA==lam_beta[0][0])]
^ ^ ^ ^
</code></pre> |
29,861,699 | DD/MM/YYYY Date format in Moment.js | <p>How can i change the current date to this format(DD/MM/YYYY) using moment.js?</p>
<p>I have tried below code.</p>
<pre><code>$scope.SearchDate = moment(new Date(), "DD/MM/YYYY");
</code></pre>
<p>But it's return <code>0037-11-24T18:30:00.000Z</code>. Did't help to format current date. </p> | 29,861,720 | 5 | 0 | null | 2015-04-25 06:13:12.533 UTC | 15 | 2021-01-18 16:34:43.96 UTC | null | null | null | null | 2,218,635 | null | 1 | 64 | javascript|angularjs|momentjs | 281,486 | <p>You need to call <a href="http://momentjs.com/docs/#/displaying/">format()</a> function to get the formatted value</p>
<pre><code>$scope.SearchDate = moment(new Date()).format("DD/MM/YYYY")
//or $scope.SearchDate = moment().format("DD/MM/YYYY")
</code></pre>
<p>The syntax you have used is used to <a href="http://momentjs.com/docs/#/parsing/string-format/">parse</a> a given string to date object by using the specified formate</p> |
30,009,948 | How to reorder indexed rows based on a list in Pandas data frame | <p>I have a data frame that looks like this:</p>
<pre><code>company Amazon Apple Yahoo
name
A 0 130 0
C 173 0 0
Z 0 0 150
</code></pre>
<p>It was created using this code:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'name' : ['A', 'Z','C'],
'company' : ['Apple', 'Yahoo','Amazon'],
'height' : [130, 150,173]})
df = df.pivot(index="name", columns="company", values="height").fillna(0)
</code></pre>
<p>What I want to do is to sort the row (with index <code>name</code>) according to a predefined list:</p>
<pre><code>["Z", "C", "A"]`
</code></pre>
<p>Resulting in this :</p>
<pre><code>company Amazon Apple Yahoo
name
Z 0 0 150
C 173 0 0
A 0 130 0
</code></pre>
<p>How can I achieve that?</p> | 30,010,004 | 2 | 0 | null | 2015-05-03 03:34:33.97 UTC | 26 | 2022-04-16 00:48:00.94 UTC | 2022-04-02 03:12:53.937 UTC | user7864386 | null | null | 67,405 | null | 1 | 101 | python|pandas|dataframe | 146,430 | <p>You could set index on predefined order using <code>reindex</code> like</p>
<pre><code>In [14]: df.reindex(["Z", "C", "A"])
Out[14]:
company Amazon Apple Yahoo
Z 0 0 150
C 173 0 0
A 0 130 0
</code></pre>
<p>However, if it's alphabetical order, you could use <code>sort_index(ascending=False)</code></p>
<pre><code>In [12]: df.sort_index(ascending=False)
Out[12]:
company Amazon Apple Yahoo
name
Z 0 0 150
C 173 0 0
A 0 130 0
</code></pre>
<p>Like pointed below, you need to assign it to some variable</p>
<pre><code>In [13]: df = df.sort_index(ascending=False)
</code></pre> |
35,025,110 | Does Alamofire store the cookies automatically? | <p>I'm new to <strong>Alamofire</strong> so I'm sorry if this it's a noob question: <strong>this framework stores the cookies automatically</strong>?</p>
<p>This is because I have a simple request like this:</p>
<pre><code>Alamofire.request(.POST, loginURL, parameters: ["fb_id": fbId, "fb_access_token": fbToken])
.responseJSON { response in
//print(response.request) // original URL request
//print(response.response) // URL response
//print(response.data) // server data
//print(response.result) // result of response serialization
if let JSON = response.result.value {
print("loginURL - JSON: \(JSON)")
}
}
</code></pre>
<p>this request response with a cookie session that I need to do other requests for security reason; the strange thing is that like magic I already can do the other requests after this first POST without read manually the cookie and store it. I'm sure the other requests need the cookie session because they fail on postman for example but not here.</p>
<p>It's just a feature? Because I can't find anything on that also on the official <a href="https://github.com/Alamofire/Alamofire" rel="noreferrer">GitHub page</a>.</p> | 35,074,449 | 2 | 0 | null | 2016-01-26 22:16:45.027 UTC | 11 | 2021-07-08 08:38:28.6 UTC | 2019-03-11 09:05:18.497 UTC | null | 4,582,941 | null | 4,582,941 | null | 1 | 36 | ios|swift|post|cookies|alamofire | 10,129 | <p>Yes! Alamofire is basically a wrapper around <code>NSURLSession</code>. Its manager uses a default <code>NSURLSessionConfiguration</code> by calling <code>defaultSessionConfiguration()</code>. </p>
<p>As its github page says under <a href="https://github.com/Alamofire/Alamofire#advanced-usage"><em>Advanced Usage</em></a> section:</p>
<blockquote>
<p>Alamofire is built on <strong>NSURLSession</strong> and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack.</p>
</blockquote>
<p>And under <a href="https://github.com/Alamofire/Alamofire#manager"><em>Manager</em></a> section:</p>
<blockquote>
<p>Top-level convenience methods like Alamofire.request use a shared instance of Alamofire.Manager, which is configured with the <strong>default NSURLSessionConfiguration</strong>.</p>
</blockquote>
<p>And the <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/index.html#//apple_ref/occ/clm/NSURLSessionConfiguration/defaultSessionConfiguration">NSURLSessionConfiguration reference</a> for <code>defaultSessionConfiguration()</code> says:</p>
<blockquote>
<p>The default session configuration uses a persistent disk-based cache (except when the result is downloaded to a file) and stores credentials in the user’s keychain. It also <strong>stores cookies</strong> (by default) in the same shared cookie store as the NSURLConnection and NSURLDownload classes.</p>
</blockquote> |
49,817,396 | Validation failed for query for method public abstract java.util.List | <p>I have a basic SpringBoot app. using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
The version of SpringBoot is 2.0.1.RELEASE.
I've created a class repository that extends from CrudRepository with this method</p>
<pre><code>@Query("select us.priceAlertsTapas.tapa from User us left join us.priceAlertsTapas pat left join pat.tapa tapa where pat.priceAlert = ?1")
List<Tapa> tapasByUserPriceAlert (PriceAlert pa);
</code></pre>
<p>But when I init the project I got this error:</p>
<pre><code>Validation failed for query for method public abstract java.util.List
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:93)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:63)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:76)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:56)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:139)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:79)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:553)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:546)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1049)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:548)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:538)
at java.util.Optional.map(Optional.java:215)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:538)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:317)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$3(RepositoryFactoryBeanSupport.java:287)
at org.springframework.data.util.Lazy.getNullable(Lazy.java:141)
at org.springframework.data.util.Lazy.get(Lazy.java:63)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:290)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:102)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1761)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698)
... 47 common frames omitted
Caused by: java.lang.NullPointerException: null
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromJoinElement(HqlSqlWalker.java:424)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.joinElement(HqlSqlBaseWalker.java:3931)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3717)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3595)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
at com.sun.proxy.$Proxy105.createQuery(Unknown Source)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87)
... 76 common frames omitted
</code></pre>
<p>With the solution proposed I got the same error</p>
<p>With this query I have also the same error (?!?)</p>
<pre><code> @Query("select us.priceAlertsTapas.tapa from User us ")
</code></pre>
<p>Here the User object:</p>
<pre><code>@Entity
@Table(name="t_user")
public class User implements Serializable, UserDetails {
...
@ManyToMany
@JoinTable(
name="t_user_price_alert_tapa",
joinColumns=@JoinColumn(name="user_id", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="price_alert_tapa_id", referencedColumnName="id"))
private Set<PriceAlertTapa> priceAlertsTapas = new HashSet<>();
}
</code></pre>
<p>and</p>
<pre><code>@Entity
@Table(name="t_price_alert")
public class PriceAlert implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public PriceAlert(int id) {
super();
this.id = id;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
...
}
</code></pre>
<p>and</p>
<pre><code>@Entity
@Table(name="t_price_alert_tapa")
public class PriceAlertTapa implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
public PriceAlertTapa(PriceAlert priceAlert, Tapa tapa) {
super();
this.tapa = tapa;
this.priceAlert = priceAlert;
}
private Tapa tapa;
private PriceAlert priceAlert;
..
}
</code></pre> | 60,945,209 | 4 | 2 | null | 2018-04-13 12:48:27.523 UTC | 3 | 2020-03-31 07:48:00.483 UTC | 2018-04-17 09:42:39.91 UTC | null | 9,559,437 | null | 9,559,437 | null | 1 | 14 | java|spring-mvc|spring-boot|spring-data|spring-data-jpa | 61,191 | <p>I was getting this error as I was using table name in <code>@Query()</code>, but you have to use class name in <code>@Query()</code>:</p>
<p>Incorrect:</p>
<pre><code>@Transactional
@Modifying
@Query("from SHIPPING_DOC e where e.fulfillmentId in ?1")
List<ShippingDocumentsJsonEntity> deleteByFulfillmentIdIn(List<String> fulfillmentIds);
</code></pre>
<p>Correct:</p>
<pre><code>@Transactional
@Modifying
@Query("from ShippingDocumentsJsonEntity e where e.fulfillmentId in ?1")
List<ShippingDocumentsJsonEntity> deleteByFulfillmentIdIn(List<String> fulfillmentIds);
</code></pre> |
27,884,703 | Set paragraph font in python-docx | <p>I am using python-docx 0.7.6.</p>
<p>I can't seem to be able to figure out how to set font family and size for a certain paragraph.</p>
<p>There is <code>.style</code> property but <code>style="Times New Roman"</code> doesn't work.</p>
<p>Can somebody please point me to an example?</p>
<p>Thanks.</p> | 29,425,929 | 5 | 0 | null | 2015-01-11 06:49:18.62 UTC | 7 | 2021-05-01 09:18:12.283 UTC | 2018-06-13 05:03:31.883 UTC | null | 3,718,878 | null | 1,736,522 | null | 1 | 13 | python|python-docx | 52,710 | <p>Support for run styles has been added in latest version of python-docx</p> |
49,757,709 | Kafka Streams and RPC: is calling REST service in map() operator considered an anti-pattern? | <p>The naive approach for implementing the use case of enriching an incoming stream of events stored in Kafka with reference data - is by calling in <code>map()</code> operator an external service REST API that provides this reference data, for each incoming event.</p>
<pre><code>eventStream.map((key, event) -> /* query the external service here, then return the enriched event */)
</code></pre>
<p>Another approach is to have second events stream with reference data and store it in <code>KTable</code> that will be a lightweight embedded "database" then join main event stream with it.</p>
<pre><code>KStream<String, Object> eventStream = builder.stream(..., "event-topic");
KTable<String, Object> referenceDataTable = builder.table(..., "reference-data-topic");
KTable<String, Object> enrichedEventStream = eventStream
.leftJoin(referenceDataTable , (event, referenceData) -> /* return the enriched event */)
.map((key, enrichedEvent) -> new KeyValue<>(/* new key */, enrichedEvent)
.to("enriched-event-topic", ...);
</code></pre>
<p>Can the "naive" approach be considered an anti-pattern? Can the "<code>KTable</code>" approach be recommended as the preferred one?</p>
<p>Kafka can easily manage millions of messages per minute. Service that is called from the <code>map()</code> operator should be capable of handling high load too and also highly-available. These are extra requirements for the service implementation. But if the service satisfies these criteria can the "naive" approach be used?</p> | 49,771,142 | 2 | 0 | null | 2018-04-10 15:35:46.713 UTC | 9 | 2019-02-11 16:03:38.243 UTC | 2019-02-11 16:03:38.243 UTC | null | 1,743,580 | null | 7,873,775 | null | 1 | 17 | apache-kafka|apache-kafka-streams | 8,670 | <p>Yes, it is ok to do RPC inside Kafka Streams operations such as <code>map()</code> operation. You just need to be aware of the pros and cons of doing so, see below. Also, you should do any such RPC calls <em>synchronously</em> from within your operations (I won't go into details here why; if needed, I'd suggest to create a new question).</p>
<p><strong>Pros of doing RPC calls from within Kafka Streams operations:</strong></p>
<ul>
<li>Your application will fit more easily into an existing architecture, e.g. one where the use of REST APIs and request/response paradigms is common place. This means that you can make more progress quickly for a first proof-of-concept or MVP. </li>
<li>The approach is, in my experience, easier to understand for many developers (particularly those who are just starting out with Kafka) because they are familiar with doing RPC calls in this manner from their past projects. Think: it helps to move gradually from request-response architectures to event-driven architectures (powered by Kafka).</li>
<li>Nothing prevents you from starting with RPC calls and request-response, and then later migrating to a more Kafka-idiomatic approach.</li>
</ul>
<p><strong>Cons:</strong></p>
<ol>
<li>You are coupling the availability, scalability, and latency/throughput of your Kafka Streams powered application to the availability, scalability, and latency/throughput of the RPC service(s) you are calling. This is relevant also for thinking about SLAs.</li>
<li>Related to the previous point, Kafka and Kafka Streams scale very well. If you are running at large scale, your Kafka Streams application might end up DDoS'ing your RPC service(s) because the latter probably can't scale as much as Kafka. You should be able to judge pretty easily whether or not this is a problem for you in practice.</li>
<li>An RPC call (like from within <code>map()</code>) is a side-effect and thus a black box for Kafka Streams. The processing guarantees of Kafka Streams do not extend to such side effects.
<ul>
<li>Example: Kafka Streams (by default) processes data based on event-time (= based on when an event happened in the real world), so you can easily re-process old data and still get back the same results as when the old data was still new. But the RPC service you are calling during such reprocessing might return a different response than "back then". Ensuring the latter is your responsibility.</li>
<li>Example: In the case of failures, Kafka Streams will retry operations, and it will guarantee exactly-once processing (if enabled) even in such situations. But it can't guarantee, by itself, that an RPC call you are doing from within <code>map()</code> will be idempotent. Ensuring the latter is your responsibility.</li>
</ul></li>
</ol>
<p><strong>Alternatives</strong></p>
<p>In case you are wondering what other alternatives you have: If, for example, you are doing RPC calls for looking up data (e.g. for enriching an incoming stream of events with side/context information), you can address the downsides above by making the lookup data available in Kafka directly. If the lookup data is in MySQL, you can setup a Kafka connector to continuously ingest the MySQL data into a Kafka topic (think: CDC). In Kafka Streams, you can then read the lookup data into a <code>KTable</code> and perform the enrichment of your input stream via a stream-table join.</p> |
44,909,140 | The audience is invalid error | <p>I have 3 projects 1- Javascript SPA 2- Web API Project, 3- IdentityServer with EF Core</p>
<p>I started debugging API and Identity Server and successfully get the jwt token but, when I try to get value from API method which has Authorize Attribute I get an error:</p>
<pre><code>WWW-Authenticate →Bearer error="invalid_token", error_description="The audience is invalid"
</code></pre>
<p>I could not found any property about audience in auth options. This is my configuration in API project</p>
<pre><code>app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
ApiSecret="secret",
Authority = "http://localhost:5000",
ApiName="fso.Api",
RequireHttpsMetadata = false,
});
</code></pre>
<p>And my Config.cs file in Identity </p>
<pre><code> public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource()
{
Name = "fso.Api",
DisplayName = "feasion API",
Scopes =
{
new Scope("api1"),
new Scope(StandardScopes.OfflineAccess)
},
UserClaims =
{
JwtClaimTypes.Subject,
JwtClaimTypes.EmailVerified,
JwtClaimTypes.Email,
JwtClaimTypes.Name,
JwtClaimTypes.FamilyName,
JwtClaimTypes.PhoneNumber,
JwtClaimTypes.PhoneNumberVerified,
JwtClaimTypes.PreferredUserName,
JwtClaimTypes.Profile,
JwtClaimTypes.Picture,
JwtClaimTypes.Locale,
JwtClaimTypes.IdentityProvider,
JwtClaimTypes.BirthDate,
JwtClaimTypes.AuthenticationTime
}
}
};
}
public static List<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Email(),
new IdentityResources.Profile(),
};
}
// client want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "fso.api",
AllowOfflineAccess=true,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
AllowedScopes =
{
StandardScopes.OfflineAccess,
"api1"
}
}
};
}
}
</code></pre> | 44,909,827 | 4 | 0 | null | 2017-07-04 14:57:24.717 UTC | 5 | 2022-04-08 21:23:11.403 UTC | null | null | null | null | 3,838,116 | null | 1 | 38 | jwt|identityserver4 | 72,893 | <p>See <a href="http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#audDef" rel="noreferrer">here</a> for what this claim is about:</p>
<blockquote>
<p>The aud (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the aud claim when this claim is present, then the JWT MUST be rejected....</p>
</blockquote>
<p>So your API's name must exist in the aud claim for the JWT to be valid when it is validated by the middleware in your API. You can use <a href="https://jwt.io/" rel="noreferrer">jwt.io</a> to look at your token by the way, that can be useful to help make sense of it.</p>
<p>In order to have IdentityServer to add your API's name to the aud claim your client code (which is attempting to get a resource from the API and therefore needs an access token) should request a scope from your API. For example like this (from an MVC client):</p>
<pre><code>app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
Authority = Configuration["IdpAuthorityAddress"],
ClientId = "my_web_ui_id",
Scope = { "api1" },
//other properties removed...
});
</code></pre> |
65,094,328 | How to fix "Content Security Policy - contains an invalid source" error? | <p>Im getting this error and I don´t know why, the scripts that I have included works?
And the error only shows up when I load a subpage. Not when I load the startpage.
So what Im I doing wrong?</p>
<pre><code>The source list for Content Security Policy directive 'script-src' contains an invalid source: ''strict-dynamic''. It will be ignored.
<meta http-equiv="Content-Security-Policy" content="script-src * 'unsafe-inline' 'unsafe-eval' https://checkout.dibspayment.eu https://www.google-analytics.com https://maps.google.com;">
</code></pre>
<p>Any input really appreciated, thanks.</p> | 65,101,892 | 1 | 0 | null | 2020-12-01 16:18:21.217 UTC | 4 | 2020-12-02 03:47:34.707 UTC | null | null | null | null | 354,901 | null | 1 | 18 | content-security-policy | 41,984 | <blockquote>
<p>And the error only shows up when I load a <strong>subpage</strong>. Im getting this error and I don´t know why<br>
<code>The source list for Content Security Policy directive 'script-src' contains an invalid source: ''strict-dynamic''. It will be ignored.</code></p>
</blockquote>
<p>It's not an error, just a warning that you browser does not support the <code>'strict-dynamic'</code> token. (guess you use Safari).</p>
<p>I guess that <strong>subpage</strong> is a some Google's iframe (oAuth2, reCaptcha, etc). That iframe publush it's own CSP wich contains the <code>'strict-dynamic'</code> token and this CSP was created in browsers <a href="https://csplite.com/csp198/#CSP_backward_compatibility" rel="noreferrer">backward compatibility</a> mode (Google make such).</p>
<p>That's a warning from third-party CSP, not your's.</p>
<blockquote>
<p>the scripts that I have included works?</p>
</blockquote>
<p>Your parent page has own CSP which allows scripts. The CSP of nested browsing context (iframe) does not affects parent page (except the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors" rel="noreferrer">frame-ancestors</a> directive).</p>
<blockquote>
<p>So what Im I doing wrong?</p>
</blockquote>
<p>Nothing. It's an intended regular work of Content Security Policy.<br>
Each browsing context can have its own CSP. But all warns will flow to one browser console, and that is mislead.</p> |
56,492,261 | The function makes the dependencies of useEffect Hook | <p>I have a function that sets my useState when on click, everything works fine but I am getting a warning everytime:</p>
<pre><code> Line 22: The 'handleClickOpen' function makes the dependencies of useEffect Hook (at line 20) change on every render. To fix this, wrap the 'handleClickOpen' definition into its own useCallback() Hook react-hooks/exhaustive-deps
</code></pre>
<p>this is my code:</p>
<pre><code> useEffect(() => {
axios.get("/api/getBlacklist/").then(data => setBlacklistItems(data.data));
// eslint-disable-next-line
}, [handleClickOpen]);
function handleClickOpen() {
setOpen(true);
}
</code></pre>
<p>I have tried to replace <code>handleClickOpen</code> in <code>useEffect</code> with just <code>setOpen(true)</code>, but then my page crashes because of too many re-renders.</p>
<p>How to deal with this situation?</p> | 56,492,329 | 1 | 1 | null | 2019-06-07 10:06:40.14 UTC | 5 | 2020-08-24 15:19:21.127 UTC | null | null | null | null | 9,067,780 | null | 1 | 57 | reactjs | 43,471 | <p>Every render it will create new <code>handleClickOpen</code> function. You can memoize it by <code>useCallback</code></p>
<pre><code>import { useCallback } from 'react'
const handleClickOpen = useCallback(() => {
setOpen(true)
}, [])
</code></pre> |
42,925,823 | Hibernate: LazyInitializationException: failed to lazily initialize a collection of role. Could not initialize proxy - no Session | <p>I have next error: <code>nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.Model.entities, could not initialize proxy - no Session</code></p>
<p>My <code>Model</code> entity:</p>
<pre><code>class Model {
...
@OneToMany(fetch = FetchType.LAZY, mappedBy = "model", orphanRemoval = true)
@Cascade(CascadeType.ALL)
@Fetch(value = FetchMode.SUBSELECT)
public Set<Entity> getEntities() {
return entities;
}
public void addEntity(Entity entity) {
entity.setModel(this);
entities.add(entity);
}
}
</code></pre>
<p>And I have a service class:</p>
<pre><code>@Service
@Transactional
class ServiceImpl implements Service {
@Override
public void process(Model model) {
...
model.addEntity(createEntity());
...
}
}
</code></pre>
<p>I'm calling service from another service method:</p>
<pre><code>@Override
@JmsListener(destination = "listener")
public void handle(final Message message) throws Exception {
Model model = modelService.getById(message.getModelId());
serviceImpl.process(model);
modelService.update(model);
}
</code></pre>
<p>But when I'm trying to call this method I'm getting exception on line <code>entities.add(entity);</code> also the same exception occurs when I'm calling <code>getEntities()</code> on <code>model</code> .
I've checked transaction manager and it's configured correctly and transaction exists on this step. Also I've checked tons of answers on stackoverflow connected to this exception but nothing useful.</p>
<p>What could be the cause of it?</p> | 42,925,997 | 2 | 4 | null | 2017-03-21 11:28:48.127 UTC | 0 | 2019-04-01 15:59:14.237 UTC | 2019-04-01 15:59:14.237 UTC | null | 2,202,415 | null | 2,055,854 | null | 1 | 13 | java|spring|hibernate|jpa|spring-transactions | 55,330 | <p>It seems that model is a detached entity.</p>
<p>Try to merge and perform operations on a merge instance:</p>
<pre><code>@Override
public void process(Model model) {
...
Model mergedModel = session.merge(model);
mergedModel.addEntity(createEntity());
...
}
</code></pre> |
25,514,876 | How to filter JSON data in node.js? | <p>I have seen very old answers to this question and many of the technologies used 2 years back have changed.</p>
<p>What I have is JSON files sent by a database over to my server, and what I would like to know is how to filter that data.</p>
<p>I am running a server with node.js, and what I would like to do is something like:</p>
<pre><code>var results = QueryLibrary.load(jsondata);
var filtered = results.query('select where user = "user1"');
</code></pre>
<p>How can I do something like this in javascript running in node?</p> | 25,515,035 | 2 | 1 | null | 2014-08-26 20:47:23.693 UTC | 3 | 2015-03-14 07:39:46.853 UTC | 2014-08-26 21:13:31.427 UTC | null | 1,026,353 | null | 1,020,804 | null | 1 | 9 | javascript|json|node.js | 49,530 | <p><a href="http://underscorejs.org/">underscore</a> has a <a href="http://underscorejs.org/#where">where</a> function that does just this</p>
<pre><code>var _ = require("underscore");
var json = '[{"user": "a", "age": 20}, {"user": "b", "age": 30}, {"user": "c", "age": 40}]';
var users = JSON.parse(json);
var filtered = _.where(users, {user: "a"});
// => [{user: "a", age: 20}]
</code></pre>
<p>Another utility library, <a href="http://lodash.com/">Lo-Dash</a>, has a <a href="http://lodash.com/docs#where">where</a> function that operates identically.</p>
<hr>
<p>You can add underscore to your project using</p>
<pre><code>$ npm install --save underscore
</code></pre>
<p>or lodash</p>
<pre><code>$ npm install --save lodash
</code></pre>
<hr>
<p>If you <strong>only</strong> care about the <code>where</code> function, lodash offers it as a separate module</p>
<pre><code>// only install lodash.where
$ npm install --save lodash.where
</code></pre>
<p>To use it in your project</p>
<pre><code>var where = require("lodash.where");
// ...
var filtered = where(users, {"user": "a"});
</code></pre>
<hr>
<p>Even if you use a library to do this, a better approach is probably to setup a chain of streams that handles all of your data processing in smaller modules.</p>
<p>Without knowing what you actually want to do, I've created this as an example. For the purposes of this code, maybe think of a debug logging stream or something.</p>
<p><strong>json-parser.js</strong></p>
<p>input: string (JSON)<br>
output: object</p>
<pre><code>var Transform = require("stream").Transform;
function JsonParser() {
Transform.call(this, {objectMode: true});
this._transform = function _transform(json, enc, done) {
try {
this.push(JSON.parse(json));
}
catch (e) {
return done(e);
}
done();
}
}
JsonParser.prototype = Object.create(Transform.prototype, {
constructor: {
value: JsonParser
}
});
module.exports = JsonParser;
</code></pre>
<p><strong>obj-filter.js</strong></p>
<p>input: object<br>
output: object (result of <code>where(data, filters)</code>)</p>
<pre><code>var Transform = require("stream").Transform;
var where = require("lodash.where");
function ObjFilter(filters) {
Transform.call(this, {objectMode: true});
this._transform = function _transform(obj, enc, done) {
this.push(where(obj, filters));
done();
}
}
ObjFilter.prototype = Object.create(Transform.prototype, {
constructor: {
value: ObjFilter
}
});
module.exports = ObjFilter;
</code></pre>
<p><strong>stringifier.js</strong></p>
<p>input: object<br>
output: string (JSON)</p>
<pre><code>var Transform = require("stream").Transform;
function Stringifier() {
Transform.call(this, {objectMode: true});
this._transform = function _transform(obj, enc, done) {
this.push(JSON.stringify(obj));
done();
}
}
Stringifier.prototype = Object.create(Transform.prototype, {
constructor: {
value: Stringifier
}
});
module.exports = Stringifier;
</code></pre>
<p><strong>app.js</strong></p>
<pre><code>// modules
var JsonParser = require("json-parser");
var ObjFilter = require("obj-filter");
var Stringifier = require("stringifier");
// run
var parser = new JsonParser();
// setup stream chain
parser.pipe(new ObjFilter({"user": "a"}))
.pipe(new Stringifier())
.pipe(process.stdout);
// send example json in
parser.write('[{"user": "a", "age": 20}, {"user": "b", "age": 30}, {"user": "c", "age": 40}]');
// output
// => [{"user":"a","age":20}]
</code></pre>
<p>Here, I made a <code>Stringifier</code> stream that converts objects back into JSON so that we can see them dumped into the console, though you could easily create any streams you needed to handle the operations that your app requires. Your stream end points will likely not end up in writing to the console.</p>
<p>As a last note, you would probably create a database stream that accepts some sort of query options and emits json. You would pipe that stream directly into <code>parser</code>.</p>
<p>Anyway, I hope this gives you a better idea of how to process data in node.js.</p> |
25,651,342 | How to add ASP.NET MVC5 Identity Authentication to existing database | <p>I am learning MVC5 identity authentication and was reading materials on www.asp.net.
I have a few questions here.</p>
<ol>
<li><p>If I want to use identity authentication, is there a reason not to use MVC template? Or is there a reason to use empty template? MVC template also provides bootstrap.</p></li>
<li><p>I have a database created, I want to have a DB first development. If I use the MVC template, the database for credentials will be created under the project folder. How can I merge the two database or I should just use two databases?</p></li>
</ol>
<p>If my question is silly, just ignore me or give tell me what to read first.
I know people in the community are good but critical.
Thank you</p> | 25,651,908 | 1 | 1 | null | 2014-09-03 18:35:37.607 UTC | 17 | 2017-10-30 23:14:50.357 UTC | 2014-09-03 19:50:06.283 UTC | null | 296,861 | null | 3,942,851 | null | 1 | 36 | asp.net|asp.net-mvc-5|asp.net-identity | 41,425 | <blockquote>
<p>1) If I want to use identity authentication, is there a reason not to use
MVC template? Or is there a reason to use empty template? MVC template
also provides bootstrap.</p>
</blockquote>
<p>Identity authentication, MVC template and bootstrap are not really related. </p>
<p>If you create new MVC 5 application, <strong>AccountController</strong> is created for you. You can use that <strong>AccountController</strong> as starting point. </p>
<p>If you want, you can delete the <strong>AccountController</strong> and create one yourself, but it is a lot of work.</p>
<blockquote>
<p>2) I have a database created, I want to have a DB first development. If I
use the MVC template, the database for credentials will be created
under the project folder. How can I merge the two database or I should
just use two databases?</p>
</blockquote>
<p><strong>You do not need two databases</strong> - you can place Identity tables and your custom tables in same database. </p>
<p>Start with Identity - let it creates database and its required tables. Then you can add custom tables to that Identity database.</p>
<p>Or </p>
<p>If you already have database with connection string, you can change the Identity connection name at the following place. Identity will create its tables inside that existing database.</p>
<p><img src="https://i.stack.imgur.com/9hU8I.png" alt="enter image description here"></p> |
46,850,694 | In Cypress how to count a selection of items and get the length? | <p>I'm starting to learn Cypress. I have a 4 row table (with a class of datatable). I can verify the number of rows this way:</p>
<pre class="lang-js prettyprint-override"><code>cy.get('.datatable').find('tr').each(function(row, i){
expect(i).to.be.lessThan(4)
})
</code></pre>
<p>This is fine, but it seems awkward, since I just want to count the length and don't really need to access the stuff in the rows, and I assume it's faster to do one thing than do 4 things.</p>
<p>If I log the selection (not sure what else to call it):</p>
<pre class="lang-js prettyprint-override"><code>cy.log(cy.get('.datatable').find('tr'))
</code></pre>
<p>it comes out as <code>[object Object]</code> and I'm not quite sure how to deconstruct that, which suggests to me that I'm thinking about this all wrong.</p>
<p>If I try:</p>
<pre class="lang-js prettyprint-override"><code>expect(cy.get('.datatable').find('tr')).to.have.lengthOf(4)
</code></pre>
<p>I get <code>AssertionError: expected { Object (chainerId, firstCall) } to have a property 'length'</code></p>
<p>If I try:</p>
<pre class="lang-js prettyprint-override"><code>expect(Cypress.$('.datatable > tr')).to.have.lengthOf(4)
</code></pre>
<p>I get <code>AssertionError: expected { Object (length, prevObject, ...) } to have a length of 4 but got 0</code> so at least it has a length here?</p>
<p>If I log that method of selection I get <code>Object{4}</code>. I'm not sure where to go from here. It seems like this would be a very common thing to deal with.</p> | 46,850,775 | 12 | 2 | null | 2017-10-20 13:57:14.627 UTC | 8 | 2022-07-14 06:14:50.96 UTC | 2022-07-14 06:14:50.96 UTC | null | 5,018,771 | null | 4,126,167 | null | 1 | 170 | automated-tests|cypress | 188,609 | <p>Found a solution, This works to check a count of items:</p>
<pre><code>cy.get('.datatable').find('tr').should('have.length', 4)
</code></pre>
<p>This does not work with the <code>Cypress.$()</code> method of notation.</p>
<p>Reference: <a href="https://docs.cypress.io/guides/references/assertions.html#Length" rel="noreferrer">https://docs.cypress.io/guides/references/assertions.html#Length</a></p> |
60,068,435 | What is Null Safety in Dart? | <p>I have heard of the new Dart null safety language feature (NNBD), currently the "<strong>'non-nullable' experiment</strong>". It is supposed to introduce <strong><em>non-nullable</em> by default</strong>.</p>
<p>The feature specification can be <a href="https://github.com/dart-lang/language/blob/bdbef03e26047a1f59152f97d23663cf93a7108e/accepted/2.12/nnbd/feature-specification.md" rel="nofollow noreferrer">found here</a> and the language <a href="https://github.com/dart-lang/language/issues/110#issue-385073398" rel="nofollow noreferrer">GitHub issue here</a>.</p>
<p>How does it work and where can I try it?</p> | 60,068,436 | 2 | 2 | null | 2020-02-05 03:01:22.037 UTC | 42 | 2022-02-21 20:31:33.447 UTC | 2022-02-21 20:31:33.447 UTC | null | 179,715 | null | 6,509,751 | null | 1 | 100 | flutter|dart|dart-null-safety | 63,310 | <h1>1. Null safety / non-nullable (by default)</h1>
<p>The null safety / non-nullable (by default), short NNBD, feature can currently be found at <a href="https://nullsafety.dartpad.dev/" rel="noreferrer">nullsafety.dartpad.dev</a>.</p>
<p>Keep in mind that you can read the <a href="https://github.com/dart-lang/language/blob/bdbef03e26047a1f59152f97d23663cf93a7108e/accepted/2.12/nnbd/feature-specification.md" rel="noreferrer">full spec here</a> and <a href="https://github.com/dart-lang/language/blob/bdbef03e26047a1f59152f97d23663cf93a7108e/accepted/2.12/nnbd/roadmap.md" rel="noreferrer">full roadmap here</a>. Now, sound null safety has also been <a href="https://medium.com/dartlang/announcing-sound-null-safety-defd2216a6f3" rel="noreferrer">officially announced for Dart</a>.</p>
<hr />
<h2>2.1. What does non-nullable by default mean?</h2>
<pre class="lang-dart prettyprint-override"><code>void main() {
String word;
print(word); // illegal
word = 'Hello, ';
print(word); // legal
}
</code></pre>
<p>As you can see above, a variable being <em>non-nullable <strong>by default</strong></em> means that every variable that is declared normally <strong>cannot</strong> be <code>null</code>. Consequently, any operation accessing the variable before it has been assigned is illegal.<br />
Additionally, assigning <code>null</code> to a non-nullable variable is also not allowed:</p>
<pre class="lang-dart prettyprint-override"><code>void main() {
String word;
word = null; // forbidden
world = 'World!'; // allowed
}
</code></pre>
<h3>2.1.1. How does this help me?</h3>
<p>If a variable is <em>non-nullable</em>, you can be sure that it is never <code>null</code>. Because of that, you never need to check it beforehand.</p>
<pre class="lang-dart prettyprint-override"><code>int number = 4;
void main() {
if (number == null) return; // redundant
int sum = number + 2; // allowed because number is also non-nullable
}
</code></pre>
<h3>2.1.2. Remember</h3>
<p>Instance fields in classes <strong>must be initialized</strong> if they are not nullable:</p>
<pre class="lang-dart prettyprint-override"><code>class Foo {
String word; // forbidden
String sentence = 'Hello, World!'; // allowed
}
</code></pre>
<p>See <code>late</code> below to modify this behavior.</p>
<h2>2.2. Nullable types (<code>?</code>)</h2>
<p>You can use <strong>nullable types</strong> by appending a question mark <code>?</code> to a variable type:</p>
<pre class="lang-dart prettyprint-override"><code>class Foo {
String word; // forbidden
String? sentence; // allowed
}
</code></pre>
<p>A <em>nullable</em> variable does not need to be initialized before it can be used. It is initialized as <code>null</code> by default:</p>
<pre class="lang-dart prettyprint-override"><code>void main() {
String? word;
print(word); // prints null
}
</code></pre>
<h3>2.2.2. <code>!</code></h3>
<p>Appending <strong><code>!</code></strong> to any variable <code>e</code> will throw a <strong>runtime error</strong> if <code>e</code> is null and otherwise convert it to a <strong>non-nullable</strong> value <code>v</code>.</p>
<pre class="lang-dart prettyprint-override"><code>void main() {
int? e = 5;
int v = e!; // v is non-nullable; would throw an error if e were null
String? word;
print(word!); // throws runtime error if word is null
print(null!); // throws runtime error
}
</code></pre>
<h2>2.3. <code>late</code></h2>
<p>The keyword <code>late</code> can be used to mark variables that will be <strong>initialized later</strong>, i.e. not when they are declared but when they are accessed. This also means that we can have non-nullable <em>instance fields</em> that are initialized later:</p>
<pre class="lang-dart prettyprint-override"><code>class ExampleState extends State {
late final String word; // non-nullable
@override
void initState() {
super.initState();
// print(word) here would throw a runtime error
word = 'Hello';
}
}
</code></pre>
<p>Accessing <code>word</code> before it is initialized will throw a runtime error.</p>
<h3>2.3.1. <code>late final</code></h3>
<p>Final variables can now also be marked late:</p>
<pre class="lang-dart prettyprint-override"><code>late final int x = heavyComputation();
</code></pre>
<p>Here <code>heavyComputation</code> will only be called once <code>x</code> is accessed. Additionally, you can also declare a <code>late final</code> without an initializer, which is the same as having just a <code>late</code> variable, but it can only be assigned once.</p>
<pre class="lang-dart prettyprint-override"><code>late final int x;
// w/e
x = 5; // allowed
x = 6; // forbidden
</code></pre>
<p>Note that all <em>top-level</em> or <em>static</em> variables with an initializer will now be evaluated <code>late</code>, no matter if they are <code>final</code>.</p>
<h2>2.4. <code>required</code></h2>
<p>Formerly an <strong>annotation</strong> (<code>@required</code>), now built-in as a modifier. It allows to mark any named parameter (for functions or classes) as <code>required</code>, which makes them non-nullable:</p>
<pre class="lang-dart prettyprint-override"><code>void allowed({required String word}) => null;
</code></pre>
<p>This also means that if a parameter should be <strong>non-nullable</strong>, it needs to be marked as <code>required</code> or have a default value:</p>
<pre class="lang-dart prettyprint-override"><code>void allowed({String word = 'World'}) => null;
void forbidden({int x}) // compile-time error because x can be null (unassigned)
=>
null;
</code></pre>
<p>Any other named parameter has to be <strong>nullable</strong>:</p>
<pre class="lang-dart prettyprint-override"><code>void baz({int? x}) => null;
</code></pre>
<h2>2.5. <code>?[]</code></h2>
<p>The null aware <code>?[]</code> operator was added for the index operator <code>[]</code>:</p>
<pre class="lang-dart prettyprint-override"><code>void main() {
List<int>? list = [1, 2, 3];
int? x = list?[0]; // 1
}
</code></pre>
<p>See also <a href="https://medium.com/dartlang/dart-nullability-syntax-decision-a-b-or-a-b-d827259e34a3" rel="noreferrer">this article about the syntax decision</a>.</p>
<h3>2.5.1. <code>?..</code></h3>
<p>The cascade operator now also has a new null aware operator: <code>?..</code>.</p>
<p>It causes the following cascade operations to only be executed if the recipient is <strong>not null</strong>. Therefore, the <code>?..</code> has to be the first cascade operator in a cascade sequence:</p>
<pre class="lang-dart prettyprint-override"><code>void main() {
Path? path;
// Will not do anything if path is null.
path
?..moveTo(3, 4)
..lineTo(4, 3);
// This is a noop.
(null as List)
?..add(4)
..add(2)
..add(0);
}
</code></pre>
<hr />
<h2>2.6. <code>Never</code></h2>
<p><em><strong>The following explanation sucks. Read <a href="https://dart.dev/null-safety/understanding-null-safety#top-and-bottom" rel="noreferrer">"Top and bottom" from "Understanding null safety"</a></strong></em> for a good one.</p>
<p>To avoid confusion: this is not something that developers have to worry about. I want to mention it for the sake of completeness.</p>
<p><code>Never</code> is going to be a type like the previously existing <a href="https://api.flutter.dev/flutter/dart-core/Null-class.html" rel="noreferrer"><code>Null</code></a> (<strong>not <code>null</code></strong>) defined in <code>dart:core</code>. Both of these classes cannot be extended, implemented, or mixed in, so they are not intended to be used.</p>
<p>Essentially, <code>Never</code> means that no type is allowed and <code>Never</code> itself cannot be instantiated.<br />
Nothing but <code>Never</code> in a <code>List<Never></code> satisfies the generic type constraint of the list, which means that it <em>has to be <strong>empty</strong></em>. <code>List<Null></code>, however, can contain <code>null</code>:</p>
<pre class="lang-dart prettyprint-override"><code>// Only valid state: []
final neverList = <Never>[
// Any value but Never here will be an error.
5, // error
null, // error
Never, // not a value (compile-time error)
];
// Can contain null: [null]
final nullList = <Null>[
// Any value but Null will be an error.
5, // error
null, // allowed
Never, // not a value (compile-time error)
Null, // not a value (compile-time error)
];
</code></pre>
<p>Example: the compiler will infer <code>List<Never></code> for an <strong>empty</strong> <code>const List<T></code>.<br />
<code>Never</code> is not supposed to be used by programmers as far as I am concerned. (<a href="https://dart.dev/null-safety/understanding-null-safety#never-for-unreachable-code" rel="noreferrer">I was wrong</a>).</p>
<h1>3. Learn more</h1>
<p>You can read the <a href="https://dart.dev/null-safety" rel="noreferrer">official article on sound null safety</a>.<br />
Furthermore as mentioned at the beginning, you can <a href="https://nullsafety.dartpad.dev/" rel="noreferrer">play with it on DartPad</a>.</p> |
20,118,783 | Web Deploy from Visual Studio 2012 to a remote IIS 8 server | <p>I have a remote Windows 2012 server running IIS 8 from which I am hosting a web application. My local development box is running Visual Studio 2012. Currently I am publishing my app as a web deployment package (.zip), RDP'ing to the production server, copy + pasting to a folder and deploying the application from within IIS. My question is, what changes do I need to make to deploy directly to IIS from Visual Studio 2012 using the web deploy option?</p>
<p>I have tried to follow <a href="http://msdn.microsoft.com/en-us/library/dd465337%28v=vs.110%29.aspx" rel="noreferrer">this guide</a> but it refers to a <code>service URL</code> which I must obtain from my hosting company. I don't have a hosting company, my server is co-located.</p>
<p>I am presented with the following options:</p>
<p><img src="https://i.stack.imgur.com/peRhQ.png" alt="Web deploy options"></p>
<p>Is the username and password the one I use for the RDP account? I already have Web Deploy 3.0 installed on IIS do I need to enable further settings?</p> | 22,937,488 | 2 | 1 | null | 2013-11-21 10:46:34.837 UTC | 16 | 2017-03-09 13:02:49.72 UTC | 2014-04-08 12:45:52.757 UTC | null | 972,891 | null | 972,891 | null | 1 | 34 | iis|visual-studio-2012|webdeploy|windows-server-2012|iis-8 | 37,741 | <p>OK I found the solution but it took me a whole day to get it working! Basically the steps are as follows. This is very sketchy but see the detailed guides below which helped me.</p>
<ol>
<li>Enable the IIS Web Management role feature.</li>
<li>Install Web Deploy 3.0 (or higher). Make sure to customise the install to include the handlers (See notes below). If you're not presented with this option go to add/remove programs, find webdeploy, right click and select "change" option.</li>
<li>In IIS click on the server node and find the "Management Service" icon. Enable remote access and configure a dedicated IIS User for remote deployment (These will be the credentials that will go in the user name and password boxes).</li>
<li>At the site level in IIS assign this user to manage the website.</li>
<li>Make sure port 8172 is open on the web server (<a href="http://www.canyouseeme.org/" rel="noreferrer">you can check this port here</a>).</li>
<li>Try reconnecting from Visual Studio. There was some trial and error here for me but the error messages do link to a MS guide for decoding :)</li>
<li>Even after connecting successfully I had to wrangle with permissions, so my IIS user had sufficient privileges to create the app pool, directories and general file management jobs.</li>
</ol>
<p>The following links really helped!</p>
<p>Configuring the handler on the web server:</p>
<p><a href="http://www.iis.net/learn/publish/using-web-deploy/configure-the-web-deployment-handler" rel="noreferrer">http://www.iis.net/learn/publish/using-web-deploy/configure-the-web-deployment-handler</a></p>
<p>Connecting via Visual Studio:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd465337(v=vs.110).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/dd465337(v=vs.110).aspx</a></p>
<p><strong>NOTES:</strong></p>
<p>To ensure the handler is running, login into your IIS server and point your browser to the following URL.</p>
<pre><code>https://<servername>:8172/MsDeploy.axd
</code></pre>
<p>F12 to open up the dev tools to see the HTTP response. Also MsDeploy also creates IIS logs in inetpub/logs which should give you some clue if you're having connectivity problems.</p> |
6,634,816 | Set time and speed complexity | <p>I am brushing up algorithms and data structures and have a few questions as well as statements I would like you to check.</p>
<p><strong>ArrayList</strong> - O(1) (size, get, set, ...), O(n) - add operation.<br>
<strong>LinkedList</strong> - all operation O(1) (including add() ), except for retrieving n-th element which is O(n). I assume size() operation runs in O(1) as well, right?</p>
<p><strong>TreeSet</strong> - all operations O(lg(N)). size() operation takes O(lg(n)), right?</p>
<p><strong>HashSet</strong> - all operations O(1) if proper hash function is applied.<br>
<strong>HashMap</strong> - all operations O(1), anologous to HashSet.</p>
<p>Any further explanations are highly welcome. Thank you in advance.</p> | 6,634,889 | 2 | 6 | null | 2011-07-09 12:47:37.107 UTC | 11 | 2018-03-12 14:37:26.333 UTC | null | null | null | null | 543,168 | null | 1 | 21 | java|algorithm|collections | 32,596 | <p><code>ArrayList.add()</code> is <em>amortized</em> O(1). If the operation doesn't require a resize, it's O(1). If it <em>does</em> require a resize, it's O(n), but the size is then increased such that the next resize won't occur for a while.</p>
<p>From the <a href="http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html" rel="noreferrer">Javadoc</a>:</p>
<blockquote>
<p>The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.</p>
</blockquote>
<p>The documentation is generally pretty good for Java collections, in terms of performance analysis.</p>
<p>The O(1) for hash algorithms isn't a matter of just applying a "proper" hash function - even with a very good hash function, you could still happen to get hash collisions. The <em>usual</em> complexity is O(1), but of course it can be O(n) if <em>all</em> the hashes happen to collide.</p>
<p>(Additionally, that's counting the cost of hashing as O(1) - in reality, if you're hashing strings for example, each call to <code>hashCode</code> may be O(k) in the length of the string.)</p> |
7,046,308 | Using a dropdown list to filter a table (dataTables) | <p>I'm using the dataTables jQuery plugin (which is totally awesome), but I'm having trouble getting my table to filter based on the change of my select box.</p>
<p>Function:</p>
<pre><code> $(document).ready(function() {
$("#msds-table").dataTable({
"sPaginationType": "full_numbers",
"bFilter": false
});
var oTable;
oTable = $('#msds-table').dataTable();
$('#msds-select').change( function() {
oTable.fnFilter( $(this).val() );
});
});
</code></pre>
<p>HTML:</p>
<pre><code> <table border="0" cellpadding="0" cellspacing="0" id="msds-table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>etc</th>
</tr>
</thead>
<tbody>
<select id="#msds-select">
<option>All</option>
<option>Group 1</option>
<option>Group 2</option>
<option>Group 3</option>
<option>Group 4</option>
<option>Group 5</option>
<option>Group 6</option>
</select>
<tr class="odd">
<td>Group 1</td>
<td><img src="images/modules/download-icon.gif" width="12" height="17" alt="" /></td>
<td><a href="#">Download</a></td>
</tr>
<tr class="even">
<td>Group 1</td>
<td><img src="images/modules/download-icon.gif" width="12" height="17" alt="" /></td>
<td><a href="#">Download</a></td>
</tr>
<tr class="odd">
<td>Group 1</td>
<td><img src="images/modules/download-icon.gif" width="12" height="17" alt="" /></td>
<td><a href="#">Download</a></td>
</tr>
</tbody>
</table>
</code></pre>
<p>Table goes on to display a bunch of items, up to "Group 6", but you get the idea.
Anyone ever tried to do this before?</p> | 7,046,545 | 3 | 3 | null | 2011-08-12 21:03:17.733 UTC | 4 | 2018-10-25 05:43:11.583 UTC | 2014-05-12 12:07:40.007 UTC | null | 80,840 | null | 606,670 | null | 1 | 9 | jquery|filter|drop-down-menu|datatables | 50,016 | <p><a href="http://www.datatables.net/usage/features">dataTables features</a></p>
<p>I knew I had done this before, and you have to watch this little piece of information:</p>
<blockquote>
<p>Note that if you wish to use filtering in DataTables this must remain
'true' - to remove the default filtering input box and retain
filtering abilities, please use
<a href="http://www.datatables.net/usage/options#sDom">sDom</a>.</p>
</blockquote>
<p>you need to set {bFilter:true}, and move your <code><select></select></code> into a custom element registered through sDom. I can guess your code will look like this:</p>
<pre><code>$(document).ready(function() {
$("#msds-table").dataTable({
"sPaginationType": "full_numbers",
"bFilter": true,
"sDom":"lrtip" // default is lfrtip, where the f is the filter
});
var oTable;
oTable = $('#msds-table').dataTable();
$('#msds-select').change( function() {
oTable.fnFilter( $(this).val() );
});
});
</code></pre>
<p>your code for <code>oTable.fnFilter( $(this).val() );</code> will not fire while <code>{bFilter:false};</code> according to the documentation</p> |
7,623,650 | resetting a stringstream | <p>How do I "reset" the state of a stringstream to what it was when I created it?</p>
<pre><code>int firstValue = 1;
int secondValue = 2;
std::wstringstream ss;
ss << "Hello: " << firstValue;
std::wstring firstText(ss.str());
//print the value of firstText here
//How do I "reset" the stringstream here?
//I would like it behave as if I had created
// stringstream ss2 and used it below.
ss << "Bye: " << secondValue;
std::wstring secondText(ss.str());
//print the value of secondText here
</code></pre> | 7,623,670 | 3 | 0 | null | 2011-10-01 23:36:41.13 UTC | 14 | 2021-10-04 21:51:38.793 UTC | null | null | null | null | 974,967 | null | 1 | 100 | c++|string|stringstream | 72,954 | <p>This is the way I usually do it:</p>
<pre><code>ss.str("");
ss.clear(); // Clear state flags.
</code></pre> |
7,373,838 | Working Capistrano recipe for uploading precompiled Rails 3.1 assets to Amazon S3 | <p>We have a Rails 3.1 app that allows users to upload photos to Amazon S3. Since we're using S3 in production I'd like to automatically (on <code>cap deploy</code>) also upload the precompiled assets (application.js & application.css & images) to our S3 bucket where they'll be served. Simple enough.</p>
<p>Beyond setting <code>config.action_controller.asset_host = "http://assets.example.com"</code> </p>
<p>In short, <strong>I'm looking for some examples of a working "recipe" for Capistrano to do so</strong> but can't seem to find any modern (3.1 asset pipeline compatible) ones. We are successfully precompiling the assets but how to move them to S3? <em>And, ideally, only the ones that have changed?</em></p>
<p>"Meat" of current "recipe":</p>
<pre><code>...
after "deploy:update_code", "deploy:pipeline_precompile"
before "deploy:finalize_update", "deploy:copy_database_config"
namespace :deploy do
task :start do ; end
task :stop do ; end
task :restart, :roles => :app, :except => { :no_release => true } do
run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
end
# copy database.yml into project
task :copy_database_config do
production_db_config = "/path_to_config/#{application}.yml"
run "cp #{production_db_config} #{current_release}/config/database.yml"
`puts "replaced database.yml with live copy"`
end
task :pipeline_precompile do
run "cd #{release_path}; RAILS_ENV=production bundle exec rake assets:precompile"
end
end
</code></pre> | 7,480,442 | 4 | 0 | null | 2011-09-10 18:46:33.633 UTC | 11 | 2012-06-08 05:23:16.727 UTC | 2012-06-08 05:23:16.727 UTC | null | 76,456 | null | 63,761 | null | 1 | 17 | ruby-on-rails|ruby-on-rails-3|capistrano|asset-pipeline | 9,491 | <p>While this doesn't directly answer the question of uploading your assets to S3 on deploy, I think the following approach may address your goals and be a little simpler to implement.</p>
<p>The primary benefits of hosting assets on S3 and using the <code>config.action_controller.asset_host</code> directive include (among others):</p>
<ul>
<li>allowing additional simultaneous downloads of assets</li>
<li>serving assets from a cookie-free domain</li>
</ul>
<p>Rather than using s3, you can use the <a href="http://aws.amazon.com/cloudfront/">CloudFront CDN</a> to achieve the same benefits. The new rails asset pipeline plays very nicely with CloudFront. Here are the steps I am currently using in production:</p>
<p><strong>Create a new CloudFront distribution</strong></p>
<ol>
<li>Delivery Method should be <em>Download</em></li>
<li>Choose <em>Custom Origin</em> and point it to your web server</li>
<li>For <em>Distribution Details</em> you can add addition CNAME records such as <code>cdn01.mydomain.com</code> etc.</li>
<li><em>Default Root Object</em> can be left empty</li>
</ol>
<p>If your site is served over SSL, you will need to use the <code>x12whx1751nfir.cloudfront.net</code> style hostname as custom certificates are not available yet as they are with ELB and your users will see certificate hostname mismatch errors. If you don't use SSL, you can use the either the default hostname or any CNAMEs prodvided.</p>
<p>Once this is setup, the initial object requests will be fetched from your server and placed within CloudFront. The digest fingerprints generated by the asset pipeline will handle your requirement for only sending assets which have changed. </p> |
7,920,777 | PostgreSQL copy command generate primary key id | <p>I have a CSV file with two columns: city and zipcode. I want to be able to copy this file into a PostgreSQL table using the <code>copy</code> command and at the same time auto generate the <code>id</code> value. </p>
<p>The table has the following columns: <code>id</code>, <code>city</code>, and <code>zipcode</code>.</p>
<p>My CSV file has only: <code>city</code> and <code>zipcode</code>.</p> | 7,921,458 | 1 | 0 | null | 2011-10-27 18:46:39.54 UTC | 13 | 2012-10-17 02:13:02.313 UTC | 2012-10-17 02:13:02.313 UTC | null | 479,863 | null | 373,201 | null | 1 | 55 | postgresql | 34,798 | <p>The <a href="http://www.postgresql.org/docs/current/static/sql-copy.html" rel="noreferrer">COPY command</a> should do that all by itself if your table uses a <code>serial</code> column for the <code>id</code>:</p>
<blockquote>
<p>If there are any columns in the table that are not in the column list, COPY FROM will insert the default values for those columns.</p>
</blockquote>
<p>So you should be able to say:</p>
<pre><code>copy table_name(city, zipcode) from ...
</code></pre>
<p>and the <code>id</code> will be generated as usual. If you don't have a <code>serial</code> column for <code>id</code> (or a manually attached sequence), then you could hook up a sequence by hand, do your COPY, and then detach the sequence.</p> |
1,531,391 | Launch XDebug in Netbeans on an external request | <p>I'm using Netbeans 6.7 and XDebug to debug a PHP site on my machine, launching the request from within Netbeans (Project->Debug). This works fine, and is very useful.</p>
<p>My question is: Is it possible to attach the debugger to any request that comes in, rather just those I launch from within Netbeans?</p>
<p>ie, instead of clicking "Debug", put Netbeans into a mode whereby the debugger is launched and attaches to the next request that comes in.</p>
<p>I have a feeling this may be a stupid question, but if it is possible, that'd be great.</p>
<p><strong>Edit:</strong> A bit more information</p>
<p>My system (Ubuntu 9.04) is set up as follows:</p>
<p>Contents of <code>/etc/php5/conf.d/xdebug.ini</code></p>
<pre><code>zend_extension=/usr/lib/php5/20060613/xdebug.so
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.idekey=netbeans-xdebug
</code></pre>
<p>Netbeans PHP debugging options are at the defaults:</p>
<pre><code>Debugger Port: 9000
Session ID: netbeans-xdebug
Stop at the First Line: ticked
</code></pre>
<p>My <code>/etc/hosts</code> file redirects <code>www.mywebsite.com</code> to <code>localhost</code></p>
<p>If I click on the debug button in Netbeans, then Firefox is launched with the address <code>http://www.mywebsite.com?XDEBUG_SESSION_START=netbeans-xdebug</code>, and the debugger works as expected.</p>
<p>But if I just browse to <code>http://www.mywebsite.com?XDEBUG_SESSION_START=netbeans-xdebug</code>, this doesn't start the debugger in Netbeans.</p>
<p>I've also tried setting <code>xdebug.remote_host=www.mywebsite.com</code> , but that makes no difference.</p>
<p>Also, I've enabled <code>xdebug.remote_log</code>, and that's showing information for when I start from within netbeans, but nothing for external requests. So I don't think XDebug is seeing the external requests at all.</p> | 1,544,745 | 4 | 3 | null | 2009-10-07 12:40:39.763 UTC | 18 | 2014-07-18 09:56:42.203 UTC | 2011-10-11 18:13:14.527 UTC | null | 8,331 | null | 8,331 | null | 1 | 38 | php|linux|netbeans|xdebug|netbeans6.7 | 21,173 | <p>go to <em>project properties</em> > <em>run configuration</em> > <em>advanced</em> > <em>debug url</em> and check <em>do not open web browser</em> (*). do <em>not</em> set the host under <em>debugger proxy</em>. save these settings. in the project window, on your project: <em>right mouse click</em> > <em>debug</em> (this starts listening for debug connections). no browser is started. enter <code>http://www.mywebsite.com?XDEBUG_SESSION_START=netbeans-xdebug</code> in your browser. it should break in netbeans. at least that's what happens here :)</p>
<p>(*) you might also have to set a <em>path mapping</em> - for me, it works without</p> |
1,834,556 | Does a File Object Automatically Close when its Reference Count Hits Zero? | <p>I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line:</p>
<pre><code>foo = open('foo').read()
</code></pre>
<p>would get you the file's contents and immediately close the file. However, after reading the answer to <a href="https://stackoverflow.com/questions/1832528/is-close-necessary-when-using-iterator-on-a-python-file-object">Is close() necessary when using iterator on a Python file object</a> I get the impression that this does not happen, and that calling <code>.close()</code> on a file object is <em>always</em> necessary.</p>
<p>Does the line above do what I think it's doing and even if it does, is it the Pythonic thing to do?</p> | 1,834,757 | 4 | 2 | null | 2009-12-02 17:35:39.72 UTC | 9 | 2012-01-06 16:49:21.21 UTC | 2017-05-23 12:18:10.873 UTC | null | -1 | null | 98,575 | null | 1 | 40 | python | 23,127 | <p>The answer is in the link you provided.</p>
<p>Garbage collector will close file when it destroys file object, but:</p>
<ul>
<li><p>you don't really have control over when it happens.</p>
<p>While CPython uses reference counting to deterministically release resources
(so you can predict when object will be destroyed) other versions don't have to.
For example both Jython or IronPython use JVM and .NET garbage collector which
release (and finalize) objects only when there is need to recover memory
and might not do that for some object until the end of the program.
And even for CPython GC algorithm may change in the future as reference counting
isn't very efficient.</p></li>
<li><p>if exception is thrown when closing file on file object destruction,
you can't really do anything about it because you won't know.</p></li>
</ul> |
7,472,863 | PyDev unittesting: How to capture text logged to a logging.Logger in "Captured Output" | <p>I am using PyDev for development and unit-testing of my Python application.
As for unit-testing, everything works great except the fact that no content is logged to the logging framework. The logger is not captured by the "Captured output" of PyDev.</p>
<p>I'm already forwarding everything logged to the standard output like this:</p>
<pre class="lang-py prettyprint-override"><code>import sys
logger = logging.getLogger()
logger.level = logging.DEBUG
logger.addHandler(logging.StreamHandler(sys.stdout))
</code></pre>
<p>Nevertheless the "Captured output" does not display the stuff logged to loggers.</p>
<p>Here's an example unittest-script: <em>test.py</em>
</p>
<pre><code>import sys
import unittest
import logging
logger = logging.getLogger()
logger.level = logging.DEBUG
logger.addHandler(logging.StreamHandler(sys.stdout))
class TestCase(unittest.TestCase):
def testSimpleMsg(self):
print("AA")
logging.getLogger().info("BB")
</code></pre>
<p>The console output is:</p>
<pre><code>Finding files... done.
Importing test modules ... done.
testSimpleMsg (itf.lowlevel.tests.hl7.TestCase) ... AA
2011-09-19 16:48:00,755 - root - INFO - BB
BB
ok
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
</code></pre>
<p>But the <strong>CAPTURED OUTPUT</strong> for the test is:</p>
<pre><code>======================== CAPTURED OUTPUT =========================
AA
</code></pre>
<p>Does anybody know how to capture everything that is logged to a <code>logging.Logger</code> during the execution of this test?</p> | 7,483,862 | 8 | 0 | null | 2011-09-19 14:54:18.383 UTC | 19 | 2021-10-04 10:22:13.137 UTC | 2019-01-22 11:05:20.737 UTC | null | 376,390 | null | 672,848 | null | 1 | 77 | python|unit-testing|logging|pydev | 74,460 | <p>The issue is that the <code>unittest</code> runner replaces <code>sys.stdout</code>/<code>sys.stderr</code> before the testing starts, and the <code>StreamHandler</code> is still writing to the original <code>sys.stdout</code>. </p>
<p>If you assign the 'current' <code>sys.stdout</code> to the handler, it should work (see the code below).</p>
<pre class="lang-py prettyprint-override"><code>import sys
import unittest
import logging
logger = logging.getLogger()
logger.level = logging.DEBUG
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
class TestCase(unittest.TestCase):
def testSimpleMsg(self):
stream_handler.stream = sys.stdout
print("AA")
logging.getLogger().info("BB")
</code></pre>
<p>Although, a better approach would be adding/removing the handler during the test:</p>
<pre class="lang-py prettyprint-override"><code>import sys
import unittest
import logging
logger = logging.getLogger()
logger.level = logging.DEBUG
class TestCase(unittest.TestCase):
def testSimpleMsg(self):
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
try:
print("AA")
logging.getLogger().info("BB")
finally:
logger.removeHandler(stream_handler)
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.