title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Is there a way to parse a vector path geometry in UWP in code behind? | <p>When rendering vector graphics across different platforms, SVG and the SVG path format works really great. But at the moment its my challenge to realize this on the Universal Windows Platform. I've a given path (taken from SVG file) for example:</p>
<pre><code>M 198.09375 723.80859 C 177.18295 774.80866 156.88493 827.84014 140.58594 884.89844 L 140.72461 885.21875 L 142.49609 885.21875 C 161.1353 855.01082 143.6824 808.69757 193.58008 822.50977 C 220.7388 819.58475 192.23555 868.86205 206.17383 873.92578 C 203.13499 858.15989 212.17478 843.34361 213.20312 827.64648 C 216.4534 822.98862 226.9422 827.32963 232.86719 826.05078 C 239.35348 827.82466 259.48464 823.52777 253.90234 835.38867 C 252.16143 848.23286 247.39181 868.36181 258.57812 876.86133 C 275.17557 871.67116 293.30624 867.51489 306.24805 855.00195 C 309.22224 855.27087 320.1309 878.89646 334.30078 869.88281 C 342.81953 864.33463 353.03187 845.67608 358.37891 844.69922 C 358.70487 862.9873 381.18689 865.55311 395.26562 864.39258 C 403.5087 857.10727 407.91814 844.31119 413.10742 836.13867 C 413.72804 849.59522 421.61104 870.22176 438.42969 865.75586 C 449.52198 855.46609 450.22121 835.34205 450.98242 820.66016 C 440.08469 801.05876 470.99505 805.89669 482.05469 800.25 C 476.90476 794.47714 457.46328 802.62763 447.61328 805.58594 C 444.73527 800.59751 438.61005 793.84755 431.14453 800.40625 C 416.99321 808.72215 417.23603 829.81536 405.94141 841.74219 C 400.48764 848.08657 398.31259 865.19549 387.45703 861.5625 C 367.90276 864.11872 352.66459 843.12021 367.92773 827.74219 C 382.01652 798.42739 389.36227 773.69059 391.92773 757.58398 C 383.28497 784.25969 367.28961 818.5148 363.43164 822.48633 C 364.07428 814.47709 365.77944 799.37383 369.08398 783.79688 C 366.4449 793.18051 363.69922 804.07698 360.89648 816.71875 C 361.48939 835.64228 349.1191 850.24112 336.55859 862.86523 C 322.97859 878.53876 301.18236 851.31729 318.63086 839.64844 C 336.61687 805.09083 357.61323 769.08136 367.24609 728.10938 C 333.91868 727.40516 318.03705 810.21063 310.98828 840.47461 C 305.31469 859.28359 283.07607 865.19391 266.34961 870.80273 C 247.72901 876.83871 255.8139 843.70138 257.98438 832.47461 C 266.45336 827.2867 286.39364 829.07792 287.33594 811.02148 C 291.66934 788.31866 263.56198 808.14794 260.3457 819.18164 C 251.10098 831.98222 228.75757 819.36332 214.10156 822.01172 C 221.58584 792.07737 236.75917 758.58129 242.01172 726.59766 C 228.826 757.22131 219.89381 789.50311 210.12695 821.36328 C 195.25141 821.35043 181.74363 813.75195 166.88086 814.64844 C 176.85082 787.46046 194.56222 754.36904 198.09375 723.80859 z M 369.08398 783.79688 C 384.88883 727.60052 396.70513 727.59038 391.92773 757.58398 C 395.19032 747.51409 397.4116 738.51802 397.52734 732.64844 C 382.96385 734.97676 374.14438 759.94316 369.08398 783.79688 z M 352.36328 749.70117 C 354.77494 749.90766 347.99282 769.96334 320.71484 828.82227 C 319.68801 830.81418 318.67223 832.81204 317.5625 834.75977 C 306.90155 826.44708 347.59605 749.29301 352.36328 749.70117 z M 437.77539 799.73438 C 438.30605 799.60547 439.62352 800.55657 442.17773 803.56641 C 441.681 810.22158 436.18342 800.12108 437.77539 799.73438 z M 281.73633 803.74805 C 288.13496 803.44121 281.42291 821.46784 274.14062 824.54883 C 249.75318 832.98346 268.85036 814.16512 275.05859 807.29688 C 278.08583 804.86441 280.25972 803.81885 281.73633 803.74805 z M 436.71484 807.25781 C 439.20814 807.30595 441.96247 808.89375 445.0332 812.71484 C 451.81999 828.77301 444.47494 846.59531 438.73438 861.81836 C 424.83443 868.53922 415.18535 844.58764 417.39258 834.13086 C 422.22834 826.55898 427.81022 807.08588 436.71484 807.25781 z M 424.49805 813.01172 C 424.74071 812.91442 424.78138 813.46109 424.44141 815.08984 C 418.59702 825.96246 423.44649 813.43336 424.49805 813.01172 z
</code></pre>
<p>(This example should just be the word 'Hello', handwritten with some errors and holes, which represents a good average of my requirements.)</p>
<p>The goal is to parse this path in code behind into a <code>Windows.UI.Xaml.Media.Geometry</code>, <em>not</em> from XAML, because I need to work with the resulting <code>Windows.UI.Xaml.Shapes.Path</code> UI element. Since I've already solved this problem on other platforms, I've got an easy solution for WPF, which should be close to UWP, because it is windows. So for WPF I simply use the following Code to create a <code>Path</code> and parse that geometry:</p>
<pre><code>new System.Windows.Shapes.Path
{
Data = System.Windows.Media.Geometry.Parse(myVectorDataStringFromAbove),
Fill = myColorBrush
};
</code></pre>
<p>Since Microsoft unified the APIs, my first thought was doing it the same way in UWP:</p>
<pre><code>new Windows.UI.Xaml.Shapes.Path
{
Data = Windows.UI.Xaml.Media.Geometry.Parse(myVectorDataStringFromAbove),
Fill = myColorBrush
};
</code></pre>
<p>The only problem is, that there is no such <code>Parse</code> method at <code>Windows.UI.Xaml.Media.Geometry</code> like in WPF. I cannot even find one at specialized classes such as <code>Windows.UI.Xaml.Media.PathGeometry</code>. But as far as I know, it is possible, to parse such path definitions from XAML (?). So my question is: <strong>how can I do this programmatically?</strong></p>
<p><em>EDIT:</em> I know that this solution kind of works for UWP as well:
<a href="https://stackoverflow.com/questions/22989172/convert-path-to-geometric-shape">Convert path to geometric shape</a>
But isn't there be a better way?</p> | 1 |
How to use factories with Ionic/Angular JS with phonegap? | <p>I'm trying use global variables in my ionic/angular + phonegap app project by using factory service.</p>
<p>However, adding even a simple factory service like the one below messes up the app somehow & all screens of the app become pure white.</p>
<pre><code>.factory('serviceName', function() {
return {}
})
</code></pre>
<p>I've 2 js files named <code>app.js</code> & <code>controller.js</code></p>
<p>app.js looks like this with much more states:</p>
<pre><code>// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers'])
//TRIED ADDING FACTORY HERE
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
});
$urlRouterProvider.otherwise('/app/playlists');
});
</code></pre>
<p>My <code>controller.js</code> somewhat looks like this with much more variables & functions:</p>
<pre><code>angular.module('starter.controllers', [])
//ALSO TRIED ADDING FACTORY HERE
.controller('AppCtrl', function($scope, $ionicModal, $timeout,$http) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
// Form data for the login modal
$scope.loginData = {};
})
.controller('PlaylistsCtrl', function($scope) {
$scope.playlists = [
{ title: 'Reggae', id: 1 },
{ title: 'Chill', id: 2 },
{ title: 'Dubstep', id: 3 },
{ title: 'Indie', id: 4 },
{ title: 'Rap', id: 5 },
{ title: 'Cowbell', id: 6 }
];
})
.controller('PlaylistCtrl', function($scope, $stateParams) {
})
</code></pre>
<p>I referred this <a href="http://mcgivery.com/ionic-using-factories-and-web-services-for-dynamic-data/" rel="nofollow">http://mcgivery.com/ionic-using-factories-and-web-services-for-dynamic-data/</a> to start using factories.</p>
<p>I know can use $rootScope but it has all the <a href="http://c2.com/cgi/wiki?GlobalVariablesAreBad" rel="nofollow">problems of global variables</a>, so please help me use factories. Also, if someone can give me debugging tips with phonegap. I use the phonegap development app on android and keep an eye on the console while working with it.</p> | 1 |
Swift iOS NSDictionary setValue crash - but why? | <p>I have this code (porting from another language, hence a bit different naming conventions, but please bear with this for now)</p>
<pre><code>var FDefaultsList: NSDictionary = [String:String]();
let TmpKey: String = TmpKeyValue[0];
let TmpValue: String = TmpKeyValue[1];
if (TmpKey != "") && (TmpValue != "") {
//let TmpAnyObjectValue: AnyObject? = TmpValue;
//FDefaultsList.setValue(TmpAnyObjectValue, forKey: TmpKey);
FDefaultsList.setValue(TmpValue, forKey: TmpKey);
}
</code></pre>
<p>However, no matter the which setValue variation I use, the call to setValue throws an error (not meaningful as far as I can tell) and exits app (Xcode editor is taken to <strong>class AppDelegate: UIResponder, UIApplicationDelegate</strong>)</p>
<p>I guess I am using NSDictionary wrong? I am trying to read in a text file where each line is key=value strings</p> | 1 |
Avoiding CORS restrictions on the Fetch API in Chrome | <p>I am using the Fetch API in my React+Redux app like this:</p>
<pre><code>fetch("http://news.at.zhihu.com/api/4/news/before/20160127").
</code></pre>
<p>The app is running in Chrome and I also set the <code>--disable-web-security</code> argument when I open Chrome. However, I still get the CORS issue:</p>
<blockquote>
<p>Fetch API cannot load <a href="http://news.at.zhihu.com/api/4/news/before/20160127" rel="nofollow">http://news.at.zhihu.com/api/4/news/before/20160127</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<a href="http://localhost:8080" rel="nofollow">http://localhost:8080</a>' is therefore not allowed access.</p>
</blockquote>
<p>If I use XMLHTTPRequest, it works well. It looks like that the <code>--disable-web-security</code> can not work well with Fetch API.</p>
<p>Does anyone know how to use Fetch API without worrying about CORS issue?
I can not modify response header such as 'Access-Control-Allow-Origin' since the services are not in my charge.</p> | 1 |
Cannot send emails to addresses with Scandinavian characters | <p>Using <code>SmtpClient</code>, <code>MailMessage</code> and <code>MailAddress</code> classes, I cannot send to email addresses such as å[email protected]. I get the error/exceptions as shown below:</p>
<blockquote>
<p>An invalid character was found in the mail header: 'å'.</p>
</blockquote>
<blockquote>
<p>--------------------------- Error sending email
--------------------------- System.Net.Mail.SmtpException: The client or server is only configured for E-mail addresses with ASCII
local-parts: å[email protected].</p>
<p>at System.Net.Mail.MailAddress.GetUser(Boolean allowUnicode)</p>
<p>at System.Net.Mail.MailAddress.GetAddress(Boolean allowUnicode)</p>
<p>at System.Net.Mail.MailAddress.Encode(Int32 charsConsumed, Boolean
allowUnicode)</p>
<p>at System.Net.Mail.MailAddressCollection.Encode(Int32
charsConsumed, Boolean allowUnicode)
at System.Net.Mail.Message.PrepareHeaders(Boolean sendEnvelope,
Boolean allowUnicode)
at System.Net.Mail.Message.Send(BaseWriter writer, Boolean
sendEnvelope, Boolean allowUnicode)
at System.Net.Mail.SmtpClient.Send(MailMessage message)</p>
</blockquote>
<p>These characters in my subject/body are fine, but not in email addresses.</p>
<p>I've tried setting <code>SmtpClient.DeliveryMethod = SmtpDeliveryFormat.International</code>, or <code>MailMessage.HeadersEncoding = Encoding.Unicode</code> (or <code>UTF8</code>) and it doesn't seem to change anything. These are real email addresses of people we need to communicate with so it's a bit of a problem.</p>
<p>I have been digging through the .Net source code but not really gotten anywhere. I tracked down a <code>ServerSupportsEai</code> property, and Google tells me EAI stands for Email Address Internationalisation (<a href="https://www.rfc-editor.org/rfc/rfc5336" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc5336</a>) but it's fairly unclear if this is a limitation in my code, or if the specific server I'm talking to just doesn't support this... since I'm using a test server to avoid sending emails to unsuspecting Swedish people!</p>
<p>Can someone help me clear this up - does .Net support this, if so what if anything should my client code do to enable it?</p> | 1 |
Compiling Python 3.5 code with Cython and MinGW on Windows 7 (64bit) | <p>I am trying to setup a workflow for generating .pyd and .exe files from Python 3.5.1 code with Cython and MinGW on Windows 7 64bit.</p>
<p>I have a simple example.py file:</p>
<pre><code>def hello(x):
print("Hello",x)
if __name__=='__main__':
hello("World!")
</code></pre>
<p>From other threads on SO, I got the Cython command below, which generates an .c file w/o warnings.</p>
<pre><code>cython --embed -o example.c example.py
</code></pre>
<p>When I invoke gcc, I get the following warning and don't quite know if these are critical.</p>
<pre><code>gcc -c -IC:\Python35\include -o example.o example.c
In file included from C:\Python35\include/Python.h:65:0,
from example.c:4:
C:\Python35\include/pytime.h:113:5: warning: 'struct timeval' declared inside pa
rameter list [enabled by default]
_PyTime_round_t round);
^
C:\Python35\include/pytime.h:113:5: warning: its scope is only this definition o
r declaration, which is probably not what you want [enabled by default]
C:\Python35\include/pytime.h:118:5: warning: 'struct timeval' declared inside pa
rameter list [enabled by default]
_PyTime_round_t round);
</code></pre>
<p>When I use gcc to generate the .pyd file, I get a bunch of undefined reference messages and ld exits with an error status.</p>
<pre><code>gcc -shared -LC:\Python35\libs -o example.pyd example.o -lpython35
example.o:example.c:(.text+0x46): undefined reference to `_imp__PyObject_GetAttr
'
example.o:example.c:(.text+0xad): undefined reference to `_imp__PyTuple_New'
example.o:example.c:(.text+0x1be): undefined reference to `_imp___Py_NoneStruct'
example.o:example.c:(.text+0x1c6): undefined reference to `_imp___Py_NoneStruct'
example.o:example.c:(.text+0x1d0): undefined reference to `_imp___Py_NoneStruct'
example.o:example.c:(.text+0x2e2): undefined reference to `_imp__PyTuple_Pack'
example.o:example.c:(.text+0x3bc): undefined reference to `_imp__PyCode_New'
example.o:example.c:(.text+0x409): undefined reference to `_imp__PyTuple_Pack'
example.o:example.c:(.text+0x4f3): undefined reference to `_imp__PyTuple_New'
example.o:example.c:(.text+0x53a): undefined reference to `_imp__PyBytes_FromStr
ingAndSize'
example.o:example.c:(.text+0x5a5): undefined reference to `_imp__PyModule_Create
2'
example.o:example.c:(.text+0x5e5): undefined reference to `_imp__PyModule_GetDic
t'
example.o:example.c:(.text+0x630): undefined reference to `_imp__PyImport_AddMod
ule'
example.o:example.c:(.text+0x682): undefined reference to `_imp__PyObject_SetAtt
rString'
example.o:example.c:(.text+0x6ef): undefined reference to `_imp__PyObject_SetAtt
rString'
example.o:example.c:(.text+0x715): undefined reference to `_imp__PyImport_GetMod
uleDict'
example.o:example.c:(.text+0x756): undefined reference to `_imp__PyDict_GetItemS
tring'
example.o:example.c:(.text+0x778): undefined reference to `_imp__PyDict_SetItemS
tring'
example.o:example.c:(.text+0x87e): undefined reference to `_imp__PyDict_SetItem'
example.o:example.c:(.text+0xa7f): undefined reference to `_imp__PyDict_New'
example.o:example.c:(.text+0xac8): undefined reference to `_imp__PyDict_SetItem'
example.o:example.c:(.text+0xc04): undefined reference to `_imp__PyErr_Occurred'
example.o:example.c:(.text+0xc0f): undefined reference to `_imp__PyExc_ImportErr
or'
example.o:example.c:(.text+0xc21): undefined reference to `_imp__PyErr_SetString
'
example.o:example.c:(.text+0xc5f): undefined reference to `_imp__PyExc_NameError
'
example.o:example.c:(.text+0xc78): undefined reference to `_imp__PyErr_Format'
example.o:example.c:(.text+0xcb8): undefined reference to `_imp__PyObject_Call'
example.o:example.c:(.text+0xcc4): undefined reference to `_imp__PyThreadState_G
et'
example.o:example.c:(.text+0xcd7): undefined reference to `_imp___Py_CheckRecurs
ionLimit'
example.o:example.c:(.text+0xcf1): undefined reference to `_imp___Py_CheckRecurs
iveCall'
example.o:example.c:(.text+0xd2a): undefined reference to `_imp__PyThreadState_G
et'
example.o:example.c:(.text+0xd3d): undefined reference to `_imp___Py_CheckRecurs
ionLimit'
example.o:example.c:(.text+0xd4b): undefined reference to `_imp___Py_CheckRecurs
ionLimit'
example.o:example.c:(.text+0xd57): undefined reference to `_imp___Py_CheckRecurs
ionLimit'
example.o:example.c:(.text+0xd6d): undefined reference to `_imp__PyThreadState_G
et'
example.o:example.c:(.text+0xd86): undefined reference to `_imp__PyErr_Occurred'
example.o:example.c:(.text+0xd99): undefined reference to `_imp__PyExc_SystemErr
or'
example.o:example.c:(.text+0xdab): undefined reference to `_imp__PyErr_SetString
'
example.o:example.c:(.text+0xdcb): undefined reference to `_imp__PyImport_AddMod
ule'
example.o:example.c:(.text+0xe02): undefined reference to `_imp__PyObject_GetAtt
rString'
example.o:example.c:(.text+0xe25): undefined reference to `_imp__PyExc_TypeError
'
example.o:example.c:(.text+0xe3b): undefined reference to `_imp__PyErr_Format'
example.o:example.c:(.text+0xe61): undefined reference to `_imp__PyExc_TypeError
'
example.o:example.c:(.text+0xe77): undefined reference to `_imp__PyErr_Format'
example.o:example.c:(.text+0xe83): undefined reference to `_imp__PyExc_Attribute
Error'
example.o:example.c:(.text+0xe8d): undefined reference to `_imp__PyErr_Exception
Matches'
example.o:example.c:(.text+0xe9d): undefined reference to `_imp__PyErr_Clear'
example.o:example.c:(.text+0xeaa): undefined reference to `_imp__PyType_Ready'
example.o:example.c:(.text+0xece): undefined reference to `_imp__PyObject_SetAtt
rString'
example.o:example.c:(.text+0xf95): undefined reference to `_imp__PyUnicode_FromS
tring'
example.o:example.c:(.text+0xfbb): undefined reference to `_imp___Py_NoneStruct'
example.o:example.c:(.text+0xfc5): undefined reference to `_imp___Py_NoneStruct'
example.o:example.c:(.text+0xfcc): undefined reference to `_imp___Py_NoneStruct'
example.o:example.c:(.text+0xffd): undefined reference to `_imp___Py_NoneStruct'
example.o:example.c:(.text+0x107e): undefined reference to `_imp__PyUnicode_Inte
rnFromString'
example.o:example.c:(.text+0x10e7): undefined reference to `_imp__PyExc_TypeErro
r'
example.o:example.c:(.text+0x10f9): undefined reference to `_imp__PyErr_SetStrin
g'
example.o:example.c:(.text+0x11ac): undefined reference to `_imp__PyExc_TypeErro
r'
example.o:example.c:(.text+0x11be): undefined reference to `_imp__PyErr_SetStrin
g'
example.o:example.c:(.text+0x1240): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x1272): undefined reference to `_imp__PyDict_New'
example.o:example.c:(.text+0x12c1): undefined reference to `_imp__PyExc_TypeErro
r'
example.o:example.c:(.text+0x12d3): undefined reference to `_imp__PyErr_SetStrin
g'
example.o:example.c:(.text+0x12fe): undefined reference to `_imp__PyExc_TypeErro
r'
example.o:example.c:(.text+0x1310): undefined reference to `_imp__PyErr_SetStrin
g'
example.o:example.c:(.text+0x1398): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x13a2): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x13a9): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x13c8): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x1485): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x148f): more undefined references to `_imp___Py_None
Struct' follow
example.o:example.c:(.text+0x14ab): undefined reference to `_imp__PyExc_TypeErro
r'
example.o:example.c:(.text+0x14bd): undefined reference to `_imp__PyErr_SetStrin
g'
example.o:example.c:(.text+0x1572): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x1598): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x15a2): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x15be): undefined reference to `_imp__PyExc_TypeErro
r'
example.o:example.c:(.text+0x15d0): undefined reference to `_imp__PyErr_SetStrin
g'
example.o:example.c:(.text+0x1685): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x16ab): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x16d0): undefined reference to `_imp__PyExc_TypeErro
r'
example.o:example.c:(.text+0x16e2): undefined reference to `_imp__PyErr_SetStrin
g'
example.o:example.c:(.text+0x1778): undefined reference to `_imp__PyDict_New'
example.o:example.c:(.text+0x17c3): undefined reference to `_imp__PyUnicode_From
String'
example.o:example.c:(.text+0x17d8): undefined reference to `_imp___PyObject_GC_N
ew'
example.o:example.c:(.text+0x1913): undefined reference to `_imp__PyObject_GC_Tr
ack'
example.o:example.c:(.text+0x1cef): undefined reference to `_imp__PyMem_Free'
example.o:example.c:(.text+0x1d13): undefined reference to `_imp__PyObject_GC_Un
Track'
example.o:example.c:(.text+0x1d2a): undefined reference to `_imp__PyObject_Clear
WeakRefs'
example.o:example.c:(.text+0x1d42): undefined reference to `_imp__PyObject_GC_De
l'
example.o:example.c:(.text+0x2030): undefined reference to `_imp__PyMethod_New'
example.o:example.c:(.text+0x203f): undefined reference to `_imp__PyInstanceMeth
od_New'
example.o:example.c:(.text+0x2048): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x206c): undefined reference to `_imp__PyMethod_New'
example.o:example.c:(.text+0x207b): undefined reference to `_imp__PyInstanceMeth
od_New'
example.o:example.c:(.text+0x20a2): undefined reference to `_imp__PyUnicode_From
Format'
example.o:example.c:(.text+0x20c5): undefined reference to `_imp__PyCFunction_Ca
ll'
example.o:example.c:(.text+0x20d4): undefined reference to `_imp__PyCFunction_Ca
ll'
example.o:example.c:(.text+0x211b): undefined reference to `_imp__PyDict_GetItem
'
example.o:example.c:(.text+0x216e): undefined reference to `_imp__PyUnicode_Type
'
example.o:example.c:(.text+0x2184): undefined reference to `_imp__PyUnicode_Type
'
example.o:example.c:(.text+0x21bb): undefined reference to `_imp___PyUnicode_Rea
dy'
example.o:example.c:(.text+0x21e3): undefined reference to `_imp___PyUnicode_Rea
dy'
example.o:example.c:(.text+0x260b): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x2625): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x2650): undefined reference to `_imp__PyObject_RichC
ompare'
example.o:example.c:(.text+0x286b): undefined reference to `_imp__PyMem_Malloc'
example.o:example.c:(.text+0x299f): undefined reference to `_imp__PyMem_Realloc'
example.o:example.c:(.text+0x2a79): undefined reference to `_imp__PyUnicode_From
String'
example.o:example.c:(.text+0x2ab2): undefined reference to `_imp__PyUnicode_From
Format'
example.o:example.c:(.text+0x2ac4): undefined reference to `_imp__PyUnicode_From
String'
example.o:example.c:(.text+0x2b60): undefined reference to `_imp__PyCode_New'
example.o:example.c:(.text+0x2cca): undefined reference to `_imp__PyThreadState_
Get'
example.o:example.c:(.text+0x2ce7): undefined reference to `_imp__PyFrame_New'
example.o:example.c:(.text+0x2d08): undefined reference to `_imp__PyTraceBack_He
re'
example.o:example.c:(.text+0x2da1): undefined reference to `_imp__Py_SetProgramN
ame'
example.o:example.c:(.text+0x2da8): undefined reference to `_imp__Py_Initialize'
example.o:example.c:(.text+0x2dc8): undefined reference to `_imp__PySys_SetArgv'
example.o:example.c:(.text+0x2de8): undefined reference to `_imp__PyErr_Occurred
'
example.o:example.c:(.text+0x2df3): undefined reference to `_imp__PyErr_Print'
example.o:example.c:(.text+0x2e3a): undefined reference to `_imp__Py_Finalize'
example.o:example.c:(.text+0x2e77): undefined reference to `_imp__PyOS_snprintf'
example.o:example.c:(.text+0x2e7e): undefined reference to `_imp__Py_GetVersion'
example.o:example.c:(.text+0x2e9f): undefined reference to `_imp__PyOS_snprintf'
example.o:example.c:(.text+0x2eed): undefined reference to `_imp__PyOS_snprintf'
example.o:example.c:(.text+0x2f0d): undefined reference to `_imp__PyErr_WarnEx'
example.o:example.c:(.text+0x2f5a): undefined reference to `_imp__PyUnicode_Inte
rnFromString'
example.o:example.c:(.text+0x2f9f): undefined reference to `_imp__PyUnicode_Deco
de'
example.o:example.c:(.text+0x2fc5): undefined reference to `_imp__PyUnicode_From
StringAndSize'
example.o:example.c:(.text+0x2feb): undefined reference to `_imp__PyBytes_FromSt
ringAndSize'
example.o:example.c:(.text+0x3028): undefined reference to `_imp___Py_TrueStruct
'
example.o:example.c:(.text+0x3039): undefined reference to `_imp___Py_FalseStruc
t'
example.o:example.c:(.text+0x304c): undefined reference to `_imp___Py_NoneStruct
'
example.o:example.c:(.text+0x306b): undefined reference to `_imp__PyObject_IsTru
e'
collect2.exe: error: ld returned 1 exit status
</code></pre>
<p>What am I doing wrong?</p>
<p>What do I have to change im my workflow to generate a standalone .exe file?</p> | 1 |
python integer between two values | <p>I found a thread on this but am not having any luck getting it working.</p>
<pre><code>min = 9
max = 10
a = ['8','9','10','11']
for x in a:
if max >= x > min:
print 'one'
else:
d = (max >= x > min)
print d, x
if (x > min >= max):
#if (min < x >= max):
print x
else:
print x, ' is equal to or greater than', max
</code></pre>
<p>Outputs:</p>
<pre><code>False 8
8 is equal to or greater than 10
False 9
9 is equal to or greater than 10
False 10
10 is equal to or greater than 10
False 11
11 is equal to or greater than 10
</code></pre>
<p>this thread <a href="https://stackoverflow.com/questions/13628791/how-do-i-check-whether-an-int-is-between-the-two-numbers">working code?</a> indicates syntax needs to be:</p>
<pre><code>if 10000 <= number <= 30000:
pass
</code></pre>
<p>I've tried every combination of signs I can think of, and the returns are always True or False for all, which is wrong.</p>
<p>I've also tried this (much longer) code:</p>
<pre><code>min = 9
max = 10
a = ['8','9','10','11']
for x in a:
print 'X is:', x
if int(x) == max:
print 'max found:', x
elif int(x) < max:
if int(x) > min:
print 'min:', x
elif int(x) < min:
print 'under range', x
else:
print 'out of range', x
</code></pre>
<p>with output also unexpected, since I expect to catch all cases:</p>
<pre><code>X is: 8
X is: 9
X is: 10
max found: 10
X is: 11
out of range 11
</code></pre>
<p>Ugh! How can I check all items 'properly' and return under, at, over my min, max?</p> | 1 |
Java streams collect list of objects to buckets | <p>I have a problem of collecting some list values to buckets. For example, let's assume I have a list of Strings:</p>
<pre><code>List<String> strs = Arrays.asList("ABC", "abc", "bca", "BCa", "AbC");
</code></pre>
<p>And I want to put the strings into set (or list) of sets, that contain only case-different strings, i.e. for example above it would be collection of two sets: <code>[["ABC", "abc", "AbC"], ["bca", "BCa"]]</code></p>
<p>So help me please to write collector for this problem.</p>
<pre><code>List<Set<String>> result = strs.stream()
.collect(/* some collectors magic here */)
</code></pre> | 1 |
apply a function to each cell in a column of a dataframe in R | <p><strong>EDIT</strong> Thanks to @user5249203 for pointing out that geocoding is best done with ggmaps' geocode call. Watch out for NA's though. </p>
<p>I am struggling with the <code>apply</code> family in R. </p>
<p>I am using a <a href="https://stackoverflow.com/questions/3257441/geocoding-in-r-with-google-maps">function</a> which takes in a string and returns longitude and latitude</p>
<p><code>> gGeoCode("Philadelphia, PA")
[1] 39.95258 -75.16522</code></p>
<p>I have a simple dataframe which has the names of all 52 states: </p>
<pre><code>dput(state_lat_long)
structure(
list(State = structure(
c(
32L, 28L, 43L, 5L, 23L, 34L,
30L, 13L, 14L, 38L, 22L, 25L, 15L, 20L, 24L, 40L, 46L, 21L, 9L,
18L, 48L, 10L, 7L, 4L, 3L, 31L, 35L, 37L, 49L, 44L, 12L, 6L,
17L, 36L, 11L, 39L, 42L, 8L, 47L, 33L, 16L, 1L, 29L, 27L, 26L,
19L, 41L, 50L, 2L, 45L
), .Label = c(
"alabama", "alaska", "arizona",
"arkansas", "california", "colorado", "connecticut", "delaware",
"florida", "georgia", "hawaii", "idaho", "illinois", "indiana",
"iowa", "kansas", "kentucky", "louisiana", "maine", "maryland",
"massachusetts", "michigan", "minnesota", "mississippi", "missouri",
"montana", "nebraska", "nevada", "new hampshire", "new jersey",
"new mexico", "new york", "north carolina", "north dakota", "ohio",
"oklahoma", "oregon", "pennsylvania", "rhode island", "south carolina",
"south dakota", "tennessee", "texas", "utah", "vermont", "virginia",
"washington", "west virginia", "wisconsin", "wyoming"
), class = "factor"
)), .Names = "State", row.names = c(NA,-50L), class = "data.frame"
)
</code></pre>
<p>To practice my <code>apply</code> skills, I simply want to apply <code>gGeoCode</code> to each cell in the only column of the <code>state_lat_long</code> dataframe. </p>
<p>Couldn't be much simpler. </p>
<p>Then what is the problem with this? </p>
<pre><code>> View(apply(state_lat_long, function(x) gGeoCode(x)))
</code></pre>
<p>When I run this, I get: </p>
<pre><code>Error in View : argument "FUN" is missing, with no default
</code></pre>
<p>which I don't understand, because <code>FUN</code> is not missing. </p>
<p>So, let's try <code>sapply</code>. It's supposed to be simple, right? </p>
<p>But what is wrong with this?</p>
<pre><code>View(sapply(state_lat_long$State, function(x) gGeoCode(x)))
</code></pre>
<p>When I run this, I get 2 rows with 50 columns, packed with <code>NA</code>s. I can't make sense of it. </p>
<p>Next, I tried </p>
<pre><code>View(apply(state_lat_long, 2, function(x) gGeoCode(x)))
</code></pre>
<p>and I got </p>
<pre><code> State
40.71278
-74.00594
</code></pre>
<p>Again, this makes no sense! </p>
<p>What am I doing wrong? Thanks. </p> | 1 |
Overlay two plots (ggplot) | <p>How I can overlay the scatter plot of AverageTime2 vs. AverageCost and AverageTime1 vs. AverageCost. (in ggplot)?</p>
<pre><code>Type<-c("a","b","c","d","e","f","g","h","i","j","k")
AverageTime<-c(12,14,66,123,14,33,44,55,55,6,66)
AverageTime2<-c(14,15,66,126,14,100,144,55,55,16,90)
AverageCost<-c(100,10000,400,20000,500000,5000,700,800,400000,500,120000)
AverageCost2<-c(10000,10000,4000,20000,5000,50000,7000,8000,40000,50000,120000)
df<-data.frame(Type,AverageTime,AverageTime2,AverageCost,AverageCost2)
</code></pre> | 1 |
Extreme values with ggplot histogram | <p>I am trying to plot a histogram using <code>ggplot()</code> however I am unable to deal with extreme values. I would like them to be comined within one bin (called "500 and more" for example). </p>
<p>I have tried the <code>scale_x_continuous(breaks = seq(0,500, by = 50))</code> function but it just removes labels from the x-axis (attached below) Any ideas of how to deal with this?<a href="https://i.stack.imgur.com/sHqjl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sHqjl.png" alt="enter image description here"></a></p> | 1 |
Cannot open source file "opencv2/highgui/highgui.hpp" | <p>I am trying to run this code that should open the webcam and take frames.
However, I am getting this error. <code>Cannot open source file "opencv2/highgui/highgui.hpp"</code></p>
<p><a href="https://i.stack.imgur.com/nqnzZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nqnzZ.png" alt="enter image description here"></a></p>
<p>I download opencv and VS15, I followed online guides on how to install opencv 3.1 on VS15 using CMAKE. </p>
<p>However, It gives the error I mentioned above along side some more errors</p>
<pre><code>Cannot open source file "opencv2/highgui/highgui.hpp"
Cannot open source file "opencv2/imgproc/imgproc.hpp"
</code></pre>
<p>I am really new to this and it got me frustrated. Any help will be apreciated. Thanks in advance!</p> | 1 |
How to read png meta data from JavaScript? | <p>My custom server embeds meta data about an image in the PNG meta data fields. The image is loaded via a regular img tag. I'd like to access the meta data from JavaScript - any way to achieve this?</p>
<p>If not, what are the alternatives for serving additional information for an image? The images are generated on the fly and are relatively expensive to produce, so I'd like to serve the meta data and the image data in a single round trip to the server.</p> | 1 |
Not-null property references a transient value - transient instance must be saved before current operation | <p>This is the log exception:</p>
<pre><code>GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/Libreria] threw exception [Request processing failed; nested exception is org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : com.angelo.springmvc.model.PrestitoLibro.prestito -> com.angelo.springmvc.model.Prestito] with root cause
org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : com.angelo.springmvc.model.PrestitoLibro.prestito -> com.angelo.springmvc.model.Prestito
at org.hibernate.action.internal.UnresolvedEntityInsertActions.checkNoUnresolvedActionsAfterOperation(UnresolvedEntityInsertActions.java:137)
at org.hibernate.engine.spi.ActionQueue.checkNoUnresolvedActionsAfterOperation(ActionQueue.java:318)
at org.hibernate.internal.SessionImpl.checkNoUnresolvedActionsAfterOperation(SessionImpl.java:658)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:813)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at com.angelo.springmvc.dao.AbstractDao.persist(AbstractDao.java:34)
at com.angelo.springmvc.dao.PrestitoLibroDaoImpl.savePrestitoLibro(PrestitoLibroDaoImpl.java:27)
at com.angelo.springmvc.service.PrestitoServiceImpl.salvaPrestito(PrestitoServiceImpl.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy45.salvaPrestito(Unknown Source)
at com.angelo.springmvc.controller.ShoppingCartController.ordinaShoppingCart(ShoppingCartController.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
</code></pre>
<p>The scenario is the following: I have two entity beans Prestito and PrestitoLibro, a ServicePrestito and a session bean ShoppingCard with a Controller: </p>
<pre><code>@Entity
@Table(name="PRESTITO")
@XmlRootElement
public class Prestito {
private Integer id;
private Cliente cliente;
private Date dataprestito;
private Set<PrestitoLibro> prestitolibros = new HashSet<PrestitoLibro>(0);
public Prestito() {
}
public Prestito(Cliente cliente, Date dataprestito) {
this.cliente = cliente;
this.dataprestito = dataprestito;
}
public Prestito(Cliente cliente, Date dataprestito, Set<PrestitoLibro> prestitolibros) {
this.cliente = cliente;
this.dataprestito = dataprestito;
this.prestitolibros = prestitolibros;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_cliente", nullable = false)
public Cliente getCliente() {
return this.cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
@Temporal(TemporalType.DATE)
@Column(name = "dataprestito", nullable = false, length = 10)
public Date getDataprestito() {
return this.dataprestito;
}
public void setDataprestito(Date dataprestito) {
this.dataprestito = dataprestito;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "prestito")
public Set<PrestitoLibro> getPrestitolibros() {
return this.prestitolibros;
}
public void setPrestitolibros(Set<PrestitoLibro> prestitolibros) {
this.prestitolibros = prestitolibros;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Prestito other = (Prestito) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Prestito [id=" + id + ", cliente=" + cliente + ", dataprestito=" + dataprestito
+ ", prestitolibros=" + prestitolibros + "]";
}
}
@Entity
@Table(name="PRESTITOLIBRO")
@XmlRootElement
public class PrestitoLibro {
private Integer id;
private Libro libro;
private Prestito prestito;
private Integer qta;
private Double subtotal;
public PrestitoLibro() {
}
public PrestitoLibro(Libro libro, Prestito prestito) {
this.libro = libro;
this.prestito = prestito;
}
public PrestitoLibro(Libro libro, Prestito prestito, Integer qta, Double subtotal) {
this.libro = libro;
this.prestito = prestito;
this.qta = qta;
this.subtotal = subtotal;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)//, cascade=CascadeType.ALL
@JoinColumn(name = "id_libro", nullable = false)
public Libro getLibro() {
return this.libro;
}
public void setLibro(Libro libro) {
this.libro = libro;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_prestito", nullable = false)
public Prestito getPrestito() {
return this.prestito;
}
public void setPrestito(Prestito prestito) {
this.prestito = prestito;
}
@Column(name = "qta")
public Integer getQta() {
return this.qta;
}
public void setQta(Integer qta) {
this.qta = qta;
}
@Column(name = "subtotal", precision = 22, scale = 0)
public Double getSubtotal() {
return this.subtotal;
}
public void setSubtotal(Double subtotal) {
this.subtotal = subtotal;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrestitoLibro other = (PrestitoLibro) obj;
if (id != other.id)
return false;
return true;
}
@Override
public String toString() {
return "PrestitoLibro [id=" + id + ", libro=" + libro + ", prestito=" + prestito + ", qta=" + qta
+ ", subtotal=" + subtotal + "]";
}
}
@Component
@Scope(value=WebApplicationContext.SCOPE_SESSION,
proxyMode=ScopedProxyMode.TARGET_CLASS)
public class ShoppingCart {
private Map<Libro, Integer> contents = new HashMap<>();
public Map<Libro, Integer> getContents() {
return contents;
}
public void setContents(Map<Libro, Integer> contents) {
this.contents = contents;
}
public void addLibro(Libro libro, int count){
if(contents.containsKey(libro)){
contents.put(libro, contents.get(libro)+count);
}else{
contents.put(libro,count);
}
}
public void removeLibro(Libro libro){
contents.remove(libro);
}
public void clearCart(){
contents.clear();
}
@Override
public String toString() {
return "ShoppingCart [contents=" + contents + "]";
}
public double getTotalCost(){
double totalcost = 0;
int i = 0;
for(Libro libro: contents.keySet()){
i = contents.get(libro);
totalcost += i * libro.getPrezzo();
}
return totalcost;
}
}
</code></pre>
<p>The problem occurs when I call <code>salvaprestito()</code> here:</p>
<pre><code>@Service("prestitoService")
@Transactional
public class PrestitoServiceImpl implements PrestitoService {
@Autowired
private PrestitoDao dao;
@Autowired
private PrestitoLibroDao daoprestitolibro;
public Prestito findById(int id) {
return dao.findById(id);
}
public void savePrestito(Prestito prestito) {
dao.savePrestito(prestito);
}
public void updatePrestito(Prestito prestito) {
Prestito entity = dao.findById(prestito.getId());
if(entity!=null){
entity.setCliente(prestito.getCliente());
entity.setDataprestito(prestito.getDataprestito());
entity.setPrestitolibros(prestito.getPrestitolibros());
}
}
public void deletePrestitoBySss(String sss) {
dao.deletePrestitoBySss(sss);
}
public List<Prestito> findAllPrestiti() {
return dao.findAllPrestiti();
}
public Prestito findPrestitoBySss(String sss) {
return dao.findPrestitoBySss(sss);
}
public boolean isPrestitoSssUnique(Integer id, String sss) {
Prestito prestito = findPrestitoBySss(sss);
return ( prestito == null || ((id != null) && (prestito.getId() == id)));
}
public void salvaPrestito(Map<Libro, Integer> shoppingcartContents, Cliente cliente){
Prestito prestito = new Prestito();
prestito = dao.findById(prestito.getId());
prestito.setCliente(cliente);
dao.savePrestito(prestito);
for(Entry<Libro, Integer> entry: shoppingcartContents.entrySet()){
PrestitoLibro prestLibro = new PrestitoLibro(entry.getKey(),prestito);
prestLibro.setQta(entry.getValue());
prestLibro.setPrestito(prestito); prestLibro.setSubtotal(entry.getKey().getPrezzo()*entry.getValue());
daoprestitolibro.savePrestitoLibro(prestLibro);
prestito.getPrestitolibros().add(prestLibro);
}
}
</code></pre>
<p>And this is the Shopping Cart Controller:</p>
<pre><code>@Controller
public class ShoppingCartController {
private static final Logger logger = LoggerFactory.getLogger(ShoppingCartController.class);
@Autowired
private LibroService libroservice;
@Autowired
private PrestitoService prestitoservice;
@Autowired
private ShoppingCart shoppingcart;
@RequestMapping(value = { "/shoppingcart/add/{libroId}" }, method = RequestMethod.GET)
public String addtoShoppingCart(@PathVariable("libroId") int libroId, @RequestHeader("referer") String rForm) {
Libro libro = (Libro) libroservice.findById(libroId);
shoppingcart.addLibro(libro, 1);
logger.debug("Aggiunto Libro a carrello" + libro);
return "redirect:" + rForm;
}
@RequestMapping(value = { "/shoppingcart" }, method = RequestMethod.GET)
public String viewShoppingCart(Model model) {
model.addAttribute("shoppingcart", shoppingcart);
return "shoppingcart";
}
@RequestMapping(value = { "/shoppingcart/order" }, method = RequestMethod.POST)
public String ordinaShoppingCart(HttpSession session) {
if(shoppingcart.getContents().isEmpty()){
return "redirect:/shoppingcart";
}else{
Cliente cliente = (Cliente) session.getAttribute("cliente");
prestitoservice.salvaPrestito(shoppingcart.getContents(), cliente);
return "redirect:/shoppingcart";
}
}
</code></pre>
<p>These are the Daos:</p>
<pre><code>@Repository("prestitolibroDao")
public class PrestitoLibroDaoImpl extends AbstractDao<Integer, PrestitoLibro> implements PrestitoLibroDao{
public PrestitoLibro findById(int id) {
PrestitoLibro prestitolibro = getByKey(id);
if(prestitolibro!=null){
Hibernate.initialize(prestitolibro.getId());
}
return prestitolibro;
}
public void savePrestitoLibro(PrestitoLibro prestitolibro) {
persist(prestitolibro);
}
public void deletePrestitoLibroById(int id) {
Query query = getSession().createSQLQuery("delete from Prestitolibro where id = :id");
query.setString("id",(String) Integer.toString(id));
query.executeUpdate();
}
@SuppressWarnings("unchecked")
public List<PrestitoLibro> findAllPrestitiLibro() {
Criteria criteria = createEntityCriteria();
return (List<PrestitoLibro>) criteria.list();
}
@SuppressWarnings("unchecked")
public List<PrestitoLibro> findAllPrestitiLibroByPrestito(int prestitoId) {
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.eq("id_prestito", prestitoId));
return (List<PrestitoLibro>) criteria.list();
}
@SuppressWarnings("unchecked")
public List<PrestitoLibro> findAllPrestitiLibroByLibro(int libroId) {
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.eq("id_libro", libroId));
return (List<PrestitoLibro>) criteria.list();
}
@Repository("prestitoDao")
public class PrestitoDaoImpl extends AbstractDao<Integer, Prestito> implements PrestitoDao{
public Prestito findById(int id) {
Prestito prestito = getByKey(id);
if(prestito!=null){
Hibernate.initialize(prestito.getId());
}
return prestito;
}
public void savePrestito(Prestito prestito) {
persist(prestito);
// Save prestito significa salvare il prestito o/e anche PrestitoLibiri
}
public void deletePrestitoBySss(String sss) {
Query query = getSession().createSQLQuery("delete from Libro where snn = :snn");
query.setString("sss", sss);
query.executeUpdate();
}
@SuppressWarnings("unchecked")
public List<Prestito> findAllPrestiti() {
Criteria criteria = createEntityCriteria();
return (List<Prestito>) criteria.list();
}
public Prestito findPrestitoBySss(String sss) {
System.out.println("SSS : "+sss);
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.eq("sss", sss));
Prestito prestito = (Prestito)criteria.uniqueResult();
if(prestito!=null){
Hibernate.initialize(prestito.getId());
}
return prestito;
}
</code></pre> | 1 |
C++ write to csv, performance | <p>This is probably a simple question, but I have not been able to find specific information on this, or atleast information in a readable format. Most of the information I have found relates to reading data from a .csv.</p>
<p>I am have a function that have to save data to a .csv file. This is not an ideal format in a performance perspective, but let us assume that this cannot change. My data is stored in a <strong>r x c x s</strong> data structure and has to be outputed in the form <strong>r,c,s,value</strong> and saved to the .csv. At the moment i have:</p>
<pre><code>char delimiter = ',';
ofstream ofs(file, ofstream::out);
for (int r = 0; r < P.n_rows; r++)
{
for (int c = 0; c < P.n_cols; c++)
{
for (int s = 0; s < P.n_slices; s++)
{
ofs << r + 1 << delimiter << c + 1 << delimiter << s + 1 << delimiter << P(c, s, s) << endl;
count++;
}
}
}
ofs.close();
</code></pre>
<p>For a data structure of size 100 x 100 x 50 this take roughly 6 sec, which I fell is an necessary long time. I would much appreciate if you could provide some information on how to speed this up.</p> | 1 |
Using dependency injection over laravel facades | <p>I have read a number of sources that hint that laravel facade's ultimately exist for convenience and that these classes should instead be <a href="https://stackoverflow.com/a/33465977/817379">injected</a> to allow loose coupling. Even <a href="https://phpnews.io/feeditem/response-don-t-use-facades" rel="noreferrer">Taylor Otwell has a post</a> explaining how to do this. It seems I am not the only one to <a href="https://stackoverflow.com/questions/27080739/laravel-should-all-the-classes-be-injected-through-constructor">wonder this</a>.</p>
<pre><code>use Redirect;
class Example class
{
public function example()
{
return Redirect::route("route.name");
}
}
</code></pre>
<p>would become </p>
<pre><code>use Illuminate\Routing\Redirector as Redirect;
class Example class
{
protected $redirect;
public function __constructor(Redirect $redirect)
{
$this->redirect = $redirect
}
public function example()
{
return $this->redirect->route("route.name");
}
}
</code></pre>
<p>This is fine except that I am starting to find that some constructors and methods are beginning to take four+ parameters. </p>
<p>Since the Laravel IoC <em>seems</em> to only inject into class constructors and certain methods (controllers), even when I have fairly lean functions and classes, I am finding that constructors of the classes are becoming packed out with the needed classes that then get injected into the needed methods.</p>
<p>Now I am finding that if I continue down this approach that I will need my own IoC container, which feels like reinventing the wheel if I am using a framework like laravel?</p>
<p>For example I use services to control the business / view logic rather than controllers dealing with them - they simply route the views. So a controller will first take its corresponding <code>service</code>, then then the <code>parameter</code> in its url. One service function also needs to check the values from a form, so then I need <code>Request</code> and <code>Validator</code>. Just like that, I have four parameters.</p>
<pre><code>// MyServiceInterface is binded using the laravel container
use Interfaces\MyServiceInterface;
use Illuminate\Http\Request;
use Illuminate\Validation\Factory as Validator;
...
public function exampleController(MyServiceInterface $my_service, Request $request, Validator $validator, $user_id)
{
// Call some method in the service to do complex validation
$validation = $my_service->doValidation($request, $validator);
// Also return the view information
$viewinfo = $my_service->getViewInfo($user_id);
if ($validation === 'ok') {
return view("some_view", ['view_info'=>$viewinfo]);
} else {
return view("another_view", ['view_info'=>$viewinfo]);
}
}
</code></pre>
<p>This is a single example. In reality, many of my constructors already have multiple classes being injected (Models, Services, Parameters, Facades). I have started to 'offload' the constructor injection (when applicable) to method injection, and have the classes calling those methods use their constructors to inject dependencies instead.</p>
<p>I have been told that more than four parameters for a method or class constructor as a rule of thumb is bad practice / code smell. However I cannot see how you can really avoid this if you choose the path of injecting laravel facades.</p>
<p>Have I got this idea wrong? Are my classes / functions not lean enough? Am I missing the point of laravels container or do I really need to think of creating my own IoC container? <a href="https://stackoverflow.com/questions/15824673/laravel-dependency-injection-and-the-ioc-container">Some</a> others <a href="https://stackoverflow.com/a/25915119/817379">answers</a> seems to hint at the laravel container being able to eliminate my issue? </p>
<p>That said, there doesn't seem to be a definitive consensus on the issue...</p> | 1 |
Laravel 5.2 make:auth | <p>I've had a problem when trying to use the <code>PHP artisan make:auth</code> function to set up my login and reg pages with the new <code>Laravel 5.2</code>. Everything seems to generate and load fine, I get to the home page, but any of the links I click on throw the same error, which is:</p>
<pre><code>FatalThrowableError in Encrypter.php line 66:
Fatal error: Call to undefined function Illuminate\Encryption\openssl_encrypt()
</code></pre>
<p>I've tried re-installing and setting up new routes to the pages and looked through google to try and find an answer to no avail. Any ideas why this is happening?</p> | 1 |
How I can close all tabs in Google Chrome window using API | <p>I need close all tabs in Chrome window via my extension. What is the best practice now? How would you have done?</p> | 1 |
Cannot implicitly convert type 'string' to 'System.Windows.Forms.Label' | <p>The code that is causing the problem is</p>
<pre><code>txtResult.Text = Convert.ToString(step3);
</code></pre>
<p>and it produces the error</p>
<blockquote>
<p>Cannot implicitly convert type 'string' to
'System.Windows.Forms.Label' </p>
</blockquote>
<p>See this image:</p>
<p><a href="https://i.stack.imgur.com/FIgDH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FIgDH.png" alt="enter image description here"></a></p> | 1 |
Creating a text-based map for a text based RPG | <p>Currently, I am creating a text based RPG. I am wondering how I could go about creating a somewhat interactive map, defining specific tiles to hold certain world information like enemy AI and loot or places like towns and dungeons, how to create text based maps for those places, and how to track player movement throughout the world. </p>
<p>I want the world to be borderless, so that player's could hypothetically play the game forever. If I were to create a few classes defining a town, how could I pull a random town object to a certain tile in the world environment for the player to interact with? </p>
<p>How would I go about structuring my player classes, enemy and character AI classes, and room classes? </p>
<p>Lastly, how could I go about creating a text-based visual map for the player to use? </p>
<p>Thanks for any help</p> | 1 |
Ruby on Rails Active Record inner join not working | <p>I have 2 models: Engagement, user. Engagement basically refers to the items booked by the user. each engagement is for a specific user. user in engagement has a foreign key. I want to join engagement with user so that i can see the details of the user. </p>
<p>Here are my models</p>
<pre><code>class Engagement < ActiveRecord::Base
belongs_to :food_item
belongs_to :user
end
class User < ActiveRecord::Base
has_many :engagements
has_many :food_item, through: :engagements
end
</code></pre>
<p>I am running below query:</p>
<pre><code>Engagement.joins("INNER JOIN users ON users.id = engagements.user_id")
</code></pre>
<p>It is not joining both the tables.</p>
<p>Any help will be appreciated</p> | 1 |
Drag & drop files upload multiple with preview before upload - php, javascript | <pre><code><div class="dragdrop">
<input type="file" name="files[]" multiple="multiple" />
</div>
<div class="preview">
<src class="image-1" href="" alt="" />
<src class="image-2" href="" alt="" />
<src class="image-3" href="" alt="" />
???
</div>
</code></pre>
<p>I'm looking for a simple drag & drop, not to be too complicated.I do not know how you can preview images, after the addition.</p>
<p>Also, if you click on an image, it must be the top priority.</p>
<pre><code>$priority = $_POST['image-2'];
</code></pre>
<p>Thanks!</p>
<p><strong>P.S.:</strong>
I check this, but no multiple: <a href="http://jsfiddle.net/ELcf6/4/" rel="nofollow">JSFIDDLE</a></p> | 1 |
How to start with Edge webdriver with python 2.7 and Robot framework 2.9 | <p>I have downloaded and installed edge webdriver from Microsoft website. I see the Edge driver folder in the "<strong>C:\Python27\Lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\edge</strong>".</p>
<p>Whenever I try to execute the below Robot Test case:</p>
<pre><code>*** Settings ***
Documentation Test Edge Browser
*** Test Case ***
Test Edge browser
open browser http://www.google.in Edge
</code></pre>
<p>Though I have set the environment path for "Mircrosoftwebdriver.exe". I see the "<em>WebDriverException: Message: The EdgeDriver executable needs to be available in the path. Please download from <a href="http://go.microsoft.com/fwlink/?LinkId=619687" rel="noreferrer">http://go.microsoft.com/fwlink/?LinkId=619687</a></em>"</p>
<p>Please let me know if anyone has the same issue and resolved.</p> | 1 |
Changing the color of a paragraph in JQuery | <p>So I have a button within a paragraph. When the user pushes the button, I want it to change the background color of the specific paragraph it is in. here is the JQuery that I have so far:</p>
<pre><code>$('<button/>',
{
text: "Done",
click: function () {
$("p:first").addClass("first");
$(".first").css({ 'background-color': 'green' });
}
});
</code></pre>
<p>My idea is to place the paragraph into a specific class first, then give it a background color. However my button is not working and when I check the console, I do not get any errors. Anything else I can try?</p> | 1 |
Bad substitution error when using bash | <p>So I wanted to do a bash script but whenever I run it I get "bad substitution" error. I have already browsed stackoverflow and tried some solutions but none worked :/
Any ideas?</p>
<pre><code>#!/bin/bash
printf "Hello. This is an OTS setup script provided by Damon at Otland. Please standby as user input may be required."
read -r -p "Do you want to install the webpanel? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y| ) ]]; then
wget https://raw.githubusercontent.com/NicolasLoew/vps/master/panelsetup.sh
sh panelsetup.sh
fi
printf "If you installed webpanel please navigate to http://yourip:2004/ and follow install instructions."
printf "Once you have installed the webpanel login and go to Enduser-->Configuration-->Apache and delete everything in the config and replace it with https://raw.githubusercontent.com/NicolasLoew/vps/master/apacheconfig. This will be needed for Znote later."
read -r -p "Do you want to compile latest TFS? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y| ) ]]; then
wget https://raw.githubusercontent.com/NicolasLoew/vps/master/tfsauto.sh
sh tfsauto.sh
fi
printf "You have successfully compiled TFS! You can start it by going to cd forgottenserver and execute ./tfs. Dont forget to configure config.lua though. You can create database in webpanel-->enduser."
read -r -p "Do you want to install ZnoteAAC? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y| ) ]]; then
wget https://raw.githubusercontent.com/NicolasLoew/vps/master/znotesetup.sh
sh znotesetup.sh
fi
printf "You havee successfully setup ZnoteAAC. Navigate to http://yourip and follow the instructions."
</code></pre>
<p><strong>Edit from the comments</strong></p>
<p>The edit is invoked as</p>
<pre><code>sh otsetup.sh
</code></pre> | 1 |
Apache Spark: multiple outputs in one map task | <p><strong>TL;DR:</strong> I have a large file that I iterate over three times to get three different sets of counts out. Is there a way to get three maps out in one pass over the data?</p>
<p>Some more detail:</p>
<p>I'm trying to compute PMI between words and features that are listed in a large file. My pipeline looks something like this:</p>
<pre><code>val wordFeatureCounts = sc.textFile(inputFile).flatMap(line => {
val word = getWordFromLine(line)
val features = getFeaturesFromLine(line)
for (feature <- features) yield ((word, feature), 1)
})
</code></pre>
<p>And then I repeat this to get word counts and feature counts separately:</p>
<pre><code>val wordCounts = sc.textFile(inputFile).flatMap(line => {
val word = getWordFromLine(line)
val features = getFeaturesFromLine(line)
for (feature <- features) yield (word, 1)
})
val featureCounts = sc.textFile(inputFile).flatMap(line => {
val word = getWordFromLine(line)
val features = getFeaturesFromLine(line)
for (feature <- features) yield (feature, 1)
})
</code></pre>
<p>(I realize I could just iterate over <code>wordFeatureCounts</code> to get the <code>wordCounts</code> and <code>featureCounts</code>, but that doesn't answer my question, and looking at running times in practice I'm not sure it's actually faster to do it that way. Also note that there are some reduceByKey operations and other stuff that I do with this after the counts are computed that aren't shown, as they aren't relevant to the question.)</p>
<p>What I would really like to do is something like this:</p>
<pre><code>val (wordFeatureCounts, wordCounts, featureCounts) = sc.textFile(inputFile).flatMap(line => {
val word = getWordFromLine(line)
val features = getFeaturesFromLine(line)
val wfCounts = for (feature <- features) yield ((word, feature), 1)
val wCounts = for (feature <- features) yield (word, 1)
val fCounts = for (feature <- features) yield (feature, 1)
??.setOutput1(wfCounts)
??.setOutput2(wCounts)
??.setOutput3(fCounts)
})
</code></pre>
<p>Is there any way to do this with spark? In looking for how to do this, I've seen questions about multiple outputs when you're saving the results to disk (not helpful), and I've seen a bit about accumulators (which don't look like what I need), but that's it.</p>
<p>Also note that I can't just yield all of these results in one big list, because I need three separate maps out. If there's an efficient way to split a combined RDD after the fact, that could work, but the only way I can think of to do this would end up iterating over the data four times, instead of the three I currently do (once to create the combined map, then three times to filter it into the maps I actually want).</p> | 1 |
How do I resolve "no package called '.GlobalEnv'" error in R? | <p>I'm getting a confusing error while using RStudio. When I use the command line, in the middle of typing a command (never while executing a command), R throws the following error:</p>
<blockquote>
<p>Error in loadNamespace(name) : there is no package called ‘.GlobalEnv’</p>
</blockquote>
<p>I am using R version 3.2.3 and RStudio version 0.99.491; I have tried to re-install RStudio and to delete settings.</p> | 1 |
FBDEV(0): FBIOPUTCMAP: Invalid argument error in Xorg.0.log file | <p>My Qt application which plays video shows just a blank <code>VideoWidget</code> window.
When I remove my <code>Xorg.conf</code> file from <code>/etc/X11/</code> directory on my Debian Jessie 8.2 and restart system, video starts to play, but there is a lack of colors on whole display.</p>
<pre><code>- Kernel version is: 4.1.15-ti-rt-r40
- Platform: BeagleBone Black
</code></pre>
<p>I found this error reported as a bug on <a href="https://bugs.launchpad.net/ubuntu/+source/xserver-xorg-video-fbdev/+bug/573668" rel="nofollow">this link</a>, but it is very old thread. Is problem in graphic card drivers built for this BB under Debian Jessie 8.2?</p> | 1 |
bubble sorting an array using recursion (no loops) c++ | <pre><code>#include <iostream>
#include <cstdlib>
using std:: cin;
using std:: cout;
using std:: endl;
const int N=10;
void readarray(int array[], int N);
int bubble_sort (int array[], int size, int round,
int place);
int main ()
{
int array[N];
readarray( array, N );
int round, place;
cout << bubble_sort(array, N, place, round);
return EXIT_SUCCESS;
}
void readarray(int array[], int N)
{
int i=0;
if (i < N)
{
cin >> array[i];
readarray(array+1, N-1);
}
}
int bubble_sort (int array[], int size, int round,
int place)
{
round =0;
place =0;
if (round < N-1) // this goes over the array again making sure it has
// sorted from lowest to highest
{
if (place < N - round -1) // this sorts the array only 2 cells at a
// time
if (array[0] > array[1])
{
int temp = array[1];
array[1]=array[0];
array[0]=temp;
return (array+1, size-1, place+1, round);
}
return (array+1, size-1, place, round+1);
}
}
</code></pre>
<p>I know how to do a bubble sort using two for loops and I want to do it using recursion. Using loops you require two for loops and I figured for recursion it might also need two recursive functions/calls. This is what I have so far. The problem is that its outputting only one number, which is either 1 or 0. I'm not sure if my returns are correct. </p> | 1 |
Slicing by specific month | <p>I have a dataframe in the following format.</p>
<pre><code> 1 2 3 4
Data
2001-07-30 0.363354 27.428261 14.639130 6.763423
... ... ... ... ...
2015-06-15 0.039085 28.562948 14.000722 8.605911
</code></pre>
<p>I wish to slice by month. Thus for example I want to select only data from month 5 and store this in a new variable. I have found several answers to similar questions. These however do not provide the intended result. </p>
<p>Examples of questions and answers in this area:</p>
<ol>
<li><a href="https://stackoverflow.com/questions/12910187/pandas-dataframe-slicing-by-day-hour-minute">Pandas DataFrame slicing by day/hour/minute</a></li>
<li><a href="https://stackoverflow.com/questions/16175874/python-pandas-dataframe-slicing-by-date-conditions">python pandas dataframe slicing by date conditions</a></li>
<li><a href="https://stackoverflow.com/questions/10565282/pandas-python-how-to-select-specific-times-in-timeseries">pandas, python - how to select specific times in timeseries</a></li>
</ol>
<p>I am new to timeseries analysis with Python and Pandas so any push to the right direction or reading material will be appreciated.</p> | 1 |
If Else Inside For Loop in R | <p>I need to create a if/else statement in the middle of a for loop in R.</p>
<p>I am trying to create a hypothetical phase 1 clinical trial with 3-3 design in R. I start with sample1 ~ binomial(3, x/10), with x starting at 1. If the sample1 = 0, increase x by 1 and take a sample again. When sample1 > 0, take a second sample, sample2 ~ binomial(3, x/10), at the same x value. If sample2=0, increase x, and take sample1 again. If sample2>0, print that x value. I want to do this 10 times and see what the x value for is. Below is my code.</p>
<pre><code>reps <- 10
MTD <- numeric(reps)
for (i in 1:reps) {
x <- 1
sample1 <- rbinom(1, 3, x/10)
if (sample1>0) {sample2 <- rbinom(1,3, x/10)
if (sample2>0) {MTD[i] <- (x)} else x<- x+1}
else x <-x+1
}
MTD
</code></pre>
<p>Looking at the results, all I get are zeros so something is not right. Could someone please assist.
Thanks.</p> | 1 |
What is the use of __attribute__ (format) in C to define a function? | <p>I came across this line of code in a C project, and I did not understand it.</p>
<pre><code>#define FMT_CHK(fmt, args) __attribute__ ((format (printf, fmt, args)))
</code></pre>
<p>The GNU website does not explain it clearly (<a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes" rel="noreferrer">https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes</a>) </p>
<p>What is the purpose of <code>__attribute__ ((format ())</code> and how should it be used?</p> | 1 |
In MySQL, how do I select a result where the result contains every value I test for? | <p>Check out this SQL Fiddle for a simplified version of my issue <a href="http://sqlfiddle.com/#!9/cf31d3/1" rel="nofollow noreferrer">http://sqlfiddle.com/#!9/cf31d3/1</a></p>
<p>I have 2 tables - chat messages and chat recipients that look like this:</p>
<p><a href="https://i.stack.imgur.com/CuwWD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CuwWD.png" alt="enter image description here"></a></p>
<p>Sample ChatMessages data:</p>
<p><a href="https://i.stack.imgur.com/6r88B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6r88B.png" alt="enter image description here"></a></p>
<p>Sample ChatRecipients data:</p>
<p><a href="https://i.stack.imgur.com/Rd57l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rd57l.png" alt="enter image description here"></a></p>
<p>Basically I want to query only messages that contain a set of user IDs - for example, show only messages exchanged between Bob, Susan, and Chelsea. If I pull up a new chat window with user IDs (1, 2, 3) what is the best way to get messages ONLY involving those 3 people?</p>
<p>Here's a simplified version of my current query (which does not produce the correct result):</p>
<pre><code>SELECT
cm.message_id as 'message_id',
cm.from_id as 'from_id',
(SELECT u.user_fname as 'fname' from Users u where u.user_id = cm.from_id) as 'firstName',
(SELECT u.user_lname as 'lname' from Users u where u.user_id = cm.from_id) as 'lastName',
cm.chat_text as 'chat_text'
FROM
ChatMessages cm
INNER JOIN
ChatRecipients cr
ON
cm.message_id = cr.message_id
INNER JOIN
Users u
ON
cm.from_id = u.user_id
WHERE
cm.from_id in ('1', '2', '3')
AND
cr.user_id in ('1', '2', '3')
</code></pre>
<p>I understand that using the 'IN' operator is not correct for this situation, but I'm a bit stuck. Thanks to anyone willing to help!</p>
<p>EDIT:</p>
<p>My sample output returns every row of data that any of the aforementioned user IDs are contained in and looks like this:</p>
<p><a href="https://i.stack.imgur.com/IiToG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IiToG.png" alt="enter image description here"></a></p>
<p>My goal is to limit the output to only messages where EVERY user ID I test for is associated with a message_id. For example, if message_id 32 is FROM user_id 7 and TO user_id(s) 11 & 3, I want to retrieve that record. Conversely, if message_id 33 is FROM user_id 7 and to user_id(s) 11 & 4 I do not want to retrieve that record.</p> | 1 |
sys_connect_by_path in MSSQL | <p>Please help me to convert the below query in MSSQL. </p>
<pre><code>select sys_connect_by_path(title, '/') "Path", ITEM_ID, PARENT_ID
from lib_items
where item_type = '1'start with title = 'root'
connect by prior item_id = parent_id
</code></pre> | 1 |
How to fix "invalid CSS property declaration" in Safari? | <p>I bought a theme from Themeforest, and notice the theme is not working well in Safari 9 and iOS. The theme does not render CSS completely and throws some messages <strong>"invalid CSS property declaration at: 0"</strong> to the CSS below:</p>
<pre><code>@-webkit-keyframes border-pulse-2 {
0% {
border-width: 3px
}
33.33333% {
border-width: 3px
}
66.66666% {
border-width: 23px
}
100% {
border-width: 23px
}
}
</code></pre>
<p>There are a few of more lines in the same CSS file showing the same issues.</p>
<p>The theme has no problem on Chrome and Firefix and the page can be shown correctly.</p> | 1 |
npm install does not work when running npm install cordova | <p>I am using Ionic framework to build hybrid apps. According to the official website, i need to get the version 4.2.4 of Node.js, which includes npm package manager. One of the dependencies needed by Ionic is cordova so that i run the following command to get it</p>
<pre><code>C:\Users\ferrero>npm install -g cordova
</code></pre>
<p>After then, the console logs</p>
<pre><code>npm info it worked if it ends with ok
npm verb cli [ 'C:\\Program Files\\nodejs\\node.exe',
npm verb cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
npm verb cli 'prefix',
npm verb cli '-g' ]
npm info using [email protected]
npm info using [email protected]
npm verb exit [ 0, true ]
npm info ok
npm info it worked if it ends with ok
npm verb cli [ 'C:\\Program Files\\nodejs\\node.exe',
npm verb cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm- cli.js',
npm verb cli 'install',
npm verb cli 'cordova' ]
npm info using [email protected]
npm info using [email protected]
npm verb config Skipping project config: C:\Users\ferrero/.npmrc.
(matches userconfig)
npm verb install initial load of C:\Users\ferrero\package.json
npm verb readDependencies loading dependencies from C:\Users\ferrero\package.json
npm verb cache add spec cordova
npm verb addNamed "latest" is being treated as a dist-tag for cordova
npm info addNameTag [ 'cordova', 'latest' ]
npm verb addNameTag registry:https://registry.npmjs.org/cordova not in flight; fetching
npm verb request uri https://registry.npmjs.org/cordova
npm verb request no auth needed
npm info attempt registry request try #1 at 16:47:06
npm verb request id 62f85abc5c5b7cd5
npm verb etag "6KQ69KRX02Y8MUJFT56H9DE6N"
npm http request GET https://registry.npmjs.org/cordova
npm info retry will retry, error on last attempt: Error: self signed certificate in certificate chain
</code></pre>
<p>As you can see from log, npm run version 2.14.12 and it complains that the cause is a self signed certificate - likely issued by <a href="https://registry.npmjs.org/cordova">https://registry.npmjs.org/cordova</a>. So, to overcome this issue, I run</p>
<pre><code>npm config set registry=http://registry.npmjs.org
</code></pre>
<p>And, after that (just the relevant part)</p>
<pre><code>C:\Users\ferrero>npm install -g cordova
npm verb cache add spec cordova
npm verb addNamed "latest" is being treated as a dist-tag for cordova
npm info addNameTag [ 'cordova', 'latest' ]
npm verb addNameTag registry:http://registry.npmjs.org/cordova not in flight; fetching
npm verb request uri http://registry.npmjs.org/cordova
npm verb request no auth needed
npm info attempt registry request try #1 at 16:59:34
npm verb request id 359f93cb3aa8b76e
npm verb etag "6KQ69KRX02Y8MUJFT56H9DE6N"
npm http request GET http://registry.npmjs.org/cordova
npm http 304 http://registry.npmjs.org/cordova
npm verb headers {
date: 'Tue, 26 Jan 2016 18:59:34 GMT',
npm verb headers via: '1.1 varnish',
npm verb headers 'cache-control': 'max-age=300',
npm verb headers etag: '"6KQ69KRX02Y8MUJFT56H9DE6N"',
npm verb headers age: '263',
npm verb headers connection: 'keep-alive',
npm verb headers 'x-served-by': 'cache-atl6230-ATL',
npm verb headers 'x-cache': 'HIT',
npm verb headers 'x-cache-hits': '1',
npm verb headers 'x-timer': 'S1453834774.362657,VS0,VE1',
npm verb headers vary: 'Accept'
}
npm verb etag http://registry.npmjs.org/cordova from cache
npm verb get saving cordova to C:\Users\ferrero\AppData\Roaming\npm-cache\registry.npmjs.org\cordova\.cache.json
npm verb addNamed "5.4.1" is a plain semver version for cordova
npm verb addRemoteTarball http://registry.npmjs.org/cordova/-/cordova-5.4.1.tgz
not in flight; adding
npm verb addRemoteTarball [ 'http://registry.npmjs.org/cordova/-/cordova-5.4.1.tgz',
npm verb addRemoteTarball 'bc56bc1d3c5387a7926408212dfbce59002f9d76' ]
</code></pre>
<p>This time, it does not complain anything else. Instead, the loading indicator - a pipe character - keep running and running. So, what should i do in order to download such dependency ?</p> | 1 |
ORA-30625: method dispatch on NULL SELF argument is disallowed | <p>Oracle keeps giving me this error: </p>
<blockquote>
<p>ORA-30625: method dispatch on NULL SELF argument is disallowed</p>
</blockquote>
<p>I trying it with <code>soap_api</code> </p>
<p>The code follows:</p>
<pre><code>FUNCTION add_numbers (p_int_1 IN NUMBER,
p_int_2 IN NUMBER)
RETURN NUMBER
AS
l_request soap_api.t_request;
l_response soap_api.t_response;
l_return VARCHAR2(32767);
l_url VARCHAR2(32767);
l_namespace VARCHAR2(32767);
l_method VARCHAR2(32767);
l_soap_action VARCHAR2(32767);
l_result_name VARCHAR2(32767);
BEGIN
l_url := 'http://192.168.1.23:8080/TestWebservice.asmx';
l_namespace := 'xmlns="http://192.168.1.23:8080/TestWebservice.asmx"';
l_method := 'add';
l_soap_action := 'http://tempuri.org/add';
l_result_name := 'return';
l_request := soap_api.new_request(p_method => l_method,
p_namespace => l_namespace);
soap_api.add_parameter(p_request => l_request,
p_name => 'int1',
p_type => 'xsd:integer',
p_value => p_int_1);
soap_api.add_parameter(p_request => l_request,
p_name => 'int2',
p_type => 'xsd:integer',
p_value => p_int_2);
l_response := soap_api.invoke(p_request => l_request,
p_url => l_url,
p_action => l_soap_action);
l_return := soap_api.get_return_value(p_response => l_response,
p_name => l_result_name,
p_namespace => l_namespace);
RETURN l_return;
END;
</code></pre> | 1 |
Access variable in if block | <pre><code>var func = function () {
var i: number = 0;
if (i == 0) {
var y: number = 1;
}
document.body.innerHTML = y.toString(); // js/ts should complain me in this line
};
func(); // output: 1
</code></pre>
<p>As you can see, I've declared variable <code>y</code> inside <code>if</code> block. So, I think it couldn't be referenced outside the scope.</p>
<p>But, when I've tried to run the code, the output is <code>1</code>.</p>
<p>Is it an issue in typescript/javascript?</p> | 1 |
Custom fields in WooCommerce product variations | <p><strong>QUESTION UPDATED AS PEOPLE SEEMED TO MISUNDERSTAND IT:</strong></p>
<p>Using the WooCommerce plugin for WordPress, I'd like to display the product variation names in the Additional Information tab in the same way as weight and dimesions are displayed.</p>
<p>For instance, I have a product that comes in two sizes, 2 litres and 10 litres, therefore it's a variable product with the two product variations '2 litres' and '10 litres'. If I check the box 'display on product page', size is displayed in the Additional Information tab like this: 'Size: 2 litres, 10 litres'.
I want it to work like the weight and dimensions, so when the product variation '2 litres' is selected, the Additional Information tab will display 'Size: 2 litres', and when the product variation '10 litres' is selected, the Additional Information tab will display 'Size: 10 litres'.</p>
<p>Can this be done?</p> | 1 |
Android - Change status bar color on pre-lollipop devices programatically | <p>I want to change the status bar colour on pre-lollipop devices programmatically. I am well aware the material design colouPrimaryDark wont work on pre-lollipop as status bar colour is concern of OS itself which pre-lollipop devices wont provide such feature. So I want to do it programmatically through java file. Is that possible?</p>
<p>currently I am using this material design code. </p>
<pre><code><resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base">
<!-- Customize your theme here. -->
</style>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/primaryColor</item>
<item name="colorPrimaryDark">@color/primaryColor</item>
<item name="colorAccent">@color/primaryColor</item>
</style>
</code></pre>
<p>
As this wont work with API below 21. So I want to do it through java.</p> | 1 |
gcc -Wall -pedantic -Wextra in Visual Studio | <p>On linux I have used these flags to compile with gcc </p>
<pre><code>CFLAGS=-Wall -pedantic -g -Wextra -pthread
</code></pre>
<p>What are my options in VS to enable similar flags? Extra warnings, etc.</p> | 1 |
Variable substitution in Maven | <p>I'm new to maven and I'm trying to change the content of a field based on the entry provided in the command line by using a variable.</p>
<p>I have the following xml file called weatherxml.xml in the directory apiproxy:</p>
<pre><code><APIProxy name="weatherxml">?
<ConfigurationVersion majorVersion="4" minorVersion="0"/>
<CreatedAt>1453818052</CreatedAt>
<Description>${description}</Description>
<DisplayName>weatherxml</DisplayName>
<validate>true</validate>
</APIProxy>
</code></pre>
<p>And in the pom.xml file I have this piece of code:</p>
<pre><code><resources>
<resource>
<directory>apiproxy</directory>
<filtering>true</filtering>
</resource>
</resources>
</code></pre>
<p>This is the test profile used for building</p>
<pre><code><profile>
<id>test</id>
<properties>
<apigee.profile>test</apigee.profile>
<apigee.env>${api_environment}</apigee.env>
<apigee.hosturl>${api_hosturl}</apigee.hosturl>
<apigee.apiversion>v1</apigee.apiversion> <!-- value of version in https://api.enterprise.apigee.com/v2 -->
<apigee.org>${api_organization}</apigee.org>
<apigee.username>${username}</apigee.username>
<apigee.password>${password}</apigee.password>
<apigee.options>override</apigee.options>
<apickli.env>.test</apickli.env>
</properties>
</profile>
</code></pre>
<p>If I invoke maven by using </p>
<pre><code>mvn resources:resources -Ddescription="Test description"
</code></pre>
<p>it creates the target directory and I can see the change has been made. However, if I invoke </p>
<pre><code>mvn install -Ptest -Dusername=xxx -Dpassword=yyy -Dhost=www.aaa.com -Ddescription="Test description"
</code></pre>
<p>it builds and deploys the code but the description field contains the "${description}" text instead of "Test description".</p>
<p>How could I get the variable substitution in the deployed code? I don't know if this could be related by the use of the plugins, maybe some of them overrides it.</p>
<pre><code><build>
<resources>
<resource>
<directory>apiproxy</directory>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>io.apigee.build-tools.enterprise4g</groupId>
<artifactId>apigee-edge-maven-plugin</artifactId>
<version>1.0.0</version>
</plugin>
</plugins>
</pluginManagement>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<!--Copy the full apiproxy folder to target folder -->
<execution>
<id>copy-apiproxy-resources</id>
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<!--this is important -->
<overwrite>true</overwrite>
<!--target -->
<outputDirectory>${target.root.dir}/apiproxy</outputDirectory>
<resources>
<resource>
<!--source -->
<directory>${project.root.dir}/apiproxy</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.apigee.build-tools.enterprise4g</groupId>
<artifactId>apigee-edge-maven-plugin</artifactId>
<configuration>
<!--Use this module level config to skip module build. Make it true -->
<skip>false</skip>
</configuration>
<executions>
<execution>
<id>configure-bundle-step</id>
<phase>package</phase>
<goals>
<goal>configure</goal>
</goals>
</execution>
<!--deploy bundle -->
<execution>
<id>deploy-bundle-step</id>
<phase>install</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- cleaning dirs -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>auto-clean-init</id>
<phase>initialize</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
<execution>
<id>auto-clean-install</id>
<phase>install</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- run cucumber / apickli tests -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<!-- run integration tests -->
<execution>
<id>integration</id>
<phase>install</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<environmentVariables>
<NODE_ENV>
${apigee.env}
</NODE_ENV>
</environmentVariables>
<executable>cucumber-js</executable>
<commandlineArgs>
tests/integration${apickli.env} --format json:cucumber-result.json
</commandlineArgs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre> | 1 |
Why header('Content-Type: application/json'); in our web service? | <p>Why we use </p>
<pre><code>header('Content-Type: application/json');
</code></pre>
<p>Before</p>
<pre><code>echo json_encode($data)
</code></pre>
<p>in the web services in php</p>
<p>If I will not use <code>header('Content-Type: application/json');</code> what is its disadvantage?</p>
<p>Help will be appreciated</p> | 1 |
How to protect a process from being killed? | <p>I've tried to protect a process in c++ windows,
the code is:</p>
<pre><code>#include <iostream>
#include <Aclapi.h>
#include <iostream>
#include <windows.h>
#include <sddl.h>
#include <stdio.h>
using namespace std;
BOOL DenyAccess()
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = FALSE;
SetKernelObjectSecurity(hProcess, DACL_SECURITY_INFORMATION, sa.lpSecurityDescriptor);
return TRUE;
}
int main()
{
while(DenyAccess());
return 0;
}
</code></pre>
<p>But I can kill process from task manager! what's wrong ?</p> | 1 |
Use jquery to animate the Fill of an SVG? | <p>I am trying to use jQuery to animate the path of my SVG, THEN after the first animation completes, animate the fill of the SVG with a duration and an easing function.</p>
<p>Is this possible?</p>
<pre><code>$(function() {
$('svg').hover(function() {
$(this).find('.social-circle').stop()
.animate({'stroke-dashoffset': 0}, 1000, 'easeOutBounce')
.css('fill', '#f4321e');
console.log('on');
}, function() {
$(this).find('.social-circle').stop()
.animate({'stroke-dashoffset': 900}, 1000, 'easeOutBounce')
.css('fill', 'none');
});
});
</code></pre>
<p>thanks for your time!</p> | 1 |
foreign key as initial value not passed to the ModelForm in django | <p>I need to pass the value (based on category_id) for a ForeignKey to the ModelForm but it's not working. My field remains "--------" and proper value is not set from the drop-down field.
Value for the Category must BE SELECTED and other values must be not hided from user to choice.</p>
<p>As the result category value successfuly passed to template but drop-down field Category not set!</p>
<p>As I can see other guys solved it via constructor for ModelForm, but I feel there must be native django solution.</p>
<p>Would be thankful for any solutions!</p>
<p>my models.py:</p>
<pre><code>class Category(models.Model):
name = models.CharField('Name', max_length=20)
icon = models.CharField('Icon', blank=True, max_length=20)
class Transaction(models.Model):
type = models.CharField('Type', default='exp', max_length=20)
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
note = models.CharField('Note', blank=True, max_length=20)
</code></pre>
<p>my urls.py:</p>
<pre><code>urlpatterns = [
url(r'^add/(?P<category_id>[0-9]+)', "core.views.add_trans_view", name='add_trans_url'),
]
</code></pre>
<p>my views.py:</p>
<pre><code>def add_trans_view(request, category_id):
category = Category.objects.get(id=category_id)
form = TransactionForm(request.POST or None, initial={'category':category.name,})
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return render(request,
'core/transaction_form.html', {'form': form, 'for_debug':category})
</code></pre>
<p>my forms.py:</p>
<pre><code>class TransactionForm(forms.ModelForm):
class Meta:
model = Transaction
fields = ['type', 'category', 'note']
</code></pre>
<p>my template:</p>
<pre><code><p>Initial 'category' value transfered from view:</p>
<h4>{{for_debug}}</h4>
<form method='POST' action=''> {% csrf_token %}
{{form.as_p}}
<input type='submit' value='Done'/>
</form>
</code></pre> | 1 |
How to speed up this ElasticSearch query? | <p>I'm trying to build auto suggest based on the docs title. If the user types 'South', the auto suggest will suggest 'South Korea' for example. I used <em>shingle</em> filter to break the title to two words. Here my mapping :</p>
<pre><code>{
"settings":{
"analysis":{
"filter":{
"suggestions_shingle":{
"type":"shingle",
"min_shingle_size":2,
"max_shingle_size":2
}
},
"analyzer":{
"suggestions":{
"tokenizer":"standard",
"filter":[
"suggestions_shingle"
]
}
}
}
},
"mappings":{
"docs":{
"properties":{
"docs_title":{
"type":"multi_field",
"fields":{
"docs_title":{
"type":"string"
},
"suggestions":{
"type":"string",
"analyzer":"suggestions",
"search_analyzer":"simple"
}
}
}
}
}
}
}
</code></pre>
<p>And Here is my query:</p>
<pre><code>{
explain:true,
"aggs":{
"description_suggestions":{
"terms":{
"field":"docs_title.suggestions",
"size":10,
"include":"South .*"
}
}
},
size:0
}
</code></pre>
<p>Here is the response from the query :</p>
<pre><code>{
"took": 2764,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 453526,
"max_score": 0,
"hits": []
},
"aggregations": {
"description_suggestions": {
"doc_count_error_upper_bound": 10,
"sum_other_doc_count": 2363,
"buckets": [
{
"key": "South Korea",
"doc_count": 274
},
{
"key": "South India",
"doc_count": 179
},
{
"key": "South Carolina",
"doc_count": 179
}
]
}
}
}
</code></pre>
<p>As you can see, the query took 2764 to complete. How can I speed up this query?</p>
<p>I was thinking to run the aggregation query only on the last 2000 docs to speed it up by using filters. I noticed Elastic Search is ignoring the filter and it run the aggs on all docs. Here is query:</p>
<pre><code>{
explain:true,
"aggs":{
"recent_suggestions":{
"filter":{
"range":{
"docs_date":{
"gte":1453886958
}
}
},
"aggs":{
"description_suggestions":{
"terms":{
"field":"docs_title.suggestions",
"size":10,
"include":"South .*"
}
}
}
}
},
size:0
}
</code></pre>
<p>and here is the response:</p>
<pre><code>{
"took": 2216,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 453526,
"max_score": 0,
"hits": []
},
"aggregations": {
"recent_suggestions": {
"doc_count": 27240,
"description_suggestions": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 173,
"buckets": [
{
"key": "South Korea",
"doc_count": 19
},
{
"key": "South India",
"doc_count": 17
},
{
"key": "South Carolina",
"doc_count": 17
}
]
}
}
}
}
</code></pre>
<p>As you can see, the total hits are the same. </p>
<p>How to make the two queries faster?</p>
<p>I'm using AWS ElasticSaerch v1.5.2 and Lucene v4.10.4 on a single instance. </p> | 1 |
Exception thrown at 0x6FDFDBF0 (vcruntime140.dll) in Main.exe | <p>I'm working on an assignment for school in C++ which contains a skeleton we have to begin with which also involves the SFML library which I've correctly imported. The skeleton is made up of 2 .cpp files, a .h header file and all the files in /Assets. Listed below are the three files.</p>
<p>Main.cpp</p>
<pre><code>#include "Game.h"
int main()
{
Game theGame;
theGame.loop();
return 0;
}
</code></pre>
<p>Game.cpp</p>
<pre><code>#include <iostream>
#include <fstream>
#include "Game.h"
Game::Game()
{
std::ifstream fileHndl;
fileHndl.open("Assets/mapdata.txt");
fileHndl >> mapCols;
fileHndl >> mapRows;
playerX = mapCols / 2;
playerY = mapRows / 2;
mapData = new int *[mapRows];
for (int i = 0; i < mapRows; i++) {
mapData[i] = new int[mapCols];
}
for (int i = 0; i < mapRows; i++) {
for (int j = 0; j < mapCols; j++) {
fileHndl >> mapData[i][j];
}
}
window.create(sf::VideoMode(1280, 1024), "COMP2501 Demo");
window.setFramerateLimit(5);
playerTexture.loadFromFile("Assets/actor.png");
playerTexture.setSmooth(true);
playerSprite.setTexture(this->playerTexture);
floorTexture.loadFromFile("Assets/floor.png");
floorTexture.setSmooth(true);
crateTexture.loadFromFile("Assets/crate.png");
crateTexture.setSmooth(true);
mapSprites = new sf::Sprite *[mapRows];
for (int i = 0; i < mapRows; i++) {
mapSprites[i] = new sf::Sprite[mapCols];
}
for (int i = 0; i < mapRows; i++)
{
for (int j = 0; j < mapCols; j++)
{
mapSprites[i][j].setPosition(j * 64, i * 64);
if (mapData[i][j] == 1)
{
mapSprites[i][j].setTexture(this->floorTexture);
}
else
{
mapSprites[i][j].setTexture(this->crateTexture);
}
}
}
}
Game::~Game()
{ }
void Game::loop()
{
while (window.isOpen())
{
inputs();
update();
render();
}
}
void Game::inputs()
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
if (this->mapData[this->playerX - 1][this->playerY] == 1)
{
this->playerX--;
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
if (this->mapData[this->playerX + 1][this->playerY] == 1)
{
this->playerX++;
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
if (this->mapData[this->playerX][this->playerY - 1] == 1)
{
this->playerY--;
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
if (this->mapData[this->playerX][this->playerY + 1] == 1)
{
this->playerY++;
}
}
}
void Game::update()
{ }
void Game::render()
{
playerSprite.setPosition(playerY * 64, playerX * 64);
window.clear();
for (int i = 0; i < mapRows; i++) {
for (int j = 0; j < mapCols; j++) {
window.draw(mapSprites[i][j]);
}
}
window.draw(playerSprite);
window.display();
}
</code></pre>
<p>Game.h</p>
<pre><code>#pragma once
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
class Game
{
public:
Game();
~Game();
void loop();
void inputs();
void update();
void render();
sf::RenderWindow window;
int playerX, playerY;
sf::Texture playerTexture;
sf::Sprite playerSprite;
int mapRows, mapCols;
int **mapData;
sf::Sprite **mapSprites;
sf::Texture floorTexture;
sf::Texture crateTexture;
};
</code></pre>
<p>The program compiles correctly however at run-time it gives me the following.</p>
<pre><code>'Main.exe' (Win32): Loaded 'C:\Users\Alex\Documents\Visual Studio 2015\Projects\Main\Debug\Main.exe'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Users\Alex\Documents\Visual Studio 2015\Projects\Main\Debug\sfml-graphics-2.dll'. Module was built without symbols.
'Main.exe' (Win32): Loaded 'C:\Users\Alex\Documents\Visual Studio 2015\Projects\Main\Debug\sfml-window-2.dll'. Module was built without symbols.
'Main.exe' (Win32): Loaded 'C:\Users\Alex\Documents\Visual Studio 2015\Projects\Main\Debug\sfml-system-2.dll'. Module was built without symbols.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winmm.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcrt.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\user32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\gdi32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\lpk.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\usp10.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\advapi32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sechost.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rpcrt4.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sspicli.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cryptbase.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp140.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\vcruntime140.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-runtime-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbase.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-core-timezone-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-core-file-l2-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-core-localization-l1-2-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-core-synch-l1-2-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-core-processthreads-l1-1-1.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-core-file-l1-2-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-string-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-heap-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-stdio-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-convert-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-locale-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-math-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-multibyte-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-time-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-filesystem-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-environment-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\api-ms-win-crt-utility-l1-1-0.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\opengl32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\glu32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ddraw.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dciman32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\setupapi.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cfgmgr32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\oleaut32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ole32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\devobj.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dwmapi.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp140d.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\vcruntime140d.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbased.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\imm32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msctf.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\uxtheme.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\nvoglv32.dll'. Cannot find or open the PDB file.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\shell32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\shlwapi.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\wtsapi32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\version.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dbghelp.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\gdi32.dll'. Symbols loaded.
'Main.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\gdi32.dll'
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\wintrust.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\crypt32.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msasn1.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntmarta.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\Wldap32.dll'. Symbols loaded.
The thread 0x4c0 has exited with code 0 (0x0).
The thread 0x1be8 has exited with code 0 (0x0).
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\powrprof.dll'. Symbols loaded.
'Main.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\powrprof.dll'
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\winsta.dll'. Symbols loaded.
The thread 0x1924 has exited with code 0 (0x0).
The thread 0x1b50 has exited with code 0 (0x0).
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dinput.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\hid.dll'. Symbols loaded.
'Main.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ole32.dll'. Symbols loaded.
'Main.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\ole32.dll'
Exception thrown at 0x6FDFDBF0 (vcruntime140.dll) in Main.exe: 0xC0000005: Access violation reading location 0x00477000.
The program '[6440] Main.exe' has exited with code 0 (0x0).
vcruntime140.dll!memcpy(unsigned char * dst, unsigned char * src, unsigned long count) Line 634 Unknown
vcruntime140.dll!__vcrt_FlsGetValue(unsigned long) Line 401 C++
</code></pre>
<p>I've looked up multiple solutions such as reinstalling the x64 and x86 re-distributable for visual studio 2015 and enabling microsoft symbols but I still get this error. It seems to be caused by vcruntime140.dll.</p> | 1 |
Alan Kay's Eval/Apply Einstein Moment | <p>Alan Kay said that <a href="https://youtu.be/HAT4iewOHDs?t=3m18s" rel="noreferrer">reading the code closely and finding the 1 and only bug in the code on page 13 of the Lisp 1.5 manual, helped him understand Computer Science by a factor of 100 better</a>.</p>
<p>The code in question is the 1st release of <code>eval</code> & <code>apply</code> that looks anything remotely like modern lisp (that I'm aware of).</p>
<p>Since the correct answer is likely known but lost (my google-fu is decent and I've searched for 20 mins at least)
I will award the 1st correct answer (I will be looking at edit times so don't try to cheat) a 250 point bounty As Soon As Possible. </p>
<p>I would suggest others contribute to the bounty as well,
remember from the video above <a href="https://en.wikipedia.org/wiki/Alan_Kay" rel="noreferrer">Alan Kay</a> said this stuff is reminiscent of the environment <a href="https://en.wikipedia.org/wiki/Albert_Einstein" rel="noreferrer">Einstein</a> was in when he discovered the <a href="https://en.wikipedia.org/wiki/Theory_of_relativity" rel="noreferrer">Theory of Relativity</a>.</p>
<p>The code in the text is written in M-Expressions. I'm working on a translator to translate from M-expressions to S-expressions (lisp code) @<a href="https://github.com/Viruliant/MccarthyMCEval-1.5" rel="noreferrer">https://github.com/Viruliant/MccarthyMCEval-1.5</a>. </p>
<p>Anyways here is the translated quote from page 13:</p>
<pre><code>;______________________________________Lisp Meta-Circular Evaluator S-Expression
;this code is written in the order it appears on pages 10-13 in the Lisp 1.5 Manual
;and is translated from the m-expressions into s-expressions
(label mc.equal (lambda (x y)
(mc.cond
((atom x) ((mc.cond ((atom y) (eq x y)) ((quote t) (quote f)))))
((equal (car x)(car y)) (equal (cdr x) (cdr y)))
((quote t) (quote f)))))
(label mc.subst (lambda (x y z)
(mc.cond
((equal y z) (x))
((atom z) (z))
((quote t) (cons (subst x y (car z))(subst x y (cdr z)))))))
(label mc.append (lambda (x y)
(mc.cond
((null x) (y))
((quote t) (cons (car x)) (append (cdr x) y)))))
(label mc.member (lambda (x y)
(mc.cond ((null y) (quote f))
((equal x (car y)) (quote t))
((quote t) (member x (cdr y))))))
(label mc.pairlis (lambda (x y a)
(mc.cond ((null x) (a)) ((quote t) (cons (cons (car x)(car y))
(pairlis (cdr x)(cdr y) a)))))
(label mc.assoc (lambda (x a)
(mc.cond ((equal (caar a) x) (car a)) ((quote t) (assoc x (cdr a))))))
(label mc.sub2 (lambda (a z)
(mc.cond ((null a) (z)) (((eq (caar a) z)) (cdar a)) ((quote t) (
sub2 (cdr a) z)))))
(label mc.sublis (lambda (a y)
(mc.cond ((atom y) (sub2 a y)) ((quote t) (cons (sublis a (car y))))
(sublis a (cdr y)))))
(label mc.evalquote (lambda (fn x)
(apply fn x nil)))
(label mc.apply (lambda (fn x a)
(mc.cond ((atom fn) (
(mc.cond
((eq fn car) (caar x))
((eq fn cdr) (cdar x))
((eq fn cons) (cons (car x)(cadr x)))
((eq fn atom) (atom (car x)))
((eq fn eq) (eq (car x)(cadr x)))
((quote t) (apply (eval (fn a)x a))))))
((eq (car fn) lambda) (eval (caddr fn) (parlis (cadr fn) x a)))
((eq (car fn) label) (apply (caddr (fn)x cons (cons (cadr (fn)))
(caddr fn))a)))))
(label mc.eval (lambda (e a)
(mc.cond
((atom e) (cdr (assoc e a)))
((atom (car e)) (mc.cond
((eq (car e) quote) (cadr e))
((eq (car e) cond) (evcon (cdr e) a))
((quote t) (apply (car e) (evlis (cdr e) a) a))))
((quote t) (apply (car e) (evlis (cdr e) a) a))))))
(label mc.evcon (lambda (c a)
(mc.cond
((eval (caar c) a) (eval (cadar c) a))
((quote t) (evcon (cdr c) a)))))
(label mc.evlis (lambda (m a)
(mc.cond
((null m) (nil))
((quote t) (cons (eval (car m) a) (evlis (cdr m) a)))))))
</code></pre> | 1 |
Compile and link C++ and C programms together with QT-Creator | <p>so I have serveal C++ files and basically need to call a C function after the C++ part of my program is done. So if there is a way to just somehow magically "start the C file" (I hope you know what I mean) I would be glad to hear about that too. Now to my actual problem: I'm trying to call the C function at the end of my main function in the main C++ file. I already saw all of this <a href="https://stackoverflow.com/questions/16850992/call-a-c-function-from-c-code">Call a C function from C++ code</a> and tried to do everything the correct way, my header file for the C file looks kind of like this: </p>
<pre><code> #ifndef H_FILE
#define H_FILE
#ifdef __cplusplus
extern "C" {
#endif
void foo();
void bar();
#ifdef __cplusplus
}
#endif
</code></pre>
<p>I then tried to include the header file in the C++ file with this:</p>
<pre><code> extern "C" {
#include "folder/file.h"
}
</code></pre>
<p>I also alternatively tried a basic #include "folder/file.h"</p>
<p>But I'm getting a undefined reference error when I'm trying to use the foo() function from my C file. My .pro file looks kind of like this:</p>
<pre><code>QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = Example
TEMPLATE = app
QMAKE_CXXFLAGS += -std=c++11
SOURCES += main.cpp\
folder/file.c \
HEADERS += main.h \
</code></pre>
<p>So I guess I have to add some kind of flag for it to be compiled correctly, but what exactly am I missing? Thank you for your help!</p> | 1 |
Improving performance on a large Doctrine query | <p>In Symfony3, I'm using Doctrine's QueryBuilder to iterate up to 500k rows from my 35 million row table:</p>
<pre><code>$query = $this->createQueryBuilder('l')
->where('l.foo = :foo')
->setParameter('foo', $foo)
->getQuery();
$results = $query->iterate();
foreach ($results as $result) {
$em->clear();
// My logic using $result[0]
}
</code></pre>
<p>The memory usage of this often approaches 512mb, before I even begin to iterate. Is there any further way I can optimise this? Am I correct in reading that hydration is turned off when iterating a query?</p> | 1 |
UIKit (getuikit) slider component refuses to work | <p>I have no idea what is going on with this slider component for UI kit. I've used UI kit successfully for months (including using the slider) and now, on this new site, it isn't rendering at all (list items showing up as default, no slide functionality, etc.).</p>
<p>I originally tried having local copies of UIKit and Jquery, but it was the same result. This occurs on my localhost server as well (so hopefully the error is a stupid mistake).</p>
<p>Entire php file:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Burn Blue</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.24.3/css/uikit.min.css" />
<link rel="stylesheet" href="css/components/slider.min.css" />
</head>
<body>
<div data-uk-slider>
<div class="uk-slider-container">
<ul class="uk-slider">
<li class="uk-width-1-1" style="background-image: url('/images/slide-1.jpg');">Test</li>
<li class="uk-width-1-1" style="background-image: url('/images/slide-2.jpg');">Test</li>
<li class="uk-width-1-1" style="background-image: url('/images/slide-3.jpg');">Test</li>
<li class="uk-width-1-1" style="background-image: url('/images/slide-2.jpg');">Test</li>
</ul>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.24.3/js/uikit.min.js"></script>
<script src="js/components/slider.min.js"></script>
</body>
</html>
</code></pre>
<p>Link to page: <a href="http://burn.blue/slider.php" rel="nofollow">http://burn.blue/slider.php</a></p>
<p>EDIT: It's now working correctly; I didn't realize I had to add the slider.min.js or slider.min.css.</p> | 1 |
"TM" in Hibernate Code Causing Confusion | <p>I am studying this book <code>Java Persistence with Hibernate</code> and on page 24 in the PDF version there is a statement like :</p>
<pre><code>UserTransaction tx = TM.getUserTransaction();
</code></pre>
<p>I don't know where the <code>TM</code> comes from. I have googled for a while but can't find any answer. Because of this i can't run my code in Netbeans.</p>
<p>I can also see <code>JPA</code> somewhere in the code. What does that also mean?</p>
<p>Thanks for helping</p>
<p>The whole code is :</p>
<pre><code>public class HelloWorldJPA {
public static void main(String[] args){
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloWorldPU");
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
} catch (NotSupportedException | SystemException ex) {
Logger.getLogger(HelloWorldJPA.class.getName()).log(Level.SEVERE, null, ex);
}
EntityManager em = emf.createEntityManager();
Message message = new Message();
message.setText("Hello World!");
em.persist(message);
tx.commit();
em.close();
} catch (HeuristicMixedException | HeuristicRollbackException | IllegalStateException | RollbackException | SecurityException | SystemException ex) {
Logger.getLogger(HelloWorldJPA.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
</code></pre> | 1 |
DoCmd.OpenQuery or DoCmd.RunSQL | <p>Redesigning parts of my employers database I come across subroutines wrote by who ever created it originally that go something like this:</p>
<pre><code>DoCmd.OpenQuery "qry1"
DoCmd.OpenQuery "qry2"
DoCmd.OpenQuery "qry3"
DoCmd.OpenQuery "qry4"
DoCmd.OpenQuery "qry5"
DoCmd.OpenQuery "qry6"
DoCmd.OpenQuery "qry7"
etc...
etc.....
etc.......
</code></pre>
<p>I have always used DoCmd.RunSQL for running queries behind events etc, mainly because the SQL is then all in front of me in one place within the VBA editor.</p>
<p>Currently some procedures have up to 50 OpenQuery dealing with tables with 250000+ records. Having a brief look through the queries it seems that many of them can be combined as they do similar things with the same data sets, it appears to me whoever wrote them didn't have a good understanding of SQL.</p>
<p>My question is which method is better in terms of performance etc. DoCmd.OpenQuery or DoCmd.RunSQL</p> | 1 |
Avoiding MemoryStream.ToArray() when using System.IO.Compression.ZipArchive | <p>A helper method to turn a string into a zipped up text file:</p>
<pre><code>public static System.Net.Mail.Attachment CreateZipAttachmentFromString(string content, string filename)
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Update))
{
ZipArchiveEntry zipArchiveEntry = zipArchive.CreateEntry(filename);
using (StreamWriter streamWriter = new StreamWriter(zipArchiveEntry.Open()))
{
streamWriter.Write(content);
}
}
MemoryStream memoryStream2 = new MemoryStream(memoryStream.ToArray(), false);
return new Attachment(memoryStream2, filename + ".zip", MediaTypeNames.Application.Zip);
}
}
</code></pre>
<p>I was really hoping to avoid turning the first memory stream into an array, making another memory stream on it to read it, and passing that to attachment. My logic was, why copy X megabytes to another place in memory to establish another stream pointing to the copy, when it's essentially just what we started out with.. It's the multi-megabyte equivalent of redundancy like <code>if(myBool == true)</code> </p>
<p>So I figured instead I would Seek back to the start of the first memory stream, and then attachment could just read that.. Or I would establish another memorystream pointing to the buffer of the first, and with the offset and length parameters set so it would know what to read</p>
<p>Neither of these approaches work out because it seems that ZipArchive only pushes data into the memory stream (in my case maybe) when control falls out of the using block and the ziparchive is disposed. Disposing it also disposes the MemoryStream and nearly everything (other than ToArray() and GetBuffer()) throw ObjectDisposedException. </p>
<p>Ultimately I can't seek it or get its length after the ZipArchive pumps data into it and before it pumps it in, the offset is usually zero and the length is definitely zero so the values are useless</p>
<p>Is there a nice optimal way, short of configuring my own over-large buffer (which then makes it non expandable by MemoryStream), to avoid having to burn up around 2x the memory bytes of the archive size with this method?</p> | 1 |
How to use srcset and sizes for responsive images | <p>I have following snap-points: <code>480px</code>, <code>900px</code>, <code>1800px</code>, <code>2400px</code>.</p>
<p>and this markup:</p>
<pre><code><img
sizes="(max-width: 2400px) 100vw, 2400px"
srcset="
boat-480.jpg 480w,
boat-900.jpg 900w,
boat-1800.jpg 1800w,
boat-2400.jpg 2400w"
src="boat-2400.jpg"
alt="This is a boat">
</code></pre>
<p>How should I get responsive images to work?</p> | 1 |
Cannot load a specific URL with file_get_contents() | <p>I am scraping <a href="http://www.beautyinzone.net/" rel="nofollow">http://www.beautyinzone.net/</a>.</p>
<p>I am using simple <code>file_get_contents()</code> to load this URL.</p>
<p>Its working perfectly on my localhost. But it does not work when I upload on my live server.</p>
<pre><code>Warning: file_get_contents(http://www.beautyinzone.net/): failed to open stream: Connection timed out in script.php on line 36 page
</code></pre>
<p>If I open some other URL it works fine.</p>
<p>URL</p>
<p>I have tried with cURL as well but that shows empty page, returns nothing.</p>
<p>One thought came in my mind that maybe I am blocked, but it should not be like that that said website using my servers.</p>
<p>What possible issue can be preventing me loading that URL?</p> | 1 |
getDatePicker().setMinDate of DatePickerDialog does not work | <p>I want the DatePickerDialog to not show dates before current date. I'm using the <code>setMinDate(long l)</code> method. But it's not working. </p>
<p>I use a inner class where I set the minDate:</p>
<pre><code>public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
DatePickerDialog datePickerDialog;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
String s = month + day + year+"";
datePickerDialog = new DatePickerDialog(getActivity(),this,year,month,day);
datePickerDialog.getDatePicker().setMinDate(Long.parseLong(s));
// Create a new instance of DatePickerDialog and return it
return datePickerDialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
SelectedDateView.setText(day+ (month + 1) + "-" + "-" + year);
}
}
</code></pre>
<p>This is the method that shows it:</p>
<pre><code>public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
</code></pre> | 1 |
ImportError: No module named oslo_config.cfg - Ryu App | <p>I am running a sample Ryu application as outlined here: <a href="https://ryu-zhdoc.readthedocs.org/en/latest/writing_ryu_app.html" rel="nofollow noreferrer">https://ryu-zhdoc.readthedocs.org/en/latest/writing_ryu_app.html</a></p>
<p>But I am getting the following error:</p>
<pre><code> Traceback (most recent call last):
File "/usr/local/bin/ryu-manager", line 9, in <module>
load_entry_point('ryu==3.29.1', 'console_scripts', 'ryu-manager')()
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 351, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2363, in load_entry_point
return ep.load()
File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2088, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/usr/local/lib/python2.7/dist-packages/ryu/cmd/manager.py", line 31, in <module>
from ryu import cfg
File "/usr/local/lib/python2.7/dist-packages/ryu/cfg.py", line 17, in <module>
import oslo_config.cfg
ImportError: No module named oslo_config.cfg
</code></pre>
<p>I have already tried the following commands and none have resolved my issue yet:</p>
<pre><code>sudo pip install oslo.config
sudo apt-get upgrade python-oslo.config
sudo apt-get install python-oslo python-netaddr
</code></pre>
<p>I am just beginning to familiarize myself with Ryu and appreciate any pointers to resolve this issue. Thanks!</p>
<p><a href="https://i.stack.imgur.com/gtnxQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gtnxQ.png" alt="Error after importing oslo"></a></p> | 1 |
how to be a super user to run linux commands in python script? | <p>I have to execute few commands in linux but I need to be a super user before I execute the command.
This has to be done via python script
The scenario is i should execute the following command in the order</p>
<pre><code>>> su
</code></pre>
<p>This prompts for password</p>
<p>After entering the password I will have to execute the bluez commands</p>
<pre><code>>> hciconfig hci0 up
>> hcitool lescan
>> hcitool lecc <address>
</code></pre>
<p>i need to do this in python
but could you please tell me how to be a super user and give password via python then later execute the above commands in order?
Meaning,I want to automate the whole process that is execute all the commands without manual intervention.</p> | 1 |
How to prevent redirect to new page on form submit | <p>I am trying to upload a form containing multiple files to my server, request is going to correct Action and I am also getting some data but all the files are coming with null values. </p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var file = function(){
this.submitForm = function () {
$("#addBrtForm").ajaxSubmit(function (response) {
if (response === "Barter Uploaded Successfully") {
alert(response);
$.mobile.changePage("#p-afterUpload");
t.somefunction();
} else {
alert("Try Again!! Barter Not Uploaded");
}
});
};
};
hm.files = new file();
//other thing that I tried
$(function(){
$('#addBrtForm').ajaxForm({
type: 'POST',
beforeSubmit: function () {
return false;
},
success: function (response) {
return false;
if (response === "Barter Uploaded Successfully") {
alert(response);
$.mobile.changePage("#p-barter");
t.setBarterpageTitle('My Barter');
} else {
alert("Try Again!! Barter Not Uploaded");
}
}
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form method="post" action="http://localhost:xxxx/Mobile/Home/FileUpload" enctype="multipart/form-data" data-ajax="false" id="addBrtForm" name="addBrtForm" >
<input type="text" name="Title" data-role="none" />
<input type="text" name="Description" data-role="none" />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="Submit" name="" value="submit" data-role="none" multiple />
<input type="Button" name="" value="submit" data-role="none" multiple onclick="hm.files.submitForm()"/>
</form></code></pre>
</div>
</div>
</p>
<ul>
<li>It is working perfectly without "ajaxSubmit" but page is redirecting to "<a href="http://localhost:xxxx/Mobile/Home/FileUpload" rel="nofollow">http://localhost:xxxx/Mobile/Home/FileUpload</a>", I don't want that page to come up, I just wanted to catch my response and do something based on that </li>
</ul>
<p>My controller</p>
<pre><code> public ActionResult FileUpload(FormCollection fc, List<HttpPostedFileBase> files)
{
//some functionilty to save data working perfectely
return Json(SuccesMessage, JsonRequestBehavior.AllowGet);
}
</code></pre>
<p>*Note - as I am using jquery mobile so there is no views in my project</p> | 1 |
Android java.io.FileNotFoundException image open failed: ENOENT from internal storage | <p>Hello I am working with android . I want to save multiple captured images in a folder(programmatically created in internal storage of the device) and read this file from the folder and send to server as multipart form. I used the below code for attaching images to multipart ,</p>
<pre><code>for(int i=0;i<Captured_imagePath.size();i++) {
try {
final File file2 = new File(android.os.Environment.getExternalStorageDirectory() + "/MyFolder/" + Captured_imagePath.get(i));
final FileBody fileBody = new FileBody(file2);
entityBuilder.addPart(file2.getName(), fileBody);
entityBuilder.setBoundary(boundary);
} catch (Exception e) {
Log.i(TAG, "Except:: " + e.toString());
}
}
</code></pre>
<p>When I use only one image in this loop it works fine. When more than one images, it cause the following exception</p>
<pre><code> 8594-9144/? W/System.err﹕ java.io.FileNotFoundException: /storage/sdcard0/MyFolder/ 20160123_121858.jpg: open failed: ENOENT (No such file or directory)
01-23 12:19:09.525 8594-9144/? W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-23 12:19:09.525 8594-9144/? W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-23 12:19:09.525 8594-9144/? W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-23 12:19:09.525 8594-9144/? W/System.err﹕ Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory).
</code></pre>
<p>I added permissions in the manifest</p>
<pre><code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code></pre>
<p>my complete multpart uploading method is</p>
<pre><code> public String uploadMultipart(String url,String json ,ArrayList<String> imagePath,ArrayList<String> Captured_imagePath) {
String result="";
File file=null;
String boundary = "-------------" + System.currentTimeMillis();
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addTextBody("json", json);
entityBuilder.setBoundary(boundary);
if(imagePath.size()!=0)
{
file = new File(android.os.Environment.getExternalStorageDirectory() + "/MyFolder/" + imagePath.get(0));
entityBuilder.addBinaryBody(file.getName(), file, ContentType.create("image/jpeg"), imagePath.get(0));
entityBuilder.setBoundary(boundary);
}
if(Captured_imagePath.size()!=0)
{
for(int i=0;i<Captured_imagePath.size();i++)
{
try {
final File file2 = new File(android.os.Environment.getExternalStorageDirectory() + "/MyFolder/" + Captured_imagePath.get(i));
final FileBody fileBody = new FileBody(file2);
entityBuilder.addPart(file2.getName(), fileBody);
entityBuilder.setBoundary(boundary);
}catch (Exception e)
{
Log.i(TAG, "Except:: " + e.toString());
}
}
}
HttpEntity entity = entityBuilder.build();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
entity.writeTo(bytes);
String content = bytes.toString();
// Log.i(TAG,"sending data"+content);
// writeToFile("shanu",content);
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
Log.i(TAG2, result);
}
catch(Exception e)
{
e.printStackTrace();
}
return result.toString();
</code></pre>
<p>I had searched for this file in my folder manually and it exist in the same folder.Then why I got this file not found exception ? How can I resolve this issue? please help.</p> | 1 |
How to call directive from template html in angularjs | <p>Html</p>
<pre><code><script type="text/ng-template" id="ProfileTemplateHTML" >
<div class="container profilepopup-cont" align="center">
<div class="row">
<div class="col-sm-3 zero-margin-padding" align="center">
<img id="DisplayImage" ng-src={{model.picLarge}} class="img-circle">
</div>
...
</script>
</code></pre>
<p>In this html template file i have to call a directive.My directive name is 'help'.But if i add to call the directive it is not working.
how to call a directive inside html template in angularjs?</p> | 1 |
Android: Google Maps Android API: Authorization failure | <p>When my app tries to use the Google Maps API, I get the following logcat error as soon as I try to access Google Map API data (scroll right to see the good stuff!):</p>
<pre><code>02-02 15:39:35.329 23868-24511/com.somepackage.name E/Google Maps Android API: Authorization failure. Please see https://developers.google.com/maps/documentation/android/start for how to correctly set up the map.
02-02 15:39:35.339 23868-24511/com.somepackage.name E/Google Maps Android API: Ensure that the following correspond to what is in the API Console:
API Key: AI~~~~~~~~~~~~~~~~~~~~~~~~~~ZwmI
Package Name: com.somepackage.name
Certificate Fingerprint: 50:~~~~~~~~~~~~~~~~~~~~:D5
</code></pre>
<p>Here is an image of the Google Developers Support Console with the Fingerprint and the API Key (and yes, they DO match!). I have also waited for the Google servers to update (5 minutes according to the dox; I have waited hours).</p>
<p><a href="https://i.stack.imgur.com/yut0A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yut0A.png" alt="enter image description here"></a></p>
<p>And here is my project's primary AndroidManifest.xml (edited for brevity):</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
...
<!--
The following two permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
...
<!--The key to use Google's map API -->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIz~~~~~~~~~~~~~~~~~~~~~~~~~~~~wmI"/>
<activity
...
</activity>
...
</application>
</code></pre>
<p></p>
<p>I have a Premium Support account with Google, but have been unable to contact them so far. Does anyone have any idea why I'm getting this Authorization Failure?</p> | 1 |
How do I allow JS onclick with pointer-events:none;? | <p>I have a <code>div</code> over the whole page to close a dropdown menu when the big <code>div</code>is clicked. The thing is that I need <code>pointer-events: none;</code> because if I don't use it, the whole page gets blocked by the big <code>div</code>.</p>
<p>JS <code>onclick</code> won't work when I have <code>pointer-events:none;</code> So, I don't really know how to solve this.</p>
<pre><code> function test() {
if (document.getElementById('div1').style.display == 'block') {
document.getElementById('div1').style.display = 'none';
}
else{
}
}
#big_div{
width: 100%;
height: 100%;
display: block;
pointer-events:none;
}
<div id="big_div" onclick="test()"></div>
</code></pre> | 1 |
Listview Contacts filtering from toolbar search | <p>I am doing one application in that i display all the contacts from device to ListView (Name, Number, Image). I want to search the contacts from the ListView using the toolbar search. I added search for toolbar but i don't know how to filter the contacts from the list. Please any one help me. </p>
<p>I used <a href="http://wptrafficanalyzer.in/blog/android-contacts-content-provider-retrieving-and-listing-contacts-in-listview-example/" rel="nofollow">this example</a> for displaying contacts in ListView.</p> | 1 |
Regex to match strings that are all punctuation but not strings with punctuation containing other characters | <p>I have some messy text responses that I'm trying to cleanup a little. I'm using R and want to match responses that are all punctuation for removal. </p>
<p>Is there a regexp I can use to match these:</p>
<pre><code>!@#$
.
**********
</code></pre>
<p>But not these:</p>
<pre><code>Hello.
!asdf
**********1
</code></pre>
<p>I had previously tried </p>
<pre><code>x[grepl("^[[:punct:]+]", x)]
</code></pre>
<p>which only matches punctuation at first character with another punctuation character</p> | 1 |
PHP Regex: Difference between \s and \\s | <p>I understand \s is used to match white space character, but sometimes I see
"\\s" is used in preg match and working fine. For eg:</p>
<pre><code>if (preg_match("/\\s/", $myString)) {
// there are spaces
}
if (preg_match("/\s/", $myString)) {
// there are spaces
}
</code></pre>
<p>Is there any difference between above two code blocks?</p> | 1 |
No cipher suites in common in Jetty 9 SSL Configuration | <p>I have spent the better part of the day on this and so far have been unable to get Jetty 9 configured to serve over HTTPS correctly. This is only for development purposes so I have generated a keystore file that I am attempting to use with Jetty.</p>
<p>I am generating the certificate like this:</p>
<pre><code>keytool -keystore keystore -alias jetty -genkey -keyalg RSA
</code></pre>
<p>This is from the Jetty instructions at <a href="https://www.eclipse.org/jetty/documentation/current/configuring-ssl.html" rel="nofollow">https://www.eclipse.org/jetty/documentation/current/configuring-ssl.html</a>.</p>
<p>Output from <code>mvn -X jetty:run</code> when I start the server showing the cipher suites:</p>
<pre><code>[DEBUG] STARTED @7821ms org.eclipse.jetty.server.ServerConnector$ServerConnectorManager@677b8e13
[DEBUG] starting SslConnectionFactory@4158debd{SSL->http/1.1}
[DEBUG] run org.eclipse.jetty.io.ManagedSelector@1b8d20e6 id=3 keys=0 selected=0
[DEBUG] EPR Idle/org.eclipse.jetty.io.ManagedSelector$SelectorProducer@3519e9bc execute
[DEBUG] EPR Prod/org.eclipse.jetty.io.ManagedSelector$SelectorProducer@3519e9bc produce enter
[DEBUG] EPR Prod/org.eclipse.jetty.io.ManagedSelector$SelectorProducer@3519e9bc producing
[DEBUG] Selector loop waiting on select
[DEBUG] starting SslContextFactory@af78c87(null,null)
[DEBUG] Selected Protocols [TLSv1, TLSv1.1, TLSv1.2] of [SSLv2Hello, SSLv3, TLSv1, TLSv1.1, TLSv1.2]
[DEBUG] Selected Ciphers [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV] of [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, TLS_DH_anon_WITH_AES_128_GCM_SHA256, TLS_DH_anon_WITH_AES_128_CBC_SHA256, TLS_ECDH_anon_WITH_AES_128_CBC_SHA, TLS_DH_anon_WITH_AES_128_CBC_SHA, TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, SSL_DH_anon_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_anon_WITH_RC4_128_SHA, SSL_DH_anon_WITH_RC4_128_MD5, SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_DH_anon_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_DH_anon_EXPORT_WITH_RC4_40_MD5, TLS_RSA_WITH_NULL_SHA256, TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_RSA_WITH_NULL_SHA, TLS_ECDH_ECDSA_WITH_NULL_SHA, TLS_ECDH_RSA_WITH_NULL_SHA, TLS_ECDH_anon_WITH_NULL_SHA, SSL_RSA_WITH_NULL_MD5, TLS_KRB5_WITH_3DES_EDE_CBC_SHA, TLS_KRB5_WITH_3DES_EDE_CBC_MD5, TLS_KRB5_WITH_RC4_128_SHA, TLS_KRB5_WITH_RC4_128_MD5, TLS_KRB5_WITH_DES_CBC_SHA, TLS_KRB5_WITH_DES_CBC_MD5, TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA, TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5, TLS_KRB5_EXPORT_WITH_RC4_40_SHA, TLS_KRB5_EXPORT_WITH_RC4_40_MD5]
</code></pre>
<p>Output from <code>mvn -X jetty:run</code> from when I attempt to make a request to <a href="https://localhost:8443" rel="nofollow">https://localhost:8443</a>:</p>
<pre><code>[DEBUG] Selector loop woken up from select, 0/0 selected
[DEBUG] EPR Prod/org.eclipse.jetty.io.ManagedSelector$SelectorProducer@5235a7a1 produced org.eclipse.jetty.io.ManagedSelector$2@7ed55f41
[DEBUG] EPR Pend/org.eclipse.jetty.io.ManagedSelector$SelectorProducer@5235a7a1 dispatch
[DEBUG] queue EPR Pend/org.eclipse.jetty.io.ManagedSelector$SelectorProducer@5235a7a1
[DEBUG] EPR Pend/org.eclipse.jetty.io.ManagedSelector$SelectorProducer@5235a7a1 run org.eclipse.jetty.io.ManagedSelector$2@7ed55f41
[DEBUG] run EPR Pend/org.eclipse.jetty.io.ManagedSelector$SelectorProducer@5235a7a1
javax.net.ssl.SSLHandshakeException: no cipher suites in common
at sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1431)
at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:535)
at sun.security.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:813)
at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:781)
at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:624)
at org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint.fill(SslConnection.java:509)
at org.eclipse.jetty.server.HttpConnection.fillRequestBuffer(HttpConnection.java:313)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:223)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:261)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.ssl.SslConnection.onFillable(SslConnection.java:192)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:261)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.net.ssl.SSLHandshakeException: no cipher suites in common
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1666)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:304)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:292)
at sun.security.ssl.ServerHandshaker.chooseCipherSuite(ServerHandshaker.java:1014)
at sun.security.ssl.ServerHandshaker.clientHello(ServerHandshaker.java:731)
at sun.security.ssl.ServerHandshaker.processMessage(ServerHandshaker.java:213)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker$1.run(Handshaker.java:919)
at sun.security.ssl.Handshaker$1.run(Handshaker.java:916)
at java.security.AccessController.doPrivileged(Native Method)
at sun.security.ssl.Handshaker$DelegatedTask.run(Handshaker.java:1369)
at org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint.fill(SslConnection.java:613)
... 13 more
</code></pre>
<p>Here is the relevant section from my <code>pom.xml</code>:</p>
<pre><code>...
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.6.v20151106</version>
<configuration>
<jettyXml>src/main/resources/jetty.xml,src/main/resources/jetty-
ssl.xml,src/main/resources/jetty-https.xml,src/main/resources/jetty-ssl-context.xml</jettyXml>
</configuration>
</plugin>
...
</code></pre>
<p>Here is my <code>jetty.xml</code>:</p>
<pre><code><?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
<Set name="secureScheme">https</Set>
<Set name="securePort"><Property name="jetty.secure.port" default="8443" /></Set>
<Set name="outputBufferSize">32768</Set>
<Set name="requestHeaderSize">8192</Set>
<Set name="responseHeaderSize">8192</Set>
<Set name="sendServerVersion">true</Set>
<Set name="sendDateHeader">false</Set>
<Set name="headerCacheSize">512</Set>
</New>
</Configure>
</code></pre>
<p><code>jetty-ssl.xml</code></p>
<pre><code><?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">
<!-- ============================================================= -->
<!-- Base SSL configuration -->
<!-- This configuration needs to be used together with 1 or more -->
<!-- of jetty-https.xml or jetty-http2.xml -->
<!-- ============================================================= -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<!-- =========================================================== -->
<!-- Add a SSL Connector with no protocol factories -->
<!-- =========================================================== -->
<Call name="addConnector">
<Arg>
<New id="sslConnector" class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="acceptors" type="int"><Property name="jetty.ssl.acceptors" deprecated="ssl.acceptors" default="-1"/></Arg>
<Arg name="selectors" type="int"><Property name="jetty.ssl.selectors" deprecated="ssl.selectors" default="-1"/></Arg>
<Arg name="factories">
<Array type="org.eclipse.jetty.server.ConnectionFactory">
<!-- uncomment to support proxy protocol
<Item>
<New class="org.eclipse.jetty.server.ProxyConnectionFactory"/>
</Item>-->
</Array>
</Arg>
<Set name="host"><Property name="jetty.ssl.host" deprecated="jetty.host" /></Set>
<Set name="port"><Property name="jetty.ssl.port" deprecated="ssl.port" default="8443" /></Set>
<Set name="idleTimeout"><Property name="jetty.ssl.idleTimeout" deprecated="ssl.timeout" default="30000"/></Set>
<Set name="soLingerTime"><Property name="jetty.ssl.soLingerTime" deprecated="ssl.soLingerTime" default="-1"/></Set>
<Set name="acceptorPriorityDelta"><Property name="jetty.ssl.acceptorPriorityDelta" deprecated="ssl.acceptorPriorityDelta" default="0"/></Set>
<Set name="acceptQueueSize"><Property name="jetty.ssl.acceptQueueSize" deprecated="ssl.acceptQueueSize" default="0"/></Set>
</New>
</Arg>
</Call>
<!-- =========================================================== -->
<!-- Create a TLS specific HttpConfiguration based on the -->
<!-- common HttpConfiguration defined in jetty.xml -->
<!-- Add a SecureRequestCustomizer to extract certificate and -->
<!-- session information -->
<!-- =========================================================== -->
<New id="sslHttpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
<Arg><Ref refid="httpConfig"/></Arg>
<Call name="addCustomizer">
<Arg>
<New class="org.eclipse.jetty.server.SecureRequestCustomizer">
<Arg type="boolean"><Property name="jetty.ssl.sniHostCheck" default="true"/></Arg>
</New>
</Arg>
</Call>
</New>
</Configure>
</code></pre>
<p><code>jetty-https.xml</code></p>
<pre><code><?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">
<!-- ============================================================= -->
<!-- Configure a HTTPS connector. -->
<!-- This configuration must be used in conjunction with jetty.xml -->
<!-- and jetty-ssl.xml. -->
<!-- ============================================================= -->
<Configure id="sslConnector" class="org.eclipse.jetty.server.ServerConnector">
<Call name="addIfAbsentConnectionFactory">
<Arg>
<New class="org.eclipse.jetty.server.SslConnectionFactory">
<Arg name="next">http/1.1</Arg>
<Arg name="sslContextFactory"><Ref refid="sslContextFactory"/></Arg>
</New>
</Arg>
</Call>
<Call name="addConnectionFactory">
<Arg>
<New class="org.eclipse.jetty.server.HttpConnectionFactory">
<Arg name="config"><Ref refid="sslHttpConfig" /></Arg>
</New>
</Arg>
</Call>
</Configure>
</code></pre>
<p><code>jetty-ssl-context.xml</code></p>
<pre><code><?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">
<!-- ============================================================= -->
<!-- SSL ContextFactory configuration -->
<!-- ============================================================= -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<New id="sslContextFactory" class="org.eclipse.jetty.util.ssl.SslContextFactory">
<Set name="KeyStorePath"><Property name="jetty.home" default="." />/src/main/resources/keystore</Set>
<Set name="KeyStorePassword">password</Set>
<Set name="KeyManagerPassword">password</Set>
<Set name="TrustStorePath"><Property name="jetty.home" default="." />/src/main/resources/keystore</Set>
<Set name="TrustStorePassword">password</Set>
<Set name="IncludeCipherSuites">
<Array type="String">
<Item>TLS_DHE_RSA.*</Item>
<Item>TLS_ECDHE.*</Item>
</Array>
</Set>
<Set name="ExcludeCipherSuites">
<Array type="String">
<Item>.*NULL.*</Item>
<Item>.*RC4.*</Item>
<Item>.*MD5.*</Item>
<Item>.*DES.*</Item>
<Item>.*DSS.*</Item>
</Array>
</Set>
</New>
</Configure>
</code></pre> | 1 |
XML Digital Signature: How is the digest value calculated for same-document reference URIs? | <p>My XML digital signature has the following excerpts: </p>
<pre><code> <Signature Id="idPackageSignature" xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#idOfficeObject" Type="http://www.w3.org/2000/09/xmldsig#Object">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>ofqf9+Tj0qTkkExCEOwFz0V4aNo=</DigestValue>
</Reference>
</SignedInfo>
<Object Id="idOfficeObject"><SignatureProperties><SignatureProperty Id="idOfficeV1Details" Target="#idPackageSignature"><SignatureInfoV1 xmlns="http://schemas.microsoft.com/office/2006/digsig"><SetupID/><SignatureText/><SignatureImage/><SignatureComments>test</SignatureComments><WindowsVersion>6.1</WindowsVersion><OfficeVersion>14.0</OfficeVersion><ApplicationVersion>14.0</ApplicationVersion><Monitors>1</Monitors><HorizontalResolution>1920</HorizontalResolution><VerticalResolution>1200</VerticalResolution><ColorDepth>32</ColorDepth><SignatureProviderId>{00000000-0000-0000-0000-000000000000}</SignatureProviderId><SignatureProviderUrl/><SignatureProviderDetails>9</SignatureProviderDetails><ManifestHashAlgorithm>http://www.w3.org/2000/09/xmldsig#sha1</ManifestHashAlgorithm><SignatureType>1</SignatureType></SignatureInfoV1></SignatureProperty></SignatureProperties></Object>
</code></pre>
<p>The referenced Object element is supposed to have the digest value <strong>ofqf9+Tj0qTkkExCEOwFz0V4aNo=</strong>. I canonicalize the Object element, and get the following output, which seems correct to me:</p>
<pre><code><Object Id="idOfficeObject"><SignatureProperties><SignatureProperty Id="idOfficeV1Details" Target="#idPackageSignature"><SignatureInfoV1 xmlns="http://schemas.microsoft.com/office/2006/digsig"><SetupID></SetupID><SignatureText></SignatureText><SignatureImage></SignatureImage><SignatureComments>test</SignatureComments><WindowsVersion>6.1</WindowsVersion><OfficeVersion>14.0</OfficeVersion><ApplicationVersion>14.0</ApplicationVersion><Monitors>1</Monitors><HorizontalResolution>1920</HorizontalResolution><VerticalResolution>1200</VerticalResolution><ColorDepth>32</ColorDepth><SignatureProviderId>{00000000-0000-0000-0000-000000000000}</SignatureProviderId><SignatureProviderUrl></SignatureProviderUrl><SignatureProviderDetails>9</SignatureProviderDetails><ManifestHashAlgorithm>http://www.w3.org/2000/09/xmldsig#sha1</ManifestHashAlgorithm><SignatureType>1</SignatureType></SignatureInfoV1></SignatureProperty></SignatureProperties></Object>
</code></pre>
<p>I store it in a file 'inputxml', and try to get the base64 encoded version of the sha1 digest using the following command:</p>
<pre><code>% shasum inputxml | cut -f 1 -d ' ' | xxd -r -p | base64
/zTi8HGHX9X+csjULYLt6FLrm3g=
</code></pre>
<p>The computed digest value does not match what is in the XML signature. What am I doing wrong? I have tried multiple various methods and tweaks, but cannot get the correct digest value. </p>
<p>Note: The XML Signature verifies correctly. So the value is correct, but I am missing some step or detail. Thanks for your help. Please let me know how can I elaborate or clarify my question further if it is not very clear.</p> | 1 |
Speed up structured NumPy array | <p><code>NumPy</code> arrays are great for both performance and easy use (easier slicing, indexing than lists).</p>
<p>I try to construct a data container out of a <code>NumPy structured array</code> instead of <code>dict</code> of <code>NumPy arrays</code>. The problem is the performance is much worse. About 2.5 times as bad using homogeneous data and about 32 times for heterogeneous data (I'm talking about <code>NumPy</code> datatypes). </p>
<p>Is there a way to speed the structured array's up? I tried changing the memoryorder from 'c' to 'f' but this didn't have any affect.</p>
<p>Here's my profiling code:</p>
<pre><code>import time
import numpy as np
NP_SIZE = 100000
N_REP = 100
np_homo = np.zeros(NP_SIZE, dtype=[('a', np.double), ('b', np.double)], order='c')
np_hetro = np.zeros(NP_SIZE, dtype=[('a', np.double), ('b', np.int32)], order='c')
dict_homo = {'a': np.zeros(NP_SIZE), 'b': np.zeros(NP_SIZE)}
dict_hetro = {'a': np.zeros(NP_SIZE), 'b': np.zeros(NP_SIZE, np.int32)}
t0 = time.time()
for i in range(N_REP):
np_homo['a'] += i
t1 = time.time()
for i in range(N_REP):
np_hetro['a'] += i
t2 = time.time()
for i in range(N_REP):
dict_homo['a'] += i
t3 = time.time()
for i in range(N_REP):
dict_hetro['a'] += i
t4 = time.time()
print('Homogeneous Numpy struct array took {:.4f}s'.format(t1 - t0))
print('Hetoregeneous Numpy struct array took {:.4f}s'.format(t2 - t1))
print('Homogeneous Dict of numpy arrays took {:.4f}s'.format(t3 - t2))
print('Hetoregeneous Dict of numpy arrays took {:.4f}s'.format(t4 - t3))
</code></pre>
<p><strong>Edit</strong>: Forgot to put my timing numbers:</p>
<pre><code>Homogenious Numpy struct array took 0.0101s
Hetoregenious Numpy struct array took 0.1367s
Homogenious Dict of numpy arrays took 0.0042s
Hetoregenious Dict of numpy arrays took 0.0042s
</code></pre>
<p><strong>Edit2</strong>: I added some additional test case with the timit module:</p>
<pre><code>import numpy as np
import timeit
NP_SIZE = 1000000
def time(data, txt, n_rep=1000):
def intern():
data['a'] += 1
time = timeit.timeit(intern, number=n_rep)
print('{} {:.4f}'.format(txt, time))
np_homo = np.zeros(NP_SIZE, dtype=[('a', np.double), ('b', np.double)], order='c')
np_hetro = np.zeros(NP_SIZE, dtype=[('a', np.double), ('b', np.int32)], order='c')
dict_homo = {'a': np.zeros(NP_SIZE), 'b': np.zeros(NP_SIZE)}
dict_hetro = {'a': np.zeros(NP_SIZE), 'b': np.zeros(NP_SIZE, np.int32)}
time(np_homo, 'Homogeneous Numpy struct array')
time(np_hetro, 'Hetoregeneous Numpy struct array')
time(dict_homo, 'Homogeneous Dict of numpy arrays')
time(dict_hetro, 'Hetoregeneous Dict of numpy arrays')
</code></pre>
<p>results in:</p>
<pre><code>Homogeneous Numpy struct array 0.7989
Hetoregeneous Numpy struct array 13.5253
Homogeneous Dict of numpy arrays 0.3750
Hetoregeneous Dict of numpy arrays 0.3744
</code></pre>
<p>The ratios between the runs seem reasonably stable. Using both methods and a different size of the array.</p>
<p>For the offcase it matters:
python: 3.4
NumPy: 1.9.2</p> | 1 |
How to use "Got It" Button in Material ShowcaseView Library? | <p>I am using Material ShowcaseView <a href="https://github.com/deano2390/MaterialShowcaseView" rel="nofollow noreferrer">https://github.com/deano2390/MaterialShowcaseView</a>.
Now I am getting the view in my app by adding <strong>transparency to the PULL DOWN TO REFRESH Activity</strong>. But when I click the <strong>"Got It"</strong> in <strong>Image1</strong>,<strong>the transparency was gone but the image(Arrow) which is marked as Red in Image2 is there.</strong></p>
<p><a href="https://i.stack.imgur.com/zI4RD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zI4RD.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/cfZ6T.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cfZ6T.jpg" alt="enter image description here"></a></p>
<p><strong>I need to go the next activity when I click "Got it" or I need to replace this "Got it" text into the Button View.How do I do this? Please help me...</strong></p>
<p>I need the output like this..Button over the transparent layer.</p>
<p><a href="https://i.stack.imgur.com/jd4kb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jd4kb.png" alt="enter image description here"></a></p> | 1 |
AssertionError: incompatible sizes: argument 'height' must be length 5 or scalar | <p>I have a json file which i am sorting in reverse using natsort and then i want to plot a graph of the "Speed" but i am getting an error. I have now included the JSON file here as well.</p>
<pre><code>"AssertionError: incompatible sizes: argument 'height' must be length 5 or scalar"
Traceback (most recent call last): File "new.py", line 71, in <module> visualize_type(sorted_waypoints) File "new.py", line 45, in visualize_type plt.bar(xlocations, counter.values()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/pyplot.py", line 2515, in bar ret = ax.bar(left, height, width=width, bottom=bottom, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 4999, in bar nbars)
</code></pre>
<p>Code:</p>
<pre><code>import json
import datetime
import pprint
from operator import itemgetter
import natsort
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
#path to gps data file in json format.
data_file = "waypoints.json"
def speed_ans(self, data_file):
pass
def visualize_type(output):
"""Visualize data by category in a bar graph"""
#This returns a dict where it sums the total per Category.
counter = Counter(item["Speed"] for item in output)
# Set the labels which are based on the keys of our counter.
labels = tuple("Speed")
# Set where the labels hit the x-axis
xlocations = np.arange(len(labels)) + 0.5
# Width of each bar
width = 0.5
# Assign data to a bar plot
plt.bar(xlocations, counter.values(), width=width)
# Assign labels and tick location to x- and y-axis
plt.xticks(xlocations + width / 2, labels, rotation=90)
plt.yticks(range(0, max(counter.values()), 5))
# Give some more room so the labels aren't cut off in the graph
plt.subplots_adjust(bottom=0.4)
# Make the overall graph/figure larger
plt.rcParams['figure.figsize'] = 12, 8
# Save the graph!
plt.savefig("Graph.png")
plt.clf()
if __name__ == '__main__':
with open(data_file) as f:
waypoints = json.load(f)
sorted_waypoints = natsort.natsorted(waypoints, key=itemgetter(*['Speed']), reverse = True)
pprint.pprint(sorted_waypoints)
visualize_type(sorted_waypoints)
</code></pre>
<p>waypoints.json file :</p>
<pre><code>[{
"Latitude": 1.282143333,
"Timestamp": 1434368770,
"Speed": 7.696,
"Longitude": 103.850785
}, {
"Latitude": 1.282205,
"Timestamp": 1434368771,
"Speed": 7.233,
"Longitude": 103.850806667
}, {
"Latitude": 1.282205,
"Timestamp": 1434368772,
"Speed": 7.233,
"Longitude": 103.850806667
}, {
"Latitude": 1.282205,
"Timestamp": 1434368773,
"Speed": 7.444,
"Longitude": 103.850806667
}, {
"Latitude": 1.282261667,
"Timestamp": 1434368774,
"Speed": 6.933,
"Longitude": 103.850833333
}]
</code></pre> | 1 |
Swift: UIView appear in UITableView cell | <p>Im having an issue putting a UIView that I created in a specific UITableView cell. Here is my code:</p>
<pre><code>class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//MARK : Properties
var tableView = UITableView()
var items: [String] = ["Age", "Gender", "Smoking Hx", "Occup. -Ag", "Family Hx", "Chronic Lung Disease Radiology", "Chronic Lung Disease Hx", "Nodule Border", "Nodule Location", "Satellite Lesions", "Nodule Pattern Cavity", "Nodule Size"]
var navigationBar = NavigationBar()
var gender = GenderView()
var maleIcon = MaleIconView()
override func viewDidLoad() {
super.viewDidLoad()
//Create TableView
tableView.frame = CGRectMake(0, self.view.bounds.height * 0.097, self.view.bounds.width,
self.view.bounds.height - self.view.bounds.height * 0.097);
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
//Create Navigation Bar with custom class
self.navigationBar = NavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height * 0.097))
self.view.addSubview(navigationBar)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
//Cell wont turn grey when selected
cell.selectionStyle = UITableViewCellSelectionStyle.None
//Want to add UIView male Icon in first row
if(indexPath.row == 0){
maleIcon = MaleIconView(frame: CGRect(x: 0, y: 0, width: 55, height: 55))
maleIcon.center.x = cell.center.x + cell.center.x * 0.5
maleIcon.center.y = cell.contentView.center.y
maleIcon.layer.cornerRadius = 0.5 * maleIcon.bounds.size.width
//maleIcon.layer.borderWidth = 3.0
cell.addSubview(maleIcon)
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return self.view.bounds.height * 0.15
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
}
}
</code></pre>
<p>Maybe the issue exists within the MaleIconView()? Here is the code to that:</p>
<pre><code>class MaleIconView: UIView {
var maleView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
self.frame = frame
setUpView()
}
func setUpView(){
maleView.frame = CGRectMake(0, 0, self.bounds.width, self.bounds.height)
maleView.alpha = 1
maleView.backgroundColor = UIColor.blackColor()
maleView.layer.cornerRadius = 0.5 * maleView.bounds.size.width
self.addSubview(maleView)
}
func hide(){
self.removeFromSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
</code></pre>
<p>Im trying to get the UIView to appear on the right side of the cell 0. There is also this issue where the indexPath's are all off, i think this could be of some issue to why the UIView appears in multiple cells. Thank you in advance!</p> | 1 |
Pass userform control to sub | <p>I've got two subs: cmdSafe and checkTime. I want to call subCheck and pass a userform control.</p>
<pre><code>Private Sub cmdSafe_click()
Call checkTime(ufTimes.txtBegin)
End Sub
Sub checkTime(cntrl as Control)
'Do something
End sub
</code></pre>
<p>In this case, I'm getting an error when it tries to call the sub. <code>Run-time error 424: Object required.</code>
I went to check ufTimes.txtBegin, but this gives the value of the textbox, <code>15</code>.</p>
<p>I hoped to be able to solve this by changing the first sub to the following:</p>
<pre><code>Private Sub cmdSafe_click()
Dim ctl as control
ctl = ufTimes.txtBegin
Call checkTime(ufTimes.txtBegin)
End Sub
</code></pre>
<p>This gave me another error (<code>Run-time error 91: Object variable or With block not set</code>) on the line <code>ctl=ufTimes.txtBegin</code>, probably because it's trying to set ctl to be a value. How do I solve this? I want to pass a control through, and it should also be able to be a ComboBox for example</p> | 1 |
currentTime() in video.js | <p>The following is my code which is not working. Any help would be appreciated.</p>
<pre><code>var myPlayer;
videojs("example_video_1").ready(function(){
myPlayer = this;
if(myPlayer.currentTime()>3)
{
alert("STARTED");
});
});
</code></pre> | 1 |
How to display error message in view page using PHP | <p>I need to display the error message using php.I am explaining my code below.</p>
<blockquote>
<p>addcomplain.php:</p>
</blockquote>
<pre><code><div style="color:#F00; text-align:center;"><?php echo $error?></div>
<form name="billdata" id="billdata" enctype="multipart/form-data" method="POST" onSubmit="javascript:return checkForm();" action="complain.php">
</form>
</code></pre>
<p>Suppose i have a form like above and when i submit the below file is called.</p>
<blockquote>
<p>complain.php:</p>
</blockquote>
<pre><code>$sql="SELECT * FROM medilink_complain WHERE email='".$email."'";
$selres = mysqli_query($con,$sql);
if(mysqli_num_rows($selres ) > 0)
{
$error = "Email Id already exists!";
}
</code></pre>
<p>when the above error will come,i need it should display just above the form.In my case i am not getting anything.Please help me to resolve this issue.</p> | 1 |
Why am I getting a 403 error when attempting to access my google cloud bucket? | <p>I've have a bucket at a url something like: <a href="https://console.developers.google.com/storage/browser/gdfp-1234/" rel="nofollow">https://console.developers.google.com/storage/browser/gdfp-1234/</a></p>
<p>Then I created a project, named something like 'api-required' so I could generate credentials at /apis/credentials?project=api-required</p>
<p>Then, I generated a json service account key with the <code>new_credentials</code> button at <code>/api/credentials/</code>. I saved the json object I downloaded to a file that I pointed my environment variable <code>GOOGLE_APPLICATION_CREDENTIALS</code> at.</p>
<p>Now, I'm building an application in python. This code:</p>
<pre><code>from gcloud import storage
gcs = storage.Client(project='my client n')
bucket = gcs.get_bucket(bucket_name)
</code></pre>
<p>Gives me a <code>403 Forbidden</code> error.</p>
<p><code>Google Cloud Storage JSON API</code> is in the Enabled API's list in the API Manager. This seems to cover everything in the docs.</p>
<p>I've been pouring over the docs, and cannot for the life of me figure out what I am doing wrong. Any help figuring this out would be greatly appreciated, thanks!</p>
<p>EDIT:<br>
Here's the traceback:</p>
<pre><code>/Users/asdf/.virtualenvs/analytics_pipeline/lib/python2.7/site-packages/gcloud/storage/client.pyc in get_bucket(self, bucket_name)
165 """
166 bucket = Bucket(self, name=bucket_name)
--> 167 bucket.reload(client=self)
168 return bucket
169
/Users/asdf/.virtualenvs/analytics_pipeline/lib/python2.7/site-packages/gcloud/storage/_helpers.pyc in reload(self, client)
75 api_response = client.connection.api_request(
76 method='GET', path=self.path, query_params=query_params,
---> 77 _target_object=self)
78 self._set_properties(api_response)
79
/Users/asdf/.virtualenvs/analytics_pipeline/lib/python2.7/site-packages/gcloud/connection.pyc in api_request(self, method, path, query_params, data, content_type, api_base_url, api_version, expect_json, _target_object)
335 if not 200 <= response.status < 300:
336 raise make_exception(response, content,
--> 337 error_info=method + ' ' + url)
338
339 string_or_bytes = (six.binary_type, six.text_type)
</code></pre> | 1 |
C++ typedef map error | <p>In visual studio 2013 ultimate:<br /></p>
<p>a)</p>
<pre><code>using namespace std;
typedef map<string, double> my_set;
</code></pre>
<blockquote>
<p>=> error: map is not a template</p>
</blockquote>
<p>b)</p>
<pre><code>typedef std::map<string, double> my_set;
</code></pre>
<blockquote>
<p>=> error: qualified name is not allowed</p>
</blockquote>
<p>a or b is in file foo.h, both versions doesn't work. What am I doing wrong?
(Yes, spent some time googling => no result, c++ is strange language)</p> | 1 |
Accessing view of a NumPy array using the C API | <p>In a Python extension module I've written in C++, I use the following snippet of code to convert a NumPy array into an <a href="http://arma.sourceforge.net/" rel="nofollow noreferrer">Armadillo</a> array for use in the C++ portion of the code:</p>
<pre class="lang-cpp prettyprint-override"><code>static arma::mat convertPyArrayToArma(PyArrayObject* pyarr, int nrows, int ncols)
{
// Check if the dimensions are what I expect.
if (!checkPyArrayDimensions(pyarr, nrows, ncols)) throw WrongDimensions();
const std::vector<int> dims = getPyArrayDimensions(pyarr); // Gets the dimensions using the API
PyArray_Descr* reqDescr = PyArray_DescrFromType(NPY_DOUBLE);
if (reqDescr == NULL) throw std::bad_alloc();
// Convert the array to Fortran-ordering as required by Armadillo
PyArrayObject* cleanArr = (PyArrayObject*)PyArray_FromArray(pyarr, reqDescr,
NPY_ARRAY_FARRAY);
if (cleanArr == NULL) throw std::bad_alloc();
reqDescr = NULL; // The new reference from DescrFromType was stolen by FromArray
double* dataPtr = static_cast<double*>(PyArray_DATA(cleanArr));
arma::mat result (dataPtr, dims[0], dims[1], true); // this copies the data from cleanArr
Py_DECREF(cleanArr);
return result;
}
</code></pre>
<p>The problem is that when I pass this a <em>view</em> of a NumPy array (i.e. <code>my_array[:, 3]</code>), it doesn't seem to handle the strides of the underlying C array correctly. Based on the output, it seems like the array <code>pyarr</code> received by the function is actually the full base array, and not the view (or at least when I access the data using <code>PyArray_DATA</code>, I seem to be getting a pointer to the full base array). If I instead pass this function a copy of the view (i.e. <code>my_array[:, 3].copy()</code>), it works as expected, but I don't want to have to remember to do that every time.</p>
<p>So, is there a way to make <code>PyArray_FromArray</code> copy only the slice of the matrix I want? I tried using the flag <code>NPY_ARRAY_ENSURECOPY</code>, but that didn't help.</p>
<h1>Edit 1</h1>
<p>As suggested in the comments, here is a full working example:</p>
<p>In file <code>example.cpp</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>#define NPY_NO_DEPRECATED_API NPY_1_9_API_VERSION
extern "C" {
#include <Python.h>
#include <numpy/arrayobject.h>
}
#include <exception>
#include <cassert>
#include <string>
#include <type_traits>
#include <map>
#include <vector>
#include <armadillo>
class WrongDimensions : public std::exception
{
public:
WrongDimensions() {}
const char* what() const noexcept { return msg.c_str(); }
private:
std::string msg = "The dimensions were incorrect";
};
class NotImplemented : public std::exception
{
public:
NotImplemented() {}
const char* what() const noexcept { return msg.c_str(); }
private:
std::string msg = "Not implemented";
};
class BadArrayLayout : public std::exception
{
public:
BadArrayLayout() {}
const char* what() const noexcept { return msg.c_str(); }
private:
std::string msg = "The matrix was not contiguous";
};
static const std::vector<npy_intp> getPyArrayDimensions(PyArrayObject* pyarr)
{
npy_intp ndims = PyArray_NDIM(pyarr);
npy_intp* dims = PyArray_SHAPE(pyarr);
std::vector<npy_intp> result;
for (int i = 0; i < ndims; i++) {
result.push_back(dims[i]);
}
return result;
}
/* Checks the dimensions of the given array. Pass -1 for either dimension to say you don't
* care what the size is in that dimension. Pass dimensions (X, 1) for a vector.
*/
static bool checkPyArrayDimensions(PyArrayObject* pyarr, const npy_intp dim0, const npy_intp dim1)
{
const auto dims = getPyArrayDimensions(pyarr);
assert(dims.size() <= 2 && dims.size() > 0);
if (dims.size() == 1) {
return (dims[0] == dim0 || dim0 == -1) && (dim1 == 1 || dim1 == -1);
}
else {
return (dims[0] == dim0 || dim0 == -1) && (dims[1] == dim1 || dim1 == -1);
}
}
template<typename outT>
static arma::Mat<outT> convertPyArrayToArma(PyArrayObject* pyarr, int nrows, int ncols)
{
if (!checkPyArrayDimensions(pyarr, nrows, ncols)) throw WrongDimensions();
int arrTypeCode;
if (std::is_same<outT, uint16_t>::value) {
arrTypeCode = NPY_UINT16;
}
else if (std::is_same<outT, double>::value) {
arrTypeCode = NPY_DOUBLE;
}
else {
throw NotImplemented();
}
const auto dims = getPyArrayDimensions(pyarr);
if (dims.size() == 1) {
outT* dataPtr = static_cast<outT*>(PyArray_DATA(pyarr));
return arma::Col<outT>(dataPtr, dims[0], true);
}
else {
PyArray_Descr* reqDescr = PyArray_DescrFromType(arrTypeCode);
if (reqDescr == NULL) throw std::bad_alloc();
PyArrayObject* cleanArr = (PyArrayObject*)PyArray_FromArray(pyarr, reqDescr, NPY_ARRAY_FARRAY);
if (cleanArr == NULL) throw std::bad_alloc();
reqDescr = NULL; // The new reference from DescrFromType was stolen by FromArray
outT* dataPtr = static_cast<outT*>(PyArray_DATA(cleanArr));
arma::Mat<outT> result (dataPtr, dims[0], dims[1], true); // this copies the data from cleanArr
Py_DECREF(cleanArr);
return result;
}
}
static PyObject* convertArmaToPyArray(const arma::mat& matrix)
{
npy_intp ndim = matrix.is_colvec() ? 1 : 2;
npy_intp nRows = static_cast<npy_intp>(matrix.n_rows); // NOTE: This narrows the integer
npy_intp nCols = static_cast<npy_intp>(matrix.n_cols);
npy_intp dims[2] = {nRows, nCols};
PyObject* result = PyArray_SimpleNew(ndim, dims, NPY_DOUBLE);
if (result == NULL) throw std::bad_alloc();
double* resultDataPtr = static_cast<double*>(PyArray_DATA((PyArrayObject*)result));
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nCols; j++) {
resultDataPtr[i * nCols + j] = matrix(i, j);
}
}
return result;
}
extern "C" {
// An example function that takes a NumPy array and converts it to
// an arma::mat and back. This should return the array unchanged.
static PyObject* example_testFunction(PyObject* self, PyObject* args)
{
PyArrayObject* myArray = NULL;
if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &myArray)) {
return NULL;
}
PyObject* output = NULL;
try {
arma::mat myMat = convertPyArrayToArma<double>(myArray, -1, -1);
output = convertArmaToPyArray(myMat);
}
catch (const std::bad_alloc&) {
PyErr_NoMemory();
Py_XDECREF(output);
return NULL;
}
catch (const std::exception& err) {
PyErr_SetString(PyExc_RuntimeError, err.what());
Py_XDECREF(output);
return NULL;
}
return output;
}
static PyMethodDef example_methods[] =
{
{"test_function", example_testFunction, METH_VARARGS, "A test function"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef example_module = {
PyModuleDef_HEAD_INIT,
"example", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
example_methods
};
PyMODINIT_FUNC
PyInit_example(void)
{
import_array();
PyObject* m = PyModule_Create(&example_module);
if (m == NULL) return NULL;
return m;
}
}
</code></pre>
<p>And <code>setup.py</code> for compiling:</p>
<pre><code>from setuptools import setup, Extension
import numpy as np
example_module = Extension(
'example',
include_dirs=[np.get_include(), '/usr/local/include'],
libraries=['armadillo'],
library_dirs=['/usr/local/lib'],
sources=['example.cpp'],
language='c++',
extra_compile_args=['-std=c++11', '-mmacosx-version-min=10.10'],
)
setup(name='example',
ext_modules=[example_module],
)
</code></pre>
<p>Now assume we have the example array</p>
<pre><code>a = np.array([[ 1, 2, 3, 4, 5, 6],
[ 7, 8, 9,10,11,12],
[13,14,15,16,17,18]], dtype='float64')
</code></pre>
<p>The function seems to work fine for multidimensional slices like <code>a[:, :3]</code>, and it returns the matrix unaltered as I'd expect. But if I give it a single-dimensional slice, I get the wrong components unless I make a copy:</p>
<pre><code>>>> example.test_function(a[:, 3])
array([ 4., 5., 6.])
>>> example.test_function(a[:, 3].copy())
array([ 4., 10., 16.])
</code></pre> | 1 |
Marathon won't launch docker container | <p>I have a 1/1 master/slave setup with the slave having 8gb ram 8 cpus. I am trying to use marathon to deploy a docker container with 1gb mem and 1 cpu but it just hangs on waiting</p>
<p>I believe this is usually caused by marathon not getting the resources it wants for the task
when I look at my logs I see </p>
<blockquote>
<p>Sending 1 offers to framework
8bb1a298-cc23-426e-ad43-d440a2a560c4-0000 (marathon) at
[email protected]:52016 I0127
23:07:37.396546 2471 master.cpp:3297] Processing DECLINE call for
offers: [ 5271fcb3-4d77-4b12-af85-d94fd9172514-O127 ] for framework
8bb1a298-cc23-426e-ad43-d440a2a560c4-0000 (marathon) at
[email protected]:52016 I0127
23:07:37.396917 2466 hierarchical.cpp:744] Recovered cpus(<em>):6;
mem(</em>):5968; disk(<em>):156020; ports(</em>):[31000-31056, 31058-32000]
(total: cpus(<em>):8; mem(</em>):6992; disk(<em>):156020;
ports(</em>):[31000-32000], allocated: cpus(<em>):2; mem(</em>):1024;
ports(*):[31057-31057]) on slave
8bb1a298-cc23-426e-ad43-d440a2a560c4-S0 from framework
8bb1a298-cc23-426e-ad43-d440a2a560c4-0000</p>
</blockquote>
<p>so it looks like marathon is declining the offer it gets? the next line in the logs say that mesos is reclaiming the offered resources and what its reclaiming looks like its plenty for my task?</p>
<p>any ideas on how to trouble shoot this further?</p>
<p>edit: so got to dig into this a bit further and found the marathon logs. </p>
<p>Basically the deployment works if we do not enter any information for port mapping in the marathon docker section. The docker container deploys successfully and I can ping it successfully from its host but I cannot access it from elsewhere.</p>
<p>if we set the container port as 8081 (which is what the docker container exposes are its application listens on) we get further in the deployment process but the app within the container fails to build with error</p>
<blockquote>
<p>Error: listen EADDRINUSE :::8081
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)
at Server._listen2 (net.js:1234:14)
at listen (net.js:1270:10)
at Server.listen (net.js:1366:5)
at EventEmitter.listen (/usr/src/app/node_modules/express/lib/application.js:617:24)
at Object. (/usr/src/app/index.js:16:18)
at Module._compile (module.js:425:26)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:138:18)
at node.js:974:3</p>
</blockquote>
<p>So I think we are further along than we were but we are still having some port issues. I dont know why the container would build successfully on its own and with marathon with no port settings but not with marathon with port settings</p> | 1 |
Regular Expression for (P) xxx-xxx-xxxx * (F) xxx-xxx-xxxx | <p>I'm new at this. Trying to match this format:</p>
<pre><code>(P) xxx-xxx-xxxx • (F) xxx-xxx-xxxx
</code></pre>
<p>Tried this:</p>
<pre><code>/^ \(([^P)])\) \d{3}-\d{3}-\d{4} \u2022 \(([^F)])\) \d{3}-\d{3}-\d{4} *$/
</code></pre>
<p>Doesn't match. Any suggestions, please?</p> | 1 |
Why "Numeric overflow in expression" warning occurs | <p>Using intellij 15.0.3 + Java 8u65...</p>
<pre><code>lower = System.currentTimeMillis();
long upper = lower + 31536000000L; //add a year-ish
</code></pre>
<p>Works fine. But if I do:</p>
<pre><code>lower = System.currentTimeMillis();
long upper = lower + (1000L*60*60*24*365);
</code></pre>
<p>Intellij now gives a warning "Numeric overflow in expression". I'd understand if this were in fact true, and it was consistently warning over both expressions, but it's not.</p>
<p>Anyone know why the 2nd expression generates the warning? I'd rather have the breakdown this way than a number because it's easier for other devs on the project to understand what it's doing (though I suppose I could comment). Code still compiles obviously but I find warnings in my builds like an itch that I can't scratch.</p>
<p><strong>EDIT</strong>
Thanks for responses...
I think this is just a caching issue in Intellij... If I know copy/paste the above I don't get the warning. If I try to edit it after the paste 1 or 2 times out of 10 I get the warning popping in. </p> | 1 |
TypeError: array[i].call is not a function Error | <p>My code is : </p>
<pre><code>$(function() {
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setClearColor(0xdddddd);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMapSoft = true;
var axis = new THREE.AxisHelper(10);
scene.add(axis);
var grid = new THREE.GridHelper(50, 5);
var color = new THREE.Color("rgb(255,0,0)");
grid.setColors(color, 0x000000);
scene.add(grid);
var Ground_geometry = new THREE.BoxGeometry( 20, 0.1, 20 );
var Ground_material = new THREE.MeshPhongMaterial( {
color: 0xa0adaf,
shininess: 150,
specular: 0xffffff,
shading: THREE.SmoothShading
} );
var ground = new THREE.Mesh( Ground_geometry, Ground_material );
ground.scale.multiplyScalar( 3 );
ground.castShadow = false;
ground.receiveShadow = true;
scene.add( ground );
var ambient = new THREE.AmbientLight( 0x404040 );
scene.add( ambient );
spotLight = new THREE.SpotLight( 0xffffff );
spotLight.position.set( 10, 10, 15 );
spotLight.castShadow = true;
spotLight.shadowCameraNear = 8;
spotLight.shadowCameraFar = 30;
spotLight.shadowDarkness = 0.5;
spotLight.shadowCameraVisible = false;
spotLight.shadowMapWidth = 1024;
spotLight.shadowMapHeight = 1024;
spotLight.name = 'Spot Light';
scene.add( spotLight );
var controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.addEventListener( 'change', renderer );
var cubeGeometry = new THREE.BoxGeometry(5, 5, 5);
var cubeMaterial = new THREE.MeshPhongMaterial({
color: 0x456574 ,
shininess: 150,
specular: 0x222222,
shading: THREE.SmoothShading,
});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.position.x = 0;
cube.position.y = 0;
cube.position.z = 0;
scene.add(cube);
camera.position.x = 40;
camera.position.y = 40;
camera.position.z = 40;
camera.lookAt(scene.position);
renderer.render(scene, camera);
$("#webGL-container").append(renderer.domElement);
$(window).resize(function(){
SCREEN_WIDTH = window.innerWidth;
SCREEN_HEIGHT = window.innerHeight;
camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
camera.updateProjectionMatrix();
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
});
});
</code></pre>
<p>I am getting an error that says : TypeError: array[i].call is not a function
<br/> and is pointing to line 7484 of three.js library. <br/>
I have included the three.js library using:
<br/></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><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r73/three.js"></script></code></pre>
</div>
</div>
</p>
<p>So as you can see, its the v73 and I haven't touched the code. What could be the problem?</p>
<p>The error only comes after screen is clicked and then mouse pointer is dragged, so it must have got to do with that piece of code.</p> | 1 |
Integrate Angular2 into existing JSF project | <p>I'm looking into a new frontend framework for our company's JSF portal and am considering Angular2. I want to gradually migrate specific components on the page from JSF to Angular2 / REST. I don't want to use Angular2 for routing, at least not yet, and I don't want Angular to completely take over the page: some components will still need to be JSF for the foreseeable future.</p>
<p>Ideally, I'd wrap the content of the body of my JSF template with my Angular root component and project the HTML rendered by JSF into the root component, so that the JSF works as before and any Angular components within the template are picked up and can all communicate. E.g.:</p>
<pre><code><h:body>
<my-app>
<h:panelGroup styleClass="languageSwitcher">
<h:form>
<h:selectOneMenu value="#{languageHandler.language}" onchange="submit()">
<f:selectItem itemValue="en" itemLabel="English" />
<f:selectItem itemValue="nl" itemLabel="Dutch" />
</h:selectOneMenu>
</h:form>
</h:panelGroup>
<my-angular-component data-source="/rest/mydata"></my-angular-component>
</my-app>
<h:body>
</code></pre>
<p>With Angular 1, I'd use transclusion to make this work. However, as I understand it, <a href="https://github.com/angular/angular/issues/1858" rel="noreferrer">Angular 2 content projection does not work on the root component</a>, as the rendered HTML is not considered an Angular-compiled view.</p>
<p>I also considered using the root component's <code>templateURL</code> to get the JSF rendered page dynamically, but this is difficult to implement and doesn't play well with the numerous POST's that JSF does.</p>
<p>The only way I can think to make this work is to make a root component of each Angular component that replaces a bit of JSF, and on every page bootstrap all components I use. The drawback here is that I need a lot of boilerplate code to bootstrap every Angular component I build, and they don't have a shared root component so communication between them is limited. Furthermore, I'll need to configure each Angular component through attributes, but as these <a href="https://github.com/angular/angular/issues/1858" rel="noreferrer">aren't picked up automatically either</a> I'll need to add custom code to each component to pick them up:</p>
<pre><code>class MyAngularComponent {
constructor(public elementRef: ElementRef) {
this.dataSourceUrl = this.elementRef.nativeElement.getAttribute("data-source");
}
}
</code></pre>
<p>Then when I finally replace the entire frontend with Angular, I have to refactor each component again to use <code>@Input</code> in stead of retrieving information from attributes manually.</p>
<p>Does anybody know a better way to do this? Or do JSF and Angular2 simply not mix well?</p> | 1 |
How to convert Mat to byte array in android opencv? | <p>Step 1: I was converted Mat to byte array using below method</p>
<pre><code>MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".png", mRgba, matOfByte);
byteArray = matOfByte.toArray();
</code></pre>
<p>its efficiently converted byte array values. But when i calculate time taken for this method is 100 - 200ms and above. </p>
<p>Step2: I did one sample in Opencv Facedetection, i pass a byte array value to native i have FPS count is 1.314. </p>
<p>Step3: Before that for my analyse I didn't call native just i return a same capture Mat i have FPS count 13 to 18 frames per second.</p>
<p>Step4: Problem i found is Mat to Byte array conversion it takes more time to convert so i didn't get any improvements in FPS.</p>
<p>Step5: I change conversion method </p>
<pre><code>byte[] return_buff = new byte[(int) (mRgba.total() *
mRgba.channels())];
mRgba.get(0, 0, return_buff);
</code></pre>
<p>this method cannot take more time to convert but when i was Pass a byte array to native, channels value changed to 1 and image not found. </p>
<p>Is there any other solution to convert byte array, please justify me, thank you</p> | 1 |
How to convert Binary String to int array? | <p>Say I have an Integer, I convert it to binary string first. </p>
<pre><code> int symptomsM = 867;
String symptomsBit = Integer.toBinaryString(symptomsM);
</code></pre>
<p>In this case, I would have symptomsBit as 1101100011 in binary. </p>
<p>But how can I further convert it to Int Array that has the same content, such as<br>
<code>symptomsBitArr[] = {1,1,0,1,1,0,0,0,1,1}</code>?</p>
<p>Okay. Here is what I have tried. I know <code>symptomsBit.split(" ")</code> isn't correct. But do not know how to further improve it.</p>
<pre><code> symptomsM = 867;
String symptomsBit = Integer.toBinaryString(symptomsM);
String[] symptomsBitArr = symptomsBit.split(" ");
System.out.println("symptomsBit: " + symptomsBit);
System.out.println("symptomsBitArray: " + symptomsBitArr);
int[] symptomsArray = new int[symptomsBitArr.length];
for (int i = 0; i < symptomsBitArr.length; i++) {
symptomsArray[i] = Integer.parseInt(symptomsBitArr[i]);
System.out.println("symptomsArray: " + symptomsArray);
}
</code></pre>
<p>I tried the way Idos suggested as below:</p>
<pre><code> symptomsM = 867;
String symptomsBit = Integer.toBinaryString(symptomsM);
String[] symptomsBitArr = symptomsBit.split(" ");
System.out.println("symptomsBit: " + symptomsBit);
System.out.println("symptomsBitArray: " + symptomsBitArr);
int[] symptomsArray = new int[symptomsBitArr.length];
for (int i = 0; i < symptomsBitArr.length; i++) {
//symptomsArray[i] = Integer.parseInt(symptomsBitArr[i]);
symptomsArray[i] = Integer.parseInt(String.valueOf(symptomsBit.charAt(i)));
System.out.println("symptomsArray: " + symptomsArray);
}
</code></pre>
<p>But it still not works. Here is the output:</p>
<pre><code>symptomsBitArray: [Ljava.lang.String; @2a139a55
symptomsArray: [I@15db9742
</code></pre> | 1 |
Angular ng-repeat for a select, setting one option as selected using $rootScope variable | <p>I have the following select:</p>
<pre><code><select class="form-control"
onchange="User_Changed_Language()"
id="HeaderLanguageSelection"
style="cursor:pointer;width:100%;height:30px;margin:0;padding:0"
title="{{Labels.Change_Language_Tooltip}}">
<option ng-repeat="One_Language in Languages_List"
value="{{One_Language.Code}}"
ng-selected="One_Language.Code == current_Language">
{{One_Language.Name}}
</option>
</select>
</code></pre>
<p>Now, <code>current_Language</code> is a <code>$rootScope</code> variable with a value (e.g. "EN"). I want the select element to display the selected value instead of the very first. What am I doing wrong?</p>
<p>One more note: I know that I could use <code>ng-click</code>, but I don't think this is the source of the issue.</p>
<p>Thanks.</p> | 1 |
return mpz_t from a function | <p>I am experiencing a problem while using mpir library in C++. Is it possible to return mpz_t value from a function? When I try to do it, I have the following error:</p>
<pre><code>RSA.cpp:50:36: error: ‘HASHtemp’ declared as function returning an array
mpz_t RSA::HASHtemp( mpz_t message )
</code></pre> | 1 |
Javascript: Array is not empty but size is 0 | <p>I create a array in Javascript. I want to use the array for key-value pair.</p>
<p>I can successfully add new items and delete items but the length of it is always 0.</p>
<p>Actually the problem I faced is when I want to convert it to a JSON string, it shows empty string: "[]". I just wonder if they are related. And I would also want to know why I cannot convert it.</p>
<p>Below is the debug information, It show the array contain 3 objects but the length is 0. The browser is Firefox 44.0 for Ubuntu.</p>
<p>Thanks!</p>
<p><a href="https://i.stack.imgur.com/YA7p5.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/YA7p5.jpg" alt="Array with length <code>0</code> and properties <code>1454073967313</code>, <code>1454073968645</code>, and <code>1454073969737</code>"></a></p>
<hr>
<p>Fellow @georg idea, I limited the index into 1000 and leave the rest code as before. Everything works including the JSON part.
The next picture shows that in my array, there are actual 4 elements, the maximum index is 805.</p>
<p><a href="https://i.stack.imgur.com/CicG9.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/CicG9.jpg" alt="enter image description here"></a></p>
<h2>One thing I learned is that the length of Javascript Array is not the real size but the maximum index number.</h2>
<p>The newest finding, the array is really as long as the largest index number. The rest of the element is Null.</p> | 1 |
iOS rotate video AVAsset avfoundation | <p><a href="http://i.stack.imgur.com/K4dFj.jpg" rel="nofollow">Example</a></p>
<p>Hi,</p>
<p>Struggling to rotate this video to show in the proper orientation and fill the entire screen.</p>
<p>I cannot get the avasset with videocompisition but cannot get it to work correctly.</p>
<pre><code> let videoAsset: AVAsset = AVAsset(URL: outputFileURL) as AVAsset
let clipVideoTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo).first! as AVAssetTrack
let newHeight = CGFloat(clipVideoTrack.naturalSize.height/3*4)
let composition = AVMutableComposition()
composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())
let videoComposition = AVMutableVideoComposition()
var videoSize = CGSize()
videoSize = clipVideoTrack.naturalSize
videoComposition.renderSize = videoSize
videoComposition.frameDuration = CMTimeMake(1, 30)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(180, 30))
// rotate to portrait
let transformer:AVMutableVideoCompositionLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)
let t1 = CGAffineTransformMakeTranslation(0, 0);
let t2 = CGAffineTransformRotate(t1, CGFloat(M_PI_2));
transformer.setTransform(t2, atTime: kCMTimeZero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
let date = NSDate()
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let outputPath = "\(documentsPath)/\(formatter.stringFromDate(date)).mp4"
let outputURL = NSURL(fileURLWithPath: outputPath)
let exporter = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)!
exporter.videoComposition = videoComposition
exporter.outputURL = outputURL
exporter.outputFileType = AVFileTypeQuickTimeMovie
exporter.exportAsynchronouslyWithCompletionHandler({ () -> Void in
dispatch_async(dispatch_get_main_queue(), {
self.handleExportCompletion(exporter)
})
})
</code></pre> | 1 |
circle image css with border on top of circle image | <p>Hello I would like to create a thick semi opaque border inverted around a css circle image.</p>
<p>This my css code: </p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.circle {
display: block;
width: 500px;
height: 500px;
margin: 1em auto;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
-webkit-border-radius: 99em;
-moz-border-radius: 99em;
border-radius: -99em;
border-bottom: -5px solid rgba(214, 11, 82, 0.73);
border-top: -5px solid rgba(214, 11, 82, 0.73);
border-left: -5px solid rgba(214, 11, 82, 0.73);
border-right: -5px solid rgba(214, 11, 82, 0.73);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="circle" style="background-image:
url('http://hk.helpstore.co.uk/images/intro.jpg')">
</div></code></pre>
</div>
</div>
</p> | 1 |
Maven 3.3.1 - Disable timestamps | <p>I have read that <code><unique></code> versions setting is no longer executed and is ignored in Maven 3 or later, as explained here: <a href="https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes#Maven3.xCompatibilityNotes-Non-uniqueSnapshotDeployments" rel="nofollow">Non-unique Versions</a>. And by design, Maven 3 or later will always produce time stamped SNAPSHOT versions.</p>
<p>When I build artifacts though, I have some artifacts that only produce the base SNAPSHOT version, even if I build it multiple times, there .</p>
<p>After building some artifacts, in my local repository there will be that base artifact-SNAPSHOT file that I built, and a few other time stamped versions of the same artifact. There is the base artifact: artifactID-4.0.1.0-SNAPSHOT.jar, and then there are others in the same directory with versions appended to them: e.g. artifact-4.0.1.0-SNAPSHOT-20160120.192041-37.jar.</p>
<p>I don't want the time stamp files built and put into my repository, as it only eats up disk space. I would like to figure out how to only produce the base 4.0.1.0-SNAPSHOT version and nothing else.</p>
<p>Other than writing a script to deleted these accumulating time stamped artifacts, Has anyone figure out a way to disable them completely so they are not created in Maven 3 or later?</p> | 1 |
OutOfMemory Error in Recycler View | <p>I am making a simple app which has a recyclerview with staggered Layout loading the data from server with the help of PHP scripts using the Volley Library When I Click on the Item in the RecyclerView my App craches with the below error log.</p>
<p>Also when I look at the Memory logs the app is using lots of memory in just loading the data from server into recyclerView</p>
<p><strong>Log</strong> //On App start</p>
<pre><code>I/Choreographer: Skipped 189 frames! The application may be doing too much work on its main thread.
I/art: Background partial concurrent mark sweep GC freed 3797(174KB) AllocSpace objects, 1(36KB) LOS objects, 6% free, 56MB/60MB, paused 19.976ms total 90.718ms
</code></pre>
<p><strong>Error Log</strong> //after clicking the item in the RecyclerView</p>
<pre><code>I/art: Alloc sticky concurrent mark sweep GC freed 10628(425KB) AllocSpace objects, 5(562KB) LOS objects, 2% free, 59MB/60MB, paused 476us total 7.071ms
I/art: Alloc partial concurrent mark sweep GC freed 928(67KB) AllocSpace objects, 1(16KB) LOS objects, 6% free, 58MB/62MB, paused 647us total 37.510ms
I/art: Alloc concurrent mark sweep GC freed 241(23KB) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 574us total 49.041ms
I/art: Forcing collection of SoftReferences for 21MB allocation
I/art: Alloc concurrent mark sweep GC freed 13(472B) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 429us total 16.959ms
E/art: Throwing OutOfMemoryError "Failed to allocate a 22400012 byte allocation with 4194304 free bytes and 5MB until OOM"I/art: Alloc sticky concurrent mark sweep GC freed 5(608B) AllocSpace objects, 0(0B) LOS objects, 3% free, 58MB/60MB, paused 509us total 8.143ms
I/art: Alloc partial concurrent mark sweep GC freed 17(480B) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 5.517ms total 17.409ms
I/art: Alloc concurrent mark sweep GC freed 14(448B) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 1.077ms total 107.298ms
I/art: Forcing collection of SoftReferences for 21MB allocation
I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 620us total 36.488ms
E/art: Throwing OutOfMemoryError "Failed to allocate a 22400012 byte allocation with 4194304 free bytes and 5MB until OOM"
D/skia: --- allocation failed for scaled bitmap
D/AndroidRuntime: Shutting down VM
FATAL EXCEPTION: main
Process: com.trueblueoperator.swachhapp, PID: 25499
java.lang.OutOfMemoryError: Failed to allocate a 22400012 byte allocation with 4194304 free bytes and 5MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:988)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2474)
at android.content.res.Resources.loadDrawable(Resources.java:2381)
at android.content.res.TypedArray.getDrawable(TypedArray.java:749)
at android.widget.ImageView.<init>(ImageView.java:146)
at android.widget.ImageView.<init>(ImageView.java:135)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:58)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:54)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:95)
at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:725)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at com.trueblueoperator.swachhapp.StoryDetailFragment.onCreate(StoryDetailFragment.java:45)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code></pre>
<p>Here is my Code for Fragment class containing the Recycler View</p>
<p><strong>FragmetnAllStory.java file</strong></p>
<pre><code>public class FragmentAllStory extends Fragment implements SwipeRefreshLayout.OnRefreshListener{// implements RecyclerView.OnScrollChangeListener {
//Creating a List of superheroes
private List<AllStoryData> allStoryDataList;
//Volley Request Queue
private RequestQueue requestQueue;
private ProgressBar progressBar;
//The request counter to send ?page=1, ?page=2 requests
private int requestCount = 1;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView.Adapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
requestCount = 1;
View v = inflater.inflate(R.layout.fragment_all_story, container, false);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(this);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view2);//new RecyclerView(getActivity());
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, 1));
}
else {
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, 1));
}
allStoryDataList = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getContext());
//getData();
recyclerView.addOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if(isLastItemDisplaying(recyclerView))
{
getData();
}
}
});
adapter = new AllStoryAdapter(allStoryDataList, getActivity());
recyclerView.setAdapter(adapter);
return v;
}
//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
//If an error occurs that means end of the list has reached
Toast.makeText(getContext(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
@Override
public void onResume() {
super.onResume();
requestCount =1;
allStoryDataList.clear();
getData();
}
//This method will get data from the web api
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromServer(requestCount));
//Incrementing the request counter
requestCount++;
swipeRefreshLayout.setRefreshing(false);
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the superhero object
AllStoryData allStoryData = new AllStoryData();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
//Adding data to the superhero object
allStoryData.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
allStoryData.setName(json.getString(Config.TAG_NAME));
allStoryData.setPublisher(json.getString(Config.TAG_PUBLISHER));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
allStoryDataList.add(allStoryData);
Log.d("ListSuper", "" + allStoryDataList);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
int[] info = new int[3];
if (recyclerView.getAdapter().getItemCount() != 0) {
((StaggeredGridLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPositions(info);
Log.d("info", "" + info[0] + " " + info[1]);
if (info[0] == recyclerView.getAdapter().getItemCount() - 1 || info[1] == recyclerView.getAdapter().getItemCount() - 1 || info[2] == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
@Override
public void onRefresh() {
requestCount =1;
allStoryDataList.clear();
getData();
}
}
</code></pre>
<p><strong>StoryDetailFragment.java file</strong></p>
<pre><code>public class StoryDetailFragment extends AppCompatActivity implements View.OnClickListener, AppBarLayout.OnOffsetChangedListener {
TextView textView;
TextView like;
ImageView imageView;
String requestString;
RequestParams params = new RequestParams();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_story_detail); // error line 45
// Intent Message sent from Broadcast Receiver
requestString = getIntent().getStringExtra("Heading");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
imageView = (ImageView) findViewById(R.id.story_image);
like = (TextView) findViewById(R.id.likes);
if (requestString != null) {
textView = (TextView) findViewById(R.id.story_detail_message);
textView.setText(requestString);
}
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
appBarLayout.addOnOffsetChangedListener(this);
FloatingActionButton fab1 = (FloatingActionButton) findViewById(R.id.fab1);
FloatingActionButton fab2 = (FloatingActionButton) findViewById(R.id.fab2);
fab1.setOnClickListener(this);
fab2.setOnClickListener(this);
getData();
}
private void getData() {
params.put("heading", "" + requestString);
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.get(Config.DETAIL_URL, params,
new JsonHttpResponseHandler() {
// When the response returned by REST has Http
// response code '200'
@Override
public void onSuccess(JSONArray response) {
Log.d("result",""+response);
try {
JSONObject result = response.getJSONObject(0);
textView.setText((CharSequence) result.get("detailstory"));
like.setText((CharSequence) result.get("likes"));
String res = (String) result.get("images");
//URL url = new URL(res);
//Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
new DownloadImagesTask().execute(res);
Log.d("result",""+res);
} catch (JSONException e) {
e.printStackTrace();
}
//super.onSuccess(response);
}
// When the response returned by REST has Http
// response code other than '200' such as '404',
// '500' or '403' etc
@Override
public void onFailure(int statusCode, Throwable error, JSONArray errorResponse) {
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(StoryDetailFragment.this,
"Requested resource not found",
Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(StoryDetailFragment.this,
"Something went wrong at server end",
Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(
StoryDetailFragment.this,
"Unexpected Error occcured! [Most common Error: Device might "
+ "not be connected to Internet or remote server is not up and running], check for other errors as well",
Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fab1:
// Code for button like click
break;
case R.id.fab2:
// Code for saving the articles
break;
}
}
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) <= appBarLayout.getTotalScrollRange() - 120) {
like.setVisibility(TextView.VISIBLE);
} else {
like.setVisibility(TextView.GONE);
}
}
public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
return download_Image(params[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bmp = null;
try {
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
} catch (Exception e) {
}
return bmp;
}
}
}
</code></pre>
<p><strong>XML File fragment_story_detail.xml</strong></p>
<pre><code><android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context="com.trueblueoperator.samplescrolling.ScrollingActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="192dp"
android:fitsSystemWindows="true"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="@+id/story_image"
android:layout_width="match_parent"
android:layout_height="192dp"
android:scaleType="centerCrop"
android:src="@drawable/image"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_scrolling"/>
<TextView
android:id="@+id/likes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:paddingRight="70dp"
android:layout_marginRight="10dp"
android:textSize="20dp"
android:background="@drawable/rounded_corner"
android:text="100"
app:layout_anchor="@id/app_bar"
app:layout_anchorGravity="right|bottom"
/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/like"
app:layout_anchor="@id/app_bar"
app:layout_anchorGravity="right|bottom" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/like"
android:layout_gravity="bottom|right" />
</android.support.design.widget.CoordinatorLayout>
</code></pre> | 1 |
React-native android ignores navigator.geolocation.getCurrentPosition | <p>I'm trying to use <code>navigator.geolocation.getCurrentPosition</code> on my Android device (Philips Xenium). It works absolutely ok in iphone and genimotion simulator.<br>
<code>navigator.geolocation.getCurrentPosition</code> returns absolutely nothing - no errors, no success.
However, if I turn off geolocation service in my smartphone, it returns <code>No available location provider</code>.</p>
<p>Also, <code>navigator.geolocation.watchPosition</code> works fine.</p> | 1 |
Sum fails on empty list | <p>This is my list: </p>
<pre><code>var MaxItemCountFromRegItems = RegisteredItems.MyRegisteredItems
.Where(s => s.ItemID == _itemID)
.Sum(s => s.Posted);`
</code></pre>
<p>It fails with error: </p>
<blockquote>
<p>Exception: System.ArgumentNullException: Value cannot be null.</p>
</blockquote>
<p>Its clear error happens because collection is empty. I am wondering how to avoid it. </p> | 1 |
writing a Bingo Game in java | <p>I'm totally new to Java and on my second self-project.
I'm trying to write a bingo game. I know there are some posts about this, but I think that my approach is a little bit different from others', so sorry if it looks redundant.
My bingo game is 5x5 matrix with 25 buttons and I labled them from 1~25 just for convenience. I also made a pseudo game board called <strong>grid</strong> variable which is a 5x5 2d Character Array. It's originially filled with 'O's but when I press on one of the buttons, then the corresponding index turns into 'X'. I'm using this <strong>grid</strong> to check for bingos since I thought it would be a lot easier than checking the actual buttons. Below is my code.</p>
<pre><code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class exex extends JFrame{
final int size =5; //5x5 bingo board
int bingos =0; // how many bingos?
int count=0; // int value for each btn
JButton[][] btn = new JButton[size][size]; //actual display of btns (bingo board)
char[][] grid = new char[size][size]; // grid to check whether it's bingo or not
int presscount = 1; // how many times ive pressed
int row; // row for action event
int column; // column for action event
boolean bingo; //check if bingo
exex(){
setTitle("Bingo for everyone");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
pane.setLayout(new GridLayout(size,size));//basic board setup
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
btn[i][j] = new JButton(Integer.toString(count)); //setting buttons 1~25;
grid[i][j] ='O'; // make a grid board to check bingos
btn[i][j].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
isBingo(grid,'X'); // check if grid has any bingos, if it does, then set bingo to true.
System.out.print(bingo);
if(bingo){
bingos++;
}
System.out.print(bingos);
JButton btnR = (JButton)e.getSource();
System.out.println(presscount);
presscount++;
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(btn[i][j] == btnR){
row = i;
column =j;
grid[row][column]='X'; //set pressed button to 'X' char on my grid(2D char array)
}
System.out.print(grid[i][j]);
}
System.out.println("");
}
System.out.println("-----------");
//Color change when pressed,
btnR.setBackground(Color.YELLOW);
btnR.setOpaque(true);
}
});
add(btn[i][j]);
count++;
}
System.out.println();
}
setSize(500,500);
setVisible(true);
}
public void isBingo(char[][] array,char g){
for(int i=0;i<array.length;i++){
for(int j=0;j<=i;j++){
if(array[0][j]==g&&array[1][j]==g&&array[2][j]==g&&array[3][j]==g&&array[4][j]==g){ //check for vertical bingos
bingo = true;
}
else if(array[i][0]==g&&array[i][1]==g&&array[i][2]==g&&array[i][3]==g&&array[i][4]==g){//check for horizontal bingos
bingo = true;
}
else if(array[0][0]==g&&array[1][1]==g&&array[2][2]==g&&array[3][3]==g&&array[4][4]==g){ //check for S.E diagonal bingos
bingo =true;
}
else if(array[0][4]==g&&array[1][3]==g&&array[2][2]==g&&array[3][1]==g&&array[4][0]==g){ //check for S.W diagonal bingos
bingo= true;
}
else // if no bingos, remains false
bingo = false;
}
}
}
public static void main(String[] args) {
new exex();
}
</code></pre>
<p>}</p>
<p>So the problem is if I make one bingo in any direction, then I'm not sure how to count the next bingos I make. Since a bingo in any direction will set my <strong><em>boolean bingo</em></strong> to true and it will remain true as long as there is a bingo... any additional bingos will not be counted.. How would I fix this?
I know the code is really messy and is not well written. Any help is appreciated. </p> | 1 |
How to cancel cancellationtoken for the second time in C# project | <p>There are two threads in my C# project; UI thread and BackgroundWorker. </p>
<p>In BackgroundWorker there are some work such as;</p>
<pre><code>private void testBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker)sender;
while (!worker.CancellationPending)
{
// Do some work!
token.WaitHandle.WaitOne(20000);
}
}
</code></pre>
<p>In UI thread;</p>
<pre><code>// Some initialization for CancellationToken
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
// Click event listener of the button!
private void testBtn_Click(object sender, EventArgs e)
{
testBgWorker.CancelAsync();
tokenSource.Cancel();
}
</code></pre>
<p>In UI thread, when user clicks the button, BackgroundWorker starts running. If user clicks the button for the second one, BackgroundWorker is cancelled. <strong><em>There is no problem for this cycle.</em></strong> </p>
<p>However, when user clicks again after BackgroundWorker is cancelled, since IsCancellationRequested is true, thread does not wait in the line of token.WaitHandle.WaitOne(20000) and passed it to next line. <strong>This is a problem!</strong></p>
<p>Cannot I use token multiple times? How do I make isCancellationRequested property of cancellationtoken to false again for the second cycle? or do I have to use new cancellationtoken?</p> | 1 |
Is a lock possible per instance of an object? | <p>I have understood that <code>lock()</code> locks a region of lines of code, other threads cannot access the locked line(s) of code. EDIT: this turns out to be just wrong.<br>
Is it also possible to do that <em>per instance</em> of an object? EDIT: yes, that's is just the difference between static and non-static. </p>
<p>E.g. a <code>null</code> reference is checked during a lazy load, but in fact there is no need to lock other objects of the same type?</p>
<pre><code>object LockObject = new object();
List<Car> cars;
public void Method()
{
if (cars == null)
{
cars = Lookup(..)
foreach (car in cars.ToList())
{
if (car.IsBroken())
{
lock(LockObject)
{
cars.Remove(car)
}
}
}
}
return cars;
}
</code></pre>
<p>EDIT, would this be a correct way to write this code:<br>
Because when <code>cars == null</code> and thread A locks it, then another thread B will wait. Then when A is ready, B continues, but should check again whether <code>cars == null</code>, otherwise the code will execute again.<br>
But this looks unnatural, I never saw such a pattern.<br>
Note that locking the first <code>null</code>-check would mean that you acquire a lock even to check for <code>null</code> and every time again and again .. so that is not good.</p>
<pre><code>public void Method()
{
if (cars == null)
{
lock(LockObject)
{
if (cars == null)
{
cars = Lookup(..)
foreach (car in cars.ToList())
{
if (car.IsBroken())
{
cars.Remove(car)
}
}
}
}
}
return cars;
}
</code></pre> | 1 |
git is not recognized as an internal or external command windows - already tried to change the environment variable | <p>I got the following error, git is not recognized as an internal or external command, operable program or batch file.
I read in some forums that i need to add the /bin & /cmd paths to 'System variable'
I've done that but am still running into the same error. Already restarted by computer. Ideas? </p> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.