title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
How to convert datetime from string format into datetime format in pyspark? | <p>I created a dataframe using sqlContext and I have a problem with the datetime format as it is identified as string.</p>
<pre><code>df2 = sqlContext.createDataFrame(i[1])
df2.show
df2.printSchema()
</code></pre>
<p>Result:</p>
<pre><code>2016-07-05T17:42:55.238544+0900
2016-07-05T17:17:38.842567+0900
2016-06-16T19:54:09.546626+0900
2016-07-05T17:27:29.227750+0900
2016-07-05T18:44:12.319332+0900
string (nullable = true)
</code></pre>
<p>Since the datetime schema is a string, I want to change it to datetime format as follows:</p>
<pre><code>df3 = df2.withColumn('_1', df2['_1'].cast(datetime()))
</code></pre>
<p>Here I got an error:
TypeError: Required argument 'year' (pos 1) not found</p>
<p>What should I do to solve this problem?</p> | 0 |
Background cover image on 100vh - screen differences | <p>So i try to set image on cover with 100vh - but i have very specific situation.</p>
<p>On my image i have big plate and tablet that "lie down" on this plate.</p>
<p>My goal is to make this image 100vh header but there is a problem - when i try test this on my big monitor it looks ok, but on monitor with smaller height it's look bad -i need this tablet to be 100% visible in all desktop devices.</p>
<p>Check my fiddle with "Full page" option to see what i'm about.</p>
<p>I also try to make this image cover without tablet, and then try to place another image with tablet and <code>position:absolute</code>, but my second image isn't always in exact same place to feet this plate insade frame.</p>
<p>Is it possible to achieve what i desire ?</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>.cover {
position: relative;
height: calc(100vh - 80px);
background-size: cover;
background-position: bottom;
background-repeat: no-repeat;
background-image: url(https://s4.postimg.org/uwxudv17x/cover.png);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div class="cover">
</div>
</body></code></pre>
</div>
</div>
</p> | 0 |
VueJS async component data and promises | <p>Trying out VueJS 2.0 RC, and using the fetch API to load some data for some of the components. Here's a mock example:</p>
<pre><code>const Component = {
template: '#comp',
name: "some-component",
data: function () {
return {
basic: data.subset,
records: function () {
return fetch('/datasource/api', {
method: 'get'
}).then(function (response) {
return response.json();
}).then(function (response) {
if (response.status == "success") {
return response.payload;
} else {
console.error(response.message);
}
}).catch(function (err) {
console.error(err);
});
}
}
}
};
</code></pre>
<p>The <code>data</code> object is a global application state, defined before the app's initialization, and only a subset of it is needed in the component, hence that part. The main set of the component's data comes from another endpoint which I'm trying to call. However, the <code>data</code> property expects an object, and it's getting back a Promise it can't really use in the context of a loop in the template for rendering etc (e.g. <code>v-for="record in records"</code>)</p>
<p>Am I going about this the wrong way? What's the approach to get the data <code>records</code> property to update once it's fully fetched? Is there a way to force the code to stop until the promise resolves (effectively making it sync)? The component is useless without the data anyway, so there's a waiting period before it can be used regardless.</p>
<p>What is <em>the right way</em> to asynchronously populate a component's data field without using plugins like vue-async or vue-resource?</p>
<p>(I know I could use the XHR/jQuery methods of non-promise ajax calls to do this, but I want to learn how to do it using fetch)</p>
<hr>
<p>Update: I tried defining a created hook, and a method to load the data, <a href="https://jsfiddle.net/ytm9zscw/" rel="noreferrer">like this</a> but no dice - in my own experiments, the records property fails to update once it's loaded. It doesn't change, even though the data is successfully fetched (successfully logs into console).</p>
<p>Could have something to do with me using vue-router and the component I'm dealing with triggering when a link is clicked, as opposed to being a regular Vue component. Investigating further...</p>
<hr>
<p>Update #2: If I continue investigating the jsfiddle approach above and log <code>this.records</code> and <code>response.payload</code> to the console, it shows the records object being populated. However, this doesn't seem to trigger a change in the template or the component itself - inspecting with Vue dev tools, the records property remains an empty array. Indeed, if I add a method <code>logstuff</code> and a button into the template which calls it, and then have this method log <code>this.records</code> into the console, it logs an observer with an empty array:</p>
<p><a href="https://i.stack.imgur.com/XB0kC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XB0kC.png" alt="enter image description here"></a></p>
<p>Now I'm wondering why the data property of a component would be not updated even after it's explicitly set to another value. Tried setting up a watcher for <code>$route</code> that triggers the <code>reload</code> method, but no dice - every subsequent load of that route does indeed re-issue the fetch, and the console logs <code>this.records</code> as populated (from within fetch), but the "real" <code>this.records</code> remains an empty array.</p> | 0 |
Dynamically Add / Remove multiple input fields in PHP with Jquery Ajax | <p>This is the HTML of my form</p>
<pre><code><div class="crcform">
<h1>Internship Details</h1>
<form name="internship_details" id="intership_details">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td>
<!--div class="top-row"-->
<div class="field-wrap">
<label>
Company<span class="req">*</span>
</label>
<input type="text" required autocomplete="off" name="company[]"/>
</div>
<div class="field-wrap">
<label>
Project<span class="req">*</span>
</label>
<input type="text"required autocomplete="off" name="project[]"/>
</div>
<div class="field-wrap">
<label>
Duration<span class="req">*</span>
</label>
<input type="text"required autocomplete="off" name="duration[]"/>
</div>
<div class="field-wrap">
<label>
Key Learning<span class="req">*</span>
</label>
<input type="text"required autocomplete="off" name="key_learning[]"/>
</div></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
<!--div class="top-row">
<div class="field-wrap">
<button class="button button-block" name="submit" id="submit"/>NEXT</button>
</div-->
</form>
</div>
</code></pre>
<p>this is javascript of dynamically add/remove form</p>
<pre><code><script>
$(document).ready(function(){
var i = 1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><div class="field-wrap"><label>Company<span class="req">*</span></label><input type="text" required autocomplete="off" name="company[]"/></div><div class="field-wrap"><label>Project<span class="req">*</span></label><input type="text"required autocomplete="off" name="project[]"/></div><div class="field-wrap"><label>Duration<span class="req">*</span></label><input type="text"required autocomplete="off" name="duration[]"/></div><div class="field-wrap"><label>Key Learning<span class="req">*</span></label><input type="text"required autocomplete="off" name="key_learning[]"/></div></td></td><td><button name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click','.btn_remove', function(){
var button_id = $(this).attr("id");
$("#row"+button_id+"").remove();
});
$('#sumbit').clic(function(){
$.ajax({
url:"internship_details.php",
method:"POST",
data:$('#internship_details').serialize(),
success:function(data)
{
alert(data);
$('#internship_details')[0].reset();
}
});
});
});
</script>
</code></pre>
<p>this is the php code to store data in database</p>
<pre><code><?php
include 'connection.php';
$number = count($_POST["company"]);
if ($number > 0){
for($i = 0; $i < $number; $i++){
if(trim($_POST["company"][$i]) != ''){
$sql = "INSERT INTO internship VALEUS('".mysqli_real_escape_string($connect, $_POST["company"][$i]."')";
mysqli_query($connect, $sql);
}
}
echo 'Data Inserted';
}
else{
echo "Enter Name";
}
?>
</code></pre>
<p>I'm unable to store the value in database. Can anyone tell me where im going wrong?
Can you also tell me what its insert query will be because i'm adding more than one column in a row. So help me with this</p> | 0 |
Why is 8086 memory divided into odd and even banks? | <ol>
<li><p>What is the benefit of dividing memory into banks ? </p></li>
<li><p>How can 8086 access a word in a single access using this scheme but can't do so using a single memory chip ? ( AFAIK processors usually access memory in chunks instead of single bytes anyways so can't understand why it can't just access a word in single access in case of a single memory chip)</p></li>
<li><p>Is the division of memory into banks a physical one or logical one ? </p></li>
<li><p>How are the data lines connected to the memory in case of even and odd banks and in case of single chip ? </p></li>
</ol> | 0 |
Is it possible to use the YouTube Live Stream API to broadcast through my phone camera? | <p>I want to create a basic app that allow users to simply start to broadcast a video through their phone camera (front and back) just by pressing a button.</p>
<p>Does the YouTube live stream API allow me to handle the video streaming process?</p>
<p>If so, is YouTube Live Stream API totally free of charges and will never ask me to pay something if I reach a certain amount of usage?</p> | 0 |
SweetAlert showLoaderOnConfirm not displaying | <p>i am using sweetalert to display delete confirmation,and process it later while displayin a loading action,though it is not working,thi is the code,that doesn't work (it is supposed to display a loading animation,but it actually is not doing so) any thoughts ?</p>
<p>This the javascript</p>
<pre><code>document.querySelector('div.test').onclick = function() {
swal({
title: 'Ajax request example',
text: 'Submit to run ajax request',
type: 'info',
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
}, function(){
setTimeout(function() {
swal('Ajax request finished!');
}, 2000);
});
};
</code></pre>
<p>Html </p>
<pre><code><div class="test">
<button>show alert</button>
</div>
</code></pre>
<p>this is the <a href="http://jsfiddle.net/xe096w10/283/" rel="nofollow">fiddle</a></p> | 0 |
How to move tests into a separate file for binaries in Rust's Cargo? | <p>I created a new binary using Cargo:</p>
<pre><code>cargo new my_binary --bin
</code></pre>
<p>A function in <code>my_binary/src/main.rs</code> can be used for a test:</p>
<pre><code>fn function_from_main() {
println!("Test OK");
}
#[test]
fn my_test() {
function_from_main();
}
</code></pre>
<p>And <code>cargo test -- --nocapture</code> runs the test as expected.</p>
<p>What's the most straightforward way to move this test into a separate file, (keeping <code>function_from_main</code> in <code>my_binary/src/main.rs</code>)?</p>
<p>I tried to do this but am not sure how to make <code>my_test</code> call <code>function_from_main</code> from a separate file.</p> | 0 |
The wait operation timed out. ASP | <p>I created an internal website for our company. It run smoothly for several months and then I made a major update due to user suggestion. When I run in live, it run normally. Then suddenly one of my user from japan sending me an "The Wait operation timed out." error. When I check access that certain link, It run normally for me and some other who I ask to check if they access that page. I already update the httpRuntime executionTimeout but still no luck. Is it the error come from database connection? If I increase the timeout in the database connection it will be fix the problem? </p> | 0 |
Posting a foreign key relationship in Django Rest Framework | <p>In my <strong>models</strong>, I have the following classes:</p>
<pre><code>class Topic(models.Model):
name = models.CharField(max_length=25, unique=True)
class Content(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
topic = models.ForeignKey(Topic, blank=True, null=True)
</code></pre>
<p>My <strong>serializers</strong> is like this:</p>
<pre><code>class TopicSerializer(serializers.ModelSerializer):
class Meta:
model = Topic
fields = ('name')
class ContentSerializer(serializers.ModelSerializer):
topic = TopicSerializer(read_only=True)
class Meta:
model = Content
fields = ('title', 'body', 'topic')
</code></pre>
<p>Alright, so in my <strong>urls</strong> file, I have the following pattern:</p>
<pre><code>urlpatterns = [
...
url(r'^api/topic_detail/(?P<name>[a-zA-Z0-9-]+)/content_list/$', views.topic_content_list, name='topic_content_list'),
...
]
</code></pre>
<p>Therefore, when the user goes to say <code>/api/topic_detail/sports/content_list/</code>, we get a list of all the contents that has the topic of <strong>sports</strong>. Now what I want is if we <strong>POST</strong> the following data to the above URL, then a Content object is created with the topic field related automatically to sports. </p>
<p>I am trying to do this the following way in my <strong>views</strong>:</p>
<pre><code>@api_view(['GET', 'POST'])
def topic_content_list(request, name):
try:
topic = Topic.objects.get(name=name)
except:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
contents = Content.objects.filter(topic=topic)
serializer = ContentSerializer(contents, many=True)
return Response(serializer.data)
elif request.method == 'POST':
request.data["topic"] = topic
serializer = ContentSerializer(data=request.data)
print request.data
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<p>Now lets say I go the URL <code>/api/topic_detail/sports/content_list/</code> and POST this:</p>
<pre><code>{
"title": "My blog post",
"body" : ".....",
}
</code></pre>
<p>The content object gets created and the title and body field is set properly. However, the topic field is set to null. How can I fix this? Any help is appreciated.</p>
<p>Also, please don't suggest using generic viewsets, as I am uncomfortable with so many things happening automatically.</p>
<p><strong>EDIT</strong></p>
<p>Alright, so I fixed my dumb mistake : </p>
<pre><code>class ContentSerializer(serializers.ModelSerializer):
topic = TopicSerializer(read_only=False)
class Meta:
model = Content
fields = ('title', 'body', 'topic')
</code></pre>
<p>That is, I set the read_only argument to False. However, now the post creates a new error:</p>
<pre><code>{
"topic": {
"non_field_errors": [
"Invalid data. Expected a dictionary, but got Topic."
]
}
}
</code></pre>
<p>This I am pretty sure refers to the fact that the data.website I'm sending in is not JSON, but instead just a Django model instance. How can I JSONify the single instance?</p> | 0 |
Kubernetes REST API - Create deployment | <p>I was looking at the kubernetes API endpoints listed <a href="http://kubernetes.io/docs/api-reference/v1/operations/" rel="noreferrer">here</a>. Im trying to create a deployment which can be run from the terminal using <code>kubectl ru CLUSTER-NAME IMAGE-NAME PORT</code>. However I cant seem to find any endpoint for this command in the link I posted above. I can create a node using <code>curl POST /api/v1/namespaces/{namespace}/pods</code> and then delete using the <code>curl -X DELETE http://localhost:8080/api/v1/namespaces/default/pods/node-name</code> where node name HAS to be a single node (if there are 100 nodes, each should be done individually). <strong>Is there an api endpoint for creating and deleting deployments??</strong></p> | 0 |
How do I project a point from [x,y] coordinates to LatLng in Leaflet? | <p>I'm using Leaflet 1.0.0rc3 and need to use an absolute pixel value to modify something on my map. Thus, I want to know where the user clicks in pixels, and then transform this back to <code>LatLng</code> coordinates. I tried using <code>map.unproject()</code>, which seems like the correct method (<a href="http://leafletjs.com/reference-1.0.0.html#map-unproject" rel="noreferrer">unproject() Leaflet documentation</a>). But the LatLng values that come out of that method are very different from the output of <code>e.latlng</code>. (E.g., input <code>LatLng (52, -1.7)</code> and output <code>LatLng (84.9, -177)</code>). So I must be doing something wrong.</p>
<p><b>Question: What's the proper way to project points from layer (x,y) space to LatLng space?</b></p>
<p>Here's a code snippet (fiddle: <a href="https://jsfiddle.net/ehLr8ehk/" rel="noreferrer">https://jsfiddle.net/ehLr8ehk/</a>)</p>
<pre><code>// capture clicks with the map
map.on('click', function(e) {
doStuff(e);
});
function doStuff(e) {
console.log(e.latlng);
// coordinates in tile space
var x = e.layerPoint.x;
var y = e.layerPoint.y;
console.log([x, y]);
// calculate point in xy space
var pointXY = L.point(x, y);
console.log("Point in x,y space: " + pointXY);
// convert to lat/lng space
var pointlatlng = map.unproject(pointXY);
// why doesn't this match e.latlng?
console.log("Point in lat,lng space: " + pointlatlng);
}
</code></pre> | 0 |
Type specified for TypedQuery is incompatible with query return type [class java.lang.Double] | <p>I'am trying to make a join between two entities using j2ee and hibernate.
But I get the following error:</p>
<p><code>java.lang.IllegalArgumentException: Type specified for TypedQuery is incompatible with query return type [class java.lang.Double]</code></p>
<p>This is the query that I'm trying to get work</p>
<pre><code>Query query = entityManager
.createQuery("SELECT avg(responseEnd - responseStart) FROM QualiteDeService q join q.test",QualiteDeService.class );
</code></pre>
<p>And these are the entities:</p>
<pre><code> @Entity
public class QualiteDeService {
private int id_qualite_service;
private Test test;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId_qualite_service() {
return id_qualite_service;
}
@ManyToOne
@JoinColumn(name = "id_test", referencedColumnName = "id_test", insertable = false, updatable = false)
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
}
@Entity
public class Test implements Serializable{
private int id_test;
private int note;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId_test() {
return id_test;
}
public void setId_test(int id_test) {
this.id_test = id_test;
}
}
</code></pre> | 0 |
How to disable git gpg signing | <p>I'm using git gpg signing. I want to disable it. I've set <code>.gitconfig</code></p>
<pre><code>[user]
name = NAME
email = EMAIL
signingkey = KEY
...
[commit]
gpgsign = false
</code></pre>
<p>My commits are still signing by default. </p>
<p>PS: I also disabled from Sourcetree <code>Repository/ Repository Settings/Security</code> tab. Both Sourcetree and terminal forces to use gpg. </p> | 0 |
Why can't IDEA find toDS() and toDF() functions? | <p>My code works well in spark-shell:</p>
<pre><code>scala> case class Person(name:String,age:Int)
defined class Person
scala> val person = Seq(Person("ppopo",23)).toDS()
person: org.apache.spark.sql.Dataset[Person] = [name: string, age: int]
scala> person.show()
+-----+---+
| name|age|
+-----+---+
|ppopo| 23|
+-----+---+
</code></pre>
<p>but wrong in IDEA:</p>
<p><a href="https://i.stack.imgur.com/2wDnH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2wDnH.png" alt="enter image description here"></a>
<br>
I have imported all jars in "spark-2.0.0-bin-hadoop2.7/jars/",but still can't find this function.</p> | 0 |
How to write .wav file from blob in Javascript/Node | <p>I'm trying to write a .wav file with fs.writeFile. The file is created successfully, however it's only 8-13bytes long, so obviously I'm not doing something right.</p>
<p>If the blob is already audio/wav can I write to disk or do I need to convert it to Base 64?</p>
<p>I'm pretty much at a loss here, I found another similar thread with no answer - <a href="https://stackoverflow.com/questions/34968728/creating-a-wav-file-in-node-js-with-fs-writefile">Here</a></p>
<p>Any input would be appreciated.</p>
<pre><code>routerApp.controller('audiotest', function($scope) {
$scope.saveToDisk = function(){
var nw = require('nw.gui');
var fs = require('fs');
var path = require('path');
fs.writeFileSync('test.wav', $scope.recordedInput)
};
}
</code></pre>
<p><code>console.log($scope.recordedInput)</code> returns <code>Blob {size: 294956, type: "audio/wav"}</code></p>
<p>It's not really relevant, but here's my HTML</p>
<pre><code><div class="row" ng-controller="audiotest">
<div class="row">
<button type="button" ng-click="saveToDisk()"> Write this sucker to disk </button>
</div>
<ng-audio-recorder id='audioInput' audio-model='recordedInput'>
<!-- Start controls, exposed via recorder-->
<div ng-if="recorder.isAvailable">
<button ng-click="recorder.startRecord()" type="button" ng-disabled="recorder.status.isRecording">
Start Record
</button>
<button ng-click="recorder.stopRecord()" type="button" ng-disabled="recorder.status.isRecording === false">
Stop Record
</button>
</ng-audio-recorder>
</div>
</code></pre> | 0 |
Programmatically scroll a UIScrollView to the top of a child UIView (subview) in Swift | <p>I have a few screens worth of content within my UIScrollView which only scrolls vertically.</p>
<p>I want to programmatically scroll to a view contained somewhere in it's hierarchy.</p>
<p>The UIScrollView move so that the child view is at the top of the UIScrollView (either animated or not)</p> | 0 |
git, How to push local branch into the specific remote | <p>Could you explain how to push a local branch to a specific remote branch?</p>
<pre><code>$ git branch -vv
dev 4d46c96 [origin/dev] Merge branch '1783' into dev
dev_3_feature 226b914 second commit in dev_3_feature
dev_second_feature 6b5f10f second commit in dev_2_feature
master baf5fc0 [origin/master: ahead 1] master feature
* myFeature da5cc64 second commit in dev_1_feature
test 334cf7e commiting my super changes locally
</code></pre>
<ol>
<li><p>I want my <code>DEV</code> features to be pushed into <code>origin/dev</code> and stay there as branches, how can I do that ?</p>
</li>
<li><p>What/where/how should I set up locally to push into <code>origin/dev</code> by default instead of <code>origin/master</code>?</p>
</li>
</ol> | 0 |
PHP's json extension is required to use Monolog's NormalizerFormatter | <p>I'am new to symfony. I have created symfony project using:
symfony new PhpSymfony // command.
when i run project using:
php bin/console server:run // command, app.php page is displayed in the browser (<a href="http://localhost:8000" rel="nofollow">http://localhost:8000</a>).
But if I run without using the command php bin/console server:run,
I will get an exception in the browser </p>
<p>"RuntimeException in classes.php line 5493: PHP's json extension is required to use Monolog's NormalizerFormatter"</p>
<p>I am running on <a href="http://localhost/app_dev.php" rel="nofollow">http://localhost/app_dev.php</a>
and I a using apache2 server...
How to solve this problem ?</p> | 0 |
Randomly insert NA's values in a pandas dataframe | <p>How can I randomly insert <code>np.nan</code>'s in a DataFrame ?
Let's say I want 10% null values inside my DataFrame. </p>
<p>My data looks like this : </p>
<pre><code>df = pd.DataFrame(np.random.randn(5, 3),
index=['a', 'b', 'c', 'd', 'e'],
columns=['one', 'two', 'three'])
one two three
a 0.695132 1.044791 -1.059536
b -1.075105 0.825776 1.899795
c -0.678980 0.051959 -0.691405
d -0.182928 1.455268 -1.032353
e 0.205094 0.714192 -0.938242
</code></pre>
<p>Is there an easy way to insert the null values?</p> | 0 |
What to import to use @SuppressFBWarnings? | <p>What to import to use SuppressFBWarnings?
I installed the findbugs plugin via help / install new software
When I type import edu., I can't do ctrl space to get the options.</p>
<p>Example</p>
<pre><code>try {
String t = null;
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
value="NP_ALWAYS_NULL",
justification="I know what I'm doing")
int sl = t.length();
System.out.printf( "Length is %d", sl );
} catch (Throwable e) {
...
}
</code></pre>
<p>Has error "edu cannot be resolved to a type"</p> | 0 |
How to get all values of an object in ActiveRecord in Rails? | <p>One can use <code>column_names</code> to get all the columns of a table, but what if one would like to know all the values of a particular instance in ActiveRecord.</p>
<p>For example,</p>
<pre><code>User.column_names
=> ["id", "email", "encrypted_password", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "tel", "interests", "admin_status", "created_at", "updated_at", "city_id", "profile_image_file_name", "profile_image_content_type", "profile_image_file_size", "profile_image_updated_at"]
User.first
=> #<User id: 1, email: "[email protected]", tel: "+923223333333", interests: "Hi, I'm interested in coding.", admin_status: "download", created_at: "2016-08-16 22:38:05", updated_at: "2016-08-16 22:38:05", city_id: 2, profile_image_file_name: "Screen_Shot_2016-07-02_at_4.41.32_PM.png", profile_image_content_type: "image/png", profile_image_file_size: 324372, profile_image_updated_at: "2016-08-16 22:38:04">
</code></pre>
<p>When <code>first</code> method is called, it returns key-value pairs. What I want is to have only values, is there a single method in ActiveRecord that can do this for us?</p> | 0 |
In bootstrap .pull-right for align right .pull-left for align left then What for center? | <p>In bootstrap .pull-right for align right .pull-left for align left then What for center ?</p> | 0 |
What does TensorFlow's `conv2d_transpose()` operation do? | <p>The documentation for the <code>conv2d_transpose()</code> operation does not clearly explain what it does:</p>
<blockquote>
<p>The transpose of conv2d.</p>
<p>This operation is sometimes called "deconvolution" after
<a href="http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf" rel="noreferrer">Deconvolutional Networks</a>, but is actually the transpose (gradient) of
conv2d rather than an actual deconvolution.</p>
</blockquote>
<p>I went through the paper that the doc points to, but it did not help.</p>
<p>What does this operation do and what are examples of why you would want to use it?</p> | 0 |
How to set chmod for a folder and all of its subfolders and files in PHP? | <p>I think my question explains everything. I want to use php's <strong>chmod() function</strong> to set a <strong>777 permission</strong> on a folder, its subfolders and files.</p>
<p>Any Help is appreciated. THX.</p> | 0 |
What's platformBuildVersionCode and platformBuildVersionName in Extracted Apk's | <p>Extracted an Apk using APKTool getting the <code>manifest.xml</code> like this,</p>
<pre><code><manifest xmlns:"http://schemas.android.com/apk/res/android"
android:versionCode="31"
android:versionName="3.1"
package="xxx.xxx.xxx"
platformBuildVersionCode="22"
platformBuildVersionName="5.1.1-1819727">
<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="22" />
</code></pre>
<p>Need to know what's <code>platformBuildVersionCode</code> and <code>platformBuildVersionName</code></p>
<p>Already Checked this,<a href="https://stackoverflow.com/q/32500911/5515371">What is "platformBuildVersionCode" in AndroidManifest.xml?</a></p> | 0 |
Angular 2 declaring an array of objects | <p>I have the following expression:</p>
<pre><code>public mySentences:Array<string> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
</code></pre>
<p>which is not working because my array is not of type <code>string</code> rather contains a list of objects. How I can delcare my array to contain a list of objects?</p>
<p>*without a new component which declaring the a class for sentence which seem a waste</p> | 0 |
pandas dataframe convert column type to string or categorical | <p>How do I convert a single column of a pandas dataframe to type string? In the df of housing data below I need to convert zipcode to string so that when I run linear regression, zipcode is treated as categorical and not numeric. Thanks!</p>
<pre><code>df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
bathrooms bedrooms floors sqft_living sqft_lot zipcode
722 3.25 4 2.0 4670 51836 98005
2680 0.75 2 1.0 1440 3700 98107
14554 2.50 4 2.0 3180 9603 98155
17384 1.50 2 3.0 1430 1650 98125
18754 1.00 2 1.0 1130 2640 98109
</code></pre> | 0 |
Why React event handler is not called on dispatchEvent? | <p>Consider the following input element in a React component:</p>
<pre><code><input onChange={() => console.log('onChange')} ... />
</code></pre>
<p>While testing the React component, I'm emulating user changing the input value:</p>
<pre><code>input.value = newValue;
TestUtils.Simulate.change(input);
</code></pre>
<p>This causes <code>'onChange'</code> to be logged, as expected.</p>
<p>However, when the <code>'change'</code> event is dispatched directly (I'm using jsdom):</p>
<pre><code>input.value = newValue;
input.dispatchEvent(new Event('change'));
</code></pre>
<p>the <code>onChange</code> handler is not called.</p>
<p>Why?</p>
<p>My motivation to use <code>dispatchEvent</code> rather than <code>TestUtils.Simulate</code> is because <code>TestUtils.Simulate</code> doesn't support event bubbling and my component's behavior relies on that. I wonder whether there is a way to test events without <code>TestUtils.Simulate</code>?</p> | 0 |
How to create a directory in node js using fs.mkdir? | <p>Here I am trying to create a directory using async function fs.mkdir using the below code but I am getting a error</p>
<pre><code>ERROR: No such file or directory, mkdir 'C:\tmp\test';
var fs = require("fs");
console.log("Going to create directory /tmp/test");
fs.mkdir('/tmp/test',function(err){
if (err) {
return console.error(err);
}
console.log("Directory created successfully!");
});
</code></pre>
<p>Any Help regarding this will be highly appreciated.</p> | 0 |
How to process the response data of FBSDKGraphRequest in Swift 3 | <p>I have integrated the FB latest SDK(non-swift) and log in is working fine. All I need to know how do I parse the Graph response data since its not a valid JSON</p>
<p>Working code: </p>
<pre><code> func configureFacebook()
{
login.readPermissions = ["public_profile", "email", "user_friends"];
login.delegate = self
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
print("Login buttoon clicked")
let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name,email, picture.type(large)"])
graphRequest.start(completionHandler: { (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print(result)
}
})
}
</code></pre>
<p>With output:</p>
<pre><code>Login button clicked
Optional({
"first_name" = KD;
id = 10154CXXX;
picture = {
data = {
"is_silhouette" = 0;
url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/XXXn.jpg?oh=a75a5c1b868fa63XXX146A";
};
};
})
</code></pre>
<p>So what format should I convert the above data to get values like URL or first_name etc? </p>
<p>Also I tried converting to <code>NSDictionary</code> and got error:</p>
<pre><code>func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
print("Login buttoon clicked")
let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name,email, picture.type(large)"])
graphRequest.start(completionHandler: { (connection, result, error) -> Void in
if ((error) != nil)
{
print("Error: \(error)")
}
else
{
do {
let fbResult = try JSONSerialization.jsonObject(with: result as! Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(fbResult.value(forKey: "name"))
} catch {
print(error)
}
}
})
}
</code></pre> | 0 |
HTML5 video MEDIA_ERR_DECODE occurs randomly | <p>I'm developing the project witch contains 6 audio and video elements which plays one after another.
The code order before issue is like that:</p>
<ol>
<li>preloading all media resources till "canplaythrough"</li>
<li>playing video-1</li>
<li>stoping video-1 and playing audio-1</li>
<li>stoping audio-1 and playing video-1 again.</li>
</ol>
<p>Then the video-1 is playing 2-3 seconds and stops sending the error code 3 (3 = MEDIA_ERR_DECODE - error occurred when decoding). I have tried to play the same video just by link and it is playing fine.</p>
<p>Also the problem randomly occurs on some OS in some browsers.
For example: </p>
<ul>
<li>Win10 latest Opera - occurs</li>
<li>Win10 latest Chrome - fine</li>
<li>MacOS all browsers - fine</li>
<li>Another MacOS latest Chrome - occurs in 1 of 10 cases</li>
<li>IPhone all browsers - fine</li>
<li>IPad all browsers - fine</li>
</ul>
<p><strong>UPDATE</strong> It is occuring on Win10 latest Opera only during first view or if cache is disabled. </p>
<p><strong>UPDATE 2</strong> Video Codec is H.264, Audio Codec is AAC, Framerate is 24. </p> | 0 |
TypeScript type definition for promise.reject | <p>The following code is correct in terms of the type that is returned, because <code>then</code> always return the promise array.</p>
<pre><code>Promise.resolve(['one', 'two'])
.then( arr =>
{
if( arr.indexOf('three') === -1 )
return Promise.reject( new Error('Where is three?') );
return Promise.resolve(arr);
})
.catch( err =>
{
console.log(err); // Error: where is three?
})
</code></pre>
<p>TypeScript throw error:</p>
<blockquote>
<p>The type argument for type parameter 'TResult' cannot be inferred from the usage. Consider specifying the type arguments explicitly.
Type argument candidate 'void' is not a valid type argument because it is not a supertype of candidate 'string[]'.</p>
</blockquote>
<p>But in reality, <code>then</code> never will return <code>void</code>.</p>
<p>I can explicitly specify type <code>.then<Promise<any>></code>, but it's more like a workaround, not the right solution.</p>
<p>How to write this right?</p> | 0 |
insert multiple values with tags into influxdb | <p>I'm trying to collect smartctl metrics and push them into influxdb. I'm having difficulty adding tags for values being pushed in so that the tags and values are in the right place.</p>
<p>If I do this:</p>
<pre><code>curl -POST 'http://localhost:8086/write?db=test' --data-binary 'smartctl Raw_Read_Error_Rate=19243395i,Spin_Up_Time=0i,Start_Stop_Count=149i,Reallocated_Sector_Ct=25i,Seek_Error_Rate=4735843653i,Power_On_Hours=41286i,Spin_Retry_Count=0i,Power_Cycle_Count=150i,End_to_End_Error=0i,Reported_Uncorrect=0i,Command_Timeout=12885098501i,High_Fly_Writes=0i,Airflow_Temperature_Cel=29i,G_Sense_Error_Rate=0i,Power_Off_Retract_Count=145i,Load_Cycle_Count=25668i,Temperature_Celsius=29i,Hardware_ECC_Recovered=19243395i,Current_Pending_Sector=0i,Offline_Uncorrectable=0i,UDMA_CRC_Error_Count=0i 1472412282915653274'
</code></pre>
<p>There are no tags:</p>
<pre><code>SHOW TAG KEYS FROM "smartctl" (empty result)
</code></pre>
<p>How do I add tags to that same curl command so that I get something like:</p>
<pre><code>host=foo,disk_name="Seagate Blah"
</code></pre>
<p>Adding some clarification:</p>
<p>If I use a comma (and set a value), then they are <em>all</em> tags, not fields:</p>
<pre><code>curl -POST 'http://localhost:8086/write?db=test' --data-binary 'smartctl,Raw_Read_Error_Rate=19243395i,Spin_Up_Time=0i,Start_Stop_Count=149i,Reallocated_Sector_Ct=25i,Seek_Error_Rate=4735843653i,Power_On_Hours=41286i,Spin_Retry_Count=0i,Power_Cycle_Count=150i,End_to_End_Error=0i,Reported_Uncorrect=0i,Command_Timeout=12885098501i,High_Fly_Writes=0i,Airflow_Temperature_Cel=29i,G_Sense_Error_Rate=0i,Power_Off_Retract_Count=145i,Load_Cycle_Count=25668i,Temperature_Celsius=29i,Hardware_ECC_Recovered=19243395i,Current_Pending_Sector=0i,Offline_Uncorrectable=0i,UDMA_CRC_Error_Count=0i value=0 1472412282915653274'
</code></pre>
<p>(side note: I also don't see what I would set as a value for "smartctl"?)</p>
<p>What I need is to set all of the above as a <em>field</em>, but with tags so I can determine the host they are reporting from. So I can do something like:</p>
<pre><code>select Temperature_Celsius from smartctl where host=foo
</code></pre> | 0 |
Angular 2 redirectTo with router not work | <p>I am developing my first app using angular 2 and I encountered strange problem.</p>
<p>I have my routes configuration like this:</p>
<pre><code>export const routes: RouterConfig = [
{ path: '', redirectTo: 'login' },
{ path: 'login', component: Login },
{ path: 'home', component: Home }
];
</code></pre>
<p>and when I enter localhost:3000 I am automatically redirected to my localhost:3000/login , which is my login form page. When I enter my credentials and click submit router naviagation doesn't work ( no errors in console ), but suprisingly router works when I refresh localhost:3000/login.</p>
<p>I call router this way:</p>
<pre><code>export class Login {
constructor(public router: Router, public http: Http) {
}
login(event, username, password) {
event.preventDefault();
// ...
this.router.navigate(['/home']);
}
</code></pre>
<p>}</p>
<p>What could be wrong with this routes configurations ?</p> | 0 |
Spark Equivalent of IF Then ELSE | <p>I have seen this question earlier here and I have took lessons from that. However I am not sure why I am getting an error when I feel it should work. </p>
<p>I want to create a new column in existing Spark <code>DataFrame</code> by some rules. Here is what I wrote. iris_spark is the data frame with a categorical variable iris_spark with three distinct categories. </p>
<pre><code>from pyspark.sql import functions as F
iris_spark_df = iris_spark.withColumn(
"Class",
F.when(iris_spark.iris_class == 'Iris-setosa', 0, F.when(iris_spark.iris_class == 'Iris-versicolor',1)).otherwise(2))
</code></pre>
<p>Throws the following error. </p>
<pre><code>---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-157-21818c7dc060> in <module>()
----> 1 iris_spark_df=iris_spark.withColumn("Class",F.when(iris_spark.iris_class=='Iris-setosa',0,F.when(iris_spark.iris_class=='Iris-versicolor',1)))
TypeError: when() takes exactly 2 arguments (3 given)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-157-21818c7dc060> in <module>()
----> 1 iris_spark_df=iris_spark.withColumn("Class",F.when(iris_spark.iris_class=='Iris-setosa',0,F.when(iris_spark.iris_class=='Iris-versicolor',1)))
TypeError: when() takes exactly 2 arguments (3 given)
</code></pre>
<p>Any idea why?</p> | 0 |
How to execute ansible playbook from crontab? | <p>Is it possible to execute an ansible playbook from crontab? We have a playbook that needs to run at a certain time ever day, but I know that cron doesn't like ssh. </p>
<p>Tower has a built in scheduling engine, but we are not interested in using Tower. How are other people scheduling ansible playbooks?</p> | 0 |
C# ReadLine float | <p>I try convert string to float because I using <code>Console.ReadLine()</code> for input.</p>
<p>The <code>Console.ReadLine()</code> only accept string values, but I need convert. How I can do that?</p>
<p>Thank you.</p> | 0 |
How to delete record in laravel 5.3 using ajax request? | <p>I'm trying to delete record using ajax in laravel 5.3, i know this is one of the common question and there is already lots of online solutions and tutorials available about this topic. I tried some of them but most of giving me same error <code>NetworkError: 405 Method Not Allowed</code>. I tried to do this task by different angle but i'm stuck and could not found where i'm wrong, that's why i added this question for guideline.</p>
<p>I'm trying following script for deleting the record.</p>
<p><strong>Controller.php</strong></p>
<pre><code>public function destroy($id)
{ //For Deleting Users
$Users = new UserModel;
$Users = UserModel::find($id);
$Users->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
}
</code></pre>
<p><strong>Routes.php</strong></p>
<pre><code>Route::get('/user/delete/{id}', 'UserController@destroy');
</code></pre>
<p><strong>In View</strong></p>
<pre><code><button class="deleteProduct" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >Delete Task</button>
</code></pre>
<p><strong>App.js</strong></p>
<pre><code>$(".deleteProduct").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'PUT',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
</code></pre>
<p>When i'm click on delete button it returning me error <code>NetworkError: 405 Method Not Allowed</code> in console. Without ajax same delete function is working properly. </p>
<p>Can anyone guide me where i'm wrong that i can fix the issue, i would like to appreciate if someone guide me regarding this. Thank You..</p> | 0 |
Angular2 Output/emit() not working | <p>For the life of me I cannot figure out why I cannot either emit or capture some data. The <code>toggleNavigation()</code> fires, but I'm not sure if the <code>.emit()</code> is actually working.</p>
<p>Eventually I want to collapse and expand the navigation, but for now I just want to understand how to send data from the <code>navigation.component</code> to the <code>app.component</code>.</p>
<p><a href="https://plnkr.co/edit/wdZ8fRxXPkC1ik3y5NSA" rel="nofollow">Here is a Plunker link</a></p>
<p><strong>app.component</strong></p>
<pre><code>import { Component } from '@angular/core';
import { PasNavigationComponent } from './shared/index';
@Component({
moduleId: module.id,
selector: 'pas-app',
template: `
<pas-navigation
(toggle)="toggleNavigation($event);">
</pas-navigation>
<section id="pas-wrapper">
<pas-dashboard></pas-dashboard>
</section>
`,
directives: [PasNavigationComponent]
})
export class AppComponent {
toggleNavigation(data) {
console.log('event', data);
}
}
</code></pre>
<p><strong>pas-navigation.component</strong></p>
<pre><code>import { Component, Output, EventEmitter } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'pas-navigation',
template: `
<nav>
<div class="navigation-header">
<i class="fa fa-bars" (click)="toggleNavigation()"></i>
</div>
</nav>
`
})
export class PasNavigationComponent {
@Output('toggle') navToggle = new EventEmitter();
toggleNavigation() {
this.navToggle.emit('my data to emit');
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>I added Pankaj Parkar's suggestions.</p> | 0 |
How to emit LLVM-IR from Cargo | <p>How can I get cargo to emit LLVM-IR instead of a binary for my project? I know that you can use the <code>--emit=llvm-ir</code> flag in <code>rustc</code>, but I've read some Github issues that show it's impossible to pass arbitrary compiler flags to cargo. </p>
<p>Is there any way I can get cargo to emit LLVM-IR directly?</p> | 0 |
XML what does that question mark mean | <p>I know XML documents usually start with something like:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
</code></pre>
<p>My question is regarding the <code><?</code> and <code>?></code> what do they mean on their own?
As in what does:</p>
<pre><code><?Any old text?>
</code></pre>
<p>mean in XML</p>
<p>Thanks</p> | 0 |
Handling Single Sign On with Selenium WebDriver and TestNG | <p><strong>Conditions:</strong></p>
<ul>
<li>Different base urls for each test class.</li>
<li>Same login credentials (sso) for each base url.</li>
<li>Different data sets for each test class.</li>
</ul>
<p><strong>Problem:<br></strong>
It passes <code>AMSValidation</code> but skips <code>SAPValidation</code>. It is saying <code>The FirefoxDriver cannot be used after quit() was called.</code>
But upon running the tests per class, they pass.<br><br></p>
<p><strong>Code:</strong></p>
<pre><code>public abstract class Validation {
// other variables
public static WebDriver driver = new FirefoxDriver();
public void doLogin() throws Exception {
// something
}
public void validateDocuments(String portal, String navigation,
String category, String title, String fileName) throws Exception {
// driver is used here
}
}
public class AMSValidation extends Validation {
@Parameters("baseUrl")
@BeforeTest(alwaysRun = true)
public void setUp(@Optional("https://website.com/ams/") String baseUrl)
throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);
doLogin();
}
@DataProvider
public Object[][] getDataForAMS() throws Exception {
// return test data for ams
}
@Test(dataProvider = "getDataForAMS")
public void validateAMS(String portal, String navigation, String category,
String title, String fileName) throws Exception {
validateDocuments(portal, navigation, category, title, fileName);
}
@AfterTest(alwaysRun = true)
public void tearDown() throws Exception {
driver.quit();
}
}
public class SAPValidation extends Validation {
@Parameters("baseUrl")
@BeforeTest(alwaysRun = true)
public void setUp(@Optional("https://website.com/sap/") String baseUrl)
throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);
doLogin();
}
@DataProvider
public Object[][] getDataForSAP() throws Exception {
// return test data for sap
}
@Test(dataProvider = "getDataForSAP")
public void validateSAP(String portal, String navigation, String category,
String title, String fileName) throws Exception {
validateDocuments(portal, navigation, category, title, fileName);
}
@AfterTest(alwaysRun = true)
public void tearDown() throws Exception {
driver.quit();
}
}
</code></pre>
<p><strong>testng.xml:</strong></p>
<pre><code><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Validation Suite" verbose="2">
<test name="AMS Test">
<parameter name="baseUrl" value="https://website.com/ams/" />
<classes>
<class name="com.website.tests.AMSValidation" />
</classes>
</test>
<test name="SAP Test">
<parameter name="baseUrl" value="https://website.com/sap/" />
<classes>
<class name="com.website.tests.SAPValidation" />
</classes>
</test>
</suite>
</code></pre>
<p><strong>Log:</strong></p>
<pre><code>PASSED: validateAMS("portal", "navigation", "category", "title", "filename")
===============================================
AMS Test
Tests run: 1, Failures: 0, Skips: 0
===============================================
FAILED CONFIGURATION: @BeforeTest setUp("https://website.com/sap/")
org.openqa.selenium.remote.SessionNotFoundException: The FirefoxDriver cannot be used after quit() was called.
// rest of stack trace
SKIPPED: validateSAP("portal", "navigation", "category", "title", "filename")
===============================================
SAP Test
Tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 0
===============================================
===============================================
Validation Suite
Total tests run: 2, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 0
===============================================
</code></pre> | 0 |
Bootstrap datetimepicker "dp.change" | <p>If I use this, the change function will only fire once at opening. Selecting a different date will not trigger the change function anymore. There are 2 datetimepickers in the form. The first is to set a date and the second has to autofill the same date as the first and the time minus 3 hours. </p>
<pre><code>$("#ed").on("dp.change", function (e) {
var d = new Date(e.date);
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();
var hour = d.getHours() - 3;
var min = d.getMinutes();
var setter = day + '-' + month + '-' + year + ' ' + hour + ':' + min;
$('#re').data("DateTimePicker").defaultDate(setter);
});
</code></pre> | 0 |
custom long date format in moment js | <p>Is there a way to add a custom format code to moment for long dates based on locale?</p>
<p>for example:</p>
<p><code>moment().format("L")</code> </p>
<p>is an existing format that will print the long date for the locale (including the year), but if I wanted to add my own that excluded the year like this:</p>
<p><code>moment().format("LTY")</code> that just printed the month and day in a given locale.</p>
<p>How can I do this?</p> | 0 |
Accessing firebase.storage() with AngularFire2 (Angular2 rc.5) | <p><br>
I am trying to access firebase.storage() on my project, with:</p>
<ul>
<li>"@angular": "2.0.0-rc.5"</li>
<li>"angularfire2": "^2.0.0-beta.3-pre2"</li>
<li>"firebase": "^3.3.0"</li>
</ul>
<p>I found this <a href="https://stackoverflow.com/questions/38593188/firebase-storage-and-angularfire2">solution</a>, and created my .component.ts file with:</p>
<pre><code>import { Component } from '@angular/core';
declare var firebase : any;
@Component({
template: '<img [src]="image">'
})
export class RecipesComponent {
image: string;
constructor() {
const storageRef = firebase.storage().ref().child('images/image.png');
storageRef.getDownloadURL().then(url => this.image = url);
}
}
</code></pre>
<p>and I get the following error in the browser console:</p>
<pre><code>EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in ./bstorageComponent class FBStorageComponent_Host - inline template:0:0
ORIGINAL EXCEPTION: Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().
ORIGINAL STACKTRACE:
Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().
</code></pre>
<p>but, I initialised firebase in app.module.ts with this import</p>
<pre><code>AngularFireModule.initializeApp(firebaseConfig)
</code></pre>
<p>I'm not getting what I'm missing. How can I access storage using firebase? I have no problem with accessing database with angularfire2.<br>
Thanks</p> | 0 |
List of all the geographic scope in Plotly | <p>I am trying to plot data on a map using <code>plotly.js</code>. I know that you can achieve a map of a country from:</p>
<pre><code>layout = dict(
title = '',
geo = dict(
scope='usa',
...
)
</code></pre>
<p>Do we have a list of available scopes, i.e. different regions, some where? I have tried googling it but can't seem to find it. In the example they have 'africa' as well, but how about other places?</p> | 0 |
How to add data labels to a bar chart in Bokeh? | <p>In the Bokeh guide there are examples of various bar charts that can be created. <a href="http://docs.bokeh.org/en/0.10.0/docs/user_guide/charts.html#id4" rel="noreferrer">http://docs.bokeh.org/en/0.10.0/docs/user_guide/charts.html#id4</a></p>
<p>This code will create one:</p>
<pre><code>from bokeh.charts import Bar, output_file, show
from bokeh.sampledata.autompg import autompg as df
p = Bar(df, 'cyl', values='mpg', title="Total MPG by CYL")
output_file("bar.html")
show(p)
</code></pre>
<p>My question is if it's possible to add data labels to each individual bar of the chart? I searched online but could not find a clear answer.</p> | 0 |
Terminated Spring Boot App in Eclipse - Shutdown hook not called | <p>I have a Spring Boot + Spring Data Redis/KeyValue project. I setup a Spring profile to run the application with all dependencies embedded. So at startup, I launch an embedded Redis Server. Everything works fine when I start it in Eclipse, except that I would like the Redis server to be stopped when I stop the Spring Boot application. So I setup several shutdown hooks, however they are not called when I terminate the application from Eclipse.</p>
<p>They are similar questions on SO, <strong>I created this one hoping there would be a Redis solution</strong>. Also none of these similar questions are specific to Spring Boot.</p>
<p>I tried many things:</p>
<ul>
<li>Spring Boot's <code>ExitCodeGenerator</code>; </li>
<li><code>DisposableBean</code>; </li>
<li><code>@PreDestroy</code>;</li>
<li>I tried a ShutdownHook (after @mp911de's answer)</li>
</ul>
<p>None of them are called.</p>
<p><strong>Perhaps there is a Redis option, timeout, keep alive.. something outside the box I am not aware of ?</strong>
<strong>How can I ensure that the Redis Server is stopped when my Spring Boot app is abruptly stopped</strong> ?</p>
<p>=> I saw this <a href="https://stackoverflow.com/questions/32524194/embedded-redis-for-spring-boot">Embedded Redis for spring boot</a>, but <code>@PreDestroy</code> is just not called when killing the application unexpectedly.</p>
<p>Here are some of the similar questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/12836551/shutdownhook-in-eclipse">Shutdown hook doesn't work in Eclipse</a>
<ul>
<li><a href="https://stackoverflow.com/questions/547169/how-to-get-shutdown-hook-to-execute-on-a-process-launched-from-eclipse">How to get shutdown hook to execute on a process launched from Eclipse</a></li>
<li><a href="https://stackoverflow.com/questions/515993/what-is-the-correct-way-to-add-a-shutdown-hook-for-an-eclipse-rcp-application">What is the correct way to add a Shutdown Hook for an Eclipse RCP application?</a></li>
</ul></li>
</ul>
<p>I also saw this post on eclipse.org discussing how shutdown hook is not called when stopping an application from eclipse: <a href="https://www.eclipse.org/forums/index.php/t/79985" rel="noreferrer">Graceful shutdown of Java Applications</a></p>
<hr>
<p>Here's all my relevant code:</p>
<p><strong>Component to start the <em>embedded</em> Redis server at startup (With my attempts to stop it too!!):</strong></p>
<pre><code>@Component
public class EmbeddedRedis implements ExitCodeGenerator, DisposableBean{
@Value("${spring.redis.port}")
private int redisPort;
private RedisServer redisServer;
@PostConstruct
public void startRedis() throws IOException {
redisServer = new RedisServer(redisPort);
redisServer.stop();
redisServer.start();
}
@PreDestroy
public void stopRedis() {
redisServer.stop();
}
@Override
public int getExitCode() {
redisServer.stop();
return 0;
}
@Override
public void destroy() throws Exception {
redisServer.stop();
}
}
</code></pre>
<p><strong>application.properties:</strong></p>
<pre><code>spring.redis.port=6379
</code></pre>
<p><strong>Spring Boot App:</strong></p>
<pre><code>@SpringBootApplication
@EnableRedisRepositories
public class Launcher {
public static void main(String[] args){
new SpringApplicationBuilder() //
.sources(Launcher.class)//
.run(args);
}
@Bean
public RedisTemplate<String, Model> redisTemplate() {
RedisTemplate<String, Model> redisTemplate = new RedisTemplate<String, Model>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName("localhost");
return jedisConnectionFactory;
}
}
</code></pre>
<p><strong>Redis server (~ embedded) running:</strong></p>
<pre><code>$ ps -aef | grep redis
... /var/folders/qg/../T/1472402658070-0/redis-server-2.8.19.app *:6379
</code></pre>
<p><strong>The embedded Redis maven dependency:</strong></p>
<pre><code><dependency>
<groupId>com.github.kstyrc</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.6</version>
</dependency>
</code></pre> | 0 |
Cannot get maven project.version property in a Spring application with @Value | <p>How to get the maven project.version property in a Spring Boot application with a @Value annotation?</p> | 0 |
React-Bootstrap Full screen Modal Dialog | <p>I am currently attempting to make the Modal component included with react-bootstrap to appear full screen.</p>
<p>I can see from the documentation that the individual components of the Dialog (Modal, Header, Footer, Body) accept custom classes through "bsClass", however once rendered the height is being restricted by another div with the class "modal-content", but cannot see a way of passing a custom class to this.</p>
<p>Is it possible to do this, or is there another way of achieving the same effect without manually changing the class once the dialog has rendered?</p> | 0 |
Jackson Annotations: Difference Between JsonIgnoreProperties(ignoreUnknown=true) and JsonInclude(Include.NON_EMPTY) | <p>I'm curious is there a difference between Jackson annotations @JsonIgnoreProperties(ignoreUnknown=true) and @JsonInclude(Include.NON_EMPTY) at the class level? Is one just a newer version of the other? Thanks!</p>
<p>The <a href="http://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonIgnoreProperties.html" rel="noreferrer">jackson docs</a> state that: </p>
<blockquote>
<p>ignoreUnknown Property that defines whether it is ok to just ignore
any unrecognized properties during deserialization.</p>
</blockquote>
<p>Is that the same as just an empty property?</p> | 0 |
Return reference to struct in Go-lang | <p>I am having some thought issues with the following code</p>
<pre><code>package main
import (
"fmt"
)
type Company struct {
Name string
Workers []worker
}
type worker struct {
Name string
Other []int
}
func (cmp *Company) NewWorker(name string) worker {
wrk := worker{Name: name}
cmp.Workers = append(cmp.Workers, wrk)
return wrk
}
func main() {
cmp := Company{}
cmp.Name = "Acme"
wrk := cmp.NewWorker("Bugs")
for i := 1; i <= 10; i++ {
wrk.Other = append(wrk.Other, i)
}
fmt.Println(wrk)
fmt.Println(cmp)
}
</code></pre>
<p><a href="https://play.golang.org/p/Bja7u148mg" rel="noreferrer">https://play.golang.org/p/Bja7u148mg</a></p>
<p>As you can see the code is not returning the worker I am creating but a copy of it. How can I get it to return the actual worker? I have tried some variations of * and & on the different workers but I end up with either:</p>
<pre><code>invalid indirect of worker literal (type worker)
</code></pre>
<p>or: </p>
<pre><code>cannot use wrk (type worker) as type *worker in return argument
</code></pre>
<p>Any ideas on how to do this?</p> | 0 |
Woocommerce product stars how to show in shop page? | <p>I want to show the number of reviews and average star ratings of a product in Shop/ Product Archive pages. Currently this is shown in single product pages. But I want it in all-products page. How can I achieve that? Please help. Thank you very much.</p> | 0 |
Insert new records only into SQL Table Using VBA | <p>I have an Excel workbook with the below code -</p>
<pre class="lang-vb prettyprint-override"><code>Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sFirstName, sLastName As String
With Sheets("Sheet1")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;" & _
"Data Source=server1;" & _
"Initial Catalog=table1;" & _
"User ID=user1; Password=pass1"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sFirstName = .Cells(iRowNo, 1)
sLastName = .Cells(iRowNo, 2)
'Generate and execute sql statement
' to import the excel rows to SQL Server table
conn.Execute "Insert into dbo.Customers (FirstName, LastName) " & _
"values ('" & sFirstName & "', '" & sLastName & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers imported."
conn.Close
Set conn = Nothing
End With
End Sub
</code></pre>
<p>This opens up a connection to my database and inputs the values from the stated columns.</p>
<p>The primary key is an incremental key on the database. The problem is it will copy ALL values.</p>
<p>I'd like to add new rows of data into the Excel Sheet and only insert those rows that don't already exist.</p>
<p>I've tried different methods ('merge', 'if exist', if not exist', etc.) but I can't get it right.</p>
<p>The solution has to be through VBA. Setting up a link using SSMS is not an option.</p>
<p>I understand that it may be possible to use temporary tables and then trigger a procedure which performs the merge but I want to look into that as a last resort. Haven't read up on it yet (making my way through my MS SQL bible book) but I'm hoping it won't be necessary.</p>
<p>---Update from @Kannan's answer---</p>
<p>New portion of VBA -</p>
<pre class="lang-vb prettyprint-override"><code>conn.Execute "IF EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _
"THEN UPDATE dbo.customers SET WHERE Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' " & _
"ELSE INSERT INTO dbo.Customers (FirstName, LastName) " & _
"VALUES ('" & sFirstName & "', '" & sLastName & "')"
</code></pre>
<p>This returns error 'Incorrect syntax near the keyword 'THEN'.</p> | 0 |
Meaning of "params" in @RequestMapping annotation? | <p>I am aware of @RequestMapping annotation which is used in Spring MVC based application.</p>
<p>I came across this piece of code:</p>
<pre><code>@RequestMapping(method = POST, params = {"someParam"})
</code></pre>
<p>I understood the <code>method</code>. However I don't know what <code>params</code> means? Before this I never had seen anything which passed params to this annotation.</p>
<p>Can anyone help in understanding this?</p> | 0 |
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.login | <p>I am using sqlite database and I declare the model as this:</p>
<pre><code>class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(80), unique=True)
password = db.Column(db.String(64))
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return self.id
# Required for administrative interface
def __unicode__(self):
return self.username
</code></pre>
<p>And I have add a Model instance like this:</p>
<pre><code>admin = admin.Admin(app, 'Example: Auth', index_view=MyAdminIndexView(), base_template='my_master.html')
admin.add_view(MyModelView(User, db.session))
db.drop_all()
db.create_all()
if db.session.query(User).filter_by(login='passport').count() <= 1:
user = User(login = 'passport', password = 'password')
db.session.add(user)
db.session.commit()
</code></pre>
<p>However, if I comment the db.drop_all(), it will occur an error which is:</p>
<pre><code>sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.login [SQL: 'INSERT INTO users (login, password) VALUES (?, ?)'] [parameters: ('passport', 'password')]
</code></pre>
<p>And if do not comment the db.drop_all(), everything is fun. Because there are other tables on this database, I do not want to drop all the tables when I run it. Are there any other solutions to fix that?</p>
<p>Thanks a lot. </p> | 0 |
In Android 7 (API level 24) my app is not allowed to mute phone (set ringer mode to silent) | <p>I have an app that mutes the phone by using AudioManager and setting ringer mode to silent with this code:</p>
<pre><code>AudioManager audioManager =
(AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
try {
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT)
} catch (Exception e) {
e.printStackTrace();
}
</code></pre>
<p>This works with Android 6, but now with Android 7, I get the following error:</p>
<pre><code>System.err: java.lang.SecurityException: Not allowed to change Do Not Disturb state
System.err: at android.os.Parcel.readException(Parcel.java:1683)
System.err: at android.os.Parcel.readException(Parcel.java:1636)
System.err: at android.media.IAudioService$Stub$Proxy.setRingerModeExternal(IAudioService.java:962)
System.err: at android.media.AudioManager.setRingerMode(AudioManager.java:1022)
System.err: at controllers.SearchResultController.mutePhone(SearchResultController.java:185)
</code></pre>
<p>Are there any new permissions I need to ask for to make this work?</p>
<p>I looked through the Android permissions list, but couldn't find any that seemed relevant.</p> | 0 |
"CSV file does not exist" for a filename with embedded quotes | <p>I am currently learning Pandas for data analysis and having some issues reading a csv file in Atom editor. </p>
<p>When I am running the following code:</p>
<pre><code>import pandas as pd
df = pd.read_csv("FBI-CRIME11.csv")
print(df.head())
</code></pre>
<p>I get an error message, which ends with </p>
<blockquote>
<p>OSError: File b'FBI-CRIME11.csv' does not exist</p>
</blockquote>
<p>Here is the directory to the file: /Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv".</p>
<p>When i try to run it this way:</p>
<pre><code>df = pd.read_csv(Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv")
</code></pre>
<p>I get another error:</p>
<blockquote>
<p>NameError: name 'Users' is not defined</p>
</blockquote>
<p>I have also put this directory into the "Project Home" field in the editor settings, though I am not quite sure if it makes any difference.</p>
<p>I bet there is an easy way to get it to work. I would really appreciate your help! </p> | 0 |
Custom brace highlighting in Visual Studio Code | <p>Is it possible to customize the brace highlighting in Visual Studio Code? It seems just about everything else is customizable through user and workspace settings, as well as textmate themes. Regardless of the syntax highlighting you employ, the braces always have the same light gray outline/rectangle around them. I don't see an existing user/workspace setting or a textmate scope that addresses this specific feature.</p>
<p>Ultimately I'd like to have a solid color highlight of matching braces, similar to what you would get with the default dark theme in Visual Studio 2013 and 2015.</p> | 0 |
Elastic Search (COUNT*) with group by and where condition | <p>Dear Elastic Serach users,</p>
<p>I am newbie in ElasticSearch.</p>
<p>I am confused for how to convert the following sql command into elasticSearch DSL query ? Can anyone help to assist me. </p>
<pre><code>SELECT ip, count(*) as c FROM elastic WHERE date
BETWEEN '2016-08-20 00:00:00' and '2016-08-22 13:41:09'
AND service='http' AND destination='10.17.102.1' GROUP BY ip ORDER BY c DESC;
</code></pre>
<p>THank YOu</p> | 0 |
Convert Uint8Array into hex string equivalent in node.js | <p>I am using node.js v4.5. Suppose I have this Uint8Array variable.</p>
<pre><code>var uint8 = new Uint8Array(4);
uint8[0] = 0x1f;
uint8[1] = 0x2f;
uint8[2] = 0x3f;
uint8[3] = 0x4f;
</code></pre>
<p>This array can be of any length but let's assume the length is 4. </p>
<p>I would like to have a function that that converts <code>uint8</code> into the hex string equivalent. </p>
<pre><code>var hex_string = convertUint8_to_hexStr(uint8);
//hex_string becomes "1f2f3f4f"
</code></pre> | 0 |
Nodemon Doesn't Restart in Windows Docker Environment | <p>My goal is to set up a Docker container that automatically restarts a NodeJS server when file changes are detected from the host machine.</p>
<p>I have chosen nodemon to watch the files for changes.</p>
<p>On Linux and Mac environments, nodemon and docker are working flawlessly.</p>
<p>However, when I am in a <strong>Windows environment</strong>, nodemon doesn't restart the server.</p>
<p>The files are updated on the host machine, and are linked using the <code>volumes</code> parameter in my docker-compose.yml file. </p>
<p>I can see the files have changed when I run <code>docker exec <container-name> cat /path/to/fileChanged.js</code>. This way I know the files are being linked correctly and have been modified in the container.</p>
<p><strong>Is there any reason why nodemon doesn't restart the server for Windows?</strong> </p> | 0 |
How to remove previous versions of .NET Core from Linux (CentOS 7.1) | <p>I would like to install the current version Core 1.0. Currently the RC2 version is installed. <a href="https://www.microsoft.com/net/core#centos" rel="noreferrer">The instruction on the official website are</a>:</p>
<blockquote>
<p>Before you start, please remove any previous versions of .NET Core
from your system.</p>
</blockquote>
<p>But I don't know how and I can't find nothing from Microsoft like for example <a href="https://docs.asp.net/en/latest/migration/rc2-to-rtm.html" rel="noreferrer">here</a>.</p>
<p>I found this <a href="https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0/scripts/obtain/uninstall/dotnet-uninstall-pkgs.sh" rel="noreferrer">script</a>... but my Linux skills are not great and I won't make it worst.</p> | 0 |
What is the difference between systemd's 'oneshot' and 'simple' service types? | <p>What is the difference between <code>systemd</code> service <code>Type</code> <code>oneshot</code> and <code>simple</code>?
This <a href="https://jason.the-graham.com/2013/03/06/how-to-use-systemd-timers/" rel="noreferrer" title="link">link</a> states to use <code>simple</code> instead of <code>oneshot</code> for timers. I am not able to understand it correctly.</p> | 0 |
IntelliJ IDEA 16 add maven dependencies to classpath | <p>I am new to IntelliJ and using 2016.2 version. Previously I was using Eclipse. I am trying to set up a simple maven spring test project, however I can't figure out what is wrong.</p>
<p><em>Note:</em> I know what the exception means, and I know the solution using Eclipse</p>
<p><em>Note 2:</em> I tried on a clean Idea installation</p>
<p>As per my understanding, idea will include maven dependencies automatically (correct me if i'm wrong)</p>
<p><em>edit 1:</em> <strong>Solution</strong></p>
<ol>
<li>Project -> Right Click -> Add Framework Support -> Check Spring / Spring MVC</li>
<li>add <code><packaging>war</packaging></code></li>
<li>Re-import maven dependencies</li>
</ol>
<p><strong>What I tried to do</strong></p>
<ol>
<li>Re-import maven dependencies </li>
<li>Close IntelliJ and remove all *.iml files and all .idea folders</li>
</ol>
<p><strong>Exception</strong></p>
<pre><code>java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
</code></pre>
<p>web.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>sample2</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sample2</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
<p>sample2-servlet.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.test"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
</code></pre>
<p>pom.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sa</groupId>
<artifactId>sample2</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>3.2.17.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
</code></pre> | 0 |
Attempt to invoke virtual method in Resources res = getResources(); | <p>I am trying to change the background color of an activity using a handler, but I am getting an error "Attempt to invoke virtual method".</p>
<p>Here is my code</p>
<pre><code>public class MainActivity extends AppCompatActivity {
private EditText editTextUser, editTextPass;
private RelativeLayout relativeLayoutMain;
private Random random = new Random();
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayoutMain = (RelativeLayout) findViewById(R.id.relativeLayoutMain);
Button btnSignIn = (Button) findViewById(R.id.buttonSignIn);
btnSignIn.setEnabled(false);
handler.postDelayed(runner, 2000);
Button buttonSignUp = (Button) findViewById(R.id.buttonSignUp);
buttonSignUp.setText("Not registered? CLICK HERE");
editTextUser = (EditText) findViewById(R.id.editTextUser);
editTextPass = (EditText) findViewById(R.id.editTextPassword);
if (editTextUser.getText().toString() != null && editTextPass.getText().toString() != null) {
btnSignIn.setEnabled(true);
}
}
android.content.res.Resources res = getResources();
int[] clrItems = res.getIntArray(R.array.color_background);
List<int[]> arrayOfColor = new ArrayList<int[]>();
public List<int[]> getArrayOfColor() {
arrayOfColor.add(clrItems);
return arrayOfColor;
}
Runnable runner = new Runnable() {
@Override
public void run() {
Log.e("run: ", "call");
Bitmap bitmap = Bitmap.createBitmap(612, 612, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
final int clr = 0xFF424242;
final Paint paint = new Paint();
final Rect destRect = new Rect((612-bitmap.getWidth())/2,
24,
(612)-(612-bitmap.getWidth())/2,
612-24);
final RectF rectF = new RectF(destRect);
final Rect srcRect = new Rect(0, 0, bitmap.getWidth(), 612);
final float roundPx = 612;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(clr);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, srcRect, destRect, paint);
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[]{0xFF616261, 0xFF131313});
gd.setCornerRadius(0f);
relativeLayoutMain.setBackground(gd);
handler.postDelayed(runner, 4000);
}
};
public void login(View view) {
intent = new Intent(this, HomeActivity.class);
startActivity(intent);
}
public void register(View view) {
intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
}
</code></pre>
<p>And here is my logcat.</p>
<pre><code> 08-31 16:29:47.122 13152-13152/com.example.salimshivani.student E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.salimshivani.student, PID: 13152
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.salimshivani.student/com.example.salimshivani.student.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3132)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:92)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at com.example.salimshivani.student.MainActivity.<init>(MainActivity.java:241)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1096)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code></pre>
<p>Please help me where i am wrong to move the backgroundColor constantly of the activity.</p>
<p>Thanks in advance</p> | 0 |
Tensorflow TypeError: Fetch argument None has invalid type <type 'NoneType'>? | <p>I'm building a RNN loosely based on <a href="https://www.tensorflow.org/versions/r0.10/tutorials/recurrent/index.html" rel="noreferrer" title="tutorial">the TensorFlow tutorial</a>.</p>
<p>The relevant parts of my model are as follows:</p>
<pre><code>input_sequence = tf.placeholder(tf.float32, [BATCH_SIZE, TIME_STEPS, PIXEL_COUNT + AUX_INPUTS])
output_actual = tf.placeholder(tf.float32, [BATCH_SIZE, OUTPUT_SIZE])
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(CELL_SIZE, state_is_tuple=False)
stacked_lstm = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * CELL_LAYERS, state_is_tuple=False)
initial_state = state = stacked_lstm.zero_state(BATCH_SIZE, tf.float32)
outputs = []
with tf.variable_scope("LSTM"):
for step in xrange(TIME_STEPS):
if step > 0:
tf.get_variable_scope().reuse_variables()
cell_output, state = stacked_lstm(input_sequence[:, step, :], state)
outputs.append(cell_output)
final_state = state
</code></pre>
<p>And the feeding:</p>
<pre><code>cross_entropy = tf.reduce_mean(-tf.reduce_sum(output_actual * tf.log(prediction), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(output_actual, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
numpy_state = initial_state.eval()
for i in xrange(1, ITERATIONS):
batch = DI.next_batch()
print i, type(batch[0]), np.array(batch[1]).shape, numpy_state.shape
if i % LOG_STEP == 0:
train_accuracy = accuracy.eval(feed_dict={
initial_state: numpy_state,
input_sequence: batch[0],
output_actual: batch[1]
})
print "Iteration " + str(i) + " Training Accuracy " + str(train_accuracy)
numpy_state, train_step = sess.run([final_state, train_step], feed_dict={
initial_state: numpy_state,
input_sequence: batch[0],
output_actual: batch[1]
})
</code></pre>
<p>When I run this, I get the following error: </p>
<pre><code>Traceback (most recent call last):
File "/home/agupta/Documents/Projects/Image-Recognition-with-LSTM/RNN/feature_tracking/model.py", line 109, in <module>
output_actual: batch[1]
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 698, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 838, in _run
fetch_handler = _FetchHandler(self._graph, fetches)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 355, in __init__
self._fetch_mapper = _FetchMapper.for_fetch(fetches)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 181, in for_fetch
return _ListFetchMapper(fetch)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 288, in __init__
self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 178, in for_fetch
(fetch, type(fetch)))
TypeError: Fetch argument None has invalid type <type 'NoneType'>
</code></pre>
<p>Perhaps the weirdest part is that this error gets thrown the <strong>second</strong> iteration, and the first works completely fine. I'm ripping my hair trying to fix this, so any help would be greatly appreciated.</p> | 0 |
SQL How to compare data in two tables and get the results that are different between two tables | <p>There are 2 tables. Table a and b. A contains msisdn, firstname, secondname, lastname, regdate(registration data). Table b also has the same fields. I want to compare these two tables, the msisdn's, firstname and lastname fields. If msisdn X in table A has firstname as jim and lastname as halpert, and the same msisdn X has firstname as michael and secondname as scott in table B, i need to get these kinds of msisdn's as my query result. the one's with same msisdn in both tables and different names. if either of these names(first or last) mismatches, that should be shown as result.</p>
<p>I'm sorry if i did not explain the scenario accurately. I hope someone understands and answers this.</p>
<p>thanks :) </p> | 0 |
Format a number to have commas (1000000 -> 1,000,000) | <p>In Bigquery: How do we format a number that will be part of the resultset to have it formatted with commas: like 1000000 to 1,000,000 ?</p> | 0 |
Terraform: How to run remote-exec more than once? | <p>I have noticed that terraform will only run "file", "remote-exec" or "local-exec" on resources once. Once a resource is provisioned if the commands in a "remote-exec" are changed or a file from the provisioner "file" is changed then terraform will not make any changes to the instance. So how to I get terraform to run provisioner "file", "remote-exec" or "local-exec" everytime I run a terraform apply?</p>
<p><strong>For more details:</strong></p>
<p>Often I have had a resource provisioned partially due to an error from "remote-exec" causes terraform to stop (mostly due to me entering in the wrong commands while I'm writing my script). Running terraform again after this will cause the resource previously created to be destroyed and force terraform to create a new resource from scratch. This is also the only way I can run "remote-exec" twice on a resource... by creating it over from scratch. </p>
<p>This is really a drawback to terraform as opposed to ansible, which can do the same exact job as terraform except that it is totally idempotent. When using Ansible with tasks such as "ec2", "shell" and "copy" I can achieve the same tasks as terraform only each of those tasks will be idempotent. Ansible will automatically recognise when it doesn't need to make changes, where it does and because of this it can pick up where a failed ansible-playbook left off without destroying everything and starting from scratch. Terraform lacks this feature.</p>
<p>For reference here is a simple terraform resource block for an ec2 instance that uses both "remote-exec" and "file" provisioners:</p>
<pre><code>resource "aws_instance" "test" {
count = ${var.amt}
ami = "ami-2d39803a"
instance_type = "t2.micro"
key_name = "ansible_aws"
tags {
name = "test${count.index}"
}
#creates ssh connection to consul servers
connection {
user = "ubuntu"
private_key="${file("/home/ubuntu/.ssh/id_rsa")}"
agent = true
timeout = "3m"
}
provisioner "remote-exec" {
inline = [<<EOF
sudo apt-get update
sudo apt-get install curl unzip
echo hi
EOF
]
}
#copying a file over
provisioner "file" {
source = "scripts/test.txt"
destination = "/path/to/file/test.txt"
}
}
</code></pre> | 0 |
How to aggregate two PostgreSQL columns to an array separated by brackets | <p>I would like to concatenate two columns using a group-by query resulting in an array separed with brackets. I know this question is related to <a href="https://stackoverflow.com/questions/43870/how-to-concatenate-strings-of-a-string-field-in-a-postgresql-group-by-query">this</a> question, but as usual my use-case is a little different.</p>
<p>A simple example (also as <a href="http://sqlfiddle.com/#!15/e6ce0/28" rel="noreferrer"><strong>SQL Fiddle</strong></a>).
Currently my query returns the following:</p>
<pre><code>ID X Y
3 0.5 2.71
3 1.0 2.50
3 1.5 2.33
6 0.5 2.73
6 1.5 2.77
</code></pre>
<p>But where I would like concatenate/aggregate the <code>X</code>/<code>Y</code> columns to get the following:</p>
<pre><code>ID XY
3 [[0.5,2.71],[1.0,2.50],[1.5,2.33]]
6 [[0.5,2.73],[1.5,2.77]]
</code></pre>
<p>Currently I've tried to concatenate the columns into one as follows:</p>
<pre><code>SELECT "ID",concat_ws(', ',"X", "Y") as XY FROM Table1;
</code></pre>
<p>Which returns:</p>
<pre><code>ID xy
3 0.5, 2.71
3 1, 2.50
3 1.5, 2.33
6 0.5, 2.73
</code></pre>
<p>And used <code>array_agg()</code>:</p>
<pre><code>SELECT "ID",array_to_string(array_agg("X"),',') AS XY
FROM Table1
GROUP BY "ID";
</code></pre>
<p>Resulting in:</p>
<pre><code>ID xy
3 0.5,1,1.5
6 0.5
</code></pre>
<p>I feel I'm getting closer, but a helping hand would be really appreciated.</p> | 0 |
done is not a function error in passport js | <p>I'm using passportjs for the authentication and session. I get the ussername from mysql and the input field from client side but when the <code>done</code> is called on verification, I get <code>done is not a function</code>.</p>
<p>The server.js :</p>
<pre><code> var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var cookieParser = require('cookie-parser');
// app.use(app.router);
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(express.static(__dirname+"/staticFolder"));
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'127.0.0.1',
user:'root',
password:'sdf',
database:'abc'
});
connection.connect(function(err){
if(err){
throw err;
}
});
passport.serializeUser(function(user,done){
console.log("serializeUser" + user);
done(null,user.body.username);
})
passport.deserializeUser(function(id, done) {
done(null, user);
});
passport.use(new LocalStrategy({
passReqToCallback : true
},function(username, password, done) {
connection.query("select * from employeedetails where empid = "+username.body.username,function(err,user,w){
if(err)
{
console.log(err+"fml $$$$$$$$$$");
return done(err);
}
if(username.body.password == user[0].password){
console.log(user[0].empid+" login");
return done(null,user[0].empid);
}
else{
return done(null,false,{message: 'Incorrect password'});
console.log(user[0].empid+" fml");
}
});
}));
app.get('/',function(request,response){
response.sendFile(__dirname+"/staticFolder/view/");
})
app.post('/saveEmployeeDetails',function(request,response){
response.end();
})
app.get('/login',function(request,response){ //the file sent when /login is requested
response.sendFile(__dirname+"/staticFolder/view/login.html");
})
app.post('/loginCheck',passport.authenticate('local', {
successRedirect : '/',
failureRedirect : '/login',
failureFlash : true //
}),
function(req, res) {
console.log("hello");
res.send("valid");
res.redirect('/');
});
</code></pre> | 0 |
MyBatis - No constructor found | <p>I have a problem with MyBatis mapping.
I have a domain class like this:</p>
<pre><code>public class MyClass
{
private Long id;
private Date create;
private String content;
MyClass (Long id, Date create, String content)
{
this.id = id;
this.create = create;
this.content = content;
}
//getters and setters
</code></pre>
<p>A mapper class with a method like this:</p>
<pre><code> @Select("SELECT * FROM MyTable WHERE id=#{id}")
MyClass getMyClass (@Param("id") Long id);
</code></pre>
<p>In the database the three columns are of type Number, Timestamp and Clob and have the same name as in the class fields.</p>
<p>When I use this method I get a:
<em>ExecutorException: No constructor found in [MyClass; matching [java.math.BigDecimal, java.sql.Timestamp, oracle.jdbc.OracleClob]</em></p>
<p>But <strong>if I remove the constructor from Myclass, then there is no problem at all</strong>. I would like to have the constructor, how can I fix it?
I tried adding the @Results annotation in the mapper like so, but it didn't make any difference:</p>
<pre><code> @Results(value = {
@Result(column = "id", property = "id", javaType = Long.class),
@Result(column = "create", property = "create", javaType = Date.class),
@Result(column = "content", property = "content", javaType = String.class)
})
</code></pre> | 0 |
Encrypt connection string and other configuration settings in ASP.Net Core | <p>I am wondering how to encrypt configuration settings, especially connection string in ASP.Net Core app.</p>
<p>The configuration files are in json.</p> | 0 |
Spring Boot: get command line argument within @Bean annotated method | <p>I'm building a Spring Boot application and need to read command line argument within method annotated with @Bean. See sample code:</p>
<pre><code>@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public SomeService getSomeService() throws IOException {
return new SomeService(commandLineArgument);
}
}
</code></pre>
<p>How can I solve my issue?</p> | 0 |
replace select dropdown arrow with fa-icon | <p>I am trying to replace a select dropdown arrow with a fa-icon (chevron-circle-down) but I can only find that the background can be replaced with an image in the css file.I can add the icon over the select,but it won't be clickable.Any help how I use font icon in select dropdown list ?</p> | 0 |
Get the value of Bootstrap.modal | <p>I have this Bootstrap modal:</p>
<pre><code><div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title" id="exampleModalLabel">Input parameters</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="recipient-name" class="form-control-label">Base URL to fill id with your data (optional):</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label for="message-text" class="form-control-label">Max #pics per cluster:</label>
<input type="text" class="form-control" id="message-text">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">
Close
</button>
<button id="paramsOkay" type="button" class="btn btn-primary">
Okay
</button>
</div>
</div>
</div>
</div>
</code></pre>
<p>and I am doing this:</p>
<pre><code>$('#exampleModal').on('click','#paramsOkay', function (e) {
console.log($('#recipient-name').text());
console.log(e);
});
</code></pre>
<p>which will fire when the "Okay" button is clicked, but the first <code>console.log()</code> is empty, and there I would expect to get user's input! The second console will log the event, but I don't really now how to extract the user's input from that...</p>
<p>How to get the value the user inputed, after the "Okay" value is clicked?</p> | 0 |
How to change field types for existing index using Elasticsearch Mapping API | <p>I am using <code>ELK</code> and have the following document structure</p>
<pre><code> {
"_index": "prod1-db.log-*",
"_type": "db.log",
"_id": "AVadEaq7",
"_score": null,
"_source": {
"message": "2016-07-08T12:52:42.026+0000 I NETWORK [conn4928242] end connection 192.168.170.62:47530 (31 connections now open)",
"@version": "1",
"@timestamp": "2016-08-18T09:50:54.247Z",
"type": "log",
"input_type": "log",
"count": 1,
"beat": {
"hostname": "prod1",
"name": "prod1"
},
"offset": 1421607236,
"source": "/var/log/db/db.log",
"fields": null,
"host": "prod1",
"tags": [
"beats_input_codec_plain_applied"
]
},
"fields": {
"@timestamp": [
1471513854247
]
},
"sort": [
1471513854247
]
}
</code></pre>
<p>I want to change the <code>message</code> field to <code>not_analyzed</code>. I am wondering how to use <code>Elasticsedarch Mapping API</code> to achieve that? For example, how to use <code>PUT Mapping API</code> to add a new type to the existing index?</p>
<p>I am using <code>Kibana 4.5</code> and <code>Elasticsearch 2.3</code>.</p>
<p>UPDATE
Tried the following <code>template.json</code> in <code>logstash</code>,</p>
<pre><code> 1 {
2 "template": "logstash-*",
3 "mappings": {
4 "_default_": {
5 "properties": {
6 "message" : {
7 "type" : "string",
8 "index" : "not_analyzed"
9 }
10 }
11 }
12 }
13 }
</code></pre>
<p>got the following errors when starting <code>logstash</code>,</p>
<pre><code>logstash_1 | {:timestamp=>"2016-08-24T11:00:26.097000+0000", :message=>"Invalid setting for elasticsearch output plugin:\n\n output {\n elasticsearch {\n # This setting must be a path\n # File does not exist or cannot be opened /home/dw/docker-elk/logstash/core_mapping_template.json\n template => \"/home/dw/docker-elk/logstash/core_mapping_template.json\"\n ...\n }\n }", :level=>:error}
logstash_1 | {:timestamp=>"2016-08-24T11:00:26.153000+0000", :message=>"Pipeline aborted due to error", :exception=>#<LogStash::ConfigurationError: Something is wrong with your configuration.>, :backtrace=>["/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/config/mixin.rb:134:in `config_init'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/outputs/base.rb:63:in `initialize'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/output_delegator.rb:74:in `register'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:181:in `start_workers'", "org/jruby/RubyArray.java:1613:in `each'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:181:in `start_workers'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:136:in `run'", "/opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/agent.rb:473:in `start_pipeline'"], :level=>:error}
logstash_1 | {:timestamp=>"2016-08-24T11:00:29.168000+0000", :message=>"stopping pipeline", :id=>"main"}
</code></pre> | 0 |
SID and HSID cookies : what are they uses? | <p>From google :</p>
<blockquote>
<p>For example, we use cookies called ‘SID’ and ‘HSID’ which contain
digitally signed and encrypted records of a user’s Google account ID
and most recent sign-in time. The combination of these two cookies
allows us to block many types of attack, such as attempts to steal the
content of forms that you complete on web pages.</p>
</blockquote>
<p>I don't really understand the last sentence . How keeping the account ID protects from attacks ? Isn't it the other way round ? Like the user should have to sign in every time for the service to be 100% secure ?</p> | 0 |
Matplotlib graph expand the x axis | <p>I have the following <a href="https://i.stack.imgur.com/cFAL2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cFAL2.png" alt="graph"></a>.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x_values = [2**6,2**7,2**8,2**9,2**10,2**12]
y_values_ST = [7.3,15,29,58,117,468]
y_values_S3 = [2.3,4.6,9.1,19,39,156]
xticks=['2^6','2^7','2^8','2^9','2^10','2^12']
plt.plot(x_values, y_values_ST,'-gv')
plt.plot(x_values, y_values_S3,'-r+')
plt.legend(['ST','S^3'], loc='upper left')
plt.xticks(x_values,xticks)
fig.suptitle('Encrypted Query Size Overhead')
plt.xlabel('Query size')
plt.ylabel('Size in KB')
plt.grid()
fig.savefig('token_size_plot.pdf')
plt.show()
</code></pre>
<p>1)How i can delete the last gap as shown after 2^12?
2)How i can spread more the values in the x axis such that the first two values are not overlapped?</p> | 0 |
How to form protobuf resource part of http request body and test it through dhc client or postman for restful services | <p>I have created a .proto message and I'm exposing a rest service which looks like this </p>
<pre><code>@Path("/test")
public interface test{
@POST
@Produces("application/x-protobuf")
@Consumes("application/x-protobuf")
public Response getProperties(TestRequest testrq);
}
</code></pre>
<p>Now TestRequest being the Java generated file of .protobuf how do i pass it in request body ?</p>
<p>this will be be the .proto file format </p>
<pre><code>message TestRequest
{
string id = 1;
string name = 2;
enum TestType
{
Test=1
}
TestType testType = 3;
}
</code></pre> | 0 |
Swift coding in visual studio code | <p>Is there any possibility to write swift code and preview in Visual Studio Code (windows coding app)? I see in the guide for swift coding that requires ios system but i have just windows for the moment. </p>
<p>Can I code swift in Windows?</p> | 0 |
Add an item to a list dependent on a conditional in ansible | <p>I would like to add an item to a list in ansible dependent on some condition being met.</p>
<p>This doesn't work:</p>
<pre><code> some_dictionary:
app:
- something
- something else
- something conditional # only want this item when some_condition == True
when: some_condition
</code></pre>
<p>I am not sure of the correct way to do this. Can I create a new task to add to the <code>app</code> value in the <code>some_dictionary</code> somehow?</p> | 0 |
How to set error on EditText using DataBinding Framework MVVM | <p>I am using Android Data Binding framework I have suppose an EditText for login form with username as below</p>
<pre><code><EditText
android:id="@+id/etext_uname"
style="@style/login_edittext"
android:hint="@string/hint_username"
android:inputType="textEmailAddress" />
</code></pre>
<p>I have defined LoginViewModel also but I need help how to set Error in edittext when user type wrong email address in some event let say inside </p>
<pre><code>public void afterTextChanged(@NonNull final Editable editable)
</code></pre>
<p>Because as far as I know in Traditional Android approach we can do this programmatically via et.setError() method but I don't want to create edittext object via Activity or Fragment.</p> | 0 |
Spring-Boot RestClientTest not correctly auto-configuring MockRestServiceServer due to unbound RestTemplate | <p>EDIT: This question is specifically pertaining to the @RestClientTest annotation introduced in spring-boot 1.4.0 which is intended to replace the factory method.</p>
<h2>Problem:</h2>
<p>According to the <a href="http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-client" rel="noreferrer">documentation</a> the @RestClientTest should correctly configure a MockRestServiceServer to use when testing a REST client. However when running a test I am getting an IllegalStateException saying the MockServerRestTemplateCustomizer has not been bound to a RestTemplate.</p>
<p>Its worth noting that I'm using Gson for deserialization and not Jackson, hence the exclude.</p>
<p>Does anyone know how to correctly use this new annotation? I haven't found any examples that require more configuration then when I have already.</p>
<p>Configuration:</p>
<pre><code>@SpringBootConfiguration
@ComponentScan
@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class})
public class ClientConfiguration {
...
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder()
.rootUri(rootUri)
.basicAuthorization(username, password);
}
}
</code></pre>
<p>Client:</p>
<pre><code>@Service
public class ComponentsClientImpl implements ComponentsClient {
private RestTemplate restTemplate;
@Autowired
public ComponentsClientImpl(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
public ResponseDTO getComponentDetails(RequestDTO requestDTO) {
HttpEntity<RequestDTO> entity = new HttpEntity<>(requestDTO);
ResponseEntity<ResponseDTO> response =
restTemplate.postForEntity("/api", entity, ResponseDTO.class);
return response.getBody();
}
}
</code></pre>
<p>Test</p>
<pre><code>@RunWith(SpringRunner.class)
@RestClientTest(ComponentsClientImpl.class)
public class ComponentsClientTest {
@Autowired
private ComponentsClient client;
@Autowired
private MockRestServiceServer server;
@Test
public void getComponentDetailsWhenResultIsSuccessShouldReturnComponentDetails() throws Exception {
server.expect(requestTo("/api"))
.andRespond(withSuccess(getResponseJson(), APPLICATION_JSON));
ResponseDTO response = client.getComponentDetails(requestDto);
ResponseDTO expected = responseFromJson(getResponseJson());
assertThat(response, is(expectedResponse));
}
}
</code></pre>
<p>And the Exception:</p>
<pre><code>java.lang.IllegalStateException: Unable to use auto-configured MockRestServiceServer since MockServerRestTemplateCustomizer has not been bound to a RestTemplate
</code></pre>
<h2>Answer:</h2>
<p>As per the answer below there is no need to declare a RestTemplateBuilder bean into the context as it is already provided by the spring-boot auto-configuration.</p>
<p>If the project is a spring-boot application (it has @SpringBootApplication annotation) this will work as intended. In the above case however the project was a client-library and thus had no main application. </p>
<p>In order to ensure the RestTemplateBuilder was injected correctly in the main application context (the bean having been removed) the component scan needs a CUSTOM filter (the one used by @SpringBootApplication)</p>
<pre><code>@ComponentScan(excludeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class)
})
</code></pre> | 0 |
typings vs @types NPM scope | <p>In some cases <code>typings</code> is used for handling TypeScript definitions (e.g. <a href="https://github.com/angular/angular2-seed">angular/angular2-seed</a>).</p>
<p>In other cases scoped NPM <code>@types</code> packages are used with no <code>typings</code> involved (e.g. <a href="https://github.com/AngularClass/angular2-webpack-starter">AngularClass/angular2-webpack-starter</a>).</p>
<p>What are the practical differences between them? Does one of them offer benefits for TypeScript development that the other doesn't?</p> | 0 |
request.body vs request.params vs request.query | <p>I have a client side JS file that has:</p>
<blockquote>
<p>agent = require('superagent'); request = agent.get(url);</p>
</blockquote>
<p>Then I have something like</p>
<pre><code>request.get(url)
//or
request.post(url)
request.end( function( err, results ) {
resultCallback( err, results, callback );
} );
</code></pre>
<p>On the backend Node side I have
<code>request.body</code> and <code>request.params</code> and some has <code>request.query</code></p>
<p>What are the difference between the body, params and query?</p> | 0 |
Attempt to invoke virtual method '...TextView.setText(java.lang.CharSequence)' on a null object reference | <p>I'm an German and new in android, so sorry for bad english or silly mistakes...
I want to edit the text of my TextView.
Eventhough I've read the problems with my error message, I didn't find a solution...
I'm receiving the error message in the title due to the following code.
Why?</p>
<p>Java Code (just the OnCreate Method where it shows up the error)</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView t= (TextView)findViewById(R.id.startofweek);
t.setText("05.09.2016");
setContentView( R.layout.activities);
}
</code></pre>
<p>FXML (just the Part of the TextView, originally it is placed in a FrameView)</p>
<pre><code><TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/example"
android:layout_gravity="left|top"
android:layout_marginTop="20dp"
android:layout_marginLeft="70dp"
android:background="#00ffffff"
android:textStyle="bold"
android:textColor="#ffffff"
android:textSize="20dp" />
</code></pre>
<p>Would be happy if someone has a solution for me :)</p> | 0 |
getLastRowNum not returning correct number of rows | <p>I am having a small conundrum in using the getLastRowNum(). I am trying to get the number of rows with data from an Excel sheet. Supposing I have 3 rows, it should return in a print out statement stating 3 rows. My issue now is no matter how many rows I populate, it is returning me a certain fixed number. The following is excerpt of the code:</p>
<pre><code>FileInputStream fis = new FileInputStream("C:\\Test Data\\Login.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("Login");
System.out.println("No. of rows : " + sheet.getLastRowNum());
</code></pre>
<p>My Excel Sheet consist of the following</p>
<p><a href="https://i.stack.imgur.com/7v1tm.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/7v1tm.jpg" alt="enter image description here"></a></p>
<p>From the attached image, I should be getting row count of 4, but I am getting 6 instead. </p>
<p>Any advice is deeply appreciated. Thank you in advance.</p> | 0 |
Serve JSON Data from Github Pages | <p>I have a repository on github which contains a number of csv, json, yml data files in the root directory of the repository.</p>
<p>How do I get it to serve those files using Github Pages?</p>
<p>So for eg: when I go to <code>http://username.github.io/reponame/</code> followed by</p>
<ul>
<li><code>/posts</code> - serve the contents of the <strong>posts.json</strong> file</li>
<li><code>/users</code> - serve the contents of the <strong>users.json</strong> file</li>
<li><code>/comments</code> - serve the contents of the <strong>comments.json</strong> file</li>
<li><code>/posts.csv</code> - serve the contents of the <strong>posts.csv</strong> file</li>
</ul> | 0 |
How to loop through object in JSX using React.js | <p>So I have a React.js component, and I want to loop through an object I import to add HTML options to it. Here is what I tried, which is both ugly and does not work:</p>
<pre><code>import React from 'react';
import AccountTypes from '../data/AccountType';
const AccountTypeSelect = (props) => {
return (
<select id={props.id} className = {props.classString} style={props.styleObject}>
<option value="nothingSelected" defaultValue>--Select--</option>
{
$.each(AccountTypes, function(index) {
<option val={this.id}>this.name</option>
})
}
</select>
);
};
export default AccountTypeSelect;
</code></pre>
<p>I received this error in the console from the above code:</p>
<p>invariant.js?4599:38 - Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {id, name, enabled, additionalInfo}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of <code>AccountTypeSelect</code>.</p>
<p>Do I really need to convert each object into an array or wrap it with createFragment to use it? What is the best practice for this case?</p> | 0 |
How to plot data from multiple files in a loop | <p>I have a more than 1000 <code>.csv</code> files (data_1.csv......data1000.csv), each containing X and Y values!</p>
<pre><code>x1 y1 x2 y2
5.0 60 5.5 500
6.0 70 6.5 600
7.0 80 7.5 700
8.0 90 8.5 800
9.0 100 9.5 900
</code></pre>
<hr />
<p>I have made a subplot program in python which can give two plots (plot1 - X1vsY1, Plot2 - X2vsY2) at a time using one file.</p>
<p>I need help in looping all the files, (open a file, read it, plot it, pick another file, open it, read it, plot it, ... until all the files in a folder get plotted)</p>
<p>I have the following code:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df1=pd.read_csv("data_csv",header=1,sep=',')
fig = plt.figure()
plt.subplot(2, 1, 1)
plt.plot(df1.iloc[:,[1]],df1.iloc[:,[2]])
plt.subplot(2, 1, 2)
plt.plot(df1.iloc[:,[3]],df1.iloc[:,[4]])
plt.show()
</code></pre>
<p>How can this be accomplished more efficiently?</p> | 0 |
How do I only allow letters when asking for a name in python? | <p>I am new to coding in python and need to know how to only allow the user to enter letters when inputting a name. So if they input a number or nothing at all, I want the code to say something like "Please only use letters, try again".</p>
<p>Cheers Chris</p> | 0 |
Matrix and vector multiplication operation in R | <p>I feel matrix operations in R is very confusing: we are mixing row and column vectors.</p>
<ul>
<li><p>Here we define <code>x1</code> as a vector, (I assume R default vector is a column vector? but it does not show it is arranged in that way.)</p></li>
<li><p>Then we define <code>x2</code> is a transpose of <code>x1</code>, which the display also seems strange for me.</p></li>
<li><p>Finally, if we define <code>x3</code> as a matrix the display seems better.</p></li>
</ul>
<p>Now, my question is that, <code>x1</code> and <code>x2</code> are completely different things (one is transpose of another), but we have the same results here. </p>
<p>Any explanations? may be I should not mix vector and matrix operations together?</p>
<pre><code>x1 = c(1:3)
x2 = t(x1)
x3 = matrix(c(1:3), ncol = 1)
x1
[1] 1 2 3
x2
[,1] [,2] [,3]
[1,] 1 2 3
x3
[,1]
[1,] 1
[2,] 2
[3,] 3
x3 %*% x1
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
x3 %*% x2
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
</code></pre> | 0 |
Reacts this.props.children in vue.js component | <p>React has something like <code>this.props.children</code>: <a href="https://facebook.github.io/react/tips/children-props-type.html" rel="noreferrer">https://facebook.github.io/react/tips/children-props-type.html</a></p>
<p>Does Vue.js have also some similar to access the child-elements?</p> | 0 |
Angular save file as csv result in Failed- network error Only on Chrome | <p>I'm using the following code to save file as csv.</p>
<pre><code>$scope.saveCSVFile = function (result)
{
var a = document.createElement('a');
a.href = 'data:application/csv;charset=utf-8,' + encodeURIComponent(result.data);
a.target = '_blank';
a.download = $scope.getFileNameFromHttpResponse(result);
document.body.appendChild(a);
a.click();
$scope.isReportInProgress = false;
};
</code></pre>
<p>The file is working on most of the cases but for some reason when the file is larger than 10MB i get "Failed - Network Error".</p>
<p>It happens only on chrome.</p>
<p>I tried to search the web for this issue and couldn't find anything relevant.</p>
<p>Can you think of an idea why does it happens? or maybe use a different save file method that will work on chrome/firefox/IE instead of my function?</p> | 0 |
Interpreting Golang Error codes | <p>So most examples of go error handling I see just pass any errors back up the stack. At some point these need interpreting and this is what I am trying to do.
Here's a snippet of my attempt:</p>
<pre><code> resp, err := http.Get(string(url))
defer out_count.Dec()
if err != nil {
switch err {
case http.ErrBodyReadAfterClose:
fmt.Println("Read after close error")
case http.ErrMissingFile:
fmt.Println("Missing File")
{some more cases here}
case io.EOF:
fmt.Println("EOF error found")
default:
fmt.Printf("Error type is %T\n", err)
panic(err)
}
return
</code></pre>
<p>This isn't working though for my current case(edited to remove url}:</p>
<pre><code>ERROR: Failed to crawl "http://{removed URL}"
Error type is *url.Error
panic: Get http://{removed url}: EOF
goroutine 658 [running]:
runtime.panic(0x201868, 0x106352c0)
/usr/lib/go/src/pkg/runtime/panic.c:279 +0x1a0
github.com/cbehopkins/grab/grab.crawl(0x10606210, 0x27, 0x105184b0, 0x105184e0, 0x10500460)
</code></pre>
<p>I can't figure out a way to get the switch statement to catch this error since the text of the error changes every time and has no explicit value I can catch against. (as the URL changes all the time). Now maybe I could do some sort of regex match in the case statement or sub-slice the error string, but that feels like a very bad way to solve this problem.</p>
<p>Any suggestions? There must be an idiomatic way to catch errors such as this surely?</p> | 0 |
Appending one data frame into another | <p>I want to bring three data frames into a single one .All data frames have a single column .</p>
<pre><code>org_city_id=p.DataFrame(training_data['origcity_id'])
pol_city_id=p.DataFrame(training_data['pol_city_id'])
pod_city_id=p.DataFrame(training_data['pod_city_id'])
</code></pre>
<p>All have 100 records in it so my goal is to bring them into a single data frame which will then contain 300 records .My below code is not working </p>
<pre><code>org_city_id.append([pol_city_id,pod_city_id])
</code></pre>
<p>the total number of records in org_city_id is still 100 .</p>
<p>Can someone please suggest .</p> | 0 |
Jenkins pipeline : templating a file with variables | <p>I have a pipeline job that treats a template file (e.g. an XML file) and needs to replace some variables from the file with job parameters before using the rendered file, but I can't seem to find anything clean to do that, for now I'm just using shell script and sed to replace each variable one by one.</p>
<p>Here is an example XML template file :</p>
<pre><code><?xml version='1.0' encoding='UTF-8'?>
<rootNode>
<properties>
<property1>${property1}</property1>
<property2>${property2}</property2>
<property3>${property3}</property3>
</properties>
</rootNode>
</code></pre>
<p>I would like the "variables" in my template file to be replaced with my job parameters <code>$property1</code>, <code>$property2</code> and <code>$property3</code>.
Here is what I'm doing today :</p>
<pre><code>sh "sed -i 's/@property1@/${property1}/' '${templateFile}'" +
"sed -i 's/@property2@/${property2}/' '${templateFile}'" +
"sed -i 's/@property3@/${property3}/' '${templateFile}'"
</code></pre>
<p>... but I find it quite ugly... is there anything in Jenkins for templating files such as what <a href="http://jinja.pocoo.org/docs/dev/" rel="noreferrer">Jinja2</a> (or any templating framework) would do ?</p> | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.