title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
Data not rendering after OnCLick
<p>I am trying to display the data after hitting the &quot;Show the data&quot; button. I can see the data in the console but it is not being display on the page. Could anyone help me out and guide me to let me know what is my mistake. Been struggling for days now. Below is my code. I have edited critical information in the code for obvious security reasons. Any help would be appreciated. Thank you.</p> <p>axios.post is used to post the token and axios.get is used to fetch the data from the backend and display it.</p> <hr /> <pre><code> import {useState} from 'react'; import axios from 'axios'; import '../App.css' var raw = JSON.stringify({ username: &quot;xyz&quot;, password: &quot;xyz&quot; }); const type_no = '88'; const URL = `example url://abc.com/abc/${type_no}`; function getToken(){ const promise = axios.post(&quot;example url://abc.com/&quot;, raw) const id = promise.then((response) =&gt; response.data.IdToken) return id }; const App = () =&gt; { const [data, setData] = useState({data: []}); const [isLoading, setIsLoading] = useState(false); const [err, setErr] = useState(''); const handleClick = async () =&gt; { getToken().then(token =&gt; { setIsLoading(true); const config = { headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json', } }; const {data} = axios.get(URL, config) .then((response) =&gt; { console.log(response); setData(response.data); }) .catch((error) =&gt; { console.log(error); }); setIsLoading(false) }) }; console.log('Data: ', JSON.stringify(data,null,4)); return ( &lt;div className=&quot;form&quot;&gt; {err &amp;&amp; &lt;h2&gt;{err}&lt;/h2&gt;} &lt;button onClick={handleClick}&gt;Show the data&lt;/button&gt; {isLoading &amp;&amp; &lt;h2&gt;Loading data...&lt;/h2&gt;} {data.data?.map(data =&gt; { return ( &lt;div key={data.id}&gt; &lt;h2&gt;{data.email}&lt;/h2&gt; &lt;h2&gt;{data.first_name}&lt;/h2&gt; &lt;h2&gt;{data.last_name}&lt;/h2&gt; &lt;br /&gt; &lt;/div&gt; ); })} &lt;/div&gt; ); }; export default App; </code></pre>
3
1,189
How can I get all the XSD validation errors from an XML file in dotnet?
<p>Caveat: I'm fairly new to .NET so I'm unfamiliar with a lot of libraries available.</p> <p>I have developed a function app using java that I'm having to port over to C#. I am currently using the built in XSD validation library for .NET and my file <em>is</em> being successfully validated, however when testing the results against the java version there are significantly less validation errors being reported in the .NET version.</p> <p><strong>Root XSD file</strong></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;xs:schema xmlns=&quot;schema_namespace&quot; xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot; targetNamespace=&quot;schema_namespace&quot; elementFormDefault=&quot;qualified&quot; attributeFormDefault=&quot;unqualified&quot;&gt; &lt;xs:include schemaLocation=&quot;included_xsd_1.xsd&quot;/&gt; &lt;xs:include schemaLocation=&quot;included_xsd_2.xsd&quot;/&gt; &lt;xs:include schemaLocation=&quot;included_xsd_3.xsd&quot;/&gt; &lt;xs:include schemaLocation=&quot;included_xsd_4.xsd&quot;/&gt; &lt;xs:include schemaLocation=&quot;included_xsd_5.xsd&quot;/&gt; &lt;xs:element name=&quot;DEMDataSet&quot;&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;Root Tag&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name=&quot;dCustomElement&quot; type=&quot;dCustomElement&quot; id=&quot;dElementSection&quot; minOccurs=&quot;0&quot;&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;Contains information for custom elements.&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;/xs:element&gt; &lt;xs:element name=&quot;Report&quot; id=&quot;ReportGroup&quot; maxOccurs=&quot;unbounded&quot;&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;Container Tag to hold each instance of a record&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name=&quot;from_included_xsd_1&quot; type=&quot;type&quot; id=&quot;typeSection&quot;&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;Some Information&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;/xs:element&gt; &lt;xs:element name=&quot;from_included_2&quot; type=&quot;type&quot; id=&quot;typeSection&quot; minOccurs=&quot;0&quot;&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;Some Information&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;/xs:element&gt; ... &lt;/xs:sequence&gt; &lt;xs:attribute name=&quot;timeStamp&quot; type=&quot;DateTimeType&quot; use=&quot;required&quot;/&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre> <p>My issue appears to be occuring when there is a missing element in one of my included xsd files, when this happens all subsequent errors in that xsd file are not reported (e.g. if the initial element is missing, no other validation errors are reported for that xsd file and the validation moves on to the next included xsd).</p> <p>My code is pretty much lifted straight from the <a href="https://docs.microsoft.com/en-us/dotnet/standard/data/xml/xml-schema-xsd-validation-with-xmlschemaset" rel="nofollow noreferrer">Microsoft documentation</a>:</p> <pre><code> public XsdValidationResult ValidateXml(string filePath) { var schemas = GetSchemas(); var settings = new XmlReaderSettings(); settings.Schemas.Add(schemas); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += XsdValidationEventHandler; using var reader = XmlReader.Create(filePath, settings); var doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(reader); return GetValidationResult(); } private void XsdValidationEventHandler(object sender, ValidationEventArgs e) { if (e.Severity != XmlSeverityType.Error) return; var sb = new StringBuilder(); sb.Append(e.Message); sb.Append($&quot; Line Number: {e.Exception.LineNumber}&quot;); sb.Append($&quot; Position: {e.Exception.LinePosition}&quot;); _errors.Add(sb.ToString()); } </code></pre> <p>The validation error I get looks something like this (before moving on to the next schema):</p> <blockquote> <p>The element 'subSchema.elementGroup' in namespace 'namespace' has invalid child element 'subSchema.element02' in namespace 'namespace'. List of possible elements expected: 'subSchema.element03' in namespace 'namespace'.</p> </blockquote> <p>I did come across this possible explanation of what is happening in the Microsoft docs:</p> <blockquote> <p>When the new XmlReader has been closed, the original XmlReader will be positioned on the EndElement node of the sub-tree. Thus, if you called the ReadSubtree method on the start tag of the book element, after the sub-tree has been read and the new XmlReader has been closed, the original XmlReader is positioned on the end tag of the book element.</p> </blockquote> <p>but this behaviour is different from what I need :(</p> <p>Ultimately my question is, is there a way to continue parsing the XML file after an element has been discovered as missing (either using a different library or through the included .NET library) so as to capture all XSD validation errors?</p>
3
2,825
django field using pictures instead of text
<p>If I choose one of whose input value is radio in HTML and submit, the selected one is delivered to the models, and finally, I want to retrieve the selected image from HTML again. But I can't even get a clue. What should I do? And I also wonder how to connect and use these with forms.py and html. I want to know the exact answer because the image field is set as a temporary measure.</p> <p>models.py '''</p> <pre><code>class Guest(models.Model): author = models.CharField(null=True,max_length=20) content=models.TextField() created_at =models.DateTimeField(auto_now_add=True) sticker=models.ImageField(label=&quot;Decorate the picture next to it!&quot;,widget=models.RadioSelect(choices=STICKER_CHOICES)) def __str__(self): return f'{self.author},{self.content}' </code></pre> <p>'''</p> <p>main html</p> <pre><code>Sticker: &lt;div class=&quot;table&quot;&gt; &lt;input type = &quot;radio&quot; name = &quot;major&quot; style=&quot;margin-left:15px;&quot;&gt;&lt;img src=&quot;{% static 'diary/css/images/sticker/boat.png' %}&quot; style=&quot;height:80px;width:80px;&quot;&gt;&lt;/input&gt; &lt;input type = &quot;radio&quot; name = &quot;major&quot; style=&quot;margin-left:15px;&quot;&gt;&lt;img src=&quot;{% static 'diary/css/images/sticker/airplane.png' %}&quot; style=&quot;height:80px;width:80px;&quot;&gt;&lt;/input&gt; &lt;input type = &quot;radio&quot; name = &quot;major&quot; style=&quot;margin-left:15px;&quot;&gt;&lt;img src=&quot;{% static 'diary/css/images/sticker/bird.png' %}&quot; style=&quot;height:80px;width:80px;&quot;&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class=&quot;table&quot;&gt; &lt;input type = &quot;radio&quot; name = &quot;major&quot; style=&quot;margin-left:15px;&quot;&gt;&lt;img src=&quot;{% static 'diary/css/images/sticker/board.png' %}&quot; style=&quot;height:80px;width:80px;&quot;&gt;&lt;/input&gt; &lt;input type = &quot;radio&quot; name = &quot;major&quot; style=&quot;margin-left:15px;&quot;&gt;&lt;img src=&quot;{% static 'diary/css/images/sticker/fish.png' %}&quot; style=&quot;height:80px;width:80px;&quot;&gt;&lt;/input&gt; &lt;input type = &quot;radio&quot; name = &quot;major&quot; style=&quot;margin-left:15px;&quot;&gt;&lt;img src=&quot;{% static 'diary/css/images/sticker/starfish.png' %}&quot; style=&quot;height:80px;width:80px;&quot;&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class=&quot;table&quot;&gt; &lt;input type = &quot;radio&quot; name = &quot;major&quot; style=&quot;margin-left:15px;&quot;&gt;&lt;img src=&quot;{% static 'diary/css/images/sticker/turtle.png' %}&quot; style=&quot;height:80px;width:80px;&quot;&gt;&lt;/input&gt; &lt;input type = &quot;radio&quot; name = &quot;major&quot; style=&quot;margin-left:15px;&quot;&gt;&lt;img src=&quot;{% static 'diary/css/images/sticker/shell.png' %}&quot; style=&quot;height:80px;width:80px;&quot;&gt;&lt;/input&gt; &lt;input type = &quot;radio&quot; name = &quot;major&quot; style=&quot;margin-left:15px;&quot;&gt;&lt;img src=&quot;{% static 'diary/css/images/sticker/palm.png' %}&quot; style=&quot;height:80px;width:80px;&quot;&gt;&lt;/input&gt; &lt;/div&gt; </code></pre>
3
1,695
In R, create a new column based on the order of a 2nd column grouped by a 3rd column
<p>This is very similar to some other questions, but I wasn't quite satisfied with the other answers.</p> <p>I have data where one column is the outcome of a Latin Square study design, where a participant had three conditions that could have come in six possible orders. I do not have a variable that indicates the order that the participant actually received the study conditions, and so need to create one myself. Here is my current and desired output using a fake example from the first three participants:</p> <pre class="lang-r prettyprint-override"><code>library(dplyr) #&gt; #&gt; Attaching package: 'dplyr' #&gt; The following objects are masked from 'package:stats': #&gt; #&gt; filter, lag #&gt; The following objects are masked from 'package:base': #&gt; #&gt; intersect, setdiff, setequal, union (current &lt;- tibble( participant = c(1,1,1,2,2,2,3,3,3), block_code = c(&quot;timed&quot;, &quot;untimed&quot;, &quot;practice&quot;, &quot;untimed&quot;, &quot;practice&quot;, &quot;timed&quot;, &quot;timed&quot;, &quot;untimed&quot;, &quot;practice&quot;) )) #&gt; # A tibble: 9 × 2 #&gt; participant block_code #&gt; &lt;dbl&gt; &lt;chr&gt; #&gt; 1 1 timed #&gt; 2 1 untimed #&gt; 3 1 practice #&gt; 4 2 untimed #&gt; 5 2 practice #&gt; 6 2 timed #&gt; 7 3 timed #&gt; 8 3 untimed #&gt; 9 3 practice (desired &lt;- current %&gt;% mutate(order_code = c(rep(&quot;tup&quot;, 3), rep(&quot;upt&quot;, 3), rep(&quot;tup&quot;, 3)))) #&gt; # A tibble: 9 × 3 #&gt; participant block_code order_code #&gt; &lt;dbl&gt; &lt;chr&gt; &lt;chr&gt; #&gt; 1 1 timed tup #&gt; 2 1 untimed tup #&gt; 3 1 practice tup #&gt; 4 2 untimed upt #&gt; 5 2 practice upt #&gt; 6 2 timed upt #&gt; 7 3 timed tup #&gt; 8 3 untimed tup #&gt; 9 3 practice tup </code></pre> <p><sup>Created on 2022-02-28 by the <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex package</a> (v2.0.1)</sup></p> <p>Participants 1 and 3 had the same order, so they ended up with the same code.</p> <p><strong>How can I tell R to create a new column based on the order of the <code>block_code</code> variable within a participant?</strong></p>
3
1,189
Can't update user's info clicking on a submit
<p>Everytime an user register in my website, they have a "free account". In my website there're 4 types of accounts:</p> <p>Free - 2GB</p> <p>Basic - 5GB</p> <p>Ultra - 10GB</p> <p>Plus - 25GB</p> <p>Each one with an unique id. I have created this code. Depending of the submit you click, your user get one of those accounts (Basic Ultra or Plus).</p> <pre><code> public static function ComprobarTarifa($user){ $sql = "SELECT id_tipocuenta FROM canal WHERE id = '$user'"; $resultado = self::Conexion($sql); $verificacion = false; if(isset($resultado)) { $fila = $resultado-&gt;fetch(); if($fila !== false){ $verificacion=true; } } return $verificacion; } public static function AmpliarCuenta($user, $tarifa){ $sql = "UPDATE canal SET id_tipocuenta = '$tarifa' WHERE id = '$user'"; $resultado = self::Conexion($sql); return $resultado; } public static function AmpliarCuentaErrores(){ $error = ""; $tarifa = 0; if(isset($_POST["tarifaBasic"])){ $tarifa = 2; if(isset($_SESSION["usuario"])){ if(self::ComprobarTarifa($_SESSION["usuario"]) != $tarifa){ DataBase::AmpliarCuenta($_SESSION["usuario"], $tarifa); $error = "&lt;div id='error_alert'&gt;&lt;div class='error_container'&gt;&lt;i class='fa fa-times awesome error_close btn'&gt;&lt;/i&gt;&lt;div class='error_text'&gt;Ya estás usando esa tarifa...&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;"; } } else { $error = "&lt;div id='error_alert'&gt;&lt;div class='error_container'&gt;&lt;i class='fa fa-times awesome error_close btn'&gt;&lt;/i&gt;&lt;div class='error_text'&gt;Debes iniciar sesión primero...&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;"; } } if(isset($_POST["tarifaUltra"])){ $tarifa = 3; if(isset($_SESSION["usuario"])){ if(self::ComprobarTarifa($_SESSION["usuario"]) != $tarifa){ DataBase::AmpliarCuenta($_SESSION["usuario"], $tarifa); $error = "&lt;div id='error_alert'&gt;&lt;div class='error_container'&gt;&lt;i class='fa fa-times awesome error_close btn'&gt;&lt;/i&gt;&lt;div class='error_text'&gt;Ya estás usando esa tarifa...&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;"; } } else { $error = "&lt;div id='error_alert'&gt;&lt;div class='error_container'&gt;&lt;i class='fa fa-times awesome error_close btn'&gt;&lt;/i&gt;&lt;div class='error_text'&gt;Debes iniciar sesión primero...&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;"; } } if(isset($_POST["tarifaPlus"])){ $tarifa = 4; if(isset($_SESSION["usuario"])){ if(self::ComprobarTarifa($_SESSION["usuario"]) != $tarifa){ DataBase::AmpliarCuenta($_SESSION["usuario"], $tarifa); $error = "&lt;div id='error_alert'&gt;&lt;div class='error_container'&gt;&lt;i class='fa fa-times awesome error_close btn'&gt;&lt;/i&gt;&lt;div class='error_text'&gt;Ya estás usando esa tarifa...&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;"; } } else { $error = "&lt;div id='error_alert'&gt;&lt;div class='error_container'&gt;&lt;i class='fa fa-times awesome error_close btn'&gt;&lt;/i&gt;&lt;div class='error_text'&gt;Debes iniciar sesión primero...&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;"; } } return $error; } </code></pre> <p>The problem is that my database doesnt update... What could it be? Error divs dont appear...</p>
3
1,888
graphql cache DataIdFromObject not causing React re-render
<p>I have two mutations <code>onLike</code> and <code>onSubmit</code> defined in one react component. For <code>onLike</code> mutation, I can use cache with <code>DataIdFromObject</code> to update the data without refetching the data with either <code>this.props.data.refetch()</code> or <code>refetchQueries: []</code>. BUT not for <code>onSubmit</code> mutation. </p> <p>// --- React component</p> <pre><code>onSubmit(e) { e.preventDefault(); this.props .addLyricQuery({ variables: { content: this.state.content, songId: this.props.params.id, }, }); } onLike(id, likes) { this.props.likeLyricQuery({ variables: { id }, optimisticResponse: { __typename: "Mutation", likeLyric: { id, __typename: "LyricType", likes: likes + 1, }, }, }); } &lt;button onClick={() =&gt; this.onLike(lyric.id, lyric.likes)}&gt; &lt;button onClick={e =&gt; this.onSubmit(e)}&gt;Submit&lt;/button&gt; </code></pre> <p>// --- apollo connect</p> <pre><code>const enhancer = compose( graphql(fetchSongQuery, { options: props =&gt; ({ variables: { id: props.params.id, }, }), }), graphql(addLyricQuery, { name: "addLyricQuery" }), graphql(likeLyricQuery, { name: "likeLyricQuery" }) ); export default enhancer(SongDetail); </code></pre> <p>// --- addLyric Query</p> <pre><code>import gql from "graphql-tag"; export default gql` mutation AddLyricToSong($content: String, $songId: ID) { addLyricToSong(content: $content, songId: $songId) { id title lyrics { id content } } } `; </code></pre> <p>// --- like query</p> <pre><code>import gql from "graphql-tag"; export default gql` mutation LikeLyric($id: ID!) { likeLyric(id: $id) { id likes content } } `; </code></pre> <p>// --- apollo store</p> <pre><code>const client = new ApolloClient({ dataIdFromObject: o =&gt; o.id }); </code></pre> <p><strong>What do I expect to see?</strong></p> <p>I expect the behavior between <code>onSubmit</code> and <code>onLike</code> to be the same. So when I click on either button, it should only query once, without needing to refetch the data.</p> <p><strong>What do I see?</strong></p> <p><code>onLike</code> works as expected. When clicked, it only issues one mutation, and the react component is rendered immediately. </p> <p><code>onSubmit</code> leads me to a blank page, then once I refresh the page, the new data displays. I can make it work by using <code>refetch</code> or <code>refetchQueries: []</code> but that is besides the point.</p>
3
1,288
DropDownListFor is not binding with model property
<p>I do not know why dropdownlist is not working in this particular case: </p> <p>I know, that i have ProjectID > 0, but in dropdownlist i always see first item selected.</p> <p>Controller:</p> <pre><code>Helpers h = new Helpers(); [HttpGet] [ActionName("Timesheet")] public ActionResult TimeSheet(LoggedAssociate assoc, DateChooserModel model) { List&lt;TimeReport&gt; timeReports = db.TimeReports.Include("TimeEntries.Project").Where( tr =&gt; tr.AssociateID == assoc.ID &amp;&amp; tr.DateSubmitted &gt;= model.StartDate &amp;&amp; tr.DateSubmitted &lt;= model.FinishDate).ToList(); ViewBag.Projects = h.GetProjects(0); return View(timeReports); } </code></pre> <p>Helper: </p> <pre><code>public class Helpers { public MyRepository db = new MyRepository(); public IEnumerable&lt;SelectListItem&gt; GetProjects(short? selectedValue) { List&lt;SelectListItem&gt; _projects = new List&lt;SelectListItem&gt;(); _projects.Add(new SelectListItem() { Text = "Project...", Value = "0", Selected = selectedValue == 0 }); foreach (var project in db.GetProjects()) { _projects.Add(new SelectListItem() { Text = project.Name, Value = project.Id.ToString(), Selected = selectedValue &gt; 0 &amp;&amp; selectedValue.Equals(project.Id) }); } return _projects; } } </code></pre> <p>View:</p> <pre><code>@using Project.DataAccess.DataModels @model List&lt;TimeReport&gt; @{ ViewBag.Title = "TimeSheet"; Layout = "~/Views/_Layout.cshtml"; int index = 0; // i use this variables to manage collections with binder int index2 = 0; } @using (Html.BeginForm()) { foreach (TimeReport t in Model) { // foreach (TimeEntry te in t.TimeEntries) { // @Html.DropDownListFor(model =&gt; model[index].TimeEntries[index2].ProjectId, (IEnumerable&lt;SelectListItem&gt;)ViewBag.Projects) // index2++; } // index++; } &lt;input type="submit" value="Submit" /&gt; } </code></pre> <p>Also in firebug i see:</p> <pre><code>&lt;select name="[0].TimeEntries[0].ProjectId"&gt; &lt;option selected="selected" value="0"&gt;Project...&lt;/option&gt; &lt;option value="1"&gt;First Project&lt;/option&gt; &lt;option value="2"&gt;Second Project&lt;/option&gt; &lt;/select&gt; </code></pre>
3
1,073
Why is "user" time different for same executable on two different AMD machines?
<p>Have tried execute the below source code on two different AMD machines which has same configurations.</p> <p>The &quot;user&quot; times are different for both the machines</p> <p>Same Source code is compiled with gcc 9 on both machines. They have the same objdump on both the machines.</p> <p>Here is the <strong>source code</strong> :</p> <pre><code>#include &lt;time.h&gt; int main() { double time_spent = 0.0; clock_t begin = clock(); int a = 0; for(int j = 0; j &lt; 1000; j++) { for(int i = 0; i &lt; 20000000; i++) { if(i%1000000 == 0) a = i; } } clock_t end = clock(); time_spent += (double)(end - begin) / CLOCKS_PER_SEC; printf(&quot;The elapsed time is %f seconds\n&quot;, time_spent); return 0; } </code></pre> <p>Output on <strong>Machine 1:</strong> (Details on Machine type mentioned below) The elapsed time is 21.140000 seconds real <strong>21.14</strong> user 21.14 sys 0.00 mem: 520</p> <p>Output on <strong>Machine 2:</strong> (Details on Machine type mentioned below) The elapsed time is 24.580000 seconds real <strong>24.59</strong> user 24.58 sys 0.00 mem: 524</p> <p><strong>Machine 1 Details:</strong> Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 128 On-line CPU(s) list: 0-127 Thread(s) per core: 2 Core(s) per socket: 32 Socket(s): 2 NUMA node(s): 2 Vendor ID: AuthenticAMD CPU family: 23 Model: 49 Model name: AMD EPYC 7542 32-Core Processor Stepping: 0 CPU MHz: 2894.795 BogoMIPS: 5789.59 Virtualization: AMD-V L1d cache: 32K L1i cache: 32K L2 cache: 512K L3 cache: 16384K NUMA node0 CPU(s): 0-31,64-95 NUMA node1 CPU(s): 32-63,96-127</p> <p><strong>Machine 2 Details:</strong> Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 128 On-line CPU(s) list: 0-127 Thread(s) per core: 2 Core(s) per socket: 32 Socket(s): 2 NUMA node(s): 2 Vendor ID: AuthenticAMD CPU family: 23 Model: 49 Model name: AMD EPYC 7542 32-Core Processor Stepping: 0 CPU MHz: 2894.705 BogoMIPS: 5789.41 Virtualization: AMD-V L1d cache: 32K L1i cache: 32K L2 cache: 512K L3 cache: 16384K NUMA node0 CPU(s): 0-31,64-95 NUMA node1 CPU(s): 32-63,96-127</p> <p>Already tried below options: (1)used &quot;tasket&quot; to pin the application to a particular CPU (2)used &quot;nice&quot; &amp; &quot;renice&quot; to change the priority of process (3)tried executing same source code from /tmp directory to ensure there was no network lag issues. (4)there is no load on the machines. (5)Have also tried using -o2, -o3 optimizations. (6)tried executing with sudo, still i notice consistent time difference in the execution on source code on two different machines which have same configurations.</p> <p>Could someone let me know as to why same source code being executed on two different AMD machines having same configurations is providing different &quot;user&quot; time</p>
3
1,601
Google App Script User Scope Approval for new scope
<p>I've added the <code>script.external_request</code> scope to my GMail Add-on so that I can connect to and store information in a MySQL dB.</p> <p>The scope was submitted and approved by Google OAuth and Marketplace SDK.</p> <p>If I run the script in the editor from the HEAD deployment, I get the OAuth approval workflow and the script connects to the database.</p> <p>In the deployed version I keep getting the following error:</p> <p><code>You do not have permission to call Jdbc.getConnection. Required permissions: https://www.googleapis.com/auth/script.external_request</code></p> <p>It seems to me that the end users are not getting a trigger to accept the new scope from the UI of the addon.</p> <p>Is there a way to force the OAuth workflow re-authorization from the addon UI?</p> <p>Or is there something else going on here?</p> <p><strong>ADDED INFO</strong></p> <p>I used Aaron's suggestion on the QuickStart to add a logging check to see if the required permissions are present. At least this will point to if this might be a red-herring.</p> <pre><code> if (authInfo.getAuthorizationStatus() == ScriptApp.AuthorizationStatus.REQUIRED) { Logger.log(`${user} - Missing required scope authorizations`) }else{ Logger.log(`${user} - Required scope authorizations present`) } </code></pre> <p>Naturally in the 12hrs this has been present, no user has opened the app. So will have to report back later.</p> <p>Also adding my appscript.json manifest</p> <pre><code> &quot;timeZone&quot;: &quot;America/New_York&quot;, &quot;runtimeVersion&quot;: &quot;V8&quot;, &quot;addOns&quot;: { &quot;common&quot;: { &quot;name&quot;: &quot;GMailAddOn&quot;, &quot;logoUrl&quot;: &quot;https://lh3.googleusercontent.com/...&quot;, &quot;layoutProperties&quot;: { &quot;primaryColor&quot;: &quot;#2772ed&quot; }, &quot;useLocaleFromApp&quot;: true }, &quot;gmail&quot;: { &quot;homepageTrigger&quot;: { &quot;enabled&quot;: true, &quot;runFunction&quot;: &quot;initApp&quot; } } }, &quot;exceptionLogging&quot;: &quot;STACKDRIVER&quot;, &quot;oauthScopes&quot;: [ &quot;https://www.googleapis.com/auth/gmail.addons.execute&quot;, &quot;https://www.googleapis.com/auth/userinfo.email&quot;, &quot;https://www.googleapis.com/auth/userinfo.profile&quot;, &quot;https://www.googleapis.com/auth/script.send_mail&quot;, &quot;https://www.googleapis.com/auth/script.locale&quot;, &quot;https://www.googleapis.com/auth/script.scriptapp&quot;, &quot;https://www.googleapis.com/auth/gmail.modify&quot;, &quot;https://www.googleapis.com/auth/script.external_request&quot; ], &quot;urlFetchWhitelist&quot;: [ &quot;https://google.com/&quot; ] } </code></pre>
3
1,114
Elixir Wallaby crashes on mix test
<p>I am trying to incorporate Wallaby into my phoenix app. I have followed the setup guide closely and made sure that phantomjs is properly installed, however on mix test I get the following error:</p> <pre><code>** (MatchError) no match of right hand side value: </code></pre> <p>My operating system is Windows10. Elixir version: 1.10.1 Phoenix version: 1.4.15 Wallaby version: 0.23.0 Phantomjs version: 2.1.1 Here is the full output:</p> <pre><code>mix test 06:21:54.255 [info] Already up 06:21:55.380 [error] Task #PID&lt;0.486.0&gt; started from #PID&lt;0.488.0&gt; terminating ** (stop) :eacces erlang.erl:2213: :erlang.open_port({:spawn_executable, 'C:\\Users\\SARELV~1\\AppData\\Local\\Temp/kz9cgp/wrapper'}, [:binary, :stream, :use_stdio, :exit_status, :stderr_to_stdout, {:args, ["phantomjs", "--webdriver=55182", "--local-storage-path=C:\\Users\\SARELV~1\\AppData\\Local\\Temp/kz9cgp/local_storage"]}]) (wallaby 0.23.0) lib/wallaby/phantom/server/start_task.ex:85: Wallaby.Phantom.Server.StartTask.start_phantom/1 (wallaby 0.23.0) lib/wallaby/phantom/server/start_task.ex:28: Wallaby.Phantom.Server.StartTask.run/2 (elixir 1.10.1) lib/task/supervised.ex:90: Task.Supervised.invoke_mfa/2 (elixir 1.10.1) lib/task/supervised.ex:35: Task.Supervised.reply/5 (stdlib 3.8) proc_lib.erl:249: :proc_lib.init_p_do_apply/3 Function: &amp;Wallaby.Phantom.Server.StartTask.run/2 Args: [#PID&lt;0.486.0&gt;, %Wallaby.Phantom.Server.ServerState{phantom_args: [], phantom_os_pid: nil, phantom_path: "phantomjs", port_number: 55182, workspace_path: "C:\\Users\\SARELV~1\\AppData\\Local\\Temp/kz9cgp", wrapper_script_os_pid: nil, wrapper_script_port: nil}] ** (MatchError) no match of right hand side value: {:error, {:wallaby, {{:shutdown, {:failed_to_start_child, Wallaby.Phantom, {:shutdown, {:failed_to_start_child, Wallaby.ServerPool, {{:badmatch, {:error, {:eacces, [{:erlang, :open_port, [{:spawn_executable, 'C:\\Users\\SARELV~1\\AppData\\Local\\Temp/kz9cgp/wrapper'}, [:binary, :stream, :use_stdio, :exit_status, :stderr_to_stdout, {:args, ["phantomjs", "--webdriver=55182", "--local-storage-path=C:\\Users\\SARELV~1\\AppData\\Local\\Temp/kz9cgp/local_storage"]}]], [file: 'erlang.erl', line: 2213]}, {Wallaby.Phantom.Server.StartTask, :start_phantom, 1, [file: 'lib/wallaby/phantom/server/start_task.ex', line: 85]}, {Wallaby.Phantom.Server.StartTask, :run, 2, [file: 'lib/wallaby/phantom/server/start_task.ex', line: 28]}, {Task.Supervised, :invoke_mfa, 2, [file: 'lib/task/supervised.ex', line: 90]}, {Task.Supervised, :reply, 5, [file: 'lib/task/supervised.ex', line: 35]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 249]}]}}}, [{:poolboy, :new_worker, 1, [file: 'c:/Coding/Projects/BoomhuisOnline/boomhuis/deps/poolboy/src/poolboy.erl', line: 283]}, {:poolboy, :prepopulate, 3, [file: 'c:/Coding/Projects/BoomhuisOnline/boomhuis/deps/poolboy/src/poolboy.erl', line: 304]}, {:poolboy, :init, 3, [file: 'c:/Coding/Projects/BoomhuisOnline/boomhuis/deps/poolboy/src/poolboy.erl', line: 153]}, {:gen_server, :init_it, 2, [file: 'gen_server.erl', line: 374]}, {:gen_server, :init_it, 6, [file: 'gen_server.erl', line: 342]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 249]}]}}}}}, {Wallaby, :start, [:normal, []]}}}} test/test_helper.exs:5: (file) (elixir 1.10.1) lib/code.ex:917: Code.require_file/2 (elixir 1.10.1) lib/enum.ex:783: Enum."-each/2-lists^foreach/1-0-"/2 (elixir 1.10.1) lib/enum.ex:783: Enum.each/2 06:21:55.392 [error] GenServer #PID&lt;0.485.0&gt; terminating ** (MatchError) no match of right hand side value: {:error, {:eacces, [{:erlang, :open_port, [{:spawn_executable, 'C:\\Users\\SARELV~1\\AppData\\Local\\Temp/kz9cgp/wrapper'}, [:binary, :stream, :use_stdio, :exit_status, :stderr_to_stdout, {:args, ["phantomjs", "--webdriver=55182", "--local-storage-path=C:\\Users\\SARELV~1\\AppData\\Local\\Temp/kz9cgp/local_storage"]}]], [file: 'erlang.erl', line: 2213]}, {Wallaby.Phantom.Server.StartTask, :start_phantom, 1, [file: 'lib/wallaby/phantom/server/start_task.ex', line: 85]}, {Wallaby.Phantom.Server.StartTask, :run, 2, [file: 'lib/wallaby/phantom/server/start_task.ex', line: 28]}, {Task.Supervised, :invoke_mfa, 2, [file: 'lib/task/supervised.ex', line: 90]}, {Task.Supervised, :reply, 5, [file: 'lib/task/supervised.ex', line: 35]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 249]}]}} (poolboy 1.5.2) c:/Coding/Projects/BoomhuisOnline/boomhuis/deps/poolboy/src/poolboy.erl:283: :poolboy.new_worker/1 (poolboy 1.5.2) c:/Coding/Projects/BoomhuisOnline/boomhuis/deps/poolboy/src/poolboy.erl:304: :poolboy.prepopulate/3 (poolboy 1.5.2) c:/Coding/Projects/BoomhuisOnline/boomhuis/deps/poolboy/src/poolboy.erl:153: :poolboy.init/3 (stdlib 3.8) gen_server.erl:374: :gen_server.init_it/2 (stdlib 3.8) gen_server.erl:342: :gen_server.init_it/6 (stdlib 3.8) proc_lib.erl:249: :proc_lib.init_p_do_apply/3 Last message: {:EXIT, #PID&lt;0.484.0&gt;, {{:badmatch, {:error, {:eacces, [{:erlang, :open_port, [{:spawn_executable, 'C:\\Users\\SARELV~1\\AppData\\Local\\Temp/kz9cgp/wrapper'}, [:binary, :stream, :use_stdio, :exit_status, :stderr_to_stdout, {:args, ["phantomjs", "--webdriver=55182", "--local-storage-path=C:\\Users\\SARELV~1\\AppData\\Local\\Temp/kz9cgp/local_storage"]}]], [file: 'erlang.erl', line: 2213]}, {Wallaby.Phantom.Server.StartTask, :start_phantom, 1, [file: 'lib/wallaby/phantom/server/start_task.ex', line: 85]}, {Wallaby.Phantom.Server.StartTask, :run, 2, [file: 'lib/wallaby/phantom/server/start_task.ex', line: 28]}, {Task.Supervised, :invoke_mfa, 2, [file: 'lib/task/supervised.ex', line: 90]}, {Task.Supervised, :reply, 5, [file: 'lib/task/supervised.ex', line: 35]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 249]}]}}}, [{:poolboy, :new_worker, 1, [file: 'c:/Coding/Projects/BoomhuisOnline/boomhuis/deps/poolboy/src/poolboy.erl', line: 283]}, {:poolboy, :prepopulate, 3, [file: 'c:/Coding/Projects/BoomhuisOnline/boomhuis/deps/poolboy/src/poolboy.erl', line: 304]}, {:poolboy, :init, 3, [file: 'c:/Coding/Projects/BoomhuisOnline/boomhuis/deps/poolboy/src/poolboy.erl', line: 153]}, {:gen_server, :init_it, 2, [file: 'gen_server.erl', line: 374]}, {:gen_server, :init_it, 6, [file: 'gen_server.erl', line: 342]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 249]}]}} </code></pre> <p>Any help/advice will be greatly appreciated!</p>
3
2,740
Image Isn't upating when going back to main activity
<p>Ok, I've got two activities, in the main activity there is an image button that takes you to a profile page activity where you can click on another image button and access your photo gallery to set a profile picture which is saved into Firebase storage and as a url in the database. This all works, the problem is that after you do all this and go back to the main activity (I'm overriding the back button and starting a new main activity) the image button shows the previous profile image despite Log.d checks reporting that I am accessing the updated url. Even stranger, if I go into the profile activity again it will display the update profile pic and when I go back to the main activity again the new image will now be displayed correctly. </p> <p>MainActivity</p> <pre><code>class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = DataBindingUtil.setContentView&lt;ActivityMainBinding&gt;(this, R.layout.activity_main) binding.activity = this setSupportActionBar(toolbar) val emailer=intent.getStringExtra("passemail") val toggle = ActionBarDrawerToggle( this, drawer_layout, toolbar, R.string.main_drawer_open, R.string.main_drawer_close) drawer_layout.addDrawerListener(toggle) toggle.syncState() val profile = findViewById&lt;de.hdodenhof.circleimageview.CircleImageView&gt;(R.id.profilebutton) val ref = FirebaseDatabase.getInstance().getReference("/users/$emailer") val valueEventListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val user = dataSnapshot.getValue(User::class.java) Log.d("msg0 main", "image url: " + user!!.profile_pic); if(user!!.profile_pic.length &gt; 0){ Picasso.get().load(user!!.profile_pic).into(profile) } } override fun onCancelled(databaseError: DatabaseError) { Log.d("msg0", databaseError.message) //Don't ignore errors! } } ref.addListenerForSingleValueEvent(valueEventListener) profile.setOnClickListener { val intent = Intent(this, ProfilePage::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK) intent.putExtra("passemail",emailer) startActivity(intent) } } } </code></pre> <p>ProfileActivity</p> <pre><code>class ProfilePage : AppCompatActivity() { private lateinit var auth: FirebaseAuth private lateinit var profilepic: de.hdodenhof.circleimageview.CircleImageView private lateinit var profileURi: Uri private lateinit var emailz: String private fun saveUserToDatabase(profilepicURL: String, emailer:String){ val uid = FirebaseAuth.getInstance().uid ?: "" val ref = FirebaseDatabase.getInstance().getReference("/users/$emailer/profile_pic") ref.setValue(profilepicURL) .addOnSuccessListener { Log.d("msg0", "saved pic to firebase database, $ref") } .addOnFailureListener{ Log.d("msg0", "failed to save pic into database, ${it.message}") } } private fun chooseImage() { val intent = Intent(Intent.ACTION_PICK) intent.type = MediaStore.Images.Media.CONTENT_TYPE startActivityForResult(intent, 10) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val emailer=intent.getStringExtra("passemail") if (requestCode == 10 &amp;&amp; resultCode == Activity.RESULT_OK &amp;&amp; data != null) { profileURi = data.data val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, profileURi) Log.d("msg0 profileuri", profileURi.toString()); profilepic.setImageBitmap(bitmap) uploadImagetoFirebase(emailer); } } private fun uploadImagetoFirebase(emailer:String){ if(profileURi == null) return val filename = UUID.randomUUID().toString() val ref = FirebaseStorage.getInstance().getReference("/images/$filename") ref.putFile(profileURi!!) .addOnSuccessListener { Toast.makeText(this, "Successfully uploaded image ${it.metadata?.path}", Toast.LENGTH_SHORT).show() Log.d("msg0 upload", "image url: " + it.metadata?.path); ref.downloadUrl.addOnSuccessListener { Log.d("msg1 upload", "image url: " + it); Toast.makeText(this, "File Location $it", Toast.LENGTH_SHORT).show() saveUserToDatabase(it.toString(),emailer) } } } override fun onBackPressed() { val intent = Intent(this, MainActivity :: class.java) Log.d("checker2", emailz) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK) intent.putExtra("passemail",emailz) startActivity(intent) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.profile_page) val emailer=intent.getStringExtra("passemail") // Initialize Firebase Auth auth = FirebaseAuth.getInstance() emailz = emailer //Create Image View and set it to call upload when clicked profilepic = findViewById&lt;de.hdodenhof.circleimageview.CircleImageView&gt;(R.id.img_profile) val uid = FirebaseAuth.getInstance().uid ?: "" val ref = FirebaseDatabase.getInstance().getReference("/users/$emailer") val valueEventListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val user = dataSnapshot.getValue(User::class.java) Log.d("msg0 profile", "image url: " + user!!.profile_pic); if(user!!.profile_pic.length &gt; 0){ Picasso.get().load(user!!.profile_pic).into(profilepic) } } override fun onCancelled(databaseError: DatabaseError) { Log.d("msg0", databaseError.message) //Don't ignore errors! } } ref.addListenerForSingleValueEvent(valueEventListener) profilepic.setOnClickListener(View.OnClickListener { chooseImage() }) } } </code></pre> <p>I'm using a library for the image buttons, but this problem existed before I added it. </p>
3
2,800
Semaphore time out while looping thu serialport.open()
<p>I have a piece of code which scans for all available comports. And than it will try to find the correct device by opening the comport and send a message, if the message is correct I have find the correct device. Now this worked pretty well but now I discovered a bug. I think I know what is happening but I'm not sure if this is the reason and also how to solve it.</p> <p>I get the error message: &quot;The semaphore timeout period has expired.&quot; Searching on Google it told me this message appears when there are problems with receive data back (files or so). I think when reaching the particular where the error appears it is one that is already open and connected to a device.</p> <p>I wrote my code like this:</p> <pre><code> // Detect VM25 and show connection is established string device; string CheckConnection; string[] ports = SerialPort.GetPortNames(); int count = 0 ; //Test which enabled port is the VM25. foreach (string port in ports) { serialPort1.PortName = port; serialPort1.ReadTimeout = 2000; serialPort1.Open(); // Display each port name to the console. Console.WriteLine(port); if (serialPort1.IsOpen) { device = &quot;&quot;; serialPort1.WriteLine(&quot;#S&quot; + Environment.NewLine); serialPort1.WriteTimeout = 1000; try { answer = serialPort1.ReadTo(&quot;/a&quot;); serialPort1.ReadTimeout = 3500; serialPort1.Close(); if (answer != &quot;&quot;) { device = answer.Substring(0, 4); //Find the correct response from the Com port where the VM25 is connected if (device == &quot;VM25&quot;) { statusLblDevice.ForeColor = Color.LawnGreen; statusLblDevice.Text = port + &quot; - &quot; + device + &quot; - Connected&quot;; VM25Port = port; serialPort1.PortName = VM25Port; serialPort1.Open(); serialPort1.WriteLine(&quot;#H&quot; + Environment.NewLine); serialPort1.WriteTimeout = 2000; //Timeout for writing the comment string input = serialPort1.ReadTo(&quot;/a&quot;); serialPort1.ReadTimeout = 5500; //Timeout for reading the data string totalMeasurements = &quot;Measurements: &quot; + input.Substring(9, 3); //Take the amount of measurements into a string MeasTotal = int.Parse(input.Substring(9, 3)); string totalFFT = &quot;FFTs: &quot; + input.Substring(18, 5); //Take the amount of FFTs into a string statusLblMeas.Text = totalMeasurements; statusLblFFT.Text = totalFFT; FFTtotal = int.Parse(input.Substring(18, 5)); serialPort1.Close(); } } } catch (TimeoutException) { serialPort1.Close(); } } } </code></pre> <p>I think I need to adjust my code such that if the comport is already open it skips the and goes to the next item in the <code>foreach</code> loop? Or are the any better ways to solve this?</p> <p>Thanks in advance</p>
3
2,031
Using an if statement to update OR insert into
<p>I have the following code which up dates my database table perfectly. However, I now wish it to either, update an existing row if the value of $status is 'open', or create a new row if the value of $status is 'completed'.</p> <p>This is my code so far;</p> <pre><code> &lt;?php if (isset($_POST['submit_update_activity'])); { require 'dbh.inc.php'; $activity_id = $_POST['hidden_activity_id']; $idFromKnowledgeBase = $_POST['hidden_idFromKnowledgeBase']; $hiddenUserID = $_POST['hidden_userId']; $title = $_POST['title']; $description = $_POST['description']; $assigned_to = $_POST['assigned_to']; $category = $_POST['category']; $cost = $_POST['cost']; $next_due = $_POST['next_due']; $due_every = $_POST['due_every']; $frequency = $_POST['frequency']; $supplier = $_POST['supplier']; $status = $_POST['status']; $comments = $_POST['comments']; $emptyAssignedTo = $_POST['empty_assigned_to']; $emptyStatus = $_POST['empty_status']; $emptyCategory = $_POST['empty_category']; $dateCompleted = $_POST['date_completed']; $emptyFrequency = $_POST['empty_frequency']; $emptyNextDue = $_POST['empty_next_due']; $next_due = date('Y-m-d', strtotime($dateCompleted. " + {$due_every} $frequency")); if (empty($frequency)) { $frequency = $emptyFrequency; } if (empty($status)) { $status = $emptyStatus; } if (empty($assigned_to)) { $assigned_to = $emptyAssignedTo; } if (empty($category)) { $category = $emptyCategory; } //This line isn't working if ($status == 'open') { $next_due = $emptyNextDue; } else { $next_due = date('Y-m-d', strtotime($dateCompleted. " + {$due_every} $frequency")); } $stmt = $conn-&gt;prepare("UPDATE activities SET idFromKnowledgeBase = ?, userId = ?, title = ?, description = ?, assigned_to = ?, category = ?, cost = ?, last_completed = ?,next_due = ?, frequency = ?, supplier = ?, status = ?, comments = ? WHERE id = ?"); $stmt-&gt;bind_param("ssssssssssssss", $idFromKnowledgeBase, $hiddenUserID, $title, $description, $assigned_to, $category, $cost, $dateCompleted, $next_due, $frequency, $supplier, $status, $comments, $activity_id); $stmt-&gt;execute(); if($stmt-&gt;affected_rows &gt;0) { header('Location: ../all_activities.php?updated'); } } ?&gt; </code></pre> <p>I've tried =, == and === for comparing $status. If I take it back a notch and echo either 'open' or 'completed' depending on the value of $status, it works fine, echoing the correct answer each time.</p> <p>Advice is appreciated.</p>
3
1,358
How Can I Insert Data Into Database From A Form Properly?
<p>so I've been working on a form using an MVC approach that will insert data into a database using PDO. I have the addWine form, addWine controller, data access model and wine class model. On submission of the form nothing happens and the database isn't populated. Can someone pinpoint what I have done wrong here? </p> <p>Wine Form</p> <pre><code>&lt;form action= "" method="POST"&gt; &lt;table&gt; &lt;b&gt;Fill the form to add new wine&lt;/b&gt;&lt;p&gt;&lt;p&gt; &lt;tr&gt; &lt;td&gt; Wine ID: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name= "wineID"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Country ID: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineCountryID"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Size ID: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineSizeID"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Rating ID: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineRatingID"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Colour ID: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineColourID"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Package ID: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="winePackageID"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Category ID: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineCategoryID"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Code: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineCode"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Price: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineCountryID"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Description: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineDescription"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Rating: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineRating"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wine Image: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="wineImage"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;p&gt;&lt;br&gt; &lt;center&gt;&lt;input type="submit" name= "addWineButton" value="Add Wine"&gt;&lt;/center&gt;&lt;p&gt;&lt;p&gt;&lt;p&gt;&lt;p&gt; &lt;/form&gt; </code></pre> <p>Add Wine Controller</p> <pre><code>&lt;?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); session_start(); require_once('../Model/dataAccess.php'); require_once('../Model/wine.class.php'); $status = false; if(isset($_POST["addWineButton"])){ $wineID = $_POST["wineID"]; $wineCountryID = $_POST["wineCountryID"]; $wineSizeID = $_POST["wineSizeID"]; $wineRatingID = $_POST["wineRatingID"]; $wineColourID = $_POST["wineColourID"]; $packageID = $_POST["packageID"]; $wineCategoryID = $_POST["wineCategoryID"]; $wineCode = $_POST["wineCode"]; $price = $_POST["price"]; $description = $_POST["description"]; $wineRating = $_POST["wineRating"]; $wineIMG = $_POST["wineIMG"]; $wineAdd = new Wine(); $wineAdd-&gt;wineID = htmlentities($wineID); $wineAdd-&gt;wineCountryID = htmlentities($wineCountryID); $wineAdd-&gt;wineSizeID = htmlentities($wineSizeID); $wineAdd-&gt;wineRatingID = htmlentities($wineRatingID); $wineAdd-&gt;wineColourID = htmlentities($wineColourID); $wineAdd-&gt;packageID = htmlentities($packageID); $wineAdd-&gt;wineCategoryID = htmlentities($wineCategoryID); $wineAdd-&gt;wineCode = htmlentities($wineCode); $wineAdd-&gt;price = htmlentities($price); $wineAdd-&gt;description = htmlentities($description); $wineAdd-&gt;wineRating = htmlentities($wineRating); $wineAdd-&gt;wineIMG = htmlentities($wineIMG); addWine($wineAdd); $status = "$description has been updated."; } ?&gt; </code></pre> <p>Wine Class Model</p> <pre><code>&lt;?php class Wine { var $wineID; var $wineSizeID; var $wineCountryID; var $wineRatingID; var $wineColourID; var $wineCode; var $price; var $description; var $wineRating; var $wineIMG; var $packageID; var $wineCategoryID; function __get($name){ return $this-&gt;$name; } function __set($name,$value){ $this-&gt;$name=$value; } } ?&gt; </code></pre> <p>Data Access Model</p> <pre><code>function addWine($wineAdd){ global $pdo; $statement = $pdo-&gt;prepare('INSERT INTO Wine (wineID, wineCountryID, wineSizeID, wineRatingID, wineColourID, packageID, wineCategoryID, wineCode, price, description, wineRating, wineIMG) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)'); $statement-&gt;execute([$wineAdd-&gt;wineID, $wineAdd-&gt;wineCountryID, $wineAdd-&gt;wineSizeID, $wineAdd-&gt;wineRatingID, $wineAdd-&gt;wineColourID, $wineAdd-&gt;packageID, $wineAdd-&gt;wineCategoryID, $wineAdd-&gt;wineCode, $wineAdd-&gt;price, $wineAdd-&gt;description, $wineAdd-&gt;wineRating, $wineAdd-&gt;wineIMG]); $statement-&gt;fetch(); } </code></pre>
3
2,480
DependencyProperty not update
<p>I have a user control with IsChecked Property</p> <pre><code>public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register( "IsChecked", typeof(bool), typeof(LabeledCheckbox),new FrameworkPropertyMetadata { DefaultValue = false, BindsTwoWayByDefault = true, }); public bool IsChecked { get { return (bool)this.GetValue(IsCheckedProperty); } set { this.SetValue(IsCheckedProperty, value); } } </code></pre> <p>I'm bounding the IsChecked Property to a another property called active and i create a checkbox that the IsChecked Property also bound to the active property</p> <pre><code>&lt;controls:LabeledCheckbox x:Name="ccc" Tag="Active" CheckedColor=" #33cc00" UncheckedColor="#cc2900" CheckedContent="hello" UncheckedContent="world" IsChecked="{Binding Active, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" FontSize="25" Margin="5" Width="100"/&gt; &lt;CheckBox IsChecked="{Binding Active, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/&gt; </code></pre> <p>The checkbox is update correctly but the controls:LabeledCheckbox not update the other DP in controls:LabeledCheckbox are working great.</p> <p>why the IsChecked property not updating? tried to use RelativeSource={RelativeSource AncestorType={x:Type Window}} on the controls:LabeledCheckbox like this:</p> <pre><code>&lt;controls:LabeledCheckbox x:Name="ccc" Tag="Active" CheckedColor=" #33cc00" UncheckedColor="#cc2900" CheckedContent="שלום" UncheckedContent="עולם" IsChecked="{Binding Active, RelativeSource={RelativeSource AncestorType={x:Type Window}}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" FontSize="25" Margin="5" Width="100"/&gt; </code></pre> <p>tried one way to source</p> <p>the set of IsChecked never triggered unless i set True ao false directly and not binding.</p> <p><strong>UPDATE</strong> Adding the UserControl's full code:</p> <pre><code>public partial class LabeledCheckbox : UserControl { public LabeledCheckbox() { InitializeComponent(); } public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register( "IsChecked", typeof(bool), typeof(LabeledCheckbox),new FrameworkPropertyMetadata { DefaultValue = false, BindsTwoWayByDefault = true, PropertyChangedCallback = CheckChanged }); private static void CheckChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MessageBox.Show("Change"); } public bool IsChecked { get { return (bool)this.GetValue(IsCheckedProperty); } set { this.SetValue(IsCheckedProperty, value); } } public static readonly DependencyProperty CheckedColorProperty = DependencyProperty.Register( "CheckedColor", typeof(Color), typeof(LabeledCheckbox), new PropertyMetadata(Colors.White)); public Color CheckedColor { get { return (Color)this.GetValue(CheckedColorProperty); } set { this.SetValue(CheckedColorProperty, value); } } public static readonly DependencyProperty CheckedContentProperty = DependencyProperty.Register( "CheckedContent", typeof(string), typeof(LabeledCheckbox), null); public string CheckedContent { get { return (string)this.GetValue(CheckedContentProperty); } set { this.SetValue(CheckedContentProperty, value); } } public static readonly DependencyProperty UncheckedColorProperty = DependencyProperty.Register( "UncheckedColor", typeof(Color), typeof(LabeledCheckbox), new PropertyMetadata(Colors.White)); public Color UncheckedColor { get { return (Color)this.GetValue(UncheckedColorProperty); } set { this.SetValue(UncheckedColorProperty, value); } } public static readonly DependencyProperty UncheckedContentProperty = DependencyProperty.Register( "UncheckedContent", typeof(string), typeof(LabeledCheckbox), null); public string UncheckedContent { get { return (string)this.GetValue(UncheckedContentProperty); } set { this.SetValue(UncheckedContentProperty, value); } } public static readonly RoutedEvent CheckedChangeEvent = EventManager.RegisterRoutedEvent("CheckedChange", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(LabeledCheckbox)); public event RoutedEventHandler CheckedChange { add { AddHandler(CheckedChangeEvent, value); } remove { RemoveHandler(CheckedChangeEvent, value); } } private void ToggleCheckbox(object sender, MouseButtonEventArgs e) { IsChecked = !IsChecked; AnimateCheckbox(); RaiseCheckedChangeEvent(); } private void AnimateCheckbox() { DoubleAnimation cAnim = null; DoubleAnimation ucAnim = null; if (IsChecked) { cAnim = AnimationsHandler.AnimateElementWidth(0, this.Width, TimeSpan.FromMilliseconds(400)); ucAnim = AnimationsHandler.AnimateElementWidth(this.Width, 0, TimeSpan.FromMilliseconds(400)); } else { cAnim = AnimationsHandler.AnimateElementWidth(this.Width, 0, TimeSpan.FromMilliseconds(400)); ucAnim = AnimationsHandler.AnimateElementWidth(0, this.Width, TimeSpan.FromMilliseconds(400)); } var sb = new Storyboard(); AnimationsHandler.AddToStoryboard(sb, cAnim, check, new PropertyPath(FrameworkElement.WidthProperty)); AnimationsHandler.AddToStoryboard(sb, ucAnim, uncheck, new PropertyPath(FrameworkElement.WidthProperty)); sb.Begin(); } void RaiseCheckedChangeEvent() { RoutedEventArgs newEventArgs = new RoutedEventArgs(LabeledCheckbox.CheckedChangeEvent); RaiseEvent(newEventArgs); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { ToggleCheckbox(null, null); } } </code></pre>
3
2,106
Android Eclipse: database doesn't seem to work when APK is installed to an external device
<p>I am a beginner mobile developer and I am developing a directory app using eclipse for android. I am not really good in coding and programming so I really need help. </p> <p>My app works good in my laptop, in eclipse emulator but when I run it in my phone, or manually copy the apk and install it in my phone, the app works from the login activity, but when I start searching in the main activity, nothing happens, <strong>no error warning</strong>, <strong>no logcat error</strong> or anything else.</p> <p>I'm suspecting that the database isn't installed together with the apk, I have no idea what's happening and what to do, please help. Thanks in advance.</p> <pre><code>package samples.planholderdirectory; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "planholder"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { /* * Create the planholder table and populate it with sample data. */ String sql = "CREATE TABLE IF NOT EXISTS planholder (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "firstName TEXT, " + "lastName TEXT, " + "contractNo TEXT, " + "plan TEXT, " + "description TEXT, " + "effectivity TEXT, " + "dueDate TEXT, " + "quotaComm TEXT, " + "quotaNComm TEXT, " + "CBI TEXT, " + "instNo TEXT, " + "aging TEXT, " + "balance TEXT, " + "taxable TEXT, " + "insured TEXT, " + "orNo TEXT, " + "orDate TEXT, " + "collDue TEXT, " + "collAdvance TEXT, " + "managerId INTEGER)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS employees"); onCreate(db); } } </code></pre> <p>This is my DatabaseHelper</p> <pre><code>package samples.planholderdirectory; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class PlanholderList extends ListActivity { protected EditText searchText; protected SQLiteDatabase db; protected Cursor cursor; protected ListAdapter adapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); db = (new DatabaseHelper(this)).getWritableDatabase(); searchText = (EditText) findViewById (R.id.searchText); } public void search(View view) { // || is the concatenation operation in SQLite and for lpa number cursor = db.rawQuery("SELECT _id, firstName, lastName, contractNo FROM planholder WHERE contractNo || ' ' || firstName || ' ' || lastName LIKE ?", new String[]{"%" + searchText.getText().toString() + "%"}); adapter = new SimpleCursorAdapter( this, R.layout.planholder_list_item, cursor, new String[] {"contractNo", "firstName", "lastName"}, new int[] {R.id.contractNo, R.id.firstName, R.id.lastName}); setListAdapter(adapter); } public void onListItemClick(ListView parent, View view, int position, long id) { Intent intent = new Intent(this, PlanholderDetails.class); Cursor cursor = (Cursor) adapter.getItem(position); intent.putExtra("PLANHOLDER_ID", cursor.getInt(cursor.getColumnIndex("_id"))); startActivity(intent); } } </code></pre> <p>this is my PlanholderList</p> <pre><code>package samples.planholderdirectory; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.widget.TextView; public class PlanholderDetails extends Activity { protected TextView planholderName; protected TextView contractNo; protected TextView plan; protected TextView description; protected TextView effectivity; protected TextView dueDate; protected TextView quotaComm; protected TextView quotaNComm; protected TextView CBI; protected TextView instNo; protected TextView aging; protected TextView balance; protected TextView taxable; protected TextView insured; protected TextView orNo; protected TextView orDate; protected TextView collDue; protected TextView collAdvance; protected int planholderId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.planholder_details); planholderId = getIntent().getIntExtra("PLANHOLDER_ID", 0); SQLiteDatabase db = (new DatabaseHelper(this)).getWritableDatabase(); Cursor cursor = db.rawQuery("SELECT emp._id, emp.firstName, emp.lastName, emp.contractNo, emp.plan, emp.description, emp.effectivity, emp.dueDate, emp.quotaComm, emp.quotaNComm, emp.CBI, emp.instNo, emp.aging, emp.balance, emp.taxable, emp.insured, emp.orNo, emp.orDate, emp.collDue, emp.collAdvance, emp.managerId, mgr.firstName managerFirstName, mgr.lastName managerLastName FROM planholder emp LEFT OUTER JOIN planholder mgr ON emp.managerId = mgr._id WHERE emp._id = ?", new String[]{""+planholderId}); if (cursor.getCount() == 1) { cursor.moveToFirst(); planholderName = (TextView) findViewById(R.id.planholderName); planholderName.setText(("Planholder: ")+ cursor.getString(cursor.getColumnIndex("firstName")) + " " + cursor.getString(cursor.getColumnIndex("lastName"))); contractNo = (TextView) findViewById(R.id.contractNo); contractNo.setText(("LPA No.: ")+ cursor.getString(cursor.getColumnIndex("contractNo"))); plan = (TextView) findViewById(R.id.plan); plan.setText(("Plan: ")+ cursor.getString(cursor.getColumnIndex("plan"))); description = (TextView) findViewById(R.id.description); description.setText(("Description: ")+ cursor.getString(cursor.getColumnIndex("description"))); effectivity = (TextView) findViewById(R.id.effectivity); effectivity.setText(("Effectivity Date: ")+ cursor.getString(cursor.getColumnIndex("effectivity"))); dueDate = (TextView) findViewById(R.id.dueDate); dueDate.setText(("Due Date: ")+ cursor.getString(cursor.getColumnIndex("dueDate"))); quotaComm = (TextView) findViewById(R.id.quotaComm); quotaComm.setText(("Quota Comm: ")+ cursor.getString(cursor.getColumnIndex("quotaComm"))); quotaNComm = (TextView) findViewById(R.id.quotaNComm); quotaNComm.setText(("Quota NComm: ")+ cursor.getString(cursor.getColumnIndex("quotaNComm"))); CBI = (TextView) findViewById(R.id.CBI); CBI.setText(("CBI: ")+ cursor.getString(cursor.getColumnIndex("CBI"))); instNo = (TextView) findViewById(R.id.instNo); instNo.setText(("Inst No.: ")+ cursor.getString(cursor.getColumnIndex("instNo"))); aging = (TextView) findViewById(R.id.aging); aging.setText(("Aging: ")+ cursor.getString(cursor.getColumnIndex("aging"))); balance = (TextView) findViewById(R.id.balance); balance.setText(("Balance: ")+ cursor.getString(cursor.getColumnIndex("balance"))); taxable = (TextView) findViewById(R.id.taxable); taxable.setText(("Taxable: ")+ cursor.getString(cursor.getColumnIndex("taxable"))); insured = (TextView) findViewById(R.id.insured); insured.setText(("Insured: ")+ cursor.getString(cursor.getColumnIndex("insured"))); orNo = (TextView) findViewById(R.id.orNo); orNo.setText(("OR Number: ")+ cursor.getString(cursor.getColumnIndex("orNo"))); orDate = (TextView) findViewById(R.id.orDate); orDate.setText(("OR Date: ")+ cursor.getString(cursor.getColumnIndex("orDate"))); collDue = (TextView) findViewById(R.id.collDue); collDue.setText(("Coll Due: ")+ cursor.getString(cursor.getColumnIndex("collDue"))); collAdvance = (TextView) findViewById(R.id.collAdvance); collAdvance.setText(("Coll Advance: ")+ cursor.getString(cursor.getColumnIndex("collAdvance"))); } } } </code></pre> <p>this is my PlanholderDetails</p> <pre><code>package samples.planholderdirectory; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SampleLogin extends Activity { EditText txtUserName; EditText txtPassword; Button btnLogin; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.samplelogin); txtUserName=(EditText)this.findViewById(R.id.txtUname); txtPassword=(EditText)this.findViewById(R.id.txtPwd); btnLogin=(Button)this.findViewById(R.id.btnLogin); btnLogin=(Button)this.findViewById(R.id.btnLogin); btnLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if((txtUserName.getText().toString()).equals("user") &amp;&amp; (txtPassword.getText().toString().equals("pass"))){ Toast.makeText(SampleLogin.this, "Login Successful",Toast.LENGTH_LONG).show(); /// Create Intent for SignUpActivity and Start The Activity Intent intentSignUP=new Intent(getApplicationContext(), PlanholderList.class); startActivity(intentSignUP); } else{ Toast.makeText(SampleLogin.this, "Invalid Login",Toast.LENGTH_LONG).show(); } } }); } @Override public void onResume(){ super.onResume(); EditText username = (EditText) findViewById(R.id.txtUname); username.setText(""); EditText password = (EditText) findViewById(R.id.txtPwd); password.setText(""); } } </code></pre> <p>this is my login activity</p>
3
4,572
Tailwind/Flowbite modal not working with Vue.js 3 v-for
<p>I am trying to call a tailwind modal from a table where the rows are generated from a for loop in vue.js with <code>v-for</code>, but the modal fails to be called. However I generate the table without the for loop it works just fine. Here is the code:</p> <h3>Table code (with v-for loop)</h3> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;overflow-x-auto relative sm:rounded-lg my-5 scrollbar-style&quot;&gt; &lt;table class=&quot;w-full text-sm text-left text-gray-700 dark:text-gray-400 relative&quot; &gt; &lt;thead class=&quot;text-xs text-gray-700 uppercase bg-gray-100 dark:bg-gray-700 dark:text-gray-400&quot; &gt; &lt;tr&gt; &lt;th scope=&quot;col&quot; class=&quot;py-3 px-6&quot;&gt;ID&lt;/th&gt; &lt;th scope=&quot;col&quot; class=&quot;py-3 px-6&quot;&gt;Product name&lt;/th&gt; &lt;th scope=&quot;col&quot; class=&quot;py-3 px-6&quot;&gt;Description&lt;/th&gt; &lt;th scope=&quot;col&quot; class=&quot;py-3 px-6&quot;&gt;Price&lt;/th&gt; &lt;th scope=&quot;col&quot; class=&quot;py-3 px-6&quot;&gt;&lt;/th&gt; &lt;th scope=&quot;col&quot; class=&quot;py-3 px-6&quot;&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;template v-for=&quot;product in products&quot; :key=&quot;product.id&quot;&gt; &lt;tr class=&quot;bg-white border-b dark:bg-gray-900 dark:border-gray-700 hover:opacity-75&quot; &gt; &lt;th scope=&quot;row&quot; class=&quot;py-4 px-6 font-medium text-gray-900 whitespace-nowrap dark:text-white&quot; &gt; {{ product.id }} &lt;/th&gt; &lt;td class=&quot;py-4 px-6&quot;&gt;{{ product.name }}&lt;/td&gt; &lt;td class=&quot;py-4 px-6 max-w-xs break-words&quot;&gt; {{ product.description }} &lt;/td&gt; &lt;td class=&quot;py-4 px-6&quot;&gt;{{ product.price }} $&lt;/td&gt; &lt;td class=&quot;py-4 px-6&quot;&gt; &lt;IconC iconName=&quot;Pencil&quot; iconClass=&quot;w-5 h-5 text-blue-700 cursor-pointer hover:text-blue-500 rounded-full&quot; /&gt; &lt;/td&gt; &lt;td class=&quot;py-4 px-6&quot;&gt; &lt;button data-modal-toggle=&quot;delete-modal&quot;&gt; Delete &lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/template&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <h3>Modal code (outside the for loop / table)</h3> <pre class="lang-html prettyprint-override"><code>&lt;div id=&quot;delete-modal&quot; tabindex=&quot;-1&quot; class=&quot;hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 md:inset-0 h-modal md:h-full&quot;&gt; &lt;div class=&quot;relative p-4 w-full max-w-md h-full md:h-auto&quot;&gt; &lt;div class=&quot;relative bg-white rounded-lg shadow dark:bg-gray-700&quot;&gt; &lt;button type=&quot;button&quot; class=&quot;absolute top-3 right-2.5 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-800 dark:hover:text-white&quot; data-modal-toggle=&quot;delete-modal&quot;&gt; &lt;svg aria-hidden=&quot;true&quot; class=&quot;w-5 h-5&quot; fill=&quot;currentColor&quot; viewBox=&quot;0 0 20 20&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;&lt;path fill-rule=&quot;evenodd&quot; d=&quot;M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z&quot; clip-rule=&quot;evenodd&quot;&gt;&lt;/path&gt;&lt;/svg&gt; &lt;span class=&quot;sr-only&quot;&gt;Close modal&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;p-6 text-center&quot;&gt; &lt;svg aria-hidden=&quot;true&quot; class=&quot;mx-auto mb-4 w-14 h-14 text-gray-400 dark:text-gray-200&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot; viewBox=&quot;0 0 24 24&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;&lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; stroke-width=&quot;2&quot; d=&quot;M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z&quot;&gt;&lt;/path&gt;&lt;/svg&gt; &lt;h3 class=&quot;mb-5 text-lg font-normal text-gray-500 dark:text-gray-400&quot;&gt;Are you sure you want to delete this product?&lt;/h3&gt; &lt;button data-modal-toggle=&quot;delete-modal&quot; type=&quot;button&quot; class=&quot;text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2&quot;&gt; Yes, I'm sure &lt;/button&gt; &lt;button data-modal-toggle=&quot;delete-modal&quot; type=&quot;button&quot; class=&quot;text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-gray-200 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600&quot;&gt;No, cancel&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
3
2,867
Why decodeAudioData for Icecast stream only works on Desktop Chrome browser
<p>I have a livestream that is served through Icecast as an audio/mpeg. I use the following code to grab the audio from a livestream to listen to the audio:</p> <pre><code> function playLiveAudio() { // Fix up prefixing window.AudioContext = window.AudioContext || window.webkitAudioContext; var context = new AudioContext(); var offset = 0; var byteOffset = 0; var minDecodeSize = 4096; // This is your chunk size var request = new XMLHttpRequest(); request.onprogress = function(evt) { if (request.response) { var size = request.response.length - byteOffset; if (size &lt; minDecodeSize) return; // In Chrome, XHR stream mode gives text, not ArrayBuffer. // If in Firefox, you can get an ArrayBuffer as is var buf; if (request.response instanceof ArrayBuffer) buf = request.response; else { ab = new ArrayBuffer(size); buf = new Uint8Array(ab); for (var i = 0; i &lt; size; i++) buf[i] = request.response.charCodeAt(i + byteOffset) &amp; 0xff; } byteOffset = request.response.length; context.decodeAudioData(ab, function(buffer) { playSound(buffer); }, function(error) { console.log(error); }); } }; request.onloadend = function(evt) { console.log(evt); }; request.open('GET', liveURL, true); request.responseType = &quot;stream&quot;; // 'stream' in chrome, 'moz-chunked-arraybuffer' in firefox, 'ms-stream' in IE request.overrideMimeType('text/plain; charset=x-user-defined'); request.send(null); function playSound(buffer) { source = context.createBufferSource(); // creates a sound source source.buffer = buffer; // tell the source which sound to play source.connect(context.destination); // connect the source to the context's destination (the speakers) source.start(offset); // play the source now // note: on older systems, may have to use deprecated noteOn(time); offset += buffer.duration; } } </code></pre> <p>I tried changing stream to moz-chunked-arraybuffer and seeing if I could manipulate the audio buffer but it doesn't seem to make a difference - I always get a decode promise rejection in Safari with no further message, or a decode audio data error in Firefox.</p> <p>For some reason, it only works on Desktop Chrome - it doesn't work on any versions of Firefox, Safari or Mobile Chrome. How can decodeAudioData() be made to work on all environments? In Firefox I receive the error: cannot decodeAudioData(). I can set an audio element to livestream the URL but then there is an 8 second delay. This code achieves a 1 second delay.</p>
3
1,565
ImputError: cannot import name "function" from "module.py"
<p>In Jupyter Notebook: repo:</p> <ul> <li>module: featurestorehouse.py</li> <li>main: preprocessing.ipynb</li> </ul> <p>I have several functions in featurestorehouse.py, I need to import most of them, and some of them, particularly the ones I wrote earlier in time, work when I import them. However, the more recent ones don't want to be imported as it gives an ImputError.</p> <p>I checked and changed where necessary, the necessary modules are imported in the module file, I tried putting the imports specific to a function within the function definition - which didn't fix anything, and I tried to not import the functions separately but adding 'fs.' in front of each to reference featurestorehouse as fs.</p> <p>The function and module:</p> <pre><code># # Feature Engineering # import pandas as pd import numpy as np import spacy import re import string from statistics import mean from collections import Counter </code></pre> <p>Some of the functions that do not work:</p> <pre><code># Phrasal complexity ## reference to Martinez (2018) def nr_np(series): &quot;&quot;&quot;Calculates nr of noun chunks in the texts.&quot;&quot;&quot; nlp = spacy.load(&quot;en_core_web_sm&quot;) text = nlp(series) nps = [] for nc in text.noun_chunks: nps.append(np) return len(nps) def count_np(df, word_count_column, np_count_column): &quot;&quot;&quot;Divides number of words by number of noun phrases.&quot;&quot;&quot; try: rel_np = df[word_count_column]/df[np_count_column] return rel_np except 'ZeroDivisionError': return '0' def count_np_words(df, np_count_column, word_count_column): &quot;&quot;&quot;Divides number of noun phrases by number of words.&quot;&quot;&quot; try: rel_np = df[np_count_column]/df[word_count_column] return rel_np except 'ZeroDivisionError': return '0' </code></pre> <p>How I tried to implement them in my main notebook:</p> <pre><code># Adding Custom Feature Columns from featurestorehouse import avg_sentlength, avg_wordlength, nr_deps, count_deps, nr_verbs, count_verbs, nr_words, nr_sents, normalize, normalize_fix, nr_np, count_np, count_np_words, nr_clauses, rel_nr_clauses, rel_nr_words_clauses, unique_words, lexical_variety ## extract relevant column as series series = df['fulltext'].astype(str) # Sentence Complexity ## sentence length df['sentence_cnt'] = series.apply(lambda x: nr_sents(x)) ## average sentence length df['avg_sentlength'] = series.apply(lambda x: avg_sentlength(x)) ## POS distributions ### extract relevant column as series series = df['POS'].astype(str) ### apply function df['VERB_cnt'] = series.apply(lambda x: nr_verbs(x)) fs.count_verbs(df, 'TAG', 'VERB_cnt') # Phrasal Complexity ## NP distributions ### extract relevant column as series series = df['fulltext'].astype(str) ### apply function df['NP_cnt'] = series.apply(lambda x: nr_np(x)) df['np_rel_cnt'] = count_np(df, 'word_cnt', 'NP_cnt') df['np_rel_word_cnt'] = count_np_words(df, 'NP_cnt', 'word_cnt') </code></pre> <p>The last set underneath &quot;### apply function&quot; gives an error when I import featurestorehouse.py as fs and add fs. to each function in the main notebook (obviously it doesn't get to this point when I'm importing each function separately from featurestorehouse.py).</p> <p>The error:</p> <pre><code>ImportError Traceback (most recent call last) &lt;ipython-input-18-8ad058b0250d&gt; in &lt;module&gt; 1 # Adding Custom Feature Columns ----&gt; 2 from featurestorehouse import avg_sentlength, avg_wordlength, nr_deps, count_deps, nr_verbs, count_verbs, nr_words, nr_sents, normalize, normalize_fix, nr_np, count_np, count_np_words, nr_clauses, rel_nr_clauses, rel_nr_words_clauses, unique_words, lexical_variety 3 4 ## extract relevant column as series 5 series = df['fulltext'].astype(str) ImportError: cannot import name 'nr_np' from 'featurestorehouse' (C:\Users\tdems\Jupyter\CEFR_AES_dissertation\featurestorehouse.py) </code></pre> <p>Does anyone know what's up with this? There's no circular dependencies involved as far as I know. There's a lot of other notebooks in the repo but that's never been a problem up till now.</p>
3
1,556
How to repeatedly loop over subsets of a collection determined by an attribute of the items?
<p>I have a collection of objects owned by a struct <code>Manager</code>. These objects have optional attributes such as <code>printable</code> or <code>dynamic</code>. I want to repeatedly loop over all printable objects to print them and loop over all dynamic objects to update them. My rather naive implementation is this:</p> <pre><code>struct Object { state: i32, printable: Option&lt;i32&gt;, dynamic: Option&lt;i32&gt; } struct Manager { objects: Vec&lt;Object&gt;, } impl Manager { fn print_objects(&amp;self) { for o in &amp;self.objects { if let Some(i) = o.printable { print!("{}: {}, ", i, o.state); } } println!(); } fn update_objects(&amp;mut self) { for o in &amp;mut self.objects { if let Some(i) = o.dynamic { o.state += i; } } } } fn main() { let mut mgr = Manager{objects: Vec::new()}; mgr.objects.push(Object{state: 0, printable: Some(10), dynamic: None}); mgr.objects.push(Object{state: 0, printable: None, dynamic: Some(1)}); mgr.objects.push(Object{state: 0, printable: Some(20), dynamic: Some(2)}); for _ in 0..3 { mgr.update_objects(); mgr.print_objects(); } } </code></pre> <p>This solution has the drawback that it needs to loop over all objects and check each for the appropriate flag. Assuming that only a small fraction of the objects are dynamic, I'd rather avoid looping over all of them. In C++ I would simply create a list of pointers to the dynamic objects and loop over that. Attempting this: </p> <pre><code>struct Manager&lt;'a&gt; { objects: Vec&lt;Object&gt;, // objects owned by Manager dynamic: Vec&lt;&amp;'a Object&gt; // references to dynamic objects } impl&lt;'a&gt; Manager&lt;'a&gt; { /* ... */ } fn main() { let mut mgr = Manager{objects: Vec::new(), dynamic: Vec::new()}; mgr.objects.push(Object{state: 0, printable: Some(10), dynamic: None}); mgr.objects.push(Object{state: 0, printable: None, dynamic: Some(1)}); mgr.objects.push(Object{state: 0, printable: Some(20), dynamic: Some(2)}); mgr.dynamic.push(&amp;mgr.objects[1]); mgr.dynamic.push(&amp;mgr.objects[2]); for _ in 0..3 { mgr.update_objects(); // can't mutably borrow because of reference held by mgr.dynamic mgr.print_objects(); } } </code></pre> <p>It seems to be a very basic problem that I can't keep a reference to elements in <code>Manager.objects</code> and at the same time borrow it mutably. Thus, I've started to doubt my whole approach. Is there an idiomatic way to implement such a pattern in Rust?</p> <p>I believe that keeping references to objects prevents me from mutating them, but I'd be happy to learn a way around that. A future goal would be to change <code>printable</code> or <code>dynamic</code> during update, but I'd like to figure out the basic stuff before tackling that step.</p>
3
1,120
Facing Errors in Laravel
<p>I am creating admin panel. When user update their profile its <code>userid</code> read by update controller method using route name <code>update</code>. The update controller method returns a view <code>updatedata</code> along with an array. I am using ORM DATABASE</p> <p><strong>Controller</strong></p> <pre><code>public function update($id) { $records = Register::find($id); return view('updatedata',['records' =&gt; $records]); } </code></pre> <p><strong>Template</strong></p> <pre><code>@extends('layout/master') @section('content') &lt;h1 align="center"&gt; @foreach($records as $records) {!! Form::open(['route'=&gt;'f.update']) !!} &lt;table border="2" align="center"&gt; &lt;tr&gt; &lt;td&gt;{!! Form::label('name','Name') !!}&lt;/td&gt; &lt;td&gt;{!! Form::text('name',$records-&gt;name) !!}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;{!!Form::label('phone','Phone')!!}&lt;/td&gt; &lt;td&gt;{!! Form::text('phone',$records-&gt;phone) !!}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;{!! Form::label('email','E-mail') !!}&lt;/td&gt; &lt;td&gt;{!! Form::email('email',$records-&gt;name) !!}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;{!! Form::label('course','Course') !!}&lt;/td&gt; &lt;td&gt;{!! Form::select('course',['MCA'=&gt;'MCA','BTECH'=&gt;'BTECH','BCA'=&gt;'BCA'],$records-&gt;course) !!}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;{!! Form::label('address','Address') !!}&lt;/td&gt; &lt;td&gt;{!! Form::textarea('address', $records-&gt;address, ['size' =&gt; '30x3']) !!}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt; {!! Form::hidden('id',$records-&gt;id) !!} &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2" align="center"&gt;{!! Form::submit() !!}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; {!! Form::close() !!} @endforeach &lt;/h1&gt; @endsection </code></pre> <p><strong>Error</strong></p> <blockquote> <p>2/2<br> ErrorException in 4de1c6468785010f583b37a90fa7bed16c4e92a7.php line 10:<br> Trying to get property of non-object (View: C:\xampp\htdocs\laravel\resources\views\updatedata.blade.php)</p> </blockquote> <p>Please help.</p>
3
1,181
Using jQuery each, scrollTop() returns zero
<p>I'm having a problem using a jQuery <code>scrollTop()</code> function with <code>$.each.</code> Every time, no matter how many <code>&lt;div class="panel"&gt;&lt;/div&gt;</code> elements are, <code>scrollTop()</code> function returns zero. I've used code in the <a href="https://stackoverflow.com/questions/14782087/get-height-of-multiple-divs-with-jquery">Get height of multiple divs with jquery</a> thread, only changed <code>height()</code> to <code>scrollTop()</code> function (<code>height()</code> still returns zero).</p> <p>Here is the code that I've created, so it will be much easier to understand the problem.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i &lt; acc.length; i++) { acc[i].onclick = function() { this.classList.toggle("active"); var panel = this.nextElementSibling; if (panel.style.maxHeight) { panel.style.maxHeight = null; } else { panel.style.maxHeight = panel.scrollHeight + "px"; } } } var $panel = $('.panel'), totalHeight = 0; $.each($panel, function() { totalHeight += $(this).scrollTop(); }); alert(totalHeight);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>button.accordion { background-color: #eee; color: #444; cursor: pointer; padding: 18px; width: 100%; border: none; text-align: left; outline: none; font-size: 15px; transition: 0.4s; } button.accordion.active, button.accordion:hover { background-color: #ddd; } button.accordion:after { content: '\002B'; color: #777; font-weight: bold; float: right; margin-left: 5px; } button.accordion.active:after { content: "\2212"; } div.panel { padding: 0 18px; background-color: white; max-height: 0; overflow: hidden; transition: max-height 0.2s ease-out; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;button class="accordion"&gt;Lėšų išsiėmimai&lt;/button&gt; &lt;div class="panel"&gt; &lt;div&gt; &lt;/div&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;Data&lt;/th&gt; &lt;th&gt;12 val.&lt;/th&gt; &lt;th&gt;0.01 Eur&lt;/th&gt; &lt;th&gt;Data&lt;/th&gt; &lt;th&gt;24 val.&lt;/th&gt; &lt;th&gt;0.02 Eur&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3"&gt;&lt;/td&gt; &lt;td&gt;2017-06-26 01:39:16&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3"&gt;&lt;/td&gt; &lt;td&gt;2017-06-24 14:43:50&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2017-06-24 14:43:27&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;td&gt;2017-06-15 14:43:43&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2017-06-15 14:42:23&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;td&gt;2017-06-07 16:34:04&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2017-06-07 16:33:36&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;td&gt;1970-01-01 03:00:00&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2017-06-06 15:13:41&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;td&gt;1970-01-01 03:00:00&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style="background: #0E82A7;"&gt;Iš viso&lt;/td&gt; &lt;td style="background: #0E82A7;" colspan="2"&gt;0.0400 Eur&lt;/td&gt; &lt;td style="background: #0E82A7;"&gt;&lt;/td&gt; &lt;td style="background: #0E82A7;" colspan="2"&gt;0.1200 Eur&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class="panel"&gt; &lt;div&gt; &lt;/div&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;Data&lt;/th&gt; &lt;th&gt;12 val.&lt;/th&gt; &lt;th&gt;0.01 Eur&lt;/th&gt; &lt;th&gt;Data&lt;/th&gt; &lt;th&gt;24 val.&lt;/th&gt; &lt;th&gt;0.02 Eur&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3"&gt;&lt;/td&gt; &lt;td&gt;2017-06-26 01:39:16&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3"&gt;&lt;/td&gt; &lt;td&gt;2017-06-24 14:43:50&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2017-06-24 14:43:27&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;td&gt;2017-06-15 14:43:43&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2017-06-15 14:42:23&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;td&gt;2017-06-07 16:34:04&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2017-06-07 16:33:36&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;td&gt;1970-01-01 03:00:00&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2017-06-06 15:13:41&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;td&gt;1970-01-01 03:00:00&lt;/td&gt; &lt;td colspan="2"&gt;+&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style="background: #0E82A7;"&gt;Iš viso&lt;/td&gt; &lt;td style="background: #0E82A7;" colspan="2"&gt;0.0400 Eur&lt;/td&gt; &lt;td style="background: #0E82A7;"&gt;&lt;/td&gt; &lt;td style="background: #0E82A7;" colspan="2"&gt;0.1200 Eur&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3
3,445
Notification not displaying on android device. (Azure notification hub)
<p>I'm trying do send a push notification to my android emulator. When the notification is sent, it receives the notification but does not display it. </p> <p>I'm using this code to display it. </p> <pre><code>void SendNotification(string messageBody) { var intent = new Intent(this, typeof(MainActivity)); intent.AddFlags(ActivityFlags.ClearTop); var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .SetContentTitle("FCM Message") .SetSmallIcon(Resource.Drawable.icon) .SetContentText(messageBody) .SetChannelId("my-chanel") .SetAutoCancel(true) .SetContentIntent(pendingIntent) .SetSound(); var notificationManager = NotificationManager.FromContext(this); notificationManager.Notify(0, notificationBuilder.Build()); } </code></pre> <p>But when the notification is received nothings happens and the logs of my devices gives me this: </p> <pre><code>[Mono] Assembly Ref addref ODEON.Android[0xa31db5c0] -&gt; System.Core[0xa1f2f900]: 7 [MyFirebaseMsgService] From: 241571420247 [MyFirebaseMsgService] noti: [Mono] DllImport searching in: '__Internal' ('(null)'). [Mono] Searching for 'java_interop_jnienv_call_boolean_method'. [Mono] Probing 'java_interop_jnienv_call_boolean_method'. [Mono] Found as 'java_interop_jnienv_call_boolean_method'. [Mono] Assembly Ref addref Xamarin.Android.Support.Compat[0xa31dca60] -&gt; Java.Interop[0xa1f2f780]: 8 [Notification] Use of stream types is deprecated for operations other than volume control [Notification] See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case </code></pre> <p>Can anyone tell my why it doesn't display. Thanks in advance! </p>
3
1,068
Bug correction in WSO2 API Manager 2.0.0
<p>Does WSO2 API Manager 2.0.0 still has <a href="https://wso2.org/jira/browse/APIMANAGER-4242" rel="nofollow noreferrer">this</a> bug, which was corrected with <a href="https://github.com/wso2/carbon-apimgt/commit/c44febfd813ff5aa8f59cdd77e492e12c7535445" rel="nofollow noreferrer">this</a> commit?</p> <p>I'm asking because I had the bug when I used WSO2 API Manager 1.10.0 and now when i started using WSO2 API Manager 2.0.0 I still get the same errors. See <a href="https://stackoverflow.com/questions/38478657/cant-get-past-call-mediator-in-custom-mediation-flow-in-wso2-api-manager">this</a> question for more details on the errors.</p> <p>Edit: The error i get after trying the <code>blocking=true</code> call</p> <pre><code>[2016-09-08 15:08:22,800] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "GET /call/1.0.4/mediator HTTP/1.1[\r][\n]" [2016-09-08 15:08:22,800] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "Authorization: Bearer 40bc5679-00c9-33cf-93b8-6fc5baa6f4c0[\r][\n]" [2016-09-08 15:08:22,800] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "Accept: application/json[\r][\n]" [2016-09-08 15:08:22,801] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "Referer: https://192.88.68.11:9448/store/apis/info?name=Call&amp;version=1.0.4&amp;provider=admin[\r][\n]" [2016-09-08 15:08:22,801] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "Accept-Language: fr-FR[\r][\n]" [2016-09-08 15:08:22,801] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "Accept-Encoding: gzip, deflate[\r][\n]" [2016-09-08 15:08:22,801] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko[\r][\n]" [2016-09-08 15:08:22,801] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "Host: 192.88.68.11:8248[\r][\n]" [2016-09-08 15:08:22,801] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "Connection: Keep-Alive[\r][\n]" [2016-09-08 15:08:22,801] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "Cookie: region3_registry_menu=visible; menuPanel=visible; menuPanelType=main; JSESSIONID=87FED1FBE54FBFBFDD8100053AA8A5F3; requestedURI="../../carbon/admin/index.jsp?loginStatus=true"; region1_configure_menu=none; region4_monitor_menu=none; region5_tools_menu=none; i18next=fr-FR; current-breadcrumb=registry_menu%2Cresource_browser_menu%23; csrftoken=7n1a71hhiuqbu8vk6ia6eaa9ar[\r][\n]" [2016-09-08 15:08:22,801] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &gt;&gt; "[\r][\n]" [2016-09-08 15:08:22,801] DEBUG - headers http-incoming-4 &gt;&gt; GET /call/1.0.4/mediator HTTP/1.1 [2016-09-08 15:08:22,803] DEBUG - headers http-incoming-4 &gt;&gt; Authorization: Bearer 40bc5679-00c9-33cf-93b8-6fc5baa6f4c0 [2016-09-08 15:08:22,803] DEBUG - headers http-incoming-4 &gt;&gt; Accept: application/json [2016-09-08 15:08:22,803] DEBUG - headers http-incoming-4 &gt;&gt; Referer: https://192.88.68.11:9448/store/apis/info?name=Call&amp;version=1.0.4&amp;provider=admin [2016-09-08 15:08:22,803] DEBUG - headers http-incoming-4 &gt;&gt; Accept-Language: fr-FR [2016-09-08 15:08:22,804] DEBUG - headers http-incoming-4 &gt;&gt; Accept-Encoding: gzip, deflate [2016-09-08 15:08:22,804] DEBUG - headers http-incoming-4 &gt;&gt; User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko [2016-09-08 15:08:22,804] DEBUG - headers http-incoming-4 &gt;&gt; Host: 192.88.68.11:8248 [2016-09-08 15:08:22,804] DEBUG - headers http-incoming-4 &gt;&gt; Connection: Keep-Alive [2016-09-08 15:08:22,804] DEBUG - headers http-incoming-4 &gt;&gt; Cookie: region3_registry_menu=visible; menuPanel=visible; menuPanelType=main; JSESSIONID=87FED1FBE54FBFBFDD8100053AA8A5F3; requestedURI="../../carbon/admin/index.jsp?loginStatus=true"; region1_configure_menu=none; region4_monitor_menu=none; region5_tools_menu=none; i18next=fr-FR; current-breadcrumb=registry_menu%2Cresource_browser_menu%23; csrftoken=7n1a71hhiuqbu8vk6ia6eaa9ar [2016-09-08 15:08:23,793] INFO - HTTPSender Unable to sendViaGet to url[http://192.88.64.163:5000/v3/users/mediator] org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:326) at org.apache.axis2.transport.http.HTTPSender.sendViaGet(HTTPSender.java:105) at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:63) at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:451) at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:278) at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442) at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:430) at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:225) at org.apache.axis2.client.OperationClient.execute(OperationClient.java:149) at org.apache.synapse.message.senders.blocking.BlockingMsgSender.sendReceive(BlockingMsgSender.java:283) at org.apache.synapse.message.senders.blocking.BlockingMsgSender.send(BlockingMsgSender.java:194) at org.apache.synapse.mediators.builtin.CallMediator.handleBlockingCall(CallMediator.java:125) at org.apache.synapse.mediators.builtin.CallMediator.mediate(CallMediator.java:97) at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:95) at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:57) at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158) at org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.mediate(APIManagerExtensionHandler.java:67) at org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.handleRequest(APIManagerExtensionHandler.java:78) at org.apache.synapse.rest.API.process(API.java:325) at org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:90) at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:69) at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:300) at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:75) at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180) at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:319) at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:152) at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) [2016-09-08 15:08:23,796] INFO - LogMediator STATUS = Executing default 'fault' sequence, ERROR_CODE = 401000, ERROR_MESSAGE = Transport error: 401 Error: Unauthorized [2016-09-08 15:08:23,800] DEBUG - headers http-incoming-4 &lt;&lt; HTTP/1.1 500 Internal Server Error [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Cookie: region3_registry_menu=visible; menuPanel=visible; menuPanelType=main; JSESSIONID=87FED1FBE54FBFBFDD8100053AA8A5F3; requestedURI="../../carbon/admin/index.jsp?loginStatus=true"; region1_configure_menu=none; region4_monitor_menu=none; region5_tools_menu=none; i18next=fr-FR; current-breadcrumb=registry_menu%2Cresource_browser_menu%23; csrftoken=7n1a71hhiuqbu8vk6ia6eaa9ar [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Access-Control-Allow-Origin: * [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Access-Control-Allow-Methods: GET [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Referer: https://192.88.68.11:9448/store/apis/info?name=Call&amp;version=1.0.4&amp;provider=admin [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Accept-Encoding: gzip, deflate [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Accept-Language: fr-FR [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Access-Control-Allow-Headers: authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Content-Type: application/xml; charset=UTF-8 [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Date: Thu, 08 Sep 2016 13:08:23 GMT [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Transfer-Encoding: chunked [2016-09-08 15:08:23,801] DEBUG - headers http-incoming-4 &lt;&lt; Connection: Keep-Alive [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "HTTP/1.1 500 Internal Server Error[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Cookie: region3_registry_menu=visible; menuPanel=visible; menuPanelType=main; JSESSIONID=87FED1FBE54FBFBFDD8100053AA8A5F3; requestedURI="../../carbon/admin/index.jsp?loginStatus=true"; region1_configure_menu=none; region4_monitor_menu=none; region5_tools_menu=none; i18next=fr-FR; current-breadcrumb=registry_menu%2Cresource_browser_menu%23; csrftoken=7n1a71hhiuqbu8vk6ia6eaa9ar[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Access-Control-Allow-Origin: *[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Access-Control-Allow-Methods: GET[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Referer: https://192.88.68.11:9448/store/apis/info?name=Call&amp;version=1.0.4&amp;provider=admin[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Accept-Encoding: gzip, deflate[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Accept-Language: fr-FR[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Access-Control-Allow-Headers: authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Content-Type: application/xml; charset=UTF-8[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Date: Thu, 08 Sep 2016 13:08:23 GMT[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Transfer-Encoding: chunked[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "Connection: Keep-Alive[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "e3[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "&lt;am:fault xmlns:am="http://wso2.org/apimanager"&gt;&lt;am:code&gt;401000&lt;/am:code&gt;&lt;am:type&gt;Status report&lt;/am:type&gt;&lt;am:message&gt;Runtime Error&lt;/am:message&gt;&lt;am:description&gt;Transport error: 401 Error: Unauthorized&lt;/am:description&gt;&lt;/am:fault&gt;[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "0[\r][\n]" [2016-09-08 15:08:23,802] DEBUG - wire HTTPS-Listener I/O dispatcher-4 &lt;&lt; "[\r][\n]" </code></pre>
3
4,731
Adding timestamp on the top of the plot using Matplotlib
<p>Is there a way to add timestamp <code>t=0</code> on the top of the plot at the specific location as shown in the expected output? In general, does Python have a time counter which appears on every frame and is split according to the number of frames? I present the current and expected outputs.</p> <pre><code>import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import numpy as np from matplotlib.colors import Normalize from matplotlib import cm import math from numpy import nan fig,aPe = plt.subplots(1) n=3 arMax=[] arMin=[] N=2*n*(n-1) J = np.array([[]]) Pe=np.array([[394.20560747663563, 408.7929050665396 , 419.132709901089 , 398.95097406721044, 403.81198021076113, 430.00914784982064, 424.50127213826016, 453.54817733128607, 441.4651085668709 , 447.42507960635163, 413.8982415602072 , 390.3025816600353 ]]) C1 = nan for i in J[0]: Pe = np.insert(Pe, i, [C1], axis=1) print(&quot;Pe =&quot;, [Pe]) for i in range(0,len(Pe)): Max=max(max(Pe[i]), max(Pe[i])) Min=min(min(Pe[i]), min(Pe[i])) arMax.append(Max) Max=np.array(arMax) arMin.append(Min) Min=np.array(arMin) a=min(Min) b=max(Max) print(&quot;a =&quot;,a) print(&quot;b =&quot;,b) Amax= math.ceil(b) Amin= math.floor(a) print(Amax, Amin) color = cm.get_cmap('Dark2') norm = Normalize(vmin=Amin, vmax=Amax) color_list = [] for i in range(len(Pe[0])): color_list.append(color(((Pe[0,i])-Amin)/(Amax-Amin))) id = 0 for j in range(0, n): for k in range(n-1): aPe.hlines(200+200*(n-j-1)+5*n, 200*(k+1)+5*n, 200*(k+2)+5*n, zorder=0, colors=color_list[id]) id += 1 for i in range(0, n): rect = mpl.patches.Rectangle((200+200*i, 200+200*j), 10*n, 10*n, linewidth=1, edgecolor='black', facecolor='black') aPe.add_patch(rect) if j &lt; n-1: aPe.vlines(200+200*i+5*n, 200*(n-1-j)+5*n, 200*(n-j)+5*n, zorder=0, colors=color_list[id]) id += 1 cb = fig.colorbar(cm.ScalarMappable(cmap=color, norm=norm), ticks=np.arange(Amin, Amax+len(color.colors), len(color.colors))) cb.set_ticks(np.arange(Amin, Amax+1, (Amax-Amin)/8).astype(np.int64)) cb.set_label(&quot;Entry pressure (N/m$^{2}$)&quot;) aPe.set_xlim(left = 0, right = 220*n) aPe.set_ylim(bottom = 0, top = 220*n) plt.axis('off') plt.show() </code></pre> <p>The current output is</p> <p><a href="https://i.stack.imgur.com/pkc6g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pkc6g.png" alt="enter image description here" /></a></p> <p>The expected output is</p> <p><a href="https://i.stack.imgur.com/i56X3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i56X3.png" alt="enter image description here" /></a></p>
3
1,308
How to remove space between expanded ExpansionPanels in ExpansionPanelList?
<p>This is an example code for <code>ExpansionPanelList</code></p> <pre><code>import 'package:flutter/material.dart'; void main() =&gt; runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); static const String _title = 'Flutter Code Sample'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: Scaffold( appBar: AppBar(title: const Text(_title)), body: const MyStatefulWidget(), ), ); } } // stores ExpansionPanel state information class Item { Item({ required this.expandedValue, required this.headerValue, this.isExpanded = false, }); String expandedValue; String headerValue; bool isExpanded; } List&lt;Item&gt; generateItems(int numberOfItems) { return List&lt;Item&gt;.generate(numberOfItems, (int index) { return Item( headerValue: 'Panel $index', expandedValue: 'This is item number $index', ); }); } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({Key? key}) : super(key: key); @override State&lt;MyStatefulWidget&gt; createState() =&gt; _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State&lt;MyStatefulWidget&gt; { final List&lt;Item&gt; _data = generateItems(8); @override Widget build(BuildContext context) { return SingleChildScrollView( child: Container( child: _buildPanel(), ), ); } Widget _buildPanel() { return ExpansionPanelList( expansionCallback: (int index, bool isExpanded) { setState(() { _data[index].isExpanded = !isExpanded; }); }, children: _data.map&lt;ExpansionPanel&gt;((Item item) { return ExpansionPanel( headerBuilder: (BuildContext context, bool isExpanded) { return ListTile( title: Text(item.headerValue), ); }, body: ListTile( title: Text(item.expandedValue), subtitle: const Text('To delete this panel, tap the trash can icon'), trailing: const Icon(Icons.delete), onTap: () { setState(() { _data.removeWhere((Item currentItem) =&gt; item == currentItem); }); }), isExpanded: item.isExpanded, ); }).toList(), ); } } </code></pre> <p>And it gives the following result:</p> <p><a href="https://i.stack.imgur.com/orXvY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/orXvY.png" alt="enter image description here" /></a></p> <p>As you see there is grey space between <code>Panel 0</code> and <code>Panel 1</code>, and between <code>Panel 1</code> and <code>Panel 2</code>. Could anyone say how to remove this space, if it is possible?</p>
3
1,184
Suppressed the virtual mechanism by storing object explicitly as base class?
<p>As you'd expect, I've arrived at a question I can't answer and I can only guess.</p> <p>Runtime polymorphism is the goal, using the virtual mechanism, but the result I'm getting is as if I called the method while suppressing it; like I called the base class method.</p> <p>I can only guess then that I am somehow doing that, the call is from an object that <em>is</em> a base class, although it was constructed as a derived class. So, constructed as a derived, stored as a base.</p> <p>I do store this as a static base class variable within a cpp and interfaced with multiple extern functions to access elsewhere. (perhaps, that's the gotcha?)</p> <p>GameScene.h:</p> <pre><code>class GameScene { public: GameScene() { SceneInit(); } ~GameScene() { } virtual void LevelInit() { } // gcc complains w/o {} void SceneInit(); virtual void UpdateLevel( const float&amp; timeDelta ) { } // gcc complains unless {} added void UpdateScene( const float&amp; timeDelta ); }; extern void NewScene( const GameScene&amp; level ); extern void UpdateScene( const float&amp; timeDelta ); class TestLevel : public GameScene { public: TestLevel() { SceneInit(); } // implementation here in header void LevelInit() override { // level-specific initialization that is apparent at runtime } void UpdateLevel( const float&amp; timeDelta ) override { // level-specific checks and performance // but, to test, I simply log "This is the test level" } }; class TutorialLevel : public GameScene { public: TutorialLevel() { SceneInit(); } // implementation here in header void LevelInit() override { // level-specific initialization that is apparent at runtime } void UpdateLevel( const float&amp; timeDelta ) { // level-specific checks and performance // debug log "This is the tutorial level" } }; </code></pre> <p>GameScene.cpp:</p> <pre><code>#include "GameScene.h" static GameScene currentScene; // I am now wondering if this pattern is the problem (by explicitly storing this as the base class) extern void NewScene( const GameScene&amp; level ) { currentScene = level; } extern void UpdateScene( const float&amp; timeDelta ) { currentScene.UpdateScene( timeDelta ); } GameScene::SceneInit() { // general init LevelInit(); // this _properly_ calls the subclass overridden version // init completion } GameScene::UpdateScene( const float&amp; timeDelta ) { // general updating and game handling UpdateLevel( timeDelta ); // this was _meant_ to call the overridden version, it does not } </code></pre> <p>EntryPoint.cpp:</p> <pre><code>#include "GameScene.h" int main() { //NewScene( TestLevel() ); NewScene( TutorialLevel() ); float deltaTime; while (gameLoop) { deltaTime = SecondsSinceLastFrame(); // pseudo UpdateScene( deltaTime ); } } </code></pre> <p>So, I was following a pattern that worked with SceneInit() calling LevelInit(), which is overridden in the derived classes. If I use either derived class constructor in NewScene(), I get those LevelInit() results at runtime. I thought this would be safe to use this pattern with UpdateScene().</p> <p>What I see is UpdateScene() called the GameScene::UpdateLevel(), even though it is clearly overridden in the subclasses, just like LevelInit() is.</p> <p>My (wild) guess is, I <em>am</em> calling UpdateLevel() as if I had explicitly cast it as GameScene. :\</p> <p>And maybe, this is because I store currentScene <em>as</em> GameScene? (but then, doesn't that defeat the purpose of having polymorphism?)</p> <p>I am missing something about either storing currentScene, or calling UpdateLevel(). I've tried calling like this:</p> <pre><code> GameScene *s = currentScene; s-&gt;UpdateLevel(); </code></pre> <p>after reading that, as a pointer, the virtual mechanism should be finding the most-derived version of the method. (but alas...)</p> <p>I wish I could have found an example here or elsewhere, but my searches pointed out problems with virtual in constructors/deconstructors, or just not using the 'virtual' keyword, etc.</p>
3
1,303
bsimagepicker Terminated due to memory issue
<p>I am using <code>Bsimagepicker</code> for multiple selection of images from the gallery. <code>Bsimagepicker</code> is working for small size images, When try to load high quality image with large size leads to </p> <blockquote> <p>"Terminated due to memory issue"</p> </blockquote> <p>Here is my code:</p> <pre><code> var SelectedAssets = [PHAsset]() var PhotoArray = [UIImage]() @objc func opengallery(_ sender: AnyObject!){ let vc = BSImagePickerViewController() self.bs_presentImagePickerController(vc, animated: true, select: { (asset: PHAsset) -&gt; Void in}, deselect: { (asset: PHAsset) -&gt; Void in }, cancel: { (assets: [PHAsset]) -&gt; Void in let a = 1 print("hello \(a)") }, finish: { (assets: [PHAsset]) -&gt; Void in self.imgc = assets.count for i in 0..&lt;assets.count { self.SelectedAssets.append(assets[i]) } self.convertAssetToImages() }, completion: guest) } func convertAssetToImages() -&gt; Void{ if SelectedAssets.count != 0{ flaggalleryin = 2 for i in 0..&lt;SelectedAssets.count{ let manager = PHImageManager.default() let option = PHImageRequestOptions() var thumbflag = 0 var thumbnail = UIImage() option.isSynchronous = true var wid :Int! var hei :Int! if(SelectedAssets[i].pixelWidth &gt; 750){ wid = 700 }else{ wid = SelectedAssets[i].pixelWidth } if(SelectedAssets[i].pixelHeight &gt; 750){ hei = 700 }else{ hei = SelectedAssets[i].pixelHeight } manager.requestImage(for: SelectedAssets[i], targetSize: CGSize(width: wid, height: hei), contentMode: .aspectFill, options: option, resultHandler: {(result, info)-&gt;Void in if(result != nil) { thumbnail = result! thumbflag = 1 }else{ thumbflag = 0 } }) let data = UIImageJPEGRepresentation(thumbnail, 1.0) let newImage = UIImage(data: data!) self.PhotoArray.append(newImage! as UIImage) } } </code></pre> <p>Please help me to resolve the Terminated due to memory issue</p> <p>Thanks </p>
3
1,132
Allowing routes with and without {culture} (.net core 2.2)
<p>UPDATE: I got it working - added the following to the routes:</p> <p>[Route("{culture}/[action]")]</p> <p>[Route("/[action]")]</p> <p>Problem is now when I am on /da/about it won't add the /da/ to the links generated on the AnchorTagHelper. </p> <hr> <p>Trying to allow culture in the routes. But I also want it to work without (fallback to english).</p> <p>domain.com/en/about</p> <p>domain.com/about</p> <p>I can only get one of them to work at one time. Adding / removing the {culture} makes it work for each.</p> <p>[Route("{culture}/about")]</p> <p>Have tried changing, moving etc. everything with the MapRoutes</p> <p>Any ideas how to catch both routes?</p> <p>I have the following code:</p> <pre><code>services.Configure&lt;RouteOptions&gt;(options =&gt; { options.ConstraintMap.Add("culture", typeof(LanguageRouteConstraint)); }); </code></pre> <p>--</p> <pre><code>services.AddLocalization(options =&gt; options.ResourcesPath = "Resources"); services.Configure&lt;RequestLocalizationOptions&gt;(options =&gt; { var supportedCultures = new List&lt;CultureInfo&gt; { new CultureInfo("en"), //new CultureInfo("da-DK"), new CultureInfo("da") }; //options.DefaultRequestCulture = new RequestCulture(DefaultCultureName, DefaultCultureName); options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en-US"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; options.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider { Options = options }); }); </code></pre> <p>--</p> <pre><code> app.UseMvc(routes =&gt; { routes.MapRoute( name: "LocalizedDefault", template: "{culture:culture}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}",//"{*catchall}", defaults: new { controller = "Home", action = "Index" }); }); </code></pre> <p>--</p> <pre><code>public class LanguageRouteConstraint : IRouteConstraint { public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { if (!values.ContainsKey("culture")) return true; var culture = values["culture"].ToString(); return culture == "en" || culture == "da"; } } </code></pre>
3
1,325
Select option only affects row one - php-jquery-mysql
<p><strong>Hi ! I used mysqli for my connection in database.<a href="https://i.stack.imgur.com/6Xt4E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Xt4E.png" alt="enter image description here"></a></strong> My problem is the second and the following rows is not affected whenever I select new option in . Can you guys please help me to solve this. <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>$(document).ready(function () { $('#dealer').change(function () { $("#tt").val($(this).val()); }); }); </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"&gt;&lt;/script&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;USERNAME&lt;/th&gt; &lt;th&gt;PASSWORD&lt;/th&gt; &lt;th&gt;CURRENT USER TYPE&lt;/th&gt; &lt;th&gt;CHANGE USER TYPE&lt;/th&gt; &lt;th&gt;UPDATE&lt;/th&gt; &lt;th&gt;DELETE&lt;/th&gt; &lt;/tr&gt; &lt;?php while($row= mysqli_fetch_array($records)) { //echo "&lt;tr&gt;&lt;form action='super_admin_function_edit.php' method='post'&gt;"; echo "&lt;tr&gt;&lt;form action=super_admin_function_edit.php method=post&gt;"; echo "&lt;td&gt;&lt;input type=text name=emp_username value='".$row['emp_username']."'&gt;&lt;/td&gt;"; echo "&lt;td&gt;&lt;input type=text name=emp_password value='".$row['emp_password']."'&gt;&lt;/td&gt;"; echo "&lt;td&gt;&lt;input type=text name=emp_type id=tt value='".$row['emp_type']."'&gt;&lt;/td&gt;"; //echo "&lt;td&gt;&lt;input type='text' id='tt' &lt;/td&gt;"; echo " &lt;td&gt;&lt;select name='dealer' id='dealer'&gt; &lt;option value='0'&gt;---- select Dealer -----&lt;/option&gt; &lt;option value='1'&gt;---- select Dealer1 -----&lt;/option&gt; &lt;option value='2'&gt;---- select Dealer2 -----&lt;/option&gt; &lt;/select&gt; &lt;/td&gt;"; echo "&lt;input type=hidden name=emp_id value='".$row['emp_id']."'&gt;&lt;/td&gt;"; echo "&lt;td&gt;&lt;input type=submit&gt;&lt;/td&gt;"; echo "&lt;td&gt;&lt;input type=submit value=Delete&gt;&lt;/td&gt;"; echo "&lt;/form&gt;&lt;/tr&gt;"; } ?&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
3
1,097
Wordpress meta_key with checkboxes
<p>I have a custom post type which contains a checkbox group "areas" which allows the user to select multiple areas covered by their service.</p> <p>On the frontend, I have a custom search query in place which allows the user to refine by basic criteria.</p> <p>It's working ok but I've hit a wall with the checkboxes. I've tried feeding in an array to the meta_key value (imploded and exploded tried so far) but I can only get it to register the first checked item.</p> <p>My HTML form:</p> <pre><code> &lt;form id="searchform" method="post" action=""&gt; &lt;fieldset&gt; &lt;select name="service"&gt; &lt;option value="" &lt;?php if(isset($_GET['service']) &amp;&amp; $_GET['service'] == "") { echo 'selected'; } ?&gt;&gt;All&lt;/option&gt; &lt;option value="3" &lt;?php if(isset($_GET['service']) &amp;&amp; $_GET['service'] == '3') { echo 'selected'; } ?&gt;&gt;Advocacy and Advice&lt;/option&gt; &lt;option value="0"&gt;Alcohol and Drug Partnership&lt;/option&gt; &lt;option value="0"&gt;Befriending&lt;/option&gt; &lt;option value="0"&gt;Care &amp;amp; Support at Home&lt;/option&gt; &lt;option value="4" &lt;?php if(isset($_GET['service']) &amp;&amp; $_GET['service'] == '4') { echo 'selected'; } ?&gt;&gt;Care Homes&lt;/option&gt; &lt;/select&gt; &lt;label class="radio" for="order-0"&gt; &lt;input name="order" id="order-0" value="ASC" type="radio" &lt;?php if(isset($_GET['order']) &amp;&amp; $_GET['order'] == 'DESC' || !$_GET['order']) { echo 'checked'; } ?&gt;&gt; Ascending &lt;/label&gt; &lt;label class="radio" for="order-1"&gt; &lt;input name="order" id="order-1" value="DESC" type="radio" &lt;?php if(isset($_GET['order']) &amp;&amp; $_GET['order'] == 'DESC') { echo 'checked'; } ?&gt;&gt; Descending &lt;/label&gt; &lt;h3&gt;Areas covered&lt;/h3&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-4"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input name="areas[]" value="Ardrossan" type="checkbox" class="check"&gt; Ardrossan &lt;/label&gt; &lt;/div&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input name="areas[]" value="Largs" type="checkbox" class="check"&gt; Largs &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;button type="submit" class="button green"&gt;Search&lt;/button&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>My query:</p> <pre><code> $custom_taxterms = wp_get_object_terms( $post-&gt;ID, 'category', array('fields' =&gt; 'ids') ); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; if($_POST['areas']) { $areas = $_POST['areas']; $areas = implode(',',$areas); } else { $areas = ''; } if($_GET['service']) { $service = $_POST['service']; } else { $service = 0; } if($_GET['order']) { $order = $_POST['order']; } else { $order = 'ASC'; } $args = array( 'post_type' =&gt; 'provider_listing', 'cat' =&gt; $service, 'order' =&gt; $order, 'paged' =&gt; $paged, 'meta_query' =&gt; array( array ( 'key' =&gt; 'areas_covered', 'value' =&gt; $areas, 'compare' =&gt; 'LIKE' ) ) ); $providers = query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; ...... </code></pre>
3
2,775
sam local invoke gets connectionRefused when accessing S3 from localstack
<p>I'm running localstack where I create an s3 bucket. But when I invoke a lambda function with SAM to list the buckets, the connection is refused.</p> <p>I start localstack with</p> <pre><code>localstack start </code></pre> <p>then I create and list a bucket with a python script:</p> <pre><code>import boto3 BUCKET_NAME = &quot;mybucket&quot; HOST_ADDRESS= &quot;http://localhost:4566&quot; s3_client = boto3.client('s3', region_name='us-east-1', endpoint_url=HOST_ADDRESS) s3_client.create_bucket(Bucket=BUCKET_NAME) </code></pre> <p>Then I list the buckets with</p> <pre><code>import boto3 s3_client = boto3.client('s3', endpoint_url=&quot;http://localhost:4566&quot;) for bucket in s3_client.list_buckets()[&quot;Buckets&quot;]: print(bucket['Name']) </code></pre> <p>Now I invoke my lambda function that does the exact same thing with <code>sam build</code> and <code>sam local invoke --profile=localstack</code>. The profile localstack constains the credentials and region for my localstack. The code is</p> <pre><code>#!/usr/bin/python3 import boto3 HOST_ADDRESS= &quot;http://localhost:4566&quot; s3_client = boto3.client('s3', endpoint_url=HOST_ADDRESS) def lambda_handler(event, context): s3_client.list_buckets() return { &quot;statusCode&quot;: 200 } </code></pre> <p>the template:</p> <pre><code>AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Description: Lambda that reads from an s3 bucket Resources: FetchFunction: Type: 'AWS::Serverless::Function' Properties: FunctionName: bucketFetchSAM Handler: app.lambda_handler Runtime: python3.8 CodeUri: fetch_new/ Timeout: 20 Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 's3:ListAllMyBuckets' Resource: '*' </code></pre> <p>This produces the following error message</p> <pre><code>START RequestId: 24050f46-f66c-4916-a082-b7f5ce2deda7 Version: $LATEST raise EndpointConnectionError(endpoint_url=request.url, error=e)ponset_exceptionlhost:4566/&quot; { &quot;errorMessage&quot;: &quot;Could not connect to the endpoint URL: \&quot;http://localhost:4566/\&quot;&quot;, &quot;errorType&quot;: &quot;EndpointConnectionError&quot;, &quot;stackTrace&quot;: [ &quot; File \&quot;/var/task/app.py\&quot;, line 13, in lambda_handler\n s3_client.list_buckets()\n&quot;, &quot; File \&quot;/var/runtime/botocore/client.py\&quot;, line 391, in _api_call\n return self._make_api_call(operation_name, kwargs)\n&quot;, &quot; File \&quot;/var/runtime/botocore/client.py\&quot;, line 705, in _make_api_call\n http, parsed_response = self._make_request(\n&quot;, &quot; File \&quot;/var/runtime/botocore/client.py\&quot;, line 725, in _make_request\n return self._endpoint.make_request(operation_model, request_dict)\n&quot;, &quot; File \&quot;/var/runtime/botocore/endpoint.py\&quot;, line 104, in make_request\n return self._send_request(request_dict, operation_model)\n&quot;, &quot; File \&quot;/var/runtime/botocore/endpoint.py\&quot;, line 138, in _send_request\n while self._needs_retry(attempts, operation_model, request_dict,\n&quot;, &quot; File \&quot;/var/runtime/botocore/endpoint.py\&quot;, line 254, in _needs_retry\n responses = self._event_emitter.emit(\n&quot;, &quot; File \&quot;/var/runtime/botocore/hooks.py\&quot;, line 357, in emit\n return self._emitter.emit(aliased_event_name, **kwargs)\n&quot;, &quot; File \&quot;/var/runtime/botocore/hooks.py\&quot;, line 228, in emit\n return self._emit(event_name, kwargs)\n&quot;, &quot; File \&quot;/var/runtime/botocore/hooks.py\&quot;, line 211, in _emit\n response = handler(**kwargs)\n&quot;, &quot; File \&quot;/var/runtime/botocore/retryhandler.py\&quot;, line 183, in __call__\n if self._checker(attempts, response, caught_exception):\n&quot;, &quot; File \&quot;/var/runtime/botocore/retryhandler.py\&quot;, line 250, in __call__\n should_retry = self._should_retry(attempt_number, response,\n&quot;, &quot; File \&quot;/var/runtime/botocore/retryhandler.py\&quot;, line 277, in _should_retry\n return self._checker(attempt_number, response, caught_exception)\n&quot;, &quot; File \&quot;/var/runtime/botocore/retryhandler.py\&quot;, line 316, in __call__\n checker_response = checker(attempt_number, response,\n&quot;, &quot; File \&quot;/var/runtime/botocore/retryhandler.py\&quot;, line 222, in __call__\n return self._check_caught_exception(\n&quot;, &quot; File \&quot;/var/runtime/botocore/retryhandler.py\&quot;, line 359, in _check_caught_exception\n raise caught_exception\n&quot;, &quot; File \&quot;/var/runtime/botocore/endpoint.py\&quot;, line 201, in _do_get_response\n http_response = self._send(request)\n&quot;, &quot; File \&quot;/var/runtime/botocore/endpoint.py\&quot;, line 270, in _send\n return self.http_session.send(request)\n&quot;, &quot; File \&quot;/var/runtime/botocore/httpsession.py\&quot;, line 438, in send\n raise EndpointConnectionError(endpoint_url=request.url, error=e)\n&quot; ] } END RequestId: 24050f46-f66c-4916-a082-b7f5ce2deda7 </code></pre> <p>I am especially confused because the commands I am using clearly work when used outside of sam, but within sam it seems the the bucket is either not found or not accessible or that there is a lack of authentication.</p> <p>When I put</p> <pre><code>logger = logging.getLogger() logger.setLevel(logging.DEBUG) </code></pre> <p>into the lambda code I get these logs:</p> <pre><code>[DEBUG] 2022-09-10T11:37:48.729Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event before-parameter-build.s3.ListBuckets: calling handler &lt;function validate_bucket_name at 0x7f2c32b7a820&gt; [DEBUG] 2022-09-10T11:37:48.729Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event before-parameter-build.s3.ListBuckets: calling handler &lt;bound method S3RegionRedirector.redirect_from_cache of &lt;botocore.utils.S3RegionRedirector object at 0x7f2c317b1910&gt;&gt; [DEBUG] 2022-09-10T11:37:48.729Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event before-parameter-build.s3.ListBuckets: calling handler &lt;bound method S3ArnParamHandler.handle_arn of &lt;botocore.utils.S3ArnParamHandler object at 0x7f2c317b19d0&gt;&gt; [DEBUG] 2022-09-10T11:37:48.729Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event before-parameter-build.s3.ListBuckets: calling handler &lt;function generate_idempotent_uuid at 0x7f2c32b7a670&gt; [DEBUG] 2022-09-10T11:37:48.729Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event before-call.s3.ListBuckets: calling handler &lt;function add_expect_header at 0x7f2c32b7ab80&gt; [DEBUG] 2022-09-10T11:37:48.729Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event before-call.s3.ListBuckets: calling handler &lt;bound method S3RegionRedirector.set_request_url of &lt;botocore.utils.S3RegionRedirector object at 0x7f2c317b1910&gt;&gt; [DEBUG] 2022-09-10T11:37:48.730Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event before-call.s3.ListBuckets: calling handler &lt;function inject_api_version_header_if_needed at 0x7f2c32b81ee0&gt; [DEBUG] 2022-09-10T11:37:48.730Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Making request for OperationModel(name=ListBuckets) with params: {'url_path': '/', 'query_string': '', 'method': 'GET', 'headers': {'User-Agent': 'Boto3/1.20.32 Python/3.8.13 Linux/5.15.0-46-generic exec-env/AWS_Lambda_python3.8 Botocore/1.23.32'}, 'body': b'', 'url': 'http://localhost:4566/', 'context': {'client_region': 'us-east-1', 'client_config': &lt;botocore.config.Config object at 0x7f2c3259f9a0&gt;, 'has_streaming_input': False, 'auth_type': None, 'signing': {'bucket': None}}} [DEBUG] 2022-09-10T11:37:48.730Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event request-created.s3.ListBuckets: calling handler &lt;bound method RequestSigner.handler of &lt;botocore.signers.RequestSigner object at 0x7f2c3259f9d0&gt;&gt; [DEBUG] 2022-09-10T11:37:48.730Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event choose-signer.s3.ListBuckets: calling handler &lt;bound method S3EndpointSetter.set_signer of &lt;botocore.utils.S3EndpointSetter object at 0x7f2c317b1a60&gt;&gt; [DEBUG] 2022-09-10T11:37:48.731Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event choose-signer.s3.ListBuckets: calling handler &lt;bound method ClientCreator._default_s3_presign_to_sigv2 of &lt;botocore.client.ClientCreator object at 0x7f2c32ba3b80&gt;&gt; [DEBUG] 2022-09-10T11:37:48.731Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event choose-signer.s3.ListBuckets: calling handler &lt;function set_operation_specific_signer at 0x7f2c32b7a550&gt; [DEBUG] 2022-09-10T11:37:48.731Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event before-sign.s3.ListBuckets: calling handler &lt;bound method S3EndpointSetter.set_endpoint of &lt;botocore.utils.S3EndpointSetter object at 0x7f2c317b1a60&gt;&gt; [DEBUG] 2022-09-10T11:37:48.731Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Using S3 path style addressing. [DEBUG] 2022-09-10T11:37:48.732Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Calculating signature using v4 auth. [DEBUG] 2022-09-10T11:37:48.732Z 3b4786a3-2b51-4213-8611-d6ff374211a2 CanonicalRequest: GET / host:localhost:4566 x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 x-amz-date:20220910T113748Z host;x-amz-content-sha256;x-amz-date e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 [DEBUG] 2022-09-10T11:37:48.732Z 3b4786a3-2b51-4213-8611-d6ff374211a2 StringToSign: AWS4-HMAC-SHA256 20220910T113748Z 20220910/us-east-1/s3/aws4_request 745622b7535d6b3346127386c068f1ada28987a487193b43981e6ca68e719eb3 [DEBUG] 2022-09-10T11:37:48.732Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Signature: ffe5af8ae43d86e0dff2c991546d722f70f886d8b49565467a607b20ef433042 [DEBUG] 2022-09-10T11:37:48.732Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Sending http request: &lt;AWSPreparedRequest stream_output=False, method=GET, url=http://localhost:4566/, headers={'User-Agent': b'Boto3/1.20.32 Python/3.8.13 Linux/5.15.0-46-generic exec-env/AWS_Lambda_python3.8 Botocore/1.23.32', 'X-Amz-Date': b'20220910T113748Z', 'X-Amz-Content-SHA256': b'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'Authorization': b'AWS4-HMAC-SHA256 Credential=test/20220910/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=ffe5af8ae43d86e0dff2c991546d722f70f886d8b49565467a607b20ef433042'}&gt; [DEBUG] 2022-09-10T11:37:48.733Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Starting new HTTP connection (1): localhost:4566 [DEBUG] 2022-09-10T11:37:48.737Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Exception received when sending HTTP request. Traceback (most recent call last): File &quot;/var/task/urllib3/connection.py&quot;, line 174, in _new_conn conn = connection.create_connection( File &quot;/var/task/urllib3/util/connection.py&quot;, line 95, in create_connection raise err File &quot;/var/task/urllib3/util/connection.py&quot;, line 85, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/var/runtime/botocore/httpsession.py&quot;, line 409, in send urllib_response = conn.urlopen( File &quot;/var/task/urllib3/connectionpool.py&quot;, line 787, in urlopen retries = retries.increment( File &quot;/var/task/urllib3/util/retry.py&quot;, line 525, in increment raise six.reraise(type(error), error, _stacktrace) File &quot;/var/task/urllib3/packages/six.py&quot;, line 770, in reraise raise value File &quot;/var/task/urllib3/connectionpool.py&quot;, line 703, in urlopen httplib_response = self._make_request( File &quot;/var/task/urllib3/connectionpool.py&quot;, line 398, in _make_request conn.request(method, url, **httplib_request_kw) File &quot;/var/task/urllib3/connection.py&quot;, line 239, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File &quot;/var/lang/lib/python3.8/http/client.py&quot;, line 1256, in request self._send_request(method, url, body, headers, encode_chunked) File &quot;/var/runtime/botocore/awsrequest.py&quot;, line 92, in _send_request rval = super(AWSConnection, self)._send_request( File &quot;/var/lang/lib/python3.8/http/client.py&quot;, line 1302, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File &quot;/var/lang/lib/python3.8/http/client.py&quot;, line 1251, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File &quot;/var/runtime/botocore/awsrequest.py&quot;, line 120, in _send_output self.send(msg) File &quot;/var/runtime/botocore/awsrequest.py&quot;, line 204, in send return super(AWSConnection, self).send(str) File &quot;/var/lang/lib/python3.8/http/client.py&quot;, line 951, in send self.connect() File &quot;/var/task/urllib3/connection.py&quot;, line 205, in connect conn = self._new_conn() File &quot;/var/task/urllib3/connection.py&quot;, line 186, in _new_conn raise NewConnectionError( urllib3.exceptions.NewConnectionError: &lt;botocore.awsrequest.AWSHTTPConnection object at 0x7f2c317e2100&gt;: Failed to establish a new connection: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/var/runtime/botocore/endpoint.py&quot;, line 201, in _do_get_response http_response = self._send(request) File &quot;/var/runtime/botocore/endpoint.py&quot;, line 270, in _send return self.http_session.send(request) File &quot;/var/runtime/botocore/httpsession.py&quot;, line 438, in send raise EndpointConnectionError(endpoint_url=request.url, error=e) botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: &quot;http://localhost:4566/&quot;[DEBUG] 2022-09-10T11:37:48.740Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Event needs-retry.s3.ListBuckets: calling handler &lt;botocore.retryhandler.RetryHandler object at 0x7f2c317b18b0&gt; [DEBUG] 2022-09-10T11:37:48.741Z 3b4786a3-2b51-4213-8611-d6ff374211a2 retry needed, retryable exception caught: Could not connect to the endpoint URL: &quot;http://localhost:4566/&quot; Traceback (most recent call last): File &quot;/var/task/urllib3/connection.py&quot;, line 174, in _new_conn conn = connection.create_connection( File &quot;/var/task/urllib3/util/connection.py&quot;, line 95, in create_connection raise err File &quot;/var/task/urllib3/util/connection.py&quot;, line 85, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/var/runtime/botocore/httpsession.py&quot;, line 409, in send urllib_response = conn.urlopen( File &quot;/var/task/urllib3/connectionpool.py&quot;, line 787, in urlopen retries = retries.increment( File &quot;/var/task/urllib3/util/retry.py&quot;, line 525, in increment raise six.reraise(type(error), error, _stacktrace) File &quot;/var/task/urllib3/packages/six.py&quot;, line 770, in reraise raise value File &quot;/var/task/urllib3/connectionpool.py&quot;, line 703, in urlopen httplib_response = self._make_request( File &quot;/var/task/urllib3/connectionpool.py&quot;, line 398, in _make_request conn.request(method, url, **httplib_request_kw) File &quot;/var/task/urllib3/connection.py&quot;, line 239, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File &quot;/var/lang/lib/python3.8/http/client.py&quot;, line 1256, in request self._send_request(method, url, body, headers, encode_chunked) File &quot;/var/runtime/botocore/awsrequest.py&quot;, line 92, in _send_request rval = super(AWSConnection, self)._send_request( File &quot;/var/lang/lib/python3.8/http/client.py&quot;, line 1302, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File &quot;/var/lang/lib/python3.8/http/client.py&quot;, line 1251, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File &quot;/var/runtime/botocore/awsrequest.py&quot;, line 120, in _send_output self.send(msg) File &quot;/var/runtime/botocore/awsrequest.py&quot;, line 204, in send return super(AWSConnection, self).send(str) File &quot;/var/lang/lib/python3.8/http/client.py&quot;, line 951, in send self.connect() File &quot;/var/task/urllib3/connection.py&quot;, line 205, in connect conn = self._new_conn() File &quot;/var/task/urllib3/connection.py&quot;, line 186, in _new_conn raise NewConnectionError( urllib3.exceptions.NewConnectionError: &lt;botocore.awsrequest.AWSHTTPConnection object at 0x7f2c317e2100&gt;: Failed to establish a new connection: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;/var/runtime/botocore/retryhandler.py&quot;, line 269, in _should_retry return self._checker(attempt_number, response, caught_exception) File &quot;/var/runtime/botocore/retryhandler.py&quot;, line 316, in __call__ checker_response = checker(attempt_number, response, File &quot;/var/runtime/botocore/retryhandler.py&quot;, line 222, in __call__ return self._check_caught_exception( File &quot;/var/runtime/botocore/retryhandler.py&quot;, line 359, in _check_caught_exception raise caught_exception File &quot;/var/runtime/botocore/endpoint.py&quot;, line 201, in _do_get_response http_response = self._send(request) File &quot;/var/runtime/botocore/endpoint.py&quot;, line 270, in _send return self.http_session.send(request) File &quot;/var/runtime/botocore/httpsession.py&quot;, line 438, in send raise EndpointConnectionError(endpoint_url=request.url, error=e) botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: &quot;http://localhost:4566/&quot;[DEBUG] 2022-09-10T11:37:48.741Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Retry needed, action of: 0.15278091352455614 </code></pre> <p>The snippet <code>[DEBUG] 2022-09-10T11:37:48.732Z 3b4786a3-2b51-4213-8611-d6ff374211a2 Sending http request: &lt;AWSPreparedRequest stream_output=False, method=GET, url=http://localhost:4566/, headers={'User-Agent': b'Boto3/1.20.32 Python/3.8.13 Linux/5.15.0-46-generic exec-env/AWS_Lambda_python3.8 Botocore/1.23.32', 'X-Amz-Date': b'20220910T113748Z', 'X-Amz-Content-SHA256': b'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'Authorization': b'AWS4-HMAC-SHA256 Credential=test/20220910/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=ffe5af8ae43d86e0dff2c991546d722f70f886d8b49565467a607b20ef433042'}&gt;</code> confirms that the right address and credentials are submitted.</p> <p>I've also found a way to generate logs for my local script, but I cannot make out any significant difference:</p> <pre><code>2022-09-10 17:26:10,363 botocore.hooks [DEBUG] Changing event name from creating-client-class.iot-data to creating-client-class.iot-data-plane 2022-09-10 17:26:10,365 botocore.hooks [DEBUG] Changing event name from before-call.apigateway to before-call.api-gateway 2022-09-10 17:26:10,366 botocore.hooks [DEBUG] Changing event name from request-created.machinelearning.Predict to request-created.machine-learning.Predict 2022-09-10 17:26:10,367 botocore.hooks [DEBUG] Changing event name from before-parameter-build.autoscaling.CreateLaunchConfiguration to before-parameter-build.auto-scaling.CreateLaunchConfiguration 2022-09-10 17:26:10,367 botocore.hooks [DEBUG] Changing event name from before-parameter-build.route53 to before-parameter-build.route-53 2022-09-10 17:26:10,368 botocore.hooks [DEBUG] Changing event name from request-created.cloudsearchdomain.Search to request-created.cloudsearch-domain.Search 2022-09-10 17:26:10,369 botocore.hooks [DEBUG] Changing event name from docs.*.autoscaling.CreateLaunchConfiguration.complete-section to docs.*.auto-scaling.CreateLaunchConfiguration.complete-section 2022-09-10 17:26:10,370 botocore.hooks [DEBUG] Changing event name from before-parameter-build.logs.CreateExportTask to before-parameter-build.cloudwatch-logs.CreateExportTask 2022-09-10 17:26:10,371 botocore.hooks [DEBUG] Changing event name from docs.*.logs.CreateExportTask.complete-section to docs.*.cloudwatch-logs.CreateExportTask.complete-section 2022-09-10 17:26:10,371 botocore.hooks [DEBUG] Changing event name from before-parameter-build.cloudsearchdomain.Search to before-parameter-build.cloudsearch-domain.Search 2022-09-10 17:26:10,371 botocore.hooks [DEBUG] Changing event name from docs.*.cloudsearchdomain.Search.complete-section to docs.*.cloudsearch-domain.Search.complete-section 2022-09-10 17:26:10,376 botocore.utils [DEBUG] IMDS ENDPOINT: http://169.254.169.254/ 2022-09-10 17:26:10,377 botocore.credentials [DEBUG] Looking for credentials via: env 2022-09-10 17:26:10,377 botocore.credentials [DEBUG] Looking for credentials via: assume-role 2022-09-10 17:26:10,377 botocore.credentials [DEBUG] Looking for credentials via: assume-role-with-web-identity 2022-09-10 17:26:10,377 botocore.credentials [DEBUG] Looking for credentials via: sso 2022-09-10 17:26:10,377 botocore.credentials [DEBUG] Looking for credentials via: shared-credentials-file 2022-09-10 17:26:10,378 botocore.credentials [INFO] Found credentials in shared credentials file: ~/.aws/credentials 2022-09-10 17:26:10,378 botocore.loaders [DEBUG] Loading JSON file: /home/.../sam_bucket_fetch/samvenv/lib/python3.8/site-packages/botocore/data/endpoints.json 2022-09-10 17:26:10,390 botocore.loaders [DEBUG] Loading JSON file: /home/.../sam_bucket_fetch/samvenv/lib/python3.8/site-packages/botocore/data/sdk-default-configuration.json 2022-09-10 17:26:10,390 botocore.hooks [DEBUG] Event choose-service-name: calling handler &lt;function handle_service_name_alias at 0x7fa830c424c0&gt; 2022-09-10 17:26:10,400 botocore.loaders [DEBUG] Loading JSON file: /home/.../sam_bucket_fetch/samvenv/lib/python3.8/site-packages/botocore/data/s3/2006-03-01/service-2.json 2022-09-10 17:26:10,408 botocore.hooks [DEBUG] Event creating-client-class.s3: calling handler &lt;function add_generate_presigned_post at 0x7fa830cbcd30&gt; 2022-09-10 17:26:10,408 botocore.hooks [DEBUG] Event creating-client-class.s3: calling handler &lt;function lazy_call.&lt;locals&gt;._handler at 0x7fa830b7e160&gt; 2022-09-10 17:26:10,422 botocore.hooks [DEBUG] Event creating-client-class.s3: calling handler &lt;function add_generate_presigned_url at 0x7fa830cbcaf0&gt; 2022-09-10 17:26:10,424 botocore.endpoint [DEBUG] Setting s3 timeout as (60, 60) 2022-09-10 17:26:10,424 botocore.loaders [DEBUG] Loading JSON file: /home/.../sam_bucket_fetch/samvenv/lib/python3.8/site-packages/botocore/data/_retry.json 2022-09-10 17:26:10,424 botocore.client [DEBUG] Registering retry handlers for service: s3 2022-09-10 17:26:10,425 botocore.hooks [DEBUG] Event before-parameter-build.s3.ListBuckets: calling handler &lt;function validate_bucket_name at 0x7fa830c5cca0&gt; 2022-09-10 17:26:10,425 botocore.hooks [DEBUG] Event before-parameter-build.s3.ListBuckets: calling handler &lt;bound method S3RegionRedirector.redirect_from_cache of &lt;botocore.utils.S3RegionRedirector object at 0x7fa83039d6a0&gt;&gt; 2022-09-10 17:26:10,425 botocore.hooks [DEBUG] Event before-parameter-build.s3.ListBuckets: calling handler &lt;bound method S3ArnParamHandler.handle_arn of &lt;botocore.utils.S3ArnParamHandler object at 0x7fa83039d760&gt;&gt; 2022-09-10 17:26:10,425 botocore.hooks [DEBUG] Event before-parameter-build.s3.ListBuckets: calling handler &lt;function generate_idempotent_uuid at 0x7fa830c5caf0&gt; 2022-09-10 17:26:10,426 botocore.hooks [DEBUG] Event before-call.s3.ListBuckets: calling handler &lt;function add_expect_header at 0x7fa830c62040&gt; 2022-09-10 17:26:10,426 botocore.hooks [DEBUG] Event before-call.s3.ListBuckets: calling handler &lt;bound method S3RegionRedirector.set_request_url of &lt;botocore.utils.S3RegionRedirector object at 0x7fa83039d6a0&gt;&gt; 2022-09-10 17:26:10,426 botocore.hooks [DEBUG] Event before-call.s3.ListBuckets: calling handler &lt;function add_recursion_detection_header at 0x7fa830c5c790&gt; 2022-09-10 17:26:10,426 botocore.hooks [DEBUG] Event before-call.s3.ListBuckets: calling handler &lt;function inject_api_version_header_if_needed at 0x7fa830c5e3a0&gt; 2022-09-10 17:26:10,426 botocore.endpoint [DEBUG] Making request for OperationModel(name=ListBuckets) with params: {'url_path': '/', 'query_string': '', 'method': 'GET', 'headers': {'User-Agent': 'Boto3/1.24.69 Python/3.8.10 Linux/5.15.0-46-generic Botocore/1.27.69'}, 'body': b'', 'url': 'http://localhost:4566/', 'context': {'client_region': 'us-east-1', 'client_config': &lt;botocore.config.Config object at 0x7fa830544880&gt;, 'has_streaming_input': False, 'auth_type': None, 'signing': {'bucket': None}}} 2022-09-10 17:26:10,426 botocore.hooks [DEBUG] Event request-created.s3.ListBuckets: calling handler &lt;bound method RequestSigner.handler of &lt;botocore.signers.RequestSigner object at 0x7fa8305448b0&gt;&gt; 2022-09-10 17:26:10,426 botocore.hooks [DEBUG] Event choose-signer.s3.ListBuckets: calling handler &lt;bound method S3EndpointSetter.set_signer of &lt;botocore.utils.S3EndpointSetter object at 0x7fa83039d7f0&gt;&gt; 2022-09-10 17:26:10,426 botocore.hooks [DEBUG] Event choose-signer.s3.ListBuckets: calling handler &lt;bound method ClientCreator._default_s3_presign_to_sigv2 of &lt;botocore.client.ClientCreator object at 0x7fa830b7c9a0&gt;&gt; 2022-09-10 17:26:10,426 botocore.hooks [DEBUG] Event choose-signer.s3.ListBuckets: calling handler &lt;function set_operation_specific_signer at 0x7fa830c5c9d0&gt; 2022-09-10 17:26:10,426 botocore.hooks [DEBUG] Event before-sign.s3.ListBuckets: calling handler &lt;bound method S3EndpointSetter.set_endpoint of &lt;botocore.utils.S3EndpointSetter object at 0x7fa83039d7f0&gt;&gt; 2022-09-10 17:26:10,426 botocore.utils [DEBUG] Using S3 path style addressing. 2022-09-10 17:26:10,426 botocore.auth [DEBUG] Calculating signature using v4 auth. 2022-09-10 17:26:10,427 botocore.auth [DEBUG] CanonicalRequest: GET / host:localhost:4566 x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 x-amz-date:20220910T152610Z host;x-amz-content-sha256;x-amz-date e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 2022-09-10 17:26:10,427 botocore.auth [DEBUG] StringToSign: AWS4-HMAC-SHA256 20220910T152610Z 20220910/us-east-1/s3/aws4_request d92a569143f1a1e667c82b75387a5c934a1827c0fe066ad45d5456e68e611c0f 2022-09-10 17:26:10,427 botocore.auth [DEBUG] Signature: cc00ece2c2d811961014abd7d8d94d89bf00bf79451984ed4d441d02f23aff74 2022-09-10 17:26:10,427 botocore.hooks [DEBUG] Event request-created.s3.ListBuckets: calling handler &lt;function add_retry_headers at 0x7fa830c5ea60&gt; 2022-09-10 17:26:10,427 botocore.endpoint [DEBUG] Sending http request: &lt;AWSPreparedRequest stream_output=False, method=GET, url=http://localhost:4566/, headers={'User-Agent': b'Boto3/1.24.69 Python/3.8.10 Linux/5.15.0-46-generic Botocore/1.27.69', 'X-Amz-Date': b'20220910T152610Z', 'X-Amz-Content-SHA256': b'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'Authorization': b'AWS4-HMAC-SHA256 Credential=test/20220910/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=cc00ece2c2d811961014abd7d8d94d89bf00bf79451984ed4d441d02f23aff74', 'amz-sdk-invocation-id': b'bc337f23-16ed-45b4-a4fc-35ef791b8ca8', 'amz-sdk-request': b'attempt=1'}&gt; 2022-09-10 17:26:10,427 urllib3.connectionpool [DEBUG] Starting new HTTP connection (1): localhost:4566 2022-09-10 17:26:10,437 urllib3.connectionpool [DEBUG] http://localhost:4566 &quot;GET / HTTP/1.1&quot; 200 None 2022-09-10 17:26:10,437 botocore.parsers [DEBUG] Response headers: {'Content-Type': 'application/xml; charset=utf-8', 'Server': 'Werkzeug/2.1.2 Python/3.10.6, hypercorn-h11', 'Date': 'Sat, 10 Sep 2022 15:26:10 GMT, Sat, 10 Sep 2022 15:26:10 GMT', 'x-amzn-requestid': 'OOV6T6D0GMR5UGEOFRVJZT7M4HERBJIRJU7KNCFOK8MA8W6WS6O3', 'Access-Control-Allow-Origin': '*', 'Connection': 'close', 'Last-Modified': 'Sat, 10 Sep 2022 15:26:10 GMT', 'x-amz-request-id': 'C1AC97638736B0D5', 'x-amz-id-2': 'MzRISOwyjmnupC1AC97638736B0D57/JypPGXLh0OVFGcJaaO3KW/hRAqKOpIEEp', 'accept-ranges': 'bytes', 'content-language': 'en-US', 'Transfer-Encoding': 'chunked'} 2022-09-10 17:26:10,437 botocore.parsers [DEBUG] Response body: b'&lt;ListAllMyBucketsResult xmlns=&quot;http://s3.amazonaws.com/doc/2006-03-01&quot;&gt;&lt;Owner&gt;&lt;ID&gt;bcaf1ffd86f41161ca5fb16fd081034f&lt;/ID&gt;&lt;DisplayName&gt;webfile&lt;/DisplayName&gt;&lt;/Owner&gt;&lt;Buckets&gt;&lt;Bucket&gt;&lt;Name&gt;mybucket&lt;/Name&gt;&lt;CreationDate&gt;2022-09-10T10:46:41.000Z&lt;/CreationDate&gt;&lt;/Bucket&gt;&lt;/Buckets&gt;&lt;/ListAllMyBucketsResult&gt;' 2022-09-10 17:26:10,438 botocore.hooks [DEBUG] Event needs-retry.s3.ListBuckets: calling handler &lt;botocore.retryhandler.RetryHandler object at 0x7fa83039d640&gt; 2022-09-10 17:26:10,438 botocore.retryhandler [DEBUG] No retry needed. 2022-09-10 17:26:10,438 botocore.hooks [DEBUG] Event needs-retry.s3.ListBuckets: calling handler &lt;bound method S3RegionRedirector.redirect_from_error of &lt;botocore.utils.S3RegionRedirector object at 0x7fa83039d6a0&gt;&gt; </code></pre>
3
12,460
WPF circular progress bar: how to move hard coded property
<p>In my application i am using <code>Circular progress-bar</code>. So in case i want to use this controller in several places how can i set the <code>Radius</code> property in my <code>XAML</code> instead of using the current value which is all the time 100 ? (in class <code>CircularProgressBar</code>)</p> <p>This is my <code>Circular progress bar</code>:</p> <pre><code>&lt;UserControl x:Class="myApplication.CircularProgressBar" x:Name="userControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"&gt; &lt;Grid&gt; &lt;Grid&gt; &lt;Path x:Name="pathRoot" Stroke="{Binding SegmentColor, ElementName=userControl}" StrokeThickness="{Binding StrokeThickness, ElementName=userControl}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="100" Width="100"&gt; &lt;Path.Data&gt; &lt;PathGeometry&gt; &lt;PathGeometry.Figures&gt; &lt;PathFigureCollection&gt; &lt;PathFigure x:Name="pathFigure"&gt; &lt;PathFigure.Segments&gt; &lt;PathSegmentCollection&gt; &lt;ArcSegment x:Name="arcSegment" SweepDirection="Clockwise" /&gt; &lt;/PathSegmentCollection&gt; &lt;/PathFigure.Segments&gt; &lt;/PathFigure&gt; &lt;/PathFigureCollection&gt; &lt;/PathGeometry.Figures&gt; &lt;/PathGeometry&gt; &lt;/Path.Data&gt; &lt;/Path&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <hr> <pre><code>public partial class CircularProgressBar : UserControl { public CircularProgressBar() { InitializeComponent(); Angle = (Percentage * 360) / 100; RenderArc(); } public int Radius { get { return (int)GetValue(RadiusProperty); } set { SetValue(RadiusProperty, value); } } public Brush SegmentColor { get { return (Brush)GetValue(SegmentColorProperty); } set { SetValue(SegmentColorProperty, value); } } public int StrokeThickness { get { return (int)GetValue(StrokeThicknessProperty); } set { SetValue(StrokeThicknessProperty, value); } } public double Percentage { get { return (double)GetValue(PercentageProperty); } set { SetValue(PercentageProperty, value); } } public double Angle { get { return (double)GetValue(AngleProperty); } set { SetValue(AngleProperty, value); } } public enum Modes { Full = 360, Half = 180, Intermediate = 250 } public Modes CircularMode { get { return (Modes)GetValue(CircularModeProperty); } set { SetValue(CircularModeProperty, value); } } public static readonly DependencyProperty CircularModeProperty = DependencyProperty.Register("CircularMode", typeof(Modes), typeof(CircularProgressBar), new PropertyMetadata(Modes.Full)); // Using a DependencyProperty as the backing store for Percentage. This enables animation, styling, binding, etc... public static readonly DependencyProperty PercentageProperty = DependencyProperty.Register("Percentage", typeof(double), typeof(CircularProgressBar), new PropertyMetadata(65d, new PropertyChangedCallback(OnPercentageChanged))); // Using a DependencyProperty as the backing store for StrokeThickness. This enables animation, styling, binding, etc... public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register("StrokeThickness", typeof(int), typeof(CircularProgressBar), new PropertyMetadata(1)); // Using a DependencyProperty as the backing store for SegmentColor. This enables animation, styling, binding, etc... public static readonly DependencyProperty SegmentColorProperty = DependencyProperty.Register("SegmentColor", typeof(Brush), typeof(CircularProgressBar), new PropertyMetadata(new SolidColorBrush(Colors.Red))); // Using a DependencyProperty as the backing store for Radius. This enables animation, styling, binding, etc... public static readonly DependencyProperty RadiusProperty = DependencyProperty.Register("Radius", typeof(int), typeof(CircularProgressBar), new PropertyMetadata(100, new PropertyChangedCallback(OnPropertyChanged))); // Using a DependencyProperty as the backing store for Angle. This enables animation, styling, binding, etc... public static readonly DependencyProperty AngleProperty = DependencyProperty.Register("Angle", typeof(double), typeof(CircularProgressBar), new PropertyMetadata(120d, new PropertyChangedCallback(OnPropertyChanged))); private static void OnPercentageChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { CircularProgressBar circle = sender as CircularProgressBar; circle.Angle = (circle.Percentage * (int)circle.CircularMode) / 100; } private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { CircularProgressBar circle = sender as CircularProgressBar; circle.RenderArc(); } public void RenderArc() { Point startPoint = new Point(Radius, 0); Point endPoint = ComputeCartesianCoordinate(Angle, Radius); endPoint.X += Radius; endPoint.Y += Radius; pathRoot.Width = Radius * 2 + StrokeThickness; pathRoot.Height = Radius * 2 + StrokeThickness; pathRoot.Margin = new Thickness(StrokeThickness, StrokeThickness, 0, 0); bool largeArc = Angle &gt; 180.0; Size outerArcSize = new Size(Radius, Radius); pathFigure.StartPoint = startPoint; if (startPoint.X == Math.Round(endPoint.X) &amp;&amp; startPoint.Y == Math.Round(endPoint.Y)) endPoint.X -= 0.01; arcSegment.Point = endPoint; arcSegment.Size = outerArcSize; arcSegment.IsLargeArc = largeArc; } private Point ComputeCartesianCoordinate(double angle, double radius) { // convert to radians double angleRad = (Math.PI / 180.0) * (angle - 90); double x = radius * Math.Cos(angleRad); double y = radius * Math.Sin(angleRad); return new Point(x, y); } } </code></pre> <p>This is the hard code value:</p> <pre><code>// Using a DependencyProperty as the backing store for Radius. This enables animation, styling, binding, etc... public static readonly DependencyProperty RadiusProperty = DependencyProperty.Register("Radius", typeof(int), typeof(CircularProgressBar), new PropertyMetadata(100, new PropertyChangedCallback(OnPropertyChanged))); </code></pre>
3
3,350
Smooth scroll anchor link requires unwanted double click
<p>Hey I'm trying to fix a tab inspired page for mobile. When the user clicks on a round circle it should ge to the text. Than when you click "Terug naar keuzemenu" you should go back to the circles (the navigation of the tabs). However when I want to go to other tabs the first time I click he doesnt scroll to the text section but the second time he does. So i have to click twice but cant figure out why.</p> <p>FIDDLE</p> <p><a href="https://jsfiddle.net/Ljv5a2ez/2/" rel="nofollow">https://jsfiddle.net/Ljv5a2ez/2/</a></p> <p>HTML</p> <pre><code>&lt;div class="span12" id="xx-content"&gt; &lt;div class="clearfix row-fluid"&gt; &lt;div class="xx_content_inner"&gt; &lt;div class="xx_row-12" id="aj_logobox"&gt; &lt;div class="span3"&gt; &lt;div class="xx_active check-up-overview" id="lente"&gt; &lt;div class="xx_logo_container"&gt; &lt;div class="xx_logo_inner"&gt; &lt;a href="#hometext"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/home_delivery.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="span3"&gt; &lt;div class="check-up-overview" id="full"&gt; &lt;div class="xx_logo_container"&gt; &lt;div class="xx_logo_inner"&gt; &lt;a href="#collecttext"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/click_and_collect.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="span3"&gt; &lt;div class="check-up-overview" id="pro"&gt; &lt;div class="xx_logo_container"&gt; &lt;div class="xx_logo_inner"&gt; &lt;a href="#moretext"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/look_for_more.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="span3"&gt; &lt;div class="check-up-overview" id="ebike"&gt; &lt;div class="xx_logo_container"&gt; &lt;div class="xx_logo_inner"&gt; &lt;a href="#smarttext"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/smartpay_cirkel.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="xx_row-2 lente bike-show" id="hometext"&gt; &lt;p&gt;&lt;span class="xx_title" id="title"&gt;&lt;h2 class="aj_h2fix"&gt;Gratis thuis leveren vanuit je A.S.Adventure Store&lt;/h2&gt;&lt;/span&gt;&lt;/p&gt; &lt;p class="xx_excl"&gt;Sta je in de winkel en is het product van je dromen niet meer beschikbaar in een andere maat of kleur?&lt;br&gt; Geen nood: indien voorradig in een andere A.S.Adventure Store, &lt;strong&gt;bestellen&lt;/strong&gt; we het gewenste product in de Store en &lt;strong&gt;leveren&lt;/strong&gt; we het &lt;strong&gt;gratis&lt;/strong&gt;&lt;br&gt; op een &lt;strong&gt;adres naar keuze&lt;/strong&gt;. Van service gesproken.&lt;/p&gt; &lt;/div&gt; &lt;div class="xx_row-2 full bike-hide" id="collecttext"&gt; &lt;p&gt;&lt;span class="xx_title" id="title"&gt;&lt;h2 class="aj_h2fix"&gt;Maak je keuze online en haal je bestelling op in de winkel&lt;/h2&gt;&lt;/span&gt;&lt;/p&gt; &lt;p class="xx_excl"&gt;Vanuit je luie zetel shoppen? Winkelen bij A.S.Adventure kun je altijd en overal. Wil je helemaal zeker zijn van de maat of kleur?&lt;br&gt; &lt;strong&gt;Reserveer online zonder aankoopverplichting&lt;/strong&gt; via de Click &amp;amp; Collect service en haal je bestelling later op in jouw&lt;br&gt; &lt;strong&gt;favoriete A.S.Adventure Store&lt;/strong&gt;. Je kiest zelf wat je wel of niet koopt.&lt;/p&gt; &lt;/div&gt; &lt;div class="xx_row-2 pro bike-hide" id="moretext"&gt; &lt;p&gt;&lt;span class="xx_title" id="title"&gt;&lt;h2 class="aj_h2fix"&gt;Ontdek een nog uitgebreider aanbod in onze webshop&lt;/h2&gt;&lt;/span&gt;&lt;/p&gt; &lt;p class="xx_excl"&gt;Dacht je dat je alles al gezien had in onze Stores? Think again! In &lt;strong&gt;onze webshop vind&lt;/strong&gt; je van de onderstaande merken een &lt;strong&gt;nog uitgebreider aanbod&lt;/strong&gt;. &lt;br&gt;Gebruik de schermen in de Stores om naar de webshop te surfen of grasduin online door ons aanbod.&lt;br&gt; Keuze gemaakt? Laat je producten dan &lt;strong&gt;gratis afleveren&lt;/strong&gt; via Home Delivery.&lt;/p&gt; &lt;/div&gt; &lt;div class="xx_row-2 ebike bike-hide" id="smarttext"&gt; &lt;p&gt;&lt;span class="xx_title" id="title"&gt;&lt;h2 class="aj_h2fix"&gt;Betaal je aankopen in de winkel met je smartphone&lt;/h2&gt;&lt;/span&gt;&lt;/p&gt; &lt;p class="xx_excl"&gt;Merk je tijdens het winkelen dat je je portefeuille bent vergeten? Geen nood, vanaf nu kun je &lt;strong&gt;in alle A.S.Adventure Stores ook betalen met SmartPay&lt;/strong&gt;. &lt;br&gt;Even je &lt;strong&gt;smartphone&lt;/strong&gt; opdiepen, de &lt;strong&gt;Bancontact-app&lt;/strong&gt; openen en de &lt;strong&gt;unieke QR-code&lt;/strong&gt; aan de kassa inscannen. &lt;br&gt;Je hoeft dan alleen nog even de betaling te bevestigen met je pincode. Makkelijk, veilig en effici&amp;euml;nt!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="clearfix row-fluid lente bike-show"&gt; &lt;div class="xx_row-3"&gt; &lt;div class="span12"&gt; &lt;div class="xx_span_inner xx_top"&gt; &lt;h3&gt;Hoe werkt het?&lt;/h3&gt; &lt;ul style="list-style:none;"&gt; &lt;li&gt;&lt;span&gt;1.&lt;/span&gt; We bestellen samen in de Store met jou het gewenste artikel via onze website.&lt;/li&gt; &lt;li&gt;&lt;span&gt;2.&lt;/span&gt; Je betaalt aan de kassa.&lt;/li&gt; &lt;li class="xx_last-item"&gt;&lt;span&gt;3.&lt;/span&gt; Je bestelling wordt enkele dagen later geleverd op een adres naar keuze of bij een afhaalpunt.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;a href="#lente"&gt;Terug naar keuzemenu&lt;/a&gt; &lt;/div&gt; &lt;div class="clearfix row-fluid full bike-hide"&gt; &lt;div class="xx_row-3"&gt; &lt;div class="span12"&gt; &lt;div class="xx_span_inner xx_top"&gt; &lt;h3&gt;Hoe werkt het?&lt;/h3&gt; &lt;ul style="list-style:none;"&gt; &lt;li&gt;&lt;span&gt;1.&lt;/span&gt; Reserveer en betaal je product(en) online.&lt;/li&gt; &lt;li&gt;&lt;span&gt;2.&lt;/span&gt; Kies de winkel waar je je product(en) wenst af te halen.&lt;/li&gt; &lt;li&gt;&lt;span&gt;3.&lt;/span&gt; Je ontvangt via mail een bevestiging van je bestelling.&lt;/li&gt; &lt;li&gt;&lt;span&gt;4.&lt;/span&gt; Via mail of sms verneem je wanneer je product(en) klaarliggen.&lt;/li&gt; &lt;li class="xx_last-item"&gt;&lt;span&gt;5.&lt;/span&gt; Mocht je in de winkel alsnog beslissen je aankoop te annuleren, krijg je onmiddellijk je geld terug.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;a href="#lente"&gt;Terug naar keuzemenu&lt;/a&gt; &lt;/div&gt; &lt;div class="clearfix row-fluid pro bike-hide"&gt; &lt;div class="xx_row-3"&gt; &lt;div class="span12"&gt; &lt;div class="xx_span_inner xx_top"&gt; &lt;h3&gt;Uitgebreid aanbod:&lt;/h3&gt; &lt;div id="xx_aanbod_logos"&gt; &lt;a alt="Fjallraven" href="http://www.asadventure.com/benl/fjallraven" target="_parent"&gt;&lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_fjallraven.png" /&gt; &lt;/a&gt; &lt;a alt="The North Face" href="http://www.asadventure.com/benl/the-north-face" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_the-north-face.png" /&gt; &lt;/a&gt; &lt;a alt="Vaude" href="http://www.asadventure.com/benl/vaude" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_vaude.png" /&gt; &lt;/a&gt; &lt;a alt="Garmin" href="http://www.asadventure.com/benl/garmin" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_garmin.png" /&gt; &lt;/a&gt; &lt;a alt="Thule" href="http://www.asadventure.com/benl/thule" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_thule.png" /&gt; &lt;/a&gt; &lt;a alt="Eastpak" href="http://www.asadventure.com/benl/eastpak" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_eastpak.png" /&gt; &lt;/a&gt; &lt;a alt="Millet" href="http://www.asadventure.com/benl/millet" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_millet.png" /&gt; &lt;/a&gt; &lt;a alt="Gore Bike wear" href="http://www.asadventure.com/benl/gore-bike-wear" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_gore_bike.png" /&gt; &lt;/a&gt; &lt;a alt="Gore Running wear" href="http://www.asadventure.com/benl/gore-running-wear" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_gore_running.png" /&gt; &lt;/a&gt; &lt;a alt="Mi-Pac" href="http://www.asadventure.com/benl/mi-pac" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_mi-pac.png" /&gt; &lt;/a&gt; &lt;br&gt; &lt;a alt="Suunto" href="http://www.asadventure.com/benl/suunto" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_suunto.png" /&gt; &lt;/a&gt; &lt;a alt="Polar" href="http://www.asadventure.com/benl/polar" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_polar.png" /&gt; &lt;/a&gt; &lt;a alt="Camel Active" href="http://www.asadventure.com/benl/camel-active" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_camel_active.png" /&gt; &lt;/a&gt; &lt;a alt="Dakine" href="http://www.asadventure.com/benl/dakine" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_dakine.png" /&gt; &lt;/a&gt; &lt;a alt="Lowa" href="http://www.asadventure.com/benl/lowa" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_lowa.png" /&gt; &lt;/a&gt; &lt;a alt="CKS" href="http://www.asadventure.com/benl/cks-dames" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_cks_black.png" /&gt; &lt;/a&gt; &lt;a alt="Komono" href="http://www.asadventure.com/benl/komono" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_komono.png" /&gt; &lt;/a&gt; &lt;a alt="Jack Wolfskin" href="http://www.asadventure.com/benl/jack-wolfskin" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_wolfskin.png" /&gt; &lt;/a&gt; &lt;a alt="BakerBridge" href="http://www.asadventure.com/benl/baker-bridge" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_baker-bridge.png" /&gt; &lt;/a&gt; &lt;a alt="BakerBridge Dames" href="http://www.asadventure.com/benl/baker-bridge-dames" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_baker-bridge-dames.png" /&gt; &lt;/a&gt; &lt;a alt="Bergans" href="http://www.asadventure.com/benl/bergans" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_bergans.png" /&gt; &lt;/a&gt; &lt;a alt="Van Hassels" href="http://www.asadventure.com/benl/van-hassels" target="_parent"&gt; &lt;img src="http://www1.asadventure.com/headoffice/13-ASA-2374/img/logo_van-hassels.png" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;a href="#lente"&gt;Terug naar keuzemenu&lt;/a&gt; &lt;/div&gt; &lt;div class="clearfix row-fluid ebike bike-hide"&gt; &lt;div class="xx_row-3"&gt; &lt;div class="span12"&gt; &lt;div class="xx_span_inner xx_top"&gt; &lt;h3&gt;Hoe werkt het?&lt;/h3&gt; &lt;ul style="list-style:none;"&gt; &lt;li&gt;&lt;span&gt;1.&lt;/span&gt; Installeer de Bancontact-app op je smartphone:&lt;/li&gt; &lt;li&gt;&lt;span&gt;&lt;/span&gt;&lt;a target="_blank" href="https://play.google.com/store/apps/details?id=mobi.inthepocket.bcmc.bancontact&amp;hl=en"&gt;Google Play &gt;&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;span&gt;&lt;/span&gt;&lt;a target="_blank" href="https://itunes.apple.com/be/app/bancontact-mobile/id858371800?l=en&amp;mt=8"&gt;Apple App Store &gt;&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;span&gt;&lt;/span&gt;&lt;a target="_blank" href="https://www.microsoft.com/en-gb/store/apps/bancontact/9nblggh3fvl1"&gt;Microsoft Store &gt;&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;span&gt;2.&lt;/span&gt; Open de Bancontact&amp;#45;app en volg de instructies om de app te activeren en je bankkaart(en) toe te voegen.&lt;/li&gt; &lt;li&gt;&lt;span&gt;3.&lt;/span&gt; Aan de kassa scan je de unieke QR&amp;#45;code die op de betaalterminal verschijnt om je betaling te bevestigen.&lt;br&gt; Dat kan gewoon vanuit de Bancontact&amp;#45;app.&lt;/li&gt; &lt;li&gt;&lt;span&gt;4.&lt;/span&gt; Je smartphone toont de naam van de winkel en het te betalen bedrag op het scherm.&lt;/li&gt; &lt;li class="xx_last-item"&gt;&lt;span&gt;5.&lt;/span&gt; Druk op OK, geef je pincode op in de app en je krijgt een bevestigingsbericht te zien op je telefoon. Transactie geslaagd!&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;a href="#lente"&gt;Terug naar keuzemenu&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>JS TABS</p> <pre><code>$(document).ready(function () { $('.check-up-overview').click(function () { if (!$(this).hasClass('xx_active')) { var sCurrent = $(this).attr('id'); var sPrevious = $('.xx_active').attr('id'); $('.xx_active').removeClass('xx_active'); $('.' + sPrevious).removeClass('bike-show').addClass('bike-hide'); $(this).addClass('xx_active'); $('.' + sCurrent).removeClass('bike-hide').addClass('bike-show'); } }); }); </code></pre> <p>JS SMOOTH</p> <pre><code>$(document).ready(function(){ $('a[href^="#"]').on('click',function (e) { e.preventDefault(); var target = this.hash; $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top //no need of parseInt here }, 900, 'swing', function () { window.location.hash = target; }); }); }); </code></pre>
3
9,548
Eliminate Half Strings when receiving from Server socket Buffer in JAVA
<p>I have written a simple NIO Server and Inner-Client (Inside the same program)in a single program such that Server receives data from outside and the Inner-Client sends the data received by the server to out side Server. I am running both the processes continuously in two parallel threads using While() loops. Now the problem is, I will be receiving data at a very high speed to the Inside server and everything I receive, I will send them to the outer server using the Inside client. Some times, the retrieval of the data from the Buffer resulting in half the size of the total string. That means I am receiving "HELLO", but the total string is "HELLO SERVER". This is just an example. I will receive very long strings. Similarly, after sending the data to Outer-server through Inner client I will be listening for data and I am receiving the same half-strings.Is there any way I can eliminate these Half-strings and get the full-length string. I have to get the full string without any fail.</p> <p>I am using while loops for the process. This is making the CPU utilization go high like 50%. Is there any way I can reduce the CPU utilization without using Thread.sleep method? Because I need to continuously listen to data from the Outer parties. They may send 2-4 strings for one single request. I tried using Executor service thread for running the processes continuously but it requires some sleep to be included. If I include some sleep I am not able to get the String and if I don't include the sleep my CPU-Utilization is going very high (50-60%). Can anyone help me with these two issues? </p> <p>Here is my code:</p> <pre><code>import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class Main { static SocketChannel channel; public static void main(String[] args) throws IOException { System.out.println("Listening for connections on : 8888"); //8888 ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.bind(new InetSocketAddress(8888)); channel = serverChannel.accept(); System.out.println("Connected..."); channel.setOption(StandardSocketOptions.TCP_NODELAY, true); channel.configureBlocking(false); ReceiveFromOMS receivefromOMS; SendToExchange sendExchange; receivefromOMS = new ReceiveFromOMS(); sendExchange = new SendToExchange(); Thread t1 = new Thread(receivefromOMS); Thread t2 = new Thread(sendExchange); t1.start(); t2.start(); } } class ReceiveFromOMS extends Thread{ public static SocketChannel channel; static ByteBuffer buffer = ByteBuffer.allocate(1024); static ServerSocketChannel serverChannel ; public static int ReceiveFromOMSPort; BlockingQueue&lt;String&gt; fromOMSqueue = new LinkedBlockingQueue&lt;&gt;(30); @Override public void run(){ while(true){ try { receiveFromOMS(); } catch (InterruptedException ex) { System.err.println(ex.getMessage()); try { Thread.sleep(5000); } catch (InterruptedException ex1) { } } } } public void receiveFromOMS() throws InterruptedException{ try { int numRead = -1; numRead = channel.read(buffer); while(numRead==0){ numRead = channel.read(buffer); } if (numRead == -1) { Socket socket = channel.socket(); SocketAddress remoteAddr = socket.getRemoteSocketAddress(); System.out.println("Connection closed by client: " + remoteAddr); channel.close(); return; } byte[] data = new byte[numRead]; System.arraycopy(buffer.array(), 0, data, 0, numRead); fromOMSqueue.add(new String(data)); String msg = fromOMSqueue.poll(); System.out.println("OutGoing To Exchange&gt;&gt; " + msg); SendToExchange.sendToEchange(msg); buffer.flip(); buffer.clear(); } catch (IOException ex) { System.err.println(ex.getMessage()); Thread.sleep(5000); } } } class SendToExchange extends Thread{ static SocketChannel channel; static ByteBuffer bb = ByteBuffer.allocateDirect(1024); static Charset charset = Charset.forName("UTF-8"); public byte[] data; public static String message; @Override public void run(){ try { while(true){ receive(); Thread.sleep(100); } } catch (IOException | InterruptedException ex) { System.err.println(ex.getMessage()); try { Thread.sleep(5000); } catch (InterruptedException ex1) {} } } public static void sendToEchange(String msg){ try { bb = stringToByteBuffer(msg, charset); channel.write(bb); } catch (IOException ex) { System.err.println(ex.getMessage()); } } public void receive() throws IOException { ByteBuffer buffer = ByteBuffer.allocateDirect(1024); int numRead = -1; numRead = channel.read(buffer); while (numRead == 0) { numRead = channel.read(buffer); } if (numRead == -1) { Socket socket = channel.socket(); SocketAddress remoteAddr = socket.getRemoteSocketAddress(); System.out.println("Connection closed by Exchange: " + remoteAddr); channel.close(); return; } buffer.flip(); data = new byte[numRead]; buffer.get(data); message = new String(data); System.out.println("Incoming from Exchange&gt;&gt; " + message); buffer.clear(); } public static ByteBuffer stringToByteBuffer(String msg, Charset charset){ return ByteBuffer.wrap(msg.getBytes(charset)); } } </code></pre>
3
2,532
Why am I getting an "Items Collection Must Be Empty" exception with nested DataGrids?
<p>I'm using nested DataGrids to manage classes with nested class collections.</p> <p>Each nested class is represented by a cell template.</p> <p>This is a minimal mockup which reproduces the issue : </p> <pre><code>using System.ComponentModel; using System.Linq; namespace ICMBE{ public class Outer : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private Nested1[ ] _categories = Enumerable.Range( 1, 1 ).Select( n =&gt; new Nested1( ) ).ToArray( ); public Nested1[ ] Categories { get { return this._categories; } } } public class Nested1 : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private Nested2[ ] _questions = Enumerable.Range( 1, 5 ).Select( n =&gt; new Nested2( ) ).ToArray( ); public Nested2[ ] Questions { get { return this._questions; } } } public class Nested2 : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private Nested3[] _answers = Enumerable.Range( 1, 5 ).Select( n =&gt; new Nested3( ) ).ToArray( ); public Nested3[ ] Answers { get { return this._answers; } } } public class Nested3 : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _foo = "Bar"; public string Foo { get { return this._foo; } } } } </code></pre> <p>Create a field value and expose it in the application : </p> <pre><code>using System.ComponentModel; namespace IMCBE{ public partial class App : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private Outer _outer = new Outer( ); } } namespace IMCBE{ public partial class Program { /// &lt;summary&gt; /// Bla bla bla /// &lt;/summary&gt; public Outer Outer{ get { return this._outer; } } } } </code></pre> <p>Using this window - </p> <pre><code>&lt;Window x:Class="ICMBE.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Controls="clr-namespace:WPFTools.Controls;assembly=WPFTools" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WhyAreMyRowNumbersChanging" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"&gt; &lt;Window.Resources&gt; &lt;!-- Answers --&gt; &lt;DataTemplate x:Key="dtAnswerTemplate"&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="100" /&gt; &lt;ColumnDefinition Width="5" /&gt; &lt;ColumnDefinition /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;ToggleButton&gt; &lt;Viewbox&gt; &lt;TextBlock Text="Correct" /&gt; &lt;/Viewbox&gt; &lt;/ToggleButton&gt; &lt;TextBox Text="Bar" /&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;!-- Questions --&gt; &lt;DataTemplate x:Key="dtQuestionTemplate"&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="25" /&gt; &lt;RowDefinition Height="5" /&gt; &lt;RowDefinition Height="25" /&gt; &lt;RowDefinition Height="5" /&gt; &lt;RowDefinition Height="50" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="128" /&gt; &lt;ColumnDefinition Width="5" /&gt; &lt;ColumnDefinition Width="128" /&gt; &lt;ColumnDefinition Width="5" /&gt; &lt;ColumnDefinition /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Viewbox Grid.ColumnSpan="3"&gt; &lt;TextBlock Text="Question" /&gt; &lt;/Viewbox&gt; &lt;TextBox Grid.Row="2" Grid.ColumnSpan="3" Text="Foo" /&gt; &lt;ToggleButton Grid.Row="4"&gt; &lt;Viewbox&gt; &lt;TextBlock Text="Bonus" /&gt; &lt;/Viewbox&gt; &lt;/ToggleButton&gt; &lt;Button Grid.Row="4" Grid.Column="2" /&gt; &lt;Viewbox Grid.Column="4"&gt; &lt;TextBlock Text="Answers" /&gt; &lt;/Viewbox&gt; &lt;DataGrid AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" Grid.Column="4" Grid.RowSpan="4" ItemsSource="{Binding Nested}"&gt; &lt;DataGridTemplateColumn Width="*" CellTemplate="{StaticResource dtAnswerTemplate}" /&gt; &lt;/DataGrid&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;!-- Categories --&gt; &lt;DataTemplate x:Key="dtCategoryTemplate"&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="25" /&gt; &lt;RowDefinition /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="256" /&gt; &lt;ColumnDefinition Width="5" /&gt; &lt;ColumnDefinition /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Viewbox&gt; &lt;TextBlock Text="Outer"/&gt; &lt;/Viewbox&gt; &lt;DataGrid AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" Grid.Row="2" Grid.ColumnSpan="3" HeadersVisibility="None" ItemsSource="{Binding Nested}"&gt; &lt;DataGrid.Columns&gt; &lt;DataGridTemplateColumn Width="*" CellTemplate="{StaticResource dtQuestionTemplate}" /&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;DataGrid Grid.Row="1" ItemsSource="{Binding Outer.Nested, Source={x:Static Application.Current}}" MaxHeight="Infinity" ScrollViewer.CanContentScroll="True"&gt; &lt;DataGrid.Columns&gt; &lt;DataGridTemplateColumn Width="*" CellTemplate="{StaticResource dtCategoryTemplate}" /&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; &lt;/Window&gt; </code></pre> <p>Running this causes the program to just crash. The exception is "Items collection must be empty".</p> <p>From what I've read, this happens if you set the <code>Items</code> and <code>ItemsSource</code> are both set, but this isn't happening here.</p> <p>Why is this crash occurring?</p>
3
3,799
Mysqli Query result to variable
<p>I was trying to make a MySQL word with PHP, and I want to call the result into the next page using session. So I can put the result in the ms word file, but the value in <code>"$_SESSION['kode_faskes'] = $d['kode_faskes'];"</code> was stated as <code>null</code>.</p> <blockquote> <p>Notice: Trying to access array offset on the value of type null in C:\xampp\htdocs\test3\index.php on line 80</p> </blockquote> <p>this is the 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>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;?php include 'connection.php'; ?&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="index.php" method="get"&gt; &lt;label&gt; Cari :&lt;/label&gt; &lt;input type="text" name="cari"&gt; &lt;input type="submit" value="cari"&gt; &lt;/form&gt; &lt;?php //search norek if(isset($_GET['cari'])) { $cari = $_GET['cari']; echo "&lt;b&gt;Hasil Pencarian : ".$cari."&lt;/b&gt;"; } ?&gt; &lt;table width="600" border="1"&gt; &lt;?php if(isset($_GET['cari'])) { $cari = $_GET['cari']; $dato = mysqli_query($connect, " SELECT * FROM faskes INNER JOIN pemilik_rekening USING ( norek ) INNER JOIN transaksi USING ( kode_faskes ) WHERE transaksi.norek LIKE '%".$cari."%' "); } else { $dato = mysqli_query($connect, " SELECT * FROM faskes INNER JOIN pemilik_rekening USING ( norek ) INNER JOIN transaksi USING ( kode_faskes ) "); } $no = 1; while($d = mysqli_fetch_array($dato)) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $no++; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $d['kode_faskes']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $d['nama_faskes']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $d['alamat_faskes']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $d['norek']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $d['pemegang_norek']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $d['tanggal_bayar']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $d['jumlah_bayar']; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } session_start(); $_SESSION['cari'] = $cari; $_SESSION['kode_faskes'] = $d['kode_faskes']; ?&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>If you can help me then I would be grateful for this.</p> <p>In addition, I'm deeply sorry about the short explanation.</p>
3
1,219
Why is my JSon giving me nulls on sub-arrays?
<p>I've been having a ghastly time trying to get an incoming Json message to serialize (and deserialize correctly). First is the incoming Json that I'm posting to our MVC rest service via POSTMAN. Validated it through JsonLint. The main problem is the two sub-arrays, accounts and propertyValues come through as null. serviceAddresses is an array member of the profilePush and its other properties are populating. Before I made them all into DataContracts, I was getting null value for serviceAddresses. What am I missing here?</p> <p>------------ Incoming JSON ------------------</p> <pre><code> { "userId" : 15, "firstName" : "Michael", "lastName" : "Smith", "email" : "msmith@google.org", "deleted" : false, "serviceAddresses" : [ { "addressId" : 18, "address1" : "8401 Lorain Road", "address2" : "Suite 10A", "city" : "Newton Falls", "state" : "OH", "zip" : "44021", "deleted" : false, "accounts" : [], "propertyAttributes" : { "attr_name" : "heat_type", "attr_value" : "Gas", "attr_name" : "hot_water_heater_type", "attr_value" : "Gas", "attr_name" : "rent_own", "attr_value" : "Own", "attr_name" : "sq_ft", "attr_value" : "2000", "attr_name" : "stove_type", "attr_value" : "Gas" } } ] } [HttpPost] public JsonResult profileInformationPush(profilePush profile ) { bool bError = false; string s = JsonConvert.SerializeObject(profile); profilePush deserializedProfile = JsonConvert.DeserializeObject&lt;profilePush&gt;(s); } </code></pre> <p>--------This is what "profile" looks like coming in to the procedure --------------</p> <pre><code>{"UserId":15,"FirstName":"Michael","LastName":"Smith","Email":"msmith@google.org","Deleted":"False","ServiceAdresses":[{"AddressId":18,"Address1":"8401 Lorain Road","Address2":"Suite 10A","City":"Newton Falls","State":"OH","Zip":"44021","Deleted":"False","Accounts":null,"PropertyAttributes":null}]} --------------Data Contracts --------------------- [DataContract] public class accountInfo { [DataMember(Name="accountNumber", EmitDefaultValue = false)] public string AccountNumber { get; set; } [DataMember(Name="deleted", EmitDefaultValue = false)] public string Deleted { get; set; } } [DataContract] public class PropertyAttributes { [DataMember(Name="attr_name", EmitDefaultValue = false)] public string Attr_Name { get; set; } [DataMember(Name="attr_value", EmitDefaultValue = false)] public string Attr_Value { get; set; } } [DataContract] public class ServiceAddresses { [DataMember(Name="addressId", EmitDefaultValue = false)] public int AddressId { get; set; } [DataMember(Name="address1", EmitDefaultValue = false)] public string Address1 { get; set; } [DataMember(Name="address2", EmitDefaultValue= false)] public string Address2 { get; set; } [DataMember(Name="city", EmitDefaultValue = false)] public string City { get; set; } [DataMember(Name="state", EmitDefaultValue = false)] public string State { get; set; } [DataMember(Name="zip", EmitDefaultValue = false)] public string Zip { get; set; } [DataMember(Name="deleted", EmitDefaultValue = false)] public string Deleted { get; set; } [DataMember(Name="accounts", EmitDefaultValue = false)] public accountInfo[] Accounts { get; set; } [DataMember(Name = "propertyAttributes", EmitDefaultValue = false)] public PropertyAttributes[] PropertyAttributes { get; set; } } [DataContract] public class profilePush { [DataMember(Name="userId", EmitDefaultValue= false)] public int UserId { get; set; } [DataMember(Name="firstName", EmitDefaultValue = false)] public string FirstName { get; set; } [DataMember(Name="lastName", EmitDefaultValue = false)] public string LastName { get; set; } [DataMember(Name="email", EmitDefaultValue = false)] public string Email { get; set; } [DataMember(Name="deleted", EmitDefaultValue = false)] public string Deleted { get; set; } [DataMember(Name="serviceAddresses", EmitDefaultValue = false)] public ServiceAddresses[] ServiceAddresses { get; set; } } </code></pre>
3
1,801
How can I move an image and scale or resize it in the same activity
<p>how's it going? I was wondering if anyone had any ideas on how to move an image and resize it within the same activity? I setup a listener to move the image and that works well. The commented out code was used to resize the image and that worked well also. But I am struggling to figure out how to implement some kind of GestureDetector or something similar to do both. Here is the code I have so far:</p> <pre><code> private static final String TAG = "CreateOutfitActivity"; Context mContext; ImageView bodyImage, outfitOne, close; Button saveButton; RecyclerView recyclerView; Spinner spinner; FirebaseAuth mAuth; String currentUserID; DatabaseReference privateUserReference; String CategoryKey; List&lt;String&gt; spinnerArray = new ArrayList&lt;&gt;(); private ScaleGestureDetector scaleGestureDetector; ViewGroup rootLayout; private int _xDelta; private int _yDelta; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_outfits); mContext = CreateOutfitActivity.this; deployWidgets(); setupRecyclerView(); setupFirebase(); setupSpinner(); } private void deployWidgets(){ bodyImage = findViewById(R.id.bodyimage); outfitOne = findViewById(R.id.image_view_one); close = findViewById(R.id.close); saveButton = findViewById(R.id.saveButton); recyclerView = findViewById(R.id.outfit_recycler_view); spinner = findViewById(R.id.spinner); outfitOne.bringToFront(); rootLayout = findViewById(R.id.view_root); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(1000, 1000); outfitOne.setLayoutParams(layoutParams); outfitOne.setOnTouchListener(new ChoiceTouchListener()); } private void setupRecyclerView(){ recyclerView.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(linearLayoutManager); } private void setupFirebase(){ mAuth = FirebaseAuth.getInstance(); currentUserID = mAuth.getCurrentUser().getUid(); privateUserReference = FirebaseDatabase.getInstance().getReference().child("private_user"); } private void setupSpinner(){ spinnerArray.add("Cutouts"); spinnerArray.add("All Items"); spinnerArray.add("Accessories"); spinnerArray.add("Athletic"); spinnerArray.add("Casual"); spinnerArray.add("Dresses"); spinnerArray.add("Jackets"); spinnerArray.add("Jewelery"); spinnerArray.add("Other"); spinnerArray.add("Pants"); spinnerArray.add("Purses"); spinnerArray.add("Shirts"); spinnerArray.add("Shoes"); spinnerArray.add("Shorts"); spinnerArray.add("Suits"); ArrayAdapter&lt;String&gt; arrayAdapter = new ArrayAdapter&lt;String&gt;(mContext, android.R.layout.simple_spinner_item, spinnerArray); arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(arrayAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) { String text = spinner.getItemAtPosition(position).toString().toLowerCase(); CategoryKey = text; if (position == 1){ CategoryKey = text.replace("All Items", "all_items"); } // if (text.equals("All Items")){ // // } queryFirebaseToDisplayCategory(CategoryKey); } @Override public void onNothingSelected(AdapterView&lt;?&gt; parent) { } }); } private void queryFirebaseToDisplayCategory(String CategoryKey){ Query query = privateUserReference.child(currentUserID).child(CategoryKey).orderByKey(); FirebaseRecyclerOptions&lt;Category&gt; firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder&lt;Category&gt;().setQuery(query, Category.class).build(); FirebaseRecyclerAdapter&lt;Category, OutfitViewHolder&gt; firebaseRecyclerAdapter = new FirebaseRecyclerAdapter&lt;Category, OutfitViewHolder&gt;(firebaseRecyclerOptions) { @Override protected void onBindViewHolder(@NonNull OutfitViewHolder outfitViewHolder, int i, @NonNull Category category) { String PostKey = getRef(i).getKey(); Picasso.get().load(category.getFile_uri()).into(outfitViewHolder.recyclerImage); outfitViewHolder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { privateUserReference.child(currentUserID).child(CategoryKey).child(PostKey) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String fileURI = dataSnapshot.child("file_uri").getValue().toString(); displayRecyclerImage(fileURI); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }); } @NonNull @Override public OutfitViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.layout_outfit_item_view, parent, false); return new OutfitViewHolder(view); } }; firebaseRecyclerAdapter.startListening(); recyclerView.setAdapter(firebaseRecyclerAdapter); } private void displayRecyclerImage(String fileURI){ if (fileURI != null){ Picasso.get().load(fileURI).into(outfitOne); } } public class OutfitViewHolder extends RecyclerView.ViewHolder{ View mView = itemView; ImageView recyclerImage; public OutfitViewHolder(@NonNull View itemView) { super(itemView); recyclerImage = mView.findViewById(R.id.outfit_recycler_image); } } private final class ChoiceTouchListener implements View.OnTouchListener { public boolean onTouch(View view, MotionEvent event){ final int X = (int) event.getRawX(); final int Y = (int) event.getRawY(); switch (event.getAction() &amp; MotionEvent.ACTION_MASK){ case MotionEvent.ACTION_DOWN: RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)view.getLayoutParams(); _xDelta = X - lParams.leftMargin; _yDelta = Y - lParams.topMargin; break; case MotionEvent.ACTION_UP: break; case MotionEvent.ACTION_POINTER_DOWN: break; case MotionEvent.ACTION_POINTER_UP: break; case MotionEvent.ACTION_MOVE: RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)view.getLayoutParams(); layoutParams.leftMargin = X - _xDelta; layoutParams.topMargin = Y - _yDelta; layoutParams.rightMargin = -0; layoutParams.bottomMargin = -0; view.setLayoutParams(layoutParams); break; } rootLayout.invalidate(); return true; } } private class MySimpleOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener{ ImageView viewMyImage; float factor; public MySimpleOnScaleGestureListener(ImageView iv) { super(); viewMyImage = iv; factor = 1.0f; } @Override public boolean onScale(ScaleGestureDetector detector) { float scaleFactor = detector.getScaleFactor() - 1; factor += scaleFactor; viewMyImage.setScaleX(factor); viewMyImage.setScaleY(factor); return true; //return super.onScale(detector); } } }``` </code></pre>
3
4,206
401 Unauthorized (WebException) while posting status on Twitter from Universal app
<p>I want to give a feature to login to Twitter &amp; to post Tweet from Windows 8.1 Universal app. Please don't suggest me to go for 3rd party library. I just want to do two things only. My efforts are given below. I doubt my authentication is wrong. I am getting <strong>System.Net.WebException => The remote server returned an error: (401) Unauthorized.</strong> What's wrong with my code, any one has idea?</p> <pre><code>public const string TwitterClientID = "XXXXXXXXXXXL3nZGhtKURASXg"; public const string TwitterClientSecret = "5HBuM1FVXXXXXXXXXXXXXXqaSm1awtNSes"; public const string TwitterCallbackUrl = "http://f.com"; public const string TweetFromAPI = "Tweeting from API"; String Oauth_token = null; String Oauth_token_secret = null; private async Task TwitterLogin() { TimeSpan SinceEpoch = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime()); Random Rand = new Random(); String TwitterUrl = "https://api.twitter.com/oauth/request_token"; Int32 Nonce = Rand.Next(1000000000); String SigBaseStringParams = "oauth_callback=" + Uri.EscapeDataString(TwitterCallbackUrl); SigBaseStringParams += "&amp;" + "oauth_consumer_key=" + TwitterClientID; SigBaseStringParams += "&amp;" + "oauth_nonce=" + Nonce.ToString(); SigBaseStringParams += "&amp;" + "oauth_signature_method=HMAC-SHA1"; SigBaseStringParams += "&amp;" + "oauth_timestamp=" + Math.Round(SinceEpoch.TotalSeconds); SigBaseStringParams += "&amp;" + "oauth_version=1.0"; String SigBaseString = "POST&amp;"; SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&amp;" + Uri.EscapeDataString(SigBaseStringParams); IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(TwitterClientSecret + "&amp;", BinaryStringEncoding.Utf8); MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); CryptographicKey MacKey = HmacSha1Provider.CreateKey(KeyMaterial); IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(SigBaseString, BinaryStringEncoding.Utf8); IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned); String Signature = CryptographicBuffer.EncodeToBase64String(SignatureBuffer); String DataToPost = "OAuth oauth_callback=\"" + Uri.EscapeDataString(TwitterCallbackUrl) + "\", oauth_consumer_key=\"" + TwitterClientID + "\", oauth_nonce=\"" + Nonce.ToString() + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + Math.Round(SinceEpoch.TotalSeconds) + "\", oauth_version=\"1.0\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\""; var m_PostResponse = await PostData(TwitterUrl, DataToPost, false); if (m_PostResponse != null) { String[] keyValPairs = m_PostResponse.Split('&amp;'); for (int i = 0; i &lt; keyValPairs.Length; i++) { String[] splits = keyValPairs[i].Split('='); switch (splits[0]) { case "oauth_token": Oauth_token = splits[1]; break; case "oauth_token_secret": Oauth_token_secret = splits[1]; break; } } if (Oauth_token != null) { TwitterUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + Oauth_token; System.Uri StartUri = new Uri(TwitterUrl); System.Uri EndUri = new Uri(TwitterCallbackUrl); WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, StartUri, EndUri); if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { var text = WebAuthenticationResult.ResponseData.Split(new char[] { '?' })[1]; var dict = text.Split(new[] { '&amp;' }, StringSplitOptions.RemoveEmptyEntries) .Select(part =&gt; part.Split('=')) .ToDictionary(split =&gt; split[0], split =&gt; split[1]); //Oauth_token = dict["oauth_token"]; //Oauth_token_secret = dict["oauth_verifier"]; await PostTweet(); } else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { } else { } } } } private async Task&lt;String&gt; PostData(String Url, String Data, bool flag) { string m_PostResponse = null; try { HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url); Request.Method = "POST"; if (flag) { Request.ContentType = "application/x-www-form-urlencoded"; } Request.Headers["Authorization"] = Data; if (flag) { using (Stream stream = await Request.GetRequestStreamAsync()) { var postBody = "status=" + Uri.EscapeDataString(TweetFromAPI); byte[] content = System.Text.Encoding.UTF8.GetBytes(postBody); stream.Write(content, 0, content.Length); } } HttpWebResponse Response = (HttpWebResponse)await Request.GetResponseAsync(); StreamReader ResponseDataStream = new StreamReader(Response.GetResponseStream()); m_PostResponse = await ResponseDataStream.ReadToEndAsync(); } catch (Exception) { throw; } return m_PostResponse; } public async Task PostTweet() { Random Rand = new Random(); Int32 Nonce = Rand.Next(1000000000); string status = TweetFromAPI; string postBody = "status=" + Uri.EscapeDataString(status); string oauth_consumer_key = TwitterClientID; string oauth_consumerSecret = TwitterClientSecret; string oauth_signature_method = "HMAC-SHA1"; string oauth_version = "1.0"; string oauth_token = Oauth_token; string oauth_token_secret = Oauth_token_secret; string oauth_nonce = Nonce.ToString(); TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); string oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString(); SortedDictionary&lt;string, string&gt; basestringParameters = new SortedDictionary&lt;string, string&gt;(); basestringParameters.Add("status", Uri.EscapeDataString(status)); basestringParameters.Add("oauth_version", oauth_version); basestringParameters.Add("oauth_consumer_key", oauth_consumer_key); basestringParameters.Add("oauth_nonce", oauth_nonce); basestringParameters.Add("oauth_signature_method", oauth_signature_method); basestringParameters.Add("oauth_timestamp", oauth_timestamp); basestringParameters.Add("oauth_token", oauth_token); //Build the signature string string baseString = String.Empty; baseString += "POST" + "&amp;"; baseString += Uri.EscapeDataString("https://api.twitter.com/1.1/statuses/update.json") + "&amp;"; foreach (KeyValuePair&lt;string, string&gt; entry in basestringParameters) { baseString += Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&amp;"); } baseString = baseString.Substring(0, baseString.Length - 3); //Build the signing key string signingKey = Uri.EscapeDataString(oauth_consumerSecret) + "&amp;" + Uri.EscapeDataString(oauth_token_secret); IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(TwitterClientSecret + "&amp;", BinaryStringEncoding.Utf8); MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1"); CryptographicKey MacKey = HmacSha1Provider.CreateKey(KeyMaterial); IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(signingKey, BinaryStringEncoding.Utf8); IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned); String signatureString = CryptographicBuffer.EncodeToBase64String(SignatureBuffer); string authorizationHeaderParams = String.Empty; authorizationHeaderParams += "OAuth "; authorizationHeaderParams += "oauth_nonce=" + "\"" + Nonce.ToString() + "\","; authorizationHeaderParams += "oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauth_signature_method) + "\","; authorizationHeaderParams += "oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauth_timestamp) + "\","; authorizationHeaderParams += "oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\","; authorizationHeaderParams += "oauth_token=" + "\"" + Uri.EscapeDataString(oauth_token) + "\","; authorizationHeaderParams += "oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\","; authorizationHeaderParams += "oauth_version=" + "\"" + Uri.EscapeDataString(oauth_version) + "\""; var respo = await PostData("https://api.twitter.com/1.1/statuses/update.json", authorizationHeaderParams, true); } </code></pre>
3
3,646
How to socket a asBroadcastStream so that it can be used in a stream builder?
<p>Hello i ran into a problem on Streams, specifically on how to use a broadcast stream for socket programming. Here is the code:</p> <pre><code>import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'dart:io'; import 'dart:typed_data'; import 'package:tcp/othermessage.dart'; import 'package:tcp/ownmessage.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:google_fonts/google_fonts.dart'; void main() async { final socket = await Socket.connect('0.0.0.0', 3389); //This ip wouldn't work but I change it for safety reasons print('Connected to: ${socket.remoteAddress.address}:${socket.remotePort}'); runApp(MyApp(socket: socket)); socket.write(&quot;h&quot;); } class MyApp extends StatelessWidget { final Socket socket; const MyApp({required this.socket, Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page', socket: socket), ); } } class MyHomePage extends StatefulWidget { final Socket socket; MyHomePage({Key? key, required this.title, required this.socket}) : super(key: key); final String title; @override State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState(); } class _MyHomePageState extends State&lt;MyHomePage&gt; { final inputController = TextEditingController(); ScrollController scrollcontrol = ScrollController(); List&lt;String&gt; messageList = []; @override void dispose() { inputController.dispose(); widget.socket.destroy(); widget.socket.close(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color.fromRGBO(236, 236, 236, 1), body: SafeArea( child: Column( children: &lt;Widget&gt;[ StreamBuilder( stream: widget.socket, builder: (context, snapshot) { if (snapshot.hasData == false || String.fromCharCodes(snapshot.data as Uint8List) .contains(&quot;joined Connected to the server!&quot;) == true) { return Container( height: MediaQuery.of(context).size.height - 300); } String sent = String.fromCharCodes(snapshot.data as Uint8List); messageList.add(sent); return Container( color: const Color.fromRGBO(236, 235, 236, 100), height: MediaQuery.of(context).size.height - 300, child: ListView.builder( controller: scrollcontrol, shrinkWrap: true, itemCount: messageList.length, itemBuilder: (BuildContext context, int index) { String messagerecieved = messageList[index]; List&lt;String&gt; messagedisected = messagerecieved.split(&quot; &quot;); if (messagedisected[0] != &quot;h:&quot; &amp;&amp; messagerecieved.contains( &quot;joined Connected to the server!&quot;) == false) { return OtherMessage( message: messageList[index]); } else { return OwnMessage(message: messageList[index]); } })); }), Row( children: [ Container( margin: EdgeInsets.only(left: 12), width: 330, decoration: BoxDecoration( color: Color.fromRGBO(214, 214, 214, 100), borderRadius: BorderRadius.circular(14.65)), child: TextFormField( keyboardType: TextInputType.multiline, minLines: 1, maxLines: 5, decoration: const InputDecoration( hintText: 'Enter your message', border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, contentPadding: EdgeInsets.only( left: 15, bottom: 11, top: 11, right: 15)), controller: inputController, ), ), IconButton( padding: const EdgeInsets.only(left: 10, right: 12, top: 10), iconSize: 50, onPressed: () { if (messageList.isNotEmpty) { scrollcontrol.animateTo( scrollcontrol.position.maxScrollExtent, duration: const Duration(milliseconds: 100), curve: Curves.easeOut); } String message = inputController.text; widget.socket.write(&quot;h: &quot; + message); inputController.clear(); }, icon: SvgPicture.asset('assets/images/SendButton.svg')) ], ), ], ), )); } } </code></pre> <p>I want to be able to expose the socket as a broadcastStream, I already tried using the asBroadcastStream function but I don't know how to pass it to another StreamBuilder. My plan is to be able to read status sent by the tcp server and update my AppBar title with StreamBuilder like so</p> <pre><code>AppBar(title: StreamBuilder&lt;Object&gt;( stream: widget.socket, builder: (context, snapshot) { return mycustomwidget(); } ) </code></pre> <p>As we know doing this is not possible cause the stream is not a broadcast stream and has already been listened by another streambuilder, I tried using asBroadCastStream like so</p> <pre><code>class _MyHomePageState extends State&lt;MyHomePage&gt; { final inputController = TextEditingController(); ScrollController scrollcontrol = ScrollController(); List&lt;String&gt; messageList = []; Stream mystream=widget.socket.asBroadcastStream(); @override void dispose() { inputController.dispose(); widget.socket.destroy(); widget.socket.close(); super.dispose(); } @override Widget build(BuildContext context) { mystream.listen((value)=&gt;print(value)); return Scaffold(//...continuation </code></pre> <p>But obviously it comes back with a badState again. I'm still very new in handling streams like this I hope someone can clarify and fix my problem. Thank you!</p>
3
3,701
Start another Activity
<p>Maybe you can help me with my problem.</p> <p>I have a <code>linearLayout</code> with a click listener and now I want to start another activity. But I get always an error when opening the app. </p> <p>Is the failure in my <code>onClick</code> or in the <code>PlaylistActivity</code>?</p> <p>It works in an other project with the same <code>PlaylistActivity</code> class. And yes, I've declared the activity in the manifest ;)</p> <p>Thanks a lot</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.browse); setVolumeControlStream(AudioManager.STREAM_MUSIC); viewFlipper = (ViewFlipper) findViewById(R.id.view_flipper); in_from_left = AnimationUtils.loadAnimation(this, R.anim.in_from_left); in_from_right = AnimationUtils.loadAnimation(this, R.anim.in_from_right); out_to_left = AnimationUtils.loadAnimation(this, R.anim.out_to_left); out_to_right = AnimationUtils.loadAnimation(this, R.anim.out_to_right); LinearLayoutTitel = (LinearLayout) findViewById(R.id.LinearLayoutTitelID); LinearLayoutAlben = (LinearLayout) findViewById(R.id.LinearLayoutAlbenID); LinearLayoutOrdner = (LinearLayout) findViewById(R.id.LinearLayoutOrdnerID); LinearLayoutInterpreten = (LinearLayout) findViewById(R.id.LinearLayoutInterpretenID); //get reference to the view flipper final ViewFlipper myViewFlipper = (ViewFlipper) findViewById(R.id.view_flipper); //set the animation for the view that enters the screen myViewFlipper.setInAnimation(in_from_right); //set the animation for the view leaving th screen myViewFlipper.setOutAnimation(out_to_right); myViewFlipper.showNext(); LinearLayoutTitel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent(getApplicationContext(), PlayListActivity.class); startActivityForResult(i, 100); myViewFlipper.showPrevious(); } });}} </code></pre> <p>and the errors:</p> <pre><code>12-19 20:25:58.299: W/asset(21248): Copying FileAsset 0x50c81038 (zip:/data/app/de.vinzzenzz.musicplayeralpha-2.apk:/resources.arsc) to buffer size 10872 to make it aligned. 12-19 20:25:58.649: I/Adreno200-EGL(21248): &lt;qeglDrvAPI_eglInitialize:265&gt;: EGL 1.4 QUALCOMM build: (CL3449569) 12-19 20:25:58.649: I/Adreno200-EGL(21248): Build Date: 05/14/13 Tue 12-19 20:25:58.649: I/Adreno200-EGL(21248): Local Branch: htc2 12-19 20:25:58.649: I/Adreno200-EGL(21248): Remote Branch: 12-19 20:25:58.649: I/Adreno200-EGL(21248): Local Patches: 12-19 20:25:58.649: I/Adreno200-EGL(21248): Reconstruct Branch: 12-19 20:25:58.789: D/qdmemalloc(21248): ion: Mapped buffer base:0x54019000 size:2088960 offset:0 fd:57 12-19 20:25:58.789: D/qdmemalloc(21248): ion: Mapped buffer base:0x40010000 size:4096 offset:0 fd:58 12-19 20:25:59.290: D/qdmemalloc(21248): ion: Mapped buffer base:0x5434d000 size:2088960 offset:0 fd:60 12-19 20:25:59.290: D/qdmemalloc(21248): ion: Mapped buffer base:0x40038000 size:4096 offset:0 fd:61 12-19 20:25:59.310: D/qdmemalloc(21248): ion: Mapped buffer base:0x5454b000 size:2088960 offset:0 fd:62 12-19 20:25:59.310: D/qdmemalloc(21248): ion: Mapped buffer base:0x4004f000 size:4096 offset:0 fd:63 12-19 20:26:00.321: D/qdmemalloc(21248): ion: Mapped buffer base:0x54879000 size:2088960 offset:0 fd:65 12-19 20:26:00.321: D/qdmemalloc(21248): ion: Mapped buffer base:0x40d3e000 size:4096 offset:0 fd:66 12-19 20:26:00.341: D/qdmemalloc(21248): ion: Mapped buffer base:0x54a77000 size:2088960 offset:0 fd:67 12-19 20:26:00.341: D/qdmemalloc(21248): ion: Mapped buffer base:0x40ec2000 size:4096 offset:0 fd:68 12-19 20:26:00.351: D/qdmemalloc(21248): ion: Mapped buffer base:0x54c75000 size:2088960 offset:0 fd:69 12-19 20:26:00.351: D/qdmemalloc(21248): ion: Mapped buffer base:0x411f2000 size:4096 offset:0 fd:70 12-19 20:26:00.361: D/qdmemalloc(21248): ion: Unmapping buffer base:0x54019000 size:2088960 12-19 20:26:00.361: D/qdmemalloc(21248): ion: Unmapping buffer base:0x40010000 size:4096 12-19 20:26:00.361: D/qdmemalloc(21248): ion: Unmapping buffer base:0x5434d000 size:2088960 12-19 20:26:00.361: D/qdmemalloc(21248): ion: Unmapping buffer base:0x40038000 size:4096 12-19 20:26:00.361: D/qdmemalloc(21248): ion: Unmapping buffer base:0x5454b000 size:2088960 12-19 20:26:00.361: D/qdmemalloc(21248): ion: Unmapping buffer base:0x4004f000 size:4096 12-19 20:26:01.282: W/dalvikvm(21248): threadid=1: thread exiting with uncaught exception (group=0x417a0ba0) 12-19 20:26:01.282: E/AndroidRuntime(21248): FATAL EXCEPTION: main 12-19 20:26:01.282: E/AndroidRuntime(21248): android.content.ActivityNotFoundException: Unable to find explicit activity class {de.vinzzenzz.musicplayeralpha/de.vinzzenzz.musicplayeralpha.PlayListActivity}; have you declared this activity in your AndroidManifest.xml? 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.app.Instrumentation.execStartActivity(Instrumentation.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.app.Activity.startActivityForResult(Activity.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.app.Activity.startActivityForResult(Activity.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at de.vinzzenzz.musicplayeralpha.BrowseActivity$1.onClick(BrowseActivity.java:58) 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.view.View.performClick(View.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.view.View$PerformClick.run(View.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.os.Handler.handleCallback(Handler.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.os.Handler.dispatchMessage(Handler.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.os.Looper.loop(Looper.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at android.app.ActivityThread.main(ActivityThread.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at java.lang.reflect.Method.invokeNative(Native Method) 12-19 20:26:01.282: E/AndroidRuntime(21248): at java.lang.reflect.Method.invoke(Method.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java) 12-19 20:26:01.282: E/AndroidRuntime(21248): at dalvik.system.NativeStart.main(Native Method) </code></pre>
3
2,674
Get an X(std) value of efficient frontier from a given Y(mean) value with cvxopt?
<p>I'm trying to do portfolio optimization with cvxopt (Python), I'm able to get the efficient frontier with the following code, however, I'm not able to specify a Y value (mean or return) and get a corresponding X value (std or risk), if anyone has knowledge about this, I would be more than grateful if you can share it:</p> <pre><code>def optimal_portfolio(returns_vec, cov_matrix): n = len(returns_vec) N = 1000 mus = [10 ** (5 * t / N - 1.0) for t in range(N)] # Convert to cvxopt matrices S = opt.matrix(cov_matrix) pbar = opt.matrix(returns_vec) # Create constraint matrices G = -opt.matrix(np.eye(n)) # negative n x n identity matrix h = opt.matrix(0.0, (n, 1)) A = opt.matrix(1.0, (1, n)) b = opt.matrix(1.0) #solvers.options[&quot;feastol&quot;] =1e-9 # Calculate efficient frontier weights using quadratic programming portfolios = [solvers.qp(mu * S, -pbar, G, h, A, b)['x'] for mu in mus] ## CALCULATE RISKS AND RETURNS FOR FRONTIER returns = [blas.dot(pbar, x) for x in portfolios] risks = [np.sqrt(blas.dot(x, S * x)) for x in portfolios] ## CALCULATE THE 2ND DEGREE POLYNOMIAL OF THE FRONTIER CURVE m1 = np.polyfit(returns, risks, 2) x1 = np.sqrt(m1[2] / m1[0]) # CALCULATE THE OPTIMAL PORTFOLIO wt = solvers.qp(opt.matrix(x1 * S), -pbar, G, h, A, b)['x'] return np.asarray(wt), returns, risks return_vec = [0.055355, 0.010748, 0.041505, 0.074884, 0.039795, 0.065079 ] cov_matrix =[[ 0.005329, -0.000572, 0.003320, 0.006792, 0.001580, 0.005316], [-0.000572, 0.000625, 0.000606, -0.000266, -0.000107, 0.000531], [0.003320, 0.000606, 0.006610, 0.005421, 0.000990, 0.006852], [0.006792, -0.000266, 0.005421, 0.011385, 0.002617, 0.009786], [0.001580, -0.000107, 0.000990, 0.002617, 0.002226, 0.002360], [0.005316, 0.000531, 0.006852, 0.009786, 0.002360, 0.011215]] weights, returns, risks = optimal_portfolio(return_vec, cov_matrix) fig = plt.figure() plt.ylabel('Return') plt.xlabel('Risk') plt.plot(risks, returns, 'y-o') print(weights) plt.show() </code></pre> <p>I would like to find the corresponding risk value for a given return value.</p> <p>Thank you very much!</p>
3
1,028
how to use a JComboBox object as a parameter of a java method?
<p>I get an error message due to the JComboBox parameter I am using in my code. The method is: <code>public void miseAJourComboBox(JComboBox&lt;String&gt; jcb)</code></p> <p>The message is:</p> <pre class="lang-none prettyprint-override"><code>error: cannot find symbol public void miseAJourComboBox(JComboBox&lt;String&gt; jcb){ symbol: class JComboBox location: class FrameAchat </code></pre> <p>and the code (simplified) is:</p> <pre><code>public class FrameAchat extends javax.swing.JFrame { public ConnectionSQL connectionSQL; /** Creates new form FrameAchat */ public FrameAchat() { connectionSQL = new ConnectionSQL(); System.out.println(&quot;passe par constructeur de achat&quot;); initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings(&quot;unchecked&quot;) // &lt;editor-fold defaultstate=&quot;collapsed&quot; desc=&quot;Generated Code&quot;&gt; private void initComponents() { jLabelFicheAchat = new javax.swing.JLabel(); jComboIdPdt = new javax.swing.JComboBox&lt;&gt;(); jLabelMarque = new javax.swing.JLabel(); jLabelModele = new javax.swing.JLabel(); jLabelAnnee = new javax.swing.JLabel(); jLabelPrix = new javax.swing.JLabel(); jComboIdFrs = new javax.swing.JComboBox&lt;&gt;(); jLabelNom = new javax.swing.JLabel(); jComboQte = new javax.swing.JComboBox&lt;&gt;(); jLabelQte = new javax.swing.JLabel(); Achat = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabelFicheAchat.setFont(new java.awt.Font(&quot;Tahoma&quot;, 0, 18)); // NOI18N jLabelFicheAchat.setText(&quot;Creation Achat&quot;); jComboIdPdt.setModel(new javax.swing.DefaultComboBoxModel&lt;&gt;(new String[] { &quot;Item 1&quot;, &quot;Item 2&quot;, &quot;Item 3&quot;, &quot;Item 4&quot; })); jLabelMarque.setText(&quot;jLabel1&quot;); jLabelModele.setText(&quot;jLabel1&quot;); jLabelAnnee.setText(&quot;jLabel1&quot;); jLabelPrix.setText(&quot;jLabel1&quot;); jComboIdFrs.setModel(new javax.swing.DefaultComboBoxModel&lt;&gt;(new String[] { &quot;Item 1&quot;, &quot;Item 2&quot;, &quot;Item 3&quot;, &quot;Item 4&quot; })); jLabelNom.setText(&quot;jLabel1&quot;); jComboQte.setModel(new javax.swing.DefaultComboBoxModel&lt;&gt;(new String[] { &quot;Item 1&quot;, &quot;Item 2&quot;, &quot;Item 3&quot;, &quot;Item 4&quot; })); jLabelQte.setText(&quot;Quantité:&quot;); Achat.setText(&quot;ACHETER&quot;); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jLabelFicheAchat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 177, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(91, 91, 91)) .add(layout.createSequentialGroup() .add(24, 24, 24) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jComboIdPdt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(53, 53, 53) .add(jLabelMarque) .add(18, 18, 18) .add(jLabelModele) .add(28, 28, 28) .add(jLabelAnnee) .add(18, 18, 18) .add(jLabelPrix)) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jComboIdFrs, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabelQte)) .add(53, 53, 53) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jComboQte, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabelNom) .add(Achat)))) .addContainerGap(66, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(21, 21, 21) .add(jLabelFicheAchat) .add(18, 18, 18) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jComboIdPdt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabelMarque) .add(jLabelModele) .add(jLabelAnnee) .add(jLabelPrix)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jComboIdFrs, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabelNom)) .add(18, 18, 18) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jComboQte, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabelQte)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 76, Short.MAX_VALUE) .add(Achat) .add(51, 51, 51)) ); pack(); }// &lt;/editor-fold&gt; /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //&lt;editor-fold defaultstate=&quot;collapsed&quot; desc=&quot; Look and feel setting code (optional) &quot;&gt; /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if (&quot;Nimbus&quot;.equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrameAchat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrameAchat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrameAchat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrameAchat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //&lt;/editor-fold&gt; /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrameAchat().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton Achat; private javax.swing.JComboBox&lt;String&gt; jComboIdFrs; private javax.swing.JComboBox&lt;String&gt; jComboIdPdt; private javax.swing.JComboBox&lt;String&gt; jComboQte; private javax.swing.JLabel jLabelAnnee; private javax.swing.JLabel jLabelFicheAchat; private javax.swing.JLabel jLabelMarque; private javax.swing.JLabel jLabelModele; private javax.swing.JLabel jLabelNom; private javax.swing.JLabel jLabelPrix; private javax.swing.JLabel jLabelQte; // End of variables declaration public void miseAJourComboBox(JComboBox&lt;String&gt; jcb){ System.out.println(&quot;hi&quot;); } } </code></pre>
3
4,585
No inverse error during encryption (node-rsa)
<p>I am trying to convert <a href="https://clover.app.box.com/s/rz18bni3bpmdrc8wc92xm4w8h9grrtty" rel="nofollow noreferrer">https://clover.app.box.com/s/rz18bni3bpmdrc8wc92xm4w8h9grrtty</a> from Java to node.js</p> <p>I am using the node-rsa package and getting <code>error:0306E06C:bignum routines:BN_mod_inverse:no inverse</code> when trying to encrypt using an imported public key.</p> <p>According to the clover example, I want to</p> <ul> <li>Parse the Base64 public key string (returned by the CDN). Obtain the modulus and exponent.</li> <li>Generate an RSA public key using the modulus and exponent values.</li> <li>Prepend the prefix value to the card number.</li> <li>Using the public key, encrypt the combined prefix and card number.</li> <li>Base64 encode the resulting encrypted data into a string.</li> </ul> <p>I was able to get the modulus and exponent, and it matches the result in Java:</p> <pre><code>modulus: 24130287975021244042702223805688721202041521798556826651085672609155097623636349771918006235309701436638877260677191655500886975872679820355397440672922966114867081224266610192869324297514124544273216940817802300465149818663693299511097403105193694390420041695022375597863889602539348837984499566822859405785094021038882988619692110445776031330831112388738257159574572412058904373392173474311363017975036752132291687352767767085957596076340458420658040735725435536120045045686926201660857778184633632435163609220055250478625974096455522280609375267155256216043291335838965519403970406995613301546002859220118001163241 exponent: 415029 </code></pre> <p>Now I want to create a public key with it, and encrypt a message:</p> <pre><code> const key = new NodeRSA(); // generate RSA public key using mod and exp values key.importKey({ n: Buffer.from('24130287975021244042702223805688721202041521798556826651085672609155097623636349771918006235309701436638877260677191655500886975872679820355397440672922966114867081224266610192869324297514124544273216940817802300465149818663693299511097403105193694390420041695022375597863889602539348837984499566822859405785094021038882988619692110445776031330831112388738257159574572412058904373392173474311363017975036752132291687352767767085957596076340458420658040735725435536120045045686926201660857778184633632435163609220055250478625974096455522280609375267155256216043291335838965519403970406995613301546002859220118001163241', 'hex'), e: Buffer.from('415029', 'hex') }, 'components-public'); // using public key, encrypt message // base64 encode encrypted data to string const encryptedString = key.encrypt(Buffer.from('message', 'hex'), 'base64', 'hex'); </code></pre> <p>However, I am getting the no inverse error mentioned above. It seems to be caused by the modulus. If I change it to something shorter, the error goes away.</p>
3
1,099
how to resolve the "Sass::SyntaxError: Invalid CSS" error in Liferay 6.2?
<p>I am using Eclipse Kepler-4.3 and Liferay 6.2 CE GA5.</p> <p>I tried to deploy a theme but I got this error:</p> <blockquote> <pre><code> [echo] Loading jar:file:/D:/FormationJEE/Liferay/LiferayGA5/tomcat/liferay-portal-6.2-ce-ga5/tomcat-7.0.62/webapps/ROOT/WEB-INF/lib/portal-impl.jar!/system.properties [echo] Loading jar:file:/D:/FormationJEE/Liferay/LiferayGA5/tomcat/liferay-portal-6.2-ce-ga5/tomcat-7.0.62/webapps/ROOT/WEB-INF/lib/portal-impl.jar!/portal.properties [echo] Sass::SyntaxError: Invalid CSS after "...ow-x: hidden\0/": expected expression (e.g. 1px, bold), was ";" [echo] expected at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:1147 [echo] expected! at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/lexer.rb:199 [echo] assert_expr at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:471 [echo] times_div_or_mod at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:233 [echo] plus_or_minus at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:225 [echo] relational at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:225 [echo] eq_or_neq at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:225 [echo] and_expr at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:225 [echo] or_expr at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:225 [echo] space at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:298 [echo] expr at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:246 [echo] send at org/jruby/RubyKernel.java:2093 [echo] assert_expr at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:470 [echo] parse at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/script/parser.rb:49 [echo] send at org/jruby/RubyKernel.java:2093 [echo] sass_script at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:1021 [echo] value! at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:881 [echo] declaration at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:858 [echo] declaration_or_ruleset at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:581 [echo] call at org/jruby/RubyProc.java:270 [echo] call at org/jruby/RubyProc.java:220 [echo] rethrow at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:1122 [echo] declaration_or_ruleset at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:591 [echo] block_child at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:553 [echo] block_contents at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:542 [echo] block at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:534 [echo] ruleset at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:528 [echo] block_child at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:552 [echo] block_contents at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:545 [echo] stylesheet at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:82 [echo] parse at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/scss/parser.rb:27 [echo] _to_tree at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/engine.rb:342 [echo] _render at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/engine.rb:315 [echo] render at C:/Users/MARWEN~1/AppData/Local/Temp/liferay/ruby/gems/sass-3.2.12/lib/sass/../sass/engine.rb:262 [echo] (root) at &lt;script&gt;:48 [echo] Unable to parse /css/app.css [echo] Exception in thread "main" org.jruby.embed.EvalFailedException: (SyntaxError) Invalid CSS after </code></pre> <p>"...ow-x: hidden\0/": expected expression (e.g. 1px, bold), was ";" [echo] at org.jruby.embed.internal.EmbedEvalUnitImpl.run(EmbedEvalUnitImpl.java:127) [echo] at org.jruby.embed.ScriptingContainer.runUnit(ScriptingContainer.java:1231) [echo] at org.jruby.embed.ScriptingContainer.runScriptlet(ScriptingContainer.java:1224) [echo] at com.liferay.portal.scripting.ruby.RubyExecutor.doEval(RubyExecutor.java:189) [echo] at com.liferay.portal.scripting.ruby.RubyExecutor.eval(RubyExecutor.java:229) [echo] at com.liferay.portal.scripting.ruby.RubyExecutor.eval(RubyExecutor.java:129) [echo] at com.liferay.portal.tools.SassToCssBuilder._parseSassFile(SassToCssBuilder.java:355) [echo] at com.liferay.portal.tools.SassToCssBuilder._cacheSass(SassToCssBuilder.java:186) [echo] at com.liferay.portal.tools.SassToCssBuilder._parseSassDirectory(SassToCssBuilder.java:317) [echo] at com.liferay.portal.tools.SassToCssBuilder.(SassToCssBuilder.java:172) [echo] at com.liferay.portal.tools.SassToCssBuilder.main(SassToCssBuilder.java:125) [echo] Caused by: org.jruby.exceptions.RaiseException: (SyntaxError) Invalid CSS after "...ow-x: hidden\0/": expected expression (e.g. 1px, bold), was ";"</p> <p>BUILD FAILED D:\FormationJEE\Liferay\LiferayGA5\sdk\liferay-plugins-sdk-6.2\build-common.xml:3162: The following error occurred while executing this line: : The following error occurred while executing this line: D:\FormationJEE\Liferay\LiferayGA5\sdk\liferay-plugins-sdk-6.2\build-common.xml:1421: The following error occurred while executing this line: : The following error occurred while executing this line: D:\FormationJEE\Liferay\LiferayGA5\sdk\liferay-plugins-sdk-6.2\build-common.xml:2866: The following error occurred while executing this line: D:\FormationJEE\Liferay\LiferayGA5\sdk\liferay-plugins-sdk-6.2\build-common.xml:190: Sass to CSS Builder generated exceptions.</p> </blockquote>
3
3,517
Logging across sub-modules – how to access parent logger name from sub-modules?
<p>I am trying to add logging to my python application that has several modules and submodules. Several sites say to create child loggers in modules. The advantage I see is that the child logger inheriting the parent logging config, it will provide consistency for the logging output (handlers, formatters, ...).</p> <p>So far I am defining the <code>__main__</code> class logger name in each class and concatenate it with the current class’ name (<code>parentName.childName</code>) to get the module’s class loggers. It does not feel right, nor scalable. How could I improve this so I don’t have to hard code the <code>__main__</code> class logger name in each class? Here is what my code looks like:</p> <p>Py file that I run:</p> <pre><code>###app.py import logging from SubModule1 import * class myApplication(): loggerName='myAPI' def __init__(self, config_item_1=None,config_item_2=None,...config_item_N=None): self.logger=self.logConfig() self.logger.info("Starting my Application") self.object1=mySubClass1(arg1, arg2, ... argM) def logConfig(self): fileLogFormat='%(asctime)s - %(levelname)s - %(message)s' consoleLogFormat='%(asctime)s - %(name)s - %(levelname)s - %(message)s' # create logger #logger = logging.getLogger(__name__) logger = logging.getLogger(self.loggerName) logger.setLevel(logging.DEBUG) ####CONSOLE HANDLER#### # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.INFO) # create formatter consoleFormatter = logging.Formatter(consoleLogFormat) # add formatter to ch ch.setFormatter(consoleFormatter) # add ch to logger logger.addHandler(ch) ####FILE HANDLER#### # create file handler and set level to debug fh = logging.FileHandler('API_Log.txt') fh.setLevel(logging.DEBUG) # create formatter fileFormatter = logging.Formatter(fileLogFormat) # add formatter to ch fh.setFormatter(fileFormatter) # add ch to logger logger.addHandler(fh) logger.info('Logging is started!!') return logger def connect(self): self.logger.info("Connecting to API") self.object1.connect() if __name__=="__main__": config={"config_item_1": x, "config_item_2": y, ... "config_item_N": z } myApp=myApplication(config['config_item_1'],config['config_item_2'],...config['config_item_N']) myApp.connect() </code></pre> <p>Module:</p> <pre><code>###SubModule1.py import logging import app class mySubClass1(): appRootLoggerName='myAPI' def __init__(self,item1): self.logger=logging.getLogger(self.appRootLoggerName + '.'+mySubClass1.__name__) self.logger.debug("mySubClass1 object created - mySubClass1") self.classObject1=item1 </code></pre> <p>The line below is the one that is bothering me. What alternative to <code>self.appRootLoggerName + '.'+mySubClass1.__name__)</code> would keep the same logging configuration shared across my application’s modules/classes? </p> <pre><code>logging.getLogger(self.appRootLoggerName + '.'+mySubClass1.__name__) </code></pre>
3
1,314
Unknown error inserting in table in Python 3
<p>I'm trying to do a class to access a database in Sqlite3 in Python 3. The database was created and when I check if its inserting on the database I get the following error on the second line of the <strong>init</strong> method:</p> <pre><code>File "~/implementacao 2/Dabase_Connection.py", line 16, in __init__ self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')') File "~/implementacao 2/Dabase_Connection.py", line 33, in insert_in_database c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data sqlite3.OperationalError: near ",": syntax error </code></pre> <p>The code is this one:</p> <pre><code>def __init__(self): # self.create_database('database_name.db', 'table_name', 'id TEXT, data TEXT') self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')') # self.delete_from_database('database_name.db', 'table_name', 'data1') # self.update_in_database('database_name.db','table_name', 'data', 'data_nova', 'data1') # self.insert_all_in_database('database_name.db', 'table_name', [('data1','data1'),('data2','data2'),('data3','data3'),('data4','data4')]) # self.Search_in_database('database_name.db', 'table_name', 'data') def create_database(self,database_name,table_name,table_args): conn = sqlite3.connect(database_name) c = conn.cursor() c.execute('CREATE TABLE '+ table_name + '(' + table_args + ')')# Create table conn.commit() # Save (commit) the changes conn.close()# We can also close the connection if we are done with it. # INSERT INTO prontuarios VALUES(id,prontuario); def insert_in_database(self,database_name,table_name, data): conn = sqlite3.connect(database_name) c = conn.cursor() c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data conn.commit() # Save (commit) the changes conn.close()# We can also close the connection if we are done with it. def delete_from_database(self,database_name,table_name, chave): conn = sqlite3.connect(database_name) c = conn.cursor() c.execute('DELETE FROM ' + table_name +' WHERE Id= '+ chave +' ; ')# Insert a row of data conn.commit() # Save (commit) the changes conn.close()# We can also close the connection if we are done with it. def update_in_database(self,database_name,table_name, table_field, data, chave): conn = sqlite3.connect(database_name) c = conn.cursor() c.execute('UPDATE ' +table_name+ ' SET ' + table_field + ' = ' + data + ' WHERE id = ' + chave+' ;')# Insert a row of data conn.commit() # Save (commit) the changes conn.close()# We can also close the connection if we are done with it. # persons = [("Hugo", "Boss"),("Calvin", "Klein")] # Fill the table conn.executemany("'"insert into person(firstname, lastname) values (?, ?)", persons) def insert_all_in_database(self,database_name,table_name, data): data_interrog = self.get_parameters(data) conn = sqlite3.connect(database_name) c = conn.cursor() c.executemany('insert into ' + table_sifnature + ' values ( '+ data_interrog +' ) ', data) conn.commit() # Save (commit) the changes conn.close()# We can also close the connection if we are done with it. def Search_in_database(self,database_name,table_name, fields): conn = sqlite3.connect(database_name) c = conn.cursor() # Print the table contents for row in c.execute('select '+ fields + ' from ' +table_name): print(row) </code></pre>
3
1,282
Avoid ConstraintViolationException in JPA and OneToMany relationship when merge
<p>What I want to achieve with the example below is to avoid the constraint violation exception that occurs when run the following:</p> <pre><code>Parent p = new Parent(); Set&lt;Child&gt; children = new HashSet&lt;Child&gt;(); Child c = new Child(); children.add(c); p.setChildren(children); entityManager.merge(p); entityManager.merge(p); </code></pre> <p>How to configure JPA to achieve this effect? Below are the classes.</p> <pre><code>@Entity @Table(name = "parent", indexes = {uniqueConstraints = { @UniqueConstraint(columnNames = { "uri" }) }) public class Parent implements Serializable { ... private String uri; private Set&lt;Child&gt; children = new HashSet&lt;Child&gt;(); @Id @Column(name = "id", unique = true) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "parent_seq") @SequenceGenerator(name = "parent_seq", sequenceName = "parent_seq", allocationSize = 1) public Long getId() { return id; } @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "parent_id") public Set&lt;Child&gt; getChildren() { return children; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Parent other = (Parent) obj; if (uri == null) { if (other.uri != null) return false; } else if (!uri.equals(other.uri)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((uri == null) ? 0 : uri.hashCode()); return result; } } @Entity @Table(name = "child", indexes = {uniqueConstraints = { @UniqueConstraint(columnNames = { "text" }) }) public class Child implements Serializable { private String text; @Id @Column(name = "id", unique = true) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "child_seq") @SequenceGenerator(name = "child_seq", sequenceName = "child_seq", allocationSize = 1) public Long getId() { return id; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Child other = (Child) obj; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((text == null) ? 0 : text.hashCode()); return result; } } </code></pre> <p>I use postgres and hibernate as JPA provider</p>
3
1,190
android app running in background with timer task,suddenly stop the task
<p>I make app in android with scheduled task and running in background, but when i open other app and do it something with my device,then i back to my app to check the task,the task is stopped. i have logcat like this,does somebody now what i'm doing wrong??</p> <pre><code>05-10 17:55:14.520: W/GpsLocationProvider(149): Unneeded remove listener for uid 1000 05-10 17:55:14.650: W/ActivityManager(149): Scheduling restart of crashed service com.sec.chaton/.push.PushClientService in 5000ms 05-10 17:55:15.740: E/ActivityThread(9192): Failed to find provider info for ownhere.google.settings 05-10 17:55:15.750: E/ActivityThread(9192): Failed to find provider info for ownhere.google.settings 05-10 17:55:15.790: E/ActivityThread(9192): Failed to find provider info for ownhere.google.settings 05-10 17:55:15.790: E/ActivityThread(9192): Failed to find provider info for ownhere.google.settings 05-10 17:55:16.580: W/ActivityManager(149): Scheduling restart of crashed service com.staircase3.opensignal/.library.Background_scan in 5000ms 05-10 17:55:21.680: E/API(9280): 15 05-10 17:55:21.700: E/Background_scan(9280): Tab_Overview.overview_visible=false; 05-10 17:55:34.990: W/ActivityManager(149): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.firstwap.celltrack/.MainActivity bnds=[834,488][1264,552] } 05-10 17:55:35.030: W/KeyguardViewMediator(149): verifyUnlock called when not externally disabled 05-10 17:55:35.140: W/ActivityManager(149): Force removing ActivityRecord{414b2478 com.firstwap.celltrack/.MainActivity}: app died, no saved state 05-10 17:55:35.250: W/GpsLocationProvider(149): Duplicate add listener for uid 10012 05-10 17:55:35.350: E/LWUIT(9312): problem with setHasAlpha 05-10 17:55:35.350: E/LWUIT(9312): java.lang.NoSuchMethodException: setHasAlpha [class java.lang.Boolean] 05-10 17:55:35.350: E/LWUIT(9312): at java.lang.Class.getConstructorOrMethod(Class.java:460) 05-10 17:55:35.350: E/LWUIT(9312): at java.lang.Class.getMethod(Class.java:915) 05-10 17:55:35.350: E/LWUIT(9312): at com.sun.lwuit.impl.android.AndroidView.initBitmaps(AndroidView.java:151) 05-10 17:55:35.350: E/LWUIT(9312): at com.sun.lwuit.impl.android.AndroidView.&lt;init&gt;(AndroidView.java:132) 05-10 17:55:35.350: E/LWUIT(9312): at com.sun.lwuit.impl.android.AndroidImplementation$1.run(AndroidImplementation.java:244) 05-10 17:55:35.350: E/LWUIT(9312): at com.sun.lwuit.impl.android.AndroidImplementation$12.run(AndroidImplementation.java:2155) 05-10 17:55:35.350: E/LWUIT(9312): at android.app.Activity.runOnUiThread(Activity.java:4170) 05-10 17:55:35.350: E/LWUIT(9312): at com.sun.lwuit.impl.android.AndroidImplementation.runOnAndroidUIThreadAndWait(AndroidImplementation.java:2151) 05-10 17:55:35.350: E/LWUIT(9312): at com.sun.lwuit.impl.android.AndroidImplementation.runOnAndroidUIThreadAndWait(AndroidImplementation.java:2144) 05-10 17:55:35.350: E/LWUIT(9312): at com.sun.lwuit.impl.android.AndroidImplementation.initSurface(AndroidImplementation.java:238) 05-10 17:55:35.350: E/LWUIT(9312): at com.sun.lwuit.impl.android.AndroidImplementation.init(AndroidImplementation.java:179) 05-10 17:55:35.350: E/LWUIT(9312): at com.sun.lwuit.Display.init(Display.java:423) 05-10 17:55:35.350: E/LWUIT(9312): at com.firstwap.celltrack.MobileCellTrackActivity.onCreate(MobileCellTrackActivity.java:173) 05-10 17:55:35.350: E/LWUIT(9312): at android.app.Activity.performCreate(Activity.java:4465) 05-10 17:55:35.350: E/LWUIT(9312): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 05-10 17:55:35.350: E/LWUIT(9312): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 05-10 17:55:35.350: E/LWUIT(9312): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 05-10 17:55:35.350: E/LWUIT(9312): at android.app.ActivityThread.access$600(ActivityThread.java:123) 05-10 17:55:35.350: E/LWUIT(9312): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 05-10 17:55:35.350: E/LWUIT(9312): at android.os.Handler.dispatchMessage(Handler.java:99) 05-10 17:55:35.350: E/LWUIT(9312): at android.os.Looper.loop(Looper.java:137) 05-10 17:55:35.350: E/LWUIT(9312): at android.app.ActivityThread.main(ActivityThread.java:4424) 05-10 17:55:35.350: E/LWUIT(9312): at java.lang.reflect.Method.invokeNative(Native Method) 05-10 17:55:35.350: E/LWUIT(9312): at java.lang.reflect.Method.invoke(Method.java:511) 05-10 17:55:35.350: E/LWUIT(9312): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 05-10 17:55:35.350: E/LWUIT(9312): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 05-10 17:55:35.350: E/LWUIT(9312): at dalvik.system.NativeStart.main(Native Method) 05-10 17:55:44.440: W/InputManagerService(149): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4164f0b0 05-10 17:55:47.510: W/InputManagerService(149): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@416f80f0 (uid=10012 pid=9312) </code></pre>
3
1,987
Revert back to the previous version of a specific time in a temporal table of MariaDB
<p>I have a MariaDB temporal table as shown in below.</p> <p><strong>Schema</strong>:</p> <pre><code>MariaDB [teamdb]&gt; DESCRIBE t2; +-------+---------+------+-----+---------+---------------------------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+---------------------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | x | int(11) | YES | | NULL | | | y | int(11) | YES | | NULL | WITHOUT SYSTEM VERSIONING | +-------+---------+------+-----+---------+---------------------------+ </code></pre> <p><strong>Data (Current)</strong>:</p> <pre><code>MariaDB [teamdb]&gt; SELECT * FROM t2; +----+------+------+ | id | x | y | +----+------+------+ | 1 | 1 | 1 | | 2 | 2 | 2 | | 3 | 3 | 4 | | 4 | 5 | 4 | +----+------+------+ </code></pre> <p><strong>Data (with History)</strong>:</p> <pre><code>MariaDB [teamdb]&gt; select *, ROW_START, ROW_END from t2 FOR SYSTEM_TIME ALL; +----+------+------+----------------------------+----------------------------+ | id | x | y | ROW_START | ROW_END | +----+------+------+----------------------------+----------------------------+ | 1 | 1 | 1 | 2019-08-15 06:41:18.684508 | 2038-01-19 03:14:07.999999 | | 2 | 1 | 2 | 2019-08-15 06:41:18.684508 | 2019-08-15 06:42:11.661167 | | 2 | 2 | 2 | 2019-08-15 06:42:11.661167 | 2038-01-19 03:14:07.999999 | | 3 | 3 | 4 | 2019-08-15 06:41:18.684508 | 2038-01-19 03:14:07.999999 | | 4 | 5 | 4 | 2019-08-15 06:41:18.684508 | 2038-01-19 03:14:07.999999 | +----+------+------+----------------------------+----------------------------+ </code></pre> <p><strong>Question:</strong> I wanted to revert back the record (<code>id=2</code>) to the version which was in <code>2019-08-15 06:42:10.661167</code> timestamp. That means, after the update, record #2 should have <code>x = 1</code> again.</p> <p>I tried inserting with <code>ON DUPLICATE</code> as shown in below query,</p> <pre><code>INSERT INTO t2 (id,x,y) SELECT t.id,t.x,t.y FROM t2 t FOR SYSTEM_TIME AS OF TIMESTAMP '2019-08-15 06:42:10.661167' WHERE t.id=2 ON DUPLICATE KEY UPDATE x=t.x, y=t.y; </code></pre> <p>This gave me the error saying there is a syntax error.</p> <pre><code>ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SYSTEM_TIME AS OF TIMESTAMP '2019-08-15 06:42:10.661167' WHERE t.id=2 ON DUPLICA' at line 1 </code></pre> <p>According to the error, it seems MariaDB does not identify <code>FOR</code> clause in select inserts.</p> <p>Any other way to revert back to the other version using a query.</p>
3
1,194
Setting the width and ellipsis to the <td> element of a table
<p>I am having table in which text inside the td's are of different length. I want to give fixed width to the td elements and the use <code>text-overflow: ellipsis</code> on the td elements, so that the whole text would not be shown. I have tried different ways but nothing works, please somebody help me with how I can achieve this.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;table&gt; &lt;tr&gt; &lt;th&gt;title&lt;/th&gt; &lt;th&gt;link&lt;/th&gt; &lt;th&gt;description&lt;/th&gt; &lt;th&gt;id&lt;/th&gt; &lt;th&gt;condition&lt;/th&gt; &lt;th&gt;price&lt;/th&gt; &lt;th&gt;availability&lt;/th&gt; &lt;th&gt;image_link&lt;/th&gt; &lt;th&gt;Shipping&lt;/th&gt; &lt;th&gt;"shipping weight"&lt;/th&gt; &lt;th&gt;gtin&lt;/th&gt; &lt;th&gt;brand&lt;/th&gt; &lt;th&gt;mpn&lt;/th&gt; &lt;th&gt;google_product_category&lt;/th&gt; &lt;th&gt;product_type&lt;/th&gt; &lt;th&gt;additional_image_link&lt;/th&gt; &lt;th&gt;color&lt;/th&gt; &lt;th&gt;size&lt;/th&gt; &lt;th&gt;Gender&lt;/th&gt; &lt;th&gt;age_group&lt;/th&gt; &lt;th&gt;item_group_id&lt;/th&gt; &lt;th&gt;sale_price&lt;/th&gt; &lt;th&gt;"sale price effective date"&lt;/th&gt; &lt;th&gt;size_type&lt;/th&gt; &lt;th&gt;size_system&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;"Metallic turquoise leather envelope clutch"&lt;/td&gt; &lt;td style="width: 200px"&gt;https://www.runway2street.com/bags/clutch-bags/metallic-turquoise-leather-envelope-clutch&lt;/td&gt; &lt;td&gt;" This elegant jeweltoned metallic leather envelope clutch with wrist strap is perfect for a fancy night out! It has a natural cork trim, magnetic closure and a zipper pocket on the inside to fit a cell phone. All accessories and hardware on the bag are gold plated. Material: 100 leather, goldplated hardwareCountry of manufacture: Lebanon "&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;td&gt;new&lt;/td&gt; &lt;td&gt;"370 USD"&lt;/td&gt; &lt;td&gt;"in stock"&lt;/td&gt; &lt;td&gt;http://az697095.vo.msecnd.net/vnext/products/3/12/Anja_Not-for-the-shy_accessories_bags_clutches_Turquoise-Cork_Metallic-turquoise-leather-envelope-clutch_38_320x480_v3.jpg&lt;/td&gt; &lt;td&gt;"US::Standard Free Shipping: 47 USD"&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;Anja&lt;/td&gt; &lt;td&gt;FALSE&lt;/td&gt; &lt;td&gt;"Apparel &amp;amp; Accessories &amp;gt; Handbags, Wallets &amp;amp; Cases &amp;gt; Handbags &amp;gt; Clutches &amp;amp; Special Occasion Bags"&lt;/td&gt; &lt;td&gt;"Clutch Bags"&lt;/td&gt; &lt;td&gt;http://az697095.vo.msecnd.net/vnext/products/3/12/Anja_Not-for-the-shy_accessories_bags_clutches_Turquoise-Cork_Metallic-turquoise-leather-envelope-clutch_35_320x480_v3.jpg&lt;/td&gt; &lt;td&gt;Turquoise/Cork&lt;/td&gt; &lt;td&gt;"One size"&lt;/td&gt; &lt;td&gt;Female&lt;/td&gt; &lt;td&gt;Adult&lt;/td&gt; &lt;td&gt;ANJAFW12mec.ct&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;Regular&lt;/td&gt; &lt;td&gt;US&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
3
1,842
How can I convert pug html and coffeescript in this codepen into html, css and plain js?
<p>This is my 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-js lang-js prettyprint-override"><code>fixedTable = (el) -&gt; $body = $(el).find '.fixedTable-body' $sidebar = $(el).find '.fixedTable-sidebar table' $header = $(el).find '.fixedTable-header table' $($body).scroll -&gt; $($sidebar).css('margin-top', -$($body).scrollTop()) $($header).css('margin-left', -$($body).scrollLeft()) demo = new fixedTable $('#demo')</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>@cellHeight: 20px; @cellWidth: 100px; @cellPadding: 5px; @cellsWide: 5; @cellsHigh: 15; .fixedTable { .table { background-color: white; width: auto; tr { td, th { min-width: @cellWidth; width: @cellWidth; min-height: @cellHeight; height: @cellHeight; padding: @cellPadding; } } }; &amp;-header { width: (@cellWidth * @cellsWide) + (@cellPadding * 2); height: @cellHeight + (@cellPadding * 2); margin-left: @cellWidth + (@cellPadding * 2); overflow: hidden; border-bottom: 1px solid #CCC; }; &amp;-sidebar { width: @cellWidth + (@cellPadding * 2); height: @cellHeight * @cellsHigh + (@cellPadding * 2); float: left; overflow: hidden; border-right: 1px solid #CCC; }; &amp;-body { overflow: auto; width: (@cellWidth * @cellsWide) + (@cellPadding * 2); height: (@cellHeight * @cellsHigh) + (@cellPadding * 2); float: left; } };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>.fixedTable#demo header.fixedTable-header table.table.table-bordered thead tr th A th B th C th D th E th F th G th H th I th J th K th L aside.fixedTable-sidebar table.table.table-bordered tbody tr td 14567567465447567467 tr td 2 tr td 3 tr td 4 tr td 5 tr td 6 tr td 7 tr td 8 tr td 9 tr td 10 tr td 11 tr td 12 tr td 13 tr td 14 tr td 15 tr td 16 tr td 17 tr td 18 tr td 19 div.fixedTable-body table.table.table-bordered tbody tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l tr td a td b td c td d td e td f td g td h td i td j td k td l</code></pre> </div> </div> </p> <p>The html is something like this:</p> <pre><code>.fixedTable#demo header.fixedTable-header table.table.table-bordered thead </code></pre>
3
4,172
show extra fields on different radio button values
<p>I have three radio buttons, when a visitor clicks the first radio, nothing will happen, when they click the second OR the third some extra fields should show up.</p> <p>I have following html:</p> <pre><code>&lt;p class="input-group input-radio input-field-workshop_wenst_u_een_factuur" &lt;label for="workshop_wenst_u_een_factuur"&gt; Wenst u een factuur? &lt;span class="em-form-required"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;span class="input-group"&gt; &lt;input class="workshop_wenst_u_een_factuur" name="workshop_wenst_u_een_factuur" val="Ik heb geen factuur nodig." type="radio"&gt; &lt;input class="workshop_wenst_u_een_factuur" name="workshop_wenst_u_een_factuur" val="Ik heb wel een factuur nodig." type="radio"&gt; &lt;input class="workshop_wenst_u_een_factuur" name="workshop_wenst_u_een_factuur" val="Mijn werkgever zal betalen." type="radio"&gt; &lt;/span&gt; &lt;/p&gt; </code></pre> <p>CSS for the extra fields:</p> <pre><code>.input-field-workshop_gelijk_adres, .input-field-factuur_bedrijf, .input-field-factuur_naam_contactpersoon, .input-field-factuur_email_contactpersoon, .input-field-factuur_straat, .input-field-factuur_nummer, .input-field-factuur_bus, .input-field-factuur_postcode, .input-field-factuur_gemeente, .input-field-factuur_land, .input-field-factuur_btw-nummer, .input-field-factuur_opmerkingen { display: none; } </code></pre> <p>I want when radio button 2 or 3 is selected show extra fields. I have following script:</p> <pre><code>$("input[name='workshop_wenst_u_een_factuur']").click(function () { $('.input-field-workshop_gelijk_adres').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_bedrijf').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_naam_contactpersoon').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_email_contactpersoon').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_straat').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_nummer').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_bus').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_postcode').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_gemeente').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_land').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_btw-nummer').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'), $('.input-field-factuur_opmerkingen').css('display', ($(this).val() === 'Ik heb wel een factuur nodig.') ? 'block':'none'); }) </code></pre> <p>This does the job when I select the second radio button, how can I make it visible when the third radio button is selected and then disappear again when the first is selected again?</p>
3
1,288
Equality comparison not working in bash script despite echo showing variables are equal
<p>I need to determine that one value set locally in the script matches either one of two values stored on a git repo in a .txt file. I successfully retrieve these values and save them into variables <code>currentVersion</code> and <code>newVersion</code>. I also do this with <code>dispGitTime</code> and <code>gitMESSAGE</code>.</p> <p>What's weird is that these two comparisons are working as expected:</p> <pre><code>if [ "$dispGitTime" = "" ]; then dispGitTime=0; fi if [ ! "$gitMESSAGE" = "" ]; then clear; echo "$gitMESSAGE"; sleep "$dispGitTime"; fi </code></pre> <p>But these two comparisons are not working! <code>else</code> is always being called!</p> <pre><code>if [ "$currentVersion" = "$scriptVersion" ]; then upToDate="true" printf "\n%*s" $((COLS/2)) "This script is up-to-date!"; sleep 1 elif [ "$newVersion" = "$scriptVersion" ]; then upToDate="true" printf "\n%*s" $((COLS/2)) "This script is up-to-date!"; sleep 1 </code></pre> <p>The entire function for context: (see below for output of this function)</p> <pre><code>gitConfigs(){ terminalPath=""; terminalPath=$(pwd) rm -rf ~/upt; mkdir ~/upt; cd ~/upt || return # clone repo or update it with git pull if it exists already (CMD_gitGet); wait cd "$terminalPath" || return # get config values from the master branch's properties.txt currentVersionLine=$(grep -n "_version " ~/upt/$gitName/properties.txt); currentVersion="${currentVersionLine##* }"; echo $currentVersion newVersionLine=$(grep -n "_newVersion " ~/upt/$gitName/properties.txt); newVersion="${newVersionLine##* }"; echo $newVersion gitMESSAGELine=$(grep -n "_gitMESSAGE " ~/upt/$gitName/properties.txt); gitMESSAGE="${gitMESSAGELine##* }" dispGitTimeLine=$(grep -n "_dispGitTime " ~/upt/$gitName/properties.txt); dispGitTime="${dispGitTimeLine##* }" echo $scriptVersion; sleep 2 # set scriptTitle to match config, else use default if scriptTitle=$(grep -n "_scriptTitle " ~/upt/Android-Installer/properties.txt); then scriptTitle="${scriptTitle##* }" else scriptTitle="$scriptTitleDEF"; fi if [ "$currentVersion" = "$scriptVersion" ]; then upToDate="true" printf "\n%*s" $((COLS/2)) "This script is up-to-date!"; sleep 1 elif [ "$newVersion" = "$scriptVersion" ]; then upToDate="true" printf "\n%*s" $((COLS/2)) "This script is up-to-date!"; sleep 1 else upToDate="false" printf "\n\n\n\n\n%*s\n" $((COLS/2)) "This script: v$scriptVersion" printf "\n%*s\n" $((COLS/2)) "Latest version: v$currentVersion" printf "%*s\n" $((COLS/2)) "Version in progress: v$newVersion" printf "\n%*s" $((COLS/2)) "Update required..."; sleep 2 #update fi # display gitMESSAGE if there is one if [ "$dispGitTime" = "" ]; then dispGitTime=0; fi if [ ! "$gitMESSAGE" = "" ]; then clear; echo "$gitMESSAGE"; sleep "$dispGitTime"; fi } </code></pre> <p>Ouput:</p> <pre><code>1.1.6-beta 1.1.7-release 1.1.7-release This script: v1.1.7-release Latest version: v1.1.6-beta Version in progress: v1.1.7-release Update required... </code></pre>
3
1,540
android: jsonArray parsing with Array.sort
<p>My Code works fine. But it is complicate...</p> <p>I get my data via json</p> <pre><code>try{ JSONArray matchdata = null; matchdata = json.getJSONArray("matchdata"); </code></pre> <p>I want to filter only the finished Matches</p> <pre><code>for(int i=0;i&lt;matchdata.length();i++){ JSONObject e = matchdata.getJSONObject(i); //only read finished Matchs if (e.getBoolean("match_is_finished") == true){ </code></pre> <p>I controll the Nr. of finished Matches 126 is OK!</p> <pre><code>Log.e("id", String.valueOf(i)); </code></pre> <p>I get my result in a Array and sort it:</p> <pre><code>Arrays.sort(addressArray, StandingsSort.ORDER_BY_RULES); //Print the sorted array for(int i=0; i&lt;addressArray.length; i++){ mylist[i] = new String(addressArray[i].toString()); } </code></pre> <p>The Code works fine when I delete the line: (and switch to a complete saison, where all matches are finished. 306 Matches)</p> <pre><code>if (e.getBoolean("match_is_finished") == true){ </code></pre> <p>then I get all what I want. But when I Filter the result, the Array.sort does not work. Why?</p> <p>here ist the json <a href="http://openligadb-json.heroku.com/api/matchdata_by_league_saison?group_order_id=3&amp;league_saison=2013&amp;league_shortcut=bl1" rel="nofollow">link:</a></p> <pre><code> }, "league_name": "1. Fussball-Bundesliga 2013/2014", "match_is_finished": false, "match_date_time_utc": "2014-05-10T13:30:00+00:00", "id_team2": "7", "goals": null, "league_saison": "2013", "match_results": null, "group_id": "8820", "icon_url_team1": "http://www.openligadb.de/images/teamicons/Hertha_BSC.gif", "league_shortcut": "bl1", "group_order_id": "34", "icon_url_team2": "http://www.openligadb.de/images/teamicons/Borussia_Dortmund.gif", "last_update": "2013-06-21T22:57:04+00:00", "match_id": "24171", "name_team1": "Hertha BSC", "group_name": "34. Spieltag", "points_team1": "-1", "match_date_time": "2014-05-10T15:30:00+00:00", "name_team2": "Borussia Dortmund" } for(int i=0;i&lt;matchdata.length();i++){ JSONObject e = matchdata.getJSONObject(i); //only read finished Matchs "true".equals(e.getString("name")) if (e.getBoolean("match_is_finished") == true){ //if (null != (e.getString("goals"))){ //calculate Points int myVarGoal1 = Integer.valueOf(e.getString("points_team1")); int myVarGoal2 = Integer.valueOf(e.getString("points_team2")); if ((myVarGoal1) &gt; (myVarGoal2)){ myPoint1 = 3; myPoint2 = 0; } if ((myVarGoal1) &lt; (myVarGoal2)){ myPoint1 = 0; myPoint2 = 3; } if ((myVarGoal1) == (myVarGoal2)){ myPoint1 = 1; myPoint2 = 1; } int calc1 = (map.get(e.getString("id_team1")) + myPoint1); int calc2 = (map.get(e.getString("id_team2")) + myPoint2); map.put("id", Integer.valueOf(i)); map.put(e.getString("id_team1"), calc1); map.put(e.getString("id_team2"), calc2); //calculate Goals int calcGoal1 = (map.get(e.getString("id_team1")+"G+") + myVarGoal1); int calcGoal2 = (map.get(e.getString("id_team1")+"G-") + myVarGoal2); int calcGoal3 = (map.get(e.getString("id_team2")+"G+") + myVarGoal2); int calcGoal4 = (map.get(e.getString("id_team2")+"G-") + myVarGoal1); map.put(e.getString("id_team1")+"G+", calcGoal1); map.put(e.getString("id_team1")+"G-", calcGoal2); map.put(e.getString("id_team2")+"G+", calcGoal3); map.put(e.getString("id_team2")+"G-", calcGoal4); Log.e("id", String.valueOf(i)); } </code></pre>
3
2,220
Cannot delete a row when the trigger is enabled
<p>Help Needed. i have a table and the respective audit table in emp schema.I was not able to delete the entry from the source table when the trigger is enabled. The table is mapped to a trigger as stated below.</p> <p>Below is the generic function , which i have used to audit across all the tables.</p> <pre><code>Function: ============ CREATE OR REPLACE FUNCTION emp.fn_entry_audit() RETURNS trigger LANGUAGE plpgsql AS $function$ declare col_name text:=''; audit_table_name text := TG_TABLE_NAME || '_audit'; begin if TG_OP = 'UPDATE' or TG_OP = 'INSERT' THEN EXECUTE format('INSERT INTO emp.%1$I SELECT ($1).*,'''||TG_OP||'''',audit_table_name) using NEW; else EXECUTE format('INSERT INTO emp.%1$I SELECT ($1).*,'''||TG_OP||'''',audit_table_name) using old; end if; return new; END $function$ Trigger creation ================= create trigger trig_anish before insert or delete or update on emp.test_empname for each row execute procedure acaas.fn_entry_audit() Table ====== create table emp.test_empname(id int4,fname varchar(300) not null,lname varchar(400),salary int4,last_modified_dt timestamp); create table emp.test_empname_audit(id int4,fname varchar(300) not null,lname varchar(400),salary int4,last_modified_dt timestamp,modified_type varchar(10)); </code></pre> <p>The difference between the two is modified_type column, which will mention whether the data is of insert, update or delete(TG_OP from above function).</p> <p>now when i insert the values in emp.test_empname, it is getting inserted correctly in emp.test_empname_audit.</p> <pre><code>select * from emp.test_empname; emp.test_empname: ================== id fname lname salary last_modified_dt =============================================================== 1 stacker pentacost 1000 04-04-18 2 lyri pav 2000 04-04-18 3 TEST TEST1 1000 04-04-18 select * from emp.test_empname_audit; id fname lname salary last_modified_dt modified_type =============================================================== 1 stacker pentacost 1000 04-04-18 INSERT 2 lyri pav 1000 04-04-18 INSERT 2 lyri pav 2000 04-04-18 UPDATE 3 TEST TEST1 1000 04-04-18 Delete </code></pre> <p>Now, the issue is whenever I perform delete on source table (test_empname), the query is executing fine, but it shows 0 rows affected. when i query in the table select * from test_empname where id=3, it still exists.But you can see the entry in audit as delete.</p> <p>I disabled the trigger and performed delete function ,it executes fine and the row gets affected.How is the trigger affecting my delete functionality.Please help!!</p>
3
1,073
Drag-and-Drop Furniture into room
<p>I got this room, and some furniture.<br> <strong>1.</strong> I would like so the furniture is above the floor instead of under the floor, when dropping the furniture.<br> <strong>2.</strong> I would like swapping furniture, so when you drop a furniture onto the floor where there already is a furniture it should swap place.</p> <p><a href="http://lolk3070.dk/roomtest/index.html" rel="nofollow noreferrer">This is what I have made for now...</a></p> <p><strong>My 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-js lang-js prettyprint-override"><code>$(document).ready(function() { $('#div2').on("drop", function(e) { e.preventDefault(); e.stopPropagation(); }); }); function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#floor { top:116px; left:393px; position:absolute; margin-bottom: 10px; height: 40px; width: 65px; background-image: url("http://i.imgur.com/tCuykFV.png") } #floor:hover { height: 43px; width: 66px; background-image: url("http://i.imgur.com/Eo1dNNv.png") } #space { width:200px; } #div3 { float: right; border: 1px solid #CCC; margin-bottom: 10px; height: 200px; width: 102px; } #dice { width:56px; height:79px; } #walls { position:absolute; top:0px; left:0px; width:688px; height:510px; border: 1px solid #CCC; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt; &lt;script type="text/javascript" src="js.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;img id="walls" src="http://i.imgur.com/FA6ka0v.png"&gt; &lt;div id="floor" ondrop="drop(event)" ondragover="allowDrop(event)"&gt;&lt;/div&gt; &lt;div id="floor" ondrop="drop(event)" ondragover="allowDrop(event)" style="top:132px;left:424px;"&gt;&lt;/div&gt; &lt;div id="floor" ondrop="drop(event)" ondragover="allowDrop(event)" style="top:132px;left:360px;"&gt;&lt;/div&gt; &lt;div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)"&gt; &lt;div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"&gt; &lt;img src="https://hydra-media.cursecdn.com/habbo.gamepedia.com/e/ed/Edicehc.png?version=6e01ba71341b8361df23749c65498f44" draggable="true" ondragstart="drag(event)" id="drag1" width="56" height="79"&gt; &lt;img src="https://hydra-media.cursecdn.com/habbo.gamepedia.com/0/0f/Mocchamaster.png?version=6cf4d970f845287fa21d4ef7691eee84" draggable="true" ondragstart="drag(event)" id="drag2" width="66" height="137"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3
1,292
Find and Delete Median In C Binary Search Tree
<p>I am working on Data structures in C and i need to find the Median of the values in the B.S.T and delete the median then showcase the new B.S.T but i haven't managed.I don't really know where am going wrong.Please help me out on this. I also need to be able to find a value that is closest to the mean and delete it</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; struct Node { int key; struct Node* left, *right; }; //Function to create new BST NODE struct Node *newNode (int item) { struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp-&gt;key = item; temp-&gt;left = temp-&gt;right = NULL; return temp; } //Function to perform INORDER traversal operation void inorder(struct Node *root) { if(root!=NULL) { inorder(root-&gt;left); printf("%d\n",root-&gt;key); inorder (root-&gt;right); } } //Function to insert new node with given key in BST struct Node* insert (struct Node* node, int key) { //if tree is empty if(node==NULL) return newNode(key); //else, recur down the tree if(key&lt; node-&gt;key) node-&gt;left = insert(node-&gt;left,key); else if(key &gt; node-&gt;key) node-&gt;right = insert(node-&gt;right,key); //Return the (unchanged) node pointer return node; } //Given a non-empty BST ,return node with minimum key value found in that tree. Whole tree not really searched struct Node * minValueNode(struct Node* node) { struct Node* current =node; //loop down to find the left-most leaf while (current-&gt;left !=NULL) current = current-&gt;left; return current; } //Given the BST and key, function to deleted the key to return new root struct Node* deleteNode(struct Node* root, int key) { if(root == NULL) return root; if(key&lt;root-&gt;key) root-&gt;left = deleteNode(root-&gt;left,key); else if (key&gt; root-&gt;key) root-&gt;right = deleteNode(root-&gt;right, key); else { //node with one or no child if(root-&gt;left == NULL) { struct Node *temp = root-&gt;right; free(root); return temp; } else if (root-&gt;right == NULL) { struct Node *temp = root-&gt;left; free(root); return temp; } //node with two children struct Node* temp = minValueNode(root-&gt;right); //copy the inorder successor to this node root-&gt;key = temp-&gt;key; //delete the inorder successor root-&gt;right = deleteNode(root-&gt;right, temp-&gt;key); } return root; } //Function to count nodes in a BST using Morris Inorder traversal int counNodes(struct Node *root) { struct Node *current, *pre; int count =0; if(root == NULL) return count; current = root; while(current!=NULL) { if(current-&gt;left == NULL) { count++; current = current-&gt;right;; } else { pre = current-&gt;left; while(pre-&gt;right !=NULL &amp;&amp; pre-&gt;right !=current) pre=pre-&gt;right; if(pre-&gt;right == NULL) { pre-&gt;right = current; current= current-&gt;left; } else { pre-&gt;right = NULL; count++; current = current-&gt;right; } } } return count; } /*FUNCTION TO FIND MEDIAN */ int FINDM(struct Node *root) { if(root == NULL) return 0; int count = counNodes(root); int currCount=0; struct Node *current = root, *pre, *prev; while(current !=NULL) { if(current-&gt;left == NULL) { currCount++; if(count%2!=0 &amp;&amp; currCount ==(count+1)/2) return (prev-&gt;key); //EVEN NUMBERS else if(count%2==0 &amp;&amp; currCount==(count/2)+1) return (prev-&gt;key + current-&gt;key)/2; prev = current; current = current-&gt;right; } else { pre=current-&gt;left; while(pre-&gt;right !=NULL &amp;&amp; pre-&gt;right !=current) pre= pre-&gt;right; if(pre-&gt;right = NULL) { pre-&gt;right = current; current = current-&gt;left; } else { pre-&gt;right = NULL; prev = pre; currCount++; if(count%2!=0 &amp;&amp; currCount == (count+1)/2) return (current-&gt;key); else if(count%2==0 &amp;&amp; currCount == (count/2)+1) return (prev-&gt;key+current-&gt;key)/2; prev = current; current = current-&gt;right; } } } } //Driver Program to test functions above int main() { // values are 28,90,0,32,56,78,212,34,62 struct Node *root =NULL; root=insert(root,65); insert(root, 28); insert(root, 90); insert(root,0); insert(root, 32); insert(root,56); insert(root, 78); insert(root,212); insert(root,34); insert(root,62); printf("InOrder Traversal of Tree\n"); inorder(root); printf("\nDelete 65!\n"); root=deleteNode(root,65); printf("Modified Tree\n"); inorder(root); printf("\nMEDIAN "); FINDM(root); return 0; } </code></pre>
3
2,574
Libgdx how to create new objects of body to draw dynimcally
<p>I am trying to make a game where apples will fall from sky and allow boy to eat them I had already made the environment and the boy and one apple falling correctly but I want to make more objects of the apple to fall from sky at specific time how can I repeat the calling of apple class, where I have to call it I built the apple body inside the apple class and use it inside the PlayScreen class and this is the code: Apple class: </p> <pre><code>public class Apple extends Sprite { public PlayScreen screen; public World world; public Apple apple; public Body b2body; public Vector2 velocity; public float counter; private TextureRegion Apple; //private Animation collectorRu; private float stateTimer; private boolean toDestroy; private boolean destroyed; public Apple(World world,PlayScreen screen) { super(screen.getAtlas().findRegion("boys3")); this.screen=screen; this.world=world; stateTimer=0; defineApple(); Apple=new TextureRegion(getTexture(),0,0,120,120); setBounds(0, 0, 20 / Fruits.PPM, 20 / Fruits.PPM);//here we can change the size of our Animation setRegion(Apple); toDestroy=false; destroyed=false; velocity=new Vector2(0,-2); counter=0; } public void defineApple() { BodyDef bdef=new BodyDef(); bdef.position.set(100/Fruits.PPM,200/Fruits.PPM); bdef.type=BodyDef.BodyType.DynamicBody; b2body=world.createBody(bdef); FixtureDef fdef=new FixtureDef(); //PolygonShape shape=new PolygonShape(); CircleShape shape=new CircleShape(); shape.setRadius(7 / Fruits.PPM); fdef.filter.categoryBits=Fruits.APPLE_BIT; fdef.filter.maskBits=Fruits.GROUND_BIT | Fruits.COLLECTOR_BIT; fdef.shape=shape; b2body.createFixture(fdef).setUserData(this); } public void update(float dt) { stateTimer += dt; if(toDestroy&amp;&amp;!destroyed) { world.destroyBody(b2body); destroyed=true; stateTimer=0; } if(!destroyed) { b2body.setLinearVelocity(velocity); setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2); } } public void draw(Batch batch) { if(!destroyed ) { super.draw(batch); } } public void hit() { toDestroy=true; } } </code></pre> <p>the Playscreen class:</p> <pre><code>public class PlayScreen implements Screen { private Fruits game; private TextureAtlas atlas; private OrthographicCamera gamecam; private Viewport gameport; private Hud hud; private TmxMapLoader mapLoader; private TiledMap map; private OrthogonalTiledMapRenderer renderer; private World world; private Box2DDebugRenderer b2dr; private Collector player; private boolean right=true; private boolean left=true; private Apple apple; public float counter; private Controller controller; public PlayScreen(Fruits game) { this.game=game; gamecam=new OrthographicCamera(); gameport=new FitViewport(Fruits.V_WIDTH/Fruits.PPM,Fruits.V_HIEGT/Fruits.PPM,gamecam); hud=new Hud(game.batch); atlas=new TextureAtlas("mypack.pack"); mapLoader=new TmxMapLoader(); map=mapLoader.load("level3.tmx"); renderer=new OrthogonalTiledMapRenderer(map,1/Fruits.PPM); gamecam.position.set(gameport.getWorldWidth()/2,gameport.getWorldHeight()/2f,0); world=new World(new Vector2(0,-10),true); b2dr=new Box2DDebugRenderer(); new B2WorldCreator(this); player=new Collector(world,this); world.setContactListener(new WorldContactListener()); controller=new Controller(game.batch); apple=new Apple(world,this); counter=0; } @Override public void show() { } public TextureAtlas getAtlas() { return atlas; } public void handleinput(float dt) { if (controller.isRightPressed()&amp;&amp;player.b2body.getPosition().x&lt;3.7f) { if(right) player.b2body.applyLinearImpulse(new Vector2(0.3f, 0), player.b2body.getWorldCenter(), true); else { player.b2body.setLinearVelocity(0, 0); right=true; left=false; } //player.b2body.setTransform(player.b2body.getPosition().x+0.05f,player.b2body.getPosition().y,player.b2body.getAngle()); } if (controller.isLeftPressed()&amp;&amp;player.b2body.getPosition().x&gt;0.26f ) { if(left) player.b2body.applyLinearImpulse(new Vector2(-0.3f, 0), player.b2body.getWorldCenter(), true);//5 else { player.b2body.setLinearVelocity(0, 0); right=false; left=true; } //player.b2body.setTransform(player.b2body.getPosition().x - 0.05f, player.b2body.getPosition().y, player.b2body.getAngle()); } if (controller.isUpPressed() &amp;&amp; player.b2body.getLinearVelocity().y == 0) { player.b2body.applyLinearImpulse(new Vector2(0, 4), player.b2body.getWorldCenter(), true); } } public void update(float dt) { handleinput(dt); world.step(1 / 60f, 6, 2); player.update(dt); apple.update(dt); gamecam.update(); renderer.setView(gamecam); } public TiledMap getMap()//12 this is for Goomba { return map; } public World getWorld() { return world; } @Override public void render(float delta) { update(delta); Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); renderer.render(); b2dr.render(world, gamecam.combined); game.batch.setProjectionMatrix(gamecam.combined); game.batch.begin(); //Gdx.app.log("hi","hello"); counter+=delta; player.draw(game.batch); apple.draw(game.batch); game.batch.end(); game.batch.setProjectionMatrix(hud.stage.getCamera().combined); hud.stage.draw(); controller.draw(); } @Override public void resize(int width, int height) { gameport.update(width,height); controller.resize(width, height); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { map.dispose(); renderer.dispose(); world.dispose(); b2dr.dispose(); hud.dispose(); } } </code></pre>
3
3,094
Query executing multiple times when using google social login with passport and sequelize
<p>Hi Guys this is my first question so please be patient, I'm having a problem using passport with sequelize, the problem happens after i search at the database for the record to check if the user already exists but when passport deserializes it, Sequelize executes five 'select queries', the code is similar to one i found in scotch.io i just attached sequelize api to it:</p> <pre><code>module.exports = function (passport) { // used to serialize the user for the session passport.serializeUser(function (user, done) { done(null, user.iduser); }); // used to deserialize the user passport.deserializeUser(function (id, done) { userModel.findById(id) .then(function (userVo) { done(null, userVo); }).catch(function(err) { if(err) throw err; }) }); passport.use(new GoogleStrategy({ clientID: 'XXXXX', clientSecret: 'XXXXXX', callbackURL: 'XXXXX' }, function (token, refreshToken, profile, done) { // make the code asynchronous // User.findOne won't fire until we have all our data back from Google process.nextTick(function () { // try to find the user based on their google id sequelize.transaction(function (t) { return sociaLoginModel.findOne({ where: { idprovided: profile.id, logintype: constants.GOOGLE_LOGIN_TYPE } }, { transaction: t }) .then(function (socialLoginResult) { //if user was found, then retrieve and create a session for him returning the value to done var socialLoginVo; if (socialLoginResult) { socialLoginVo = socialLoginResult.dataValues return userModel.findById(socialLoginVo.tb11_fkuser, { transaction: t }) .then(function (userResult) { return userResult.dataValues; }); } else { return individualsModel.create({ name: profile.displayName }, { transaction: t }) .then(function (individualsResult) { var individualsVo = individualsResult.dataValues return userModel.create({ email: profile.emails[0].value, user_type: constants.USER_INDIVIDUALS, tb12_fkindividuals: individualsVo.idindividuals }, { transaction: t }) .catch(function (err) { if (err) throw err; }) .then(function (userResult) { var userVo = userResult.dataValues console.log(typeof profile.id) return sociaLoginModel.create({ idprovided: profile.id, token: token, logintype: constants.GOOGLE_LOGIN_TYPE, tb11_fkuser: userVo.iduser }, { transaction: t }) .then(function (sociaLoginResult) { return userVo }) .catch(function(err) { if(err) throw err; }) }) }).catch(function(err) { if(err) throw err }) } }).catch(function(err) { if(err) throw err }) }).then(function (result) { return done(null, result); }).catch(function (err) { if (err) return done(err) }); }) })) }; </code></pre> <p>This code is in a file and i use it as a middleware in app.js calling:</p> <pre><code>require('./logins/google')(passport); </code></pre> <p>I do that with local-login and facebook too, as almost the same code as in google login, why does Sequelize is executing that number of queries?? Am i doing something wrong?? How can i minimize that number? Thanks.</p>
3
4,165
POSIX shell function: printing arguments as a TSV record
<p>I'm writing a POSIX shell function that prints its arguments as a TSV record. <br> Each argument is escaped with the following rules:</p> <ul> <li><code>\n</code> for newline</li> <li><code>\t</code> for tab</li> <li><code>\r</code> for carriage return</li> <li><code>\\</code> for backslash</li> </ul> <p>Here is the function:</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh tsv_print() { rec= for str in &quot;$@&quot; do esc= i=${#str} until [ $i -eq 0 ] do end=&quot;${str#?}&quot; chr=&quot;${str%&quot;$end&quot;}&quot; case $chr in &quot;$__TAB__&quot;) chr='\t' ;; &quot;$__LF__&quot;) chr='\n' ;; &quot;$__CR__&quot;) chr='\r' ;; \\) chr='\\' ;; esac esc=&quot;$esc$chr&quot; str=&quot;${end}&quot; i=$((i-1)) done rec=&quot;$rec${rec:+&quot;$__TAB__&quot;}$esc&quot; done # echo &quot;$rec&quot; printf '%s\n' &quot;$rec&quot; } </code></pre> <p>With the — <em>painful to read in code</em> — characters stored beforehand as follows:</p> <pre><code>__TAB__=$(printf '\t') __CR__=$(printf '\r') __LF__=&quot; &quot; </code></pre> <hr /> <p>I would like to know:</p> <ol> <li><p><s>Why doesn't my code escape the characters at all?</s></p> <p><sup><em><strong>edit:</strong></em> As @GordonDavisson pointed out, <code>echo</code> was the culprit!! Using <code>printf</code> seems to be the only portable way, with the cost of a possible fork.</sup></p> </li> <li><p>Is there a better, POSIX compliant, method to do it? <code>awk</code> and <code>sed</code> don't seem appropriate for the job...</p> </li> <li><p>How would you do the un-escaping?</p> <p><sup><em><strong>edit:</strong></em> As @KamilCuk posted in his <a href="https://stackoverflow.com/a/70049950/3387716">answer</a>, a <code>printf '%b'</code> would suffice; the TSV record has the correct format for that.</sup></p> </li> </ol> <hr /> <h5>postscript</h5> <p>In the end, the function wasn't needed because the input didn't contain any character to escape. That said, the input format wasn't that straight-forward to convert. It was a <a href="https://en.wikipedia.org/wiki/Self-defining_Text_Archive_and_Retrieval" rel="nofollow noreferrer">STAR File</a> with varying number of columns per line (limiting the lines to 80 characters max) and containing quoted strings...</p> <p>input:</p> <pre><code>... loop_ _refl_0201 _refl_0012 _refl_2003 _refl_1600 _refl_1304 _refl_1305 _refl_1800 _refl_1801 _refl_1802 _refl_1803 _refl_1804 _refl_1805 _refl_1806 _refl_1701 _refl_1700 _refl_1202 '0 0 6' .147364 Z000020c1 .41 1 78.45 3.501 35.2221 -35.2221 0 -1.6055 -3.0963 -36.7288 -5.0964 39.3109 5.909983 '0 0 12' .294551 Z000010c1 .9 1 48.44 2.3805 39.910008 39.9101 .268379-04 1.75598 3.09745 41.6656 3.09809 47.8384 0 .939517 ... </code></pre> <p>output (separators are tabs):</p> <pre><code>_refl_0201 _refl_0012 _refl_2003 _refl_1600 _refl_1304 _refl_1305 _refl_1800 _refl_1801 _refl_1802 _refl_1803 _refl_1804 _refl_1805 _refl_1806 _refl_1701 _refl_1700 _refl_1202 '0 0 8' .147364 Z000020c1 .41 1 78.45 3.501 35.2221 -35.2221 0 -1.6055 -3.0963 -36.7288 -5.0964 39.3109 5.909983 '0 0 14' .294551 Z000010c1 .9 1 48.44 2.3805 39.910008 39.9101 .268379-04 1.75598 3.09745 41.6656 3.09809 47.8384 0.939517 ... </code></pre>
3
1,605
using two data tables in a procedure SQL
<p>I was put in a situation where I was forced to create a procedure that uses two data tables such as this:</p> <pre><code>ALTER PROCEDURE [sesuser].[Login_GetUserList] ( @beginsWith NVARCHAR(20) = NULL, @SortBy nvarchar(20) = NULL, @sortByDirection nvarchar(5) = N'ASC' ) AS BEGIN DECLARE @searchStr NVARCHAR(21) IF @beginsWith IS NULL SET @beginsWith = N'' ELSE SET @beginsWith = dbo.SuperTrim(@beginsWith); IF LEN(@beginsWith) &gt; 0 SET @searchStr = @beginsWith + N'%' ELSE SET @searchStr = N'%' DECLARE @sqlSTR NVARCHAR(4000) DECLARE @sqlOffice NVARCHAR(100) DECLARE @sqlOfficeID NVARCHAR(10) DECLARE @sqlEndSTR NVARCHAR(4000) SET @sqlSTR = N' SELECT [SESLoginID] AS LoginID ,[SESSuspended] AS LoginSuspended ,[SESAdmin] AS Role_Admin ,[SESLoginID] ,[SESFirstName] ,[SESLastName] ,[SESEmail] ,[SESSuspended] FROM sesuser.SESLogin WHERE SESFirstName LIKE ''' + @searchStr + '''' SET @sqlOfficeID = N' SELECT [SESLoginID] FROM sesuser.SESLogin WHERE SESFirstName LIKE ''' + @searchStr + '''' SET @sqlOffice = N' SELECT [OfficeName] FROM sesuser.Office WHERE OfficeID LIKE ''' + @sqlOfficeID + '''' SET @sqlEndSTR = @sqlSTR + @sqlOffice PRINT @sqlEndSTR EXEC sp_ExecuteSQL @sqlEndSTR END </code></pre> <p>so as I understand it, this code supposed to in a table of office IDs and equivalent Office Name to replace the office ID with a Name in the other table and return it.</p> <p>I then use the retrieve data string in a method in my c# code:</p> <pre><code>public static DataTable GetUserList(string beginsWith, out string errMessage, string sortBy, string sortByDirection) { DataTable dt = null; int errNum = 0; string sql = "[sesuser].[Login_GetUserList]"; SqlDataAdapter adap = null; SqlParameter param = null; errMessage = ""; SqlConnection conn = Functions.Database.DBConnect(out errNum); try { SqlCommand cmd = new SqlCommand(sql); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; param = new SqlParameter("@beginsWith", SqlDbType.NVarChar, 40); param.Value = string.IsNullOrEmpty(beginsWith) ? "" : beginsWith.Trim(); cmd.Parameters.Add(param); cmd.Parameters.AddWithValue("@SortBy", sortBy); cmd.Parameters.AddWithValue("@sortByDirection", sortByDirection); adap = new SqlDataAdapter(cmd); dt = new DataTable(); adap.Fill(dt); } catch (Exception ex) { errMessage = ex.Message; } finally { Functions.Database.DBClose(conn); } return dt; } </code></pre> <p>and later in my asp.net code I call back office name</p> <pre><code>&lt;asp:BoundField DataField="OfficeName" HeaderText="Business Unit" ReadOnly="True" /&gt; </code></pre> <p>The problem is, it errors, saying that it cant find <code>OfficeName</code>.</p> <p>Is there something I forgot? Or am I doing it wrong?</p>
3
1,265
Django,DRF, get another app's view name for a reverse
<p>I'm trying to create a link for another app in my serializer using the solution provided here:</p> <p><a href="https://stackoverflow.com/a/45850334/12177026">https://stackoverflow.com/a/45850334/12177026</a></p> <p>I'm trying to match the view's name but every way I try I get this error:</p> <pre><code>Reverse for 'KnownLocationView' not found. 'KnownLocationView' is not a valid view function or pattern name. </code></pre> <p>serializers:</p> <pre class="lang-py prettyprint-override"><code>class MissionSerializer(HyperlinkedModelSerializer): gdt = ChoiceField(choices=lazy(get_locations, tuple)()) location = SerializerMethodField(label='Open Location') def get_location(self, obj): request = self.context.get('request') return request.build_absolute_uri(reverse('KnownLocationView', kwargs={'Name': obj.gdt})) class Meta: model = Mission fields = ('MissionName', 'UavLatitude', 'UavLongitude', 'UavElevation', 'Area', 'gdt', 'location') </code></pre> <p>KnownLoction/urls.py</p> <pre class="lang-py prettyprint-override"><code>from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import KnownLocationView app_name = 'KnownLocation' router = DefaultRouter() router.register(r'knownlocations', KnownLocationView) urlpatterns = [ path('', include(router.urls)), ] </code></pre> <p>I tried replacing view_name with either of the following:</p> <pre><code>'knownlocations' 'KnownLocation:knownlocations' 'KnownLocation:KnownLocationView' </code></pre> <p>But get the same error</p> <p>even tried to reorder the installed apps.</p> <p>api/urls.py:</p> <pre class="lang-py prettyprint-override"><code> urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', include('landingpage.urls')), # API Landing Page path('', include('ThreeLocations.urls')), # Triangulation between two Known GDTs and uav location. path('', include('SecondGDT.urls')), # Options For Second GDT Positioning. path('', include('KnownLocation.urls', namespace='knownlocations')), # Add Known Location To the map. ] + staticfiles_urlpatterns() </code></pre> <p>KnownLocation/views.py</p> <pre class="lang-py prettyprint-override"><code>from rest_framework.renderers import AdminRenderer from rest_framework.viewsets import ModelViewSet from .models import KnownLocation from .serializers import KnownLocationSerializer class KnownLocationView(ModelViewSet): """ List of Known Locations In which we can place one of our ground positions. press create to add a new location. """ serializer_class = KnownLocationSerializer queryset = KnownLocation.objects.all() def get_serializer_context(self): data = KnownLocationSerializer(self.queryset, many=True, context={'request': self.request}) return data renderer_classes = [AdminRenderer] </code></pre>
3
1,156
Why can't I get touch input (Unity with C#) to work?
<p>I'm trying to finish the Android game I've been working on. I first made to controlling mechanism using mouse, but as it needs to work with multitouch for the shot button and the aiming area, I tried converting the script to touch input according to tutorials but it doesn't seem to register any touch.</p> <p>Also, I wanted the script to record whether one of the touches, regardless of order, was placed on the area for either shot or aiming control when it begun, and place that in a Vector3 list. When respectable touch is lifted, it resets the value in that list index. Then, for example, the shooting script checks whether one of the list values is within the range of the shooting button radius, so it activates the weapon loading. It keeps telling me this error: </p> <blockquote> <p>ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index</p> </blockquote> <pre><code>Here are the class codes for the touch inputs and for the shooting button: using System.Collections; using System.Collections.Generic; using UnityEngine; public class TouchControls : MonoBehaviour { public static bool shotTime = false; public static List &lt;Vector3&gt; position = new List&lt;Vector3&gt;(2); public static bool moveTime = false; // Start is called before the first frame update void Start() { position[0] = new Vector3(0, 0, 0); position[1] = new Vector3(0, 0, 0); } // Update is called once per frame void Update() { for (int i = 0; i &lt; Input.touchCount &amp;&amp; i &lt; 2; i++) { Debug.Log("Touch"); Touch touch = Input.GetTouch(i); Vector3 pos = Camera.main.ScreenToWorldPoint(touch.position); pos.z = 0; if (touch.phase == TouchPhase.Began) { position[i] = pos; } if (touch.phase == TouchPhase.Ended) { position[i] = new Vector3(0, 0, 0); } } Debug.Log(position[0] + position[1]); } } </code></pre> <hr> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShotButton : MonoBehaviour { public static bool time = false; private Vector3 scale; // Start is called before the first frame update void Start() { scale = gameObject.transform.localScale; } // Update is called once per frame void Update() { { if (Vector2.Distance(gameObject.transform.position, TouchControls.position[0]) &lt; scale.x || Vector2.Distance(gameObject.transform.position, TouchControls.position[1]) &lt; scale.x) { time = true; gameObject.transform.localScale = scale * 0.9f; } else { time = false; gameObject.transform.localScale = scale; } } } } </code></pre> <p>What is wrong with the code? How can I fix it?</p>
3
1,200
Bug in JavaFX by binding with middle man onto slider value property?
<p>I stumbled upon a problem using a slider in JavaFX.<br> I create a fxml-file with a <em>Slider</em> and add a controller to it.<br> Inside the controller I have a <em>DoubleProperty</em>, which binds to the <em>Slider</em>'s <em>valueProperty</em>. Then, when I want to bind to this property from somewhere else, I bind to the property, which is inside the controller (some kind of a middle-man approach see Figure).<br> <a href="https://i.stack.imgur.com/cQ7Dq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cQ7Dq.png" alt="enter image description here"></a><br> But when I do so, it does not work properly. </p> <p>When I use the slider, the values get updated accordingly for a while, but when I wiggle it around, at some point it seems to stop updating the binding and refuses to do so again even after releasing and pressing it again.<br> When I delete the middle-man property in the controller and just pipe through the <em>valueProperty</em> from the slider directly, it is working. </p> <p><strong>Program:</strong><br> Main.java </p> <pre><code>public class Main extends Application{ private MainController controller; @Override public void start(Stage primaryStage) throws Exception { FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("main.fxml")); Parent root = loader.load(); controller = loader.getController(); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); showSlider(); } private void showSlider() { SliderShower sliderShower = new SliderShower(); sliderShower.show(); sliderShower.getSliderValueProp().addListener(((observable, oldValue, newValue) -&gt; { controller.setText(Double.toString((double)newValue)); })); } public static void main(String[] args) { launch(args); } } </code></pre> <p>main.fxml </p> <pre><code>&lt;?import javafx.scene.control.Label?&gt; &lt;?import javafx.scene.layout.ColumnConstraints?&gt; &lt;?import javafx.scene.layout.GridPane?&gt; &lt;?import javafx.scene.layout.RowConstraints?&gt; &lt;GridPane prefHeight="100.0" prefWidth="100.0" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sliderBug.main.MainController"&gt; &lt;columnConstraints&gt; &lt;ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" /&gt; &lt;/columnConstraints&gt; &lt;rowConstraints&gt; &lt;RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /&gt; &lt;/rowConstraints&gt; &lt;children&gt; &lt;Label fx:id="label" text="Label" /&gt; &lt;/children&gt; &lt;/GridPane&gt; </code></pre> <p>MainController.java </p> <pre><code>public class MainController { @FXML private Label label; public void setText(String text) { label.setText(text); } } </code></pre> <p>SliderShower.java </p> <pre><code>public class SliderShower { private Parent root; private SliderShowerController controller; private Stage stage; private DoubleProperty sliderValueProp; public SliderShower() { sliderValueProp = new SimpleDoubleProperty(0); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("sliderShower.fxml")); try { root = loader.load(); controller = loader.getController(); stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); stage.setScene(new Scene(root)); sliderValueProp.bind(controller.getSliderValueProp()); } catch (IOException e) { e.printStackTrace(); } } public DoubleProperty getSliderValueProp() { return sliderValueProp; // This does not work // return controller.getSliderValueProp(); // This would work } public void show() { stage.show(); } } </code></pre> <p>sliderShowerController.java</p> <pre><code>public class SliderShowerController { @FXML private Slider sliderUI; DoubleProperty getSliderValueProp() { return sliderUI.valueProperty(); } } </code></pre> <p>sliderShower.fxml </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?import javafx.scene.control.Slider?&gt; &lt;?import javafx.scene.layout.ColumnConstraints?&gt; &lt;?import javafx.scene.layout.GridPane?&gt; &lt;?import javafx.scene.layout.RowConstraints?&gt; &lt;GridPane prefHeight="100.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sliderBug.sliderShower.SliderShowerController"&gt; &lt;columnConstraints&gt; &lt;ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" /&gt; &lt;/columnConstraints&gt; &lt;rowConstraints&gt; &lt;RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /&gt; &lt;/rowConstraints&gt; &lt;children&gt; &lt;Slider fx:id="sliderUI" max="200.0" min="1.0" /&gt; &lt;/children&gt; &lt;/GridPane&gt; </code></pre> <p>Here is a link to a repository depicting the problem:<br> <a href="https://github.com/Chrisss50/sliderBug" rel="nofollow noreferrer">https://github.com/Chrisss50/sliderBug</a> </p> <p>Am I doing something wrong or is this just a bug? </p> <p>Greetings</p>
3
2,188
Dependent dropdown
<p>i have a problem in dependent dropdown and i am not professional in this issue </p> <p>so the problem is when i choose the first one the another one doesnt get any value from database and i didnt know the solution</p> <pre><code>&lt;?php include 'header.php'; require 'connection.php'; ?&gt; &lt;div class="container"&gt; &lt;form id="contact" action="add_line.php" method="post"&gt; &lt;center&gt; &lt;h3&gt;Add Line&lt;/h3&gt;&lt;/center&gt; &lt;fieldset&gt; &lt;?php require 'connection.php'; $query = "select * from agents"; $result = mysqli_query($conn,$query); ?&gt; &lt;div class="select"&gt; &lt;select class="agents-name " name="agents-name" autofocus tabindex="1"&gt; &lt;option selected="selected"&gt;--Select agent--&lt;/option&gt; &lt;?php while ($row = mysqli_fetch_assoc($result)): ?&gt; &lt;option value="&lt;?php $row['id'];?&gt;"&gt;&lt;?php echo $row['name'];?&gt;&lt;/option&gt; &lt;?php endwhile;?&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="select" &gt; &lt;select tabindex="1" name="sp_choosen" class="sp_choosen" onChange="getState( this.value );" tabindex="2"&gt; &lt;option selected="selected"&gt;--Select service provider--&lt;/option&gt; &lt;option value="CELLCOM"&gt;CELLCOM&lt;/option&gt; &lt;option value="HoTMobile"&gt;HoTMobile&lt;/option&gt; &lt;option value="Orange"&gt;Orange&lt;/option&gt; &lt;option value="Pelphone"&gt;Pelphone&lt;/option&gt; &lt;option value="Golan"&gt;Golan&lt;/option&gt; &lt;option value="019"&gt;019&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="select"&gt; &lt;select id="packet_select" name="packet_chossen" tabindex="3"&gt; &lt;option selected="selected"&gt;--Select packet--&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;input placeholder="customer name" type="text" tabindex="4" name="customer_name" required &gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;input placeholder="SIM_SERIAL" type="tel" tabindex="5" name="sim_serial" required &gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;input placeholder="phone_number" type="tel" tabindex="6" name="number" required &gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;label&gt;&lt;/label&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;button name="submit" type="submit" id="contact-submit" tabindex="7" &gt;Add Available line&lt;/button&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/div&gt; &lt;script src="https://code.jquery.com/jquery-1.9.1.min.js"&gt;&lt;/script&gt; &lt;script&gt; function getState(val) { $.ajax({ type: "POST", url: "dropdown_add_line.php", data:'sp='+val, success: function(data){ $("#packet_select").html(data); } }); } &lt;/script&gt; &lt;?php include 'footer.php'; ?&gt; </code></pre> <p>and this is the dropdown_add_line.php :</p> <pre><code>&lt;?php require_once("connectione.php"); $db_handle = new DBController(); if(!empty($_POST["sp"])) { $sp=$_POST['sp']; $query ="SELECT * FROM packets p WHERE sp LIKE '%$sp%'"; $results = $db_handle-&gt;runQuery($query); ?&gt; &lt;option value=""&gt;--Select service provider--&lt;/option&gt; &lt;?php foreach($results as $packets) { ?&gt; &lt;option value= "&lt;?php echo $packets["id"]; ?&gt;" &gt;&lt;?php echo $packets["packet"]; ?&gt;&lt;/option&gt; &lt;?php } } ?&gt; </code></pre> <p>and the table name is "packets" and the columns is "id","sp","packet" </p>
3
1,449
Call to a member function get() when calling a doctrine 2 entity form the service locator
<p>I am new to Doctrine 2 and ZF2.</p> <p><strong>My problem:</strong> I go to the route <code>myPage/bnk</code> that instantiates the class <code>BnkController</code> and the method <code>indexAction</code> if I try to access the <code>getEntityManager</code> method <strong>from there it all works</strong>. </p> <p>Now when I instantiate the class <code>DataManager</code> in the method <code>indexAction</code> and then I try to call the <code>getEntityManager</code> method inside the class <code>DataManager</code> I get <code>Fatal error: Call to a member function get() on a non-object</code> which I dont understand why is happening if it is all working in the <code>BnkController</code></p> <p>Why I am getting this error when I try to get the doctrine <code>EntityManager</code> from the <code>getServiceLocator</code> inside the class <code>DataManager</code>? </p> <pre><code>class BnkController extends AbstractActionController { public function indexAction () { $this-&gt;uploadCSVAction( "data/bnk.csv" ); } public function uploadCSVAction ( $fileName ) { $parseCSV = new CsvParser(); $dataManager = new DataManager(); // Transforms CSV into Array $CSVData = $parseCSV-&gt;parseCSV( $fileName ); // Makes sure that we are only using the right transactions and no overlap is happening $CSVData = $dataManager-&gt;validateTransactions($CSVData,$parseCSV); $dataManager-&gt;saveCSVDataToDB( $CSVData ); } /** * @return \Doctrine\ORM\EntityManager */ protected function getEntityManager () { /** @var \Doctrine\ORM\EntityManager $objectManager */ $objectManager = $this -&gt;getServiceLocator() -&gt;get( 'Doctrine\ORM\EntityManager' ); return $objectManager; } </code></pre> <p>DataManager</p> <pre><code>&lt;?php namespace Bnk\Controller; /** * Class DataManager * * @package Bnk\Controller */ class DataManager { /** * @return \Bnk\Repository\Transaction */ protected function getTransactionRepository () { /** @var \Bnk\Repository\Transaction $repository */ $repository = $this-&gt;getEntityManager()-&gt;getRepository( 'Bnk\Entity\Transaction' ); return $repository; } /** * @return \Doctrine\ORM\EntityManager */ protected function getEntityManager () { /** @var \Doctrine\ORM\EntityManager $objectManager */ $objectManager = $this -&gt;getServiceLocator() -&gt;get( 'Doctrine\ORM\EntityManager' ); return $objectManager; } } </code></pre>
3
1,144
Input data is not loading into database
<p>I am encountering the following problem: I have a program that is supposed to load some data into a database, and it is not working. No errors are popping out, it just does not load and save the data.</p> <p>Here is the connection code:</p> <pre><code>public Conexion() { string dataSource = ".\\SQLEXPRESS"; string rutaBase = HostingEnvironment.MapPath(@"/App_Data/Database1.mdf"); cadenaConexion = "Data Source=" + dataSource + ";AttachDbFilename=\"" + rutaBase + "\";Integrated Security=true;User Instance=True"; } </code></pre> <p>Edit 1: Here is the code used to insert the data and a screen capture of the server explorer.</p> <pre><code>namespace WebApplication1.Persistencia { public class PersistenciaEmpresaAuspiciante { readonly Conexion conexion = new Conexion(); public bool ExisteAuspiciante(EmpresasAuspiciantes pAuspiciante) { if (pAuspiciante == null) return false; string sql = "Select * FROM AUSPICIANTES WHERE IdAuspiciante=" + pAuspiciante.idAuspiciante.ToString(); DataSet resultado = conexion.Seleccion(sql); if (resultado == null) return false; return resultado.Tables[0].Rows.Count &gt; 0; } public bool AltaAuspiciante(EmpresasAuspiciantes pAuspiciante) { if (pAuspiciante == null) return false; if (ExisteAuspiciante(pAuspiciante)) return false; string sql = "INSERT INTO AUSPICIANTES (IdAuspiciante, NombreAuspiciante) Values" + pAuspiciante.idAuspiciante.ToString() + ", '" + pAuspiciante.nombreAuspiciante + " ', '" + "')"; return conexion.Consulta(sql); } public bool BajaAuspiciante(EmpresasAuspiciantes pAuspiciante) { if (pAuspiciante == null) return false; if (!ExisteAuspiciante(pAuspiciante)) return false; string sql = "DELTE FROM AUSPICIANTES WHERE IdAuspiciante=" + pAuspiciante.idAuspiciante.ToString(); return conexion.Consulta(sql); } public bool ModificarAuspiciante(EmpresasAuspiciantes pAuspiciante) { if (pAuspiciante == null) return false; if (!ExisteAuspiciante(pAuspiciante)) return false; string sql = "UPDATE AUSPICIANTES SET" + "NombreAuspiciante" + pAuspiciante.nombreAuspiciante + "' WHERE IdAuspiciante =" + pAuspiciante.idAuspiciante.ToString() + ";"; return conexion.Consulta(sql); } public List&lt;EmpresasAuspiciantes&gt; ListaAuspiciante() { string sql = "SELECT * FROM AUSPICIANTES"; DataSet resultado = conexion.Seleccion(sql); List&lt;EmpresasAuspiciantes&gt; lista = new List&lt;EmpresasAuspiciantes&gt;(); if (resultado == null) return lista; DataRowCollection tabla = resultado.Tables[0].Rows; foreach (DataRow fila in tabla) { object[] elementos = fila.ItemArray; EmpresasAuspiciantes auspiciante = new EmpresasAuspiciantes(); auspiciante.idAuspiciante = int.Parse(elementos[0].ToString()); auspiciante.nombreAuspiciante = elementos[1].ToString(); lista.Add(auspiciante); } return lista; } } } </code></pre> <p><a href="https://i.stack.imgur.com/p8c2a.png" rel="nofollow noreferrer">Database explorer</a></p> <p>Connection string for the <code>.mdf</code> file:</p> <pre><code>Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\srjua\OneDrive\Escritorio\ctc\Codificacion, persistencia y controladora 2\WebApplication1\App_Data\Database1.mdf";Integrated Security=True </code></pre>
3
1,953
GitHub push Error occurs. (ssh key doesn't work)
<p><strong>Problem Description</strong>: While I try to push to GitHub Pages I got an Error .</p> <pre><code>ERROR: Permission to lut/EvolutionApp.git denied to ~. fatal: Could not read from remote repository. </code></pre> <p>I've searched this for 3 days, and I've tried all solutions but it didn't work at all. I don't know since when but, I've changed branch <code>master</code> to <code>main</code>(remote and local both).<br /> I'm not sure this is the main problem.<br /> <strong>I've tried</strong>:</p> <ol> <li>I generated <code>ssh key</code> and add it to GitHub Settings.<br /> when I write <code>&gt;ssh -T git@github.com</code> it shows <code>Hi DanielFH1! You've successfully authenticated, but GitHub does not provide shell access.</code></li> </ol> <p><strong>Status</strong>:<br /> 1.</p> <pre><code># I've changed default branch master to main &gt;git status on branch main </code></pre> <ol start="2"> <li></li> </ol> <pre><code>&gt;git remote origin </code></pre> <ol start="3"> <li></li> </ol> <pre><code># I've deleted branch master and leave only default branch 'main' &gt;git branch -d master Deleted branch master (was 6eca8640). </code></pre> <ol start="4"> <li></li> </ol> <pre><code>&gt;git branch * main </code></pre> <p><strong>Full Error</strong>: errors are mainly cannot push(1) or pull(2)<br /> 1.</p> <pre><code>&gt;git push origin main ERROR: Permission to lut/EvolutionApp.git denied to ~. fatal: Could not read from remote repository. </code></pre> <ol start="2"> <li></li> </ol> <pre><code>&gt;git pull origin main fatal: couldn't find remote ref main </code></pre> <ol start="3"> <li></li> </ol> <pre><code># It seems it connected to port 22 as github description says, and says 'successfully authenticated' in the last line. Are these means OK? &gt;ssh -vT git@github.com OpenSSH_for_Windows_7.7p1, LibreSSL 2.6.5 debug1: Connecting to github.com [52.78.231.108] port 22. debug1: Connection established. debug1: identity file C:\\Users\\SeungWoo/.ssh/id_rsa type 0 debug1: key_load_public: No such file or directory debug1: identity file C:\\Users\\SeungWoo/.ssh/id_rsa-cert type -1 debug1: key_load_public: No such file or directory debug1: identity file C:\\Users\\SeungWoo/.ssh/id_dsa type -1 debug1: key_load_public: No such file or directory debug1: identity file C:\\Users\\SeungWoo/.ssh/id_dsa-cert type -1 debug1: key_load_public: No such file or directory debug1: identity file C:\\Users\\SeungWoo/.ssh/id_ecdsa type -1 debug1: key_load_public: No such file or directory debug1: identity file C:\\Users\\SeungWoo/.ssh/id_ecdsa-cert type -1 debug1: key_load_public: No such file or directory debug1: identity file C:\\Users\\SeungWoo/.ssh/id_ed25519 type -1 debug1: key_load_public: No such file or directory debug1: identity file C:\\Users\\SeungWoo/.ssh/id_ed25519-cert type -1 debug1: key_load_public: No such file or directory debug1: identity file C:\\Users\\SeungWoo/.ssh/id_xmss type -1 debug1: key_load_public: No such file or directory debug1: identity file C:\\Users\\SeungWoo/.ssh/id_xmss-cert type -1 debug1: Local version string SSH-2.0-OpenSSH_for_Windows_7.7 debug1: Remote protocol version 2.0, remote software version babeld-17a926d7 debug1: no match: babeld-17a926d7 debug1: Authenticating to github.com:22 as 'git' debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: algorithm: curve25519-sha256 debug1: kex: host key algorithm: ecdsa-sha2-nistp256 debug1: kex: server-&gt;client cipher: chacha20-poly1305@openssh.com MAC: &lt;implicit&gt; compression: none debug1: kex: client-&gt;server cipher: chacha20-poly1305@openssh.com MAC: &lt;implicit&gt; compression: none debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug1: Server host key: ecdsa-sha2-nistp256 SHA256:p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM debug1: Host 'github.com' is known and matches the ECDSA host key. debug1: Found key in C:\\Users\\SeungWoo/.ssh/known_hosts:1 debug1: rekey after 134217728 blocks debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: rekey after 134217728 blocks debug1: pubkey_prepare: ssh_get_authentication_socket: No such file or directory debug1: SSH2_MSG_EXT_INFO received debug1: kex_input_ext_info: server-sig-algs=&lt;ssh-ed25519-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp256-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,sk-ssh-ed25519@openssh.com,sk-ecdsa-sha2-nistp256@openssh.com,ssh-ed25519,ecdsa-sha2-nistp521,ecdsa-sha2-nistp384,ecdsa-sha2-nistp256,rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss&gt; debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey debug1: Next authentication method: publickey debug1: Offering public key: RSA SHA256:isIh1SLbiAdxDs2LohVlLlC4mXm0bKEWPhMvuZLlpuQ C:\\Users\\SeungWoo/.ssh/id_rsa debug1: Server accepts key: pkalg rsa-sha2-512 blen 407 debug1: Authentication succeeded (publickey). Authenticated to github.com ([52.78.231.108]:22). debug1: channel 0: new [client-session] debug1: Entering interactive session. debug1: pledge: network debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0 debug1: client_input_channel_req: channel 0 rtype exit-status reply 0 Hi DanielFH1! You've successfully authenticated, but GitHub does not provide shell access. debug1: channel 0: free: client-session, nchannels 1 Transferred: sent 2944, received 2912 bytes, in 0.4 seconds </code></pre>
3
2,137
Flutter web renderer (not CanvasKit): Nested Y Axis rotation causes a child widget to disappear
<p>While nesting two <code>Transform</code> widgets, child widget (I.E. a picture) is disappearing in some cases.</p> <p>It happens with <code>Animation</code> and <code>AnimatedBuilder</code> as well.</p> <p>Conditions for reproducing:</p> <ul> <li>Wide screen resolution only.</li> <li>Flutter Web with HTML web renderer only (Not Android nor Flutter Web with <code>CanvasKit</code>)</li> <li>Flutter 2.10.2</li> </ul> <p>Minimal reproduce:</p> <ol> <li><p>Create new folder <code>flutter_web_bug</code></p> </li> <li><p>Open terminal inside that folder and execute <code>flutter create .</code></p> </li> <li><p>Replace <code>./lib/main.dart</code> contents with the following code</p> </li> <li><p>Open terminal and execute <code>flutter run -d chrome --web-renderer html</code></p> <pre><code> import 'dart:async'; import 'dart:math'; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Flutter web bug', home: MyHomePage(title: 'Flutter web bug'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState(); } class _MyHomePageState extends State&lt;MyHomePage&gt; { double angle = 0.0; @override void initState() { super.initState(); Timer.periodic(const Duration(milliseconds: 20), (timer) { setState(() { angle += 0.01; }); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Transform( transform: Matrix4.identity() ..setEntry(3, 2, 0.001) ..rotateY(pi * angle), alignment: Alignment.center, child: Align( alignment: Alignment.center, child: Container( color: const Color(0xffaaffff), child: Transform( alignment: Alignment.center, transform: Matrix4.identity()..rotateY(pi), child: Image.network('https://docs.flutter.dev/assets/images/dash/dash-fainting.gif'))))), )); } } </code></pre> </li> </ol> <p>Demonstration:</p> <p><a href="https://i.stack.imgur.com/uUl4y.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uUl4y.gif" alt="HTML web renderer bug" /></a></p>
3
1,221
Parsing specific region of a txt, comparing to list of strings, then generating new list composed of matches
<p>I am trying to do the following:</p> <ol> <li>Read through a specific portion of a text file (there is a known starting point and ending point)</li> <li>While reading through these lines, check to see if a word matches a word that I have included in a list </li> <li>If a match is detected, then add that specific word to a new list</li> </ol> <p>I have been able to read through the text and grab other data from it that I need, but I've been unable to do the above mentioned thus far.</p> <p>I have tried to implement the following example: <a href="https://stackoverflow.com/questions/49033177/python-search-text-file-for-any-string-in-a-list">Python - Search Text File For Any String In a List</a> But I have failed to make it read correctly.</p> <p>I have also tried to adapt the following: <a href="https://www.geeksforgeeks.org/python-finding-strings-with-given-substring-in-list/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/python-finding-strings-with-given-substring-in-list/</a> But I was equally unsuccessful.</p> <p>Here is some of my code:</p> <pre><code>import re from itertools import islice import os # list of all countries oneCountries = "Afghanistan, Albania, Algeria, Andorra, Angola, Antigua &amp; Deps, Argentina, Armenia, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bhutan, Bolivia, Bosnia Herzegovina, Botswana, Brazil, Brunei, Bulgaria, Burkina, Burma, Burundi, Cambodia, Cameroon, Canada, Cape Verde, Central African Rep, Chad, Chile, China, Republic of China, Colombia, Comoros, Democratic Republic of the Congo, Republic of the Congo, Costa Rica,, Croatia, Cuba, Cyprus, Czech Republic, Danzig, Denmark, Djibouti, Dominica, Dominican Republic, East Timor, Ecuador, Egypt, El Salvador, Equatorial Guinea, Eritrea, Estonia, Ethiopia, Fiji, Finland, France, Gabon, Gaza Strip, The Gambia, Georgia, Germany, Ghana, Greece, Grenada, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Holy Roman Empire, Honduras, Hungary, Iceland, India, Indonesia, Iran, Iraq, Republic of Ireland, Israel, Italy, Ivory Coast, Jamaica, Japan, Jonathanland, Jordan, Kazakhstan, Kenya, Kiribati, North Korea, South Korea, Kosovo, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Marshall Islands, Mauritania, Mauritius, Mexico, Micronesia, Moldova, Monaco, Mongolia, Montenegro, Morocco, Mount Athos, Mozambique, Namibia, Nauru, Nepal, Newfoundland, Netherlands, New Zealand, Nicaragua, Niger, Nigeria, Norway, Oman, Ottoman Empire, Pakistan, Palau, Panama, Papua New Guinea, Paraguay, Peru, Philippines, Poland, Portugal, Prussia, Qatar, Romania, Rome, Russian Federation, Rwanda, St Kitts &amp; Nevis, St Lucia, Saint Vincent &amp; the Grenadines, Samoa, San Marino, Sao Tome &amp; Principe, Saudi Arabia, Senegal, Serbia, Seychelles, Sierra Leone, Singapore, Slovakia, Slovenia, Solomon Islands, Somalia, South Africa, Spain, Sri Lanka, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Tajikistan, Tanzania, Thailand, Togo, Tonga, Trinidad &amp; Tobago, Tunisia, Turkey, Turkmenistan, Tuvalu, Uganda, Ukraine, United Arab Emirates, United Kingdom, United States, Uruguay, Uzbekistan, Vanuatu, Vatican City, Venezuela, Vietnam, Yemen, Zambia, Zimbabwe" countries = oneCountries.split(",") path = "C:/Users/me/Desktop/read.txt" thefile = open(path, errors='ignore') countryParsing = False for line in thefile: line = line.strip() # if line.startswith("Submitting Author:"): # if re.match(r"Submitting Author:", line): # print("blahblah1") # countryParsing = True # if countryParsing == True: # print("blahblah2") # # res = [x for x in line if re.search(countries, x)] # print("blah blah3: " + str(res)) # elif re.match(r"Running Head:", line): # countryParsing = False # if countryParsing == True: # res = [x for x in line if re.search(countries, x)] # print("blah blah4: " + str(res)) # for x in countries: # if x in thefile: # print("a country is: " + x) # if any(s in line for s in countries): # listOfAuthorCountries = listOfAuthorCountries + s + ", " # if re.match(f"Submitting Author:, line"): </code></pre> <p>The #commented out lines are versions of the code that I've tried and failed to make work properly.</p> <p>As requested, this is an example of the text file that I'm trying to grab the data from. I've modified it to remove sensitive information, but in this particular case, the "new list" should be appended with a certain number of "France" entries: </p> <pre><code> txt above.... Submitting Author: asdf, asdf (proxy) France asdfasdf blah blah asdfasdf asdf, Provence-Alpes-Côte d'Azu 13354 France blah blah France asdf Running Head: ...more text below </code></pre>
3
1,663
C++ Structure declaration and usage to hold IP + Connections
<p>Good day to all, i am having a massive confusion declaring and using my structure to hold <strong>[IP] - [Connections]</strong> record. I am trying to insert the IP address that is connecting into the structure, and his connection number <strong>#</strong>, for example if <strong>IP 123.123.12</strong> connects 2 (two) times, then update the <strong>[Connections]</strong> number in the struct for that <strong>IP (123.123.12)</strong>.</p> <p>I have the following code, wich should work:</p> <pre><code>// the struct typedef struct { int id; // is this usefull anyway ? char *ip; int connNumbers; }test_sock; // init struct test_sock holder[5000]; int len = 0; // the function void AddtoStruct(char *ip) { if (len == 0) //if empty, insert. { len++; holder-&gt;id = len; holder-&gt;ip = ip; holder-&gt;connNumbers = 1; //1 conexiune return; } for (int i = 0; i&lt;len; i++) { if (test_sock-&gt;id != 0) //check if its the same id !? { //Exista deja in structura , doar increase connNumbers; if (strcmp(ip, holder-&gt;ip) == 0) { holder++; holder-&gt;connNumbers++; holder-&gt;id = antiddos_len; holder-&gt;ip = ip; return; // should return or not ?! } else{ //new IP, insert into struct. len++; // COUNT AGAIN ? holder-&gt;id = len; holder-&gt;ip = ip; holder-&gt;connNumbers = 1; // 1 connection return; // should return or not ?! } } } } </code></pre> <p>Ok so what it should is: Check the new incoming <strong>IP</strong> if it`s <strong>ALLREADY</strong> in the structure, then increase the number of connections for that ip If the new incoming <strong>IP</strong> is <strong>NOT</strong> inside the structure, insert it, and if he connects again, of course increase the number of connections.</p> <p>I compiled a minimal example below, wich you can run without problems on a Windows machine, using Visual Studio (i used 2013).</p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;Windows.h&gt; using namespace std; // the struct typedef struct { int id; // is this usefull anyway ? char *ip; int connNumbers; }test_sock; // init struct test_sock holder[5000]; int len = 0; // the function void AddtoStruct(char *ip) { if (len == 0) //if the struct is empty, insert. { len++; holder-&gt;id = len; holder-&gt;ip = ip; holder-&gt;connNumbers = 1; //1 conexiune cout &lt;&lt; "ADDED NEW IP: " &lt;&lt; holder-&gt;ip &lt;&lt; " Connections: " &lt;&lt; holder-&gt;connNumbers &lt;&lt; endl; cout &lt;&lt; "-----------------------------------------------------------" &lt;&lt; endl; return; } for (int i = 0; i &lt;= len; i++) { if (holder-&gt;id != 0) //verificam ca sa nu fie ACELASI ID { //Exista deja in structura , doar increase connNumbers; if (strcmp(ip, holder-&gt;ip) == 0) { len++; holder-&gt;connNumbers++; holder-&gt;id = len; holder-&gt;ip = ip; cout &lt;&lt; "NEW CONNECTION FROM IP: " &lt;&lt; holder-&gt;ip &lt;&lt; " Connections: " &lt;&lt; holder-&gt;connNumbers &lt;&lt; endl; cout &lt;&lt; "-----------------------------------------------------------" &lt;&lt; endl; } else{ //new IP, insert into struct. len++; // COUNT AGAIN ? holder-&gt;id = len; holder-&gt;ip = ip; holder-&gt;connNumbers = 1; // 1 connection cout &lt;&lt; "CONNECTION FROM NEW IP: " &lt;&lt; holder-&gt;ip &lt;&lt; " Connections: " &lt;&lt; holder-&gt;connNumbers &lt;&lt; endl; cout &lt;&lt; "-----------------------------------------------------------" &lt;&lt; endl; return; // should return or not ?! } } } } // use the function int main() { char *ip = "127.0.0.1"; char *ip2 = "127.0.0.3"; AddtoStruct(ip); Sleep(5); // wait for new IP AddtoStruct(ip2); Sleep(5); // wait for SAME IP AddtoStruct(ip); system("pause"); } </code></pre> <p>As you can see, if you run the code, it does not work as it should, it count the same number of connections for every new IP ... So please give me advice, or a fix, or anything, because i really need this, and it`s been 3 days of testing, without any progress. Many thanks!</p>
3
2,167
Same object getting pushed in arrayList
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var totalList=[]; $("#formContainer").on("click","button",function() { var selector = "div."+$(this).data("type")+"-table"; var $div = $(this).closest(selector); var $newDiv = $div.clone(); $newDiv.find(":input").val(""); // clear all $newDiv.find("[type=number]").val(0); // clear numbers $newDiv.find(".sum").text(0); // clear total $newDiv.insertAfter($div) var user_profile = [ { assessmentType: "PRE", assessCatId :1, assessReason:$(".customReason").val(), assessAmount:$(".customAmount").val(), assessPenalty: $(".customPenalty").val() } ] totalList.push(user_profile); console.log(totalList); }); $("form").submit(function() { event.preventDefault(); }); $("#formContainer").on("input","[type=number]",function() { $("#formContainer [type=number]").each(function() { var $row = $(this).closest(".row"); var $fields = $row.find("[type=number]"); var val1 = $fields.eq(0).val(); var val2 = $fields.eq(1).val(); var tot = (isNaN(val1)?0:+val1)+(isNaN(val2)?0:+val2) $row.find(".sum").text(tot); }); var total = 0; $(".sum").each(function() { total += isNaN($(this).text())?0:+$(this).text() }); console.log(total); $("#tot").text(total); }); </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;form id="myForm"&gt; &lt;div id="formContainer" class="col-md-12" style="float: none;"&gt; &lt;!-- &lt;button onclick="myFunction()" class="pull-right"&gt;+&lt;/button&gt; --&gt; &lt;div style="margin-bottom: 30px;"&gt; &lt;div class="form-group row"&gt; &lt;div class="col-md-1"&gt;&lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;label&gt;Reason&lt;/label&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;label&gt;Amount&lt;/label&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;label&gt;Penalty&lt;/label&gt; &lt;/div&gt; &lt;div class="col-md-1"&gt;Total&lt;/div&gt; &lt;div class="col-md-2"&gt;Action&lt;/div&gt; &lt;/div&gt; &lt;div class="customs-table row"&gt; &lt;div class="col-md-1"&gt; &lt;label&gt;Customs&lt;/label&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;input type="text" class="form-control customReason" id="customReason" /&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;input type="number" class="form-control txt customAmount" value="0" name="abc" min="0" id="customAmount" /&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;input type="number" class="form-control txt customPenalty" value="0" name="abc" min="0" id="customPenalty" /&gt; &lt;/div&gt; &lt;div class="col-md-1"&gt; &lt;span class="sum"&gt;0&lt;/span&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;button data-type="customs" class="add-customs"&gt;+&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="vat-table row"&gt; &lt;div class="col-md-1"&gt; &lt;label&gt;VAT&lt;/label&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;input type="text" class="form-control vatReason" name="vatReason" /&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;input type="number" class="form-control txt1 vatAmount" value="0" name="vatAmount" min="0" /&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;input type="number" class="form-control txt1 vatPenalty" value="0" name="vatPenalty" min="0" /&gt; &lt;/div&gt; &lt;div class="col-md-1"&gt; &lt;span class="sum"&gt;0&lt;/span&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;button class="add-vat" data-type="vat"&gt;+&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="excise-table row"&gt; &lt;div class="col-md-1"&gt; &lt;label&gt;Excise&lt;/label&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;input type="text" class="form-control exciseReason" name="exciseReason" /&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;input type="number" class="form-control txt2 exciseAmount" value="0" name="exciseAmount" min="0" /&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;input type="number" class="form-control txt2 excisePenalty" value="0" name="excisePenalty" min="0" /&gt; &lt;/div&gt; &lt;div class="col-md-1"&gt; &lt;span class="sum"&gt;0&lt;/span&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;button data-type="excise" class="add-excise"&gt;+&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-1 pull-right"&gt; &lt;label&gt;Total:&lt;/label&gt; &lt;b&gt; &lt;span id="tot"&gt;0&lt;/span&gt;&lt;/b&gt; &lt;/div&gt; &lt;/div&gt; &lt;button type="submit" class="btn btn-success pull-right"&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p><strong>Here i clicked "+" button and second custom row appears.</strong></p> <p><a href="https://i.stack.imgur.com/b2xEv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b2xEv.png" alt="enter image description here"></a></p> <p>I tried to push them into arrayList named <code>"totalList=[];"</code> but it is pushing the same object repeatedly so:(See Array1 and array2 are same though their data from form is different)</p> <p><a href="https://i.stack.imgur.com/MZ1sA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MZ1sA.png" alt="enter image description here"></a></p> <p>How can i make this arrayList so dynamic which just push the current object rather than the old object? I am not able to push the newly created object into the arrayList.How can i change my arraylist?</p>
3
3,306
Bootstrap JavaScript adding events dynamically not linking to modal window
<p>I have a filter, where they select a media item (ie: radio, digital streetpole, traditional streetpole, bench, poster, etc.) and it then adds that with a whole bunch of it's variables. Let me expand:</p> <p>The user has preset areas that they selected earlier but is also able to select multiple areas (Johannesburg, CapeTown, California, India) on top of that, then he selects a media item and it goes and looks for the average price of that media item in that area.</p> <p>There are going to be more options now, on a modal window, that will allow them to select certain options about that media type in that area. </p> <p>The thing leading to my issue: There are preset modal windows with options inside of them, depending on which 'more options' button they click on (so which media type), it must pop up the relevant modal window.</p> <p><strong>MY ISSUE</strong></p> <p>When adding a new media item, the modal window for extra options does not pop up anymore but does on the ones that were already there (ie: the preset ones).</p> <p>Here are some pictures to show you what I mean:</p> <p>Preset media items:</p> <p><img src="https://i.stack.imgur.com/aFcRW.png" alt="initial preset media items"></p> <p>modal window on one of the selected more options buttons:</p> <p><img src="https://i.stack.imgur.com/ZGHrq.png" alt="modal window on one of the selected more options buttons"></p> <p>adding media type / filtering:</p> <p><img src="https://i.stack.imgur.com/cy7yC.png" alt="adding media type / filtering"></p> <p>adds extra media item / filtering:</p> <p><img src="https://i.stack.imgur.com/f5IIf.png" alt="adds extra media item / filtering"></p> <p>So as you can see, the media item adds to the list, but selecting the 'more options' button, nothing happend on the new item, but it will still work on the old ones.</p> <p>Here is the code:</p> <p>HTML for Modal Popup:</p> <pre><code>&lt;div class="modal fade" id="optionsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;&lt;span class="sr-only"&gt;Close&lt;/span&gt;&lt;/button&gt; &lt;h4 class="modal-title" id="myModalLabel"&gt;Choose the size&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;table class="table"&gt; &lt;thead&gt; &lt;th width="100"&gt;&amp;nbsp;&lt;/th&gt; &lt;th&gt;Size Options&lt;/th&gt; &lt;th&gt;Printable Size&lt;/th&gt; &lt;th&gt;Price Range (Min-Max)&lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;4 Sheet&lt;/td&gt; &lt;td&gt;60X60 Inches&lt;/td&gt; &lt;td&gt;R500 - R10,000&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;4 Sheet&lt;/td&gt; &lt;td&gt;60X60 Inches&lt;/td&gt; &lt;td&gt;R500 - R10,000&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;4 Sheet&lt;/td&gt; &lt;td&gt;60X60 Inches&lt;/td&gt; &lt;td&gt;R500 - R10,000&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;4 Sheet&lt;/td&gt; &lt;td&gt;60X60 Inches&lt;/td&gt; &lt;td&gt;R500 - R10,000&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="checkbox"&gt;&lt;/td&gt; &lt;td&gt;4 Sheet&lt;/td&gt; &lt;td&gt;60X60 Inches&lt;/td&gt; &lt;td&gt;R500 - R10,000&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;button type="button" class="btn btn-primary"&gt;Save changes&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>HTML for populating the list (includes PHP):</p> <pre><code>&lt;tr class="asset_&lt;? echo $counterForAsset; ?&gt; asset_item"&gt; &lt;td&gt;&lt;?php echo strtoupper($media_types[$i]); ?&gt; &lt;input type="hidden" id="media_category" name="mec_id[]" value=""&gt; &lt;input type="hidden" id="media_category" name="media_category[]" value="&lt;?php echo $media_types[$i]; ?&gt;"&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" class="form-control input-sm q_asset_&lt;? echo $counterForAsset; ?&gt; med_quantity" name="med_quantity[]" id="med_quantity" placeholder="Quantity Required" value="&lt;? echo $qty; ?&gt;"/&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" readonly="true" name="avg_total[]" id="asset_&lt;? echo $counterForAsset; ?&gt;" class="form-control input-sm avg_asset_&lt;? echo $counterForAsset; ?&gt;" value="&lt;? echo number_format($av_price, 2); ?&gt;"/&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" readonly="true" name="rem_total[]" id="asset_&lt;? echo $counterForAsset; ?&gt;" class="form-control input-sm rem_asset rem_asset_&lt;? echo $counterForAsset; ?&gt;" value="&lt;? echo number_format($price, 2); ?&gt;"/&gt;&lt;/td&gt; &lt;td width="50"&gt;&lt;a href="#" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#&lt;?php echo strtolower($type); ?&gt;OptionsModal"&gt;&lt;span class="glyphicon glyphicon-play"&gt;&lt;/span&gt; More options&lt;/a&gt;&lt;/td&gt; &lt;td&gt; &lt;center&gt;&lt;input type="checkbox" name="checks[]" id="asset_&lt;? echo $counterForAsset; ?&gt;" class="check_asset_&lt;? echo $counterForAsset; ?&gt;"/&gt;&lt;/center&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>And JS for adding a new media item:</p> <pre><code>tdMediaType.innerHTML = type.toUpperCase() + ' &lt;input type="hidden" id="media_category", value="'+type+'" name="media_category[] /&gt;'; tdQuantity.innerHTML = '&lt;input id="med_quantity" class="form-control input-sm q_asset_'+assetNumber+' med_quantity" type="text" value="0" placeholder="Quantity Required" name="med_quantity[]"&gt;'; tdAverageAssetPrice.innerHTML = '&lt;input id="asset_'+assetNumber+'" class="form-control input-sm avg_asset_'+assetNumber+'" type="text" value="'+aap.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&amp;,')+'" name="avg_total[]" readonly="true"&gt;'; tdPrice.innerHTML = '&lt;input id="asset_'+assetNumber+'" class="form-control input-sm rem_asset rem_asset_'+assetNumber+'" type="text" value="0.00" name="rem_total[]" readonly="true"&gt;'; tdMoreOptions.innerHTML = '&lt;a href="#" class="btn btn-primary btn-sm" data-target="#'+type2+'OptionsModal" data-togle="modal"&gt;&lt;span class="glyphicon glyphicon-play"&gt;&lt;/span&gt; More Options&lt;/a&gt;'; tdMoreSelect.innerHTML = '&lt;center&gt;&lt;input id="asset_'+assetNumber+'" class="check_asset_'+assetNumber+'" type="checkbox" name="checks[]"&gt;&lt;/center&gt;'; </code></pre> <p>Please also take note that the <code>type2</code> variable does put out the correct media type which is a lowercase, spaceless and bracketless string ie: <code>bus (Digital)</code> would be <code>busdigital</code>.</p>
3
4,450
AttributeError at /search/ 'QuerySet' object has no attribute 'facet'
<p>I'm Getting an AttributeError:</p> <pre><code>(AttributeError at /search/ 'QuerySet' object has no attribute 'facet') while setting up custom filters for django-taggit tags with Haystack </code></pre> <p>The search function is working fine when I enter a query like so: <code>http://localhost:8000/search/?q=las+vegas</code></p> <p>But the error is showing up when I try to add an other variable for the ptags filter like so: <code>http://localhost:8000/search/?q=las+vegas&amp;ptags=Solo</code></p> <p>How can I solve this?</p> <p>Full output:</p> <blockquote> <pre><code>20:56:46 Django version 1.10.5, using settings 'uvergo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /search/ Traceback (most recent call last): File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 120, in get form = self.get_form(form_class) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\edit.py", line 45, in get_form return form_class(**self.get_form_kwargs()) File "C:\Users\loicq\Desktop\Coding\UVERGO_SEARCH\venv\src\search\views.py", line 47, in get_form_kwargs kwargs = super().get_form_kwargs() File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 94, in get_form_kwargs kwargs = super(FacetedSearchMixin, self).get_form_kwargs() File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 65, in get_form_kwargs kwargs.update({'searchqueryset': self.get_queryset()}) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 108, in get_queryset qs = qs.facet(field) AttributeError: 'QuerySet' object has no attribute 'facet' [02/May/2019 20:57:04] "GET /search/?q=las+vegas&amp;ptags=Solo HTTP/1.1" 500 97950 ``` </code></pre> </blockquote> <p><code>Models.py</code>:</p> <pre><code>class Product(models.Model): title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') ptags = TaggableManager() image = models.ImageField(default='') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.title </code></pre> <p>My Custom <code>forms.py</code>:</p> <pre><code>from haystack.forms import FacetedSearchForm from django.db.models.query import QuerySet #from haystack.query import SearchQuerySet class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) data = dict(kwargs.get("data", [])) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() ptags = self.request.GET.get('ptags', None) if ptags: ptags = ptags.split(',') sqs = self.queryset.filter(ptags__name__in=ptags).distinct() return sqs: </code></pre> <p>I'm passing the custom forms in the views like this:</p> <pre><code>class FacetedSearchView(BaseFacetedSearchView): form_class = FacetedProductSearchForm queryset = Product.objects.all() facet_fields = ['ptags'] template_name = 'search_result.html' paginate_by = 6 context_object_name = 'object_list' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["request"] = self.request return kwargs </code></pre> <p>Urls:</p> <pre><code>from django.conf.urls import url from django.contrib import admin from search.views import HomeView, ProductView, FacetedSearchView, autocomplete from .settings import MEDIA_ROOT, MEDIA_URL from django.conf.urls.static import static urlpatterns = [ url(r'^$', HomeView.as_view()), url(r'^admin/', admin.site.urls), url(r'^product/(?P&lt;slug&gt;[\w-]+)/$', ProductView.as_view(), name='product'), url(r'^search/autocomplete/$', autocomplete), url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'), ] + static(MEDIA_URL, document_root=MEDIA_ROOT) </code></pre>
3
2,130
Uncaught Error: Sys.InvalidOperationException: 'DocMapUpdatePanelId' is not a property or an existing field
<p>I am building an asp.net C# application which uses buttons to retrieve and display RDLC reports within a View. The reports load without issue on localhost but when placed on Windows Server 2012 R2 Standard 64-bit and served through IIS version 8.5 the error:</p> <p><strong>Uncaught Error: Sys.InvalidOperationException: 'DocMapUpdatePanelId' is not a property or an existing field.</strong></p> <p>is given and none of the reports display. It looks like this: <a href="https://i.stack.imgur.com/CU2tX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CU2tX.png" alt="enter image description here"></a></p> <ul> <li>Application was built in Visual Studio 2015. </li> <li>.NET 3.5 Report Viewer 2012 and Report Viewer 2015 are both installed </li> <li>Microsoft System CLR Types for SQL Server 2012 and 2014</li> </ul> <p><strong>Default.aspx</strong></p> <pre><code>&lt;asp:View ID="reportView" runat="server"&gt; &lt;div class="div-view-title"&gt;&lt;h3&gt;TURNOUT REPORTS&lt;/h3&gt;&lt;/div&gt; &lt;div style="padding-left: 0%;"&gt; &lt;asp:Button ID="btnCONSTITUENCY_REPORT" runat="server" Text="CONSTITUENCY REPORT" style="background-color: #ade1ff;background: linear-gradient(#ade1ff, #6facd0);position: relative; width: 250px;height: 90px;margin: 12px; box-shadow: 10px 10px 5px #716f6f;background-size: 100% 100%;background-repeat: no-repeat;" OnClick="btnCONSTITUENCY_REPORT_Click" /&gt; &lt;asp:Button ID="btnLOCATION_NAME_REPORT" runat="server" Text="LOCATION REPORT" style="background-color: #ade1ff;background: linear-gradient(#ade1ff, #6facd0);position: relative; width: 200px;height: 90px;margin: 12px; box-shadow: 10px 10px 5px #716f6f;background-size: 100% 100%;background-repeat: no-repeat;" OnClick="btnLOCATION_NAME_REPORT_Click" /&gt; &lt;asp:Button ID="btnEPMVTR_SECTION_REPORT" runat="server" Text="EPMVTR SECTION REPORT" style="background-color: #ade1ff;background: linear-gradient(#ade1ff, #6facd0);position: relative; width: 250px;height: 90px;margin: 12px; box-shadow: 10px 10px 5px #716f6f;background-size: 100% 100%;background-repeat: no-repeat;" OnClick="btnEPMVTR_SECTION_REPORT_Click"/&gt; &lt;/div&gt; &lt;div&gt; &lt;/div&gt; &lt;/asp:View&gt; </code></pre> <p><strong>Default.aspx.cs</strong></p> <pre><code>protected void btnCONSTITUENCY_REPORT_Click(object sender, EventArgs e) { if (IsUserSessionExpired()) lblError.Text = "Session Expired"; System.Web.UI.HtmlControls.HtmlGenericControl viewCont = (System.Web.UI.HtmlControls.HtmlGenericControl)FindControl("lbtnReportsViewParent"); if (viewCont != null) { viewCont.Style.Add("background-color", "#e4e4e4"); viewCont.Style.Add("background", "linear-gradient(#a4a8ce, #e7e6ff)"); } System.Web.UI.HtmlControls.HtmlGenericControl viewCont2 = (System.Web.UI.HtmlControls.HtmlGenericControl)FindControl("lbtnElevenViewParent"); if (viewCont2 != null) { viewCont2.Style.Remove("background-color"); viewCont2.Style.Remove("background"); } try { ReportViewerCONSTITUENCY_REPORT.Reset(); ReportDataSource rptdsrc = new ReportDataSource("PVC_SSVGE_CONSTITUENCY_REPORT_DataSet", GetData(@"with tosum as ( select e.cnstncy_nbr, cnstncy_nm, e.epmv_pk, e.elctn_id, e.epm_type, e.voting_location,e.location_address, e.stations, e.total_elctr as 'total_elctr', e.voter_turnout_11am as 'total_turnout_11am', e.voter_turnout_3pm as 'total_turnout_3pm', e.misc as 'total_turnout_misc', e.aud_uid from EPMVTR_STATS e inner join UNI_CNSTNCY c on e.cnstncy_nbr = c.cnstncy_nbr and e.elctn_id = c.elctn_id where e.cnstncy_nbr = c.cnstncy_nbr ) select cnstncy_nbr, cnstncy_nm, epm_type, sum(total_elctr) [total_elctr], sum(total_turnout_11am) [total_turnout_11am] ,sum(total_turnout_3pm) [total_turnout_3pm] ,sum(total_turnout_misc) [total_turnout_misc] from tosum group by cnstncy_nbr, cnstncy_nm, epm_type order by cnstncy_nbr; ").Tables["resultsTable"]);//GetData("Select * from EPMVTR_STATS").Tables["resultsTable"]); //ReportDataSource rptdsrcSum = new ReportDataSource("PVC_SSVGE_CONSTITUENCY_REPORT_DataSet", GetData("select e.cnstncy_nbr, cnstncy_nm, e.epmv_pk, e.elctn_id, e.epm_type, e.voting_location,e.location_address, e.stations, e.total_elctr, e.voter_turnout_11am, e.voter_turnout_3pm, e.misc, e.aud_uid, e.aud_uid from EPMVTR_STATS e inner join UNI_CNSTNCY c on e.cnstncy_nbr = c.cnstncy_nbr and e.elctn_id = c.elctn_id order by cnstncy_nbr").Tables["resultsTable"]); ReportViewerCONSTITUENCY_REPORT.LocalReport.DataSources.Add(rptdsrc); ReportViewerCONSTITUENCY_REPORT.LocalReport.ReportPath = MapPath("~\\App_Browsers\\PVC_SSVGE_CONSTITUENCY_REPORT.rdlc"); ReportViewerCONSTITUENCY_REPORT.LocalReport.Refresh(); } catch { } epmMultiView.SetActiveView(viewCONSTITUENCY_REPORT); } protected void btnLOCATION_NAME_REPORT_Click(object sender, EventArgs e) { if (IsUserSessionExpired()) lblError.Text = "Session Expired"; System.Web.UI.HtmlControls.HtmlGenericControl viewCont = (System.Web.UI.HtmlControls.HtmlGenericControl)FindControl("lbtnReportsViewParent"); if (viewCont != null) { viewCont.Style.Add("background-color", "#e4e4e4"); viewCont.Style.Add("background", "linear-gradient(#a4a8ce, #e7e6ff)"); } System.Web.UI.HtmlControls.HtmlGenericControl viewCont2 = (System.Web.UI.HtmlControls.HtmlGenericControl)FindControl("lbtnElevenViewParent"); if (viewCont2 != null) { viewCont2.Style.Remove("background-color"); viewCont2.Style.Remove("background"); } try { ReportViewerLOCATION_NAME_REPORT.Reset(); ReportDataSource rptdsrc = new ReportDataSource("PVC_SSVGE_LOCATION_NAME_REPORT_DataSet", GetData("select cnstncy_nm,e.* from EPMVTR_STATS e inner join UNI_CNSTNCY c on e.cnstncy_nbr = c.cnstncy_nbr and e.elctn_id = c.elctn_id order by cnstncy_nbr, stations").Tables["resultsTable"]); lbtnReportsView.Text = "Test Got here"; ReportViewerLOCATION_NAME_REPORT.LocalReport.DataSources.Add(rptdsrc); ReportViewerLOCATION_NAME_REPORT.LocalReport.ReportPath = Server.MapPath("PVC_SSVGE_LOCATION_NAME_REPORT.rdlc"); ReportViewerLOCATION_NAME_REPORT.LocalReport.Refresh(); } catch(Exception) { lbtnReportsView.Text = "Exception"; } epmMultiView.SetActiveView(viewLOCATION_NAME_REPORT); } protected void btnEPMVTR_SECTION_REPORT_Click(object sender, EventArgs e) { if (IsUserSessionExpired()) lblError.Text = "Session Expired"; System.Web.UI.HtmlControls.HtmlGenericControl viewCont = (System.Web.UI.HtmlControls.HtmlGenericControl)FindControl("lbtnReportsViewParent"); if (viewCont != null) { viewCont.Style.Add("background-color", "#e4e4e4"); viewCont.Style.Add("background", "linear-gradient(#a4a8ce, #e7e6ff)"); } System.Web.UI.HtmlControls.HtmlGenericControl viewCont2 = (System.Web.UI.HtmlControls.HtmlGenericControl)FindControl("lbtnElevenViewParent"); if (viewCont2 != null) { viewCont2.Style.Remove("background-color"); viewCont2.Style.Remove("background"); } try { ReportViewerEPMVTR_SECTION_REPORT.Reset(); ReportDataSource rptdsrc = new ReportDataSource("PVC_SSVGE_EPMVTR_SECTION_REPORT_DataSet", GetData("select cnstncy_nm,e.* from EPMVTR_STATS e inner join UNI_CNSTNCY c on e.cnstncy_nbr = c.cnstncy_nbr and e.elctn_id = c.elctn_id order by cnstncy_nbr").Tables["resultsTable"]); ReportViewerEPMVTR_SECTION_REPORT.LocalReport.DataSources.Add(rptdsrc); ReportViewerEPMVTR_SECTION_REPORT.LocalReport.ReportPath = MapPath("~\\App_Browsers\\PVC_SSVGE_EPMVTR_SECTION_REPORT.rdlc"); ReportViewerEPMVTR_SECTION_REPORT.LocalReport.Refresh(); } catch { } epmMultiView.SetActiveView(viewEPMVTR_SECTION_REPORT); } </code></pre> <p>Any ideas on whats causing this error and how to fix it?</p> <p>Thanks in advance</p>
3
3,639
XNA DrawPrimitives unintended line to 0,0
<p>I'm trying to learn XNA. I'm currently drawing a figure on the screen where the user clicks. I use an indexbuffer and PrimitiveType.LineList. It works fine, however occasionally a line is drawn between a figure's first vertex and what seems like position 0,0. Why is it doing that?</p> <p><strong>Screenshot</strong> <a href="https://i.stack.imgur.com/HSCXF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HSCXF.png" alt="enter image description here"></a></p> <p><strong>Draw Code</strong></p> <pre><code> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue); #region Transform //Covered later in the Course effect.VertexColorEnabled = true; effect.World = Matrix.Identity; effect.View = new Matrix( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); effect.Projection = Matrix.CreateOrthographicOffCenter( 0f, this.GraphicsDevice.DisplayMode.Width, this.GraphicsDevice.DisplayMode.Height, 0f, -10f, 10f ); #endregion -&gt; Wordt later behandeld if (vertex.Count &gt; 0) { VertexBuffer vBuffer = new VertexBuffer(this.GraphicsDevice, typeof(VertexPositionColor), vertex.Count, BufferUsage.None); vBuffer.SetData&lt;VertexPositionColor&gt;(vertex.ToArray()); this.GraphicsDevice.SetVertexBuffer(vBuffer); effect.CurrentTechnique.Passes[0].Apply(); this.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.LineList, 0, 0, this.vertex.Count, 0, vertex.Count * 2); } base.Draw(gameTime); } </code></pre> <p><strong>Add Figure Code</strong></p> <pre><code> private void addFigure(Microsoft.Xna.Framework.Point location, Size size, Microsoft.Xna.Framework.Color color) { this.vertex.Add(new VertexPositionColor(new Vector3(location.X, location.Y - 40, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X + 10, location.Y - 20, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X + 20, location.Y - 20, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X + 20, location.Y - 10, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X + 40, location.Y, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X + 20, location.Y + 10, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X + 20, location.Y + 20, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X + 10, location.Y + 20, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X, location.Y + 40, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X - 10, location.Y + 20, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X - 20, location.Y + 20, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X - 20, location.Y + 10, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X - 40, location.Y, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X - 20, location.Y - 10, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X - 20, location.Y - 20, 0), Microsoft.Xna.Framework.Color.Red)); this.vertex.Add(new VertexPositionColor(new Vector3(location.X - 10, location.Y - 20, 0), Microsoft.Xna.Framework.Color.Red)); for (short i = 16; i &gt; 0; i--) { this.index.Add((short)(this.vertex.Count - i)); if (i - 1 &gt; 0) { this.index.Add((short)(this.vertex.Count - i + 1)); } else { this.index.Add((short)(this.vertex.Count - 16)); } } this.ib = new IndexBuffer(this.GraphicsDevice, typeof(short), this.index.Count, BufferUsage.None); this.ib.SetData&lt;short&gt;(this.index.ToArray()); this.GraphicsDevice.Indices = ib; } </code></pre>
3
1,985
Proper Use of MYSQL UPDATE Function
<p>I am using MySQL query to UPDATE the information in the database.</p> <p>I tried updating the information from the localhost/phpmyadmin and later on copy the code that was given in the localhost/phpmyadmin.</p> <p>The problem is that the information/values are not updating in the database.</p> <p>Below is the code:</p> <pre><code>&lt;?php if(isset($_POST['updateProfile'])) { $newUser = $_POST['newUsername']; $newPass = $_POST['newPassword']; $newConNum = $_POST['newContactNumber']; $newAdd = $_POST['newAddress']; include("dbconnect.php"); //avatarPATH $filepath = "avatar/owner-".$_SESSION['username']."-fname-".$_SESSION['fname']."-l_name-".$_SESSION['lname']."-filename-".$_FILES["file"]["name"]; $checkQuery = "SELECT * FROM `users`.`info` WHERE username = '".$userName."' "; $checkResult = $con-&gt;query($checkQuery); $count = mysqli_num_rows($checkResult); while ($rows = mysqli_fetch_array($checkResult, MYSQLI_ASSOC)) { $username = $rows['username']; $userpass = $rows['password']; $firstName = $rows['firstname']; $lastName = $rows['lastname']; $ConNum = $rows['contact_number']; $usrAdd = $rows['user_address']; $avaImgPth = $rows['avatar_image_path']; $adminLvl = $rows['admin_level']; } $query = "SELECT * FROM `users`.`info` WHERE username = '".$newUser."' "; $queryResult = $con-&gt;query($query); $result = mysqli_num_rows($queryResult); if($result == 1) { echo $newUser." is already in use"; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "avatar/owner-".$_SESSION['username']."-fname-".$_SESSION['fname']."-l_name-".$_SESSION['lname']."-filename-".$_FILES["file"]["name"]); //$updateQuery = "UPDATE `users`.`info` SET `username` = $newUser, `password` = $newPass, `contact_number` = $newConNum , `user_address` = $newAdd, `avatar_image_path` = $filepath WHERE `info`.`username` = '$username' AND `info`.`password` = '$userpass' AND `info`.`f_name` = '$firstname' AND `info`.`l_name` = '$lastname' AND `info`.`admin_level` = '$adminLvl' AND `info`.`contact_number` = '$ConNum' AND AND `info`.`user_address` = '$usrAdd' AND `info`.`avatar_image_path` = '$avaImgPth' "; $updateQuery = " UPDATE `users`.`info` SET `username` = '$newUser',`password` = '$newPass',`f_name` = '$firstName',`l_name` = '$lastName',`contact_number` = '$newConNum',`user_address` = '$newAdd',`avatar_image_path` = '$filepath' WHERE `info`.`username` = 'username' AND `info`.`password` = 'userpass' AND `info`.`f_name` = 'firstName' AND `info`.`l_name` = 'lastName' AND `info`.`admin_level` =$adminLvl AND `info`.`contact_number` = '$ConNum' AND `info`.`user_address` = '$usrAdd' AND `info`.`avatar_image_path` = '$avaImgPth' "; echo "Profile successfully UPDATED!"; } } ?&gt; </code></pre> <p>Thank you so much for your response.</p>
3
1,748
FlatList: "Tried to get frame for out of range index NaN" with useEffect + fetch
<p>I'm trying to render a FlatList with data coming from fetch. It worked before, but now it gives me the error &quot;&quot;Tried to get frame for out of range index NaN&quot;. I have an async function which await the fetch but my return (render) with FlatList is being called first. I've changed the fetch code to use <code>useCallback(async() =&gt; ....) </code> but it doesn't work. I can't put the fetch inside the useEffect because I need it elsewhere inside the component (refresh stuff). Here is my Component code:</p> <pre><code>function Home() { const [data, setData] = useState({}); const getDataFromApi = useCallback(async() =&gt; { const u = await SecureStore.getItemAsync('user'); const p = await SecureStore.getItemAsync('password'); await fetch('https://arko.digital/wp-json/wp/v2/arko_alerta', { method: 'GET', headers: { 'Authorization': 'Basic ' + Buffer.from(u + ':' + p).toString('base64'), }}) .then((response) =&gt; response.json()) .then((json) =&gt; { setData(json) }) .catch((error) =&gt; { console.error(error); }); }, []); useEffect(() =&gt; { getDataFromApi(); }, []); return ( &lt;View style={{flex: 1}}&gt; &lt;FlatList data={data} refreshing={refreshing} onRefresh={onRefresh} keyExtractor={({ id }, index) =&gt; id} ListHeaderComponent={&lt;Text style={commonStyles.bigHeader}&gt;Alertas&lt;/Text&gt;} renderItem={({ item }) =&gt; ( &lt;Alerta title={item.content.rendered.split('&lt;/b&gt;')} content={item.content.rendered} time={item.date} excerpt={item.excerpt.rendered} hidden={true} /&gt; )} /&gt; &lt;/View&gt; ); } export default Home; </code></pre> <p>Using console.log i've noticed that the fetch INDEED return an array of objects in a couple of seconds. The problem is that my FlatList is not awaiting the fetch call. What am I doing wrong? I'm a newbie</p> <p>As I said, this worked before with a simple <code> async function getDataFromApi(){ ... }</code> outside useEffect and <code>getDataFromApi()</code> call inside useEffect.</p> <p>Thanks in advance</p>
3
1,138
firebase_messaging fails to build for iOS but works for Android
<p>I'm looking to add the <code>firebase_messaging 7.0.3</code> package to add Push Notifications to my project. I've configured it for Android and it's working like a charm. Getting the Registration Token and can push notifications to my emulator and phone no problem.</p> <p>Now, when I run the iOS build it fails on finding protocol declaration for 'FIRMessagingDelegate'. From what I understand the <code>FIR-</code> prefix has been removed some time ago and should now just be called MessagingDelegate.</p> <p>I've ran both pod install and update and tried cleaning flutter.</p> <pre><code>flutter clean pod install pod update </code></pre> <p>Also, tried to add <code>Firebase-Messaging</code> to my Podfile version less and trying older versions to no avail.</p> <p>I followed all the steps in the iOS configuration at: <a href="https://pub.dev/packages/firebase_messaging" rel="nofollow noreferrer">https://pub.dev/packages/firebase_messaging</a> and tried it with method swizzling and without. I've ran out of options to try, perhaps some dependencies are not using the right version of firebase someplace but I'm not really sure how to check for those.</p> <p>Here's the Stack Trace from the build:</p> <pre><code>Launching lib/main.dart on iPhone 12 Pro Max in debug mode... Running pod install... Running Xcode build... Xcode build done. 56.0s Failed to build iOS app Error output from Xcode build: ↳ 2021-02-08 16:55:26.766 xcodebuild[37625:1544731] DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/DVTiOSFrameworks/DVTiOSFrameworks-17705/DTDeviceKitBase/DTDKRemoteDeviceData.m:371 Details: (null) deviceType from 00008030-000E78DC3C81802E was NULL when -platform called. Object: &lt;DTDKMobileDeviceToken: 0x7fdc6daa9710&gt; Method: -platform Thread: &lt;NSThread: 0x7fdc6d00f3d0&gt;{number = 2, name = (null)} Please file a bug at https://feedbackassistant.apple.com with this warning message and any useful information you can provide. ** BUILD FAILED ** Xcode's output: ↳ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:14:43: error: cannot find protocol declaration for 'FIRMessagingDelegate' @interface FLTFirebaseMessagingPlugin () &lt;FIRMessagingDelegate&gt; ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:190:43: error: expected a type - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage { ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:284:28: error: expected a type - (void)messaging:(nonnull FIRMessaging *)messaging ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:289:20: error: expected a type - (void)messaging:(FIRMessaging *)messaging ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:290:24: error: expected a type didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage { ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:55:6: error: use of undeclared identifier 'FIRMessaging' [FIRMessaging messaging].delegate = self; ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:136:6: error: use of undeclared identifier 'FIRMessaging' [FIRMessaging messaging].shouldEstablishDirectChannel = true; ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:144:7: error: use of undeclared identifier 'FIRMessaging' [[FIRMessaging messaging] subscribeToTopic:topic ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:150:7: error: use of undeclared identifier 'FIRMessaging' [[FIRMessaging messaging] unsubscribeFromTopic:topic ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:155:21: warning: 'FIRInstanceID' is deprecated: FIRInstanceID is deprecated, please use FIRInstallations for installation identifier handling and use FIRMessaging for FCM registration token handling. [-Wdeprecated-declarations] [[FIRInstanceID instanceID] ^ In module 'FirebaseInstanceID' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Headers/Public/Firebase/Firebase.h:72: /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/FirebaseInstanceID/Firebase/InstanceID/Public/FIRInstanceID.h:190:1: note: 'FIRInstanceID' has been explicitly marked deprecated here __deprecated_msg(&quot;FIRInstanceID is deprecated, please use FIRInstallations for installation &quot; ^ In module 'UIKit' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Target Support Files/firebase_messaging/firebase_messaging-prefix.pch:2: In module 'Foundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h:8: In module 'CoreFoundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6: In module 'Darwin' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:16: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/sys/cdefs.h:200:48: note: expanded from macro '__deprecated_msg' #define __deprecated_msg(_msg) __attribute__((__deprecated__(_msg))) ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:156:33: warning: 'FIRInstanceIDResult' is deprecated: FIRInstanceIDResult is deprecated, please use FIRInstallations for app instance identifier handling and use FIRMessaging for FCM registration token handling. [-Wdeprecated-declarations] instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable instanceIDResult, ^ In module 'FirebaseInstanceID' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Headers/Public/Firebase/Firebase.h:72: /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/FirebaseInstanceID/Firebase/InstanceID/Public/FIRInstanceID.h:153:1: note: 'FIRInstanceIDResult' has been explicitly marked deprecated here __deprecated_msg(&quot;FIRInstanceIDResult is deprecated, please use FIRInstallations &quot; ^ In module 'UIKit' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Target Support Files/firebase_messaging/firebase_messaging-prefix.pch:2: In module 'Foundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h:8: In module 'CoreFoundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6: In module 'Darwin' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:16: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/sys/cdefs.h:200:48: note: expanded from macro '__deprecated_msg' #define __deprecated_msg(_msg) __attribute__((__deprecated__(_msg))) ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:156:9: warning: 'instanceIDWithHandler:' is deprecated: Use `Installations.installationID(completion:)` to get the app instance identifier instead. Use `Messaging.token(completion:)` to get FCM registration token instead. [-Wdeprecated-declarations] instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable instanceIDResult, ^ In module 'FirebaseInstanceID' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Headers/Public/Firebase/Firebase.h:72: /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/FirebaseInstanceID/Firebase/InstanceID/Public/FIRInstanceID.h:215:5: note: 'instanceIDWithHandler:' has been explicitly marked deprecated here __deprecated_msg(&quot;Use `Installations.installationID(completion:)` to get the app instance &quot; ^ In module 'UIKit' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Target Support Files/firebase_messaging/firebase_messaging-prefix.pch:2: In module 'Foundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h:8: In module 'CoreFoundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6: In module 'Darwin' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:16: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/sys/cdefs.h:200:48: note: expanded from macro '__deprecated_msg' #define __deprecated_msg(_msg) __attribute__((__deprecated__(_msg))) ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:166:21: warning: 'FIRInstanceID' is deprecated: FIRInstanceID is deprecated, please use FIRInstallations for installation identifier handling and use FIRMessaging for FCM registration token handling. [-Wdeprecated-declarations] [[FIRInstanceID instanceID] deleteIDWithHandler:^void(NSError *_Nullable error) { ^ In module 'FirebaseInstanceID' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Headers/Public/Firebase/Firebase.h:72: /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/FirebaseInstanceID/Firebase/InstanceID/Public/FIRInstanceID.h:190:1: note: 'FIRInstanceID' has been explicitly marked deprecated here __deprecated_msg(&quot;FIRInstanceID is deprecated, please use FIRInstallations for installation &quot; ^ In module 'UIKit' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Target Support Files/firebase_messaging/firebase_messaging-prefix.pch:2: In module 'Foundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h:8: In module 'CoreFoundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6: In module 'Darwin' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:16: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/sys/cdefs.h:200:48: note: expanded from macro '__deprecated_msg' #define __deprecated_msg(_msg) __attribute__((__deprecated__(_msg))) ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:166:33: warning: 'deleteIDWithHandler:' is deprecated: Use `Installations.delete(completion:)` instead. Also check `Messaging.deleteData(completion:)`if you want to delete FCM registration token. [-Wdeprecated-declarations] [[FIRInstanceID instanceID] deleteIDWithHandler:^void(NSError *_Nullable error) { ^ In module 'FirebaseInstanceID' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Headers/Public/Firebase/Firebase.h:72: /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/FirebaseInstanceID/Firebase/InstanceID/Public/FIRInstanceID.h:321:33: note: 'deleteIDWithHandler:' has been explicitly marked deprecated here __deprecated_msg(&quot;Use `Installations.delete(completion:)` instead. &quot; ^ In module 'UIKit' imported from /Users/peterpoliwoda/Development/git/bd4qol_mobile_app/ios/Pods/Target Support Files/firebase_messaging/firebase_messaging-prefix.pch:2: In module 'Foundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h:8: In module 'CoreFoundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6: In module 'Darwin' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:16: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.4.sdk/usr/include/sys/cdefs.h:200:48: note: expanded from macro '__deprecated_msg' #define __deprecated_msg(_msg) __attribute__((__deprecated__(_msg))) ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:176:20: error: use of undeclared identifier 'FIRMessaging' BOOL value = [[FIRMessaging messaging] isAutoInitEnabled]; ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:180:6: error: use of undeclared identifier 'FIRMessaging' [FIRMessaging messaging].autoInitEnabled = value.boolValue; ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:191:52: error: property 'appData' not found on object of type '__strong id' [self didReceiveRemoteNotification:remoteMessage.appData]; ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:204:7: error: use of undeclared identifier 'FIRMessaging' [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:263:5: error: use of undeclared identifier 'FIRMessaging' [[FIRMessaging messaging] setAPNSToken:deviceToken type:FIRMessagingAPNSTokenTypeSandbox]; ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:268:48: error: use of undeclared identifier 'FIRMessaging' [_channel invokeMethod:@&quot;onToken&quot; arguments:[FIRMessaging messaging].FCMToken]; ^ /Users/peterpoliwoda/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_messaging-7.0.3/ios/Classes/FLTFirebaseMessagingPlugin.m:291:63: error: property 'appData' not found on object of type '__strong id' [_channel invokeMethod:@&quot;onMessage&quot; arguments:remoteMessage.appData]; ^ 5 warnings and 16 errors generated. </code></pre> <pre><code> $ flutter --version Flutter 1.22.6 • channel stable • https://github.com/flutter/flutter.git Framework • revision 9b2d32b605 (3 weeks ago) • 2021-01-22 14:36:39 -0800 Engine • revision 2f0af37152 Tools • Dart 2.10.5 </code></pre>
3
6,784
Does the transform function in plyr change variable names?
<p>The data set I am working with has two and three-word variable names with space in between. </p> <pre><code>&gt; names(final.data1) ## [1] "Vehicle ID" "Frame ID" "Total Frames" ## [4] "Global Time" "Local X" "Local Y" ## [7] "Global X" "Global Y" "Vehicle Length" ## [10] "Vehicle width" "Vehicle class" "Vehicle velocity" ## [13] "Vehicle acceleration" "Lane" "Preceding Vehicle ID" ## [16] "Following Vehicle ID" "Spacing" "Headway" ## [19] "svel" "sacc" "PrecVehClass" </code></pre> <p>I didn't change the names and kept doing analyses as is. When I used <code>transform</code> of <code>plyr</code> package, I got 2 columns for some of the variables which contained same numbers but had different names. </p> <pre><code># Determining when the lane change occured final.data1 &lt;- ddply(final.data1, c("`Vehicle class`", "`Vehicle ID`"), transform, lane.change = c(NA, ifelse(diff(Lane) != 0, "yes", "."))) ordr &lt;- with(final.data1, order(`Vehicle ID`)) final.data1 &lt;- final.data1[ordr, ] #sort in ascending order by vehicle ID names(final.data1) ## [1] "Vehicle class" "Vehicle ID" "Vehicle.ID" ## [4] "Frame.ID" "Total.Frames" "Global.Time" ## [7] "Local.X" "Local.Y" "Global.X" ## [10] "Global.Y" "Vehicle.Length" "Vehicle.width" ## [13] "Vehicle.class" "Vehicle.velocity" "Vehicle.acceleration" ## [16] "Lane" "Preceding.Vehicle.ID" "Following.Vehicle.ID" ## [19] "Spacing" "Headway" "svel" ## [22] "sacc" "PrecVehClass" "lane.change" </code></pre> <p>See <code>Vehicle ID</code> and <code>Vehicle.ID</code>? Why is this happening and how can I prevent this if I don't want to change original variable names?</p>
3
1,025
Ajax Form Submit - When click change html element text
<p>So I'm trying to create a message system. When I click on the Message to open my template opens in the same page the message content. I'm trying to make like: "See" Button->ajax->replace with jquery .text("Blah Blah"). the problem is that when I try tod</p> <p>HTML Code:</p> <pre><code>&lt;form method="POST"&gt; &lt;button type="button" class="btn btn-small btn-success" name="msg_preview_id" value="'.$inbox_row['id'].'"&gt;New&lt;/button&gt; &lt;/form&gt; </code></pre> <p>Jquery Ajax Form:</p> <pre><code>$(document).ready(function(){ $('button[name=msg_preview_id]').click(function(event) { var formData = {'msg_preview_id' : $('button[name=msg_preview_id]').val()}; $.ajax({ type : 'POST', // define the type of HTTP verb we want to use (POST for our form) url : '../../class/messages/inbox_preview.php', // the url where we want to POST data : formData, // our data object dataType : 'json' // what type of data do we expect back from the server }) .done(function(data) { console.log(data); //Email Stuff $('h1[id=emailheading]').text(""+data.info.subject+""); $('a[id=emailfrom]').text(""+data.info.from+""); $('span[id=emaildate]').text(""+data.info.rcvdat+""); $('p[id=emailtext]').text(""+data.info.text+""); //Ceninhas $('#inbox-wrapper').addClass('animated fadeOut'); $('#inbox-wrapper').hide(); $('#preview-email-wrapper').addClass('animated fadeIn '); $('#preview-email-wrapper').show(); //$('.page-title').show(); //Load email details $('#inbox-wrapper').removeClass('animated fadeOut'); $('#inbox-wrapper').removeClass('animated fadeIn'); }); event.preventDefault(); }); }); </code></pre> <p>PHP:</p> <pre><code>&lt;?php include ('../../inc/config.inc.php'); $data = array(); $info = array(); $Msg_Preview_ID = $_POST['msg_preview_id']; $MsgSQL = mysqli_query($Connection, "SELECT * FROM messages_inbox WHERE id='$Msg_Preview_ID'"); $Msg = mysqli_fetch_assoc($MsgSQL); $bzQuery = mysqli_query($Connection, "SELECT * FROM members_profile WHERE id='".$Msg['from']."'"); $bzFetch = mysqli_fetch_assoc($bzQuery); $info['from'] = $bzFetch['fname']." ".$bzFetch['lname']; $info['subject'] = $Msg['subject']; $info['text'] = $Msg['text']; $info['rcvdat'] = $Msg['rcvdat']; $data['info'] = $info; echo json_encode($data); </code></pre>
3
1,587
inject all services in startup.cs, .net core, overloaded
<p>This is more a general question.</p> <p>But I have a question about injecting services in the startup.cs:</p> <pre><code>public void ConfigureServices(IServiceCollection services) { services.AddControllers(opt =&gt; { var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); opt.Filters.Add(new AuthorizeFilter(policy)); }) .AddFluentValidation(config =&gt; { config.RegisterValidatorsFromAssemblyContaining&lt;Create&gt;(); }); services.AddApplicationServices(Configuration); services.AddIdentityServices(Configuration); } </code></pre> <p>So anyway I split the services in other file:</p> <pre><code>public static class StartupExtensionClass { public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration Configuration) { services.AddSwaggerGen(c =&gt; { c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;API&quot;, Version = &quot;v1&quot; }); }); services.AddDbContext&lt;DataContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;))); services.AddCors(opt =&gt; { opt.AddPolicy(&quot;CorsPolicy&quot;, policy =&gt; { policy.AllowAnyMethod().AllowAnyHeader().WithOrigins(&quot;http://localhost:3000&quot;); }); }); services.AddMediatR(typeof(List.Handler).Assembly); services.AddAutoMapper(typeof(MappingProfiles).Assembly); services.AddScoped&lt;IUserAccessor, UserAccessor &gt;(); services.AddScoped&lt;IPhotoAccessor, PhotoAccessor&gt;(); services.Configure&lt;CloudinarySettings&gt;(Configuration.GetSection(&quot;Cloudinary&quot;)); return services; } </code></pre> <p>But for example if you have hundreds of services. IS that not overloading the application in the start phase?</p> <p>Because all the services will initialized in the beginning.</p> <p>Is there not a way just to initialise some services when they will directly been called.</p> <p>Like lazy loading</p> <p>Thank you</p>
3
1,060
Nothing returned if the column with the WHERE condition has an index
<p>Working on Debian 11 (Bullseye) first with the distribution's MariaDB version 10.5 and now with the version 10.6.7 from MariaDB repositories.</p> <p>I'm failing to get correct indexes for some big tables from the dump of a genetics database (ensembl homo_sapiens_variation_106_37) from here: <a href="ftp://ftp.ensembl.org/pub/grch37/release-106/mysql/homo_sapiens_variation_106_37/" rel="nofollow noreferrer">ftp://ftp.ensembl.org/pub/grch37/release-106/mysql/homo_sapiens_variation_106_37/</a></p> <p>The one table is variation_feature:</p> <pre><code>CREATE TABLE `variation_feature` ( `variation_feature_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `seq_region_id` int(10) unsigned NOT NULL, `seq_region_start` int(11) NOT NULL, `seq_region_end` int(11) NOT NULL, `seq_region_strand` tinyint(4) NOT NULL, `variation_id` int(10) unsigned NOT NULL, `allele_string` varchar(50000) DEFAULT NULL, `ancestral_allele` varchar(50) DEFAULT NULL, `variation_name` varchar(255) DEFAULT NULL, `map_weight` int(11) NOT NULL, `flags` set('genotyped') DEFAULT NULL, `source_id` int(10) unsigned NOT NULL, `consequence_types` set('intergenic_variant','splice_acceptor_variant','splice_donor_variant','stop_lost','coding_sequence_variant','missense_variant','stop_gained','synonymous_variant','frameshift_variant','non_coding_transcript_variant','non_coding_transcript_exon_variant','mature_miRNA_variant','NMD_transcript_variant','5_prime_UTR_variant','3_prime_UTR_variant','incomplete_terminal_codon_variant','intron_variant','splice_region_variant','downstream_gene_variant','upstream_gene_variant','start_lost','stop_retained_variant','inframe_insertion','inframe_deletion','transcript_ablation','transcript_fusion','transcript_amplification','transcript_translocation','TFBS_ablation','TFBS_fusion','TFBS_amplification','TFBS_translocation','regulatory_region_ablation','regulatory_region_fusion','regulatory_region_amplification','regulatory_region_translocation','feature_elongation','feature_truncation','regulatory_region_variant','TF_binding_site_variant','protein_altering_variant','start_retained_variant') NOT NULL DEFAULT 'intergenic_variant', `variation_set_id` set('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59','60','61','62','63','64') NOT NULL DEFAULT '', `class_attrib_id` int(10) unsigned DEFAULT '0', `somatic` tinyint(1) NOT NULL DEFAULT '0', `minor_allele` varchar(50) DEFAULT NULL, `minor_allele_freq` float DEFAULT NULL, `minor_allele_count` int(10) unsigned DEFAULT NULL, `alignment_quality` double DEFAULT NULL, `evidence_attribs` set('367','368','369','370','371','372','418','421','573','585') DEFAULT NULL, `clinical_significance` set('uncertain significance','not provided','benign','likely benign','likely pathogenic','pathogenic','drug response','histocompatibility','other','confers sensitivity','risk factor','association','protective','affects') DEFAULT NULL, `display` int(1) DEFAULT '1', PRIMARY KEY (`variation_feature_id`), KEY `pos_idx` (`seq_region_id`,`seq_region_start`,`seq_region_end`), KEY `variation_idx` (`variation_id`), KEY `variation_set_idx` (`variation_set_id`), KEY `consequence_type_idx` (`consequence_types`), KEY `source_idx` (`source_id`) ) ENGINE=MyISAM AUTO_INCREMENT=743963234 DEFAULT CHARSET=latin1; </code></pre> <p>It has over 700,000,000 records and occupies on the disk:</p> <pre><code># ls -lh variation_feature.* -rw-rw---- 1 mysql mysql 56K Mai 3 09:41 variation_feature.frm -rw-rw---- 1 mysql mysql 55G Mai 2 20:44 variation_feature.MYD -rw-rw---- 1 mysql mysql 61G Mai 2 22:27 variation_feature.MYI </code></pre> <p>Despite not getting any errors importing the variation_feature.txt some essential indexes are not working. In this case, selecting a known row of data based on variation_id won't return anything, e.g.</p> <pre><code>SELECT * FROM variation_feature WHERE variation_id = 617544728; --&gt; nothing </code></pre> <p>The value 617544728 seems not to be in the index, because</p> <pre><code>SELECT variation_id FROM variation_feature WHERE variation_id = 617544728; --&gt; nothing </code></pre> <p>Disabling the index and waiting for the long table scan returns the row:</p> <pre><code>ALTER TABLE variation_feature ALTER INDEX variation_idx IGNORED; SELECT * FROM variation_feature WHERE variation_id = 617544728; variation_feature_id seq_region_id seq_region_start seq_region_end seq_region_strand variation_id allele_string ancestral_allele variation_name map_weight flags source_id consequence_types variation_set_id class_attrib_id somatic minor_allele minor_allele_freq minor_allele_count alignment_quality evidence_attribs clinical_significance display -------------------- ------------- ---------------- -------------- ----------------- ------------ ------------- ---------------- -------------- ---------- ------ --------- ----------------- ------------------------------------------------------------------------------------------- --------------- ------- ------------ ----------------- ------------------ ----------------- ------------------------------- --------------------- ------- 632092737 27511 230845794 230845794 1 617544728 A/G G rs699 1 &lt;null&gt; 1 missense_variant 2,5,6,9,10,11,12,13,15,16,17,23,24,25,26,30,40,42,43,44,45,47,48,49,50,51,52,53,54,55,56,57 2 false A 0.2949 1477 &lt;null&gt; 368,370,371,372,418,421,573,585 benign,risk factor 1 </code></pre> <p>myisamchk is fixing the indexes without error, but the index &quot;variation_idx&quot; won't work.</p> <p>DROPping and re-CREATing the one index runs without error, but the index won't work.</p> <p>The other indexes are OK.</p> <p>In another genome of this database (ensembl homo_sapiens_variation_106_38 - slightly bigger) from here: <a href="ftp://ftp.ensembl.org/pub/release-106/mysql/homo_sapiens_variation_106_38/" rel="nofollow noreferrer">ftp://ftp.ensembl.org/pub/release-106/mysql/homo_sapiens_variation_106_38/</a> I have the same problem (on another computer but with the same program installations). With one difference: there is also the PRIMARY KEY (variation_feature_id) not working.</p> <p>myisamchk is also running without error, but to no avail.</p> <p>mysqlcheck (version 10.6 running very slow compared to 10.5) returns on the first computer then:</p> <pre><code>homo_sapiens_variation_106_37.variation_feature error : Key in wrong position at page 22405134336 error : Corrupt </code></pre> <p>Now, this we know, but no repair tool can really repair or give a hint, what's wrong.</p> <p>I've CREATEd an index on variation_name: it's working.</p> <p>My changes to mariadb.cnf to adapt to the huge databases and the mysql versions of ensembl:</p> <pre><code>[mysqld] ## this was some time ago - because some bug mysql or mariadb didn't took this from the system default-time-zone = Europe/Berlin ## ensembl has mysql version 5.6 ## because of table creation scripts I need compatibility: show_compatibility_56 = ON performance_schema ## ensembl writes in DATETIME fields: &quot;0000-00-00 00:00:00&quot; ## the new sql_mode in 5.7 doesn't allow it any more ## SHOW VARIABLES LIKE 'sql_mode' ; ## ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION ## so change sql_mode deleting NO_ZERO_IN_DATE,NO_ZERO_DATE sql_mode = ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION datadir = /mnt/SRVDATA/var/lib/mysql tmpdir = /mnt/WORK/tmp [mariadb] [mariadb-10.6] ## MyISAM for building ensembl homo_sapiens lower_case_table_names=1 bulk_insert_buffer_size = 1G myisam_sort_buffer_size = 56G sort_buffer_size = 56G </code></pre> <p>Thank you for the patience to read all this.</p>
3
3,106
Flutter TextFormField moving up when TextHelp is visible
<p>I don't understood what's happening, but when the form got erros the helper text message is moving the TextFormField. I tried increasing the height but I could not fix. </p> <p>Anyone knows what's happening?</p> <p>Look the image:</p> <p><a href="https://i.stack.imgur.com/3gUmq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3gUmq.png" alt="enter image description here"></a></p> <p>Follow the code:</p> <pre><code>Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Container( alignment: Alignment.centerRight, child: CountryCodePicker( showFlagMain: true, onChanged: print, initialSelection: I18n.of(context).locale.countryCode, favorite: ['+55', 'BR'], showCountryOnly: false, showOnlyCountryWhenClosed: false, textStyle: TextStyle( color: Colors.white, fontSize: 19.0), flagWidth: 40.0, )), Container( width: 200, alignment: Alignment.center, child: TextFormField( keyboardType: TextInputType.phone, controller: _phoneTextController, inputFormatters: [ MaskTextInputFormatter( mask: "(##) #####-####", filter: {"#": RegExp(r'[0-9]')}) ], autocorrect: false, autofocus: false, style: TextStyle( color: Colors.white, fontSize: 19.3), cursorColor: Colors.yellow, decoration: const InputDecoration( border: InputBorder.none, hintText: '(99) 99999-9999', filled: true, hintStyle: TextStyle(color: Colors.grey)), validator: (String value) =&gt; phoneValidator(value), )) ], ), SizedBox(height: 20), RaisedButton( child: Text('Send'), onPressed: () { if (this._form.currentState.validate()) { print(this._unmask(this._phoneTextController.text)); } }, ) ], </code></pre> <p>Thanks.</p>
3
2,026
Robotframework - Appium Locating an Element (XPATH - NO IDENTIFICATORS)
<p>I need help clicking on an Element in an Android App, here's the source of the page, I'm using Robot Framework with it's Appium Library.</p> <pre><code>&lt;android.view.View index=&quot;0&quot; package=&quot;com.zentity.android.redesign.rbcz.mobilbank.test&quot; class=&quot;android.view.View&quot; text=&quot;&quot; checkable=&quot;false&quot; checked=&quot;false&quot; clickable=&quot;true&quot; enabled=&quot;true&quot; focusable=&quot;true&quot; focused=&quot;fal se&quot; long-clickable=&quot;false&quot; password=&quot;false&quot; scrollable=&quot;false&quot; selected=&quot;false&quot; bounds=&quot;[0,1458][1080,1626]&quot; displayed=&quot;true&quot; /&gt; &lt;android.view.View index=&quot;1&quot; package=&quot;com.zentity.android.redesign.rbcz.mobilbank.test&quot; class=&quot;android.view.View&quot; text=&quot;&quot; checkable=&quot;false&quot; checked=&quot;false&quot; clickable=&quot;true&quot; enabled=&quot;false&quot; focusable=&quot;false&quot; focused=&quot;f alse&quot; long-clickable=&quot;false&quot; password=&quot;false&quot; scrollable=&quot;false&quot; selected=&quot;false&quot; bounds=&quot;[24,1470][168,1614]&quot; displayed=&quot;true&quot;&gt; &lt;android.view.View index=&quot;0&quot; package=&quot;com.zentity.android.redesign.rbcz.mobilbank.test&quot; class=&quot;android.view.View&quot; text=&quot;&quot; content-desc=&quot;Internet activation&quot; checkable=&quot;false&quot; checked=&quot;false&quot; clickable=&quot;false&quot; enable d=&quot;true&quot; focusable=&quot;false&quot; focused=&quot;false&quot; long-clickable=&quot;false&quot; password=&quot;false&quot; scrollable=&quot;false&quot; selected=&quot;false&quot; bounds=&quot;[72,1518][120,1566]&quot; displayed=&quot;true&quot; /&gt; &lt;/android.view.View&gt; &lt;android.view.View index=&quot;2&quot; package=&quot;com.zentity.android.redesign.rbcz.mobilbank.test&quot; class=&quot;android.view.View&quot; text=&quot;Internetové bankovnictví&quot; checkable=&quot;false&quot; checked=&quot;false&quot; clickable=&quot;false&quot; enabled=&quot;true&quot; focu sable=&quot;false&quot; focused=&quot;false&quot; long-clickable=&quot;false&quot; password=&quot;false&quot; scrollable=&quot;false&quot; selected=&quot;false&quot; bounds=&quot;[192,1512][721,1572]&quot; displayed=&quot;true&quot; /&gt; &lt;/android.view.View&gt; </code></pre> <p>button looks like this</p> <p><a href="https://i.stack.imgur.com/rsUI7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rsUI7.png" alt="Button look" /></a></p> <p>Problem is that only clickable element is the first view with index &quot;0&quot;.</p> <p>I've tried following:</p> <ol> <li><p>Click Text 'Internetové bankovnictví' but it's clickable=false so it doesn't click, also tried the Tap Function in Appium Library by Robot Framework</p> </li> <li><p>Click Element with absolute xpath <code>xpath=//android.view.View[@index='1']/android.view.View[@index='0']</code> while <code>android.view.View[@index='0']</code> is clickable, but it doesn't find the element with the xpath I set.</p> </li> </ol>
3
1,335
stuck on cubit changing state to 2 widgets
<p>I have my base code working for cubit to update a simple counter in a class that is in a row on my app listview.</p> <p>I want to update the counter of total items using bottomNavigationBar and a totalbagel field which is in a different class that my cubit. I wrapped my navbar text field totalbabgel in a block see below.</p> <p>My issue is i do not know how to call in the cubit field in my bottom nav bar variable.</p> <p>What is the correct format to reference a state variable from my cubit class?? All the online examples show only cubit state within same class text update. I need update state in 2 widgets.</p> <p>text</p> <pre><code> bottomNavigationBar: BottomAppBar( child: Row( children: [ //IconButton(icon: Icon(Icons.menu), onPressed: () {}), Spacer(), Container( height: 55.0, width: 1.0, ), //TODO get bakerdoz and etotal on footer working need to pass data between main and bagelcounter BlocBuilder&lt;CounterCubit, CounterCubitState&gt;( key: UniqueKey(), builder: (context,state) =&gt; Text(&quot;Baker's Dozen: &quot; + $totalbagels + &quot; Singles: $singles&quot;, style: TextStyle( color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.w500)), ), my test cubit increment code: CounterCubit() : super(CounterCubitInitial(dozcount: 0, singcount: 0, totalbagels: 0)); void increment() { int holdcart = (state.totalbagels + 1); holdtotal = ((state.totalbagels + 1) ~/ 13); holdsingle = ((state.totalbagels + 1) % 13); print(&quot;+holdsingle: &quot; + holdsingle.toStringAsFixed(2)); print(&quot;+holdtotal: &quot; + holdtotal.toStringAsFixed(2)); print(&quot;+holdcart: &quot; + holdcart.toStringAsFixed(2)); CartTotal(holdcart); emit(CounterCubitIncreased( totalbagels: (state.totalbagels + 1), // dozcount: ((state.totalbagels +1) ~/ 13), singcount: ((state.totalbagels +1) % 13), // singcount: ((state.totalbagels +1) % 13), )); } </code></pre>
3
1,120
Plot a scatter plot using plotly to see the relationship between the 'Budget' vs 'Gross values' using data visualisation concepts
<p>Plot a scatter plot using plotly to see the relationship between the 'Budget' vs 'Gross values' according to different genres</p> <p>Subtasks for customizations -</p> <p>Subtask 1.1 - Try customizing your scatter plot with addition of marginal plots such as histogram, box plot or violin plot Subtask 1.2 - Try linking hover-over data and try exploring the option to choose the genres dynamically</p> <p>My Wrong Code: </p> <pre><code>#Sub task 1.1 marginal plots with an histogram movies = px.data.iris() fig = px.scatter(movies, x="budget", y="Gross", color="genre_1", marginal_y="rug", marginal_x="histogram") fig </code></pre> <p>Error Message:</p> <pre><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-23-78b585ad2937&gt; in &lt;module&gt;() 1 #Sub task 1.1 marginal plots with an histogram 2 movies = px.data.iris() ----&gt; 3 fig = px.scatter(movies, x="budget", y="Gross", color="genre_1", marginal_y="rug", marginal_x="histogram") 4 fig ~/anaconda3_420/lib/python3.5/site-packages/plotly/express/_chart_types.py in scatter(data_frame, x, y, color, symbol, size, hover_name, hover_data, custom_data, text, facet_row, facet_col, error_x, error_x_minus, error_y, error_y_minus, animation_frame, animation_group, category_orders, labels, color_discrete_sequence, color_discrete_map, color_continuous_scale, range_color, color_continuous_midpoint, symbol_sequence, symbol_map, opacity, size_max, marginal_x, marginal_y, trendline, trendline_color_override, log_x, log_y, range_x, range_y, render_mode, title, template, width, height) 51 In a scatter plot, each row of `data_frame` is represented by a symbol mark in 2D space. 52 """ ---&gt; 53 return make_figure(args=locals(), constructor=go.Scatter) 54 55 ~/anaconda3_420/lib/python3.5/site-packages/plotly/express/_core.py in make_figure(args, constructor, trace_patch, layout_patch) 1092 1093 args, trace_specs, grouped_mappings, sizeref, show_colorbar = infer_config( -&gt; 1094 args, constructor, trace_patch 1095 ) 1096 grouper = [x.grouper or one_group for x in grouped_mappings] or [one_group] ~/anaconda3_420/lib/python3.5/site-packages/plotly/express/_core.py in infer_config(args, constructor, trace_patch) 975 all_attrables += [group_attr] 976 --&gt; 977 args = build_dataframe(args, all_attrables, array_attrables) 978 979 attrs = [k for k in attrables if k in args] ~/anaconda3_420/lib/python3.5/site-packages/plotly/express/_core.py in build_dataframe(args, attrables, array_attrables) 897 "\n To use the index, pass it in directly as `df.index`." 898 ) --&gt; 899 raise ValueError(err_msg) 900 if length and len(df_input[argument]) != length: 901 raise ValueError( ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species', 'species_id'] but received: budget </code></pre> <p>Kindly assist Thanks, SB</p>
3
1,298
Method to touch MapControl XAML to set route
<p>I implemented a WPF MapControl control in my Winform application.</p> <p>(Basically, add a WPF User Control project to your Winform solution. Drag and drop whatever WPF control. I chose a DevExpress WPF MapControl, but Microsoft's variant or any other control works just as nicely. Build the project once, and then drag and drop the control which then appears onto your Winform project. If you wish to set/get any properties or expose any methods, you would go to the associated C# code behind and make that public.)</p> <p>Problem: I want to create a method, which would have two GeoPoint arguments (longitude / latitude pairs). The method would then show the best route using BingMaps or the OpenMapDocs to show the route from point A to B, think Google Maps. I would call this method from a button or link on the Winform side.</p> <p>Now, I understand crystal clear how to implement the transition and method. Been there, done that, so to speak. I have the two GeoPoint longitude/latitude pairs inside the code behind for the control.</p> <p>My problem is how to handle the XAML side. I am not that familiar with WPF yet and the XAML side.</p> <p>DevExpress said:</p> <blockquote> <p>It is necessary to configure the route data service inside the XAML user control.</p> </blockquote> <p>That was not the most helpful.</p> <p>Any ideas?</p> <p>I am using .Net 4.5.</p> <p>Here is the XAML code for the DevExpress MapControl. The question is identical to the Microsoft MapControl. Both codes share very similar XAML, at least from my visual looking at it.</p> <pre><code>&lt;UserControl x:Class="bvMaps.MapDevex" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:dxm="http://schemas.devexpress.com/winfx/2008/xaml/map" mc:Ignorable="d" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"&gt; &lt;Grid x:Name="MapContainer"&gt; &lt;dxm:MapControl HorizontalAlignment="Left" Margin="0,0,0,0" Name="mapControl1" VerticalAlignment="Top"&gt; &lt;dxm:InformationLayer&gt; &lt;dxm:InformationLayer.DataProvider&gt; &lt;dxm:BingSearchDataProvider BingKey="myBingKey"/&gt; &lt;/dxm:InformationLayer.DataProvider&gt; &lt;/dxm:InformationLayer&gt; &lt;dxm:InformationLayer&gt; &lt;dxm:InformationLayer.DataProvider&gt; &lt;dxm:BingGeocodeDataProvider BingKey="myBingKey"/&gt; &lt;/dxm:InformationLayer.DataProvider&gt; &lt;/dxm:InformationLayer&gt; &lt;dxm:InformationLayer&gt; &lt;dxm:InformationLayer.DataProvider&gt; &lt;dxm:BingRouteDataProvider BingKey="myBingKey"/&gt; &lt;/dxm:InformationLayer.DataProvider&gt; &lt;/dxm:InformationLayer&gt; &lt;dxm:ImageTilesLayer Margin="0,0,0,0"&gt; &lt;dxm:ImageTilesLayer.DataProvider&gt; &lt;dxm:BingMapDataProvider Kind="Road" BingKey="myBingKey"/&gt; &lt;/dxm:ImageTilesLayer.DataProvider&gt; &lt;/dxm:ImageTilesLayer&gt; &lt;/dxm:MapControl&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre>
3
1,462
how to fix required a bean of type and This application has no explicit mapping for /error in spring boot
<p>here is the aborescence of the packages</p> <pre><code>com +-bass_trans.java_spring_eclips_management +-GestionBassTransApplication.java | +-worker +-adaters | +-in | | +-WorkerController.java (Rest controller use ListOfWorkerImpl) | +-out | +-ListWorkerImpl.java (class implements ListOfWorkerRepository) +-application | +-port | +-in | | +-ListOfWorker.java (interface) | +-out | +-ListOfWorkerRepository.java (interface) +-usecase +-ListOfWorkerImpl (class implements ListOfWorker) </code></pre> <p>// here is my controller class</p> <pre><code>@RestController @RequestMapping() public class WorkerController { private ListOfWorker listOfWorker; @Autowired public WorkerController(ListOfWorker listOfWorker) { this.listOfWorker = listOfWorker; } @GetMapping(&quot;/listWorkers&quot;) public List&lt;Worker&gt; getWorkers() { return listOfWorker.findAll(); } @GetMapping(&quot;/hello&quot;) public String sayHello(){ return &quot;Hello&quot;; }} </code></pre> <p>To solve the error concerning required a bean of type... i use this solution</p> <pre><code>@SpringBootApplication(scanBasePackages={ &quot;bj.com.bass_trans.java_spring_eclips_management.worker.application.port.out.ListOfWorkerRepository&quot;, &quot;bj.com.bass_trans.java_spring_eclips_management.worker.application.port.in.ListOfWorker&quot; //....)} </code></pre> <p>now i found <code>This application has no explicit mapping for /error in spring boot</code> to resolved i use</p> <pre><code>@SpringBootApplication(scanBasePackages={ &quot;bj.com.bass_trans.java_spring_eclips_management.worker.adapters.in&quot; //...)} </code></pre> <p>after that line <strong>required a bean of type...</strong> reappears</p> <p>i thing that is caus of<br /> <code> bj.com.bass_trans.java_spring_eclips_management.worker.adapters.in.WorkerController</code></p> <p>// main class</p> <pre><code>@SpringBootApplication(scanBasePackages={ &quot;bj.com.bass_trans.java_spring_eclips_management.worker.application.port.out.ListOfWorkerRepository&quot;, &quot;bj.com.bass_trans.java_spring_eclips_management.worker.application.port.in.ListOfWorker&quot;, &quot;bj.com.bass_trans.java_spring_eclips_management.worker.adapters.in.WorkerController&quot;, &quot;bj.com.bass_trans.java_spring_eclips_management.worker.adapters.in&quot;, }) public class GestionBassTransApplication implements CommandLineRunner{ public static void main(String[] args) { SpringApplication.run(GestionBassTransApplication.class, args); } @Override public void run(String... args) throws Exception { } } </code></pre> <p>// complete error</p> <pre><code> Description: Parameter 0 of constructor in bj.com.bass_trans.java_spring_eclips_management.worker.adapters.in.WorkerController required a bean of type 'bj.com.bass_trans.java_spring_eclips_management.worker.application.port.in.ListOfWorker' that could not be found. Action: Consider defining a bean of type 'bj.com.bass_trans.java_spring_eclips_management.worker.application.port.in.ListOfWorker' in your configuration. </code></pre> <p>// This application has no explicit mapping...</p> <pre><code>Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Mon Dec 13 15:24:37 WAT 2021 There was an unexpected error (type=Not Found, status=404). No message available </code></pre> <p>how how can i solve these errors</p>
3
1,472
Namespacing "Class not found" when autoloading via composer
<p>I created a small project with a <code>composer.json</code> and have this set up:</p> <pre class="lang-json prettyprint-override"><code>&quot;autoload&quot;: { &quot;psr-4&quot;: { &quot;MyApp\\&quot;: &quot;src/&quot; } }, &quot;autoload-dev&quot;: { &quot;psr-4&quot;: { &quot;MyApp\\Tests\\&quot;: &quot;tests/&quot; } }, </code></pre> <p><a href="https://i.stack.imgur.com/Zj3Aw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zj3Aw.png" alt="Folder Structure" /></a></p> <h4><code>phpunit.xml</code></h4> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;phpunit xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:noNamespaceSchemaLocation=&quot;https://schema.phpunit.de/9.5/phpunit.xsd&quot; bootstrap=&quot;vendor/autoload.php&quot; cacheResultFile=&quot;.phpunit.cache/test-results&quot; executionOrder=&quot;depends,defects&quot; forceCoversAnnotation=&quot;true&quot; beStrictAboutCoversAnnotation=&quot;true&quot; beStrictAboutOutputDuringTests=&quot;true&quot; beStrictAboutTodoAnnotatedTests=&quot;true&quot; convertDeprecationsToExceptions=&quot;true&quot; failOnRisky=&quot;true&quot; failOnWarning=&quot;true&quot; verbose=&quot;true&quot;&gt; &lt;testsuites&gt; &lt;testsuite name=&quot;default&quot;&gt; &lt;directory&gt;tests&lt;/directory&gt; &lt;/testsuite&gt; &lt;/testsuites&gt; &lt;coverage cacheDirectory=&quot;.phpunit.cache/code-coverage&quot; processUncoveredFiles=&quot;true&quot;&gt; &lt;include&gt; &lt;directory suffix=&quot;.php&quot;&gt;src&lt;/directory&gt; &lt;/include&gt; &lt;/coverage&gt; &lt;/phpunit&gt; </code></pre> <h4><code>ClientCrawler.php</code></h4> <pre class="lang-php prettyprint-override"><code>namespace MyApp; class ClientCrawler { } </code></pre> <h4><code>ClientCrawlerTest.php</code></h4> <pre class="lang-php prettyprint-override"><code>namespace MyApp\Tests; use MyApp\ClientCrawler; use PHPUnit\Framework\TestCase; class ClientCrawlerTest extends TestCase { public function testCheckClient() { $this-&gt;assertTrue(true); $crawler = new ClientCrawler(); } } </code></pre> <h4>Test Command (PhpStorm)</h4> <pre><code>C:\xampp\php\php.exe D:\phpunit\phpunit.phar --no-configuration --filter MyApp\\Tests\\ClientCrawlerTest --test-suffix ClientCrawlerTest.php C:\Users\MYNAME\PhpstormProjects\CodingPractice\tests --teamcity --cache-result-file=C:\Users\MYNAME\PhpstormProjects\CodingPractice\.phpunit.result.cache </code></pre> <h4>Result</h4> <blockquote> <p>Error: Class &quot;MyApp\ClientCrawler&quot; not found</p> </blockquote> <h3>Things I tried</h3> <ul> <li><code>composer dump-autoload</code></li> <li>Deleted vendor and <code>composer install</code> (with another <code>dump-autoload</code>)</li> <li>Deleted the <code>.phpunit.result.cache</code></li> <li>Restarted PhpStorm</li> </ul> <p>Where am I wrong?</p>
3
1,463
Flutter App not running in Android studio
<p>I have simple flutter app with sqflite db. When I try to run via <code>Android Studio</code> , it gives error as follow:</p> <pre><code>Launching lib/main.dart on iPhone 12 Pro in debug mode... Running pod install... CocoaPods' output: ↳ CDN: trunk Relative path: CocoaPods-version.yml exists! Returning local because checking is only performed in repo update Error output from CocoaPods: ↳ WARNING: CocoaPods requires your terminal to be using UTF-8 encoding. Consider adding the following to ~/.profile: export LANG=en_US.UTF-8 /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/unicode_normalize/normalize.rb:141:in `normalize': Unicode Normalization not appropriate for ASCII-8BIT (Encoding::CompatibilityError) from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/config.rb:166:in `unicode_normalize' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/config.rb:166:in `installation_root' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/config.rb:226:in `podfile_path' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/user_interface/error_report.rb:105:in `markdown_podfile' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/user_interface/error_report.rb:30:in `report' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/command.rb:66:in `report_error' from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:396:in `handle_exception' from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:337:in `rescue in run' from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:324:in `run' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/command.rb:52:in `run' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/bin/pod:55:in `&lt;top (required)&gt;' from /usr/local/bin/pod:23:in `load' from /usr/local/bin/pod:23:in `&lt;main&gt;' /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/unicode_normalize/normalize.rb:141:in `normalize': Unicode Normalization not appropriate for ASCII-8BIT (Encoding::CompatibilityError) from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/config.rb:166:in `unicode_normalize' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/config.rb:166:in `installation_root' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/config.rb:226:in `podfile_path' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/config.rb:205:in `podfile' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/command.rb:160:in `verify_podfile_exists!' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/command/install.rb:46:in `run' from /Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/lib/cocoapods/command.rb:52:in `run' from /Library/Ruby/Gems/2.6.0/gems/cocoapods-1.11.2/bin/pod:55:in `&lt;top (required)&gt;' from /usr/local/bin/pod:23:in `load' from /usr/local/bin/pod:23:in `&lt;main&gt;' Error running pod install Error launching application on iPhone 12 Pro. </code></pre> <p><strong>When I try to run via external terminal then it works fine</strong></p> <p>I already try to run export UTF-8 command but nothing happens.</p> <p>How can I resolve this issue? Hope you get my question. Thank you</p>
3
1,667
Getting undefined array key when passing data with XMLHttpRequest
<p>I'm trying to pass a long formatted text string to a php process to save to a file. I am use the POST method as the string can be quite long. It seems to run thro the process and gives back the message 'File saved' but with the error message 'Undefined Array Key &quot;data&quot;' on line 2 of the php code. The file does not get saved and no data is being sent across from the XMLHttpRequest in the previous function. My code is:- This gets 'str' from the previous function and is formatted correctly.</p> <pre><code>function getGame(str){ //Sends data to the php process &quot;saveGame.php&quot;. var data = str; var xhr = new XMLHttpRequest(); xhr.open(&quot;POST&quot;, &quot;saveGame.php&quot;, true); xhr.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); xhr.onreadystatechange = function() { if (this.readyState === 4 ){ alert(xhr.responseText); } }; xhr.send(data); } </code></pre> <p>it then goes the the 'saveGame.php' where the problem occurs on line 2.</p> <pre><code>&lt;?php $outputString = $_POST[&quot;data&quot;]; $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; $fp = fopen(&quot;C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt&quot;,&quot;w&quot;); fwrite($fp, $outputString); if (!$fp){ $message = &quot;Error writing to file. Try again later!&quot; ; }else{ $message = &quot;File saved!&quot;; } fclose($fp); echo $message; ?&gt; </code></pre> <p>I think my code of the process is okay but there is a problem with passing the &quot;data&quot; variable and I not sure what it is.</p> <p>I tested the file saving process. I put a dummy string as a value of 'outputString' and it saved it. When I went back and used the current code the file was overwritten and was blank, indicating it had saved a blank string. So it seems no data is been passed to saveTeams.php although the saving of the file works.</p> <p>I have got a reproducible example below. If you use it with the saveTeams.php file and a file to attempt to save the data to it should display the error I get in an alert drop down.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;head&gt; &lt;title&gt;Test program&lt;/title&gt; &lt;script language=&quot;javascript&quot;&gt; function formatOutput() { // lots of formatting goes on here var formattedText = &quot;This is a test&quot;; //test data getGame(formattedText); } function getGame(str){ //Sends data to the php process &quot;save Game&quot;. var data = str; var xhr = new XMLHttpRequest(); xhr.open(&quot;POST&quot;, &quot;saveGame.php&quot;, true); xhr.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); xhr.onreadystatechange = function() { if (this.readyState === 4 ){ alert(xhr.responseText); } }; xhr.send(data); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table width=&quot;1000&quot; align=&quot;center&quot; border=&quot;0&quot;&gt; &lt;br /&gt; &lt;tr&gt; &lt;td width=&quot;500&quot;align=&quot;center&quot; colspan=&quot;3&quot; &lt;button onclick=&quot;formatOutput()&quot;/&gt;Click on me&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Hope this okay. I'm a bit new to this.</p>
3
1,367
jquery plugin, tablesorter pager with multiple tables
<p>I'm trying to use the jQuery tablesorter plugin on multiple tables with asp.net/mvc3. I'm following this tutorial: <a href="http://weblogs.asp.net/hajan/archive/2011/02/09/table-sorting-amp-pagination-with-jquery-in-asp-net-mvc.aspx" rel="nofollow">http://weblogs.asp.net/hajan/archive/2011/02/09/table-sorting-amp-pagination-with-jquery-in-asp-net-mvc.aspx</a></p> <p>I have 2 different tables on my page. I'd like to have the ability to set the number of rows for each table using this plugin. One problem I have is the tables by default have the number of rows shown by the first table. Then I'm able to use the plugin on each table. So for example, below table 1, I have this:</p> <pre><code>&lt;div id="pagerOwnerRequests"&gt; &lt;form&gt; &lt;select id="selectOwnerRequests" class="pagesize"&gt; @*&lt;select id="selectOwnerRequests" class="pagesizeOwnerRequests"&gt;*@ &lt;option selected="selected" value="0"&gt;0&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>Below table 2, I have this:</p> <pre><code>&lt;div id="pagerBoardRequests"&gt; &lt;form&gt; &lt;select id="selectBoardRequests" class="pagesize"&gt; &lt;option selected="selected" value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>At the bottom of my .cshtml file for this page, I have this:</p> <pre><code> $(document).ready(function () { $("#tbOwnerRequests").tablesorter({ headers: { 6: { sorter: false } } } ).tablesorterPager({ container: $("#pagerOwnerRequests"), size: $(".pagesize option:selected").val() }); }); $(document).ready(function () { $("#tbBoardRequests").tablesorter({ headers: { 7: { sorter:false } } } ).tablesorterPager({ container: $("#pagerBoardRequests"), size: $(".pagesize option:selected").val() }); }); </code></pre> <p>So what happens when the page load is, because table 1's drop down list is set to 0, both table 1 and table 2 have 0 elements. then when I manually go in and change the drop down for table 1 or table 2, it updates properly. I'm not sure why. I just started using jQuery/html/css so sorry if the answer is obvious, but I can't seem to see it. TIA.</p>
3
1,228
Lazy loading of child throwing session error
<p>I'm the following error when calling purchaseService.updatePurchase(purchase) inside my TagController:</p> <pre><code>SEVERE: Servlet.service() for servlet [PurchaseAPIServer] in context with path [/PurchaseAPIServer] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.model.Purchase.tags, no session or session was closed] with root cause org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.model.Purchase.tags, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375) at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368) at org.hibernate.collection.PersistentSet.add(PersistentSet.java:212) at com.app.model.Purchase.addTags(Purchase.java:207) at com.app.controller.TagController.createAll(TagController.java:79) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) at javax.servlet.http.HttpServlet.service(HttpServlet.java:641) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) </code></pre> <p><em><strong>TagController:</em></strong></p> <pre><code>@RequestMapping(value = "purchases/{purchaseId}/tags", method = RequestMethod.POST, params = "manyTags") @ResponseStatus(HttpStatus.CREATED) public void createAll(@PathVariable("purchaseId") final Long purchaseId, @RequestBody final Tag[] entities) { Purchase purchase = purchaseService.getById(purchaseId); Set&lt;Tag&gt; tags = new HashSet&lt;Tag&gt;(Arrays.asList(entities)); purchase.addTags(tags); purchaseService.updatePurchase(purchase); } </code></pre> <p><br> <strong><em>Purchase:</em></strong></p> <pre><code>@Entity @XmlRootElement public class Purchase implements Serializable { /** * */ private static final long serialVersionUID = 6603477834338392140L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToMany(mappedBy = "purchase", fetch = FetchType.LAZY, cascade={CascadeType.ALL}) private Set&lt;Tag&gt; tags; @JsonIgnore public Set&lt;Tag&gt; getTags() { if (tags == null) { tags = new LinkedHashSet&lt;Tag&gt;(); } return tags; } public void setTags(Set&lt;Tag&gt; tags) { this.tags = tags; } public void addTag(Tag tag) { tag.setPurchase(this); this.tags.add(tag); } public void addTags(Set&lt;Tag&gt; tags) { Iterator&lt;Tag&gt; it = tags.iterator(); while (it.hasNext()) { Tag tag = it.next(); tag.setPurchase(this); this.tags.add(tag); } } ... } </code></pre> <p><br> <strong><em>Tag:</em></strong></p> <pre><code>@Entity @XmlRootElement public class Tag implements Serializable { /** * */ private static final long serialVersionUID = 5165922776051697002L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({@JoinColumn(name = "PURCHASEID", referencedColumnName = "ID")}) private Purchase purchase; @JsonIgnore public Purchase getPurchase() { return purchase; } public void setPurchase(Purchase purchase) { this.purchase = purchase; } } </code></pre> <p><br> <strong><em>PurchaseService:</em></strong></p> <pre><code>@Service public class PurchaseService implements IPurchaseService { @Autowired private IPurchaseDAO purchaseDAO; public PurchaseService() { } @Transactional public List&lt;Purchase&gt; getAll() { return purchaseDAO.findAll(); } @Transactional public Purchase getById(Long id) { return purchaseDAO.findOne(id); } @Transactional public void addPurchase(Purchase purchase) { purchaseDAO.save(purchase); } @Transactional public void updatePurchase(Purchase purchase) { purchaseDAO.update(purchase); } } </code></pre> <p><br> <strong><em>TagService:</em></strong></p> <pre><code>@Service public class TagService implements ITagService { @Autowired private ITagDAO tagDAO; public TagService() { } @Transactional public List&lt;Tag&gt; getAll() { return tagDAO.findAll(); } @Transactional public Tag getById(Long id) { return tagDAO.findOne(id); } @Transactional public void addTag(Tag tag) { tagDAO.save(tag); } @Transactional public void updateTag(Tag tag) { tagDAO.update(tag); } } </code></pre> <p><br> Any ideas on how I can fix this? (I want to avoid using EAGER loading).</p> <p>Do I need to setup some form of session management for transactions?</p> <p>Thanks</p> <h2>Updates based on JB suggestions</h2> <p><em><strong>TagController</em></strong></p> <pre><code>@RequestMapping(value = "purchases/{purchaseId}/tags", method = RequestMethod.POST, params = "manyTags") @ResponseStatus(HttpStatus.CREATED) public void createAll(@PathVariable("purchaseId") final Long purchaseId, @RequestBody final Tag[] entities) { Purchase purchase = purchaseService.getById(purchaseId); // Validation RestPreconditions.checkRequestElementNotNull(purchase); RestPreconditions.checkRequestElementIsNumeric(purchaseId); Set&lt;Tag&gt; tags = new HashSet&lt;Tag&gt;(Arrays.asList(entities)); purchaseService.addTagsToPurchase(purchaseId, tags); } </code></pre> <p><em><strong>PurchaseService</em></strong></p> <pre><code>@Transactional public void addTagsToPurchase(Long purchaseId, Set&lt;Tag&gt; tags) { Purchase p = purchaseDAO.findOne(purchaseId); p.addTags(tags); } </code></pre>
3
3,293
With Ant, how do I create seperate jar files from one src directory?
<p>I have one source directory in which I am trying to create separate cod files since my resources (PNG files) are beyond the limit imposed by the RAPC compiler.</p> <p>I am trying to create:</p> <ol> <li>.cod(s) for the source</li> <li>.cod(s) for low res. resources</li> <li>.cod(s) for hi res. resources</li> </ol> <p>Which I am successful in creating the following:</p> <p>AppMeasurement_BlackBerry.cod</p> <p>com_mch_coffeehouse-1.cod</p> <p>com_mch_coffeehouse.cod</p> <p>com_mch_coffeehouse.jad</p> <p>com_mch_coffeehouse_resources_hires-1.cod</p> <p>com_mch_coffeehouse_resources_hires-2.cod</p> <p>com_mch_coffeehouse_resources_hires-3.cod</p> <p>com_mch_coffeehouse_resources_hires-4.cod</p> <p>com_mch_coffeehouse_resources_hires-5.cod</p> <p>com_mch_coffeehouse_resources_hires-6.cod</p> <p>com_mch_coffeehouse_resources_hires-7.cod</p> <p>com_mch_coffeehouse_resources_hires.cod</p> <p>com_mch_coffeehouse_resources_lowres-1.cod</p> <p>com_mch_coffeehouse_resources_lowres-2.cod</p> <p>com_mch_coffeehouse_resources_lowres-3.cod</p> <p>com_mch_coffeehouse_resources_lowres-4.cod</p> <p>com_mch_coffeehouse_resources_lowres.cod</p> <p>common-1.cod</p> <p>common.cod</p> <p>However, the application does not start-up and from the event log on the device, I get that wonderful encrypted message:</p> <p>RIM Wireless Handheld Java Loader Copyright 2001-2009 Research In Motion Limited Connected guid:0x97C9F5F641D25E5F time: Wed Dec 31 19:00:00 1969 severity:0 type:2 app:System data:JVM:INFOp=23575346,a='5.0.0.979',o='5.1.0.177',h=4001507 guid:0x9C3CD62E3320B498 time: Fri Jul 01 16:59:26 2011 severity:1 type:3 app:Java Exception data: Error No detail message com_mch_coffeehouse(4E0E2E1F) CoffeeHouseClient 0x3764 com_mch_coffeehouse(4E0E2E1F) CoffeeHouseClient main 0x30BD guid:0x0 time: Fri Jul 01 16:59:26 2011 severity:2 type:3 app: data: Traceback:</p> <p>guid:0x97C9F5F641D25E5F time: Fri Jul 01 16:59:31 2011 severity:0 type:2 app:System data:JVM:INFOp=23575346,a='5.0.0.979',o='5.1.0.177',h=4001507</p> <p>Anyway, any help or suggestions is greatly appreciated before this becomes a critical blocker - yippee!</p> <p>My Ant script:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; </code></pre> <p> </p> <pre><code>&lt;property name="package.label" value="com_mch_coffeehouse" /&gt; &lt;property name="lowres.label" value="com_mch_coffeehouse_resources_lowres" /&gt; &lt;property name="hires.label" value="com_mch_coffeehouse_resources_hires" /&gt; &lt;property name="jde.home" value="C:\Eclipse3.6\plugins\net.rim.ejde.componentpack5.0.0_5.0.0.25\components" /&gt; &lt;property name="workspace" value="C:\Users\jtp\Documents\mch" /&gt; &lt;property name="appmeasure" value="${workspace}\AppMeasurement_BlackBerry\deliverables\Standard\5.0.0" /&gt; &lt;property name="common" value="${workspace}\Common-BlackBerry\deliverables\Standard\5.0.0" /&gt; &lt;property name="simulator" value="${jde.home}\simulator" /&gt; &lt;property name="bin" value="${jde.home}\bin" /&gt; &lt;property name="src" value="src" /&gt; &lt;property name="respackage" value="${src}\com\mch\coffee_house\res" /&gt; &lt;property name="hi" value="${respackage}\hi" /&gt; &lt;property name="low" value="${respackage}\low" /&gt; &lt;property name="dest" value="deliverables" /&gt; &lt;property name="ota.dir" value="${dest}\ota" /&gt; &lt;target name="debug" depends="ota" description="Build, deploy project and Launches Remote Debug Server"&gt; &lt;exec executable="cmd.exe" dir="${bin}" spawn="true"&gt; &lt;arg value="/c" /&gt; &lt;arg value="jdwp.bat" /&gt; &lt;/exec&gt; &lt;/target&gt; &lt;target name="simulate" depends="ota" description="Build, deploy project and Launches Simulator"&gt; &lt;exec executable="cmd.exe" dir="${simulator}" spawn="true"&gt; &lt;arg value="/c" /&gt; &lt;arg value="${simulator}\9700.bat" /&gt; &lt;/exec&gt; &lt;/target&gt; &lt;target name="ota" depends="build" description="Build OTA project."&gt; &lt;mkdir dir="${ota.dir}" /&gt; &lt;jadtool input="${dest}\${package.label}.jad" destdir="${ota.dir}"&gt; &lt;fileset dir="${appmeasure}" includes="*.cod" /&gt; &lt;fileset dir="${common}" includes="*.cod" /&gt; &lt;fileset dir="${dest}" includes="*.cod" /&gt; &lt;/jadtool&gt; &lt;/target&gt; &lt;target name="deploy" depends="build" description="Build and deploy project."&gt; &lt;copy todir="${simulator}" overwrite="true"&gt; &lt;fileset dir="${appmeasure}"&gt; &lt;include name="*.cod" /&gt; &lt;include name="*.debug" /&gt; &lt;include name="*.csl" /&gt; &lt;include name="*.cso" /&gt; &lt;/fileset&gt; &lt;/copy&gt; &lt;copy todir="${simulator}" overwrite="true"&gt; &lt;fileset dir="${common}"&gt; &lt;include name="*.cod" /&gt; &lt;include name="*.debug" /&gt; &lt;include name="*.csl" /&gt; &lt;include name="*.cso" /&gt; &lt;/fileset&gt; &lt;/copy&gt; &lt;copy todir="${simulator}" overwrite="true"&gt; &lt;fileset dir="${dest}"&gt; &lt;include name="*.cod" /&gt; &lt;include name="*.debug" /&gt; &lt;include name="*.csl" /&gt; &lt;include name="*.cso" /&gt; &lt;/fileset&gt; &lt;/copy&gt; &lt;/target&gt; &lt;target name="build" depends="buildhiresources" description="Builds project."&gt; &lt;!-- Copy the resource package to be compiled with preserved folder hierarchy --&gt; &lt;!--&lt;copy todir="${dest}"&gt; &lt;fileset dir="${src}"&gt; &lt;include name="com/mch/coffee_house/res/low/*.png" /&gt; &lt;include name="com/mch/coffee_house/res/hi/*.png" /&gt; &lt;exclude name="**/*.java" /&gt; &lt;exclude name="com/mch/coffee_house/res/torch/*.png" /&gt; &lt;/fileset&gt; &lt;/copy&gt;--&gt; &lt;!-- ${appmeasure}\AppMeasurement_BlackBerry.jar:${common}\danicacommon.jar:${dest}\com_mch_coffeehouse_resources_hires.jar:${dest}\com_mch_coffeehouse_resources_lowres.jar --&gt; &lt;rapc jdehome="${jde.home}" jdkhome="${java.home}" import="${appmeasure}\AppMeasurement_BlackBerry.jar:${common}\danicacommon.jar:${dest}\com_mch_coffeehouse_resources_hires.jar:${dest}\com_mch_coffeehouse_resources_lowres.jar" destdir="${dest}" noconvert="false" output="${package.label}" quiet="true" verbose="false" generatesourcelist="false" nopreverify="true"&gt; &lt;jdp type="cldc" title="mch coffeehouse" vendor="MCH Inc" version="1.0.0" description="Find a coffee house from your BlackBerry device." arguments="" systemmodule="false" runonstartup="false" startuptier="7" ribbonposition="0" nameresourcebundle="com.mch.coffeehouse" nameresourceid="0" icon="../src/com/mch/coffee_house/res/hi/icon.png"&gt; &lt;/jdp&gt; &lt;src&gt; &lt;fileset dir="."&gt; &lt;exclude name="src/com/mch/coffee_house/res/hi/*.java*" /&gt; &lt;exclude name="src/com/mch/coffee_house/res/low/*.java*" /&gt; &lt;include name="src/**/*.java*" /&gt; &lt;include name="src/**/*.rrc*" /&gt; &lt;include name="src/**/*.rrh*" /&gt; &lt;include name="src/**/*.cod*" /&gt; &lt;include name="src/**/*.cso*" /&gt; &lt;include name="src/**/*.MF*" /&gt; &lt;!-- Add the preserved folder hierachy to be compiled as is --&gt; &lt;!--&lt;include name="${dest}/com/**/*.*" /&gt;--&gt; &lt;/fileset&gt; &lt;/src&gt; &lt;/rapc&gt; &lt;sigtool jdehome="${jde.home}" password="########" close="false"&gt; &lt;fileset dir="${dest}" includes="*.cod" /&gt; &lt;/sigtool&gt; &lt;/target&gt; &lt;!-- Hi Res. Resources --&gt; &lt;target name="buildhiresources" depends="buildlowresources" description="Builds low resolution resources project."&gt; &lt;!-- Copy the resource package to be compiled with preserved folder hierarchy --&gt; &lt;copy todir="${dest}"&gt; &lt;fileset dir="${src}"&gt; &lt;include name="com/mch/coffee_house/res/hi/*.png" /&gt; &lt;exclude name="com/mch/coffee_house/res/low/*.png" /&gt; &lt;exclude name="**/*.java" /&gt; &lt;exclude name="com/mch/coffee_house/res/torch/*.png" /&gt; &lt;/fileset&gt; &lt;/copy&gt; &lt;rapc jdehome="${jde.home}" jdkhome="${java.home}" destdir="${dest}" noconvert="false" output="${hires.label}" quiet="true" verbose="false" generatesourcelist="false" nopreverify="true"&gt; &lt;jdp type="library" title="MCH Library" vendor="MCH Inc" version="1.0.0" description="coffeehouse hi-res resources library."&gt; &lt;/jdp&gt; &lt;src&gt; &lt;fileset dir="."&gt; &lt;!-- Add the preserved folder hierachy to be compiled as is --&gt; &lt;include name="src/com/mch/coffee_house/res/hi/*.java*" /&gt; &lt;include name="${dest}/com/**/*.*" /&gt; &lt;exclude name="${dest}/com/mch/coffee_house/res/low/*.png" /&gt; &lt;/fileset&gt; &lt;/src&gt; &lt;/rapc&gt; &lt;sigtool jdehome="${jde.home}" password="########" close="false"&gt; &lt;fileset dir="${dest}" includes="*.cod" /&gt; &lt;/sigtool&gt; &lt;/target&gt; &lt;!-- Low Res. Resources --&gt; &lt;target name="buildlowresources" description="Builds low resolution resources project."&gt; &lt;!-- Copy the resource package to be compiled with preserved folder hierarchy --&gt; &lt;copy todir="${dest}"&gt; &lt;fileset dir="${src}"&gt; &lt;exclude name="com/mch/coffee_house/res/hi/*.png" /&gt; &lt;include name="com/mch/coffee_house/res/low/*.png" /&gt; &lt;exclude name="**/*.java" /&gt; &lt;exclude name="com/mch/coffee_house/res/torch/*.png" /&gt; &lt;/fileset&gt; &lt;/copy&gt; &lt;rapc jdehome="${jde.home}" jdkhome="${java.home}" destdir="${dest}" noconvert="false" output="${lowres.label}" quiet="true" verbose="false" generatesourcelist="false" nopreverify="true"&gt; &lt;jdp type="library" title="MCH Library" vendor="MCH Inc" version="1.0.0" description="coffeehouse low-res resources library."&gt; &lt;/jdp&gt; &lt;src&gt; &lt;fileset dir="."&gt; &lt;!-- Add the preserved folder hierachy to be compiled as is --&gt; &lt;include name="src/com/mch/coffee_house/res/low/*.java*" /&gt; &lt;include name="${dest}/com/**/*.*" /&gt; &lt;/fileset&gt; &lt;/src&gt; &lt;/rapc&gt; &lt;sigtool jdehome="${jde.home}" password="########" close="false"&gt; &lt;fileset dir="${dest}" includes="*.cod" /&gt; &lt;/sigtool&gt; &lt;/target&gt; &lt;target name="clean" description="Clean the destination directory."&gt; &lt;delete dir="${ota.dir}" failonerror="no" /&gt; &lt;delete dir="${dest}" failonerror="no" /&gt; &lt;mkdir dir="${dest}" /&gt; &lt;/target&gt; </code></pre> <p></p>
3
5,260
Can Excel Vba code be updated via an Excel Add In for multiple users
<p>I have an Excel workbook that contains lots of VBA code. The VBA Code consists of many Sub routines, Functions and User Forms. Over 200+ employees will be using this Workbook.</p> <p>Currently my VBA code lives inside the distributed Excel Workbook. The problem I fear I will be faced with is updating each Workbooks VBA code if any update is ever needed.</p> <p>Would it be best to write all my VBA code as part of an Add In, upload a new version of the Add In to a site and have employees download from there? If so, would I encounter any limitations or restrictions? Is such feature even possible? Is VB.Net a better solution?</p> <p>I have created an XLAM file from my original Workbook File. The original Workbook file containa all my Sub Routines, Functions, and UserForms. I am encountering an error when calling the UserForm directly, even though I referenced the XLAM file that contains UserForm1. </p> <p>The following scenarios are being ran from the distributed WorkBook copy. The WorkBook is referencing the XLAM file. </p> <p><strong>Scenario1: Calling a UserForm from a Sub assigned to a shape</strong> The following Sub returns a <code>Runtime Error 424 Object Required</code></p> <pre><code>Sub RectangleRoundedCorners1_Click() UserForm1.Show 'highlights this line on the error, XLAM reference houses UserForm1 End Sub </code></pre> <p><strong>Scenario2: Calling a Sub Procedure from a shape that calls the UserForm</strong> This method doesn't return an error, why? Can we not reference UserForm Objects from a referenced Add In? </p> <pre><code>Sub RectangleRoundedCorners1_Click() showUserForm End Sub Sub showUserForm() UserForm1.Show End Sub </code></pre> <p><strong>Scenario 3: Using UserForms to input values into Worksheet Cells</strong></p> <p><em>Would I have to refrence the <code>ActiveWorkbook</code> in each of my UserForms?</em></p> <pre><code>Private Sub CommandButton1_Click() Set wb = ActiveWorkbook Set ws = wb.Sheets("clientmenu") forceLogOut 'clear filter so that we dont mix new customers up If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData With ws.Shapes("priorities") .Fill.ForeColor.RGB = RGB(64, 64, 64) End With End If If contact.value &lt;&gt; "" And result.value = vbNullString Then MsgBox "Please enter a result" result.BorderColor = vbRed result.BackColor = vbYellow result.DropDown Exit Sub ElseIf contact.value = vbNullString And result.value &lt;&gt; "" Then MsgBox "Please enter a date" contact.BorderColor = vbRed contact.BackColor = vbYellow Exit Sub Else: With ws callDate callResult End With End If With ws lastrow = .Range("A" &amp; Rows.Count).End(xlUp).Row + 1 If Me.priority_ = vbNullString Then ws.Range("A" &amp; lastrow).Interior.Color = vbWhite ws.Range("A" &amp; lastrow).Font.Color = RGB(0, 0, 0) ElseIf Me.priority_ = "None" Then ws.Range("A" &amp; lastrow).Interior.Color = vbWhite ws.Range("A" &amp; lastrow).Font.Color = RGB(0, 0, 0) ws.Range("B" &amp; lastrow).value = vbNullString ElseIf Me.priority_ = "High" Then '.Cells(x, 1).Interior.Color = RGB(0, 176, 80) ws.Range("A" &amp; lastrow).Font.Color = RGB(0, 176, 80) ws.Range("B" &amp; lastrow).value = addnewClient.priority_.Text ElseIf Me.priority_ = "Medium" Then '.Cells(x, 1).Interior.Color = RGB(255, 207, 55) ws.Range("A" &amp; lastrow).Font.Color = RGB(255, 207, 55) ws.Range("B" &amp; lastrow).value = addnewClient.priority_.Text ElseIf Me.priority_ = "Low" Then '.Cells(x, 1).Interior.Color = RGB(241, 59, 59) ws.Range("A" &amp; lastrow).Font.Color = RGB(241, 59, 59) ws.Range("B" &amp; lastrow).value = addnewClient.priority_.Text End If If Me.client = vbNullString Then MsgBox "Must enter Clients name in order to proceed" Exit Sub ElseIf Me.client &lt;&gt; vbNullString Then ws.Range("L" &amp; lastrow).value = Format(Now(), "mm/dd/yyyy") ws.Range("A" &amp; lastrow).value = addnewClient.client.Text ws.Range("A" &amp; lastrow).Font.Name = "Arial" ws.Range("A" &amp; lastrow).Font.Size = 18 ws.Range("A" &amp; lastrow).Font.Bold = True ws.Range("B" &amp; lastrow).Font.Name = "Arial" ws.Range("B" &amp; lastrow).Font.Size = 14 ws.Range("B" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("C" &amp; lastrow).value = addnewClient.priority.Text ws.Range("C" &amp; lastrow).Font.Name = "Arial" ws.Range("C" &amp; lastrow).Font.Size = 14 ws.Range("C" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("E" &amp; lastrow).value = addnewClient.contact.value ws.Range("E" &amp; lastrow).Font.Name = "Arial" ws.Range("E" &amp; lastrow).Font.Size = 14 ws.Range("E" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("G" &amp; lastrow).value = addnewClient.result.Text ws.Range("G" &amp; lastrow).Font.Name = "Arial" ws.Range("G" &amp; lastrow).Font.Size = 14 ws.Range("G" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("I" &amp; lastrow).value = addnewClient.segmentType.Text ws.Range("I" &amp; lastrow).Font.Name = "Arial" ws.Range("I" &amp; lastrow).Font.Size = 14 ws.Range("I" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("K" &amp; lastrow).value = addnewClient.notes.Text If Me.contact = vbNullString Then ElseIf Me.contact &lt;&gt; vbNullString Then ws.Range("J" &amp; lastrow) = Sheet3.Range("J" &amp; lastrow).value + 1 ws.Range("J" &amp; lastrow).Font.Name = "Arial" ws.Range("J" &amp; lastrow).Font.Size = 14 ws.Range("J" &amp; lastrow).Font.Bold = True ws.Range("J" &amp; lastrow).HorizontalAlignment = xlCenter End If End If End With 'With Sheet3 'Sheet3.Range("A" &amp; lastrow &amp; ":K" &amp; lastrow).Interior.Color = vbWhite Application.GoTo Range("A" &amp; lastrow), True 'End With wb.Sheets(2).Range("C4") = Format(Now, "mm/dd/yyyy") Unload Me End Sub </code></pre>
3
2,664
Bootstrap - Responsive navbar works on index page but no other page
<p>Pretty much says my issue in the title. The responsive nav works fine for the index page, but on other pages, it doesn't. It still collapses, but nothing happens when you click on the dropdown icon.</p> <p>My nav code is:</p> <pre><code> &lt;div class="navbar"&gt; &lt;div class="navbar-inner"&gt; &lt;div class="container"&gt; &lt;a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/a&gt; &lt;div class="nav-collapse collapse"&gt; &lt;ul class="nav"&gt; &lt;li class="navbar_link navitem1"&gt;&lt;a href="index.html"&gt;&lt;strong&gt;HOME&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class="divider-vertical navitem2"&gt;&lt;/li&gt; &lt;li class="navbar_link navitem3"&gt;&lt;a href="gallery.html"&gt;&lt;strong&gt;GALLERY&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class="divider-vertical navitem4"&gt;&lt;/li&gt; &lt;li class="navbar_link navitem5"&gt;&lt;a href="aboutus.html"&gt;&lt;strong&gt;ABOUT US&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class="divider-vertical navitem6"&gt;&lt;/li&gt; &lt;li class="navbar_link navitem7"&gt;&lt;a href="contact.html"&gt;&lt;strong&gt;CONTACT&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Any help is greatly appreciated.</p>
3
1,105
I cannot find my error and it repeats forever
<p>Below while-loop is meant to repeat forever (thus <code>i=0</code> never modified inside the loop). The loop has a <code>checkpoint</code> so every read line continues where it left off.</p> <p>But the checkpoint is not working, any way to fix that? Okay, I am not modifying the i var (which is a big suggestion) unless it is done, so it repeats, resumes checkpoint, and writes data, repeat. BUT what I am trying to say is that the checkpoint is broken and the program will not end after it is done reading all of the file.</p> <h3>Code</h3> <pre><code>i = 0 while i == 0: file1 = open('APPMAKE', 'r') Lines = file1.readlines() count = 0 checkpoint = 0 ccount = 1 modeset = 0 # Strips the newline character for line in Lines: count += 1 ccount += 1 modeset += 1 if ccount &gt; checkpoint: checkpoint += 1 if modeset &gt; 2: modeset == 1 if modeset == 1: elfexecutable = line if modeset == 2: appname = line checkpoint = count + 1 break #writing data file1.close() file2 = open(appname + &quot;.app&quot;, &quot;a&quot;) # append mode file2.write(elfexecutable + &quot;\n&quot;) file2.close() </code></pre> <p>I put this in the APPMAKE file to test:</p> <pre><code>elf.elf ap.app elf.elf ap.app elf.elf ap.app elf.elf ap.app </code></pre> <p>Oh, and I made a manual to use this Python script. This <em>might</em> help you understand it:</p> <pre class="lang-text prettyprint-override"><code>APP MAKE INSTRUCTIONS ===================== First, to generate app, create a APPMAKE file. Next, add repeated code scripts that are like this: [elf file to link to] [app file name] ... Then, you made a APPMAKE file! To make more configs, list more of the scripts above. Remember yo replace the things in the []s! Also, you can make a app run more than 1 elf you can make more than 1 configuration for each file. Now, how do you run a APPMAKE file? Well first go copy &amp; paste (do this sentence if your project is not a template) the elfexepreferences.sh file into the folder with the APPMAKE file. (do this even if your project is a template --&gt;) Now, edit the file you just pasted and edit the part that looks like this: elfexecute () { [function to execute elf] $1 } Edit the []s depending on what system your apps are running on. (the elf exepreferences file needs to be in every dir with a APPMAKE file.) And, getting close to finished, copy and paste the elfexecuter.sh to your programs's main dir if it is not already there. Then, in the same dir as the elfexecuter.sh file, add a appexecute file and add a list of the APP files. Now, wanna make an app? To execute the APPMAKE file, copy and paste appmake.py to the same dir as the programs if it is not already there. Execute it and your app is compiled. NOTICE: appexecute conatins names of .app files! Add the extensions! So, I obeyed with my manual and tested the first few steps and got this to repeat and write a ENDLESS amount of elf.elf to my app file! Can someone please help! </code></pre> <p>My new edit but it still does not work:</p> <pre><code>checkpoint = 0 i = 5 while i == 5: file1 = open('APPMAKE', 'r') Lines = file1.readlines() count = 0 ccount = 0 modeset = 0 # Strips the newline character for line in Lines: count += 1 ccount += 1 modeset += 1 if modeset &gt; 2: modeset == 1 if ccount &gt; checkpoint: checkpoint += 1 if modeset == 1: elfexecutable = line if modeset == 2: appname = line checkpoint = count + 1 break #writing data file1.close() file2 = open(appname + &quot;.app&quot;, &quot;a&quot;) # append mode file2.write(elfexecutable + &quot;\n&quot;) file2.close() </code></pre> <p>SOO, above is my newest edit but it <em>still will not work</em>! Any help is appreciated. I listened to all the suggestions with the new edit.</p>
3
1,441