input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Django Allauth and urls <p>I have a dev environment for a test of Django. I am running Python 3.5.2 out of a "local" <code>pyenv</code> install. I have Django 1.10.2. I discovered the <code>allauth</code> registration plugin yesterday and have been playing with it but have hit a snag.</p>
<p>My site is "dev.my.domain.com". The intent is that there will not be any "public" information on the production version of this site. The production version will be called something like: "members.my.domain.com". So, I wonder if it is possible for the "allauth" plugin to have all non-/adomn inbound requests check for auth?</p>
<p>So, requests to: </p>
<ul>
<li>dev.my.domain.com</li>
<li>dev.my.domain.com/foo</li>
<li>dev.my.domain.com/foo/../bar/...</li>
</ul>
<p>should all be checked for auth. If not there then I assume "allauth" will redirect to a login/signup page.</p>
<p>I have tried setting the <code>Members/urls.py</code> file as:</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('allauth.urls')),
url(r'^admin/', admin.site.urls),
]
</code></pre>
<p>but that bombs with a Page Not Found error and the <code>DEBUG</code> message:</p>
<pre><code> Using the URLconf defined in Members.urls, Django tried these URL patterns, in this order:
^$ ^ ^signup/$ [name='account_signup']
^$ ^ ^login/$ [name='account_login']
^$ ^ ^logout/$ [name='account_logout']
^$ ^ ^password/change/$ [name='account_change_password']
^$ ^ ^password/set/$ [name='account_set_password']
^$ ^ ^inactive/$ [name='account_inactive']
^$ ^ ^email/$ [name='account_email']
^$ ^ ^confirm-email/$ [name='account_email_verification_sent']
^$ ^ ^confirm-email/(?P<key>[-:\w]+)/$ [name='account_confirm_email']
^$ ^ ^password/reset/$ [name='account_reset_password']
^$ ^ ^password/reset/done/$ [name='account_reset_password_done']
^$ ^ ^password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$ [name='account_reset_password_from_key']
^$ ^ ^password/reset/key/done/$ [name='account_reset_password_from_key_done']
^$ ^social/
^$ ^google/
^$ ^facebook/
^$ ^facebook/login/token/$ [name='facebook_login_by_token']
^admin/
The current URL, , didn't match any of these.
</code></pre>
<p>I bowed to my ignorance and went back to the allauth docs and used their default <code>urls</code> setting:</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^accounts/', include('allauth.urls')),
url(r'^admin/', admin.site.urls),
]
</code></pre>
<p>but that also bombs with a Page Not Found and a different message:</p>
<pre><code> Using the URLconf defined in Members.urls, Django tried these URL patterns, in this order:
^accounts/
^admin/
The current URL, , didn't match any of these.
</code></pre>
<p>I think the rest of the "allauth" install was done correctly but I am missing something.</p>
<p>Ideas?</p>
| <p>In your <em>view.py</em> file, you just need to do a little "filter" before giving away the page to see if the user is authenticated.</p>
<p>An example for this will be:</p>
<pre><code>def myview(request):
if request.user.is_authenticated():
# do something if the user is authenticated, like showing a page.
else:
# do somthing else
</code></pre>
<p>Regrading the urls structure - just try to add /accounts/ to the url and the 404 page will show you all the end points if you are on Debug mode (DEBUG = True).
You can also find all urls for endpoints on the documentation.</p>
<p>Hope I understood your problem correctly :)</p>
|
How to get a div to move while scrolling in angular 2 <p>I was looking for solutions for this in Angular 2 and I can't seem to find anything out there. I see many solutions that uses jquery but I'm not sure that jquery works well with angular 2 and is frowned upon(correct me if im wrong and if so can you please provide me a way where i can do this in angular 2). I was hoping that there is another way to do this through angular 2 or some npm package.</p>
<p>Here is a <a href="http://www.pixelbind.com/examples/stick-a-div/2/" rel="nofollow">link</a> that better explains what I want to do. If you look at the right, the box is stationary and then moves with the window and then when scrolling back up it goes back to place. </p>
<p>Thanks!</p>
| <p>You can either write your own directive that detects a window scroll and changes the css of the div to a fixed position or you can use <a href="http://www.github.com/makseo/ng2-sticky" rel="nofollow">www.github.com/makseo/ng2-sticky</a> ... I like writing my own directives, but this one is pretty well written and simple to use!</p>
|
Invalid left-hand side expression <p>I'm trying to figure out why the bottom function I've written isn't working properly. Whenever I try to test it out, I get the following error: Uncaught ReferenceError: Invalid left-hand side expression in postfix operation. I'm assuming it's because the code is failing to recognize the "x" string as being the same as the variable x once it's been stripped of it quotation marks when adding to the value of x. Can someone help me finesse this in a way to make it work? If not, can you suggest some alternate approach? Thanks in advance! </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var grid = [[null, null, null],
[null, null, null],
[null, null, null]];
function checkWin() {
vals = ["x", "o"];
var x = 0;
var o = 0;
for (var k = 0; k < vals.length; k++) {
var value = vals[k];
for (var i = 0; i < 3; i++) {
if (grid[i][i] === value) {
(value.replace(/['"]+/g, '')) ++;
}
if (grid[2 - i][i] === value) {
(value.replace(/['"]+/g, '')) ++;
}
for (var j = 0; j < 3; j++) {
if (grid[i][j] === value) {
(value.replace(/['"]+/g, '')) ++;
}
if (grid[j][i] === value) {
(value.replace(/['"]+/g, '')) ++;
}
}
}
}
if (x === 3) {
alert("X wins!");
} else if (o === 3) {
alert("O wins!");
}
}</code></pre>
</div>
</div>
</p>
| <p>What about put your data in a object like this:</p>
<pre><code>var _ = {
x : 0,
o : 0
};
</code></pre>
<p>and change the value like this:</p>
<pre><code>_[value]++;
</code></pre>
<p>I hope this helps.</p>
|
Merging multiple json objects fetched with async calls <p>I have a situation in my project(java based web app) in which I need to get service response from REST web service in multiple calls. Lets say web service contains 20K of records(large records containing very complex json structure) and in a go I can fetch 5K record. So I want to fetch them asynchronously & then parse them to put in a final response bean.</p>
<p>So below are the steps I want to follow:</p>
<p>1) I want to make 4 asynch calls(using asyncRestTemplate & future interface probably) to fetch all the records asynchronously.</p>
<p>2) Either of below steps:</p>
<pre><code> a) Whatever Service response(out of multiple call made in step1) I get
first I want to put it in a file followed by others(because these
response will be quiet complex & I am not too confident to deal with
them in memory). So that I have a file containing all the json records
together.
OR
b) I can leave reference of every service response in a memory only.
</code></pre>
<p>3) Either of below steps:</p>
<pre><code> a) Then I want to parse this final merged file & put required fields in
final required response bean.
OR
b) Read all service response & put required fields in final response
beans.
</code></pre>
<p>4) Either of below steps:</p>
<pre><code>a) Then finally I want to read records from the bean and extract
the required fields in final response of a DAO layer.
OR
b) Merge all the final response bean to generate final bean to pass to DAO
layer.
</code></pre>
<p>So my question is:</p>
<pre><code>1) Out of above approach mentioned i.e file based vs memory which
one is better? Or let me know if there is something better in range of
java/Spring or related technology.
2) What are the best steps(technically which framework, etc) to achieve
recommended approach?
</code></pre>
<p>Any useful inputs for the above situation will be much appreciated. Thanks!</p>
| <p>My opinion is:</p>
<ul>
<li><p>Answer to 1st query, It depends on the size of records and their structure, If it's in thousands then you can directly consume it and store it in database. But if it is in lacs then Store it in file because if in case any exception occurs or your database is down. In that case, you don't need to call service again & again, and do access the service and process huge records. So, better is to store it in file and then read it.</p></li>
<li><p>Answer to 2nd query, You can use any REST based framework, i.e. Jersey.</p></li>
</ul>
|
Storing objects in array (Haxe) <p>How would I go about sorting an new instance of an object into an array in Haxe? </p>
<p>For example I have a class called weapon and in the player class I gave an array inventory.
So how would I store this? </p>
<pre><code>private void gun:Weapon
gun = new Weapon; //into the array
</code></pre>
| <p>I think you are looking for this:</p>
<pre><code>private var inventory:Array<Weapon>;
</code></pre>
<p>This is an array of type <code>Weapon</code>.
To add stuff to it use <code>push()</code>, as seen in this example:</p>
<pre><code>class Test {
static function main() new Test();
// create new array
private var inventory:Array<Weapon> = [];
public function new() {
var weapon1 = new Weapon("minigun");
inventory.push(weapon1);
var weapon2 = new Weapon("rocket");
inventory.push(weapon2);
trace('inventory has ${inventory.length} weapons!');
trace('inventory:', inventory);
}
}
class Weapon {
public var name:String;
public function new(name:String) {
this.name = name;
}
}
</code></pre>
<p>Demo: <a href="http://try.haxe.org/#815bD" rel="nofollow">http://try.haxe.org/#815bD</a></p>
|
htaccess rewrite URLby removing #! <p>I have a URL as below,</p>
<pre><code>http://localhost:8080/mysite/#!/skin-conditions/angioedema
</code></pre>
<p>I want this URL to be redirected to</p>
<pre><code>http://localhost:8080/mysitenew/?id=skin-conditions/angioedema
</code></pre>
<p>In here, I want redirected URL to have <code>mysitenew</code> instead of <code>mysitenew</code> and I want the rest of the URL (after <code>#!</code>) to be sent as a parameter. How should I write a rewrite rule for this? I don't want a rewrite condition for this, I just want a rewrite rule.</p>
<p>Thanks</p>
| <p>Sorry but this is not possible: the anchor (or fragment) part of an URL (<code>#!/skin-conditions/angioedema</code> in your example) is not sent by the client to the server (no way to rewrite something you don't have).</p>
|
Requiring tensorflow with Python 2.7.11 occurs ImportError <p>I tried <code>pip install tensorflow</code> on OS X El Capitan and it succeeded.
However, if I tried to import tensorflow, ImportError occured.
Please tell me when you know.</p>
<pre><code>>>> import tensorflow
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 23, in <module>
from tensorflow.python import *
File "/usr/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
File "/usr/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
_pywrap_tensorflow = swig_import_helper()
File "/usr/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: dlopen(/usr/local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so, 10): no suitable image found. Did find:
/usr/local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x03
>>>
</code></pre>
<hr>
| <p>I got the same question.
Try to follow the [official instruction] to install tensorflow: <a href="https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation" rel="nofollow">https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation</a></p>
<pre><code># Mac OS X
$ sudo easy_install pip
$ sudo easy_install --upgrade six
</code></pre>
<p>Then, select the correct binary to install:</p>
<pre><code># Ubuntu/Linux 64-bit, CPU only, Python 2.7
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc0-cp27-none-linux_x86_64.whl
# Ubuntu/Linux 64-bit, GPU enabled, Python 2.7
# Requires CUDA toolkit 7.5 and CuDNN v5. For other versions, see "Install from sources" below.
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0rc0-cp27-none-linux_x86_64.whl
# Mac OS X, CPU only, Python 2.7:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.11.0rc0-py2-none-any.whl
# Mac OS X, GPU enabled, Python 2.7:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow-0.11.0rc0-py2-none-any.whl
# Ubuntu/Linux 64-bit, CPU only, Python 3.4
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc0-cp34-cp34m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, GPU enabled, Python 3.4
# Requires CUDA toolkit 7.5 and CuDNN v5. For other versions, see "Install from sources" below.
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0rc0-cp34-cp34m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, CPU only, Python 3.5
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.11.0rc0-cp35-cp35m-linux_x86_64.whl
# Ubuntu/Linux 64-bit, GPU enabled, Python 3.5
# Requires CUDA toolkit 7.5 and CuDNN v5. For other versions, see "Install from sources" below.
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.11.0rc0-cp35-cp35m-linux_x86_64.whl
# Mac OS X, CPU only, Python 3.4 or 3.5:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.11.0rc0-py3-none-any.whl
# Mac OS X, GPU enabled, Python 3.4 or 3.5:
$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow-0.11.0rc0-py3-none-any.whl
</code></pre>
<p>Install TensorFlow:</p>
<pre><code># Python 2
$ sudo pip install --upgrade $TF_BINARY_URL
# Python 3
$ sudo pip3 install --upgrade $TF_BINARY_URL
</code></pre>
|
I want to display items in list according to Categories <p>I can't display products according to their Categories</p>
<p>Althought when i run the app all products are displayed and the category (either Men or Women) is written under every product but when i try choosing products from (Men Category) it displays EMPTY LIST</p>
<pre><code> public class ProductController : Controller
{
private readonly IProductRepository repository;
public int PageSize = 3;
public ProductController(IProductRepository repo)
{
repository = repo;
}
public ViewResult List(string category, int Page = 1)
{
ProductsListViewModel model = new ProductsListViewModel
{
Products= repository.Products
.Where(p => category == null || p.Category == category)
.OrderBy(p => p.ProductID)
.Skip((Page - 1) * PageSize)
.Take(PageSize),
pagingInfo = new PagingInfo
{
CurrentPage = Page,
ItemPerPage = PageSize,
TotalItems = repository.Products.Count()
},
CurrentCategory = category
};
return View(model);
}
}
</code></pre>
| <p>I think you should use</p>
<pre><code>p.Category.Equals(category, StringComparison.InvariantCultureIgnoreCase)
</code></pre>
<p>instead of</p>
<pre><code>p.Category.equal == category
</code></pre>
|
Highcharts Ajax Json not displaying Chart <p>I am trying to use the ajax line chart and I've created the following but it's not displaying anything.</p>
<p>What i am trying to achieve is to display the page views for the last 30 days. Hence my Json encode shows [date,page views]</p>
<p>I want the dates to display at the bottom horizontally, and the number of page counts on the vertical axis.</p>
<p>When i load the page, there's no error but it displays blank.</p>
<p><strong>Update: I've updated the JSON data but I do not understand what kind of order it needs to be sorted by, since the data now is [A,B] and I sorted it ascending order of A.</strong></p>
<blockquote>
<p>{"data":[[1476374400000,143],[1476288000000,190],[1476201600000,108],[1476115200000,145],[1476028800000,125],[1475942400000,15],[1475856000000,18],[1475769600000,26],[1475683200000,31],[1475596800000,42],[1475510400000,19],[1475424000000,34],[1475337600000,46],[1475251200000,34],[1475164800000,46],[1475078400000,34],[1474992000000,33],[1474905600000,39],[1474819200000,52],[1474732800000,47],[1474646400000,60],[1474560000000,40],[1474473600000,52],[1474387200000,51],[1474300800000,70],[1474214400000,69],[1474128000000,64],[1474041600000,45],[1473955200000,47],[1473868800000,44]],"name":"www.example.com"}</p>
</blockquote>
<p>And then by following the codes on highcharts website I got this.</p>
<pre><code><head>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.src.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<!-- Additional files for the Highslide popup effect -->
<!-- Additional files for the Highslide popup effect -->
<script src="https://www.highcharts.com/samples/static/highslide-full.min.js"></script>
<script src="https://www.highcharts.com/samples/static/highslide.config.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="https://www.highcharts.com/samples/static/highslide.css"/>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
$(document).ready(function () {
// Get the CSV and create the chart
$.getJSON('https://www.micro.sg/json/', function (data) {
$('#container').highcharts({
data: {
json: data
},
title: {
text: 'Daily visits at www.highcharts.com'
},
subtitle: {
text: 'Source: Google Analytics'
},
xAxis: {
tickInterval: 24 * 3600 * 1000, // one week
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'left',
x: 3,
y: -3
}
},
yAxis: [{ // left y axis
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
format: '{value:.,0f}'
},
showFirstLabel: false
}, { // right y axis
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
format: '{value:.,0f}'
},
showFirstLabel: false
}],
legend: {
align: 'left',
verticalAlign: 'top',
y: 20,
floating: true,
borderWidth: 0
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function (e) {
hs.htmlExpand(null, {
pageOrigin: {
x: e.pageX || e.clientX,
y: e.pageY || e.clientY
},
headingText: this.series.name,
maincontentText: Highcharts.dateFormat('%A, %b %e, %Y', this.x) + ':<br/> ' +
this.y + ' visits',
width: 200
});
}
}
},
marker: {
lineWidth: 1
}
}
},
series: [{
name: 'All visits',
lineWidth: 4,
marker: {
radius: 4
}
}, {
name: 'New visitors'
}]
});
});
});
</script>
</body>
</code></pre>
| <p>You have two issues in your code. The first thing is you do not have to use data module to load json - actually it does nothing with the data - so your chart is empty.
You should put the data into series property - remember one thing that it requires array, not an object, so in this case it should be like this (such options include 3 series, which 2 of them have no data):</p>
<pre><code>series: [series, {
name: 'All visits',
lineWidth: 4,
marker: {
radius: 4
},
}, {
name: 'New visitors'
}]
</code></pre>
<p>The other problem is that the data needs to be sorted. Preferable way is to do this on server side but, of course, you can sort this in the browser.</p>
<pre><code> series.data.sort(function (a, b) {
return a[0]-b[0];
});
</code></pre>
<p>Example: <a href="http://jsfiddle.net/ojg90mmg/1/" rel="nofollow">http://jsfiddle.net/ojg90mmg/1/</a></p>
|
NODE_ENV is not recognised as an internal or external command <p>I am developing in node.js and wanted to take into account both production and development environment. I found out that setting NODE_ENV while running the node.js server does the job. However when I try to set it in package.json script it gives me the error:</p>
<blockquote>
<p>NODE_ENV is not recognised as an internal or external command</p>
</blockquote>
<p>Below is my package.json</p>
<pre><code>{
"name": "NODEAPT",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "NODE_ENV=development node ./bin/server",
"qa2": "NODE_ENV=qa2 node ./bin/server",
"prod": "NODE_ENV=production node ./bin/server"
},
"dependencies": {
"body-parser": "~1.15.1",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"express": "~4.13.4",
"fs": "0.0.1-security",
"jade": "~1.11.0",
"morgan": "~1.7.0",
"oracledb": "^1.11.0",
"path": "^0.12.7",
"serve-favicon": "~2.3.0"
}
}
</code></pre>
<p>I run my node server as: <code>npm run qa2</code> for example.</p>
<p>I don't know what I am doing wrong. Any help is appreciated</p>
| <p>Since you are using <code>windows operating system.</code>, the command varies from the unix system command that you are using.</p>
<p>In windows you have to modify you script as. </p>
<pre><code>"scripts": {
"start": " SET NODE_ENV=development & node ./bin/server",
"qa2": "SET NODE_ENV=qa2 & node ./bin/server",
"prod": "SET NODE_ENV=production & node ./bin/server"
},
</code></pre>
<p>Use <code>SET</code> and then an <code>&</code> after that </p>
|
How to check if a factor variable has only the levels I want? <p>What's the simplest way to verify a factor variable has the levels I want to?</p>
<pre><code># I want to make sure a factor variable has 'FP', 'TP' but nothing else
a <- factor(c('TP','TP','FP')) # Return TRUE
b <- factor(c('TP')) # Return TRUE
c <- factor(c('TP', '1234')) # Return FALSE
</code></pre>
| <p>We can use <code>all</code> with <code>%in%</code></p>
<pre><code>all(levels(a) %in% c("FP", "TP"))
#[1] TRUE
all(levels(b) %in% c("FP", "TP"))
#[1] TRUE
all(levels(c) %in% c("FP", "TP"))
#[1] FALSE
</code></pre>
<hr>
<p>Just to avoid the repetition of code or in case if there are more levels that we need to check</p>
<pre><code>checkFactor <- c("FP", "TP")
all(levels(a) %in% checkFactor)
#[1] TRUE
all(levels(b) %in% checkFactor)
#[1] TRUE
all(levels(c) %in% checkFactor)
#[1] FALSE
</code></pre>
|
django - How to customise Model save method when a specified field is changed <p>I have a model, let's save A, the definition is as below:</p>
<pre><code>class A(models.Model):
name = models.CharField('name', max_length=10)
enabled = models.BooleanField('enabled', default=False)
field1 = models.CharField('field1', max_length=10)
field2 = models.CharField('field2', max_length=10)
field3 = models.CharField('field3', max_length=10)
parent = models.ForeignKey('self', null=True, blank=True) # hierarchy
</code></pre>
<p>and some object instances of this model, a, b, c, d. the hierarchy is represented by the parent field.</p>
<pre><code>a
|-- b
|-- c
|-- d
</code></pre>
<p>So, what I need to do is, when <code>b.enabled</code> change from <code>False</code> to <code>True</code>, or vice versa, I need to update <code>c.enabled</code> and <code>d.enabled</code> to value: <code>b.enabled</code>.</p>
<p>That's say, I need to broadcast the change to the children instances when the parent's <code>enabled</code> field was changed.</p>
<p>For performance consideration, I only need to broadcast the changes when <code>enabled</code> field is really changed. And don't want to always update the child instance whenever the parent is save, e.g. only updating field1 or field2.</p>
<p>So, do anyone knows, what is the best way to implement this logic? Thanks in advance.</p>
| <p>In short â no. But you can do it manually overloading the save method.</p>
<pre><code>class B(models.Model):
...
def save(self, *args, **kwargs):
if self.pk is not None:
original = B.objects.get(pk=self.pk)
if original.enabled != self.enabled:
C.enabled = self.enabled
C.save()
D.enabled = self.enabled
D.save()
super(B, self).save(*args, **kw)
</code></pre>
|
How to validate web api response <p>I am working on a web api where I need to validate response returned. I want to write some generic code to ensure that response returned from api is in a correct format.</p>
<p>Basically there are fields like status, remarks etc which should be present in response if these are null or invalid then i should return some error code but not sure how to achieve this, can someone guide me here? Thanks in advance.</p>
<p>Thanks,
Sudama</p>
| <p>The following might work for you. It assumes you're using an <code>ObjectResult</code> though you can adapt it to the <code>IActionResult</code> implementation that you're actually using. The following is not production code; rather, it gives a sense of what you could do. </p>
<pre><code>public class MyResultFilter : IResultFilter
{
public void OnResultExecuted(ResultExecutedContext context)
{
}
public void OnResultExecuting(ResultExecutingContext context)
{
var result = context.Result as ObjectResult;
var value = result.Value as MyCustomType;
if (!IsValid(value)
{
context.Result = new StatusCodeResult(500);
}
}
private bool IsValid(MyCustomType value)
{
return value != null &&
value.Status != null &&
value.Remarks != null;
}
}
</code></pre>
|
Sort a String array by second word <p>I have the following data</p>
<pre><code>1. John Smith
2. Tom Cruise
3. Chuck Norris
4. Bill Gates
5. Steve Jobs
</code></pre>
<p>As you can see, the data is in specific format, <code>[ID]. [Firstname] [Lastname]</code>. Is there a way to sort this array by <code>Firstname</code>?</p>
<p>Output should look something like this:</p>
<pre><code>4. Bill Gates
3. Chuck Norris
1. John Smith
5. Steve Jobs
2. Tom Cruise
</code></pre>
| <p>You can use lambda to pass your own comparison criteria.</p>
<pre><code>String[] names = {"1. John Smith", "2. Tom Cruise", "3. Chuck Norris", "4. Bill Gates", "5. Steve Jobs"};
ArrayList<String> namesList = new ArrayList<>();
for(int i=0; i<names.length; i++) {
namesList.add(names[i]);
}
Collections.sort(namesList, (name1, name2) -> name1.split(" ")[1].compareTo(name2.split(" ")[1]));
for(String name : namesList) {
System.out.println(name);
}
</code></pre>
<p>Output:</p>
<pre><code>4. Bill Gates
3. Chuck Norris
1. John Smith
5. Steve Jobs
2. Tom Cruise
</code></pre>
|
Blank Datagridview <p>I have a function that populates a datagridview using the code given below. It basically displays a list of patients scheduled for a given timeslot and date for up to 7 days (Sun-Sat).</p>
<p>The datagridview is displaying fine on my machine on both release and debug versions. I also tried publishing the application and installing it in the same machine and had no problems at all.</p>
<p>Unfortunately, when the same application is published and installed on a different machine, the datagridview doesn't show any data. The same application also displays other datagridviews for a list of patients and other details and they are all displaying just fine.</p>
<p>I've read a LOT of threads here and have been fiddling with the code but so far, I haven't found any solutions. Is there a problem with the code or is there a problem with any settings of some kind that I am not aware of?</p>
<p>Any help or input will be deeply appreciated.</p>
<p>Edit: I've updated the code to provide more details (just in case)</p>
<pre><code>SqlConnection c = new SqlConnection(connectionString);
//weeArray simply contains 7 dates, (Sun-Sat)
for (int ctr = 0; ctr < weekArray.Length; ctr++)
{
c.Open();
SqlCommand command = new SqlCommand(null, c);
command.CommandText = @"Reealy long sql that I'm sure isn't causing the issue";
command.Parameters.Add("@scheduleDate", SqlDbType.Date).Value = weekArray[ctr];
command.Parameters.Add("@scheduleStaff_ID", SqlDbType.Int).Value = comboBox2.SelectedValue;
command.Prepare();
command.ExecuteReader();
SqlDataAdapter a = new SqlDataAdapter(command);
c.Close();
DataTable dt = new DataTable();
a.Fill(dt);
if (ctr == 0)
{
dataGridView2.DataSource = dt;
if (weekArray[ctr].Equals(DateTime.Now.ToString("MM-dd-yyyy")))
dataGridView2.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192);
else
dataGridView2.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(230, 255, 255);
}
else if (ctr == 1)
{
dataGridView3.DataSource = dt;
if (weekArray[ctr].Equals(DateTime.Now.ToString("MM-dd-yyyy")))
dataGridView3.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192);
else
dataGridView3.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 255);
}
else if (ctr == 2)
{
dataGridView4.DataSource = dt;
if (weekArray[ctr].Equals(DateTime.Now.ToString("MM-dd-yyyy")))
dataGridView4.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192);
else
dataGridView4.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 255);
}
else if (ctr == 3)
{
dataGridView5.DataSource = dt;
if (weekArray[ctr].Equals(DateTime.Now.ToString("MM-dd-yyyy")))
dataGridView5.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192);
else
dataGridView5.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 255);
}
else if (ctr == 4)
{
dataGridView6.DataSource = dt;
if (weekArray[ctr].Equals(DateTime.Now.ToString("MM-dd-yyyy")))
dataGridView6.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192);
else
dataGridView6.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 255);
}
else if (ctr == 5)
{
dataGridView7.DataSource = dt;
if (weekArray[ctr].Equals(DateTime.Now.ToString("MM-dd-yyyy")))
dataGridView7.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192);
else
dataGridView7.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 255);
}
else if (ctr == 6)
{
dataGridView8.DataSource = dt;
if (weekArray[ctr].Equals(DateTime.Now.ToString("MM-dd-yyyy")))
dataGridView8.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192);
else
dataGridView8.Columns["patient"].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 255);
}
}
</code></pre>
| <p>Apparently, the blank datagridview is caused by the fact that I am using a prepared statement. There are no problems with the statement itself, it just so happens that that section of code doesn't work well with a prepared statement. </p>
<p>Based from what I've read so far, it's usually caused by different/older versions of SQL express and/or .NET framework (sometimes both).</p>
<p>Since that section of code doesn't really require the use of a prepared statement, I've modified it to a simple sqlcommand instead since there will be no user input other than button clicks and the issue was resolved.</p>
<p>The solution was only applicable in this case since there is no user text input involved and an install/upgrade of the SQL/.NET framework isn't a viable option because the target machine is rather old and lacks disk space (aside from other reasons including but not limited to outdated hardware and software.)</p>
<p>(Thanks for all your input, they were a huge help in tracing the problem much more faster.)</p>
|
Implementing a Skiplist Node in C++ <p>I am looking to create a a Skip List data structure. Here is a snapshot of code that I have so far for Node. </p>
<pre><code> #define MAX_HEIGHT = 20;
struct Node {
int i;
Node *nodes[20];
}
</code></pre>
<p>I understand that if I used vector in this case it would be far better as you can dynamically change its size. I was wondering where would I go if I wanted to use arrays. </p>
<p>I am new to C++, so I am wondering whether it is possible to assign the size of the array at a later instance. Say, I wanted to add another node that only has size 2 array of pointers. </p>
| <p>You can pass the height to the constructor of the node being created, inside the constructor you just <strong>dynamically allocate an array of pointers of <code>Node</code></strong>, and don't forget to free that memory in the destructor:</p>
<pre><code>struct Node {
int i;
int height;
Node* *nodes;
Node(int h) {
nodes = new Node*[h];
height = h;
}
~Node() {
delete [] nodes;
}
};
</code></pre>
|
SQL: Count of matches in WHERE clause <p>i need to find the number of expressions matched in WHERE clause for a SELECT statement. Sample data and table is as follows:</p>
<pre><code> declare @var1 varchar(10), @var2 varchar(10), @var3 varchar(10)
set @var1 = 'a'
set @var2 = null
set @var3 = 'c'
insert into tempTable values(1, 'a', 'b', 'c')
insert into tempTable values(2, 'a', 'e', 'c')
insert into tempTable values(3, 'g', 'b', 'c')
select id from tempTable
where ISNULL(@var1, colA) = colA
AND ISNULL(@var2, colB) = colB
AND ISNULL(@var3, colC) = colC
</code></pre>
<p>The output should be like this:</p>
<pre><code> id MatchingCount
------------------------
1 2 (because @var1 and @var3 are matched)
2 2 (because @var1 and @var3 are matched)
</code></pre>
<p>thanks.</p>
| <pre><code>select id, cast ((case when @var1 = colA then 1 else 0 end) as int)
+cast ((case when @var2 = colB then 1 else 0 end) as int)
+cast ((case when @var3= colC then 1 else 0 end) as int) as MatchCount
from tempTable
</code></pre>
<p>Use Case</p>
|
How to make replacement in python's dict? <p>The goal I want to achieve is to exchange all items whose form is <code>#item_name#</code> to the from <code>(item_value)</code> in the dict. I use two <code>dict</code> named <code>test1</code> and <code>test2</code> to test my function. Here is the code:</p>
<pre><code>test1={'integer_set': '{#integer_list#?}', 'integer_list': '#integer_range#(?,#integer_range#)*', 'integer_range': '#integer#(..#integer#)?', 'integer': '[+-]?\\d+'}
test2={'b': '#a#', 'f': '#e#', 'c': '#b#', 'e': '#d#', 'd': '#c#', 'g': '#f#', 'a': 'correct'}
def change(pat_dict:{str:str}):
print('Expanding: ',pat_dict)
num=0
while num<len(pat_dict):
inv_pat_dict = {v: k for k, v in pat_dict.items()}
for value in pat_dict.values():
for key in pat_dict.keys():
if key in value:
repl='#'+key+'#'
repl2='('+pat_dict[key]+')'
value0=value.replace(repl,repl2)
pat_dict[inv_pat_dict[value]]=value0
num+=1
print('Result: ',pat_dict)
change(test1)
change(test2)
</code></pre>
<p>sometimes I can get correct result like:</p>
<pre><code>Expanding: {'integer': '[+-]?\\d+', 'integer_list': '#integer_range#(?,#integer_range#)*', 'integer_set': '{#integer_list#?}', 'integer_range': '#integer#(..#integer#)?'}
Result: {'integer': '[+-]?\\d+', 'integer_list': '(([+-]?\\d+)(..([+-]?\\d+))?)(?,(([+-]?\\d+)(..([+-]?\\d+))?))*', 'integer_set': '{((([+-]?\\d+)(..([+-]?\\d+))?)(?,(([+-]?\\d+)(..([+-]?\\d+))?))*)?}', 'integer_range': '([+-]?\\d+)(..([+-]?\\d+))?'}
Expanding: {'c': '#b#', 'f': '#e#', 'e': '#d#', 'b': '#a#', 'g': '#f#', 'd': '#c#', 'a': 'correct'}
Result: {'c': '((correct))', 'f': '(((((correct)))))', 'e': '((((correct))))', 'b': '(correct)', 'g': '((((((correct))))))', 'd': '(((correct)))', 'a': 'correct'}
</code></pre>
<p>But most of time I get wrong results like that:</p>
<pre><code>Expanding: {'integer_range': '#integer#(..#integer#)?', 'integer': '[+-]?\\d+', 'integer_set': '{#integer_list#?}', 'integer_list': '#integer_range#(?,#integer_range#)*'}
Result: {'integer_range': '([+-]?\\d+)(..([+-]?\\d+))?', 'integer': '[+-]?\\d+', 'integer_set': '{(#integer_range#(?,#integer_range#)*)?}', 'integer_list': '#integer_range#(?,#integer_range#)*'}
Expanding: {'f': '#e#', 'a': 'correct', 'd': '#c#', 'g': '#f#', 'b': '#a#', 'c': '#b#', 'e': '#d#'}
Result: {'f': '(((((correct)))))', 'a': 'correct', 'd': '(((correct)))', 'g': '((((((correct))))))', 'b': '(correct)', 'c': '((correct))', 'e': '((((correct))))'}
</code></pre>
<p>How could I update my code to achieve my goal?</p>
| <p>Your problem is caused by the fact that python dictionaries are unordered. Try using a <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">OrderedDict</a> instead of <code>dict</code> and you should be fine. The OrderedDict works just like a normal <code>dict</code> but with ordering retained, at a small performance cost.</p>
<p>Note that while you could create an OrderedDict from a dict literal (like I did here at first), that dict would be unordered, so the ordering might not be guaranteed. Using a list of <code>(key, value)</code> pairs preserves the ordering in all cases.</p>
<pre><code>from collections import OrderedDict
test1=OrderedDict([('integer_set', '{#integer_list#?}'), ('integer_list', '#integer_range#(?,#integer_range#)*'), ('integer_range', '#integer#(..#integer#)?'), ('integer', '[+-]?\\d+')])
test2=OrderedDict([('b', '#a#'), ('f', '#e#'), ('c', '#b#'), ('e', '#d#'), ('d', '#c#'), ('g', '#f#'), ('a', 'correct')])
def change(pat_dict:{str:str}):
print('Expanding: ',pat_dict)
num=0
while num<len(pat_dict):
inv_pat_dict = {v: k for k, v in pat_dict.items()}
for value in pat_dict.values():
for key in pat_dict.keys():
if key in value:
repl='#'+key+'#'
repl2='('+pat_dict[key]+')'
value0=value.replace(repl,repl2)
pat_dict[inv_pat_dict[value]]=value0
num+=1
print('Result: ',pat_dict)
change(test1)
change(test2)
</code></pre>
|
Postman oAuth2 error Unauthorized grant type <p>I have an application that use oAuth2, and I try to request an access token from terminal with this command </p>
<pre><code>curl -X POST -vu clientapp:123456 http://localhost:8080/oauth/token -H "Accept: application/json" -d "password=spring&username=roy&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"
</code></pre>
<p>it works fine and I get a response like this</p>
<pre><code>{"access_token":"29c4c218-1d9a-4d2d-abe3-197bc2969679","token_type":"bearer","refresh_token":"6b7ffda7-4652-4197-b8e9-c80635eb9143","expires_in":38630,"scope":"read write"}
</code></pre>
<p>but the problem is when I try to request an access token via postman is always get this error:</p>
<pre><code>Handling error: InvalidClientException, Unauthorized grant type: client_credentials
</code></pre>
<p>how do get access token via postman like I get token via curl command?</p>
| <p>check the attached image, you need to pass like below .</p>
<p>And in header you also need to pass Authorization header.</p>
<p><code>Authorization</code> --> <code>Basic Y2xpZW50OnNlY3JldA==</code></p>
<p><a href="https://i.stack.imgur.com/EItxH.png" rel="nofollow"><img src="https://i.stack.imgur.com/EItxH.png" alt="enter image description here"></a></p>
<p>This will work for me , I hope this will help you .</p>
|
Use id to find the element to get information and add to array android java <p>I am getting element using </p>
<pre><code>JSONArray myArray = new JSONArray();
for (View touchable : allTouchables) {
JSONObject j = new JSONObject();
// To check if touchable view is button or not
//if( touchable instanceof LinearLayout) {
//System.out.println("LinearLayout "+touchable.toString());
//}
if( touchable instanceof Button) {
System.out.println("Button "+touchable.getId());
}
if( touchable instanceof TextView) {
TextView question = (TextView) findViewById(touchable.getId());
System.out.println("TextView "+ question.getText().toString());
//j.put("key",value);
}
if( touchable instanceof RadioButton) {
RadioButton value = (RadioButton)findViewById(touchable.getId());
System.out.println("RadioButton "+value.getText().toString());
}
if( touchable instanceof CheckBox) {
CheckBox value = (CheckBox)findViewById(touchable.getId());
System.out.println("CheckBox "+value.getText().toString());
}
j.put("array",myArray);// error1.1
}
</code></pre>
<blockquote>
<p>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference</p>
</blockquote>
<p>and error1.1 is:</p>
<blockquote>
<p>Unhandled exception: org.json.JSONException</p>
</blockquote>
<p>My Question is:</p>
<ol>
<li>How to use <code>touchable.getId()</code> to get the id of textview radio button and checkbox? So I can get further information for the said element.</li>
<li>Fix exception.</li>
</ol>
| <p>1) Instead of findViewById(touchable.getId())</p>
<p>Use this</p>
<pre><code>if( touchable instanceof TextView) {
TextView question = (TextView)touchable;
System.out.println("TextView "+ question.getText().toString());}
</code></pre>
<p>2) handle exception by proper try catch method</p>
<pre><code>try {
j.put("array",myArray);} catch (JSONException e) {e.printStackTrace();}
</code></pre>
|
unable to convert string to integer using parseInt() <p>As a beginner I know that Integer.parseInt() is used to convert strings to integers but here I tried a program but its not working</p>
<pre><code>Public static void main(String args[])
{
Scanner sr=new Scanner(System.in);
String s=sr.nextLine();
int i=Integer.parseInt(s);
System.out.println(i);
}
</code></pre>
<p>I want to take a line as input and convert it into integers and print but while executing it show NumberFormatException</p>
| <h2>Not all strings can be converted to integers.</h2>
<p>For example, how should <code>"xyz"</code> be converted to an integer? There's simply no way. Java notifies the programmer of such situations with an <code>NumberFormatExcpetion</code>. And we programmers should handle such exception properly.</p>
<pre><code>try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
// s cannot be converted to int, do sth.
e.printStackTrace();
}
</code></pre>
<p><code>Scanner.nextInt()</code> will throw a different exception (<code>InputMismatchException</code>) for invalid inputs. Nothing is changed in terms of handling inputs that simply cannot be converted to int.</p>
|
SQL Server Columns are equal but showing not equal. How are they different? <p>I have the following code</p>
<pre><code>select
Name, UniqueId,
checksum(Name) as CheckName,
checksum(UniqueId) as CheckId
from
DataManagementPipeline.dbo.pod_1801_energex_vegetation_zones
where
Name <> UniqueId
</code></pre>
<p>The results are the following</p>
<pre><code>Name UniqueId CheckName CheckId
********************************************************
VZ-4820/73 VZ-4820/73 -1880307869 -21513965
VZ-400706 VZ-400706 591267130 536293334
</code></pre>
<p>The values are the same (white space and all) yet they are appearing as different and interestingly the checksums are different. Is it an encoding issue as to why they are different? Any ideas?</p>
| <p><code>CHECKSUM</code> will return different values, if the types are different. See more at <a href="https://msdn.microsoft.com/en-us/library/ms189788.aspx" rel="nofollow">MSDN Checksum</a>. I think in your case, <em>Name</em> & <em>UniqueId</em> are of different types. Please see the example code below</p>
<pre><code>CREATE TABLE test(origname varchar(36), uniqueid nvarchar(36))
INSERT INTO test(origname,uniqueid)
values ('venkat',N'venkat')
SELECT CHECKSUM(origname), CHECKSUM(uniqueid) FROM test
-- Returned Values
178987073 1792344567
</code></pre>
|
Verilog help needed. Unexpected output <pre><code>module hi (
input wire clk,
output wire [6:0] a
);
wire [7:0] b;
assign b= 8'd24;
assign a[6:0] = b[7:1];
initial $display ("%d", a);
endmodule
</code></pre>
<p>I get a high impedance 'z' output. Where am i going wrong?</p>
| <p>You didn't give the <code>assign</code> statement a chance to propagate the values on the wires. The <code>initial</code> block executes first. Add a delay before the <code>$display</code>, or use <code>$strobe</code> instead. </p>
|
ls Not Listing Documents <p>When I use ls in the terminal all that shows up is the bin folder, and I can't find the documents folder I need to git clone into: </p>
<p>vagrant@vagrant-ubuntu-wily-64:~$ ls bin </p>
<p>What should I do?</p>
| <p>If you're just writing <code>ls bin</code> in your terminal, that's absolutely the expected behaviour. The first argument after the <code>ls</code> command is the folder which contains the files you want to list.
Use <code>cd</code> and <code>pwd</code>commands to move through your folders : <a class='doc-link' href="http://stackoverflow.com/documentation/linux/345/command-line-basics#t=201610140933027760027">Command Line Basics</a></p>
<p>I'd also suggest you to read the <code>ls</code> manual (<code>man ls</code>), and to search a little bit before asking questions on forums, because this is a very basic operation.</p>
|
The address of the specified listener name is incorrect while adding a listener <p>listener.ora</p>
<pre><code>CALLOUT_LISTENER =
(ADDRESS_LIST =
(ADDRESS= (PROTOCOL= IPC)(KEY=EXTPROC))
)
log_directory_callout_listener = /FIN10_2_17/finadm/assure
trc_directory_callout_listener = /FIN10_2_17/finadm/assure
SID_LIST_CALLOUT_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME= /ORACLE/ora11203/app/db)
(PROGRAM = /ORACLE/ora11203/app/db/bin/extproc)
)
)
</code></pre>
<p>tnsnames.ora</p>
<pre><code>extproc_connection_data =
(DESCRIPTION =
(ADDRESS =
(PROTOCOL = IPC)
(KEY = EXTPROC)
)
(CONNECT_DATA =
(SID = PLSExtProc)
)
)
</code></pre>
<p>I am trying to add a new listener in listener.ora file, I have named it as CALLOUT_LISTENER.
I am getting an error <code>specified listener name is incorrect</code> when I try to execute <code>lsnrctl start CALLOUT_LISTENER</code></p>
| <p>After few testing I came to know that you have a space in-front of the <code>SID_LIST_CALLOUT_LISTENER</code> name. </p>
<pre><code>[oracle@localhost admin]$ cat listener.ora
CALLOUT_LISTENER =
(ADDRESS_LIST =
(ADDRESS= (PROTOCOL= IPC)(KEY=EXTPROC))
)
log_directory_callout_listener = /FIN10_2_17/finadm/assure
trc_directory_callout_listener = /FIN10_2_17/finadm/assure
[here]SID_LIST_CALLOUT_LISTENER =
(SID_LIST =
(SID_DESC =
(SID_NAME = PLSExtProc)
(ORACLE_HOME= /ORACLE/ora11203/app/db)
(PROGRAM = /ORACLE/ora11203/app/db/bin/extproc)
)
)
</code></pre>
<p>After eliminating that space it works fine for you.</p>
|
Want to make Superfish vertical menu Responsive <p>I am using super fish vertical menu but its not working on responsive view. Need to fix this for responsive. </p>
| <p>Media queries will help you make it responsive
Have a look at this <a href="https://codepen.io/Imperative/pen/qaskf" rel="nofollow">codepen</a> another great example given in <a href="http://stackoverflow.com/a/15928198/2299040">this question</a> </p>
<p>following code is taken from codepen which makes the menu responsive.</p>
<pre><code>@media screen and (max-width: 768px) {
body {
margin: 0; } }
@media screen and (max-width: 768px) {
header.global nav #hamburger {
display: block; } }
header.global nav ul {
margin: 0;
padding: 0 25px;
display: block; }
@media screen and (max-width: 768px) {
header.global nav ul {
display: none;
margin: 7px 0;
padding: 0; } }
@media screen and (max-width: 768px) {
header.global nav ul li {
width: 100%;
background: #2d2d2d;
border-left: none;
border-right: none;
border-top: 1px solid #474747;
border-bottom: 1px solid #141414; }
header.global nav ul li:first-child {
border-top: none; }
header.global nav ul li:last-child {
border-bottom: none; } }
@media screen and (min-width: 768px) {
header.global nav ul li:hover > a {
position: relative; }
header.global nav ul li:hover > a:after {
content: "";
position: absolute;
left: 20px;
top: 40px;
border-width: 0 8px 8px;
border-style: solid;
border-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0) #ef3636;
display: block;
width: 0;
z-index: 999; } }
@media screen and (max-width: 768px) {
header.global nav ul li ul {
width: 100% !important;
}
}
@media screen and (min-width: 768px) {
header.global nav ul li ul li:hover a:after {
border: none; } }
</code></pre>
|
In a UITableViewCell used with autosizing, what is missing from the vertical constraints to make the height as small as possible? <p>I'm trying to use dynamic heights in a UITableView with a specific cell layout. Consider the following illustrative representation of that layout: </p>
<p><a href="https://i.stack.imgur.com/9jfGN.png" rel="nofollow"><img src="https://i.stack.imgur.com/9jfGN.png" alt="enter image description here"></a></p>
<p>I have the horizontal constraints working properly (15px from both edges, 15px between them, equal widths) but I'm struggling with the vertical constraints. Here are the vertical requirements for this layout:</p>
<ol>
<li>The vertical intrinsic content size of both the green and blue rectangles are based on external data which is passed to the cell at the time of creation.</li>
<li>Both rectangles are vertically centered within their superview</li>
<li>There will always be a minimum space of 15px between the top/bottom edges of the rectangles and the respective edges on the superview. In other words, whichever one is taller dictates the height of the superview (i.e. the cell)</li>
</ol>
<p>To that end, here's what I have constraint-wise so far:</p>
<ol>
<li>Vertical center constraints for both rectangles</li>
<li>Height constraints of the rectangles equal to or less than the height of the superview minus 30 (i.e. if the rectangle's height is 40, the superview must be a minimum of 70. This theoretically achieves the same effect as setting separate top and bottom '>= 15' constraints while using two less.)</li>
<li>Vertical content Hugging on the superview set to 'required' (i.e. 1000)</li>
</ol>
<p>The third point is because the second points together only define the minimum height for the superview (yellow), but not a maximum. In theory, if it had a height of 10,000 it would still satisfy those constraints.</p>
<p>My thought is setting its content hugging to 'required' would make the superview as short as possible without violating the other constraints, thus at all times, either the green rectangle or the blue rectangle would be 15 px from the edge depending on whichever was taller. However, the height still seems to be 'stretched out' as seen here...</p>
<p><a href="https://i.stack.imgur.com/O0wrq.png" rel="nofollow"><img src="https://i.stack.imgur.com/O0wrq.png" alt="enter image description here"></a></p>
<blockquote>
<p>Note: The views on the inside are properly vertically centered and correctly maintain a minimum distance from the top/bottom edges. The problem I'm trying to solve is restricting the height of the superview to be as small as possible.</p>
</blockquote>
<p>It doesn't appear that I'm getting any ambiguous constraint messages (I don't see anything in the logs, but I believe I should be because again <= constraints aren't enough on their own, so I'm not sure exactly how to use the tools to debug this, or to find out which constraint is driving the height.</p>
<p>So, can anyone help?</p>
<p><em>P.S. To ensure it wasn't something external to the cell, like forgetting to configure auto-heights for the UITableView, I removed the two rectangles and replaced them with a simple multi-line label pinned to all four edges. When I ran it with that, the cell properly shrank in size as expected. I bring that up to hopefully stave off answers suggesting that's potentially the problem.</em></p>
| <p>Reading the requirements you provided I have added constraints shown below:</p>
<p><a href="https://i.stack.imgur.com/LWsK0.png" rel="nofollow"><img src="https://i.stack.imgur.com/LWsK0.png" alt="enter image description here"></a></p>
<p>For demonstration purpose I have used a simple view container instead of a cell. Since inner boxes will have intrinsic content size derived externally, I have taken labels to mimic that.</p>
<p>To reiterate, constraints added are:</p>
<p><strong>Horizontal</strong></p>
<ol>
<li>Container view(orange) has leading and trailing constraints with the super view.</li>
<li>Inner views has leading, trailing constraints with 15points of space.</li>
<li>Both labels have leading and trailing constraints with 9 points.</li>
<li>Both inner views have equal width constriant.</li>
</ol>
<p><strong>Vertical</strong></p>
<ol>
<li>Container view is vertically in center.</li>
<li>Both inner views have vertically center constraint applied.</li>
<li>Both inner views have top and bottom constraints with >= 15 condition.</li>
<li>Both inner labels have top and bottom constraints with their super views.</li>
</ol>
<p>I set the no. of lines property of both labels to zero so that they can grow at run time.</p>
<p>At runtime I changed the text of one of the label and the box and container grew accordingly.</p>
<p><a href="https://i.stack.imgur.com/ISGIZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/ISGIZ.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/Lvkm4.png" rel="nofollow"><img src="https://i.stack.imgur.com/Lvkm4.png" alt="enter image description here"></a></p>
<p>To refresh your cell height implement heightForRow method and provide the latest height. A typical snippet will look something like this (assuming you have already initialized the cell):</p>
<pre><code>cell.needsUpdateConstraints()
cell.updateConstraintsIfNeeded()
cell.contentView.setNeedsLayout()
cell.contentView.layoutIfNeeded()
let height = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + 1
return height
</code></pre>
<p>Hope this will help.</p>
|
How to conditionally add attributes to react DOM element <p>I have a scenario where I'm using React.js to create a div using the following code :</p>
<pre><code>React.createElement('div', {}, "div content")
</code></pre>
<p>Some additional javascript processing will allow me afterwards to deduce if this div needs to have the className attribute set to" ClassA" or "ClassB" or if it shouldn't have className at all. </p>
<p>Is there a way in javascript to access the div that was created from the React DOM and to add to it the className attribute? </p>
<p>Note : I couldn't achieve this is JSX so I resorted to the createElement method. </p>
<p>Edit: it is worth to mention that i might need to conditionally add attributes other than className. For example, I might need to add to an anchor tag an "alt" attribute or not based on conditional logic.
Thank you in advance. </p>
| <p>This is a quite normal situation in React and requires virtually no special handling.</p>
<p><sup>Note: It is best to hand props down the component tree declaratively but if that is not an option you can bind listener functions in <code>componentDidMount</code> and unbind them in <code>componentWillUnmount</code> as shown in the following example. So long as they call setState, your component's render function will get triggered.</sup></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { Component, cloneElement } = React
class Container extends Component {
constructor(props) {
super(props)
this.state = { classNames: [ 'foo' ] }
this.appendClassName = () => {
const { classNames } = this.state
this.setState({ classNames: [ ...classNames, `foo_${classNames.length}` ] })
}
}
componentDidMount() {
document.querySelector('button').addEventListener('click', this.appendClassName)
}
componentWillUnmount() {
document.querySelector('button').removeEventListener('click', this.appendClassName)
}
render() {
const { children } = this.props
const { classNames } = this.state
return <div className={classNames.join(' ')}>{children}</div>
}
}
ReactDOM.render(<Container>I am content</Container>, document.getElementById('root'))</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.foo {
font-family: monospace;
border: 1px solid rgb(100, 50, 50);
font-size: 1rem;
border-style: solid;
border-width: 1px;
width: 50vw;
height: 50vh;
margin: auto;
display: flex;
align-self: center;
justify-content: center;
align-items: center;
}
.foo.foo_1 {
font-size: 1.5rem;
background-color: rgb(200, 100, 200);
}
.foo.foo_2 {
font-size: 2rem;
border-radius: 3px 7px;
background-color: rgb(180, 120, 200);
}
.foo.foo_3 {
border-style: dashed;
background-color: rgb(175, 130, 180);
}
.foo.foo_4 {
border-width: 2px;
background-color: rgb(160, 165, 170);
}
.foo.foo_5 {
border-width: 1rem;
background-color: rgb(150, 200, 150);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<button>Click me</button>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p><sup>P.S. - Avoid using <code>componentWillMount</code>, it can lead to bugs in the lifecycle and there is talk that it may be removed in a future version of React. Always make async <em>side-effect</em> laden requests within <code>componentDidMount</code> and clean them up in <code>componentWillUnmount</code>. Even if you have nothing to render, you are best off rendering a placeholder component until your data arrives (best option for fast loading), or nothing at all.</sup></p>
|
Django django.test django.db.models.fields.related_descriptors.ManyRelatedManager <p>Please assert type: 'django.db.models.fields.related_descriptors.ManyRelatedManager'. </p>
<p>In other words, how to import the module in order to assert that the field 'user.groups' is of type 'django.db.models.fields.related_descriptors.ManyRelatedManager'?</p>
<pre><code>from django.db.models.fields import related_descriptors
# AttributeError: 'module' object has no attribute 'ManyRelatedManager'
self.assertIsInstance(user.groups, related_descriptors.ManyRelatedManager)
print(type(dummy_user.groups)) # <class 'django.db.models.fields.related_descriptors.ManyRelatedManager'>
</code></pre>
<p>Here's the error:
AttributeError: 'module' object has no attribute 'ManyRelatedManager</p>
<p>Thanks</p>
| <p>You cannot make such an assertion on <code>user.groups</code> and <code>related_descriptors.ManyRelatedManager</code>. </p>
<p>The <code>ManyRelatedManager</code> class is not accessible using import like <code>from django.db.models.fields import related_descriptors</code> because if you look at the source code of django, the <code>ManyRelatedManager</code> lives inside of <code>create_forward_many_to_many_manager</code> function.</p>
<p>P.S. I do not see any reasons why you want to check the type of <code>user.groups</code>. It is always the same and tested by django tests already.</p>
|
$state.go on search input <p>I've built a small movies search app with AngularJS, UI Router, UI Bootstrap Typeahead and Elasticsearch. For reference, I asked <a href="http://stackoverflow.com/questions/40012048/search-input-and-state-go">this</a> yesterday here and received a good, quick answer. I managed to get it working without ng-keypress. I simply put <code>$state.go()</code> right in the function and the linking/transition worked. On keypress on the search input it goes from the home/query page to the results page. However, it is NOT displaying any suggestions. Once it goes to the results page... nothing happens. I have to type in the search input again for suggestions and search to execute.</p>
<p>I'm really trying to get functionality where on the hp, as soon as a user types in the search input that it goes to the results page AND once it gets there, that suggestions are displaying and search can be executed.</p>
<p>Here is my code</p>
<p>HTML</p>
<pre><code><form ng-submit="vm.search()" class="form-horizontal col-md-8 col-md-offset-2" id="hp-search-form"><div class="input-group input-group-lg">
<input type="text" name="q" ng-model="vm.searchTerms" ng-keypress="navigate('search')" placeholder="Search" class="form-control input-lg" uib-typeahead="query for query in vm.getSuggestions($viewValue)" typeahead-show-hint="true" typeahead-focus-first="false" typeahead-on-select="vm.search($item)" auto-focus style="border:0px;">
<i ng-show="loadingLocations" class="fa fa-refresh"></i>
<div ng-show="noResults">
<i class="fa fa-remove"></i> No Results Found
</div>
<span class="input-group-btn">
<button class="btn btn-primary btn-lg" type="submit" value="Search" id="hp-search-button" ng-submit="vm.search()"><i class="fa fa-search fa-lg"></i></button>
</span>
</code></pre>
<p>
</p>
<p>and the getSuggestions function in the <code>searchCtrl</code></p>
<pre><code> vm.getSuggestions = function(query) {
$state.go('search');
console.log(vm.searchTerms);
vm.isSearching = true;
console.log(vm.searchTerms);
return searchService.getSuggestions(query).then(function(es_return){
console.log(vm.searchTerms);
var suggestions = es_return.hits.hits;
if (suggestions) {
//console.log(suggestions);
return vm.autocomplete.suggestions = suggestions.map(function(item) {
return item._source.ymme;
//console.log(autocomplete.suggestions);
});
}
else {
vm.autocomplete.suggestions = [];
vm.noResults = true;
}
vm.isSearching = false;
},
function(error) {
//console.log('ERROR: ', error.message);
vm.isSearching = false;
});
};
</code></pre>
| <p>You could pass the results along with the $state.go() like so:</p>
<pre><code> $state.go('search', { results: vm.autocomplete.suggestions });
</code></pre>
<p>You'll be needing to do the $state.go() in the section where you're returning the result ofc. In the config.routes.js file where you have 'search' defined, you'll also need this so the next page can accept the 'results' as part of the $state.params:</p>
<pre><code> params: {
results: null
}
</code></pre>
<p>In the 'search' page, you can then access the search results via this:</p>
<pre><code> $state.params.results
</code></pre>
<p>Then you can do the work of doing something with the results.</p>
|
Completely uninstall Xcode and all settings <p>I am trying to completely uninstall Xcode. However I followed the post <a href="http://stackoverflow.com/questions/31011062/how-to-completely-uninstall-xcode-and-clear-all-settings">How to Completely Uninstall Xcode and Clear All Settings</a></p>
<p>After following the instructions, I ran find for xcode string in my entire system and found the following locations.</p>
<p>Can I remove the below or should not I?</p>
<pre><code>/private/var/db/receipts/com.apple.pkg.Xcode.bom
/private/var/db/receipts/com.apple.pkg.Xcode.plist
/private/var/db/xcode_select_link
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.DeveloperTools/7.2-7C68/Xcode
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.DeveloperTools/7.2-7C68/Xcode/CachedSpecifications-Xcode
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.DeveloperTools/7.2-7C68/Xcode/CachedSpecifications-xcodebuild
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.DeveloperTools/7.2-7C68/Xcode/PlugInCache-xcodebuild-Debug.xcplugincache
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode/CachedSpecifications-Xcode
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode/CachedSpecifications-xcodebuild
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode/PlugInCache-xcodebuild-Debug.xcplugincache
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.dt.Xcode.InstallCheckCache_14F1021_7C1002
/private/var/folders/rj/90swtn490tq7hgw36cmsln0m0000gn/C/com.apple.Xcode.501
/private/var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/C/com.apple.DeveloperTools/7.2-7C68/Xcode
/private/var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/C/com.apple.DeveloperTools/7.2-7C68/Xcode/CachedSpecifications-xcodebuild
/private/var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/C/com.apple.DeveloperTools/7.2-7C68/Xcode/PlugInCache-xcodebuild-Debug.xcplugincache
/private/var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode
/private/var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode/CachedSpecifications-xcodebuild
/private/var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode/PlugInCache-xcodebuild-Debug.xcplugincache
/private/var/folders/zz/zyxvpxvq6csfxvn_ngzzzzzvzzzzzy/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode
/private/var/folders/zz/zyxvpxvq6csfxvn_ngzzzzzvzzzzzy/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode/CachedSpecifications-xcodebuild
/private/var/folders/zz/zyxvpxvq6csfxvn_ngzzzzzvzzzzzy/C/com.apple.DeveloperTools/7.2.1-7C1002/Xcode/PlugInCache-xcodebuild-Debug.xcplugincache
/private/var/root/Library/Preferences/com.apple.dt.xcodebuild.plist
/private/var/root/Library/Preferences/xcodebuild.plist
/System/Library/Automator/Build Xcode Project.action
/System/Library/Automator/Build Xcode Project.action/Contents/MacOS/Build Xcode Project
/Users/mac1234/Library/Caches/com.apple.dt.Xcode.Playground
/Users/mac1234/Library/Preferences/com.apple.dt.Xcode.LSSharedFileList.plist
/Users/mac1234/Library/Preferences/com.apple.dt.Xcode.Playground.plist
/Users/mac1234/Library/Preferences/com.apple.dt.xcodebuild.plist
/usr/bin/xcode-select
/usr/bin/xcodebuild
/usr/share/man/man1/xcode-select.1
</code></pre>
| <p>refer this link and do something like this using terminal n your mac,</p>
<p><a href="http://recomhub.com/blog/how-to-uninstall-xcode-on-mac-os-x/" rel="nofollow">http://recomhub.com/blog/how-to-uninstall-xcode-on-mac-os-x/</a></p>
<pre><code>sudo /Developer/Library/uninstall-devtools --mode=all
</code></pre>
<p>Its working and easy to do.</p>
|
AngularJS - HTML Table handling of click events <p>I have the following table:</p>
<pre><code><table>
<tr data-ng-repeat-start=... data-ng-click="contactGroup.expanded = !contactGroup.expanded">
<td class="myColumn" data-ng-click=...>
</code></pre>
<p>when a row is clicked than the row expands and additional information is shown to this row - this works fine.
In this row there is also a column (<strong>myColumn</strong>) which can be clicked.
If this column is clicked than first the row expands and than the proper click event is handled. Is there a way to prevent the expandation of the row when the column <strong>myColumn</strong> is clicked?</p>
| <p>The reason it is happening because of event bubbling and to stop it <code>event.stopPropogation()</code> can be used.</p>
<p>While clicking the column bind a method; and use <code>$event</code> to prevent default</p>
<pre><code><table>
<tr data-ng-repeat-start=... data-ng-click="contactGroup.expanded = !contactGroup.expanded">
<td class="myColumn" data-ng-click="toggleColumn($event)">
</code></pre>
<p>And in Controller:</p>
<pre><code>$scope.toggleColumn = function(e){
e.stopPropogation(); //This would prevent event bubbling from td to tr
e.preventDefault(); //This will prevent default action like link load on click of hyperlink
//toggle functionality
}
</code></pre>
|
broken dropdown menu code <p>I was following <a href="https://www.youtube.com/watch?v=PSm-tq5M-Dc" rel="nofollow">https://www.youtube.com/watch?v=PSm-tq5M-Dc</a> a tutorial for doing a drop-down menu in a gui. In the video the code works but i can't get mine too, I think it may have something to do with different python versions.</p>
<pre><code>from tkinter import *
def doNothing():
print ("ok ok i won't...")
root = Tk()
menu = Menu(root)
roo.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Project..."), comand=doNothing
subMenu.add_command(label="New"), comand=doNothing
subMenu.add_separator()
subMenu.add_command(label="Exit", command=doNothing)
editMenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editMenu)
editMenu.add_command(label="Redo", comand=doNothing)
root.mainloop()
</code></pre>
<p>This is the error</p>
<pre><code>C:\Users\TheSheep\Desktop\pygui>python dropdown.py
File "dropdown.py", line 14
subMenu.add_command(label="New Project..."), comand=doNothing
^
SyntaxError: can't assign to function call
</code></pre>
| <p>You have few "typos"</p>
<ul>
<li><p>it has to be <code>root</code> instead <code>roo</code> in <code>roo.config()</code></p></li>
<li><p><code>)</code> has to be at the end of line in both</p>
<pre><code>subMenu.add_command(label="New Project..."), comand=doNothing #
subMenu.add_command(label="New"), comand=doNothing
</code></pre></li>
<li><p>it has to be <code>command=</code> instead of <code>comand=</code> (see: <code>mm</code>) </p></li>
</ul>
<p>.</p>
<pre><code>from tkinter import *
def doNothing():
print ("ok ok i won't...")
root = Tk()
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Project...", command=doNothing)
subMenu.add_command(label="New", command=doNothing)
subMenu.add_separator()
subMenu.add_command(label="Exit", command=doNothing)
editMenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editMenu)
editMenu.add_command(label="Redo", command=doNothing)
root.mainloop()
</code></pre>
|
How to Bind Years in DropdownList <p>Here I have a task that Years Should be Bind in DropdownList Like 1947 to 2016 if I write Code Like</p>
<pre><code><select>
<option value="1947">1947</option>
<option value="2016">2016</option>
</select>
</code></pre>
<p>Its Taken whole day</p>
| <p>This could be done by javascript for example:</p>
<pre><code><select id="year"></select>
</code></pre>
<p>JScript:</p>
<pre><code>var year = 1947;
var till = 2016;
var options = "";
for(var y=year; y<=till; y++){
options += "<option>"+ y +"</option>";
}
document.getElementById("year").innerHTML = options;
</code></pre>
|
Bootstrap date time picker <p>I am trying to implement the date time picker as explained here <a href="https://eonasdan.github.io/bootstrap-datetimepicker/#minimum-setup" rel="nofollow">https://eonasdan.github.io/bootstrap-datetimepicker/#minimum-setup</a>, I have downloaded the <code>js</code> file <code>css</code> file to the directory <code>js</code> and <code>css</code>. But the calendar is not popup up when click on icon.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $(function() {
$('#datetimepicker1').datetimepicker();
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker-standalone.css">
<script type="text/javascript" src="js/bootstrap-datetimepicker.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| <p>Try This:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<script src="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#datetimepicker1').datetimepicker();
});
</script>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
Set two button below grid View <p>Actually i want to set the two button below the grid view and i try Relative Layout and other things but the problem is not solve</p>
<p>XML code:</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"
android:layout_width="match_parent"
android:id="@+id/widget"
android:layout_height="match_parent">
<include layout="@layout/toolbar"
android:id="@+id/toolbar">
</include>
<GridView
android:id="@+id/gridView1"
android:layout_width="363dp"
android:layout_height="442dp"
android:columnWidth="90dp"
android:gravity="bottom"
android:layout_weight="1"
android:layout_marginTop="70dp"
android:layout_below="@+id/toolbar"
android:horizontalSpacing="0dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="0dp"
android:numColumns="2"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"></GridView>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p><a href="https://i.stack.imgur.com/FVFc3.png" rel="nofollow"><img src="https://i.stack.imgur.com/FVFc3.png" alt="enter image description here"></a></p>
| <p>try to this hope this can help you..</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/rlListChariTrust"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/ll"
android:orientation="vertical">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />
<GridView
android:id="@+id/gridView1"
android:layout_width="363dp"
android:layout_height="442dp"
android:layout_below="@+id/toolbar"
android:layout_marginLeft="10dp"
android:layout_marginRight="0dp"
android:layout_marginTop="70dp"
android:layout_weight="1"
android:columnWidth="90dp"
android:gravity="bottom"
android:horizontalSpacing="0dp"
android:numColumns="2"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
</android.support.design.widget.CoordinatorLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="bt1" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="bt2" />
</LinearLayout></RelativeLayout>
</code></pre>
|
Application design is not display properly in simulator after updating xcode 8 <p>I have updated xcode 8 and then tested application in <strong>iphone 6 (ios 10) simulator</strong>.
Application desiging is not showing properly as it should be.
In xcode 8, storyboard designing is not proper.
Storyboard showing designs properly but runtime it's now showing properly.
I'm not able to get any solution.
If anyone know the answer please suggest me.</p>
| <p>from storyboard, Select your view controller and set proper device from View As button. If your storyboard is designed using previous version of Xcode, try selecting iPhone SE from "View As" as shown in below image.</p>
<p><a href="https://i.stack.imgur.com/IZ2Rz.png" rel="nofollow"><img src="https://i.stack.imgur.com/IZ2Rz.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/aMduV.png" rel="nofollow"><img src="https://i.stack.imgur.com/aMduV.png" alt="selecting View As option"></a></p>
|
Get location of text in textview on the screen <p>I make an app that allow user to read in English and in my language.
But the text is long, maybe 100 lines for each file.<br>
so when the user scroll down maybe to line 20(like reading in English), the when user switch to my language, it is on line 15 or 16.
so how can i let the user go to line 20 when they switch to other language?
now i am using Textview to show the text. </p>
| <p>Easiest way is to get it using <code>View.getLocationOnScreen();</code> OR <code>getLocationInWindow()</code>;</p>
<p>And if you want position relative to root Layout then <a href="http://stackoverflow.com/a/3621042/3496570">See</a></p>
|
Python and Pip not in sync <p>I am working on a remote linux server with python 2.7.6 pre-installed. I want to <strong>upgrade to python 2.7.12</strong> (because I am not able to install some libraries on the 2.7.6 due to some <strong>ssl error</strong> shown below).</p>
<p>I downloaded and compiled from source and installed 2.7.12 and <code>python2.7</code> opens 2.7.12. However, I still get an update python version warning while using pip. It seems the pip has not synced with 2.7.12 and continues to serve 2.7.6 and I am not able to find other installations of pip in system.</p>
<p>I just want a working version of python2.7.x with pip/pip2/pip2.7 working properly.</p>
<pre><code> /usr/local/lib/python2.7/dist-packages/pip-8.1.2-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/pip-8.1.2-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
</code></pre>
| <p>Upgrade (and automatically reinstall) pip this way: </p>
<pre><code>/path/to/python2.7.12 -m pip install pip --upgrade
</code></pre>
<p>The <code>-m</code> flag loads the corresponding module, and in the case of pip will execute <code>pip</code> (thanks to <a href="https://docs.python.org/3/library/__main__.html" rel="nofollow">the power of the <code>__main__</code> module inside the package</a>).</p>
<p>After installation, your current <code>pip</code> should also be up-to-date.</p>
<hr>
<p>Alternatively, you could run </p>
<pre><code>/path/to/python2.7.12 /path/to/pip2 install pip --upgrade
</code></pre>
<hr>
<p>NB: be wary about which <code>pip</code> and <code>python2</code> you're running: there'll probably be a <code>/usr/bin/python</code> and /usr/bin/pip<code>next to the ones you installed in</code>/usr/local/<code>. The ones in</code>/usr/bin` should just be updated following the standard system updates, if at all.</p>
|
Check the username and password using .NET Webservice (SOAP) <p>I want to consume a SOAP Webservice in android, created in .NET framework and using it want to check the username and password.</p>
<p>How to check the username and password entered by user with the data which is stored on Server using webservice?</p>
| <p>Use <strong>okHttp</strong> library for android.This library will provide you all the HTTP methods to consume Webservice.</p>
|
Datetime VB net to SQL table <p>I have this:</p>
<pre><code> Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim con As New SqlConnection
Dim myCommand As New SqlCommand
Try
Dim a As String
con.ConnectionString = "Data Source=SVNAV;Initial Catalog=NAV_Vermorel_Live;User ID=sa;Password=1234"
con.Open()
Dim laser As String
Dim debit As String
Dim indoire As String
Dim uzinaj As String
Dim dlaser As Nullable(Of DateTime) = DateTime.Now
Dim ddebit As Nullable(Of DateTime) = DateTime.Now
Dim dindoire As Nullable(Of DateTime) = DateTime.Now
Dim duzinaj As Nullable(Of DateTime) = DateTime.Now
If NewCheckBox1.Checked = True Then
laser = "Finished"
Else
laser = "In Progress"
dlaser = Nothing
End If
If NewCheckBox2.Checked = True Then
debit = "Finished"
Else
debit = "In Progress"
ddebit = Nothing
End If
If NewCheckBox3.Checked = True Then
indoire = "Finished"
Else
indoire = "In Progress"
dindoire = Nothing
End If
If NewCheckBox4.Checked = True Then
uzinaj = "Finished"
Else
uzinaj = "In Progress"
duzinaj = Nothing
End If
a = "INSERT INTO [dbo].[SC Vermorel SRL$PregatirePROD]
(
[FPO]
,[Articol]
,[Descriere]
,[Cantitate]
,[LASER]
,[DEBITARE]
,[INDOIRE]
,[UZINAJ]
,[EndDateLASER]
,[EndDateDEBIT]
,[EndDateINDOIRE]
,[EndDateUZINAJ])
VALUES
(@FPO,
@Articol
,@Descriere
,@Cantitate
,@LASER
,@DEBITARE
,@INDOIRE
,@UZINAJ
,@EndDateLASER
,@EndDateDEBIT
,@EndDateINDOIRE
,@EndDateUZINAJ)"
myCommand = New SqlCommand(a, con)
myCommand.Parameters.AddWithValue("@FPO", txtFpo.Text)
myCommand.Parameters.AddWithValue("@Articol", txtItem.Text)
myCommand.Parameters.AddWithValue("@Descriere", txtDesc.Text)
myCommand.Parameters.AddWithValue("@Cantitate", txtQty.Text)
myCommand.Parameters.AddWithValue("@LASER", laser)
myCommand.Parameters.AddWithValue("@DEBITARE", debit)
myCommand.Parameters.AddWithValue("@INDOIRE", indoire)
myCommand.Parameters.AddWithValue("@UZINAJ", uzinaj)
myCommand.Parameters.AddWithValue("@EndDateLaser", dlaser)
myCommand.Parameters.AddWithValue("@EndDateDEBIT", ddebit)
myCommand.Parameters.AddWithValue("@EndDateINDOIRE", dindoire)
myCommand.Parameters.AddWithValue("@EndDateUZINAJ", duzinaj)
myCommand.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Eroare ..." & ex.Message, "Inserare campuri")
Finally
con.Close()
End Try
Me.SC_Vermorel_SRL_PregatirePRODTableAdapter.Fill(Me.NAV_Vermorel_LiveDataSet._SC_Vermorel_SRL_PregatirePROD)
End Sub
</code></pre>
<p>The table design from, prtscreen from SSM:</p>
<p><a href="https://i.stack.imgur.com/lLOfQ.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/lLOfQ.jpg" alt="tabledesign"></a></p>
<p>Im trying to add the DateTime.Now value of dlaser into an SQL field. I get SQL type overflow, dates must be between etc etc. </p>
<p>The format of date witch SMS displays is: 2016-09-30 14:58:46.343. SQL Server 2005. </p>
<p>How can i be sure that vb net application outputs datetime in same format?</p>
| <p>In the <code>Else</code> part you leave VB variable <code>dlaser</code> uninitialized, which means it has value <code>0001-01-01 00:00:00</code>. But that variable is always used for parameter <code>@EndDateLaser</code> to set column [EndDateLASER].</p>
<p>Column [EndDateLASER] has SQL type <code>datetime</code>, but <code>datetime</code> does not allow <code>0001-01-01</code>, the minimum value allowed is <code>1753-01-01</code>.</p>
<p>Apart from that, I wonder why you <em>sometimes</em> add a <code>@dlaser</code> SqlParameter (with value DBNull). For the query as shown that parameter is irrelevant because it does not use <code>@dlaser</code> anywhere. And also, why add it only in one situation, while your query is fixed.</p>
|
Adding 0 (Zero) as Key in array doesn't work but when i change it to 1 it works <p>I'm still confused why when i use 0 as key in array it does not work but when i changed it to 1 it works normally. Can someone explain me why this is happening.
Thanks in advance.</p>
<h1>$myArray = {1,2,3,4}</h1>
<h1>Using foreach loop to get the data and to add to my new array</h1>
<pre><code> $o = array();
foreach($myArray as $key=>$value){
//using to $key to set the key for item in my array
$o[$key] = $value;
}
</code></pre>
<h1>Output should be like this</h1>
<h1>$o={0:1,1:2,2:3,3:4}</h1>
<p>But when the key start with 0 it returns like this</p>
<h1>$o={1,2,3,4}</h1>
<p>When i change it to </p>
<pre><code>$o = array();
foreach($myArray as $key=>$value){
//using to $key to set the key for item in my array
$o[$key+1] = $value;
}
</code></pre>
<h1>the ouput</h1>
<h1>$o={1:1,2:2,3:3,4:4}</h1>
<h1>my main goal ouput</h1>
<h1>$o={0:1,1:2,2:3,3:4}</h1>
| <p>check this,</p>
<pre><code><?php
$o = array(1,2,3,4);
$bind = array();
foreach($o as $key=>$value){
$bind[] = $key.":".$value;
}
echo implode( ',', $bind );
?>
Output: 0:1,1:2,2:3,3:4
</code></pre>
|
SQL Server 2008 Stored Procedure execution issue <p>I will try to explain the problem in details. I wrote a SP and executed it successfully. Here it is:</p>
<pre><code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[InvoiceReference]
@StartDate DateTime = NULL,
@EndDate DateTime = NULL,
@DocumentType nvarchar(50) = NULL,
@Partners nvarchar(MAX) = NULL,
@PriceFrom numeric(19,6) = NULL,
@PriceTo numeric(19,6) = NULL,
@VATFrom numeric(19,6) = NULL,
@VATTo numeric(19,6) = NULL,
@PageNumber INT,
@PageSize INT
AS
BEGIN SET NOCOUNT ON;
DECLARE @StartPage as int
DECLARE @EndPage as int
SET @StartPage = ((@PageNumber-1) * @PageSize) + 1;
SET @EndPage = @StartPage + (@PageSize) - 1;
WITH ResultSet As (select
ROW_NUMBER() OVER (order by d.DocumentID) AS 'RowNumber',
d.DocNumber, dt.Name as DocumentTypesName, d.Date, p.Name as PartnersName, dd.SalePrice, dd.VAT, (dd.SalePrice + dd.VAT) as TotalSum
from [dbo].[Documents] d join [dbo].[DocumentTypes] dt on d.TypeID = dt.TypeID
join [dbo].[Partners] p on d.PartnerID = p.PartnerID
join [dbo].[DocumentDetails] dd on d.DocumentID = dd.DocumentID
where ((@StartDate is null) or (d.Date >= @StartDate))
and ((@EndDate is null) or (d.Date <= @EndDate))
and ((@DocumentType is null) or (dt.Name = @DocumentType))
--and ((@Partners is null) or (p.Name = @Partners))
and ((@Partners is null) or (p.Name in (select * from dbo.fnSplitString(@Partners, ','))))
and ((@PriceFrom is null) or (dd.SalePrice >= @PriceFrom))
and ((@PriceTo is null) or (dd.SalePrice <= @PriceTo))
and ((@VATFrom is null) or (dd.VAT >= @VATFrom))
and ((@VATTo is null) or (dd.VAT <= @VATTo))
)
Select * from ResultSet rs WHERE RowNumber between @StartPage and @EndPage
ORDER BY rs.Date ASC
END
</code></pre>
<p>But then i found that i had to make a filter by more than one "Partner" (for example: Partner1, Partner2, ...). Then i wrote a function which splitted the SP parameter @Partners in separate strings. But when i commented the old part in the "where" clause and putted the new one (invoking the function i wtrote) it gave me this error message: "Cannot resolve the collation conflict between "Cyrillic_General_CI_AS" and "Cyrillic_General_CS_AS" in the equal to operation." when i tried to execute the SP. And the error is on line 26, which is:
SET @StartPage = ((@PageNumber-1) * @PageSize) + 1;
and i haven't changed anything there. I read some matirials i found here about collation but i still can't figure the problem out for myself. The function i wrote is:</p>
<pre><code> ALTER FUNCTION [dbo].[fnSplitString]
(
@string NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @output TABLE(splitdata NVARCHAR(200)
)
BEGIN
DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
WHILE @start < LEN(@string) + 1 BEGIN
IF @end = 0
SET @end = LEN(@string) + 1
INSERT INTO @output (splitdata)
VALUES(SUBSTRING(@string, @start, @end - @start))
SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
END
RETURN
END
</code></pre>
<p>Any help will be appreciated.</p>
| <p>You have to set default collation before comparing result OR before IN Statement.</p>
<p>try your where condition as below:</p>
<pre><code>and ((@Partners is null) or (p.Name COLLATE DATABASE_DEFAULT in (select * from dbo.fnSplitString(@Partners, ','))))
</code></pre>
<p><strong>OR</strong></p>
<pre><code>Set datatype to NVARCHAR of related column
</code></pre>
|
UPDATE with SELECT with a reference to the updated table <p>I have a script:<br/></p>
<pre><code>UPDATE a
SET fieldX =
(SELECT F_Aggregate(x.fieldy)
FROM table_B
INNER JOIN ....
INNER JOIN ....
INNER JOIN ....
....
INNER JOIN table_C on .....
WHERE table_C.fieldY = table_A.fieldY)
FROM table_A a;
</code></pre>
<p>But now I want to update fieldX only when the select gives a different value. <br/>Like:<br/></p>
<pre><code>UPDATE a
SET fieldX =
(SELECT dbo.F_Aggregate(x.fieldy) as result
FROM table_B
INNER JOIN ....
INNER JOIN ....
INNER JOIN ....
....
INNER JOIN table_C on .....
WHERE table_C.fieldY = table_A.fieldY)
FROM table_A a
WHERE fieldX <> result;
</code></pre>
<p>I have found questions/answers that looks like this but they all have a select statement without a reference to the updated table.
Does anybody know a solution?</p>
| <p>Move the calculation in other <code>Data Source</code> - it could be CTE, table variable or temporary table, etc. Then join the updated table with it:</p>
<pre><code>WITH DataSource (fieldY, result) AS
(
SELECT table_C.fieldY
,dbo.F_Aggregate(x.fieldy) as result
FROM table_B
INNER JOIN ....
INNER JOIN ....
INNER JOIN ....
....
INNER JOIN table_C on .....
GROUP BY table_C.fieldY
)
UPDATE table_A
SET fieldX = result
FROM table_A A
INNER JOIN DataSource DS
ON A.[fieldY] = DS.[fieldY]
WHERE fieldX <> result
</code></pre>
|
"eurekaHealthIndicator" issue with netflix eureka client <p>Trying to write Eureka Client With Spring Cloud Netflix v1.2.0.Release
but facing the below mentioned issue. PFB code and configurations.</p>
<p>EurekaClient.java</p>
<pre><code>import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Configuration
@EnableAutoConfiguration
@EnableEurekaClient
@RestController
@ComponentScan(basePackages={"com.west.eas.netflix.config"})
public class EurekaClient {
@RequestMapping("/")
public String home() {
return "Hello World";
}
public static void main(String[] args) {
new SpringApplicationBuilder(EurekaClient.class).run(args);
}
}
</code></pre>
<p>application.yml</p>
<pre><code>server:
port: 9000
spring:
application:
name: eas-eureka-client
eureka:
client:
healthcheck:
enabled: true
serviceUrl:
defaultZone: http://localhost:8761/eureka/
instance:
preferIpAddress: true
</code></pre>
<p>bootstrap.yml</p>
<pre><code>spring:
application:
name: eu-client
cloud:
config:
uri: http://localhost:8888
encrypt:
failOnError: false
</code></pre>
<p>Client fails to start with following error</p>
<blockquote>
<p>" Parameter 0 of method eurekaHealthIndicator in
org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration$EurekaHealthIndicatorConfiguration
required a bean of type 'com.netflix.discovery.EurekaClient' that
could not be found."</p>
</blockquote>
<p>the below screenshot will have more details on error stack</p>
<p><a href="https://i.stack.imgur.com/YGbHU.png" rel="nofollow"><img src="https://i.stack.imgur.com/YGbHU.png" alt="enter image description here"></a></p>
<p>I even tried setting healthcheck enable to false in application.yml but it still wont work. Any Help would be appreciated.</p>
<p>Regards</p>
| <p>The problem seems to be that you are naming your client <strong><em>EurekaClient</em></strong>, There is already a bean with that name. Rename that class to something else and it should work</p>
|
Spark - PySpark sql error <p>I have a simple pyspark code but i can't run it. I try to run it on Ubuntu system and I use PyCharm IDE. I would like to connect to Oracle XE Database and I want to print my test table. </p>
<p>Here comes my spark python code: </p>
<pre><code>from pyspark import SparkContext
from pyspark.sql import SQLContext
sc = SparkContext()
sqlContext = SQLContext(sc)
demoDf = sqlContext.read.format("jdbc").options(
url="jdbc:oracle:thin:@10.10.10.10:1521:XE",
driver="oracle.jdbc.driver.OracleDriver",
table="tst_table",
user="xxx",
password="xxx").load()
demoDf.show()
</code></pre>
<p>And this is my trace:</p>
<pre><code>Traceback (most recent call last):
File "/home/kebodev/PycharmProjects/spark_tst/cucc_spark.py", line 13, in <module>
password="xxx").load()
File "/home/kebodev/spark-2.0.1/python/pyspark/sql/readwriter.py", line 153, in load
return self._df(self._jreader.load())
File "/home/kebodev/spark-2.0.1/python/lib/py4j-0.10.3-src.zip/py4j/java_gateway.py", line 1133, in __call__
File "/home/kebodev/spark-2.0.1/python/pyspark/sql/utils.py", line 63, in deco
return f(*a, **kw)
File "/home/kebodev/spark-2.0.1/python/lib/py4j-0.10.3-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o27.load.
: java.lang.RuntimeException: Option 'dbtable' not specified
at scala.sys.package$.error(package.scala:27)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$2.apply(JDBCOptions.scala:30)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$2.apply(JDBCOptions.scala:30)
at scala.collection.MapLike$class.getOrElse(MapLike.scala:128)
at org.apache.spark.sql.execution.datasources.CaseInsensitiveMap.getOrElse(ddl.scala:117)
at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions.<init>(JDBCOptions.scala:30)
at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:33)
at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:330)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:149)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
at py4j.Gateway.invoke(Gateway.java:280)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:214)
at java.lang.Thread.run(Thread.java:745)
Process finished with exit code 1
</code></pre>
<p>Can Anybody help me? </p>
| <p>Change to <code>dbtable</code> from <code>table</code> like this,</p>
<pre><code>demoDf = sqlContext.read.format("jdbc").options(
url="jdbc:oracle:thin:@10.10.10.10:1521:XE",
driver="oracle.jdbc.driver.OracleDriver",
dbtable="tst_table",
user="xxx",
password="xxx").load()
</code></pre>
|
Working with dbms_lob.copy and error ORA-06502: <p>I am bit lost with working with <code>dbms_lob.copy</code></p>
<pre><code>CREATE OR REPLACE PROCEDURE Ex_PRC IS
dest_lob CLOB;
src_lob CLOB;
BEGIN
SELECT F_CLOB INTO dest_lob
FROM EX_EMPLOYEE
WHERE id = 1;
dbms_lob.copy (dest_lob, src_lob, 30, 1, 1);
COMMIT;
END;
</code></pre>
<p>/</p>
<p>I got error
<code>numeric or value error invalid lob locator specified ora-22275</code></p>
<p>I followed up this <a href="http://stackoverflow.com/questions/13648830/split-blob-file/13680419#13680419">SO</a> answer because thats what I needed is to split the blob and move them .but I didnt understand why he used <code>dbms_lob.createtemporary</code></p>
| <pre><code>set serveroutput on
create or replace procedure test_clob (p_clob_res out clob) is
cursor c_tabs is
select ename from emp;
v_clob clob;
amt integer := 0;
begin
dbms_lob.createtemporary(v_clob,true,dbms_lob.session);
for r_tabs in c_tabs
loop
dbms_lob.writeappend(v_clob,length(r_tabs.ename)+1,r_tabs.ename||' ');
amt := amt + length(r_tabs.ename);
end loop;
p_clob_res := v_clob;
end test_clob;
/
create or replace procedure call_clob is
p_clob clob;
my_buff varchar2 (2000);
amt binary_integer := 2000;
begin
test_clob(p_clob);
my_buff := dbms_lob.substr(p_clob,amt,1);
dbms_output.put_line(my_buff);
end call_clob;
/
begin
call_clob();
end;
/
</code></pre>
|
How to convert intArray to ArrayList<Int> in Kotlin? <p>From</p>
<pre><code>val array = intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4)
</code></pre>
<p>I need to convert to <code>ArrayList<Int></code></p>
<p>I have tried <code>array.toTypedArray()</code></p>
<p>But it converted to <code>Array<Int></code> instead</p>
| <p>You can use <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-collection.html"><code>toCollection</code></a> function and specify <code>ArrayList</code> as a mutable collection to fill:</p>
<pre><code>val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
</code></pre>
|
How do I upgrade React from 0.13 to 15.0.1? <p>Please tell me step by step process of upgrading React from version .13 to 15.0.1 .</p>
| <p>Update react version in package.json <br>
Delete node_modules folder<br>
Run npm install<br></p>
<p>install process will fail if there is any version mismatch among other dependencies in package file, console will show the expected compatible version number. Update those and run npm install again.</p>
<p>Once install is complete, then build your application and test. If any error appear due to deprecated code, then you would have to fix those as well.<br>
One of the deprecated syntax from ver 13, is usage of react.render<br>
There you will have to import react-dom and use that to call render. There can be many other potential issues which you may encounter. So test you app properly.</p>
<p>React entries in packge.json that I have:</p>
<pre><code>"react": "15.0.1",
"react-addons-perf": "15.0.1",
"react-addons-test-utils": "15.0.1",
"react-addons-update": "15.0.1",
"react-dom": "15.0.1"
</code></pre>
<p>All the best!<br>
P.S. This is the process I follow, there may be some other way to do it.</p>
|
How to unset chrome.windows.onRemoved.addListener? <p>I have the following code in my Chrome extension to detect when windows are closed:</p>
<pre><code> closeListener = chrome.windows.onRemoved.addListener(function(closed_window_id){
// something
}
</code></pre>
<p>How do I unset this such that the anonymous function does not fire? i.e. Something like:</p>
<pre><code> chrome.windows.onRemoved.removeListener(closeListener)
</code></pre>
<p><strong>ANSWER</strong></p>
<p><a href="http://stackoverflow.com/users/4394729/stephan-genyk">Stephan</a>/<a href="http://stackoverflow.com/users/3959875/woxxom">wOxxOm</a>s answer is correct. The function within the addListener cannot be anonymous and the removeListener syntax uses the function name (or a variable pointing to the function) to clear it.</p>
<p>Updated codepen: <a href="http://codepen.io/anon/pen/EgpNpz" rel="nofollow">http://codepen.io/anon/pen/EgpNpz</a></p>
| <p>After taking a look at your code, I see your problem. The function you put into the <code>addListener</code> is anonymous and needs to be set to a variable or become a named function.</p>
<pre><code>function newListener() {
alert();
}
//This will add the listener
chrome.windows.onRemoved.addListener(newListener);
//This will remove it
chrome.windows.onRemoved.removeListener(newListener);
</code></pre>
|
Scriptella data copy error on mysql <p>I am using <a href="https://scriptella.org/" rel="nofollow">Scriptella</a> to copy data from one table to another table(different database) on Mysql. For source, I have used table <a href="https://dev.mysql.com/doc/sakila/en/sakila-structure-tables-film.html" rel="nofollow">film</a> from Mysql sample database Sakila.</p>
<p>While copying the data I am getting this error message.</p>
<pre><code>Exception in thread "main" scriptella.execution.EtlExecutorException: Location: /etl/query[1]/script[1]
JDBC provider exception: Unable to get parameter 4
Error codes: [S1009, 0]
Driver exception: java.sql.SQLException: Cannot convert value '2006' from column 4 to TIMESTAMP.
at scriptella.execution.EtlExecutor.execute(EtlExecutor.java:190)
at com.zensar.scrptellaTest.App.main(App.java:21)
Caused by: scriptella.core.ExceptionInterceptor$ExecutionException: /etl/query[1]/script[1] failed: Unable to get parameter 4
at scriptella.core.ExceptionInterceptor.execute(ExceptionInterceptor.java:44)
at scriptella.core.QueryExecutor$QueryCtxDecorator.processRow(QueryExecutor.java:114)
at scriptella.jdbc.StatementWrapper.query(StatementWrapper.java:92)
at scriptella.jdbc.SqlExecutor.statementParsed(SqlExecutor.java:128)
at scriptella.jdbc.SqlParserBase.handleStatement(SqlParserBase.java:129)
at scriptella.jdbc.SqlParserBase.parse(SqlParserBase.java:72)
at scriptella.jdbc.SqlExecutor.execute(SqlExecutor.java:85)
at scriptella.jdbc.JdbcConnection.executeQuery(JdbcConnection.java:222)
at scriptella.core.QueryExecutor.execute(QueryExecutor.java:71)
at scriptella.core.ContentExecutor.execute(ContentExecutor.java:73)
at scriptella.core.ElementInterceptor.executeNext(ElementInterceptor.java:56)
at scriptella.core.StatisticInterceptor.execute(StatisticInterceptor.java:41)
at scriptella.core.ElementInterceptor.executeNext(ElementInterceptor.java:56)
at scriptella.core.ConnectionInterceptor.execute(ConnectionInterceptor.java:36)
at scriptella.core.ElementInterceptor.executeNext(ElementInterceptor.java:56)
at scriptella.core.ExceptionInterceptor.execute(ExceptionInterceptor.java:39)
at scriptella.core.Session.execute(Session.java:103)
at scriptella.execution.EtlExecutor.execute(EtlExecutor.java:227)
at scriptella.execution.EtlExecutor.execute(EtlExecutor.java:183)
... 1 more
</code></pre>
<p>This is one row from the table.</p>
<pre><code>'1', 'ACADEMY DINOSAUR', 'A Epic Drama of a Feminist And a Mad Scientist who must Battle a Teacher in The Canadian Rockies', 2006, '1', NULL, '6', '0.99', '86', '20.99', 'PG', 'Deleted Scenes,Behind the Scenes', '2006-02-15 05:03:42'
</code></pre>
<p>Here it the DDL statement of both the tables.</p>
<p><strong>sakila.film</strong></p>
<pre><code>CREATE TABLE `film` (
`film_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` text,
`release_year` year(4) DEFAULT NULL,
`language_id` tinyint(3) unsigned NOT NULL,
`original_language_id` tinyint(3) unsigned DEFAULT NULL,
`rental_duration` tinyint(3) unsigned NOT NULL DEFAULT '3',
`rental_rate` decimal(4,2) NOT NULL DEFAULT '4.99',
`length` smallint(5) unsigned DEFAULT NULL,
`replacement_cost` decimal(5,2) NOT NULL DEFAULT '19.99',
`rating` enum('G','PG','PG-13','R','NC-17') DEFAULT 'G',
`special_features` set('Trailers','Commentaries','Deleted Scenes','Behind the Scenes') DEFAULT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`film_id`),
KEY `idx_title` (`title`),
KEY `idx_fk_language_id` (`language_id`),
KEY `idx_fk_original_language_id` (`original_language_id`),
CONSTRAINT `fk_film_language` FOREIGN KEY (`language_id`) REFERENCES `language` (`language_id`) ON UPDATE CASCADE,
CONSTRAINT `fk_film_language_original` FOREIGN KEY (`original_language_id`) REFERENCES `language` (`language_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8;
</code></pre>
<p><strong>trg.film</strong></p>
<pre><code>CREATE TABLE `film` (
`film_id` smallint(5) unsigned NOT NULL,
`title` varchar(255) NOT NULL,
`description` text,
`release_year` year(4) DEFAULT NULL,
`language_id` tinyint(3) unsigned NOT NULL,
`original_language_id` tinyint(3) unsigned DEFAULT NULL,
`rental_duration` tinyint(3) unsigned NOT NULL DEFAULT '3',
`rental_rate` decimal(4,2) NOT NULL DEFAULT '4.99',
`length` smallint(5) unsigned DEFAULT NULL,
`replacement_cost` decimal(5,2) NOT NULL DEFAULT '19.99',
`rating` enum('G','PG','PG-13','R','NC-17') DEFAULT 'G',
`special_features` set('Trailers','Commentaries','Deleted Scenes','Behind the Scenes') DEFAULT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code></pre>
<p><strong>Scriptella etl.xml</strong></p>
<pre><code><!DOCTYPE etl SYSTEM "http://scriptella.javaforge.com/dtd/etl.dtd">
<etl>
<description>Scriptella ETL File Template.</description>
<!-- Connection declarations -->
<connection id="source" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1:3306/sakila" user="root" password="12345" />
<connection id="target" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1:3306/trg" user="root" password="12345" />
<!-- Uncomment and modify to run a query-based transformation -->
<query connection-id="source">
SELECT * FROM film;
<script connection-id="target">
INSERT INTO film VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13);
</script>
</query>
</etl>
</code></pre>
<p><strong>Java Code</strong></p>
<pre><code>public static void main(String[] args) throws EtlExecutorException {
ProgressIndicatorBase indicatorBase = new ProgressIndicatorBase() {
@Override
protected void show(String label, double progress) {
System.out.println(label + "--> " + progress);
}
};
EtlExecutor.newExecutor(new File("etl.xml")).execute(indicatorBase);
}
</code></pre>
<p>Please tell me where I am doing wrong or is there any workaround to solve it.</p>
| <p>The exception you receive is</p>
<pre><code>Driver exception: java.sql.SQLException: Cannot convert value '2006' from column 4 to TIMESTAMP.
</code></pre>
<p>It seems that the particular DB line contains value 2006 in a column where a TIMESTAMP type is expected, the format of which for MySQL seems to be</p>
<pre><code>TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
</code></pre>
|
PHP LDAP number of locked out users <p>I am working on a script that can get the number of locked out users from Active directory. Not disabled, just current number of locked out users. Is this possible? I havent worked with fetching data from AD before so I'm asking you guys before I try.</p>
| <p>Try searching for <code>(|(!(gosaVacationStop=*))(!(gosaVacationStop=0)))</code>.</p>
<p>That should fetch all users that have the attribute <code>lockoutTime</code> set and where it is not 0.</p>
<pre><code>$result = ldap_search($con, '(&(samaccountname=*)(|(!(gosaVacationStop=*))(!(gosaVacationStop=0))))', '*');
echo ldap_count_entries($con, $result);
</code></pre>
<p>That should give you the number of locked accounts.</p>
|
How to make an iPhone app uncloseable? <p>I would like to hand out iPhones as navigation/information devices to users at an event but users should only be able to see and use the event app and not close it or tamper with phone settings etc.</p>
<p>Is it possible to make an iPhone app not closable by the user and put it into a sort of 'presentation mode'?</p>
| <p>Yes its possible by using guid access in your iphone,</p>
<p>Here is image how to set it.</p>
<p><a href="https://i.stack.imgur.com/aLKRp.png" rel="nofollow"><img src="https://i.stack.imgur.com/aLKRp.png" alt="enter image description here"></a></p>
<p>So without your permission user cannot close apps.</p>
|
How Spring Batch Restart logic works on hadoop job? <p>Suppose i have 10 records and some of them are corrupted records so how spring will handle restart.</p>
<p>Example suppose record no. 3& 7 are corrupt and they go to different reducer then how spring will handle the restart
1.how it will maintain the queue to track where it last failed.
2.what are the different ways we can solve this one</p>
| <p>SpringBatch will do exactly what you tell SpringBatch to do.</p>
<p>Restart for SpringBatch means run the same job that failed with the same set of input parameters. However, the new instance (execution) of this job will be created.</p>
<p>The job will run on the <strong>same data set</strong> that the failed instance of the job ran on.
In general, it is not a good idea to modify the input data set for you job - the input data of MapReduce job must be immutable (I assume, you will not modify the same data set you use as an input).</p>
<p>In your case the job is likely to complete with the <code>BatchStatus.COMPLETED</code> unless you put a very specific logic in the <strong>last step</strong> of your SpringBatch job.
This last step will validate all records and if any broken records detected artificially will set the status of the job to <code>BatchStatus.FAILED</code> like below:</p>
<pre><code>jobExecution.setStatus(BatchStatus.FAILED)
</code></pre>
<p>Now how to restart the job is a good question that I will answer in a few moments.
However, before restrting the question you need to ask is: <strong>if the input data set for your MapReduce job and the code of your MapReduce job have not changed, how restrt is going to help you?</strong></p>
<p>I think you need to have some kind of data set where you dump all the bad records that the original MapReduce job failed to process. Than how to process these broken records is for you to decide.</p>
<p>Anyway, restarting SpringBatch job is easy, once you know what is the ID of failed <code>jobExecution</code>. Below is the code:</p>
<pre><code>final Long restartId = jobOperator.restart(failedJobId);
final JobExecution restartExecution = jobExplorer.getJobExecution(restartId);
</code></pre>
<p><strong>EDIT</strong></p>
<p>Read about <a href="http://docs.spring.io/spring-batch/trunk/reference/html/readersAndWriters.html" rel="nofollow">ItemReader, ItemWriter and ItemProcessor</a> interfaces
I think that you can achieve tracking by using <a href="http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/item/support/CompositeItemProcessor.html" rel="nofollow">CompositeItemProcessor</a>.
In Hadoop every record in a file must have a unique ID. So, I think you can store the list of IDs of the bad record in the Job context. Update <code>JobParameter</code> that you would have created when the job starts for the first time, call it <code>badRecordsList</code>. Now when you restart/resume your job, you will read the value of the <code>badRecordsList</code>and will have a reference.</p>
|
Uploading file in Cakephp not adding file name in mysql database table <p>Please help me. Thanks in advance. I am new to Cakephp.
I am using cakephp2.8.5 version. I was trying to upload a file from HTML form, i can able to store the file in the targeted folder but not able to store the file name in the mysql database table.</p>
<pre><code>My code as follows:
View Page is add.ctp
<form name="add_userform" class="form-horizontal" role="form" accept-charset="utf-8" enctype="multipart/form-data" method="post" id="UserAddForm" action="/invl_exams/users/add" >
<div style="display:none;"><input type="hidden" value="POST" name="_method"></div>
<div class="form-group">
<label for="UserUsername">Username</label>
<input type="text" class="form-control" required="required" id="UserUsername" maxlength="255" name="data[User][username]">
<label id="UserUsername-error" class="error" for="UserUsername"></label>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" required="required" id="UserPassword" name="data[User][password]">
<label id="UserPassword-error" class="error" for="UserPassword"></label>
</div>
<div class="form-group" id="ShowDoc" style="display:none">
<label for="usersFile">File</label>
<?php echo $this->Form->file('Document.submittedfile'); ?>
</div>
Controller Page is UsersController.php
public function add()
{
if($this->request->is('post')|| $this->request->is('put'))
{
$this->User->create();
$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
$file = $this->request->data['Document']['submittedfile'];
move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/invl_exams/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
if($this->User->save($this->request->data))
{
$this->redirect('addExam');
}
}
}
Model Page is User.php
<?php
//App::uses ('AppModel','Model');
class User extends AppModel{
public $validate = array(
'username' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Username is required'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken')
),
'password' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'A password is required'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'Password has already been taken')
),
'full_name' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Full name is required'
)
),
/*'role' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Role is required'
)
) */
'email' => array(
array(
'rule' => array('email'),
'massage' => 'Please enter a valid email address',
),
),
'secondary_email' => array(
array(
'rule' => array('email'),
'massage' => 'Please enter a valid email address',
),
),
'phone' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Phone is required'
)
),
'secondary_phone' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Phone is required'
)
),
'location' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Loacation is required'
)
),
'business_name' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Business Name is required'
)
),
'document' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Document is required'
)
),
'pname' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Name is required'
)
),
'pemail' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Please enter a Valid Email Id'
)
),
'pOfc_phone' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Please enter a Phone Number'
)
),
'pdesignation' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'Designation is Required'
)
),
);
}
?>
</code></pre>
| <p>You didn't add image name in your <strong>$this->request->data</strong> array if your image field name is <strong>image_name</strong>. Then add this line </p>
<pre><code> $this->request->data['User']['image_name'] = $this->data['Document']['submittedfile']['name']
</code></pre>
<p>After </p>
<pre><code>$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
</code></pre>
<p>Then the code looks like </p>
<pre><code>$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
$this->request->data['User']['image_name'] = $this->data['Document']['submittedfile']['name'];
</code></pre>
|
Detect whether iPad supports sim card programatically <p>Currently, I have an app that shows the 3G data / Wifi used by the user since the last reboot.
What I want to do is, if the app is running on an iPad which doesnât support SIM card, I want to hide certain statistics shown to the user.</p>
<p>Is it somehow possible to detect whether the current iOS device supports a sim card or not?</p>
| <p>As far as I know, you cannot detect if the SIM card is installed. You can only determine if a WWAN connection is available using <a href="https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html" rel="nofollow">Reachability</a> (<a class='doc-link' href="http://stackoverflow.com/documentation/ios/704/checking-for-network-connectivity#t=20161014214909799942">Documentation</a>)</p>
<p>or you can use <a href="https://developer.apple.com/reference/coretelephony/ctcarrier#//apple_ref/doc/uid/TP40009596-CH1-SW1" rel="nofollow">CTCarrier</a> </p>
<pre><code>@import CoreTelephony;
-(BOOL)hasCellularCoverage
{
CTTelephonyNetworkInfo *networkInfo = [CTTelephonyNetworkInfo new];
CTCarrier *carrier = [networkInfo subscriberCellularProvider];
if (!carrier.isoCountryCode) {
NSLog(@"No sim present Or No cellular coverage or phone is on airplane mode.");
return NO;
}
return YES;
}
</code></pre>
|
Restart Revmob Session - If no connection and then got connected <p>I have an adobe AIR AS3 application for both Android and iOS. I have implemented all the necessary code with the help of revmob's great technical support team. My problem now is if the user originally was not connected to a wifi or cellular network, the session won't start, thus the banner won't show nor the video, which is normal. <br/></p>
<p>The problem is, when the user switches back to connected, the banner won't show, so i'm guessing the session didn't start.<br/></p>
<p>How can i keep trying to start the revmob session, depending on when the user gets connected? in other terms, how can i restart the session as soon as the user gets connected?</p>
| <p>You can see how to create a <strong>ConnectionChecker</strong> class to check for a internet connection in this <a href="http://stackoverflow.com/a/13569775/5128351">link </a>. After creating a <strong>ConnectionChecker</strong> instance, you can call it and call the startSession method when connection is successful.</p>
<p>Following the link, your code will look something like this:</p>
<pre><code>var checker:ConnectionChecker = new ConnectionChecker();
checker.addEventListener(ConnectionChecker.EVENT_SUCCESS, checker_success);
checker.addEventListener(ConnectionChecker.EVENT_ERROR, checker_error);
checker.check();
private function checker_success(event:Event):void {
// There is internet connection, so call startSession
revmob = new RevMob(< YOUR_APP_ID>);
}
private function checker_error(event:Event):void {
// There is no internet connection, do nothing
}
</code></pre>
<p>Best regards,</p>
|
Is it Pythonic to passed in arguments in a function that will be used by a function inside it? <p>Is there a better way to do this? Like I'm passing in arguments to <code>func</code> that will be used in <code>inside_func</code> function? </p>
<pre><code>def inside_func(arg1,arg2):
print arg1, arg2
return
def func(arg1, arg2):
inside_func(arg1,arg2)
return
</code></pre>
| <p>Of course it is.</p>
<p>Your outer function provides a service, and to do its job it may need inputs to work with. <em>How it uses those inputs</em> is up to the function. If it needs another function to do their job and they pass in the arguments verbatim, is an implementation detail.</p>
<p>You are doing nothing more than standard encapsulation and modularisation here. This would be correct programming practice in any language, not just Python.</p>
<p>The Python standard library is full of examples; it is often used to provide a simpler interface for quick use-cases. The <a href="https://hg.python.org/cpython/file/v3.5.2/Lib/textwrap.py#l369" rel="nofollow"><code>textwrap.wrap()</code> function</a> for example:</p>
<pre><code>def wrap(text, width=70, **kwargs):
"""Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in 'text' so it fits in lines of no
more than 'width' columns, and return a list of wrapped lines. By
default, tabs in 'text' are expanded with string.expandtabs(), and
all other whitespace characters (including newline) are converted to
space. See TextWrapper class for available keyword args to customize
wrapping behaviour.
"""
w = TextWrapper(width=width, **kwargs)
return w.wrap(text)
</code></pre>
<p>This does nothing else but pass the arguments on to other callables, just so your code doesn't have to remember how to use the <code>TextWrapper()</code> class for a quick one-off text wrapping job.</p>
|
Django - What is the best way to have multi level status before login <p>I have one scenario, there is a user registration and it should have multiple status(may be is_active - but this is boolean by default)</p>
<ol>
<li>List item Code - 0 -> Pending for Email Confirmation</li>
<li>List item Code - 1 -> Account Activated/Active(Only after email confirmed admin will approve it)</li>
<li>List item Code - 2 -> Email Confirmed</li>
</ol>
<p>I am using django allauth, I was browsing to achieve it, but unable to find some close match of it. For your info I also have <code>Profile OnetoOne model for User model</code></p>
<p><strong>Updated</strong> </p>
<pre><code>class CustomConfirmEmailView(ConfirmEmailView):
def get(self):
raise Exception('GET')
def post(self,*args,**kwargs):
raise Exception('POST')
</code></pre>
<p><strong>Settings file</strong></p>
<pre><code>ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
</code></pre>
| <p>You should create custom <code>User</code> or custom <code>Profile</code>(i believe that it's better with custom <code>Profile</code>, to avoid messing with django <code>User</code>):</p>
<pre><code>from itertools import compress
class CustomProfile(Profile):
is_confirmed = models.BooleanField(default=False)
@property
def status(self):
return next(compress(['Pending', 'Active', 'Confirmed'],
[not self.is_confirmed, not self.is_confirmed and self.user.is_active, self.confirmed and self.user.is_active]))
</code></pre>
<p>You can see that i added <code>@property</code> that would answer your question about user status.</p>
<p>But for setting <code>is_confirmed</code> you need to look at the sources, <a href="http://django-allauth.readthedocs.io/en/latest/views.html#e-mail-verification" rel="nofollow">docs</a> lead you to <a href="https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py#L225" rel="nofollow"><code>allauth.account.views.ConfirmEmailView</code></a> view.</p>
<p>And i think that you need to override <code>post</code> method.</p>
<pre><code>class CustomConfirmEmailView(ConfirmEmailView):
def post(self, *args, **kwargs):
self.object = confirmation = self.get_object()
confirmation.confirm(self.request)
get_adapter(self.request).add_message(
self.request,
messages.SUCCESS,
'account/messages/email_confirmed.txt',
{'email': confirmation.email_address.email})
if app_settings.LOGIN_ON_EMAIL_CONFIRMATION:
resp = self.login_on_confirm(confirmation)
if resp is not None:
return resp
profile = confirmation.email_address.user.profile
profile.is_confirmed = True
profile.save()
redirect_url = self.get_redirect_url()
if not redirect_url:
ctx = self.get_context_data()
return self.render_to_response(ctx)
return redirect(redirect_url)
</code></pre>
<p>And then you need to put that View in url.</p>
<p>That's it. Sure i didn't run it. But the logic is here.</p>
|
How to make communication between UWP Client and Java Server using WebSocket? <p>I need to send text,primitive data types and object between a UWP client and JAVA server using WebSocket, however I don't know how to code.</p>
<p>I don't understand if there is any difference between these two languages that make coding thing really hard? (I've searched for online tutorials but still couldn't make my code works).</p>
<p><strong>Provider.java</strong> :</p>
<pre><code>public class Provider{
ServerSocket providerSocket;
Socket connection = null;
OutputStream out;
InputStream in;
String message;
MesageModel model;
Provider(){}
void run()
{
try{
providerSocket = new ServerSocket(9999, 10);
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("New connection accepted "+":" + connection.getPort());
in = connection.getInputStream();
out = connection.getOutputStream();
if(out == null)
{
System.out.println("Out Status : Null");
}else
{
System.out.println("Out Status : Not Null");
sendMessage("Hello Client");
}
if(in == null)
{
System.out.println("In Status : Null");
}else
{
receiveConnection();
}
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
if(in != null){
System.out.println("Close In");
in.close();
}
if(out != null){
System.out.println("Close Out");
out.close();
}
System.out.println("Close Socket");
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
void receiveConnection() throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder outsb = new StringBuilder();
String line = "";
System.out.println("In Status : Not Null");
System.out.println("In Status : Go To While to Read Line");
while ((line = reader.readLine()) != null) {
outsb.append(line);
System.out.println(outsb.toString());
}
System.out.println(outsb.toString());
reader.close();
System.out.println("Closed Reader");
}
void sendMessage(String msg)
{
byte[] byteS = msg.getBytes();
try{
out.write(byteS);
out.flush();
System.out.println("To Server >" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Provider server = new Provider();
while(true){
server.run();
}
}
}
</code></pre>
<p><strong>MainPage.xaml.cs</strong></p>
<pre><code>namespace WebsocketTest
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
createSocket();
}
public async void createSocket()
{
MessageWebSocket webSock = new MessageWebSocket();
webSock.Control.MessageType = SocketMessageType.Binary;
webSock.MessageReceived += webSock_MsgReceived;
webSock.Closed += webSock_Closed;
Uri serverUri = new Uri("ws://localhost:9999");
try
{
await webSock.ConnectAsync(serverUri);
tbConnect.Text = "Connected";
webSock_SendMessage( webSock, "Hello");
tbError.Text = "Sent Greeting";
}
catch (Exception ex)
{
tbError.Text = ex.Message + " / " + ex.HResult + " / " + ex.Data;
}
}
private async Task webSock_SendMessage(MessageWebSocket webSock, string m)
{
BinaryWriter messageWriter = new BinaryWriter((Stream)webSock.OutputStream);
messageWriter.Write(m);
}
private void webSock_Closed(IWebSocket sender, WebSocketClosedEventArgs args)
{
}
private void webSock_MsgReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
{
DataReader messageReader = args.GetDataReader();
messageReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
string messageString = messageReader.ReadString(messageReader.UnconsumedBufferLength);
tbReceived.Text = messageString;
}
}
}
</code></pre>
<p>Currently these code don't work at all, ... I can't send, can't read ... at both side.</p>
<p><strong>My Questions:</strong></p>
<p>How to Send and Read Messages from my UWP client?</p>
<p>How to Send and Read Messages from my JAVA server?</p>
<p>Please I need something helpful ... a code sample.</p>
| <p>Your Java code creates a plain TCP/IP socket, not a [websocket][1], which is a higher level protocol on top of TCP/IP.</p>
<p>If you want websockets you need to either implement websockets for yourself (don't do that if you are not very experienced at network programming) or use a Java library that provides websocket server functionality. Jetty, Netty or J2EE servers might be candidates for that.</p>
|
Get an exception with Invalid reference from Solr DocumentExpressionDictionaryFactory <p>I am using solr 6.2. I am trying to configure multiple suggester definition in Solr search component and got error information like:</p>
<pre><code>java.lang.IllegalArgumentException: Invalid reference 'softId_suggest'
at org.apache.lucene.expressions.SimpleBindings.getValueSource(SimpleBindings.java:84)
at org.apache.lucene.expressions.ExpressionValueSource.<init>(ExpressionValueSource.java:45)
at org.apache.lucene.expressions.Expression.getValueSource(Expression.java:80)
at org.apache.solr.spelling.suggest.DocumentExpressionDictionaryFactory.fromExpression(DocumentExpressionDictionaryFactory.java:107)
at org.apache.solr.spelling.suggest.DocumentExpressionDictionaryFactory.create(DocumentExpressionDictionaryFactory.java:92)
at org.apache.solr.spelling.suggest.SolrSuggester.build(SolrSuggester.java:174)
at org.apache.solr.handler.component.SuggestComponent$SuggesterListener.buildSuggesterIndex(SuggestComponent.java:528)
at org.apache.solr.handler.component.SuggestComponent$SuggesterListener.newSearcher(SuggestComponent.java:508)
at org.apache.solr.core.SolrCore.lambda$3(SolrCore.java:1863)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.apache.solr.common.util.ExecutorUtil$MDCAwareThreadPoolExecutor.lambda$execute$0(ExecutorUtil.java:229)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
</code></pre>
<p>and the config in my Solrconfig.xml is:</p>
<pre><code> <field name="softId_suggest" type="int" indexed="true" stored="true" />
<copyField source="softId" dest="softId_suggest" />
</code></pre>
<p></p>
<pre><code> <lst name="suggester">
<str name="name">MySuggest</str>
<str name="lookupImpl">AnalyzingInfixLookupFactory</str>
<str name="dictionaryImpl">DocumentExpressionDictionaryFactory</str>
<str name="field">suggest_name</str>
<str name="highlight">false</str>
<str name="weightExpression">softId_suggest</str>
<str name="indexPath">analyzingInfixSuggesterIndexDir</str>
<str name="suggestAnalyzerFieldType">text_suggest</str>
</lst>
</code></pre>
<p>From the source of lucene I know that it seems that the field <code>softId_suggest</code> is null, but how to configure it to be right?</p>
| <p>In your description, you say that you configured softId_suggest in <strong>solrconfig.xml</strong>. But the fields are configured in <strong>managed-schema</strong> file. So, either that's the problem or you need to correct the question.</p>
<p>If it is defined correctly, make sure you've reloaded the core, rerun the import and committed.</p>
<p>Then, I would check Admin UI's Schema page and ensure that the field is both present in the dropdown and that it has some values loaded (<em>Load Term Info</em> button).</p>
|
yii2, how can I create table in database based on imported excel or csv file <p>I want to import excel or csv file into not existent table. Most of the extensions for yii2 imports files into existing table with known column names and attributes.</p>
| <p>It is not clear the excect difficulty which you met.</p>
<p>If you want to extract the list of columns of your excel document, you can use PhpExcel library like <a href="http://stackoverflow.com/a/5578240/6222876">here</a>. You can add it into your project with <code>composer</code> as:</p>
<pre><code>php composer.phar require --prefer-dist moonlandsoft/yii2-phpexcel "*"
</code></pre>
<p>Creation of the table can be done with the usage of <a href="http://www.yiiframework.com/doc-2.0/yii-db-command.html" rel="nofollow">yii\db\Command</a> class. There is a <code>createTable</code> function.</p>
|
Unable to locate an element error is coming when i am running the below piece of code <pre><code>public class TestWebtable {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.espncricinfo.com/indian-premier-league-2016/engine/match/981019.html");
int i = 2;
int rowNum = 0;
while (driver
.findElement(
By.xpath(".//*[@id='full-scorecard']/div[2]/div/table[1]/tbody/tr["
+ i + "]/td[2]/a")).isDisplayed()) {
i = i + 2;
rowNum++;
}
System.out.println("Total rows are : " + rowNum);
}}
</code></pre>
<hr>
<p>Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[@id='full-scorecard']/div[2]/div/table[1]/tbody/tr[20]/td[2]/a"}
Command duration or timeout: 40 milliseconds
For documentation on this error, please visit: <a href="http://seleniumhq.org/exceptions/no_such_element.html" rel="nofollow">http://seleniumhq.org/exceptions/no_such_element.html</a>
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:32:46'
System info: host: 'pc-PC', ip: '192.168.0.14', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_101'
Driver info: org.openqa.selenium.firefox.FirefoxDriver</p>
| <p>Try this</p>
<pre><code>driver.get("http://www.espncricinfo.com/indian-premier-league-2016/engine/match/981019.html");
int i = 2;
int rowNum = 0;
while (true) {
try {
driver.findElement(
By.xpath(".//*[@id='full-scorecard']/div[2]/div/table[1]/tbody/tr[" + i + "]/td[2]/a"));
i = i + 2;
rowNum++;
} catch (Exception e) {
break;
}
}
System.out.println("Total rows are : " + rowNum);
</code></pre>
|
Regex password validation add underscore like special symbol <p>Password must contains :
1 Upper letter
1 lower letter
1 digit
1 special symbol
Minimum 8 symbols</p>
<p>Here it is my regex:</p>
<pre><code>^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@_$%^&*-]).{8,}$
</code></pre>
<p>But when i try to validate for example with password: Test_123 it returns me <code>false</code></p>
<p>here is my code : </p>
<pre><code>public class PasswordCheck {
static Logger logger = Logger.getLogger(CommonHelper.class);
private static final String PASSWORD_PATTERN = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@_$%^&*-]).{8,}$";
private Pattern pattern;
private Matcher matcher;
public PasswordCheck() {
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/**
* Validate password with regular expression
*
* @param password
* password for validation
* @return true valid password, false invalid password
*/
public boolean validate(final String password) {
matcher = pattern.matcher(password);
System.out.println(password);
System.out.println(matcher.matches());
return matcher.matches();
}
}
</code></pre>
<p>I just try it to set new String in validate function with the same text: Test_1523 and return me true but when i post this string via rest service and pass it to the function returns me false</p>
| <p>No matter if you are using regular expressions or other means to validate those strings - but please: don't push everything into one piece of code or regex. </p>
<p>You want to create code that is easy to read and maintain; and a single regex containing so much "coded" knowledge wont help with that. I have more than once used something like</p>
<pre><code>interface PasswordValidator {
boolean isValid(String input);
String getErrorMessage();
}
</code></pre>
<p>To then create various classes implementing such an interface. And finally, you simply create one object per implementation class; and you can put those into some static list. And then validating means: just run all validator objects in that list. On fail, you can directly ask for the error message for the user (so you can tell him exactly what is missing; instead of throwing the whole rule set at him again).</p>
<p>Not saying that something like that is always required, but in my experience: password rules might change frequently. Hard-baking them into regexes is rarely a durable approach.</p>
|
Different marker colors for start and end points in pyplot <p>I am trying to plot lines on a plot between two point tuples. I have following arrays:</p>
<pre><code>start_points = [(54.6, 35.2), (55.5, 32.7), (66.5, 23.7), (75.5, 47.8), (89.3, 19.7)]
end_points = [(38.9, 44.3), (46.7, 52.2), (72.0, 1.4), (62.3, 18.9), (80.8, 26.2)]
</code></pre>
<p>So what I am trying to do is drawing lines between points at same index like a line from (54.6, 35.2) to (38.9, 44.3), another line from (55.5, 32.7) to (46.7, 52.2) and so on.</p>
<p>I achieved this by plotting <code>zip(start_points[:5], end_points[:5])</code>, but I want different marker styles for start and end points of lines. I want start_points to be green circle, and end_points to be blue x for example. Is this possible?</p>
| <p>The trick is to first plot the line (<code>plt.plot</code>) and then plot the markers using a scatter plot (<code>plt.scatter</code>).</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
start_points = [(54.6, 35.2), (55.5, 32.7), (66.5, 23.7), (75.5, 47.8), (89.3, 19.7)]
end_points = [(38.9, 44.3), (46.7, 52.2), (72.0, 1.4), (62.3, 18.9), (80.8, 26.2)]
for line in zip(start_points, end_points):
line = np.array(line)
plt.plot(line[:, 0], line[:, 1], color='black', zorder=1)
plt.scatter(line[0, 0], line[0, 1], marker='o', color='green', zorder=2)
plt.scatter(line[1, 0], line[1, 1], marker='x', color='red', zorder=2)
</code></pre>
|
C# find cost, calculate the cost of item and include 10% GST <p>I am studying C# and have been asked to create a grocery program. I am stuck and can't seem to find anything on the net to help me. I have created a grocery item class with properties containing Name and Price. I have also created a subclass of purchasedItem which has an integer of quantity. I now need to create a method which finds Price, calculates the Price and adds 10% GST. Any ideas of how to do this.
This is what I have so far - any help would be appreciated:</p>
<pre><code>namespace Groceries1
{
class Program
{
static void Main(string[] args)
{
groceryItem mygroceryItem = new groceryItem();
mygroceryItem.play();
purchasedItem mypurchasedItem = new purchasedItem();
}
class groceryItem
{
private string myName = 0;
private int myPrice = 0;
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public int Price
{
get
{
return myPrice;
}
set
{
myPrice = value;
}
}
}
class purchasedItem
{
private int myquantity = 0;
public int quantity
{
get
{
return myquantity;
}
set
{
myquantity = Price*quantity*1.1;
}
}
}
}
}
</code></pre>
| <p>You can try this,</p>
<pre><code>using System;
using System.Collections.Generic;
namespace Groceries
{
public class Program
{
public static void Main(string[] args)
{
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = "Fresh grocery";
freshGrocery.Price = 30;
freshGrocery.Weight = 0.5;
Grocery grocery = new Grocery();
grocery.Name = "Grocery";
grocery.Price = 50;
grocery.Quantity = 2;
ShoppingCart cart = new ShoppingCart();
cart.Orders = new List<GroceryItem>();
cart.Orders.Add(freshGrocery);
cart.Orders.Add(grocery);
double price = cart.Calculate();
Console.WriteLine("Price: {0}", price);
}
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery: GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate() {
return this.Price * this.Weight;
}
}
class Grocery: GroceryItem
{
private int quantity = 0;
private double gst = 10; // In Percentage
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate() {
double calculatedPrice = this.Price * this.Quantity;
// VAT
if(calculatedPrice > 0)
{
calculatedPrice += calculatedPrice * (gst/100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if(this.Orders != null)
{
foreach(GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}
</code></pre>
|
How to delete some rows which keys has the same prefix from a table in SQLite android? <p>simple table with </p>
<p><code>CREATE TABLE IF NOT EXISTS tb (id TEXT NOT NULL, json TEXT NOT NULL,PRIMARY KEY(id))</code></p>
<p>insert 4 rows into the table, looks like:
<code>
akey1, avalue1
akey2, avalue2
bkey1, bvalue1
bkey2, bvalue2
</code></p>
<p>in android, I execute delete with <code>like</code>:</p>
<pre><code>final SQLiteDatabase database = this.getWritableDatabase();
boolean result = false;
database.beginTransaction();
try{
database.delete(tableName," id like ? ", new String[]{"akey%"})
database.setTransactionSuccessful();
result = true;
}catch(Exception e){
result = false;
}finally{
database.endTransaction();
}
</code></pre>
<p>I found that, the two rows: <code>akey1</code> and <code>akey2</code> were NOT be removed.</p>
<p>If I run <code>DELETE FROM tb where id like 'akey%'</code> with sqlitebrowser, It is OK.</p>
<p>What's wrong for that?</p>
| <p>The problem must be you missing single qoutation around like statement and it may work if you add single qoutations around your like condition. Like so:</p>
<pre><code>database.delete(tableName," id like '?';", new String[]{"akey%"});
</code></pre>
<p>but anyway The "?" Placeholder is a little buggy some times.</p>
<p>You better to construct the statement on your own and send null as args like below:</p>
<pre><code> String likeCondition = "akey%";
database.delete(tableName," id like '"+ likeCondition + "';", null);
</code></pre>
|
mousedown and move cross dom element, keep cursor is crosshair <p>When mousedown and mouse move from outside to inside, the cursor become like text, how to keep cursor is crosshair?<br>
I tried use <code>:active</code> but not work ..</p>
<p><a href="https://jsfiddle.net/xu9tmmfr/" rel="nofollow">https://jsfiddle.net/xu9tmmfr/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div,
img {
cursor: crosshair;
}
.a {
width: 300px;
height: 300px;
background-color: red;
}
.a {
width: 200px;
height: 200px;
background-color: green;
}
.c {
width: 100px;
height: 100px;
background-color: pink;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
<div class="b">
<img class="c" src="" alt="">
</div>
</div></code></pre>
</div>
</div>
</p>
| <p>This one is bit hacky but should work .Prevent default action (which is to change cursor) upon mousedown on the container</p>
<pre><code>$('.a').mousedown(function (e) {
e.preventDefault();
});
</code></pre>
<p><a href="https://jsfiddle.net/g7nw10dk/" rel="nofollow">https://jsfiddle.net/g7nw10dk/</a></p>
|
Jquery Number counting slowdown animation when target reach <pre><code>$(this).prop('Counter', 0).animate({
Counter: 123456789
}, {
duration: 2000,
easing: 'easeOutBack',
step: function (now) {
$(this).html(parseFloat(now).toFixed(2));
},
complete: function () {
}
});
</code></pre>
<p>In this code number running same speed till ends. I need the number running speed will slow down when reached the target.</p>
| <p>You can make a variable for speed and incrase this with step. In your exemple is:</p>
<pre><code>var speed = 2000;
$(this).prop('Counter', 0).animate({
Counter: 123456789
}, {
duration: speed,
easing: 'easeOutBack',
step: function (now) {
$(this).html(parseFloat(now).toFixed(2));
if(counter < 1000){
speed += 100;
}
},
complete: function () {
}
});
</code></pre>
|
SonarQube Analysis Task Error After File Move <p>We have been using SonarQube analysis on a C# project as part of a TFS 2015/15 RC2 vNext build for ages which has been working fine.</p>
<p>A few days a go I refactored several aspects of code, this consisted of moving files into new folders within the same project, as opposed to class name changes etc. Visual Studio didn't handle this correctly and I had to remove and re-add some files to the project on an individual basis.</p>
<p>Our analysis is now failing, when looking at the logs for the analysis task I can see the following error:</p>
<pre><code>ERROR [o.s.s.c.t.CeWorkerCallableImpl] Failed to execute task AVe_-iOpE8SSKScA9O_3 java.lang.IllegalStateException:
Original file OriginalFile{id=1363, uuid='ca50dc09-5d0b-4083-9e52-eb0f66361422', key='MIS:MIS:4E9625D2-557E-450C-90CC-A6B6FB57B6C9:Models/XXX/Grids/ProjectTeams/SmpProjectTeamFilterModel.cs'}
already registered for file
ComponentImpl{key='StanMIS:StanMIS:4E9625D2-557E-450C-90CC-A6B6FB57B6C9:Models/Smp/Grids/ProjectTeams/SmpProjectTeamFilterModel.cs', type=FILE, uuid='AVe_-nQKU1hbfyCkniEZ', name='', description='null', fileAttributes=FileAttributes{languageKey='cs', unitTest=false},
reportAttributes=ReportAttributes{ref=1506, version='null',
path='Models/Smp/Grids/ProjectTeams/SmpProjectTeamFilterModel.cs'}}.
Unable to register OriginalFile{id=1353, uuid='1488ce7d-094c-4859-9e23-adae0f1ac2a3', key='StanMIS:StanMIS:4E9625D2-557E-450C-90CC-A6B6FB57B6C9:Models/XXX/Grids/DStanContacts/SmpDStanContactFilterModel.cs'}.
at com.google.common.base.Preconditions.checkState(Preconditions.java:197) ~[guava-18.0.jar:na]
at org.sonar.server.computation.filemove.MutableMovedFilesRepositoryImpl.setOriginalFile(MutableMovedFilesRepositoryImpl.java:41) ~[sonar-server-6.0.jar:na]
at org.sonar.server.computation.filemove.FileMoveDetectionStep.registerMatches(FileMoveDetectionStep.java:144) ~[sonar-server-6.0.jar:na]
at org.sonar.server.computation.filemove.FileMoveDetectionStep.execute(FileMoveDetectionStep.java:139) ~[sonar-server-6.0.jar:na]
at org.sonar.server.computation.step.ComputationStepExecutor.executeSteps(ComputationStepExecutor.java:64) ~[sonar-server-6.0.jar:na]
at org.sonar.server.computation.step.ComputationStepExecutor.execute(ComputationStepExecutor.java:52) ~[sonar-server-6.0.jar:na]
at org.sonar.server.computation.taskprocessor.report.ReportTaskProcessor.process(ReportTaskProcessor.java:75) ~[sonar-server-6.0.jar:na]
at org.sonar.server.computation.taskprocessor.CeWorkerCallableImpl.executeTask(CeWorkerCallableImpl.java:81) ~[sonar-server-6.0.jar:na]
at org.sonar.server.computation.taskprocessor.CeWorkerCallableImpl.call(CeWorkerCallableImpl.java:56) ~[sonar-server-6.0.jar:na]
at org.sonar.server.computation.taskprocessor.CeWorkerCallableImpl.call(CeWorkerCallableImpl.java:35) [sonar-server-6.0.jar:na]
at java.util.concurrent.FutureTask.run(Unknown Source) [na:1.8.0_45]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [na:1.8.0_45]
at java.util.concurrent.FutureTask.run(Unknown Source) [na:1.8.0_45]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) [na:1.8.0_45]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) [na:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_45]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_45]
ERROR [o.s.s.c.t.CeWorkerCallableImpl] Executed task | project=MIS | type=REPORT | id=AVe_-iOpE8SSKScA9O_3 | submitter=XXX | time=24633ms
</code></pre>
| <p>You face <a href="https://jira.sonarsource.com/browse/SONAR-8013" rel="nofollow">https://jira.sonarsource.com/browse/SONAR-8013</a>. It is fixed in version 6.1.</p>
|
I have requirment like <p>I have requirment like In which I have to create</p>
| <p>Have a look at <a href="http://www.wiris.com/editor/docs/javaswing" rel="nofollow">WIRIS</a>. You can integrate it in your Swing application (using Java/Swing API) or web application (using JavaScript API).</p>
<p>How to use:</p>
<ol>
<li>Create an instance of the editor and use the toolbar to enter the formula.</li>
<li>Once done get the MathML from the editor and save it in your database.</li>
<li>Later you can use this MathML to show formula in UI.</li>
</ol>
<p>You will need to spend some time in understanding their API and documentation before you start coding. They provide math expression evaluation service too, check their online <a href="http://www.wiris.com/quizzes/demo/generic/en/level3.php" rel="nofollow">demo</a>.</p>
|
log4j2 queue/topic configuration by spring <p>Are there any way to configure log4j2 to read Appender attributes from for example a spring bean? I am curious especially in JmsAppender to dynamically set it's target destination based on a parameter read from database and not from JNDI context.</p>
<p>BR
Zoltán</p>
| <p>Your best chance is to extend the JMSAppender and override the append methods in the logger. A good example is <a href="https://github.com/danveloper/real-time-logging/blob/master/enhanced-log4j-jms-appender/src/main/java/com/danveloper/log4j/jms/EnhancedJMSAppender.java" rel="nofollow">here</a></p>
<p>This case , the class extends and uses AMQ to post these messages into. You should be able to extend this from the DB and use API's to get a handle to the Queue or Topic and start appending messages into it. This assumes that you have the right client libraries and permissions to connect to the messaging provider (e.g. in WMQ you may need the QM Name , Queue , Host, port) from the DB (in your case). The extended JMS appender can then be used in your LOG4J2 configuration for sending log messages.</p>
|
How to change the value of an input inside of a frame with VBScript <p>I want to make a script which will open IE and automatically fill in inputs in a form on an external website. The inputs I want filled-in are placed inside of a frame. So the <code>getElementByID</code> won't work here.</p>
<p>I've made my own test site to use the script on. Later on I will implement it to the other one but I wanted to start off simple. This is the site the script will open:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<frameset cols="25%,*,25%">
<frame name="menu" src="menu.html">
<frame name="form" src="form.html">
<frame name="application" src="application.html">
</frameset>
</html>
</code></pre>
<p>This is an example of <code>form.html</code> (It doesnt have to submit anything yet it's just a test):</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<div class="login">
<form action='' method='POST' id='nameform'>
Username: <input type='text' name='user' id='user' value=""><br>
Password: <input type='password' name='pswrd' id='pswrd' value=""><br>
<input name='submit' type='submit' value='submit' id='submit'><br>
</form>
</div>
</body>
</html>
</code></pre>
<p>And last but not least here is my VBScript:</p>
<pre class="lang-vb prettyprint-override"><code>Call Main
Function Main
Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
IE.Visible = True
IE.Navigate "http://example.com"
Wait IE
With IE.Document
.getElementByID("user").value = "CoolUsername123"
.getElementByID("pswrd").value = "BestPasswordEver321"
End With
End Function
Sub Wait(IE)
Do
WScript.Sleep 500
Loop While IE.ReadyState < 4 And IE.Busy
End Sub
</code></pre>
<p>This code works fine on other sites, I've used it on trello.com before. However this site doesn't use frames and I think this might be the problem.</p>
<p>I've tried to use this code as well:</p>
<pre><code>Call Main
Function Main
Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
IE.Visible = True
IE.Navigate "http://example.com"
Wait IE
With IE.Document
set frame = IE.document.getElementsByName("form")(0)
frame.contentwindow.document.getElementByID("user").value = "CoolUsername123"
frame.contentwindow.document.getElementByID("pswrd").value = "BestPasswordEver321"
End With
End Function
Sub Wait(IE)
Do
WScript.Sleep 500
Loop While IE.ReadyState < 4 And IE.Busy
End Sub
</code></pre>
| <p>First get the frame named "form" from the page. Since it has only name, we can use the <a href="https://msdn.microsoft.com/en-us/library/ms536438(v=vs.85).aspx" rel="nofollow">getElementsByName</a> method and get the first element of the returned collection:</p>
<pre><code>set frame = IE.document.getElementsByName("form")(0)
</code></pre>
<p>Now access the form fields using the <a href="https://msdn.microsoft.com/en-us/library/ms533692(v=vs.85).aspx" rel="nofollow">contentWindow property</a>.</p>
<pre><code> frame.contentwindow.document.getElementByID("user").value = "CoolUsername123"
frame.contentwindow.document.getElementByID("pswrd").value = "BestPasswordEver321"
</code></pre>
|
How can you build RealmSwift for Swift 2.3 from sources using Xcode 8 IDE? <p>I see <a href="http://stackoverflow.com/questions/38888454/how-to-build-realm-using-swift-2-3">here</a> that it is possible to build RealmSwift for swift 2.3 from the command-line.<br>I have RealmSwift as a dependent project within my workspace.<br><br>Is there a tag or commit of <a href="https://github.com/realm/realm-cocoa" rel="nofollow" title="realm-cocoa">realm-cocoa</a> that has the required <code>SWIFT_VERSION = 2.3</code> buildSetting in <code>Realm.xcodeproj</code> to build my project within the Xcode 8 IDE?</p>
| <p>To my knowledge, it's not possible to override an Xcode subproject's <code>SWIFT_VERSION</code> within the IDE. You can specify <code>SWIFT_VERSION</code> when invoking <code>xcodebuild</code>, which should also propagate to Xcode subprojects, but I don't know of any way to do that from the Xcode GUI.</p>
<p>I'd recommend either using an alternative form of installation (CocoaPods, Carthage or prebuilt binaries) or to fork <a href="https://github.com/realm/realm-cocoa" rel="nofollow"><code>realm-cocoa</code></a>, changing the value of <code>SWIFT_VERSION</code> and using that fork as your Xcode subproject.</p>
<p>I'd also recommend filing a radar so that Apple can be made aware of this unfortunate limitation!</p>
<p>To answer your other question, no there have never been any releases of Realm where <code>SWIFT_VERSION</code> was set to <code>2.3</code> in the Xcode project.</p>
|
How to have two series in one chart in stimulsoft? <p><a href="https://i.stack.imgur.com/cfXeH.png" rel="nofollow"><img src="https://i.stack.imgur.com/cfXeH.png" alt="enter image description here"></a></p>
<p>I want to have a scatter diagram and its regression line simultaneously in one chart. How it is possible in stimulsoft ? </p>
| <p>You could add a Scatter Line to the Scatter chart.</p>
|
Spring Mqtt integration: outbound topic issue <p>Hi I'm trying to use spring integration to receive MQTT messages, process them and publish to another topic.</p>
<p>Here is the integration.xml:</p>
<pre><code> <int-mqtt:outbound-channel-adapter id="mqtt-publish"
client-id="spring-foo-1"
client-factory="clientFactory"
auto-startup="true"
url="tcp://localhost:1883"
default-qos="0"
default-retained="true"
default-topic="tweets/akki" />
<int-mqtt:message-driven-channel-adapter id="oneTopicAdapter"
client-id="spring-foo-2"
client-factory="clientFactory"
auto-startup="true"
url="tcp://localhost:1883"
topics="mqtt/publish"
/>
<int:service-activator input-channel="oneTopicAdapter" method="logMessages" ref="mqttLogger" output-channel="mqtt-publish"></int:service-activator>
<bean id="mqttLogger" class="hello.mqttReceiver" />
</code></pre>
<p>And mqttReceiver.java:</p>
<pre><code>package hello;
public class mqttReceiver {
public String logMessages(String a){
String processed_data = a; //TODO Process Data
return processed_data;
}
}
</code></pre>
<p>Following are the issues I'm facing:</p>
<ul>
<li>The <code>processed_data</code> is routed to mqtt/publish and not mqtt/akki</li>
<li>The <code>processed_data</code> is not published ones but many times</li>
</ul>
| <p>That's correct because the <code>AbstractMqttMessageHandler</code> takes a look first of all into <code>headers</code>:</p>
<pre><code>String topic = (String) message.getHeaders().get(MqttHeaders.TOPIC);
Object mqttMessage = this.converter.fromMessage(message, Object.class);
if (topic == null && this.defaultTopic == null) {
throw new MessageHandlingException(message,
"No '" + MqttHeaders.TOPIC + "' header and no default topic defined");
}
</code></pre>
<p>When the <code>DefaultPahoMessageConverter</code> populates that <code>MqttHeaders.TOPIC</code> header from the <code>MqttPahoMessageDrivenChannelAdapter</code> on message arrival.</p>
<p>You should consider to use <code><int:header-filter header-names="mqtt_topic"/></code> before sending message to the <code><int-mqtt:outbound-channel-adapter></code></p>
|
Sequence Recognition using fsm in python <p>What is the best way to detect a sequence of characters in python?</p>
<p>I'm trying to use transitions package by Tal yarkoni for creating fsm's based on input sequences. Then i want to use the created fsms for new sequence recognition.
I'm storing the created fsm in a dict with sequence number as key. </p>
<p>All the fsms from the dictionary should make transition as per input chars. The one which reaches end state is the required sequence and the function should return the key. </p>
<p>Problem is that there is no concept of end state in the transitions fsm model.
Is it possible to do this using transitions package?</p>
| <p>There is no concept of end state, but you can define a state 'end' on each fsm and check for it (see 'checking state' in the git readme), or you could add a 'on enter' reference on the 'end' state and that function will be called when the 'end' state is entered.</p>
<p>Haven't seen transitions before, looks very nice, I like being able to produce the diagrams.</p>
|
i want to save data using following c# code but its not working <p>i want to upload two pic and one file and other data using asp.net with following c#.but it giving error of Uploadresumepic.SaveAs(path1);</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class resume_add : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["JOBConnectionString1"].ConnectionString;
string f1;
string f2;
string f3;
string path1;
string path2;
string path3;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submitresumebtn_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(strConnString))
{
if (Uploadresumepic.PostedFile.ContentLength > 0)
{
f1 = Path.GetFileName(Uploadresumepic.FileName);
path1 = Server.MapPath("profile_pic") + "/" + f1;
Uploadresumepic.SaveAs(path1);
}
if (FileUploadresumefile.PostedFile.ContentLength > 0)
{
f2 = Path.GetFileName(FileUploadresumefile.FileName);
path2 = Server.MapPath("resume_file") + "/" + f2;
FileUploadresumefile.SaveAs(path2);
}
if (coverimage.PostedFile.ContentLength > 0)
{
f3 = Path.GetFileName(coverimage.FileName);
path3 = Server.MapPath("cover_image") + "/" + f3;
coverimage.SaveAs(path3);
}
using (SqlCommand com = new SqlCommand("Recruiter_detail"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.Parameters.AddWithValue("@profile_pic", f1);
com.Parameters.AddWithValue("@name", TextName.Text.Trim());
com.Parameters.AddWithValue("@headline", TxtHedline.Text.Trim());
com.Parameters.AddWithValue("@short_description", textdescription.Text.Trim());
com.Parameters.AddWithValue("@location", TextBoxlocation.Text.Trim());
com.Parameters.AddWithValue("@website_address", TextBoxadress.Text.Trim());
com.Parameters.AddWithValue("@salary", TextBoxsalary.Text.Trim());
com.Parameters.AddWithValue("@phone_no", TxtBoxphoneno.Text.Trim());
com.Parameters.AddWithValue("@resume_file", f2);
com.Parameters.AddWithValue("@cover_image", f3);
com.Parameters.AddWithValue("@facebook_Url", FbURL.Text.Trim());
com.Parameters.AddWithValue("@Twitter_Url", TwitterUrl.Text.Trim());
com.Parameters.AddWithValue("@google_url", GoogleUrl.Text.Trim());
com.Parameters.AddWithValue("@youtube_url", YoutubeUrl.Text.Trim());
com.Parameters.AddWithValue("@age", TextBoxage.Text.Trim());
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
con.Close();
}
Lblsubmit.Text = "Resume Created";
}
}
}
</code></pre>
<p>The sql create procedure i am using is:</p>
<pre><code>USE [JOB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Recruiter_detail]
@profile_pic varchar(50),
@name varchar(50),
@headline nvarchar(50),
@short_description nvarchar(50),
@location nvarchar(50),
@website_address nvarchar(50),
@salary nvarchar(50),
@phone_no nvarchar(50),
@resume_file nvarchar(50),
@cover_image nvarchar(50),
@facebook_Url nvarchar(50),
@Twitter_Url nvarchar(50),
@google_url nvarchar(50),
@youtube_url nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT Recruiter_id FROM Recruiter WHERE Username = '" + Session["name"] + "')
BEGIN
SELECT -1
END
ELSE
BEGIN
INSERT INTO [Recruiter]
([profile_pic]
,[name]
,[headline]
,[short_description]
,[location]
,[website_address]
,[salary]
,[phone_no]
,[resume_file]
,[cover_image]
,[facebook_Url]
,[Twitter_Url]
,[google_url]
,[youtube_url]
)
VALUES
(@profile_pic
,@name
,@headline
,@short_description
,@location
,@website_address
,@salary
,@phone_no
,@resume_file
,@cover_image
,@facebook_Url
,@Twitter_Url
,@google_url
,@youtube_url
)
SELECT SCOPE_IDENTITY() -- Recruiter_id
END
END
GO
</code></pre>
<p>the following tags in aspx code i am using </p>
<pre><code><div class="row">
<div class="col-xs-12 col-sm-4">
<div class="form-group">
<asp:FileUpload ID="Uploadresumepic" type="file" class="dropify" data-default-file="assets/img/avatar.jpg" runat="server" />
<span class="help-block">Please choose a 4:6 profile picture.</span>
</div>
</div>
<div class="col-xs-12 col-sm-8">
<div class="form-group">
<asp:TextBox ID="TextName" type="text" class="form-control input-lg" placeholder="Name" runat="server"></asp:TextBox>
</div>
<div class="form-group">
<asp:TextBox ID="TxtHedline" type="text" class="form-control" placeholder="Headline (e.g. Front-end developer)" runat="server"></asp:TextBox>
</div>
<div class="form-group">
<asp:TextBox ID="textdescription" class="form-control" rows="3" placeholder="Short description about you" runat="server"></asp:TextBox>
</div>
<hr class="hr-lg">
<h6>Basic information</h6>
<div class="row">
<div class="form-group col-xs-12 col-sm-6">
<div class="input-group input-group-sm">
<span class="input-group-addon"><i class="fa fa-map-marker"></i></span>
<asp:TextBox ID="TextBoxlocation" type="text" class="form-control" placeholder="Location, e.g. Melon Park, CA" runat="server"></asp:TextBox>
</div>
</div>
<div class="form-group col-xs-12 col-sm-6">
<div class="input-group input-group-sm">
<span class="input-group-addon"><i class="fa fa-globe"></i></span>
<asp:TextBox ID="TextBoxadress" type="text" class="form-control" placeholder="Website address" runat="server"></asp:TextBox>
</div>
</div>
<div class="form-group col-xs-12 col-sm-6">
<div class="input-group input-group-sm">
<span class="input-group-addon"><i class="fa fa-usd"></i></span>
<asp:TextBox ID="TextBoxsalary" type="text" class="form-control" placeholder="Salary, e.g. 85" runat="server"></asp:TextBox>
<span class="input-group-addon">Per hour</span>
</div>
</div>
<div class="form-group col-xs-12 col-sm-6">
<div class="input-group input-group-sm">
<span class="input-group-addon"><i class="fa fa-birthday-cake"></i></span>
<asp:TextBox ID="TextBoxage" type="text" class="form-control" placeholder="Age" runat="server"></asp:TextBox>
<span class="input-group-addon">Years old</span>
</div>
</div>
<div class="form-group col-xs-12 col-sm-6">
<div class="input-group input-group-sm">
<span class="input-group-addon"><i class="fa fa-phone"></i></span>
<asp:TextBox ID="TxtBoxphoneno" type="text" class="form-control" placeholder="Phone number" runat="server"></asp:TextBox>
</div>
</div>
<div class="form-group col-xs-12 col-sm-6">
<div class="input-group input-group-sm">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<asp:TextBox ID="TextBoxaddress" type="text" class="form-control" placeholder="Email address" runat="server"></asp:TextBox>
</div>
</div>
</div>
</div>
</div>
<div class="button-group">
<div class="action-buttons">
<div class="upload-button">
<button class="btn btn-block btn-gray">Choose a resume file</button>
<asp:FileUpload ID="FileUploadresumefile" type="file" runat="server" />
</div>
<div class="upload-button">
<button class="btn btn-block btn-primary">Choose a cover image</button>
<asp:FileUpload ID="coverimage" type="file" runat="server" />
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-facebook"></i></span>
<asp:TextBox ID="FbURL" type="text" class="form-control" placeholder="Profile URL" runat="server"></asp:TextBox>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-google-plus"></i></span>
<asp:TextBox ID="GoogleUrl" type="text" class="form-control" placeholder="Profile URL" runat="server"></asp:TextBox>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-twitter"></i></span>
<asp:TextBox ID="TwitterUrl" type="text" class="form-control" placeholder="Profile URL" runat="server"></asp:TextBox>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-youtube"></i></span>
<asp:TextBox ID="YoutubeUrl" type="text" class="form-control" placeholder="Profile URL" runat="server"></asp:TextBox>
</div>
</div>
</div>
</div>
<asp:Button ID="submitresumebtn" class="btn btn-success btn-xl btn-round" runat="server" Text="Submit your resume" OnClick="submitresumebtn_Click" />
</code></pre>
| <p>just change the code to <br></p>
<pre><code>path1 = Server.MapPath("~/profile_pic/" + f1);
</code></pre>
|
How to display image which is in binary form in SQL database? <p>I am using this code but image is not displaying full. This code is displaying one forth part of image rather full image. </p>
<pre><code><?php
echo '<img src="data:'.$image_mime_type.';base64,'.base64_encode($rs["Pic"]).'" alt="My image alt" />';
?>
</code></pre>
<p><strong>Screenshot:</strong></p>
<p><img src="https://i.stack.imgur.com/NMx3z.png" alt="enter image description here"></p>
| <p>Try this,</p>
<pre><code>$path = $rs["Pic"];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
//echo $base64;
echo '<img src="'.$base64.'" alt="My image alt" />';
</code></pre>
|
Swap the label text of two buttons in Swift <p>I have 2 button like picture below, their text label are: "Input location...". Now i want to click on the swap button on the right, so the text label of these button will swap. It's look like you have 2 location and you want to swap it. Please any one can point me how to do it. Thank you very much.</p>
<p><img src="https://i.stack.imgur.com/48d6M.png" alt="screenShot"></p>
| <p>On click just set their text to each other. </p>
<pre><code>var tempString = secondButton.titleLabel.text
secondButton.setTitle(firstButton.titleLabel.text, forState: UIControlState.Normal)
firstButton.setTitle(tempString, forState: UIControlState.Normal)
</code></pre>
|
Swift 3 conversion - function in capture list <p>I am trying to convert a project from Swift 2.3 to Swift 3.
Code before the convertor was: </p>
<p>Code in Swift 2.3</p>
<pre><code>..., handler: { [performSegueWithIdentifier] _ in
performSegueWithIdentifier("Help Segue", sender: nil)
}
</code></pre>
<p>After convertor, in Swift 3.0, code become:</p>
<pre><code>..., handler: { [performSegue(withIdentifier:sender:)] _ in
performSegueWithIdentifier("Help Segue", sender: nil)
}
</code></pre>
<p>But I have a compile error:</p>
<pre><code>'Expected 'weak', 'unowned', or no specifier in capture list'
</code></pre>
<p>What I have tried:</p>
<ul>
<li>remove parameters, but it seems that <code>Expression type 'Void' (aka '()') is ambiguous without more context</code>.</li>
</ul>
| <p>The error:
'Expression type 'Void' ...' is related to second line: </p>
<p><code>performSegue(withIdenfifier: "Help Segue", sender: nil)</code></p>
<p>So, all will become: </p>
<pre><code>handler: { [performSegue] _ in
performSegue("Help Segue", nil)
})
</code></pre>
|
Detect the number of physical objects in an image (Image processing) <p>I am developing a Ruby on Rails application where I want to detect the number of physical objects (bottles and food packets) in an image.</p>
<p>I just explored Google Vision API (<a href="https://cloud.google.com/vision/" rel="nofollow">https://cloud.google.com/vision/</a>) to check whether this is possible or not. I uploaded a photo which has some cool drink bottles and got the below response.</p>
<pre><code>{
"responses" : [
{
"labelAnnotations" : [
{
"mid" : "\/m\/01jwgf",
"score" : 0.77698487,
"description" : "product"
},
{
"mid" : "\/m\/0271t",
"score" : 0.72027034,
"description" : "drink"
},
{
"mid" : "\/m\/02jnhm",
"score" : 0.51373237,
"description" : "tin can"
}
]
}
]
}
</code></pre>
<p>My concern here is, it is not giving the number of cool drink bottles available in the image, rather it returning type of objects available in the photo.</p>
<p>Is this possible in Google Vision API or any other solution available for this?</p>
<p>Any help would be much appreciated.</p>
| <p>I've made a simple command line program that detects faces and replaces them with emojis using OpenCV through JRuby. It's an absolute pain to set up, but once it is done it is a beauty to write in. I also made a small script to create OpenCV JRuby projects that can be executed with the required command line arguments in a shell script, which alleviates most, if not all, of the pain when setting up.</p>
<p>Later on when I'm at my computer I'll upload both the project and the script to GitHub and link them here if you want me to, but for now I can direct you to <a href="https://github.com/ryotarai/opencv_on_jruby?files=1" rel="nofollow">this project</a> as an example.</p>
<h3>EDIT</h3>
<p>Here are the links to the JRuby OpenCV project and script:</p>
<p><a href="https://github.com/eschutz/emojify" rel="nofollow">JRuby OpenCV Project</a></p>
<p><a href="https://github.com/eschutz/ropencv" rel="nofollow">Project Creation Script</a></p>
|
No respond from getSelectedItem Spinner <p>I have a Spinner with list of category, which get the data from JSON. I want to make, when an item other than <em>All Category</em> get selected, another spinner of subcategory become visible, and get loaded with data from JSON according to its category.</p>
<p>Previously I managed to do it but after left it for a few days and have other parts done, it no longer works.</p>
<p>Since the first one loaded into spinner is <em>All Category</em>, it triggered <code>setOnItemSelectedListener()</code> and hid <code>subcategorySpinner</code>. If other item get selected, <code>subcategorySpinner</code> still not shown.</p>
<p>Is there something wrong with the code logic? Please help.</p>
<pre><code>categorySpinner = (Spinner) rootView.findViewById(R.id.categorySpinner);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity().getApplicationContext(), R.layout.spinner_item, categoryList);
adapter2.setDropDownViewResource(R.layout.spinner_dropdown_item);
categorySpinner.setAdapter(adapter2);
categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
categoryString = categorySpinner.getSelectedItem().toString().replace(" ", "%20");
if (categorySpinner.getSelectedItem().toString().equals("All Category")) {
Log.d("debug", "all category");
subcategorySpinner.setVisibility(View.GONE);
} else {
Log.d("debug", "other than all category");
subcategorySpinner.setVisibility(View.VISIBLE);
generateSubcategorySpinner(Config.GET_SUBCATEGORY_URL+"?category="+categoryString);
}
}
});
</code></pre>
| <p>change your code to</p>
<pre><code>categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
categoryString = parent.getItemAtPosition(position).toString();
Log.d("debug", categoryString+"..."+position);
if (categoryString.equals("All Category")) {
Log.d("debug", "all category");
subcategorySpinner.setVisibility(View.GONE);
} else {
Log.d("debug", "other than all category");
subcategorySpinner.setVisibility(View.VISIBLE);
categoryString = categoryString.replace(" ", "%20")
generateSubcategorySpinner(Config.GET_SUBCATEGORY_URL+"?category="+categoryString);
}
}
</code></pre>
|
Cannot initialize an uninitialized variable inside a class method <p>I have just started practicing OO programming using PHP. Recently I have encountered a problem.<br>
I am trying to declare a variable inside a class but leaving it uninitialized. Later inside a method of the class when i try to initialize the variable it shows the following errors:</p>
<blockquote>
<p>Undefined variable: a in C:\wamp\www\sample.php on line 6</p>
<blockquote>
<p>Fatal error: Cannot access empty property in C:\wamp\www\sample.php on line 6</p>
</blockquote>
</blockquote>
<p>Here is the code that i am trying to execute: </p>
<pre><code><?php
class Sample{
public $a;
function call($b){
$this->$a = $b;
echo $a;
}
}
$sam = new Sample();
$sam->call(5);
?>
</code></pre>
<p>How do i fix this?</p>
| <p>In function call $a does not exist. Only $this->a (without $ before the a), which is the property of your "sam" object, and $b, which is an input parameter.
Plus when you set the property, you must not use $a. Use $this->a.
If you would have a variable which contains a property name of the class, you should use $this->$a, which would mean $this->asdf, if $a = 'asdf';</p>
|
How do I split a list containing data frames into the individual data frames? <p>I have 6 lists (<code>l1</code>,<code>l2</code>,<code>l3</code>,<code>l4</code>,<code>l5</code>,<code>l6</code>) in total and in each list, I have 12 dataframes (<code>df1</code>,<code>df2</code>,<code>df3</code>,...,<code>df10</code>,<code>df11</code>,<code>df12</code>). I would like to split all the lists. This is what I have tried.</p>
<pre><code>split_df<-function(list){
for (i in 1:length(list)){
assign(paste0("df",i),list[[i]])}
}
</code></pre>
<p>It only works if I use the for loop only. But it doesnt work with the function.</p>
<p>Let's look at the following list, l1:</p>
<pre><code>l1<-list(data.frame(matrix(1:10,nrow=2)),data.frame(matrix(1:4,nrow=2)))
split_df(l1)
df1
Error: object 'df1' not found
df2
Error: object 'df2' not found
</code></pre>
<p>But without the function:</p>
<pre><code>for (i in 1:length(l1)){
assign(paste0("df",i),l1[[i]])}
df1
# X1 X2 X3 X4 X5
# 1 1 3 5 7 9
# 2 2 4 6 8 10
df2
# X1 X2
# 1 1 3
# 2 2 4
</code></pre>
<p>How do I rectify this?</p>
| <p>You use assign locally. So inside the function, you create the <code>data.frame</code>s <code>df1</code> and <code>df2</code>. You can assign these to the global environment instead: </p>
<pre><code>split_df<-function(list){
for (i in 1:length(list)){
assign(paste0("df",i), list[[i]], envir = .GlobalEnv)
}
}
</code></pre>
|
Upload data and file with ng-file-upload <p>I am new to angular. I have searched a lot but didn't find a way to grab the data send through <strong>Upload.upload()</strong> of ng-file-upload. Though my file is uploaded into the destination folder using muter</p>
<p>Here is my controlled function which is called on upload click from the view.</p>
<pre><code>$scope.doUpload = function() {
Upload.upload({
url: '/api/upload/',
data: {'sabhaDetails': sabhaDetails},
file: sabhaFile,
fileName: sabhaDetails.sabha_video_name
});
}
</code></pre>
<p>In my route I have: </p>
<pre><code>/ annotator page. (http://localhost:1337/api/upload)
annotationRouter.route('/upload')
.post(function(req, res) {
**console.log(req.data);**
upload(req, res, function(err) {
if(err) {
res.json({ error_code:1, err_desc:err });
return;
}
res.json({ error_code:0, err_desc:null });
})
});
</code></pre>
<p>But I am getting undefined for my req.data. Is there something wrong. How to grab the send data through upload?</p>
| <p>You are receiving <code>multipart/form-data</code> from ngf. </p>
<p>I don't know which server you are using, but I think you should check <code>req.form</code> rather than <code>req.data</code> or something. </p>
<p>Alternatively, you can use some external middleware, like <a href="https://github.com/expressjs/body-parser" rel="nofollow" title="this">this</a></p>
|
android listview with button does not work <p>I created a listview adapter which a row contains a button. It works when i clicked on the button , but not when i click on the row
This is my main activity</p>
<pre><code>public class MainActivity extends AppCompatActivity {
.
.
.
ListView lvProducts = (ListView) findViewById(R.id.lvProducts);
lvProducts.addHeaderView(getLayoutInflater().inflate(R.layout.product_list_header, lvProducts, false));
ProductAdapter productAdapter = new ProductAdapter(this);
productAdapter.updateProducts(Constant.PRODUCT_LIST);
lvProducts.setAdapter(productAdapter);
lvProducts.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Product product = Constant.PRODUCT_LIST.get(position - 1);
Intent intent = new Intent(MainActivity.this, ProductActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("product", product);
Log.d(TAG, "View product: " + product.getName());
intent.putExtras(bundle);
startActivity(intent);
}
});
</code></pre>
<p>This is the adapter part</p>
<pre><code>public class ProductAdapter extends BaseAdapter {
bAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(v.getContext(),"Button "+position,Toast.LENGTH_SHORT).show();
Cart cart = CartHelper.getCart();
Log.d(TAG, "Adding product: " + product.getName());
cart.add(product, 1);
Intent intent = new Intent(context, ShoppingCartActivity.class);
context.startActivity(intent);
}
});
</code></pre>
<p>The xml file of adapter</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200px"
android:layout_margin="5dp"
android:minHeight="50dp"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="@+id/tvProductName"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.50"
android:gravity="center"
android:text=""/>
<ImageView android:id="@+id/ivProductImage"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.25"
android:gravity="center"/>
<TextView
android:id="@+id/tvProductPrice"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="0.24"
android:gravity="center"
android:text=""/>
<Button
android:id="@+id/tvAddItem"
android:layout_width="69dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="A"
/>
</LinearLayout>
</code></pre>
| <p>In your custom layout file set</p>
<pre><code>android:focusable="false"
android:focusableInTouchMode="false"
</code></pre>
<p>for your button.</p>
|
Prompt the user for an index - 2D array - output the array element given by the index - java <p>I'm very new to Java and have no idea what I'm doing. How can I prompt the user for an index for a 2D array in the format 'ab' (the value of a is row number and the value of b is column number) and output the array element given by the index? For example, if the use enters "00" it
should output '3'.
Any help would be appreciated. Please keep in mind that I'm not allowed to use array list.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import java.util.Scanner;
public class Exercise23 {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int row = 3;
int col = 4;
int[][] array = new int[row][col];
System.out.println("Enter the index: ");
int index=scanner.nextInt();
String sIndex= String.format("%2d", index);
String quit = "quit";
if(sIndex!=quit){
array[0][0] =3;
array[0][1] =0;
array[0][2] =0;
array[0][3] =4;
array[1][0] =2;
array[1][1] =8;
array[1][2] =0;
array[1][3] =0;
array[2][0] =1;
array[2][1] =1;
array[2][2] =0;
array[2][3] =1;
for(int i=0; i<row; i++) {
for(int j=0; j<col; j++) {
System.out.print(array[i][j]);
}
System.out.println("");
}
}
}
}</code></pre>
</div>
</div>
</p>
| <p>There are a number of ways to do this. I would do:</p>
<pre><code> if (sIndex.length() == 2) {
int selectedRow = Character.getNumericValue(sIndex.charAt(0));
int selectedColumn = Character.getNumericValue(sIndex.charAt(1));
// do your stuff
}
</code></pre>
<p>You will probably want to add an else part that issues an error message.</p>
<p>If the user is nasty and enters -1, the length will be 2, and I donât know what the above code will do, certainly nothing meaningful.</p>
|
Execute a method inside Eventhandler with delay and ignore th next eventhandler during this interval <p>I have a textbox filter which is binded to the following event handler</p>
<pre><code> SimpleFilterTextBox.TextChanged += OnFilterTextBoxTextChangedHandler;
private void OnFilterTextBoxTextChangedHandler(object oSender, TextChangedEventArgs oArgs)
{
//Other operations
_oCollectionView.Filter = new Predicate<object>(DoFilter);
}
</code></pre>
<p>I want the DoFilter to be called after the first character is pressed and wait for 1 sec( in case the user enters another character during this time). Don't call the method DoFilter during this gap. And the same for the third and further on.</p>
<p>The problem here I face is the second character is handled in a new handler, how can I make it to accept 2 or more characters with the given delay. </p>
| <p>Use <code>async</code> and <code>CancellationToken</code>.</p>
<pre><code>private void OnFilterTextBoxTextChangedHandler(object oSender, TextChangedEventArgs oArgs)
{
//Other operations
_oCollectionView.Filter = new Predicate<object>(DoFilter);
}
private CancellationTokenSource filterToken;
private async void DoFilter(object parameter)
{
CancellationTokenSource localToken;
try
{
if (this.filterToken != null)
this.filterToken.Cancel();
this.filterToken = new CancellationTokenSource();
localToken = this.filterToken;
await Task.Delay(1000, localToken.Token);
// Your logic
}
catch (TaskCanceledException) {}
catch (Exception e) { // Other Exceptions }
finally
{
localToken.Dispose();
}
}
</code></pre>
|
JTextfield only accept numbers between 0-255 <p>for a little test application I need a TextField which only accepts numbers. In addition the user should only be able to enter numbers from 0-255. So far i found this:</p>
<pre><code>import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* A JTextField that accepts only integers.
*
* @author David Buzatto
*/
public class IntegerField extends JTextField {
public IntegerField() {
super();
}
public IntegerField( int cols ) {
super( cols );
}
@Override
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
@Override
public void insertString( int offs, String str, AttributeSet a )
throws BadLocationException {
if ( str == null ) {
return;
}
char[] chars = str.toCharArray();
boolean ok = true;
for ( int i = 0; i < chars.length; i++ ) {
try {
Integer.parseInt( String.valueOf( chars[i] ) );
} catch ( NumberFormatException exc ) {
ok = false;
break;
}
}
if ( ok ) {
super.insertString( offs, new String( chars ), a );
}
}
}
</code></pre>
<p>I added to the for Loop the following so only Numbers which contain of 3 Digits can be typed</p>
<pre><code> if(super.getLength() == 3) {
ok = false;
System.out.println("tooLong");
break;
}
</code></pre>
<p>But how can I set a maximum input value? The user should only enter numbers which goes from 0-255.</p>
<p>Thanks in advance</p>
| <p>you can implement those two checks as follows:</p>
<pre><code> if(str.length()>3) {
return;
}
int inputNum = Integer.parseInt(str);
if(inputNum<0 || inputNum>255) {
return;
}
</code></pre>
<p>Add these checks before the last if block and you should be good to go.</p>
|
Get back Access Token of Twitch API with node js <p>I am developping a google chrome extension in which I need to authenticate the user on Twitch. According to <a href="https://github.com/justintv/Twitch-API/blob/master/authentication.md" rel="nofollow">https://github.com/justintv/Twitch-API/blob/master/authentication.md</a>, I registered an application to get a client_id and my chrome extension open the following link:</p>
<pre><code>https://api.twitch.tv/kraken/oauth2/authorize
?response_type=token
&client_id=[your client ID]
&redirect_uri=[your registered redirect URI]
&scope=[space separated list of scopes]
</code></pre>
<p>After accepting to use my application, users are redirected to this link:</p>
<pre><code>https://[your registered redirect URI]/#access_token=[an access token]&scope=[authorized scopes]
</code></pre>
<p>[your registered redirect URI] is the link of my node js server. I need to save the access_token information, but I don't know how to access to elements after '#'. The request url or its params aren't containing them.</p>
| <p>There is already an explanation in the documentation just below the line that you 've posted:</p>
<blockquote>
<p>Note that the access token is in the URL fragment, not the query
string, so it won't show up in HTTP requests to your server. URL
fragments can be accessed from JavaScript with document.location.hash</p>
</blockquote>
<p>The browser/client removes the fragment elements before sending the request to the server. You have to load the page, have a small javascript script and retrieve the values from the client. Then you can decide how to handle the data. For example, you can fire an ajax request to your server.</p>
|
Initialize a struct in C using {} <p>In the marked line I get an error <code>Error - expected expression</code></p>
<pre><code>#include <stdlib.h>
struct list_head {
struct list_head *next, *prev;
};
struct program_struct {
const char *name;
struct list_head node;
};
typedef struct program_struct program_t;
struct task_t {
program_t blocked_list;
};
int main() {
struct task_t *p = malloc(sizeof(*p));
p->blocked_list.name = NULL;
p->blocked_list.node = {&(p->blocked_list.node), &(p->blocked_list.node)}; //error
return 0;
}
</code></pre>
<p>I know I can replace this line with </p>
<pre><code>p->blocked_list.node.next = &(p->blocked_list.node);
p->blocked_list.node.prev = &(p->blocked_list.node);
</code></pre>
<p>But can I make it work using <code>{}</code> like I tried in the first piece of code?</p>
| <p>Initialization is allowed only when you define a variable. So, you can't use initializers in assignment.
You can instead use C99's <a href="https://gcc.gnu.org/onlinedocs/gcc-3.2.3/gcc/Compound-Literals.html" rel="nofollow">compound literals</a>:</p>
<pre><code>p->blocked_list.node = (struct list_head) {&(p->blocked_list.node), &(p->blocked_list.node)}; //error
</code></pre>
|
How to create angular2 jwt token in angular2 <p>I need to create a jwt in angular2. How do I do that?
I am using this for an api service.</p>
<pre><code> jwt_token = ?
</code></pre>
<p>I can create in python with no issue. </p>
| <p><strong>Normally tokens are generated on the server-side !!
If you are creating them on client side, its easy to see your password!!</strong></p>
<p>Anyway, to answer your question:</p>
<p>Best way is to use an existing library, like this one: <a href="https://www.npmjs.com/package/jsonwebtoken" rel="nofollow">https://www.npmjs.com/package/jsonwebtoken</a></p>
<p><code>npm install jsonwebtoken --save</code></p>
<p>install its typings (if you use TypeScript)</p>
<p><code>npm install @types/jsonwebtoken --save</code></p>
<p>and use it like this:</p>
<pre class="lang-js prettyprint-override"><code>import * as jwt from 'jsonwebtoken';
let token = jwt.sign({ anyObject: 'here..' }, 'your super secret password!!');
</code></pre>
|
Calling a Java 8 function only once when iterating a function list <p>Is there an elegant way to store the return value of the <code>apply()</code> method so it won't have to be invoked more than once? Because the only way I could think of is to create a local map variable that will store the function-"return value" pairs.</p>
<pre><code>@Autowired
private List<Function<String, String>> evaluators;
//...
private String evaluate(String code) {
return evaluators.stream().filter(f -> f.apply(code) != null).findFirst().get().apply(code);
}
</code></pre>
| <p>Try this.</p>
<pre><code> private String evaluate(String code) {
return evaluators.stream()
.map(f -> f.apply(code))
.filter(s -> s != null)
.findFirst().get();
}
</code></pre>
|
Unable to create post on my Google plus activity <p>How to sent <code>CURLOPT_POSTFIELDS</code> values for google plus..add post.</p>
<p>I'm able to get ..authentication token on google plus..but when I add post on google plus.. then I am getting that error </p>
<pre><code>{
"error":{
"errors":[
{
"domain":"global",
"reason":"forbidden",
"message":"Forbidden"
}
],
"code":403,
"message":"Forbidden"
}
}
</code></pre>
<p>Send data </p>
<pre><code>{
"object":{
"originalContent":"Happy weekend!"
},
"access":{
"items":[
{
"type":"domain"
}
],
"domainRestricted":true
}
}
</code></pre>
<p>code:</p>
<pre><code> $url = 'https://www.googleapis.com/plusDomains/v1/people/' . $user_id . '/activities';
$headers = array(
'Authorization : Bearer ' . $accesstoken,
'Content-Type : application/json',
'Accept : application/json',
);
$post_data = array("object" => array("originalContent" => "Happy weekend!"), "access" => array("items" => array(array("type" => "domain")),"domainRestricted" => true));
//$post_data = array("message" => "Shareing Message to your account will be here");
///$post_data['newcontent'] = "Post on Google Plus Test By Me";
echo $data_string = json_encode($post_data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$file_result = curl_exec($ch);
print_r($file_result);
curl_close($ch);
</code></pre>
| <p>There are two possible causes for this problem:</p>
<ol>
<li>Your question says you are trying to post to <a href="https://plus.google.com/u/0/" rel="nofollow">Google+</a>. There is no way to post to Google+ the social media site the <a href="https://developers.google.com/+/web/api/rest/" rel="nofollow">Google+ API</a> is read only.</li>
<li>Your code is trying to post to google plus domains. Using the <a href="https://developers.google.com/+/domains/api/" rel="nofollow">Google+ domains API</a>. That error is caused by the user you are authenticating with not having access to a <a href="https://developers.google.com/+/domains/" rel="nofollow">google plus domains account</a>. Double check that the user has the correct access to your Google Plus Domains account. Also please fix the title and tag of your question to correctly reflect that you are asking about Google Plus domains and not Google plus the social media site.</li>
</ol>
<p>If you are trying to post to Google+ the social media website you can stop now because its not possible to do that.</p>
|
Matplotlib : single line chart with different markers <p>I have a list for markers on my time series depicting a trade. First index in each each list of the bigger list is the index where i want my marker on the line chart. Now I want a different marker for buy and sell</p>
<pre><code>[[109, 'sell'],
[122, 'buy'],
[122, 'sell'],
[127, 'buy'],
[131, 'sell'],
[142, 'buy'],
[142, 'sell'],
[150, 'buy']]
</code></pre>
<p>code:</p>
<pre><code>fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(1,1,1)
ax.set_ylim( min(timeSeriesList_1)-0.5, max(timeSeriesList_1)+0.5)
start, end = 0, len(timeSeriesList_index)
stepsize = 10
ax.xaxis.set_ticks(np.arange(start, end, stepsize))
ax.set_xticklabels(timeSeriesList_index2, rotation=50)
## change required here:
ax.plot(timeSeriesList_1, '-gD', markevery= [ x[0] for x in markers_on_list1])
</code></pre>
<p>This is how my chart looks:</p>
<p><a href="https://i.stack.imgur.com/MCvrv.png" rel="nofollow"><img src="https://i.stack.imgur.com/MCvrv.png" alt="enter image description here"></a></p>
<p>Please tell me, how I can have different markers for buy and sell.</p>
| <p>Create two new arrays, one buy-array and one sell-array and plot them individually, with different markers. To create the two arrays you can use list-comprehension</p>
<pre><code>buy = [x[0] for x in your_array if x[1]=='buy']
sell = [x[0] for x in your_array if x[1]=='sell']
</code></pre>
|
Find the last visited URL in javascript with history <p>I know about <code>document.referer</code> and this is not what I'm looking for.
It could probably be a solution but I want to retrieve it in local without using server.</p>
<h2>Steps :</h2>
<ul>
<li><p>I'm pushing a new state in the current url of my page with <code>history.pushState('','','#test')</code></p></li>
<li><p>I'm going to the next page.</p></li>
<li><p>And now I want to retrieve the URL but <code>history.previous</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/History#Properties" rel="nofollow">has been erased since Gecko 26</a>.</p></li>
</ul>
<p>Is there an other way of getting this value except from using cookies or sessionStorage?</p>
| <p>One way of doing it would be to put the value in a parameter of the next page address, like so:</p>
<pre><code>http://server.com/next-page-address/whatever.html?prevData=RequiredStateData
</code></pre>
<p>Note that using this approach, you might be exposed to users changing <code>RequiredStateData</code> in a malicious way. You can protect yourself using encryption or some checksum field.</p>
|
JOptionPane.showinputdialog To only Input Letters or Numbers and multiple choice <p>Hello i'm new to java and i would like to ask some question regarding JOptionPane.showinput so that it will only accept letters/numbers only and if they enter an incorrect one it will result to an error and need to retype again (searched the site for some solution but they don't work on my code i don't know why)
And lastly i was planning to multiple choices on my joptionpane but when i typed icon it got registered as an error
heres my code</p>
<pre><code> JFrame frame = new JFrame("Student Record");
JOptionPane.showMessageDialog(frame,
"Welcome to the School's Student Grade Record!");
System.out.println("School's Student Grade Record");
String name;
name = JOptionPane.showInputDialog(frame,"Enter the name of the student");
System.out.println("The name of the student is: "+name);
Object[] choices = {"Filipino", "Math", "English"};
String grade = (String)JOptionPane.showInputDialog(frame,
"What grade subject do you choose to input?\"","Customized Dialog",
JOptionPane.PLAIN_MESSAGE,icon,choices,"Math");
System.exit(0);
}
}
</code></pre>
| <p>for getting a valid string that contains only alphabets and numbers then regex are a great help <strong>^[a-zA-Z0-9]*$</strong> it allows only alphabets and numbers only and the following code will ask repeatedly until a valid input is given</p>
<pre><code>String input;
String string = "";
do {
input = JOptionPane.showInputDialog("Enter String ");
if (input.matches("^[a-zA-Z0-9]*$")) {
string = input;
System.out.println("Name "+string);
} else {
System.out.println("Please enter a valid name containing: âa-zâ or âA-Zâ lower or upper case or numbers");
}
} while (!input.matches("^[a-zA-Z0-9]*$"));
</code></pre>
<p>now about your icon here is a way to specify <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html" rel="nofollow">icons</a></p>
|
Displaying progress in one line? <p>Is it possible to display progress on one line instead of having the for-loop printing out a bunch of lines for every action?</p>
<p>Like, for example. Instead of this:</p>
<pre><code>Progress: 0%
Progress: 15%
Progress: 50%
Progress: 100%
</code></pre>
<p>It does all that in one line (while showing progress, of course):</p>
<pre><code>Progress: 100%
</code></pre>
<p>Basically, I'm making a sockets program to transfer files from one socket to another socket. And it's taking the amount transferred divided by the file size multiplied by 100 to get its percentage.</p>
| <p>Use</p>
<pre><code>printf ("\r progress =%d", progress)
</code></pre>
|
jQuery function into ajax <p>I'm using jQuery for a while but it is the first time I need to create my own function. (I'm using noConflict)</p>
<p>I have a code who work like this :</p>
<pre><code>jQuery(function()
{
jQuery("#tabs-3").dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
//etendre tt les noeuds
jQuery("#tabs-3").dynatree("getRoot").visit(function(dtnode){
dtnode.expand(true);
});
});
</code></pre>
<p>The code above is working, BUT, this part of code is in an ajax call, it worked for the first time when I called it, but not the second time or in future. when i call it with a function it gives error "jQuery.mytree is not a function". So what's wrong in my code. please help me . </p>
<pre><code>(function(jQuery){
jQuery.fn.extend({
mytree: function (mytreename)
{
alert(mytreename);
jQuery(mytreename).dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
}
});
jQuery.mytree('#tabs-3');
})(jQuery);
</code></pre>
<p>Thanks!</p>
| <p>That's because when you do jQuery.fn.extend, it extends your selector.</p>
<p>For example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id = "tabs-3"></div>
<script type="text/javascript">
(function(jQuery){
jQuery.fn.extend({
mytree: function mytree() {
console.log("My tree ", this.attr("id"));
// Do your cool AJAX calls
}
});
jQuery("#tabs-3").mytree();
})(jQuery);
</script></code></pre>
</div>
</div>
</p>
<p>Will work. Inside mytree(), this is the result of your selector.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.