Id int64 34.6M 60.5M | Title stringlengths 15 150 | Body stringlengths 33 36.7k | Tags stringlengths 3 112 | CreationDate stringdate 2016-01-01 00:21:59 2020-02-29 17:55:56 | Y stringclasses 3 values |
|---|---|---|---|---|---|
34,646,833 | Any Javascript Expert: Who can add multiple IDs in This Script to Check If CSS does not match redirect Page | Javascript expert,
i have the below script
$('#copyright, #credit, #doom a').each(function () {
if ($(this).css('font-size') != '15px') {
document.location.href = "http://www.example.com";
}
});
It check all these IDs Css properties for font-size 15px if not equal then the page will be redirect to example.com
Now here what i want, I want to know how can i add **multiple css property** in that script not only the font-size but i also want to include position:relative;height:auto;background:#000; to check it..
it may be look like this: (this is only example not the working script )
$('#copyright, #credit, #doom a').each(function () {
if
position:relative;height:auto;background:#000
{ do nothing }
else
{
document.location.href = "http://www.example.com";
}
});
| <javascript><jquery><html><redirect><url-redirection> | 2016-01-07 03:20:24 | LQ_EDIT |
34,646,992 | How to work with xml and java (android) | <p>How do I make something in xml, and change the value of it in Java?</p>
<p>ex:</p>
<pre><code><TextView
android:text="Hello World!"
android:textSize="50dp"
android:layout_marginTop="27dp"
android:id="@+id/textView"
android:editable="true"
android:enabled="true" />
</code></pre>
<p>Now how do I edit the text from being "Hello World" to something else in Java?</p>
| <java><android><xml> | 2016-01-07 03:41:04 | LQ_CLOSE |
34,647,303 | Spring RestTemplate with paginated API | <p>Our REST APIs are returning results in Pages. Here is an example of one Controller</p>
<pre><code>@RequestMapping(value = "/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
@ResponseStatus(HttpStatus.OK)
public Page<MyObject> findAll(Pageable pageable) {
...
}
</code></pre>
<p>Is there an easy way to consume that API with RestTemplate?</p>
<p>if we do</p>
<pre><code>ParameterizedTypeReference<Page<MyObject>> responseType = new ParameterizedTypeReference<Page<MyObject>>() { };
ResponseEntity<Page<MyObject>> result = restTemplate.exchange(url, HttpMethod.GET, null/*httpEntity*/, responseType);
List<MyObject> searchResult = result.getBody().getContent();
</code></pre>
<p>it throws an exception </p>
<pre><code>org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of org.springframework.data.domain.Page,
problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information at [Source: java.io.PushbackInputStream@3be1e1f2; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.springframework.data.domain.Page, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
</code></pre>
<p>Thank you in advance</p>
| <spring><rest><resttemplate> | 2016-01-07 04:18:45 | HQ |
34,647,536 | how to get audio.duration value by a function | <p>Im my audio player I need to get the duration of my audio track. I need a function that gets src of the audio and returns its duration. Here is what I am trying to do but does not work:</p>
<pre><code>function getDuration(src){
var audio = new Audio();
audio.src = "./audio/2.mp3";
var due;
return getVal(audio);
}
function getVal(audio){
$(audio).on("loadedmetadata", function(){
var val = audio.duration;
console.log(">>>" + val);
return val;
});
}
</code></pre>
<p>I tried to split into two functions but it does not work. It would be great if it was as on working function.</p>
<p>Any idea?</p>
| <javascript><jquery><audio><html5-audio> | 2016-01-07 04:44:14 | HQ |
34,647,589 | how can i add values with the same "account title" and display this in my gridview using vb.net / aspx | [This is the source grid view with a sql datasource named trialbalance][1]
[1]: http://i.stack.imgur.com/bA2jO.jpg
[Output gridview should look like this...][2]
[2]: http://i.stack.imgur.com/M9Qmd.jpg | <asp.net><sql-server><vb.net> | 2016-01-07 04:49:45 | LQ_EDIT |
34,647,831 | Best resources for learning Machine Learning for beginners | <p>I am keen in learning machining learning. I know programming, just want to know some useful sites which will help in understanding the concepts of machine learning with simple examples.</p>
| <machine-learning> | 2016-01-07 05:16:50 | LQ_CLOSE |
34,647,874 | Java servets response.getMethod() not working | Hello I am trying to create a simple servlet as follows
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Form extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter p=res.getWriter();
p.println("<html><head></head><body bgcolor=\"red\">The request came from"+req.getMethod()+"</body></html>");
}
}
I am taking the request from an html file coded as follows.
{html}
{body}
{form action="http://localhost:8080/Form" method="GET"}
First Name: {input type="text" name="name"}
{br }
{input type="submit" value="Enter"}
{/form}
{/body}
{/html}
| <java><servlet-3.0><get-method> | 2016-01-07 05:21:09 | LQ_EDIT |
34,648,255 | Using clang-format in CLion | <p>I'd like to format my code using clang-format in CLion. I've gone through the settings and haven't found any setting that would allow me to run an external command to transform code. How are such things normally done in CLion?</p>
| <c++><clang><clion><clang-format> | 2016-01-07 05:56:16 | HQ |
34,648,336 | how to get IP address and pc name of all pc's shared with me in a array using matlab script | <p>the array should be looks like below.<br>
<strong>PC NAME IP ADDRESS</strong></p>
<pre><code> SYSTEM1 192.168.12.45
SYSTEM2 192.168.12.4
SYSTEM3 192.168.12.5
SYSTEM4 192.168.12.15
</code></pre>
| <matlab> | 2016-01-07 06:02:37 | LQ_CLOSE |
34,648,411 | instead of passing whole array to intent pass only onClicked value | i am trying to pass only the onClicked value in the below code instead of passing the whole array to intent. Is it possible??
here, i am sending whole array as in "i.putExtra("rank", rank)", is there some other way.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rank = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
country = new String[] { "China", "India", "United States",
"Indonesia", "Brazil", "Pakistan", "Nigeria", "Bangladesh",
"Russia", "Japan" };
population = new String[] { "2,000,000,000", "1,500,000,000",
"123,123,123", "123,123,123", "123,123,123", "123,123,123",
"123,123,123", "123,123,123", "123,123,123", "123,123,123" };
flag = new int[] { R.drawable.china, R.drawable.india,
R.drawable.unitedstates, R.drawable.indonesia,
R.drawable.brazil, R.drawable.pakistan, R.drawable.nigeria,
R.drawable.bangladesh, R.drawable.russia, R.drawable.japan };
listView = (ListView) findViewById(R.id.listview);
listViewAdapter = new ListViewAdapter(this, rank, country, population, flag);
listView.setAdapter(listViewAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent i = new Intent(MainActivity.this, SingleItemView.class);
i.putExtra("rank", rank);
i.putExtra("country", country);
i.putExtra("population", population);
i.putExtra("flag", flag);
i.putExtra("position", position);
startActivity(i);
}
});
' | <android><arrays><android-intent> | 2016-01-07 06:09:01 | LQ_EDIT |
34,648,673 | Custom Serchbar in ios | Hello i am using `UISerchbar` in `tableview` but is there any easy way to create custom `searchbar` in `tableview headerview`? | <ios><objective-c><uitableview><uisearchbar> | 2016-01-07 06:30:23 | LQ_EDIT |
34,648,921 | Pair up row in Sql | I have a Players table with 3 columns id, name, wins(number of win matches). To make a Swiss pairing, I sort this table order by wins. How can I return a table with 4 columns id1, name1, id2, name2 such that each row of new table is the pair of rows in Players table. I can do it in python language, but I want to know that there is any query in SQL which could implement this task?
For example
Player table
Id Name Wins
1 A 3
2 B 1
3 C 4
4 D 0
I want to return
Id Name Id Name
3 C 1 A
2 A 4 D
Thanks | <sql><postgresql> | 2016-01-07 06:47:25 | LQ_EDIT |
34,649,300 | Cookies vs. Web storage | <p>I am creating a project where I want to save the last level that the user reached so they can continue where they leave off the next time. I am wondering whether I should use cookies or web storage, and the reasons for using each one. For example, does one affect performance, is one commonly enabled/disabled, is one not supported by modern browsers, etc.</p>
<p>I am also interested in knowing whether there are other options besides these two that I could use instead, and what the advantages and disadvantages to those are.</p>
<p>Thank you!</p>
| <javascript><html> | 2016-01-07 07:13:00 | LQ_CLOSE |
34,649,311 | Will it cause any issue if I use multiple Facebook Pixel in one page? | <p>I would like to include both my Facebook Pixel id and customer's Facebook Pixel id in one page, so both of us can have some insight about users, and customer can also create ADs for the page if he or she wants to.</p>
<p>I already test tracking and it seems to work fine. However I do receive warnings from Pixel SDK about "Multiple different pixels were detected on this page".</p>
<p>Since I cannot find any information about this scenario, I would like to know whether it is okay to do so ?</p>
<p>Thanks</p>
| <facebook> | 2016-01-07 07:13:32 | HQ |
34,649,969 | How to find the features names of the coefficients using scikit linear regression? | <pre><code>#training the model
model_1_features = ['sqft_living', 'bathrooms', 'bedrooms', 'lat', 'long']
model_2_features = model_1_features + ['bed_bath_rooms']
model_3_features = model_2_features + ['bedrooms_squared', 'log_sqft_living', 'lat_plus_long']
model_1 = linear_model.LinearRegression()
model_1.fit(train_data[model_1_features], train_data['price'])
model_2 = linear_model.LinearRegression()
model_2.fit(train_data[model_2_features], train_data['price'])
model_3 = linear_model.LinearRegression()
model_3.fit(train_data[model_3_features], train_data['price'])
# extracting the coef
print model_1.coef_
print model_2.coef_
print model_3.coef_
</code></pre>
<p>If I change the order of the features, the coef are still printed in the same order, hence I would like to know the mapping of the feature with the coeff</p>
| <python><machine-learning><scikit-learn><linear-regression> | 2016-01-07 07:58:04 | HQ |
34,650,410 | Angular 2 [hidden] does not seem to be working? | <p>My component is defined this way:</p>
<pre><code>import { Component } from 'angular2/core'
@Component({
selector: 'sidebar',
templateUrl: 'js/app/views/sidebar.html',
})
export class SidebarComponent {
public sections: boolean[] = [
true,
false,
false,
false,
false,
false,
false,
false
];
}
</code></pre>
<p>The <code>sidebar.html</code> template:</p>
<pre><code><h3 class="proofTitle">...</h3>
<p [hidden]="sections[0]">
...
</p>
<p [hidden]="sections[1]">
...
</p>
...
<p [hidden]="sections[7]">
...
</p>
</code></pre>
<p>Seems pretty straight forward, but for some reason, it's showing all of the sections... what am I missing?</p>
| <angular> | 2016-01-07 08:28:14 | HQ |
34,650,738 | How can I change the format of this input? | <p>I have this script in js:</p>
<p><strong>CODE HTML:</strong></p>
<pre><code><input class="required-input" type="text" name="date_of_birth" id="date_of_birth" placeholder="MM/DD/YYYY">
</code></pre>
<p><strong>CODE JS:</strong></p>
<pre><code>$('.required-input').each(function() {
$(this).on('input keyup keypress blur change', function() {
const dob= /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/;
var regex;
if ($(this).attr("id") == "date_of_birth")
{
regex = dob;
}
//SOME CODE JS:
});
});
</code></pre>
<p>I want these things:</p>
<p>1.To be the next format <code>23/09/1992</code></p>
<p>2.You can not write more characters than necessary.</p>
<p>3.You can not write letters, only numbers</p>
<p>How to change this variable <code>(dob)</code> to be good?</p>
<p>Thanks in advance!</p>
| <javascript><regex><validation> | 2016-01-07 08:48:14 | LQ_CLOSE |
34,651,379 | how to make py.test --cov skip virtualenv directory | <p>Should I care how my tests cover the external libraries I'm using in my project ? </p>
<p>The py.test --cov displays how all files are covered, including ones in my virtualenv directory. How can I make the output show only the coverage of the modules I've written ?</p>
| <python-2.7><virtualenv><pytest><test-coverage> | 2016-01-07 09:21:37 | HQ |
34,652,311 | When OutofMemory error occurs in Android? | I am parsing JSON String fetched from web.(Around 40,000 records in a single chunk). I call AsyncTask recursively(40k records retrieved in a single call) until i fetched all the records from server(Total records 2 lac).
In first two calls app responds smooth and around 80k records fetched from server, but in third call OutOfMemory error occurs. I searched the web and got to know that this error occurs when heap size overflowed.
String response = "";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost("http://URL");
httpPost.setEntity(new StringEntity(strings[0]));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Error occurs on the below line.
response = EntityUtils.toString(httpEntity);
My code works fine for first 2 calls, then why it throws OutOfMemory in next call? Why first two calls works fine with the same size of data?
I know their are many questions regarding OutOfMemory error. But, I want to know that how android allocates the heap size? Does it depends on the free memory of device? Does the size of heap reduced by android when the size of app data increase or it remains same?
Please ignore if you found this question worthless. :) | <android> | 2016-01-07 10:05:40 | LQ_EDIT |
34,652,998 | How does angular "$uibModalInstance.close(data)" works? | <p>The official documentation of AngularJS does not contain any thing that describes how <code>$uibModalInstance.close</code> works, in the following code fragment, <code>scope.close</code> is a method used to close the modal window and pass an object to the caller controller</p>
<pre class="lang-js prettyprint-override"><code>var app = angular.module('myApp');
app.controller('ModalController', ['$uibModalInstance', modalControllerFn]);
function modalControllerFn($uibModalInstance) {
var scope = this;
// some data object
scope.data = {key1: "value1", key2: "value2"};
scope.close = function() {
$uibModalInstance.close(scope.data);
}
}
</code></pre>
<h3>Question (1)</h3>
<p>Does passing anything belonging to the modal scope using <code>$uibModalInstance.close</code> (non-literal value, i.e: <code>scope.x</code>) prevents angular garbage collection from destroying the entire modal scope? is this a scenario for causing memory leaks?</p>
<h3>Question (2)</h3>
<p>How does angular <code>$uibModalInstance.close(data)</code> exactly works?</p>
| <angularjs><angular-ui-modal> | 2016-01-07 10:37:29 | HQ |
34,653,770 | Why does Ubuntu have old versions of nodejs and npm in their apt-get package manager? | <p>When I install nodejs and npm with apt-get </p>
<pre><code>sudo apt-get update
sudo apt-get install nodejs modejs-legacy npm
I have the versions
</code></pre>
<p>I get the following versions</p>
<pre><code>npm -v
1.3.10
nodejs -v
v0.10.25
</code></pre>
<p>I know how to update these manually, but why does the apt-get package manager have old versions of these packages?</p>
| <node.js><ubuntu><npm><apt-get> | 2016-01-07 11:16:51 | HQ |
34,653,869 | Android studio - share data between activity | <p>Im making an app/game in android studio. And I have over 10 activities in my app/game and I have f.eks "int HP" I want to share with the others activities. </p>
| <java><android><android-studio> | 2016-01-07 11:22:03 | LQ_CLOSE |
34,654,869 | What is the meaning of this -> symbol in Java? | <p>I am not able to understand how to make this code should work in Java7</p>
<pre><code>RetryPolicy retryPolicy = new RetryPolicy()
.retryWhen((ClientResponse response) -> response.getStatus() != 200)
.withDelay(1, TimeUnit.SECONDS)
.withMaxRetries(3);
Recurrent.get(() -> webResource.post(ClientResponse.class, input), retryPolicy);
</code></pre>
<p>What exactly this <code>-></code> symbol mean in java?</p>
<p>If Java7 not support it how to change it so it should work.</p>
| <java> | 2016-01-07 12:13:51 | LQ_CLOSE |
34,655,321 | MySQL: How to ORDER BY on multiple columns? | <p>I have the the following columns on a table</p>
<pre><code>type | date_1 | date_2 | date_3
</code></pre>
<p>type column is </p>
<pre><code>ENUM('1','2','3')
</code></pre>
<p>I need to order by on date columns but use appropriate columns based on <code>type</code> column on every row.</p>
| <mysql><sql> | 2016-01-07 12:37:23 | LQ_CLOSE |
34,655,695 | Redux - how to keep the reducer state during hot reload | <p>I use <em>React</em> + <em>Redux</em> + <em>Webpack</em> + <em>WebpackDevserver</em>. Once the hot loader is launched all my reducers are reseted to the initial state. </p>
<p>Can I keep somehow my reducers in the actual state?</p>
<p>My Webpack config contains:</p>
<pre><code>entry: [
"./index.jsx"
],
output: {
filename: "./bundle.js"
},
module: {
loaders: [
{
test: /\.js|\.jsx$/,
exclude: /node_modules/,
loaders: ["react-hot","babel-loader"],
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
</code></pre>
<p>My reducers stats with:</p>
<pre><code>const initialState = {
...
}
export default function config(state = initialState, action) { ...
</code></pre>
<p>I start my Webpack Dev-Server just by:</p>
<pre><code>"start": "webpack-dev-server",
</code></pre>
| <webpack><redux><webpack-dev-server><react-hot-loader> | 2016-01-07 12:54:56 | HQ |
34,656,168 | Stay signed in option with cookie-session in express | <p>I would like to have a "Stay signed in" option such as the one provided by Gmail.
This way, the user <strong>can decide</strong> if they want to keep the session open upon opening a new browser session after previously closing it.</p>
<p>Looking into the github issues I saw <a href="https://github.com/expressjs/cookie-session/issues/21#issuecomment-52973886">the cookie-session component doesn't provide a way to upate the <code>maxAge</code> property dynamilly</a>. </p>
<p>I'm wondering then if there's any way at all to achieve the "Stay signed in" feature with the <code>cookie-session</code> component.</p>
<p>It seems to me a basic feature for a component which is being downloaded <a href="https://www.npmjs.com/package/cookie-session">80K times a month</a>.</p>
| <node.js><express><cookie-session> | 2016-01-07 13:18:55 | HQ |
34,656,814 | how to implement this function | now have `fmapT` and `traverse` :
fmapT ::
Traversable t =>
(a -> b)
-> t a
-> t b
traverse ::
Applicative f =>
(a -> f b)
-> t a
-> f (t b)
how can i implement the function `over` with `traverse` as an argument to `fmapT`:
over ::
((a -> Identity b) -> s -> Identity t)
-> (a -> b)
-> s
-> t
over = error "undefined" | <haskell><traversal><functor><haskell-lens> | 2016-01-07 13:50:12 | LQ_EDIT |
34,657,545 | sql server login failed for user client computer | I am using sql sever r2 dadabase as a remote server having mixed mode sql authentication...
when run my c# program from client computer to access database with following connection string:-
"Data Source=192.168.1.101\SQLEXPRESS,1433;Initial Catalog=Login; Integrated Security=true;Connection timeout=30; User ID=sa;Password=23456"
and facing an error :-
Login failed for user 'VAIO\Guest'.
'VAIO' is remote PC. | <c#><sql-server> | 2016-01-07 14:24:39 | LQ_EDIT |
34,657,942 | How can I change the format of the phone number in my example? | I have this sample:
[link][1]
[1]: http://jsfiddle.net/Xxk3F/2864/
**CODE HTML:**
<input class="" type="text" name="primary_phone" id="primary_phone" maxlength="10" placeholder="1234567890">
**CODE CSS:**
$( "#primary_phone" ).blur(function() {
text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
$(this).val(text);
});
At this time, the format is the next phone
123-123-1123
I want to have the next form:
(123)456-7890
How can I change the format to whatever shape that I want?
Thanks in advance!
| <javascript><jquery> | 2016-01-07 14:43:22 | LQ_EDIT |
34,658,888 | R how to remove first row of duplicate values from a big column | <p>in R I have a file (df) consisting in 2 very big columns, A and B (aprox. 1000000 elements each). I know I have many duplicate values in A. I know how to remove the duplicates (remove second rows of each duplicate):</p>
<pre><code>df1 = df[!duplicated(df$A), ]
</code></pre>
<p>but I would like to remove the first rows in the duplicate and keep the second rows. For instance, in the following example, I would like to remove 71 T and keep 71 C, NOT the other way around:</p>
<pre><code>A B
4 A
8 C
21 T
71 T
71 C
74 C
75 G
78 C
86 T
</code></pre>
<p>Thanks very much in advance</p>
| <r><duplicates><row> | 2016-01-07 15:25:20 | LQ_CLOSE |
34,658,988 | Powershell application runs in windows 7 but not windows 10 | I have created an app for back up and restore of computers. I also allows modification of ADObjects through the use of custom Profile.ps1 file. The app runs fine in the ISE with no errors and works properly no errors in Windows 7. However when I try to run it in a newly imaged Windows 10 machine I get "Property Can Not Be Found" errors on all my object propertys. The thing is I can read all the propetys when I fill comboboxes fine. The error only occurs when the form is submitted. I will attach 1 of the forms I am having a problem with. Again it runs fine in Windows 7 But not Windows 10. could this be a problem with Microsoft updates. Also "Yes" I am setting "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted". Thanks | <powershell><windows-10> | 2016-01-07 15:30:12 | LQ_EDIT |
34,659,252 | Polymer - Animating a DIV | <p>I am learning Polymer. I have a element that includes a <code>div</code>. I want to animate that div's height. In an attempt to do this, I've got the following:</p>
<p><strong>my-element.html</strong></p>
<pre><code><dom-module id="my-element">
<template>
<div id="container" style="height:100px; background-color:green; color:white;">
Hello!
</div>
<paper-button on-click="_onTestClick">Expand</paper-button>
</template>
<script>
Polymer({
is: 'my-element',
_onTestClick: function() {
// expand the height of container
}
});
</script>
</dom-module>
</code></pre>
<p>I then used the grow height animation shown <a href="https://github.com/PolymerElements/paper-menu-button/blob/master/paper-menu-button-animations.html">here</a> for inspiration. So, I basically, have a animation defined like this:</p>
<pre><code>Polymer({
is: 'grow-height-animation',
behaviors: [
Polymer.NeonAnimationBehavior
],
configure: function(config) {
var node = config.node;
var rect = node.getBoundingClientRect();
var height = rect.height;
this._effect = new KeyframeEffect(node, [{
height: (height / 2) + 'px'
}, {
height: height + 'px'
}], this.timingFromConfig(config));
return this._effect;
}
});
</code></pre>
<p>My challenge is, I do not understand how to integrate this animation with the <code>div</code> element with the id of "container". Everything I see seems like it only works on Polymer elements. Yet, I'm trying to figure out how to animate the <code>div</code> using Polymer. What am I missing?</p>
<p>Thanks!</p>
| <javascript><polymer> | 2016-01-07 15:41:51 | HQ |
34,659,952 | Converting NSDictionary to JSON in Objective C | <p>i want to generate a JSON in Objective C , below is an example, one dictionary which has some fields, and within that dictionary i want to add another dictionary. i.e. Student dictionary can have subjects dictionary(which can have multiple items.</p>
<pre><code>{
"student": {
"name": "b",
"std": "d",
"subjects": [{"id":"1","id":"2","id":"3"}]
}}
</code></pre>
<p>I am trying using NSJSONSerialization , i tried first creating json string of subjects dictionary but, after converting final JSON of main dictionary its showing (Slash) which is breaking json. i added subjects inside main dictionary then after converting its showing subjects json starting with <strong>(</strong></p>
<p>Any suggestion what m i missing?</p>
<p>Thanks</p>
| <ios><objective-c> | 2016-01-07 16:13:12 | LQ_CLOSE |
34,660,049 | What am I doing wrong? | >I keep getting an out of bounds error. Want to check for duplicates. there is more after this, but for right now all thats important. its for a school project. it says the the Array list is index:1 size: 1 out of bounds exception
ArrayList <Integer> lottery = new ArrayList<Integer>();
for (int n=0; n<4;)
{
int number = 0;
int first = 0;
int value = 0;
boolean found = false;
first =(int)(Math.random()*42 +1);
lottery.add(first);
count[first]++;
for (int i=1; i<6;)
{
number = (int)(Math.random()*42 +1);
for(int k = 0; k<6; )
{
// here value = lottery.get(k);
if (value == number)
{
found = true;
}
else
{
found = false;
}
if (found == true)
{
number = (int)(Math.random()*42 +1);
}
else
{
k++;
}
}
System.out.println("number " + (i+1) + ": " + number);
if ( found == false)
{
lottery.add(number);
count[number] ++;
i++;
}
} | <java><error-handling><runtime-error> | 2016-01-07 16:17:13 | LQ_EDIT |
34,660,500 | Mobile Safari multi select bug | <p>If found a really annoying bug on the current (iOS 9.2) mobile safari (first appearing since iOS 7!)</p>
<p>If you using multi select fields on mobile safari - like this:</p>
<pre class="lang-html prettyprint-override"><code><select multiple>
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test3">Test 3</option>
</select>
</code></pre>
<p>You will have problems with automatically selection!</p>
<p>iOS is automatically selecting the first option after you opened the select (without any user interaction) - but it will not show it to you with the blue select "check".</p>
<p>So if you now select the second option, the select will tell you that two options are selected (but only highlighting one as selected)...</p>
<p>If you now close and open the select again, iOS will automatically deselect the first value - if you repeat, it will be selected again without any user interaction.</p>
<p>Thats a really annoying system bug, which is breaking the user experience!</p>
| <html><ios><select><mobile-safari><multi-select> | 2016-01-07 16:38:39 | HQ |
34,660,727 | cloud 9.io css google chome error | I have been getting an error from Google chrome saying
: Failed to load resource: the server responded with a status 404 error.
I linked the path to the correct folder in cloud 9 project, but there is another project with the same format as my current one and it works fine. I am also using Semantic ui does that have anything to do with it? | <css><google-chrome><cloud9-ide><semantic-ui> | 2016-01-07 16:49:21 | LQ_EDIT |
34,661,027 | Javascript working on local, not working online | <p>I've just uploaded my website and something is wrong. I have a smooth scrolling when clicking in the navigation menù, and it worked on local (I used brackets), now it's not. Also, when I access to the site from my phone, the menù doesn't open.
Can someone help please? The site is <a href="http://www.chiarabonsignore.com" rel="nofollow">http://www.chiarabonsignore.com</a></p>
| <javascript> | 2016-01-07 17:02:51 | LQ_CLOSE |
34,661,210 | How to bind Kibana to multiple host names / IPs | <p>Is there a way to bind Kibana to more than one IP address using kibana's config file: <code>kibana.yml</code>?
Right now, if I modify the line<br>
<code>server.host: "127.0.0.1"</code><br>
to<br>
<code>server.host: ["127.0.0.1","123.45.67.89"]</code><br>
which is valid YML, I get an error.<br>
Is there any way to accomplish this from within Kibana or do I need to do it through a proxy/nginx?</p>
| <kibana> | 2016-01-07 17:12:04 | HQ |
34,661,853 | Django REST Framework : "This field is required." with required=False and unique_together | <p>I want to save a simple model with Django REST Framework. The only requirement is that <code>UserVote.created_by</code> is set automatically within the <code>perform_create()</code> method. This fails with this exception:</p>
<pre><code>{
"created_by": [
"This field is required."
]
}
</code></pre>
<p>I guess it is because of the unique_together index.</p>
<p>models.py:</p>
<pre><code>class UserVote(models.Model):
created_by = models.ForeignKey(User, related_name='uservotes')
rating = models.ForeignKey(Rating)
class Meta:
unique_together = ('created_by', 'rating')
</code></pre>
<p>serializers.py</p>
<pre><code>class UserVoteSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
created_by = UserSerializer(read_only=True)
class Meta:
model = UserVote
fields = ('id', 'rating', 'created_by')
</code></pre>
<p>views.py</p>
<pre><code>class UserVoteViewSet(viewsets.ModelViewSet):
queryset = UserVote.objects.all()
serializer_class = UserVoteSerializer
permission_classes = (IsCreatedByOrReadOnly, )
def perform_create(self, serializer):
serializer.save(created_by=self.request.user)
</code></pre>
<p>How can I save my model in DRF without having the user to supply <code>created_by</code> and instead set this field automatically in code?</p>
<p>Thanks in advance!</p>
| <python><django><database><django-rest-framework><unique> | 2016-01-07 17:49:11 | HQ |
34,662,574 | Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC | <p>I just installed <code>Node.js</code> on my <code>Ubuntu 14.04</code> operating system for the first time. I also installed <code>npm</code>. The next step in my installation process was installing <code>nodemon</code>. This all worked out fine. </p>
<hr>
<p><strong><em>But, when I run <code>nodemon</code> by typing <code>nodemon app.js</code> in my command line, I get the following error...</em></strong> </p>
<p><code>[nodemon] 1.8.1
[nodemon] to restart at any time, enter</code>rs<code>
[nodemon] watching: *.*
[nodemon] starting</code>node app.js<code>
[nodemon] Internal watch failed: watch ENOSPC
</code></p>
<p><strong><em>In the command line below the error...</em></strong></p>
<pre><code>alopex@Alopex:~/Desktop/coding_dojo/week-9/javascript/node/testing_node$ Hello World
</code></pre>
<p>Why is this happening? Is this normal behavior for nodemon? If not, how can I fix it? </p>
<hr>
<p><strong><em>Side notes...</em></strong></p>
<p>1) <code>app.js</code> is a <code>Javascript</code> file with <code>console.log(111)</code> inside of it.<br>
2) <code>node</code> version is <code>v0.10.25</code><br>
3) <code>npm</code> version is <code>1.3.10</code><br>
4) <code>nodemon</code> version is <code>1.8.1</code><br>
5) <code>ubuntu</code> version is...<br></p>
<pre><code>Distributor ID: Ubuntu
Description: Ubuntu 14.04.3 LTS
Release: 14.04
Codename: trusty
</code></pre>
| <javascript><node.js> | 2016-01-07 18:31:37 | HQ |
34,662,879 | Protractor - Wait for multiple elements | <p>I am trying to wait for multiple elements on the page, I don't know how many there could be but there will be at least one. I understand waiting for a single element using the following, which works fine.</p>
<pre><code>var EC = protractor.ExpectedConditions;
browser.wait(EC.presenceOf(element(by.css("h3[title='Test Form']"))), 10000);
expect(element(by.css("h3[title='Test Form']")).isPresent()).toBeTruthy();
</code></pre>
<p>I wanted to change this slightly to wait for multiple elements and so tried the below (adding .all to element).</p>
<pre><code>var EC = protractor.ExpectedConditions;
browser.wait(EC.presenceOf(element.all(by.css("h3[title='Test Form']"))), 10000);
expect(element.all(by.css("h3[title='Test Form']")).isPresent()).toBeTruthy();
</code></pre>
<p>Unfortunately when I try this I get </p>
<pre><code>Cannot read property 'bind' of undefined
</code></pre>
<p>Any help on this would be very much appreciated.</p>
<p>p.s. Newbie to Protracor and its quirks. </p>
| <javascript><protractor> | 2016-01-07 18:48:55 | HQ |
34,663,335 | C vs C++ sizeof | <p>I just came across this simple code snippet and am wondering why output of this program when it's compiled by a C compiler is <code>4</code> and when it's compiled by a C++ one is <code>8</code>.</p>
<pre><code>#include <stdio.h>
int x;
int main(){
struct x {int a; int b;};
printf("%d", sizeof(x));
return 0;
}
</code></pre>
<p>C++ output is rational (<code>8 = 4 + 4 = sizeof(x.a) + sizeof(x.b)</code>), but output of C isn't. So, how does <code>sizeof</code> work in C?</p>
<ul>
<li>C : <a href="https://ideone.com/zj5Qd2">https://ideone.com/zj5Qd2</a></li>
<li>C++ : <a href="https://ideone.com/ZZ4v6S">https://ideone.com/ZZ4v6S</a></li>
</ul>
<p>Seems C prefers global variables over local ones. Is it right?</p>
| <c++><c><sizeof> | 2016-01-07 19:16:31 | HQ |
34,663,911 | [VB6]No experience with it but I need it | Private Sub cmdtiehack_Click()
Dim hwnd
hwnd = FindWindow(vbNullString, "Window name")
If hwnd = 0 Then
MsgBox "Program is not open"
Else
Dim Retval As Long
Retval = ShellExecute(Me.hwnd, "open", "5.exe", _ 0, 0, SW_HIDE)
Delay 1
Retval = ShellExecute(Me.hwnd, "open", "6.exe", _ 0, 0, SW_HIDE)
End If
End Sub
I didn't use VB in past, but I can't see where's the error. Should I compile it or save like a .vbs just by using Notepad? Thanks for advice. | <vbscript><vb6> | 2016-01-07 19:49:54 | LQ_EDIT |
34,664,131 | Camera2 ImageReader freezes repeating capture request | <p>I'm trying to capture image data from the camera using the camera2 API. I've mostly used code taken from the android Capture2RAW example. Only a few images come through (i.e. calls to onImageAvailable) before stopping completely. I've tried capturing using the RAW_SENSOR and JPEG formats at different sizes with the same results. What am I doing wrong?</p>
<pre><code>this.mImageReader = ImageReader.newInstance(width, height, ImageFormat.RAW_SENSOR, /*maxImages*/ 1);
Surface surface = this.mImageReader.getSurface();
final List<Surface> surfaces = Arrays.asList(surface);
this.mCamera.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
// Callback methods here
}, null);
CaptureRequest.Builder captureRequestBuilder;
captureRequestBuilder = this.mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
this.mCaptureRequest = captureRequestBuilder.build();
this.mCaptureSession.setRepeatingRequest(mCaptureRequest, null, null);
</code></pre>
| <android><android-camera2> | 2016-01-07 20:03:14 | HQ |
34,664,416 | How to check if the dates are of same format in PERL? | <p>I have a .csv file.
The second column are dates.</p>
<p>The dates maye not be of the same format.</p>
<p>how can I check to make sure if they are in same format or if I can use some method to change all dates into 1 specific format?</p>
| <perl> | 2016-01-07 20:19:58 | LQ_CLOSE |
34,664,705 | Why I cannot assign event listner to a button? | Here's the code to add event listeners to all the button elements in my html. Why does it not work?
window.onload = function(){
addEvListeners();
// This function is to assign ELs to buttons in my HTML
function addEvListeners(){
var target = document.getElementsByTagName("button");
for (i = 0; i <= target.length - 1; i ++){
target[i].addEventListener("click", function(){model();},false);
}
}
function model(){
return true; // just for placeholder
}
} | <javascript><dom-events><addeventlistener><event-listener> | 2016-01-07 20:38:22 | LQ_EDIT |
34,664,709 | What type of weather chart is this? | <p>I like the look of this chart for weather data but I do not know the name of the chart type.</p>
<p>I may try to render my own version but I would like to know if any chart libraries (Javscript Based) support it but I need to know its name.</p>
<p>Maybe someone has written it for D3.js ?</p>
<p><a href="https://i.stack.imgur.com/Imvb6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Imvb6.jpg" alt="enter image description here"></a></p>
| <javascript><d3.js><charts><weather> | 2016-01-07 20:38:39 | LQ_CLOSE |
34,664,810 | Create an application that loads a website? | <p>I have an existing MVC web application and I want to create a native application for Android, IOS, and PC that, when launched, navigates to a website but does not show typical browser features such as the URL bar, navigation buttons, bookmarks, etc.</p>
<p>Are there any tools that will allow me to do this for one or more of the targeted platforms?</p>
| <android><ios><asp.net-mvc> | 2016-01-07 20:45:16 | LQ_CLOSE |
34,664,853 | Sequelize composite unique constraint | <p>Defining model:</p>
<pre><code>export default function(sequelize, DataTypes) {
return sequelize.define('Item', {
minor: DataTypes.INTEGER,
major: DataTypes.INTEGER,
});
}
</code></pre>
<p>Can I define the pair minor and major as a composite UNIQUE constraint?</p>
| <mysql><node.js><sequelize.js> | 2016-01-07 20:47:58 | HQ |
34,664,950 | how to fix an error on a simulation? | Please help me to find the errors .I am trying to run a simulation but I keep getting some kind of error.I am not very experienced in c++ .I will attach both files the main file of the simulation and the file ndn-v2v..
i will appreciate any help i can get even a small advice and thanks in advance.[i also added a screen capture for the error while compilling the script here][1]
enter code here
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/mobility-module.h"
#include "ns3/config-store-module.h"
#include "ns3/wifi-module.h"
#include "ns3/internet-module.h"
#include "ns3/ndnSIM-module.h"
#include "ns3/corner-propagation-loss-model.h"
#include "ns3/ndn-v2v-net-device-face.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include "../src/ndnSIM/utils/tracers/ndn-l3-aggregate-tracer.h"
#include "../src/ndnSIM/utils/tracers/ndn-l3-rate-tracer.h"
#include "../src/ndnSIM/utils/tracers/v2v-tracer.h"
NS_LOG_COMPONENT_DEFINE ("Wifiv2v");
using namespace ns3;
#define MAX_NODES 1002;
static int packet_count = 0;
// Variable for simulation-traces
//------------------------------------//
//------------------------------------//
//------------------------------------//
int mac_tx_count = 0; // counts how many packets a rereceived from the higher layers in order to be enqueued for transmission
int mac_tx_drop = 0; //counts how many packets are has been dropped in the Mac layer before beeing queued for transmission
int mac_rx_count = 0; //counts how many packets a rereceived from the phy layer and is being forwarded to the local protocol stack
int mac_rx_drop = 0; //counts how many packtes has been dropped in the Mac layer after has been passed
//up from phylayer
//------------------------------------//
//------------------------------------//
// Call back for simulation-traces
//------------------------------------//
//------------------------------------//
void MacTxCount(Ptr<const Packet> p) {
mac_tx_count++;
NS_LOG_DEBUG(
"[MACTXCOUNT] Packet is going to be transmitted...mac_tx_count="
<< mac_tx_count);
}
void MacTxDrop(Ptr<const Packet> p) {
mac_tx_drop++;
NS_LOG_DEBUG(
"[MAC_TX_DROP] Packet has been dropped before transmission...mac_tx_drop="
<< mac_tx_drop);
}
void MacRxCount(Ptr<const Packet> p) {
mac_rx_count++;
NS_LOG_DEBUG(
"[MAC_RX_COUNT] Packet has been received,going to forward...mac_rx_drop="
<< mac_rx_count);
}
void MacRxDrop(Ptr<const Packet> p) {
mac_rx_drop++;
NS_LOG_DEBUG(
"[MAC_RX_DROP] Packet has been dropped by Mac before forward...mac_rx_drop="
<< mac_rx_drop);
}
void PrintTrasmission() {
//std::cout<<Simulator::Now().GetSeconds()<<"\t"<<
mac_tx_count << "\t" << mac_tx_drop << "\t" << mac_rx_count << "\t"
<< mac_rx_drop << "\n ";
NS_LOG_DEBUG(
" [ PRINT-TRANSMISSION]Time=" << Simulator::Now().GetSeconds()
<< " mac_tx_count=" << mac_tx_count << " mac_tx_drop= "
<< mac_tx_drop << " mac_rx_count= " << mac_rx_count
<< " mac_rx_drop=" << mac_rx_drop);
Simulator::Schedule(Seconds(5.0), &PrintTrasmission);
}
void OutInterest(Ptr<const ns3::ndn::InterestHeader> interestHeader,
Ptr<const ns3::ndn::Face> face) {
NS_LOG_DEBUG(
"[OUT INTEREST]Time=" << Simulator::Now().GetSeconds() << " NID= "
<< face->GetNode()->GetId() << " Nonce= "
<< interestHeader->GetNonce() << "Name="
<< interestHeader->GetName() << "\n");
}
void InInterest(Ptr<const ns3::ndn::InterestHeader> interestHeader,
Ptr<const ns3::ndn::Face> face) {
NS_LOG_DEBUG(
"[IN INTEREST]Time=" << Simulator::Now().GetSeconds() << "NID="
<< face->GetNode()->GetId() << "Nonce="
<< interestHeader->GetNonce() << "Name="
<< interestHeader->GetName() << "Position="
<< face->GetNode()->GetObject<MobilityModel>()->GetPosition()
<< "\n");
}
void DropInterest(Ptr<const ns3::ndn::InterestHeader> interestHeader,
Ptr<const ns3::ndn::Face> face) {
NS_LOG_DEBUG(
"[DROPINTEREST]Time=" << Simulator::Now().GetSeconds() << "NID="
<< face->GetNode()->GetId() << "Nonce="
<< interestHeader->GetNonce() << "Name="
<< interestHeader->GetName() << "\n");
}
void InData(Ptr<const ns3::ndn::ContentObjectHeader> contentHeader,
Ptr<const ns3::Packet> packet, Ptr<const ns3::ndn::Face> face) {
NS_LOG_DEBUG(
"[INDATA]Time=" << Simulator::Now().GetSeconds() << "NID="
<< face->GetNode()->GetId() << "Name="
<< contentHeader->GetName() << "Position="
<< face->GetNode()->GetObject<MobilityModel>()->GetPosition()
<< "\n ");
}
void OutData(Ptr<const ns3::ndn::ContentObjectHeader> contentHeader,
Ptr<const ns3::Packet> packet, bool value,
Ptr<const ns3::ndn::Face> face) {
NS_LOG_DEBUG(
"[OUT DATA]Time=" << Simulator::Now().GetSeconds() << "NID="
<< face->GetNode()->GetId() << "Name="
<< contentHeader->GetName() << "\n");
}
void DropData(Ptr<const ns3::ndn::ContentObjectHeader> contentHeader,
Ptr<const ns3::Packet> packet, Ptr<const ns3::ndn::Face> face) {
NS_LOG_DEBUG(
"[DROP DATA]Time=" << Simulator::Now().GetSeconds() << "NID="
<< face->GetNode()->GetId() << "Name="
<< contentHeader->GetName() << "\n");
}
Ptr<ndn::NetDeviceFace> V2vNetDeviceFaceCallback(Ptr<Node> node,
Ptr<ndn::L3Protocol> ndn, Ptr<NetDevice> device) {
//NS LOG UNCOND ("Creating ndn::V2vNetDeviceFace on node"<< node->GetId()
);
Ptr < ndn::NetDeviceFace > face = CreateObject < ndn::V2vNetDeviceFace
> (node, device);
NS_LOG_DEBUG("Node=" << node->GetId() << "MAC=" << device->GetAddress());
ndn->AddFace(face);
return face;
}
voidprintPosition(Ptr<const MobilityModel>mobility)
{
NS LOG INFO("Time="<<Simulator::Now().GetSeconds( )<<"Positionof:"<< mobility->GetObject<Node>()->GetId()<<":"<<mobility->GetPosition());
}
//------------------------------------//
void ReceivePacket(Ptr<Socket> socket) {
//NS LOG UNCOND ("Received one packet!");
packet_count++;
}
int main(int argc, char* argv[]) {
//NS LOG UNCOND( "NDN SIMULATION ---->Started<----");
std::stringphyMode("OfdmRate6Mbps"); //("DsssRate1Mbps");
double rss = -80; // -dBm
uint32_t packet
Size = 512; // bytes
uint32_t numPackets = 50;
// double interval=0.5;//seconds
bool verbose = false;
//Param for simulation and tracing
bool pcapOn = true; // Tracing is enabled by default
uint32_t numberOfConsumer = 1; // D a f ault value:1
uint32_t numberOfProducer = 1; //Default value:1
uint32_t numberOfRuns = 50; //Default value:50
uint32_t numOfNodes = 357; //Default value:12
std::string mobFile("/home/user/Desktop/ndnSIM/ns-3/scratch/losangeles.cc");
double time = 0;
double x = 0, y = 0, z = 0;
int nodeNo = 0;
CommandLine cmd;
cmd.AddValue("phyMode", "Wifi Phy mode", phyMode);
cmd.AddValue("rss", "received signal strength", rss);
cmd.AddValue("packet Size", " size of application packet sent", packetSize);
cmd.AddValue("numPackets ", "number of packets generated", numPackets);
//cmd . AddValue("interval","interval(seconds) between packets",interval);
cmd.AddValue("verbose"," turn on all WifiNetDevice log components",verbose) ;
//new param
cmd.AddValue("pcapOn","Turn on/off pcap tracing.Tracing is enabled by default",pcapOn);
cmd.AddValue("numConsumer","Number of consumer in the simulation",numberOfConsumer);
cmd.AddValue("numProducer","Number of producer in the simulation",numberOfProducer);
cmd.AddValue("numRun", "Number of run per simulation",numberOfRuns);
cmd.AddValue("mobilityFile", "Insertfullpath", mobFile);
cmd.AddValue("numNodes"," Total number o f nodes in the simulation",numOfNodes);
cmd.Parse(argc, argv);
// Convert to time object
//Time inter Packet Interval= Seconds (interval);
// NS LOG UNCOND("true");
//disable fragmentation for frames below 2200 bytes
Config::SetDefault(
"ns3::WifiRemoteStationManager::FragmentationThreshold ",
StringValue("2200"));
// turn off RTS/CTS for frames below 2200bytes
Config::SetDefault(
"ns3::WifiRemoteStationManager::RtsCtsThreshold ",
StringValue("2200"));
// Fix non-unicast data rate to be the same as that of unicast
Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode",String Value(phyMode));
//enable cache unsolicited Data
Config::SetDefault(
"ns3::ndn::ForwardingStrategy::CacheUnsolicitedData",
BooleanValue(true));
//Read number of cars directly from file
std::ifstreamreadNcars;
std::map<int, int> map
count;
int count = 0;
readNcars.open(mobFile.cstr(), std::ios::in);
while (readNcars >> nodeNo) {
readNcars >> time >> x >> y >> z;
if (mapcount.find(nodeNo) != mapcount.end()) { // cout<<"Ke yis present:"<<nodeNo<<" is present!\n";
count = mapcount[nodeNo];
count++;
mapcount[nodeNo] = count;
} else {
// cout <<"Key not present:"<<nodeNo<<"is not present!\n";
mapcount[nodeNo] = 1;
}
}
numOfNodes = map
count.size();
NodeContainer c;
c.Create(numOfNodes);
// The below set of helpers will help us to put together th e wifi NICs we want
WifiHelperwifi;
if (verbose) {
wifi.EnableLogComponents(); // Turn on all Wifi logging
}
wifi.SetStandard ( WIFI PHY STANDARD 80211a); //WIFI PHY STANDARD 80211b
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default();
// This is one parameter that matters when using FixedRssLossModel
// set it to zero;otherwise, gain will be added
wifiPhy.Set("RxGain ", DoubleValue(0));
wifiPhy.Set("EnergyDetectionThreshold", DoubleValue(-93)); //dBm,default value is -96 dBm
// ns-3 supports RadioTap and Prism tracing extensions for 802.11b
wifiPhy.SetPcapDataLinkType(
YansWifiPhyHelper::DLTIEEE80211RADIO);
YansWifiChannelHelperwifiChannel;
wifiChannel.SetPropagationDelay(
"ns3::ConstantSpeedPropagationDelayModel ");
// Proptagation model is CORNER
wifiChannel.AddPropagationLoss(
"ns3::CornerPropagationLossModel");
wifiPhy.SetChannel(wifiChannel.Create());
// Add a non-QoS upper mac,and disablerate control
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default();
wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
"DataMode ", StringValue(phyMode), "ControlMode",
StringValue(phyMode));
// Set it to adhoc mode
wifiMac.SetType("ns3::AdhocWifiMac");
NetDeviceContainerdevices = wifi.Install(wifiPhy, wifiMac, c);
// Create file for thecapture
if(pcapOn==true) {
//wifiPhy.EnablePcap("capture examp",devices);
//wifiPhy.EnablePcap Internal("captureexampnode0",devices.Get(0),true);
//wifiPhy.Enable Pcap Internal("captureexampnode1",devices.Get(0),true);}
//the format of corner.mobility
//NodeNum time x y z
// by reading each line ,we can get a detaile dtrace of nodes ’ mobility
MobilityHelper mobility;
mobility.SetMobilityModel("ns3::WaypointMobilityModel");
mobility.Install(c);
std::ifstream mobileInput;
mobileInput.open(mobFile.cstr(),std::ios::in);
if(!mobileInput.isopen()) {
NS LOG ERROR("Invalidmap.The path("<<mobFile<<"is wrong.Please check it again");
return -1;
}
//With map
std::map<int,Ptr<WaypointMobilityModel>>wayMobility;
//NS LOG UNCOND ( " nNodes = "<<nNodes ) ;
uint32_t indexc=0;
for(std::map<int,int>::iteratorit=mapcount.begin();
it!=mapcount.end();it++,indexc++) {
wayMobility[it ->first]=c.Get(indexc)->GetObject<WaypointMobilityModel >();
// cout <<"Key="<<it->first<<"Value="<<it->
second <<"\n ";
}
// setting initial position to all the nodes.We put all the cars far away from the map (100Km +some randomvalue)
double sinkX =100000;
double sinkY = 100000;
double sinkZ =0;
index c = 0;
for (std::map<int,int>::iteratorit=map count.begin();
it!=mapcount.end();it++,indexc++) {
Waypoint waypoint(Seconds(0.1),Vector3D(sinkX+(indexc *10000),sinkY+(indexc *10000),sinkZ));
// wayMobility [ i ]->AddWaypoint (waypoint);
Simulator::Schedule(Seconds(0.1),&WaypointMobilityModel::SetPosition,wayMobility[it->first],Vector3D(sinkX+(indexc*10000),sinkY+(indexc*10000),sinkZ)
);
}
std::map<int,int>endTime;
for(std::map<int,int>::iteratorit=mapcount.begin();
it != map count.end();it++) {
endTime[it->first]=0;
}
while(mobileInput>>nodeNo)
{
mobileInput>>time>>x>>y>>z;
if(time <=0.1) {
//discarding the positionatsec0; we ’ ve substituted them with sink coordinates
continue;
}
endTime[nodeNo]=time;
Waypoint waypoint(Seconds (time),Vector3D(x,y,z));
//NS LOG UNCOND( "Reading mobility file Id="<< nodeNo<<" time="<<time<<"("<<x<<","<<y<<")");
wayMobility[nodeNo]->AddWaypoint(waypoint);
/*if(nodeNo==0)
{
wayMobility0->AddWaypoint ( waypoint );} else if(nodeNo==1)
{
wayMobility1->AddWaypoint(waypoint);
}*/
}
//std::vector<Ptr<Node>>::constiterator it=c.Begin();
//setting sink coordinates when a car mobility terminates
uint32_t numberOfWaypoint;
Waypoint point;
for(std::map<int,int>::iteratorit=map count.begin();
it!=mapcount.end();it ++) {numberOfWaypoint = wayMobility[it->first]->WaypointsLeft(); //TO DO chec kif it goes to the last element
if(numberOfWaypoint==0) {
continue;
}
index c = 0;
Simulator::Schedule(Seconds(endTime[it->first]+0.0001),&WaypointMobilityModel::SetPosition,wayMobility[it->first],Vector3D (sinkX+(indexc*10000),sinkY+(indexc*10000),sinkZ));}
//NS LOG UNCOND ("Mobility read!") ;
// Install Ndn stack on all nodes
//NS LOG INFO ( " Installing Ndnstack ") ;
ndn::StackHelperndnHelper;
EndnHelper.AddNetDeviceFaceCreateCallback (
WifiNetDevice : : GetTypeId ( ),MakeCallback(V2vNetDeviceFaceCallback ) );
//...setting ad hoc forwarding
ndnHelper.SetForwardingStrategy("ns3::ndn::fw::V2v");
ndnHelper.SetDefaultRoutes(true);
ndnHelper.InstallAll( );
// Test with more than one consumer
std::ifstream fileConsumer;
fileConsumer.open("/home/nrl/contolic/vndn-sim/ns-3/scratch/consumer.txt",std::ios::in);
if ( !fileConsumer.is open () ) {
NS LOG ERROR("Invalidname.The name"<<fileConsumer<<"is wrong.Please check it again");
return -1;
}
int idConsumer = 0;
int countCons = 0;
int indexCNodes = numOfNodes - 1;
while(fileConsumer>>idConsumer ) {
//NS LOG UNCOND( " idConsumer " << idConsumer ) ;
std::string consumerName=" c"+idConsumer;
Ptr<Node> nodeConsumer = CreateObject <Node >();
//Names : : Add( consumerName , nodeConsumer ) ;
ndn::AppHelper consumerHelper("ns3::ndn::ConsumerCbr");
consumerHelper.SetPrefix("/prefix");
consumerHelper.SetAttribute(" Frequency ",StringValue ("1"));
consumerHelper.SetAttribute("Randomize",StringValue("uniform "));
ApplicationContainerconsumers=consumerHelper.Install(c.Get(indexCNodes-countCons));
consumers.Start(Seconds(50));//(50)-countCons *10
consumers.Stop(Seconds(450));//(600)-30
countCons++;
}
// Test with more than oneproducer
std::ifstream fileProducer;
fileProducer.open("/home/nrl/contolic/vndn-sim/ns-3/scratch/producer.txt",std::ios::in);
if(!fileProducer.is open () ) {
NS LOG ERROR( "Invalidname.Thename"<<fileProducer<<"iswrong.Please check it again ");
return -1;
}
int idProducer = 0;
int countProd = 0;
int indexPNodes = 0;
while(fileProducer>>idProducer) {
//NS LOG UNCOND("idProducer"<<idProducer);
std::string producerName="c"+idProducer;Ptr<Node>nodeProducer=CreateObject<Node >();
//Names::Add(producerName,nodeProducer);
ndn::AppHelperproducerHelper("ns3::ndn::Producer");
producerHelper.SetPrefix("/prefix" );
producerHelper.SetAttribute("PayloadSize",StringValue ("1024") );
ApplicationContainerproducers=producerHelper.Install(c.Get(indexPNodes+countProd));
//producers.Start(Seconds(countProd*0.5));
countProd++;}
/*ndn::AppHelperproducerHelper("ns3::ndn::Producer");
// Producer willreply to all requestsstarting
with/prefixproducerHelper.SetPrefix("/prefix");
producerHelper.SetAttribute(" PayloadSize ",StringValue("1024"));
//ApplicationContainerproducers=producerHelper.
Install(c.Get(0));// AlmostatLincolnBlvd
on WilshireBlvd*/
//NS LOG UNCOND(" Applicationinstalled!!" ) ;
// Trace oflevel2.5
Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/MacTx",MakeCallback(&MacTxCount));
Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/MacRx",MakeCallback(&MacRxCount ) );
Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice /Mac/MacTxDrop",MakeCallback(&MacTxDrop));
Config::ConnectWithoutContext("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/MacRxDrop",MakeCallback(&MacRxDrop));
// Trace
Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/OutInterests",MakeCallback(&OutInterest));
Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/InInterests",MakeCallback(&InInterest));
Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/DropInterests",MakeCallback(& DropInterest));
Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/InData ",MakeCallback(&InData));
Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/DropData ",MakeCallback(&DropData ));
Config::ConnectWithoutContext("/NodeList/*/$ns3::ndn::ForwardingStrategy/OutData",MakeCallback(&OutData ) );
/* Tracing the car position*/
Config::ConnectWithoutContext("/NodeList/*/$ns3::MobilityModel / CourseChange ",MakeCallback(&printPosition ) );
Simulator::Stop(Seconds(600.0));//(600.0)-30
/*Testingtraces*/
/* boost::tuple< boost::sharedptr<std::ostream >,
std::list<Ptr<ndn::L3AggregateTracer> > >
aggTracers= ndn::L3AggregateTracer::InstallAll("/ mnt/space/simulationlog/ndn-600s-aggregate-trace-v2v.txt",Seconds (0.5));*/
/* boost::tuple<boost::sharedptr<std::ostream >,std::list<Ptr<ndn::L3RateTracer> > >
rateTracers=ndn::L3RateTracer::InstallAll("/mnt/space/simulationlog/ndn-600s-rate-trace-v2v.txt",Seconds(0.5));*/
/*
boost::tuple<boost::sharedptr<std::ostream >,
std::list<boost::sharedptr<ndn::V2vTracer> >>v2vtracing=ndn::V2vTracer::InstallAll("v2v.tracer.txt");*/
Simulator:: Run ( );
Simulator:: Destroy ( );
return 0;
}
also here is the second file ndn-v2v-net-device-face.h
enter code here
#ifndef NDN_V2V_NET_DEVICE_FACE_H
#define NDN_V2V_NET_DEVICE_FACE_H
#include "ns3/nstime.h"
#include "ns3/event-id.h"
#include "ns3/random-variable.h"
#include "ns3/traced-callback.h"
#include "ns3/ndn-net-device-face.h"
#include "ns3/ndn-header-helper.h"
namespace ns3 {
class Vector3D;
typedef Vector3D Vector;
namespace ndn {
class NameComponents;
/**
* \ingroup ndn-face
* \brief Implementation of layer-2 broadcast vehicle-2-vehicle NDN face
*
* This class defines basic functionality of NDN face. Face is core
* component responsible for actual delivery of data packet to and
* from NDN stack
*
* ndn::NetDevice face is permanently associated with one NetDevice
* object and this object cannot be changed for the lifetime of the
* face
*
* The only difference from the base class is that ndn::V2vNetDevice
* makes additional consideration for overheard information
*
* \see ndn::AppFace, ndn::NetDeviceFace
*/
class V2vNetDeviceFace : public NetDeviceFace
{
public:
static TypeId
GetTypeId ();
/**
* \brief Constructor
*
* \param netDevice a smart pointer to NetDevice object to which
* this face will be associate
*/
V2vNetDeviceFace (Ptr<Node> node, const Ptr<NetDevice> &netDevice);
virtual ~V2vNetDeviceFace();
// from CcnxFace
virtual void
SendLowPriority (Ptr<Packet> p);
protected:
// from ndn::NetDeviceFace
virtual bool
SendImpl (Ptr<Packet> p);
public:
virtual std::ostream&
Print (std::ostream &os) const;
private:
V2vNetDeviceFace (const V2vNetDeviceFace &); ///< \brief Disabled copy constructor
V2vNetDeviceFace& operator= (const V2vNetDeviceFace &); ///< \brief Disabled copy operator
/// \brief callback from lower layers
virtual void
ReceiveFromNetDevice (Ptr<NetDevice> device,
Ptr<const Packet> p,
uint16_t protocol,
const Address &from,
const Address &to,
NetDevice::PacketType packetType);
void
SendFromQueue ();
void
SetMaxDelay (const Time &value);
Time
GetMaxDelay () const;
void
SetMaxDelayLowPriority (const Time &value);
Time
GetMaxDelayLowPriority () const;
void
ProcessRetx ();
Time
GetPriorityQueueGap () const;
void
NotifyJumpDistanceTrace (const Ptr<const Packet> packet);
private:
struct Item
{
Item (const Time &_gap, const Ptr<Packet> &_packet);
Item (const Item &item);
Item &
operator ++ ();
Item &
Gap (const Time &time);
Time gap;
Ptr<Packet> packet;
HeaderHelper::Type type;
Ptr<const NameComponents> name;
uint32_t retxCount;
};
typedef std::list<Item> ItemQueue;
EventId m_scheduledSend;
// Primary queue (for requested ContentObject packets)
Time m_totalWaitPeriod;
UniformVariable m_randomPeriod;
Time m_maxWaitPeriod;
uint32_t m_maxPacketsInQueue;
ItemQueue m_queue;
// Low-priority queue (for pushing Interest and ContentObject packets)
Time m_maxWaitLowPriority;
double m_maxDistance;
ItemQueue m_lowPriorityQueue;
// Retransmission queue for low-priority pushing
EventId m_retxEvent;
Time m_maxWaitRetransmission;
ItemQueue m_retxQueue;
uint32_t m_maxRetxAttempts;
TracedCallback<double, double> m_waitingTimeVsDistanceTrace;
TracedCallback<Ptr<const Node>, double> m_jumpDistanceTrace;
TracedCallback<Ptr<Node>, Ptr<const Packet>, const Vector&> m_tx;
TracedCallback<Ptr<Node>, Ptr<const Packet> > m_cancelling;
};
} // namespace ndn
} // namespace ns3
#endif // NDN_V2V_NET_DEVICE_FACE_H
[1]: http://i.stack.imgur.com/kdiPk.png | <c++><ns-3><ndnsim> | 2016-01-07 20:53:22 | LQ_EDIT |
34,666,148 | Openshift v3 - update image stream to fetch changes from external docker registry | <p>I'm seeming to run into a simple problem and have the feeling I'm missing something essential.</p>
<p>I'm having a private docker image registry at our company, which hosts all the docker images we develop.</p>
<p>This registry is constantly updated during our build process and new images are pushed to it quite often.</p>
<p>Now we are utilizing an openshift system, with a handful of images and it's own registry. </p>
<p>What would be the best way to synchronize images between these 2 systems?</p>
<p>As example, we have an app deployed like this:</p>
<pre><code>oc new-app myregistry.mydomain.edu/binbase/minix
</code></pre>
<p>which is running nicely.</p>
<p>We would now like to update this deployment with the latest changes and for this I do:</p>
<pre><code>oc import-image minix
</code></pre>
<p>Tag Spec Created PullSpec Image
latest 23 hours ago myregistry.mydomain.edu/binbase/minix:latest f6646382cfa32da291e8380421ea656110090256cd195746a5be2fcf61e4edf1</p>
<p>which is the correct image and now executing a</p>
<pre><code>oc deploy minix --latest
</code></pre>
<p>but this still deploys the current image, not the newly updated image.</p>
<p>Any idea why this, or what we are doing wrong?</p>
<p>All I would like todo is to now redeploy the newest image.</p>
<p>kind regards</p>
| <docker><openshift> | 2016-01-07 22:14:48 | HQ |
34,666,159 | Very poor performance of async task run on threadpool in .Net native | <p>I've observed a strange difference in managed vs .Net native code. I've a heavy job redirected to threadpool. When running the app in managed code, everything works smooth but as soon as I switch on native compilation - the task run few times slower and so slow that it hangs UI thread (I guess CPU is so overloaded). </p>
<p>Here are two screenshots from debug output, the one on the left is from managed code, and the one on the right is from native compilation. As you can see the time consumed by UI task is nearly the same in both cases, up to a time when threadpool job is started - then in managed version UI elapsed time grows (in fact UI gets blocked and you cannot take any action). Timings of threadpool job speak for themselves. </p>
<p><a href="https://i.stack.imgur.com/8x7vvm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8x7vvm.png" alt="Managed"></a><a href="https://i.stack.imgur.com/qof4pm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qof4pm.png" alt="Native"></a></p>
<p>The sample code to reproduce the problem:</p>
<pre class="lang-cs prettyprint-override"><code>private int max = 2000;
private async void UIJob_Click(object sender, RoutedEventArgs e)
{
IProgress<int> progress = new Progress<int>((p) => { MyProgressBar.Value = (double)p / max; });
await Task.Run(async () => { await SomeUIJob(progress); });
}
private async Task SomeUIJob(IProgress<int> progress)
{
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < max; i++)
{
if (i % 100 == 0) { Debug.WriteLine($" UI time elapsed => {watch.ElapsedMilliseconds}"); watch.Restart(); }
await Task.Delay(1);
progress.Report(i);
}
}
private async void ThreadpoolJob_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Firing on Threadpool");
await Task.Run(() =>
{
double a = 0.314;
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 50000000; i++)
{
a = Math.Sqrt(a) + Math.Sqrt(a + 1) + i;
if (i % 10000000 == 0) { Debug.WriteLine($"Threadpool -> a value = {a} got in {watch.ElapsedMilliseconds} ms"); watch.Restart(); };
}
});
Debug.WriteLine("Finished with Threadpool");
}
</code></pre>
<p>If you need a complete sample - then you can <a href="https://onedrive.live.com/redir?resid=87995A9E6AADB641!58603&authkey=!AJz9OH5TWsnVe5k&ithint=file%2czip" rel="noreferrer">download it here</a>.</p>
<p>As I've tested the difference appears on both optimized/non optimized code, in both debug and release versions.</p>
<p>Does anybody have an idea what can cause the problem?</p>
| <c#><async-await><win-universal-app><uwp><.net-native> | 2016-01-07 22:15:25 | HQ |
34,666,416 | Get a yarn configuration from commandline | <p>In EMR, is there a way to get a specific value of the configuration given the configuration key using the <code>yarn</code> command?</p>
<p>For example I would like to do something like this</p>
<pre><code>yarn get-config yarn.scheduler.maximum-allocation-mb
</code></pre>
| <hadoop><yarn><hadoop2><emr><elastic-map-reduce> | 2016-01-07 22:31:03 | HQ |
34,666,822 | Is it allowed to place ...<T> as class name java? | <p>I have this code for a class that represent a element in a list</p>
<pre><code>public class Element<T>{
Element<T> next;
Element<T> previous;
T info;
}
</code></pre>
<p>I have some ideas but I actually don't figure out the full meaning of the above declaration. And have some hard times to search for an explanation of this technique.</p>
| <java> | 2016-01-07 23:05:51 | LQ_CLOSE |
34,666,904 | when I close my java program it refreshes everything | Label.setEnabled(true)
If(i==0)
Label.setEnabled(false);
. if I is equal to 0 it would not be enabled but when I close the program and open it again it will be enabled instead of staying disabled. | <java><swing> | 2016-01-07 23:13:29 | LQ_EDIT |
34,667,134 | Implicitly lazy static members in Swift | <p>I just noticed that <code>static</code> members of Swift <code>structs</code> are implicitly <code>lazy</code>. </p>
<p>For instance, this will only call the <code>init</code> once:</p>
<pre><code>class Baz {
init(){
print("initializing a Baz")
}
}
struct Foo {
static let bar = Baz()
}
var z = Foo.bar
z = Foo.bar
</code></pre>
<p>What's the rationale behind this?</p>
<p>What if I want the opposite behaviour?</p>
| <swift><static><swift2><lazy-loading><static-members> | 2016-01-07 23:36:11 | HQ |
34,667,237 | Initialize map with pair of std::arrays c++11 | <p>I would like to compile this lines. Insert to map pair of std::arrays.</p>
<pre><code>#include<iostream>
#include<map>
#include<array>
#include<utility>
using namespace std;
int main()
{
array<double, 8> l;
array<double, 8> r;
map<double, pair<array<double, 8>, array<double, 8>>> m;
pair<array<double, 8>, array<double, 8>> p;
p = make_pair(l, r);//ok
m.insert(1., make_pair(l, r));//not ok
return 0;
}
//clear && g++ getMinPosition.cpp -std=c++11 -o getMinPosition && ./getMinPosition
</code></pre>
| <c++><c++11><stdmap><std-pair><stdarray> | 2016-01-07 23:45:32 | LQ_CLOSE |
34,667,606 | Can't enable phar writing | <p>I am actually using wamp 2.5 with PHP 5.5.12 and when I try to create a <strong>phar</strong> file it returns me the following message : </p>
<blockquote>
<p>Uncaught exception 'UnexpectedValueException' with message 'creating archive "..." disabled by the php.ini setting phar.readonly'</p>
</blockquote>
<p>even if I turn to off the <em>phar.readonly</em> option in <em>php.ini</em>.</p>
<p><strong>So how can I enable the creation of phar files ?</strong></p>
| <phar><php-ini> | 2016-01-08 00:24:20 | HQ |
34,668,133 | Which is the most difficult to reverse the order of the sort (largest to smallest) from Insertions sort selection sort or merge sort? | I know that the answer to the question is that they are all equally difficult to reverse but I don't know why. Could someone explain this? | <sorting><mergesort><insertion-sort><selection-sort> | 2016-01-08 01:33:52 | LQ_EDIT |
34,668,175 | How to remove "My Wish List" and "Compare Products" blocks from Magento 2.0 Luma template? | <p>I have spent a lot of hours trying to remove "My Wish List" and "Compare Products" blocks from Luma template. Besides, I need to change and remove some of the bottom links.</p>
<p>I cannot find where to modify. Can you help me, please?</p>
<p>Thanks</p>
| <magento2><magento-2.0> | 2016-01-08 01:39:49 | HQ |
34,668,429 | Count the difference in sql result | [enter image description here][1]
[1]: http://i.stack.imgur.com/suHH7.jpg
I would like to get number that has different isreq but the same type. Anyone please. Thanks. | <sql><linq><linq-to-sql> | 2016-01-08 02:14:52 | LQ_EDIT |
34,668,678 | Having trouble writing a main method for my class | <p>So im writing a method for my computer science class in which im trying to make a kinda like walking path thing. What i want to do is test the methods where the isLevelSegment part will return true if the difference between the maximum and minimum elevation in the walking path segment is less than or equal to ten meters and the isDifficult method is trying to see if there are 3 or more elevation changes in a path ( elevation changes are at least 30 meters up or down ). All my code is written [ idk if its correct or not, i think it is ] and basically and idk why im having a really hard time writing the main method to test it. Help?</p>
<p>public class Lab11 {</p>
<pre><code>public class WalkingPath
{
private int[] markers;
public boolean isLevelSegment (int start, int end )
{
int min = 1;
int max = 0;
for (int i = start; i<= end ; i ++)
{
if (markers[i] > max)
max = markers[i];
if (markers[i] < min || min == -1)
min = markers [i];
}
if ((max - min) <= 10)
return true;
else
return false;
}
public boolean isDifficult ()
{
int changes = 0;
for ( int i = 1 ; i< markers.length ; i ++)
{
if ((markers[i] - markers [i - 1]) >= 30)
changes ++;
}
if (changes >= 3)
return true;
else
return false;
}
}
}
</code></pre>
| <java> | 2016-01-08 02:46:34 | LQ_CLOSE |
34,668,878 | should i use `return` in Promise? | <pre><code>function saveToTheDb(value) {
return new Promise(function(resolve, reject) {
db.values.insert(value, function(err, user) { // remember error first ;)
if (err) {
return reject(err); // don't forget to return here
}
resolve(user);
})
}
}
</code></pre>
<p>Here is the code which i see from <a href="https://blog.risingstack.com/asynchronous-javascript/" rel="noreferrer">here</a>.
i am confused about <code>return</code> keyword.</p>
<p>For <code>resolve(user);</code>, do i need <code>return</code>?</p>
<p>For <code>reject(user);</code>, do i need <code>return</code>?</p>
| <node.js><promise> | 2016-01-08 03:06:37 | HQ |
34,669,501 | How did Neil Patel make the text on http://www.quicksprout.com/pro dynamically insert the cirt name into the HTML? | <p>This is an awesome way to appeal to folks from the city that they are browsing from. Is this some kind of JS technique? Would love a link to an example or if it already exists on GitHub? Sorry for the newbie question--I'm new to front-end dev.</p>
<p>Screenshot:</p>
<p><a href="http://i.stack.imgur.com/sCWqD.png" rel="nofollow">Quicksprout site:</a></p>
| <javascript><html><css><node.js> | 2016-01-08 04:26:39 | LQ_CLOSE |
34,669,611 | An error while submitting app to app store "ERROR ITMS-90455" | <p>This error show up when I am submitting the app to the store.What I have done is I have re-create the watch kit after I found that my project doesn't need to have glance interface.I have remove the target and old file.It have no problem when I execute on the device.</p>
<p>Error ITMS-90455: "Invalid WatchKit App Bundle.The value '2.1' for MinimunOSVersion key in info.plist in bundle 'appname.watchkitapp'is not supported."</p>
| <ios><app-store><watchos-2> | 2016-01-08 04:39:39 | LQ_CLOSE |
34,669,632 | Trying to ping linux vm hosted on azure does not work | <p>As title, how can I ping my machine to do some basic network testing? I have created a new VM but pinging it's public address returns request timeout.</p>
| <linux><azure><virtual-machine><ping><icmp> | 2016-01-08 04:41:16 | LQ_CLOSE |
34,669,824 | Flask app context for sqlalchemy | <p>I am working on a small rest api in flask. Api has route that registers a request and spawn separate thread to run in background. Here is the code:</p>
<pre><code>def dostuff(scriptname):
new_thread = threading.Thread(target=executescript,args=(scriptname,))
new_thread.start()
</code></pre>
<p>Thread starts but it errors out when I try to insert into db from executescript function. It complains about db object not registered with the app.</p>
<p>I am dynamically creating my app (with api as Blueprint).</p>
<p>Here is the structure of the app</p>
<pre><code>-run.py ## runner script
-config
-development.py
-prod.py
-app
-__init__.py
- auth.py
- api_v1
- __init__.py
- routes.py
- models.py
</code></pre>
<p>here is my runner script <code>run.py</code> :</p>
<pre><code>from app import create_app, db
if __name__ == '__main__':
app = create_app(os.environ.get('FLASK_CONFIG', 'development'))
with app.app_context():
db.create_all()
app.run()
</code></pre>
<p>Here is the code from <code>app/__init__.py</code> which creates the app:</p>
<pre><code>from flask import Flask, jsonify, g
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app(config_name):
"""Create an application instance."""
app = Flask(__name__)
# apply configuration
cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
app.config.from_pyfile(cfg)
# initialize extensions
db.init_app(app)
# register blueprints
from .api_v1 import api as api_blueprint
app.register_blueprint(api_blueprint, url_prefix='/api/')
return app
</code></pre>
<p>All I need to know is how do I extend app context in <code>routes.py</code>. I can not import app there directly and if I do the following, I get <code>RuntimeError: working outside of application context</code></p>
<pre><code>def executescript(scriptname):
with current_app.app_context():
test_run = Testrun(pid=989, exit_status=988,comments="Test TestStarted")
db.session.add(test_run)
db.session.commit()
</code></pre>
| <python><flask><flask-sqlalchemy><flask-restful> | 2016-01-08 05:01:21 | HQ |
34,669,977 | How to use annotation style used on The Atlantic's article, "The Host" by David Foster Wallace | <p><a href="https://38.media.tumblr.com/e35167d2556a8a6416ae68f9b6c2b514/tumblr_inline_notlshs8W31qz6f4b_540.gif" rel="nofollow">This is what I want</a> to replicate on my website for students. I am new to coding and I have tried to copy, paste a chunk of the source code, but nothing seems to work. </p>
<p><a href="http://www.theatlantic.com/magazine/archive/2005/04/host/303812/#annotation1" rel="nofollow">Here is a link to the article itself</a>. </p>
<p>Any help is appreciated. If this is considered spam, my apologies. </p>
| <html><css> | 2016-01-08 05:15:15 | LQ_CLOSE |
34,670,533 | Wordpress REST API (wp-api) 404 Error | <p>I have been using the Wordpress REST plugin WP-API for months now while developing locally with XAMPP. I recently migrated my site to an EC2 instance and everything is working fine <strong>except</strong> I now get a 404 with the following message whenever I try to access any endpoint on the API:</p>
<blockquote>
<p>The requested URL /wordpress/wp-json/ was not found on this server</p>
</blockquote>
<p><strong>Pretty permalinks are enabled</strong> with the following structure <code>http://.../wordpress/sample-post/</code> which works fine when navigating to a specific post in the browser.</p>
<p>Here are some details about my setup:</p>
<ul>
<li>Wordpress 4.4.1
<ul>
<li><strong>Not a Multisite</strong></li>
</ul></li>
<li>WP REST API plugin 2.0-beta9</li>
<li>Apache 2.2.22</li>
<li>Ubuntu 12.04.5</li>
</ul>
<p>Any help would be greatly appreciated as I have gone through SO and the WP Support forums for several hours and am out of ideas. Thank you!</p>
| <wordpress><wp-api><wordpress-rest-api> | 2016-01-08 06:08:21 | HQ |
34,670,698 | How to delete files older than 5 days using only regular expression | <p>How to delete files older than 5 days based on current date.</p>
<p>My File names are like that:</p>
<pre><code>2016-01-01 Normal.csv
2016-01-02 Normal.csv
2016-01-03 Normal.csv
2016-01-04 Normal.csv
2016-01-05 Normal.csv
2016-01-06 Normal.csv
2016-01-07 Normal.csv
</code></pre>
<p>Every day one new file in coming into that folder. I want to delete older than 5 days file.</p>
| <regex> | 2016-01-08 06:20:46 | LQ_CLOSE |
34,670,901 | In C#, when does Type.FullName return null? | <p>The <a href="https://msdn.microsoft.com/en-us/library/system.type.fullname(v=vs.110).aspx">MSDN for Type.FullName</a> says that this property return</p>
<blockquote>
<p><strong>null</strong> if the current instance represents a generic type parameter, an array type, pointer type, or <strong>byref</strong>type based on a type parameter, or a generic type that is not a generic type definition but contains unresolved type parameters.</p>
</blockquote>
<p>I count five cases, and I find each one more unclear than the last. Here is my attempt to construct examples of each case.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication {
public static class Program {
public static void Main(string[] args) {
GenericTypeParameter();
ArrayType();
PointerType();
ByRefTypeBasedOnTypeParameter();
NongenericTypeDefinitionWithUnresolvedTypeParameters();
Console.ReadKey();
}
public static void GenericTypeParameter() {
var type = typeof(IEnumerable<>)
.GetGenericArguments()
.First();
PrintFullName("Generic type parameter", type);
}
public static void ArrayType() {
var type = typeof(object[]);
PrintFullName("Array type", type);
}
public static void PointerType() {
var type = typeof(int*);
PrintFullName("Pointer type", type);
}
public static void ByRefTypeBasedOnTypeParameter() {
var type = null;
PrintFullName("ByRef type based on type parameter", type);
}
private static void NongenericTypeDefinitionWithUnresolvedTypeParameters() {
var type = null;
PrintFullName("Nongeneric type definition with unresolved type parameters", type);
}
public static void PrintFullName(string name, Type type) {
Console.WriteLine(name + ":");
Console.WriteLine("--Name: " + type.Name);
Console.WriteLine("--FullName: " + (type.FullName ?? "null"));
Console.WriteLine();
}
}
}
</code></pre>
<p>Which has this output.</p>
<pre><code>Generic type parameter:
--Name: T
--FullName: null
Array type:
--Name: Object[]
--FullName: System.Object[]
Pointer type:
--Name: Int32*
--FullName: System.Int32*
ByRef type based on type parameter:
--Name: Program
--FullName: ConsoleApplication.Program
Nongeneric type definition with unresolved type parameters:
--Name: Program
--FullName: ConsoleApplication.Program
</code></pre>
<p>I am only one for five with two "blanks".</p>
<h2>Question</h2>
<blockquote>
<p>Can someone modify my code to give simple examples of each way in which Type.FullName can be null?</p>
</blockquote>
| <c#><arrays><pointers><generics><types> | 2016-01-08 06:37:39 | HQ |
34,671,217 | In Flask, What is request.args and how is it used? | <p>I'm new in Flask. I can't understand how <code>request.args</code> is used. I read somewhere that it is used to return values of query string[correct me if I'm wrong]. And how many parameters <code>request.args.get()</code> takes.
I know that when I have to store submitted form data, I can use</p>
<pre><code>fname = request.form.get("firstname")
</code></pre>
<p>Here, only one parameter is passed.</p>
<p>Consider this code. Pagination has also been done in this code.</p>
<pre><code>@app.route("/")
def home():
cnx = db_connect()
cur = cnx.cursor()
output = []
page = request.args.get('page', 1)
try:
page = int(page)
skip = (page-1)*4
except:
abort(404)
stmt_select = "select * from posts limit %s, 4;"
values=[skip]
cur.execute(stmt_select,values)
x=cur.fetchall()
for row in reversed(x):
data = {
"uid":row[0],
"pid":row[1],
"subject":row[2],
"post_content":row[3],
"date":datetime.fromtimestamp(row[4]),
}
output.append(data)
next = page + 1
previous = page-1
if previous<1:
previous=1
return render_template("home.html", persons=output, next=next, previous=previous)
</code></pre>
<p>Here, <code>request.args.get()</code> takes two parameters. Please explain why it takes two parameters and what is the use of it.</p>
| <python><python-2.7><flask><pagination> | 2016-01-08 07:00:59 | HQ |
34,671,374 | I am new to openCV and javaCV and i am trying the following code but getting 'ImageGenerator' cannot be resolve. Anybody can help me out? | I have imported the required libraries of javacv and opencv. I need to import more libraries? if yes may i know the name? coz i have seacrhed it so much, but could not find it!!!
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.nio.ByteBuffer;
import javax.naming.Context;
enum Resolution {
NORMAL, HIGH
}
public class KinectCapture
{
private BufferedImage image = null;
private int imWidth, imHeight;
private int fps;
private boolean isReleased = true;
// when Kinect context has been released
// OpenNI
private Context context;
private ImageGenerator imageGen; **Here I am getting the error.**
public KinectCapture()
{ this(Resolution.NORMAL); }
public KinectCapture(Resolution res)
{ configOpenNI(res); }
private void configOpenNI(Resolution res)
// create context and image generator
{
try {
context = new Context();
// add the NITE Licence
License licence = new License("PrimeSense", "0KOIk2JeIBYClPWVnMoRKn5cdY4="); // vendor, key
context.addLicense(licence);
imageGen = ImageGenerator.create(context);
| <java><opencv><javacv><openni> | 2016-01-08 07:12:30 | LQ_EDIT |
34,672,035 | Replace sting with substing with regular expression | I am not good in regular expression please help to solve this problem. its urgent that's why I can't study more about it.
Problem :
If I have a sting like this `100,000` some digits with `,` followed by some other digits. I need to replace all digits so that the sting become `100`.
I Have to user 'replace()' function so please provide the expression.
var str = "1200,00";
str.replace("Expression");// Need this.
Thanks In advance.
| <javascript> | 2016-01-08 07:54:50 | LQ_EDIT |
34,672,248 | Let's Encrypt Failing DVSNI Challenge | <p>I'm trying to configure <a href="https://letsencrypt.org/">Let's Encrypt certificates</a> on a server that is publically accessible. Originally, the server was hiding behind a router, but I have since forwarded ports 80 and 443.</p>
<p>The certificate seems to have completed a majority of the install process, but fails with the message: <code>Failed to connect to host for DVSNI challenge</code>.</p>
<p>Full stack trace:</p>
<pre><code>Updating letsencrypt and virtual environment dependencies......
Requesting root privileges to run with virtualenv: sudo /bin/letsencrypt certonly --standalone -d example.net -d www.example.net
Failed authorization procedure. example.net (tls-sni-01): urn:acme:error:connection :: The server could not connect to the client to verify the domain :: Failed to connect to host for DVSNI challenge
IMPORTANT NOTES:
- The following 'urn:acme:error:connection' errors were reported by
the server:
Domains: example.net
Error: The server could not connect to the client to verify the
domain
</code></pre>
<p>Any support would be greatly appreciated!</p>
<p>I looked around elsewhere for a solution and haven't had much luck. Most other similar situations were resolved by forwarding port 443, but I am certain this port is already forwarded and open, albeit no service is currently running on it.</p>
<p>It shouldn't make a difference, but I'm trying to configure this certificate for use with Node JS on a Raspberry Pi.</p>
| <ssl-certificate><lets-encrypt> | 2016-01-08 08:09:31 | HQ |
34,672,258 | NSDictionary EXC_BAD_ACCESS | I have the following code:
NSString * client_type = @"client_credentials";
@implementation OauthObject
- (NSDictionary*) getParamsCredintion{
return [[NSDictionary alloc] initWithObjectsAndKeys:client_id, @"client_id", client_secret, @"client_secret", client_type, "@client_credentials", nil];
}
When i try to init NSDictionary with `client_type` key I get error:
`NSDictionary EXC_BAD_ACCESS`
| <ios><objective-c><xcode7> | 2016-01-08 08:10:04 | LQ_EDIT |
34,672,361 | how to avoid java.util.zip.ZipException in android studio at build time | Do not suggest to clean build or ./gredlew clean solution already tried a lot.
I simply want to avoid this error without excluding any jar file.
Error details
com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: android/support/v7/cardview/BuildConfig.class | <java><android> | 2016-01-08 08:17:08 | LQ_EDIT |
34,673,361 | SQL query: How to join two different tables in one query | i have two tables grades and scholars.
grades has fields: id, subject_code, subject_description,midterm, final, and final_remarks
AND
scholars has fields:id, Id Number, Lastname,Firstname, Middlename ,School, Year, Semester, Course,Action
how can i join them? i wanna get the subject_code, subject_description,midterm, final, and final_remarks from grades and fullname from scholars?
THANK YOU!PLEASE HELP ME WITH THIS. | <php><sql> | 2016-01-08 09:21:00 | LQ_EDIT |
34,673,396 | What does the standard Keras model output mean? What is epoch and loss in Keras? | <p>I have just built my first model using Keras and this is the output. It looks like the standard output you get after building any Keras artificial neural network. Even after looking in the documentation, I do not fully understand what the epoch is and what the loss is which is printed in the output.</p>
<p><strong>What is epoch and loss in Keras?</strong> </p>
<p>(I know it's probably an extremely basic question, but I couldn't seem to locate the answer online, and if the answer is really that hard to glean from the documentation I thought others would have the same question and thus decided to post it here.)</p>
<pre><code>Epoch 1/20
1213/1213 [==============================] - 0s - loss: 0.1760
Epoch 2/20
1213/1213 [==============================] - 0s - loss: 0.1840
Epoch 3/20
1213/1213 [==============================] - 0s - loss: 0.1816
Epoch 4/20
1213/1213 [==============================] - 0s - loss: 0.1915
Epoch 5/20
1213/1213 [==============================] - 0s - loss: 0.1928
Epoch 6/20
1213/1213 [==============================] - 0s - loss: 0.1964
Epoch 7/20
1213/1213 [==============================] - 0s - loss: 0.1948
Epoch 8/20
1213/1213 [==============================] - 0s - loss: 0.1971
Epoch 9/20
1213/1213 [==============================] - 0s - loss: 0.1899
Epoch 10/20
1213/1213 [==============================] - 0s - loss: 0.1957
Epoch 11/20
1213/1213 [==============================] - 0s - loss: 0.1923
Epoch 12/20
1213/1213 [==============================] - 0s - loss: 0.1910
Epoch 13/20
1213/1213 [==============================] - 0s - loss: 0.2104
Epoch 14/20
1213/1213 [==============================] - 0s - loss: 0.1976
Epoch 15/20
1213/1213 [==============================] - 0s - loss: 0.1979
Epoch 16/20
1213/1213 [==============================] - 0s - loss: 0.2036
Epoch 17/20
1213/1213 [==============================] - 0s - loss: 0.2019
Epoch 18/20
1213/1213 [==============================] - 0s - loss: 0.1978
Epoch 19/20
1213/1213 [==============================] - 0s - loss: 0.1954
Epoch 20/20
1213/1213 [==============================] - 0s - loss: 0.1949
</code></pre>
| <python><machine-learning><neural-network><keras><data-science> | 2016-01-08 09:22:31 | HQ |
34,673,736 | Split one file into multiple based on keyword | <p>I want to split my single file into two file when a particular keyword comes in the file.. Consider that I have whole content in single line. So it is not possible to count line number and then split it.</p>
<p>Thanks in advance for help </p>
| <batch-file><cmd> | 2016-01-08 09:39:38 | LQ_CLOSE |
34,675,045 | Should subscribeOn and observeOn only be invoked by the final subscriber? | <p>The <a href="http://www.introtorx.com/content/v1.0.10621.0/15_SchedulingAndThreading.html">Scheduling and Threading</a> section of <em>Intro to Rx</em> says that </p>
<blockquote>
<p>the use of SubscribeOn and ObserveOn should only be invoked by the final subscriber</p>
</blockquote>
<p>It also says that in an UI application, the presentation layer, which is normally the final subscriber, should be the one to invoke these methods.</p>
<p>I am wondering if the advice is solid, since I see some situations in which this is not convenient:</p>
<ol>
<li>For starters, I don't believe that the presentation layer should decide where an Observable coming from the data layer should be subscribed. In my opinion, the presentation layer should be unaware if the data is coming from a database, from a REST API, or from memory. For this reason, it's convenient for the data layer to call <code>subscribeOn()</code> before returning the Observable, passing the IO Scheduler or the immediate Scheduler as convenient.</li>
<li>If the presentation layer gets the Observable from some service or use case (which in turn gets it from the data layer) and this service decides that it needs to process the stream in some computation Scheduler, why should the presentation layer care about this?</li>
<li>What about a stream that is originally coming from the UI, so it needs to be subscribed in the UI thread. Then it will be sent to some service to do some work and finally come back to the presentation layer to be observed in the UI thread. That would require the UI stream to be <code>subscribeOn()</code> the UI Scheduler, then <code>observeOn()</code> some other Scheduler, and finally <code>observeOn()</code> the UI Scheduler. In this case, being able to invoke <code>subscribeOn()</code> and <code>observeOn()</code> only in the final subscriber would mean that the stream can only be processed in the UI thread.</li>
</ol>
<p>Is there some good reason why I should sacrifice the architecture of my application and ignore Rx's ability to easily switch threads by invoking these two methods only by the final subscriber?</p>
| <system.reactive><reactive-programming><rx-java><reactivex> | 2016-01-08 10:43:06 | HQ |
34,675,914 | Using variables in Gradle build script | <p>I am using Gradle in my project. I have a task for doing some extra configuration with my war. I need to build a string to use in my task like, lets say I have:</p>
<pre><code>task extraStuff{
doStuff 'org.springframework:spring-web:3.0.6.RELEASE@war'
}
</code></pre>
<p>This works fine. What I need to do is define version (actually already defined in properties file) and use this in the task like:</p>
<pre><code>springVersion=3.0.6.RELEASE
task extraStuff{
doStuff 'org.springframework:spring-web:${springVersion}@war'
}
</code></pre>
<p>My problem is spring version is not recognised as variable. So how can I pass it inside the string?</p>
| <groovy><gradle> | 2016-01-08 11:24:26 | HQ |
34,676,984 | cannot export const arrow function | <p>new to ES6, I was trying to make a React simple functional component like this</p>
<pre><code>// ./Todo.jsx
export default const Todo = ({
todos,
onTodoClick,
}) => (
<ul>
{todos.map( (todo, i) =>
<li key = {i}
onClick = {() => onTodoClick(i) }
style = {{textDecoration: todo.completed ? 'line-through': 'none' }}
>
{todo.text}
</li>
)}
</ul>
)
</code></pre>
<p>But </p>
<pre><code>// Another file
import Todo from './Todos.jsx';
console.log(Todo) // undefined
</code></pre>
<p>did not yield the arrow function.</p>
<p>but if I leave off the "const todo =" part in the export link, like so</p>
<pre><code> export default ({
todos,
onTodoClick,
}) => (...)
</code></pre>
<p>It gets successfully imported. </p>
<p>Why is that?</p>
| <ecmascript-6> | 2016-01-08 12:17:59 | HQ |
34,677,194 | have to make algo of this functiionality in php | i have a string -
<b>Hello, How Are You.</b>
i want this output ->
<b>eHllo, oHw rAe oYu.</b>
it doesnot matter whether there is any special character , i just want to reverse the two alphabets cosecutively in a word. | <php> | 2016-01-08 12:30:08 | LQ_EDIT |
34,677,278 | Can someone pls help me solve this issue | <p>Create a function fizzBuzz to return 'Fizz', 'Buzz', 'FizzBuzz', or the argument it receives, all depending on the argument of the function, a number that is divisible by, 3, 5, or both 3 and 5, respectively.</p>
<p>When the number is not divisible by 3 or 5, the number itself should be returned</p>
| <javascript> | 2016-01-08 12:34:58 | LQ_CLOSE |
34,677,342 | trying to create td with rowspan |
trying to create td with rowspan
i have to create a table with 6 columns from the second column the user has to set the rowspan
for example
column 2 row1 column3 row1
column 2 row2 column3 row1
column 2 row3 column3 row1
function addRow() {
var myName = document.getElementById("namez");
var age = document.getElementById("age");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= '<input type="text" name="txtbox1[]" />';
row.insertCell(2).innerHTML= '<input type="text" name="txtbox2[]" />';
var td3 = row.insertCell(3).innerHTML= '<input type="text" name="txtbox3" />';
td3.setAttribute('rowSpan', '2'); | <javascript><html> | 2016-01-08 12:39:25 | LQ_EDIT |
34,677,343 | Accessing same-type inactive member in unions | <p>I have something like this:</p>
<pre><code>union DataXYZ
{
struct complex_t
{
float real, imag;
} complex;
struct vector_t
{
float magnitude, phase;
} vector;
};
</code></pre>
<p>I have some vectors of these, being general-purpose workspace memory, where I use the fields accordingly after the semantic context. </p>
<p>I know it's undefined behaviour to read a field in a union, when the last active member was another field (and type?). Does this matter when the types and layout match exactly?</p>
<p>I've been commenting on some other similar questions, asking for references that guarantee the behaviour, but nothing came up yet - hence this question.</p>
| <c++><undefined-behavior><unions> | 2016-01-08 12:39:31 | HQ |
34,678,093 | Replacing letters from input with a changing item from a list | In python, I'm trying to write a python script that replaces each letter with another letter from a 3 item long **list**. I am doing this for each letter of the alphabet, so use the `replace` method.
For example:
`list_a = "B,C,D" % `
`$ what is your message? > aaaa`
`$ This is your encrypted message: BCDB`
Thanks a lot!!!! | <python><list><python-3.x><encryption> | 2016-01-08 13:19:54 | LQ_EDIT |
34,678,374 | JVM versus C++ compiler | <p>I have a query in which I cannot give a satisfactory answer. Java is notorious for its independence over machine architectures grace to JVM. I 've understood the following: </p>
<ul>
<li>Different JVM implementations are sitting on different machines as to produce the appropriate output (different for any different architecture) from the same input(.class files).</li>
</ul>
<p>Let's now consider C++. Why not to do the same with Java? Namely, implement different C++ compiler versions for different architectures, feed them with the same source and make every compiler produce the appropriate output; just make C++ compiler to mimic JVM! </p>
<p><em>This is my query since I cannot understand why Java is unique in that...</em></p>
| <java><c++><jvm> | 2016-01-08 13:35:48 | LQ_CLOSE |
34,678,558 | C# "content acceptance | Hi you know I can't make my character move in unity, because c# doesn't accet word "velocity". Help me solve this problem please.
public class MarioController : MonoBehaviour
{
public float maxSpeed=10f;
bool facingRight=true;
void Start ()
{}
void FixedUpdate ()
{
float move = Input.GetAxis ("Horizontal");
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
if (move > 0 && !facingRight)
Flip ();
else if (move < 0 && facingRight)
Flip ();
}
void Flip ()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
| <c#><unity3d> | 2016-01-08 13:45:30 | LQ_EDIT |
34,678,828 | Get the next row of a dataframe in r programming | I am working on a r programming project..
I have a dataframe (df) with about 790 observations in. I am trying to extract certain rows from the dataframe. The only simularity with the row i am trying to extract with the row above, which are all named S_NAME:
<LI>1 cat </li>
<li>2 hat </li>
<li>3 S_NAME </li>
<li>4 tin </li>
<li>5 sin </li>
<li>6 S_NAME </li>
<li>7 foo </li>
<li>8 sin </li>
<li>9 S_NAME </li>
<li>10 tinn </li>
So for example, I would want to extract row 4,7 and 10 which all follow S_NAME
I am unsure of how to do this, any help will be great thanks. I know i have tagged python, although that code might help me understand.
Thanks
| <python><r><dataframe> | 2016-01-08 13:59:37 | LQ_EDIT |
34,679,013 | Is possible to modify arcanist/differential template? | <p>I'm trying to configure a phabricator instance, and I find that change the arcanist default template when we use <code>arc diff</code> can be very useful for the team. </p>
<p>Actually the template contains this text: </p>
<pre><code><<Replace this line with your Revision Title>>
Summary:
Test Plan:
Reviewers:
Subscribers:
# Tip: Write "Fixes T123" in your summary to automatically close the
# corresponding task when this change lands.
# NEW DIFFERENTIAL REVISION
# Describe the changes in this new revision.
#
# arc could not identify any existing revision in your working copy.
# If you intended to update an existing revision, use:
#
# $ arc diff --update <revision>
</code></pre>
<p>I'm googling to find any way to change this default template, but I can't find it... </p>
<p>There is any way to "personalize" this template?</p>
| <phabricator><arcanist> | 2016-01-08 14:09:07 | HQ |
34,680,450 | `this` is undefined in expressJS route handler | <p><strong>groups.js</strong></p>
<pre><code>class groupsCtrl {
constructor() {
this.info = "test";
}
get(res, req) {
console.log("LOG ! ", JSON.stringify(this));
}
}
module.exports = new groupsCtrl(); //singleton
</code></pre>
<p><strong>routes.js</strong></p>
<pre><code>var express = require('express');
var router = express.Router();
var groupsCtrl = require('controllers/api_admin/groups.js');
router.get('/groups/', groupsCtrl.get);
</code></pre>
<p>This logs <code>LOG ! undefined</code></p>
<p>How can I have access to <code>this</code> in my controller class ?</p>
| <javascript><node.js><express> | 2016-01-08 15:26:33 | HQ |
34,680,836 | NGINX configuration for Rails 5 ActionCable with puma | <p>I am using Jelastic for my development environment (not yet in production).
My application is running with Unicorn but I discovered websockets with ActionCable and integrated it in my application.</p>
<p>Everything is working fine in local, but when deploying to my Jelastic environment (with the default NGINX/Unicorn configuration), I am getting this message in my javascript console and I see nothing in my access log</p>
<pre><code>WebSocket connection to 'ws://dev.myapp.com:8080/' failed: WebSocket is closed before the connection is established.
</code></pre>
<p>I used to have on my local environment and I solved it by adding the needed ActionCable.server.config.allowed_request_origins in my config file. So I double-checked my development config for this and it is ok.</p>
<p>That's why I was wondering if there is something specific for NGINX config, else than what is explained on ActionCable git page </p>
<pre><code>bundle exec puma -p 28080 cable/config.ru
</code></pre>
<p>For my application, I followed everything from <a href="https://github.com/rails/rails/tree/master/actioncable">enter link description here</a> but nothing's mentioned about NGINX configuration</p>
<p>I know that websocket with ActionCable is quite new but I hope someone would be able to give me a lead on that</p>
<p>Many thanks</p>
| <nginx><jelastic><ruby-on-rails-5><actioncable> | 2016-01-08 15:45:45 | HQ |
34,681,072 | Xcode Objective C Yaw Pitch Roll | I'm trying to display the yaw pitch and roll of the device in a label. I cannot seem to get the values to display, it only shows a '...' where the numbers should be. This is my code, any help is greatly appreciated.
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController (){
}
@property (strong, nonatomic) CMMotionManager *motionManager;
@end
@implementation ViewController
@synthesize motionManager;
@synthesize roll;
@synthesize pitch;
@synthesize yaw;
@synthesize xLabel;
@synthesize yLabel;
@synthesize zLabel;
- (void)viewDidLoad {
[super viewDidLoad];
/** Do any additional setup after loading the view, typically from a nib.
UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
accelerometer.updateInterval = 1.0f/60.0f;
accelerometer.delegate = self;
**/
//motionManager = [[CMMotionManager alloc] init];
//motionManager.deviceMotionUpdateInterval = 1.0 / 60.0;
motionManager = [[CMMotionManager alloc] init];
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(doGyroUpdate) userInfo:nil repeats:YES];
//CMDeviceMotion *deviceMotion = motionManager.deviceMotion;
//CMAttitude *attitude = deviceMotion.attitude;
[motionManager startDeviceMotionUpdates];
}
-(void)doGyroUpdate
{
double x = motionManager.deviceMotion.attitude.roll*180/M_PI;
double y = motionManager.deviceMotion.attitude.pitch*180/M_PI;
double z = motionManager.deviceMotion.attitude.yaw*180/M_PI;
NSString *myString = [NSString stringWithFormat:@"%g", x];
xLabel.text = myString;
myString = [NSString stringWithFormat:@"%f", y];
yLabel.text = myString;
myString = [NSString stringWithFormat:@"%f", z];
zLabel.text = myString;
} | <ios><objective-c><uilabel> | 2016-01-08 15:57:18 | LQ_EDIT |
34,681,369 | Error - php propel init | I guys! I have a problem when I start my project with Propel.
I leave the error below, Thanks!
<!-- begin snippet: js hide: false -->
<!-- language: lang-html -->
Nicolass-MacBook-Pro:api Nico$ php propel init
Fatal error: Class 'Symfony\Component\Console\Helper\DialogHelper' not found in /Applications/XAMPP/xamppfiles/htdocs/rmanager/api/vendor/propel/propel/src/Propel/Generator/Command/Helper/DialogHelper.php on line 8
<!-- end snippet -->
| <php><symfony><propel> | 2016-01-08 16:11:28 | LQ_EDIT |
34,681,533 | Why wont my Excel functions execute? | <p>I am having problems with excel 2013, where none of my functions will execute rather the cell will just present my formula...
has any one ran into this problem?
it is for all functions</p>
| <excel> | 2016-01-08 16:20:04 | LQ_CLOSE |
34,682,035 | Cluster and Fork mode difference in PM2 | <p>I've searched a lot to figure out this question, but I didn't get clear explanation. Is there only one difference thing that clustered app can be scaled out and forked app cannot be?</p>
<p>PM2's public site explains Cluster mode can do <a href="http://pm2.keymetrics.io/docs/usage/cluster-mode/" rel="noreferrer">these feature</a> but no one says about pros of Fork mode (maybe, it can get <code>NODE_APP_INSTANCE</code> variable).</p>
<p>I feel like Cluster might be part of Fork because Fork seems like to be used in general. So, I guess Fork means just 'forked process' from the point of PM2 and Cluster means 'forked process that is able to be scaled out'. Then, why should I use Fork mode?</p>
| <node.js><pm2> | 2016-01-08 16:47:31 | HQ |
34,682,099 | How to call REST from jenkins workflow | <p>I wonder how to call REST API from a (groovy) Jenkins workflow script. I can execute "sh 'curl -X POST ...'" - it works, but building the request as a curl command is cumbersome and processing the response gets complicated. I'd prefer a native Groovy HTTP Client to program in groovy - which one should I start with? As the script is run in Jenkins, there is the step of copying all needed dependency jars to the groovy installation on Jenkins, so something light-weight would be appreciated.</p>
| <groovy><jenkins-workflow> | 2016-01-08 16:50:43 | HQ |
34,682,748 | return the int result of sql query to php echo? | A little help would be lifesaving. I have an sql query that works in phpMyAdmin and gives me the result i need.
When i build this query into a php statement i cant seem to access the result (an integer)
I literally need to echo the value, so i need to output for exanmple " your number is" result.
here is my query:
$sqlstatement = "SELECT (SELECT `embark` FROM info ORDER BY `index_no` DESC LIMIT 1)-(SELECT `embark` FROM info ORDER BY `index_no` ASC LIMIT 1)";
$sql_result = mysqli_query($connection, $sqlstatement) or die
(" Couldn't execute the SQL calculate disembark statement********");
If anyone can help i would really appreciate it
Scott | <php><mysql><phpmyadmin> | 2016-01-08 17:28:44 | LQ_EDIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.