title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
Could not find com.google.firebase:firebase-database:9.2.0
|
<p>I was trying to install new firebase database into my app, but it was failed with next error:</p>
<blockquote>
<p>Error:Could not find com.google.firebase:firebase-database:9.2.0. Required
by:
appName:app:unspecified</p>
</blockquote>
<p>than i clone official google example frome <a href="https://github.com/firebase/quickstart-android" rel="nofollow">here</a> and was trying to build database example, but i still get same error...</p>
<p>looks like this is because of some google error. am i right?
in other case, why it happens and how to fix this?</p>
| 2 |
C++ printf only appear in the end
|
<p>This is the program that I was trying to make to learn</p>
<p>the program works but the message "type the rectangle height" and "type the rectangle width" only appear when the program is over</p>
<pre><code>#include < stdio.h >
using namespace std;
float calculateArea(float a, float b)
{
return a * b;
}
float calculatePerimeter(float a, float b)
{
return 2*a + 2*b;
}
void showMessage(char *msg, float vlr)
{
printf("%s %5.2f", msg, vlr);
}
int main()
{
float height, width, area, perimeter;
printf("type the rectangle height");
scanf("%f%*c", &height);
printf("type the rectangle width");
scanf("%f%*c", &width);
area = calculateArea(height, width);
perimeter = calculatePerimeter(height, width);
showMessage("The area value is =", area);
showMessage("The perimeter value is =", perimeter);
return 0;
}
</code></pre>
| 2 |
Creating nested array in firebase Object
|
<p>I want to push a value to a nested array which is stored in my firebase database. The target looks like this: </p>
<p><a href="https://i.stack.imgur.com/YG8tL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YG8tL.png" alt="rateData is the array i want to push new data"></a></p>
<p>I'm query the firebase database and receive snapshot. With this snapshot I want to store my changes. If i push the new value it creates me in firebase this: </p>
<p><a href="https://i.stack.imgur.com/F6AlC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F6AlC.png" alt="Firebase after push"></a></p>
<p>How can I avoid the unique FB id and replace it with a normal index counter? </p>
<p>My code from the angular service:</p>
<pre><code> //Save StarBewertung on Mamis
this.saveStarOnMami = function (data) {
var ref = new Firebase("https://incandescent-heat-5149.firebaseio.com/contacts")
var query = ref.orderByChild("id").equalTo(data).on("child_added", function(snapshot) {
if( snapshot.val() === null ) {
/* does not exist */
} else {
//snapshot.ref().update({"phone_fixed": '123'});
snapshot.ref().child('rateData').push(1);
}
});
}
</code></pre>
<p>Is there a way to get the snapshot as an $firebaseobject, manipulate it, and then save it to the Firebase DB with $save? </p>
<p>Thanks...</p>
| 2 |
Maximum sum in a non-binary tree in Python
|
<p>I have a non-binary tree and each node of that tree has a value. I would like to get the maximum sum available.
For example:</p>
<pre><code> 10
9 8 7
1 2 5 5 15
</code></pre>
<p>The return would be 10+7+15=32
I know how to do this if the tree was binary, but what if the tree has n branches?
This code is the binary one taken from the first answer of this question: <a href="https://stackoverflow.com/questions/25953446/find-the-maximum-sum-of-a-tree-in-python">Find the maximum sum of a tree in python</a></p>
| 2 |
Database not persisting in docker
|
<p>I know I am missing something very basic here. I have see some of the older questions on persisting data using docker, but I think I am following the most recent documentation found <a href="https://docs.docker.com/compose/rails/" rel="nofollow">here</a>.
I have a rails app that I am trying to run in docker. It runs fine but every time I start it up i get <code>ActiveRecord::NoDatabaseError</code>. After I create the database and migrate it, the app runs fine, until I shut it down and restart it.</p>
<p>here is my docker file:</p>
<pre><code>FROM ruby:2.3.0
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
ENV RAILS_ROOT /ourlatitude
RUN mkdir -p $RAILS_ROOT/tmp/pids
WORKDIR $RAILS_ROOT
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN gem install bundler
RUN bundle install
COPY . .
</code></pre>
<p>and here is my docker-compose.yml file</p>
<pre><code>version: '2'
services:
db:
image: postgres:9.4.5
app:
build: .
environment:
RAILS_ENV: $RAILS_ENV
ports:
- "3000:3000"
command: bundle exec rails s -b 0.0.0.0
volumes:
- .:/ourlatitude/database
depends_on:
- db
</code></pre>
<p>the basic flow I am following is this:</p>
<pre><code>export RAILS_ENV=development
docker-compose build
docker-compose up
docker-compose run app rake db:create
docker-compose run app rake db:migrate
</code></pre>
<p>at this point the app will be running fine</p>
<p>but then I do this</p>
<pre><code>docker-compose down
docker-compose up
</code></pre>
<p>and then I am back to the <code>ActiveRecord::NoDatabaseError</code></p>
<p>So as I said, I think I am missing something very basic.</p>
| 2 |
Count rows and copy number
|
<p>I have an excel workbook with multiple sheets with tables in the range <strong>from A to L</strong>. I want to count the rows and paste the result into a summary sheet. </p>
<p>For example: </p>
<p>Sheet2 has 3 rows. I want to copy the number of rows into sheet1 C3</p>
<p>Sheet3 has 9 rows. I want to copy the number of rows into sheet1 C4</p>
<p>Sheet4 has 5 rows. I want to copy the number of rows into sheet1 C5</p>
<p>and so on through all my sheets. (I have over 3000 sheets)</p>
<p>I am new to macro in excel so I would appreciete any help, thanks so much.</p>
| 2 |
Installing Tensorflow on Mac for PyPy
|
<p>I am able to install tensorflow for python using pip just fine but when I try and install tensorflow for pypy using:</p>
<pre><code>pypy -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0-py2-none-any.whl
</code></pre>
<p>I get error messages about how pypy doesn't play well with numpy. I already have numpy installed for pypy and it workes fine. I can do </p>
<pre><code>pypy
>>>>import numpy
</code></pre>
<p>without any errors.</p>
<p>What am I doing wrong here? Is there a way to try and install tensorflow without it trying to install numpy? Has anyone done this before?</p>
| 2 |
Compare files in git remote vs local
|
<p>I am new to Git and I have tried playing around with a few features.</p>
<p>What does</p>
<pre><code>git diff HEAD...origin master
</code></pre>
<p>vs.</p>
<pre><code>git diff origin master
</code></pre>
<p>do?</p>
<p>They seem to give me entirely different results.</p>
<p>Perhaps it's good to note that I do have a <code>origin/master</code> that is different from <code>origin master</code>.</p>
<p>Shouldn't it all mean the same thing?</p>
| 2 |
How can I show and hide dynamic divs triggered by dynamic buttons in Angular 2
|
<p>I got this work using a click event and some plain javascript but I'm sure there is a better way for this.</p>
<p>I'm generating some dynamic rows and corresponding dynamic buttons using ngFor.</p>
<p>They look like this:</p>
<pre><code><div *ngFor="let section of data.order?.sections" id="{{section.class}}Detail" class="{{section.name | lowercase | removeAmpersand | removeSpaces }}">Random Text Here</div>
</code></pre>
<p>And then elsewhere on the page there is a list of anchor tags also generated using an ngFor:</p>
<pre><code><a (click)="showDetails($event)" id="{{section.name | lowercase | removeAmpersand | removeSpaces }}"><span class="icomoon icomoon-eye"></span> Detail/a>
</code></pre>
<p>My question is, what is the preferred way that I could show and hide the divs? Each of the divs starts off with a css property of <code>display: none</code> and I was hoping to just toggle that. Instead I'm just using the click event to run a function that gets the div id and then I have some pure javascript that looks like this:</p>
<pre><code>myDiv.style.display = myDiv.style.display === '' ? 'block' : '';
</code></pre>
<p>What should I do that would be the preferred method?</p>
| 2 |
Metadata lost when saving photo using PHPhotoLibrary
|
<p>I used to save a photo to the camera roll using ALAssetLibrary's writeImageToSavedPhotosAlbum:metadata:completionBlock, but that is now deprecated in iOS 9.0, so I switched to PHPhotoLibrary's version which looks like</p>
<pre><code>[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:image];
}completionHandler:^(BOOL success, NSError *error) {
if (success){
NSLog(@"Image Saved!");
} else {
NSLog(@"Error: %@", error);
}
}];
</code></pre>
<p>This saves the image itself, but loses the metadata (exif ect) and I can't find any fixes of how to preserve this data when I save the photo. Any help would be appreciated. TYIA</p>
| 2 |
Elasticsearch DeleteByQuery not working, getting 400 bad request
|
<p>I have the following Nest query to delete all the matching documents, quite straight forward but I am getting 400 bad request on it.</p>
<pre><code> var client = new ElasticClient();
var request = new DeleteByQueryRequest<Type>("my-index")
{
Query = new QueryContainer(
new TermQuery
{
Field = "versionId",
Value = "ea8e517b-c2e3-4dfe-8e49-edc8bda67bad"
}
)
};
var response = client.DeleteByQuery(request);
Assert.IsTrue(response.IsValid);
</code></pre>
<p>Thanks for any help.</p>
<p>---------------Update---------------</p>
<p>Request Body</p>
<pre><code>{"query":{"term":{"versionId":{"value":"ea8e517b-c2e3-4dfe-8e49-edc8bda67bad"}}}}
</code></pre>
<p>Response Body</p>
<pre><code>{"took":0,"timed_out":false,"_indices":{"_all":{"found":0,"deleted":0,"missing":0,"failed":0}},"failures":[]}
</code></pre>
<p>Query in Sense plugin:</p>
<pre><code>GET /my-index/type/_search
{
"query": {
"match": {
"versionId": "ea8e517b-c2e3-4dfe-8e49-edc8bda67bad"
}
}
}
</code></pre>
<p>Query Response:</p>
<pre><code>{
"took": 3,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 116,
"max_score": 2.1220484,
"hits": []
...
}}
</code></pre>
<p>---------------NEST QUERY--------------</p>
<pre><code>DELETE http://localhost:9200/my-index/component/_query?pretty=true
{
"query": {
"term": {
"versionId": {
"value": "ea8e517b-c2e3-4dfe-8e49-edc8bda67bad"
}
}
}
}
Status: 200
{
"took" : 0,
"timed_out" : false,
"_indices" : {
"_all" : {
"found" : 0,
"deleted" : 0,
"missing" : 0,
"failed" : 0
}
},
"failures" : [ ]
}
</code></pre>
| 2 |
Counting Cells with date enter as MM/DD/YYYY, but formatted as Month-YY
|
<p>I have a document that shows users who have accounts for a company resource, and it shows their last login. The exported data into excel shows as Last Login (Column E) and the cell data is MM/DD/YYYY with a time stamp. Example: 4/15/2015 3:01:59 PM</p>
<p>I have formatted all the cells to read as Month-YY. So that example shows April-15.</p>
<p>I am trying to make a chart to show how many users last logged in by counting the dates. So say 10 people last logged in April-15, and 20 people in June-15.</p>
<p>I have this formula I am trying to use, Table1[Last Login] is column E.</p>
<p>=COUNTIF(Table1[Last Login],"<em>April-15</em>")</p>
<p>That returns 0.</p>
<p>The issue I am running into is the formula is looking at the data in the cell as 4/15/2015 3:01:59 PM, rather than what I formatted it to, April-15. I have a little VB experience, but its been a while since school.</p>
<p>Any help is much appreciated!</p>
| 2 |
textbox split text by number of characters
|
<p>I need to read 70 character chunks and send to a terminal emulator. I'm really not sure how to do this when substring
length, cannot be greater amount of data in string (microsoft generates error). The last line in the textbox is always less than 70.</p>
<p>Does anyone know of a better way to do this?</p>
<p>TextBox can accept 1000 characters with word wrap turned on.</p>
<pre><code>int startIndex = 0;
int slength = 70;
for (int i = 0; i < body.Text.Length; i += 70)
{
if(body.Text.Length < 70)
{
String substring1 = body.Text.Substring(startIndex, body.Text.Length);
CoreHelper.Instance.SendHostCommand("¤:5H¤NCCRMKS / " + body.Text, UIHelper.Instance.CurrentTEControl, true, true);
};
if (body.Text.Length > 70)
{
String substring1 = body.Text.Substring(startIndex, slength);
CoreHelper.Instance.SendHostCommand("¤:5H¤NCCRMKS / " + body.Text, UIHelper.Instance.CurrentTEControl, true, true);
};
}
</code></pre>
| 2 |
alternative to long list of nested ifelse statement with multiple conditions
|
<p>I have the following data frame</p>
<pre><code> structure(list(FY = c("2015-2016", "2015-2016", "2015-2016",
"2015-2016"), YEARMN = structure(c(2015.25, 2015.25, 2015.25,
2015.25), class = "yearmon"), BRAND = c("3M CAR CARE", "CAR CARE 3M",
"CAR CARE 3M", "CAR CARE 3M"), variable = structure(c(1L,
2L, 3L, 4L), .Label = c("IstWEEKRent", "IIndWEEKRent", "IIIrdWEEKRent",
"IVthWEEKRent", "mymonth"), class = "factor"), value = c("0",
"17500", "85000", "212500"), mymonth = c("Apr", "Apr", "Apr",
"Apr")), .Names = c("FY", "YEARMN", "BRAND", "variable", "value",
"mymonth"), row.names = c(NA, 4L), class = "data.frame")
</code></pre>
<p>The actual data frame looks like this:</p>
<pre><code> FY YEARMN BRAND variable value mymonth
1 2015-2016 Apr 2015 3M CAR CARE IstWEEKRent 0 Apr
2 2015-2016 Apr 2015 CAR CARE 3M IIndWEEKRent 17500 Apr
3 2015-2016 Apr 2015 CAR CARE 3M IIIrdWEEKRent 85000 Apr
4 2015-2016 Apr 2015 CAR CARE 3M IVthWEEKRent 212500 Apr
</code></pre>
<p>The my month column has months from Apr to Mar...and every month has 4 weeks in my dataset which is given in column variable. I am trying to create a week number for the FY Apr - Mar, starting from 1 to 48. I want to give week number 1 which matches the condition </p>
<pre><code>variable == "IstWeekRent" & mymonth == "Apr"
</code></pre>
<p>I used ifelse function to get this done...which works fine...but when I include the same into my shiny application I am getting the following error:</p>
<pre><code>Error in parse(file, keep.source = FALSE, srcfile = src, encoding = enc) :
contextstack overflow at line 2870
</code></pre>
<p>My current ifelse condition statement looks like this:</p>
<pre><code>trndR$weeks <- ifelse(trndR$mymonth == "Apr" & trndR$variable == "IstWEEKRent", 1,
ifelse(trndR$mymonth == "Apr" & trndR$variable == "IIndWEEKRent", 2,
ifelse(trndR$mymonth == "Apr" & trndR$variable == "IIIrdWEEKRent", 3,
ifelse(trndR$mymonth == "Apr" & trndR$variable == "IVthWEEKRent", 4,
ifelse(trndR$mymonth == "May" & trndR$variable == "IstWEEKRent", 5,
ifelse(trndR$mymonth == "May" & trndR$variable == "IIndWEEKRent", 6,
</code></pre>
<p><code>trndR</code> is the name of my df and the condition extends upto 48.</p>
<p>I figured out that I can have only upto 50 nested ifelse condition...but not quite not sure how to rectify this. I read about apply function but don't know how to use it in this case. </p>
| 2 |
Insert data into separate tables related by foreign keys
|
<p>I have a database with two tables:</p>
<p>posts: id(primary key, autoincrement), title_bg, title_en, body_bg, body_en, status, created, updated</p>
<p>postimage: id(primary key, auto increment), post_id, name</p>
<p>When I'm not using a foreign key, the form with multiple elements is working fine. It fills all the details for the post into the posts table and the multiple images are uploading into the postimage table, but they're not related, so the post_id field shows 0 value.</p>
<p>When I set the foreign key on phpMyAdmin with this query:</p>
<pre><code>ALTER TABLE `postimage` ADD FOREIGN KEY ( `post_id` ) REFERENCES `database_name`.`posts` ( `id` ) ON DELETE RESTRICT ON UPDATE RESTRICT ;
</code></pre>
<p>and when I create a new post, all the values are saved into the posts table, except the images into the second table. The postimage table is empty.</p>
<p>Here's my code:</p>
<pre><code> <?php
if(isset($_POST['submit'])) {
$title_bg = $_POST['title_bg'];
$title_en = $_POST['title_en'];
$body_bg = $_POST['body_bg'];
$body_en = $_POST['body_en'];
if(isset($_FILES['image'])) {
foreach($_FILES['image']['name'] as $key => $name) {
$image_tmp = $_FILES['image']['tmp_name'][$key];
move_uploaded_file($image_tmp, '../uploads/' . $name);
$query = "INSERT INTO postimage(name) ";
$query .= "VALUES('$name')";
$upload_images = mysqli_query($connection, $query);
}
}
$status = $_POST['status'];
$query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
$query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";
$create_post = mysqli_query($connection, $query);
header("Location: posts.php");
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-item">
<label for="title_bg">Post title BG</label>
<input type="text" name="title_bg">
</div>
<div class="form-item">
<label for="title_en">Post title EN</label>
<input type="text" name="title_en">
</div>
<div class="form-item">
<label for="body_bg">Post body BG</label>
<textarea id="editor" name="body_bg" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="body_en">Post body EN</label>
<textarea id="editor2" name="body_en" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="image">Image</label>
<input type="file" name="image[]" multiple>
</div>
<div class="form-item">
<label for="status">Post status</label>
<select name="status">
<option value="published">published</option>
<option value="draft">draft</option>
</select>
</div>
<div class="form-item">
<input type="submit" class="form-submit" name="submit" value="Submit">
</div>
</form>
</code></pre>
<p>I've also created a two new tables as a test:</p>
<p>teachers: id, name, content_area, room</p>
<p>students: id, name, homeroom_teacher </p>
<p>When I set the foreign key on students field homeroom_teacher and insert the data manually from phpMyAdmin, they become related and the id on students table becomes clickable and it shows the relation with the teacher. So manually it's working great and the problem is in the PHP code.</p>
<p>What query do I need to change, so to make the connection with post id from the posts table and post_id from the postimage table?</p>
<p>I know that I'm missing the id from the $_FILES query, but I don't know how to get it, because it's already automatic auto increment field.</p>
<p>Thanks.</p>
| 2 |
PHP Warning: POST Content-Length exceeds the limit
|
<p>I have a simple contact form with file upload. I got the following warning, but I would like to make an error message for the users that this file is bigger than the limit. Yes I know i can disable the "Warning: POST Content-Length..." message if I switch off error_reporting, but I would warn the users. One more problem appeared when I fill the contact form and try to upload bigger file I press submit and all my filled fileds will be empty. Is it any kind of way to get the error message and don't lose the filled fields?</p>
| 2 |
Configure pandoc to extract media to different folder
|
<p>I use pandoc to convert <code>docx</code> to <code>markdown</code> with the following: </p>
<p><code>pandoc -f docx -t markdown --extract-media="pandoc-output/$filename/" -o "pandoc-output/$filename/full.md" "$fullfile"</code></p>
<p>Which works OK. However, the media is stored in:</p>
<p><code>pandoc-output/$filename/media/</code></p>
<p>I want the media to be stored in </p>
<p><code>/pandoc-output/media/$filename/</code></p>
<p>Is this possible?</p>
<p><strong><em>UPDATE</em></strong> </p>
<p>I ended up with a <code>sed</code> command to search and replace the offending lines together with a <code>mv</code> to the proper directory. </p>
<p><code>gsed -i -r "s/([a-zA-Z0-9_-]+)\/pandoc-output\/media\/([a-zA-Z0-9]+)/\/public\/media\/\1\/\2/" $ROOTDIR"$d"_"$filename.html.md"</code></p>
| 2 |
How to implement LAR patch in ns2?
|
<p>I am new to Network Simulator (NS2).
I want to simulate Location Aided Routing Protocol over ns2.34 or 2.35.
I have installed ns-allinone-2.35 and have LAR-DREAM Patch file for ns2.35.</p>
<p><strong>HOW TO INSTALL PATCH?</strong></p>
<p>I tried
#patch -p1 < LAR-DREAM.patch</p>
<p>but it says no such file or directory. Placed patch file under ns-allinone-2.35 folder.</p>
<p>Do reply!</p>
| 2 |
PySpark job seems to be stuck while materializing RDD
|
<p>I have a SparkJob that starts off by creating a pairwise score matrix between N items. Though intensive this is pretty fast up-to about 20K elements after which it seems to get stuck for a very long time. The last log line that I saw over multiple attempts was 'cleaned accumulator ' I've attached the code block below to repro the issue with a randomly created dataset of 50K elements. The cartesian product is quite fast and a count on the resulting RDD returns in a couple of minutes (2.5 billion rows) but the second count gets stuck for over two hours with no progress updates in the logs or the Spark Jobs UI. I have a cluster of 15 EC2 M3.2xLarge nodes. How can I understand what's happening here and what can be done to speed this up?</p>
<pre><code>import random
from pyspark.context import SparkContext
from pyspark.sql import HiveContext, SQLContext
import math
from pyspark.sql.types import *
from pyspark.sql.types import Row
sc=SparkContext(appName='kmedoids_test')
sqlContext=HiveContext(sc)
n=50000
A = [random.normalvariate(0, 1) for i in range(n)]
B = [random.normalvariate(1, 1) for i in range(n)]
C = [random.normalvariate(-1, 0.5) for i in range(n)]
df = sqlContext.createDataFrame(zip(A,B,C), ["A","B","C"])
f = lambda x, y : math.pow((x.A - y.A), 2) + math.pow((x.B - y.B), 2) + math.pow((x.C - y.C), 2)
schema = StructType([StructField("row_id", LongType(), False)] + df.schema.fields[:])
no_of_cols=len(df.columns)
rdd_zipped_with_index=df.rdd.zipWithIndex()
reconstructed_rdd = rdd_zipped_with_index.map(lambda x: [x[1]]+list(x[0][0:no_of_cols]))
indexed_df=reconstructed_rdd.toDF(schema)
indexed_rdd = indexed_df.rdd
sc._conf.set("spark.sql.autoBroadcastJoinThreshold","-1") #turning off broadcast join
rdd_cartesian_prod = indexed_rdd.cartesian(indexed_rdd)
print "----------Count in self-join--------------- {0}".format(rdd_cartesian_prod.count()) #this returns quickly in about 160s
ScoreVec = Row("head_id","tail_id","score")
output_rdd = rdd_cartesian_prod.map(lambda x : ScoreVec(float(x[0].row_id), float(x[1].row_id), float(f(x[0], x[1]))))
print "-----------Count after scoring--------------- {0}".format(output_rdd.count()) #gets stuck here for a LONG time
output_df = output_rdd.toDF() #does not get here
</code></pre>
| 2 |
python setup.py build ignoring some files
|
<p>I have the following structure for my Python package:</p>
<pre><code>$ tree -d | grep -v "__pycache__"
.
├── src
│ ├── poliastro
│ │ ├── iod
│ │ ├── tests
│ │ └── twobody
│ │ └── tests
├── setup.py
└── MANIFEST.in
47 directories
</code></pre>
<p>Buf after performing <code>python setup.py build</code>, the innermost <code>test</code> directory is not getting copied:</p>
<pre><code>$ tree -d | grep -v "__pycache__"
.
├── build
│ ├── lib
│ │ └── poliastro
│ │ ├── iod
│ │ ├── tests
│ │ └── twobody
</code></pre>
<p>On the contrary, <code>python setup.py sdist</code> works correctly.</p>
<p>So far I've used the <code>MANIFEST.in</code> rules to include or exclude certain files, patterns and directories from the sdist. Is there a way to control what goes to the <code>build</code> directory? Why some tests are getting there and some others aren't?</p>
<p>Reference to original issue and source code: <a href="https://github.com/poliastro/poliastro/issues/129">https://github.com/poliastro/poliastro/issues/129</a></p>
| 2 |
where can i find the header of __sync_add_and_fetch
|
<p>can any one tell me where can I find the header for <code>__sync_add_and_fetch</code> built in function<br>
with out header how could we able to compile the code . </p>
| 2 |
r mgcv Error in predict.gam model
|
<p>My testing data a my trining data have different factors levels. I try to merge levels but it doesnt works.</p>
<pre><code>library(mgcv)
library(ff)
myData <- read.csv.ffdf(file = "myFile.csv")
myData$myVar <- as.factor(myData$myVar)
testData <- read.csv(file = "test.csv")
testData$myVar <- as.factor(testData$myVar)
form <- dependent ~ .
model <- gam(form, data=myData)
model$xlevels[["myVar"]] <- union(model$xlevels[["myVar"]], levels(testData$myVar))
predictedData <- predict(model, newdata=testData)
</code></pre>
<p>then R gives me this error:
Error in predict.gam(model, newdata = testData) : 1001, 1213,1231 not in original fit
Calls: predict -> predict.gam</p>
| 2 |
Get time from date and time using Regex
|
<p>How do I extract <code>12:05 AM</code> from <code>7/16/2016 12:05:00 AM</code> using Regex?</p>
<p>I've made it this far</p>
<pre><code>test = "7/16/2016 12:05:00 AM"
test.match(/^(\S+) (.*)/)[2]
> "12:05:00 AM"
</code></pre>
<p>but I can't figure out how to remove the seconds. Plus, if there's a simpler/more efficient way of doing what I'm trying to do, please let me know.</p>
<p>I would rather not rely on third-party libraries like moment.js</p>
<hr>
<p>NOTE: My desired output is <code>12:05 AM</code> and not just <code>12:05</code></p>
| 2 |
how to use zip function spark java
|
<p>i need to transform this partition of code of scala to java language</p>
<pre><code> scala> List("a", "b", "c") zip (Stream from 1)
res1: List[(String, Int)] = List((a,1), (b,2), (c,3))
</code></pre>
<p>how can i replace (Stream from 1) in java?
help please</p>
| 2 |
Deploy to localhost from Visual Studio
|
<p>I'm working on 'asp.mvc' web site. When i deploy it to 'iis express', site is available from 'localhost:333'.
<a href="https://i.stack.imgur.com/KqcDQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KqcDQ.png" alt="enter image description here"></a>
I want to deploy this site to 'iis' (and keep url like localhost:xxx), but when i change 'iis express' to 'iis', i receive an error.
<a href="https://i.stack.imgur.com/F1jzs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F1jzs.png" alt="enter image description here"></a></p>
<p>How to deploy site to iis 10 from VisualStudio 2013/2015 and access it from localhost:xxx?</p>
| 2 |
ORA-00904: invalid identifier in subquery (in select clause)
|
<p>I have a subquery that needs to use a value from the outer query. It fails because of the notorious "subquery in Oracle can't access a value from a parent query more than two level deeper" issue.</p>
<p>However, I can't figure out how to re-write it. Most examples on the web are for when the subquery is in the WHERE clause; mine is in the SELECT clause.</p>
<p>Help anyone?</p>
<pre><code>select agre.*, agre.orga_ky,
orga.NAME_LA_LB as orga_name,
pers.LAST_NAME_LA_LB as SIGNATORY_ORGA__LASTNAME, pers.FIRST_NAME_LA_LB as SIGNATORY_ORGA_FIRSTNAME,
upper(pers.LAST_NAME_LA_LB) || ' ' || pers.FIRST_NAME_LA_LB as SIGNATORY_ORGA_FULLNAME,
-- Get the most current agreement for this orga and compare it with this row to find out if this row is current or expired
CASE WHEN (
SELECT AGRE_KY
FROM (
SELECT a.AGRE_KY
FROM T_AGREEMENT a
WHERE a.ORGA_KY = agre.orga_ky -- fail!!! ORA-00904: invalid identifier
ORDER BY a.REC_CREATION_DT DESC
)
WHERE ROWNUM = 1
) = agre.agre_ky THEN 'Current' ELSE 'Expired' END as agreement_status
from T_AGREEMENT agre
left outer join T_ORGANIZATION orga on agre.orga_ky = orga.orga_ky
left outer join T_PERSON pers on agre.SIGNATORY_ORGA_PERS_KY = pers.pers_ky
;
</code></pre>
| 2 |
How to remove duplicates when using xslt
|
<p>I am able to remove duplicates from either city1 or city2 or city 3 using Muenchian grouping which is key and generate id as shown below. but am not able to remove duplicates by looping into all city1, city2 and city3</p>
<p>Below is the xml </p>
<pre><code><test>
<records>
<city1>Sweden</city1>
<country1>value1<country1>
<town1>value2<town1>
<city2>Paris</city2>
<country2>value1<country2>
<town2>value2<town2>
<city3>London</city3>
<country3>value1<country3>
<town3>value2<town3>
</records>
<records>
<city1>Sweden</city1>
<country1>value1<country1>
<town1>value2<town1>
<city2>Frankfut</city2>
<country2>value1<country2>
<town2>value2<town2>
<city3>NEwYork</city3>
<country3>value1<country3>
<town3>value2<town3>
</records>
<records>
<city1>SFO</city1>
<country1>value1<country1>
<town1>value2<town1>
<city2>London</city2>
<city2>Frankfut</city2>
<country2>value1<country2>
<city3>Frankfut</city3>
<country3>value1<country3>
<town3>value2<town3>
</records>
</test>
</code></pre>
<p>Output should be </p>
<pre><code>Row|Add|Sweden|value1|value2
Row|Add|London|value1|value2
Row|Add|NewYork|value1|value2
Row|Add|SFO|value1|value2
</code></pre>
<p>Code used for removing duplicates from city1 </p>
<pre><code> <xsl:key name="Keycity" match="//test/records" use="city1" />
<xsl:for-each select="//records[generate-id(.) = generate-id(key('Keycity', city1))]">
<xsl:sort select="."/>
<xsl:variable name="city1" select="."/>
<Row Action="ADD">
<xsl:value-of select="city1" />
</Row>
</xsl:if>
</xsl:for-each>
</code></pre>
| 2 |
Cannot read property 'props' of undefined
|
<p>You'll have to go easy on me.. very new to React Native</p>
<p>I have this piece of code, pretty simple:</p>
<pre><code>export default class signup extends Component {
constructor(props){
super(props);
this.state = {
loaded: true,
email: '',
password: ''
};
}
signup(){
this.setState({
loaded: false
});
firebaseApp.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function() {
this.props.navigator.push({
component: Login
});
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
console.log("ERROR WITH SIGNIN")
console.log( errorMessage )
});
}
goToLogin(){
this.props.navigator.push({
component: Login
});
}
render() {
return (
<View style={styles.container}>
<Header text="Signup" loaded={this.state.loaded} />
<View style={styles.body}>
<TextInput
style={styles.textinput}
onChangeText={(text) => this.setState({email: text})}
value={this.state.email}
placeholder={"Email Address"}
/>
<TextInput
style={styles.textinput}
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
secureTextEntry={true}
placeholder={"Password"}
/>
<Button
text="Signup"
onpress={this.signup.bind(this)}
button_styles={styles.primary_button}
button_text_styles={styles.primary_button_text} />
<Button
text="Got an Account?"
onpress={this.goToLogin.bind(this)}
button_styles={styles.transparent_button}
button_text_styles={styles.transparent_button_text} />
</View>
</View>
);
}
}
AppRegistry.registerComponent('signup', () => signup);
</code></pre>
<p>What I do not understand is if I click the "Go to login" button it runs the function perfectly and goes to the Login page</p>
<pre><code> goToLogin(){
this.props.navigator.push({
component: Login
});
}
</code></pre>
<p>However when I click the signup button, it throws the error </p>
<blockquote>
<p>Cannot read property 'props' of undefined</p>
</blockquote>
<p>I figured I could just put the same block of code for it to run : </p>
<pre><code> this.props.navigator.push({
component: Login
});
</code></pre>
<p>However it causes an error. I am a little confused why this would be happening as it works perfectly in the other function.. I am sure this is just me and my lack of understanding of react native..
Thanks guys!</p>
| 2 |
Update `RecyclerView` dataset from a service
|
<p>How to update the <code>RecyclerView Dataset</code> from the background service.
The service maintains a socket connection with the server and when the server responds with data, the <code>service</code> has to update that in the recyclerview (that is in the MainActivity).</p>
| 2 |
Android and Google Maps: Fading pulse animation
|
<p>I have created a pulse animation, that takes a location on a map, and continuously emits a pulse (circle). This works as expected. However, I would like the pulse to fade out, the further it is away from the point. Any thoughts on how to achieve this best?</p>
<p>The animation is as follows:</p>
<pre><code> mCircle = mMap.addCircle(
new CircleOptions()
.center(mMarker.getPosition())
.strokeWidth(STROKE_WIDTH)
.strokeColor(Color.parseColor(DEFAULT_COLOR))
.radius(RADIUS));
mAnimator.setRepeatCount(ValueAnimator.INFINITE);
mAnimator.setRepeatMode(ValueAnimator.RESTART);
mAnimator.setIntValues(0, 100);
mAnimator.setDuration(DURATION);
mAnimator.setEvaluator(new IntEvaluator());
mAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float animatedFraction = valueAnimator.getAnimatedFraction();
mCircle.setRadius(animatedFraction * SIZE);
}
});
mAnimator.start();
</code></pre>
| 2 |
How to get JWT token from URL using Express server?
|
<p>Supposing the URL is like <code>http://localhost:3000/auth?token=helloworld</code></p>
<p>How to get the jwt token from this url using express server? I have tried this code below.. no output.</p>
<pre><code>var express = require('express');
var app = express();
var router = express.Router();
router.use(function(req, res, next) {
var token = req.query.token;
console.log(token);
try {
var decoded = jwt.verify(token, 'thisismysecretstring');
console.log(decoded);
res.send(req.query.token);
} catch (err) {
console.log(err);
}
});
app.use('/auth', router);
</code></pre>
| 2 |
Buttons inside datatables cell not sorting
|
<p>I have buttons inside datatables cells:</p>
<pre><code><button class="btn btn-primary waves-effect waves-light" data-toggle="modal" data-target="#remote-modal3" data-remote="../api/?type=list-of-ranged&amp;pid=4694124&">2</button>
</code></pre>
<p>Problem is that sorting is not working. If I define :</p>
<pre><code>{"title":"Ranged", "data":"Ranged", "type":"num-html"},
</code></pre>
<p>I get some funny sorting , like : 2,3,1,1,2,1</p>
<p>If I do not define anything there, it detects it as html and again I get some funny sorting.</p>
<p>I read about the data-sort and data-order property which I have added as bellow : </p>
<pre><code><button data-sort="8" class="btn btn-primary waves-effect waves-light" data-toggle="modal" data-target="#remote-modal3" data-remote="../api/?type=list-of-ranged&amp;pid=4694124&">2</button>
</code></pre>
<p>but still get the same problem.
How do I properly sort this column? </p>
<p>Note: I am generating the buttons in some other part of the code so I cannot touch the th tag. code is generated from php and is consumed via ajax in the datatable as bellow :</p>
<pre><code>$aaData[$storeIndex]['Ranged'] = '<button data-sort="'.$ranged_v.'" class="btn btn-primary waves-effect waves-light" data-toggle="modal" data-target="#remote-modal1" data-remote="'.$rangedurl.'">'.$ranged_v.'</a>';
</code></pre>
| 2 |
jQuery functions not working after click button?
|
<h2>What I want to happen</h2>
<ul>
<li>When press the add button, a row will be added underneath the add button's row</li>
<li>When press the remove button, that row will be removed.</li>
<li>When hover or click on a certain input text, an add button will show up next to it.
<ul>
<li>When mouse is not hovering over the input text or the input text is not selected, then the add button should disappear.</li>
</ul></li>
<li>When hover over a certain bullet, a remove button will show up in place of the bullet.
<ul>
<li>When mouse moves away from remove button, it will revert back to a bullet.</li>
</ul></li>
</ul>
<p>I suspect some of my problems are occurring b/c I'm putting all my functions in <code>$(document).ready()</code>. If someone could type out the jQuery code that I should be using I would be really grateful!</p>
<h2>What is happening</h2>
<p><em>The Add Button</em>
<a href="https://i.stack.imgur.com/sZBsU.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sZBsU.gif" alt="enter image description here"></a></p>
<p>Only the first add button works.</p>
<p><em>The Remove button</em>
<a href="https://i.stack.imgur.com/mEgeo.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mEgeo.gif" alt="enter image description here"></a>
The other added rows' remove buttons only show up when hover over the first bullet.</p>
<p><a href="https://i.stack.imgur.com/dkx4N.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dkx4N.gif" alt="enter image description here"></a>
The remove button only works once. After remove one row, the remove button & add button lose their functionality. The remove and add button also don't disappear as they should.</p>
<h2>My code</h2>
<p><em>HMTL</em></p>
<p>This is the row I want to add</p>
<pre><code><div class="row">
<div class="col-lg-7">
<div class="form-group">
<div class="input-group input-group-lg">
<div class="input-group-btn">
<button type="button" class="btn btn-default button-remove" aria-label="Remove">
<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-default button-bullet" aria-label="Bullet">
<span class="glyphicon glyphicon-one-fine-dot" aria-hidden="true"></span>
</button>
</div>
<input type="text" name="Worksheet-Problem" class="form-control" placeholder="Problem..." aria-label="Write worksheet problem here">
<div class="input-group-btn">
<button type="button" class="btn btn-default button-add" aria-label="Add">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</button>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p><em>jQuery</em></p>
<p>These are the functions I'm using to animate the buttons and add/remove rows.</p>
<pre><code>$(document).ready(function(){
$("input[type='text'][name='Worksheet-Problem']").closest('.row').hover(function() {
$(".button-add").fadeToggle(300);
})
$(".button-bullet").closest('.input-group-btn').hover(function(){
$('.button-bullet').toggle();
$(".button-remove").toggle();
})
$(".button-add").click(function(){
var $row = $(this).closest('.row');
var $wsProbRow = $row.clone();
$wsProbRow.insertAfter($row);
console.log("Add-Button pressed");
})
$(".button-remove").click(function(){
$(this).closest('.row').remove();
console.log("Remove-Button pressed");
})
})
</code></pre>
<p><a href="https://jsfiddle.net/14ongm/d5dedcLj/3/" rel="nofollow noreferrer">JSFiddle</a></p>
| 2 |
Intending return null (or it has null argument)?
|
<p>I have no idea why "intending" in the following code returns null. I just copied the code from here: <a href="https://google.github.io/android-testing-support-library/docs/espresso/intents/index.html" rel="nofollow">https://google.github.io/android-testing-support-library/docs/espresso/intents/index.html</a></p>
<p><strong>The exception is</strong> </p>
<pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.test.espresso.intent.OngoingStubbing android.support.test.espresso.intent.Intents.internalIntending(org.hamcrest.Matcher)' on a null object reference
at android.support.test.espresso.intent.Intents.intending(Intents.java:155)
at GsonActivityTest.ensureHandleActivityResultCorrectly(GsonActivityTest.java:37)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at android.support.test.internal.statement.UiThreadStatement.evaluate(UiThreadStatement.java:55)
at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:257)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:54)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:240)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1879)
</code></pre>
<p><strong>The code is</strong></p>
<pre><code>import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.example.myapplication.R;
import com.example.myapplication.activity.GsonActivity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.intent.Intents.intending;
import static android.support.test.espresso.intent.matcher.IntentMatchers.toPackage;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
@RunWith(AndroidJUnit4.class)
public class GsonActivityTest {
@Rule
public ActivityTestRule<GsonActivity> rule = new ActivityTestRule<>(GsonActivity.class);
@Test
public void ensureHandleActivityResultCorrectly() {
// Build a result to return when a particular activity is launched.
Intent resultData = new Intent();
String phoneNumber = "123-345-6789";
resultData.putExtra("phone", phoneNumber);
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
// Set up result stubbing when an intent sent to "contacts" is seen.
intending(toPackage("com.android.contacts")).respondWith(result);
// User action that results in "contacts" activity being launched.
// Launching activity expects phoneNumber to be returned and displays it on the screen.
onView(withId(R.id.button8)).perform(click());
// Assert that data we set up above is shown.
onView(withId(R.id.editText)).check(matches(withText(phoneNumber)));
}
}
</code></pre>
| 2 |
Set Visual Studio 2015 Compiler to VS 2010 version
|
<p>I'm a student and i'm using Visual Studio 2015 to learn C++.</p>
<p>I need to set my compiler so it will check my code the same as Visual Studio 2010's compiler so no errors show up on my disciple's end who was instructed to check our code in 2010 environment.
Is there any way i can do that?
sorry for any bad English and i hope you understand my question.</p>
<p>thanks in advance!</p>
| 2 |
display the text as diagonally at 45 in textview
|
<p>I'm trying to display my text in diagonally at 45 degree as from bottom to top. I have tried <code>SetRotation("45")</code> and <code>android:rotation="45"</code> and tried anim in xml also like this </p>
<p>
</p>
<pre><code><item>
<rotate
android:fromDegrees="-45"
android:toDegrees="45"
android:pivotX="20%"
android:pivotY="20%" >
<shape
android:shape="line"
android:top="1dip" >
<stroke
android:width="1dip"
android:color="#0000" />
</shape>
</rotate>
</item>
</code></pre>
<p></p>
<p>Its not displaying in diagonally. Please help if you any idea, how to show the text in diagonally. Thanks in Advance. </p>
| 2 |
C++ - Get Starting Address of a function from Ending Address / Get size of a function
|
<p>I am using /Gh and /GH compiler option of visual studio to profile a bunch of code. Two methods used are _penter and _pexit which are called when a function is entered or exited in the code being profiled. Since I need specific functions being profiled/debugged, I use an already defined array <em>FuncTable</em> which contains the addresses of the functions I need to instrument with their names as string. So when a function is entered, the <em>pStack[0]</em>, which basically contains the register contents, contains the address to current line of the code being executed. Similarly when a function is exited, <em>pStack[0]</em> contains the address of last line of the code.</p>
<p><strong>THE ISSUE</strong>: When a function is entered (_penter is called), I get the address of first line of the function in pStack[0] and hence I can get the function's address by subtracting a constant(-5) and save that to my list to be retrieved later in the _pexit function. But since in _pexit I am getting address to the last line of the function, I need to find the size of the function in order to subtract that size from the address in pStack[0] to reach the starting address of the function and then compare that address to the ones saved in my list. Pasted below is the code.</p>
<pre><code>void _stdcall EnterFunc0(unsigned * pStack)
{
void * pCaller;
pCaller = (void *)(pStack[0] - 5); // pStack[0] is first line, -5 for function address
Signature * funct = FuncTable;
while (funct->function)
{
const BYTE * func = (const BYTE *)funct->function;
if ((func == (const BYTE *)pCaller) || ((*func == 0xE9) && ((func + *(DWORD *)(func + 1) + 5) == (const BYTE *)pCaller)))
{
Stack_Push(funct->name, funct->returnType, true, pCaller);
}
funct++;
}
}
extern "C" __declspec(naked) void __cdecl _penter()
{
_asm
{
pushad // save all general purpose registers
mov eax, esp // current stack pointer
add eax, 32 // stack pointer before pushad
push eax // push pointer to return address as parameter to EnterFunc0
call EnterFunc0
popad // restore general purpose registers
ret // start executing original function
}
}
void _stdcall ExitFunc0(unsigned * pStack)
{
if (startRecording)
{
StackEntry * start = top;
while (start != NULL)
{
//**HERE I NEED TO COMPARE THE ADDRESS OF THE FUNCTION WITH THE ONE ALREADY IN MY STACK**
if ((void *)(pStack[0] - sizeOfTheFunction) == start->Address)
{
OutputDebugString("Function Found\n");
}
start = start->next;
}
}
}
extern "C" __declspec(naked) void __cdecl _pexit()
{
_asm
{
pushad // save all general purpose registers
mov eax, esp // current stack pointer
add eax, 32 // stack pointer before pushad
push eax // push pointer to return address as parameter to EnterFunc0
call ExitFunc0
popad // restore general purpose registers
ret // start executing original function
}
}
</code></pre>
| 2 |
merging inputs with embeddings and dense layer
|
<p>I have two inputs, x_a and x_b where x_a is a categorical variable (hence the embedding) and x_b which is a usual feature matrix. Basically I want to multiply x_b by a weights matrix W_b which is a <code>10x64</code> matrix so that I end up with a 64 dimensional output.</p>
<pre><code>from keras.models import Sequential
from keras.layers import Dense, Activation, Embedding, Merge
encoder_cc = Sequential()
# Input layer for countries(x_a)
encoder_cc.add(Embedding(cc_idx.max(),64))
# Input layer for triggers(x_b)
encoder_trigger = Sequential()
# This should effectively be <W_b>
encoder_trigger.add(Dense(64, input_dim=10, init='uniform'))
model = Sequential()
model.add(Merge([encoder_cc, encoder_trigger], mode='concat'))
</code></pre>
<p>Then I want to combine (merge) these two before I do the usual Neural net stuff. Except that I get the error: </p>
<pre><code>Exception: "concat" mode can only merge layers with matching output shapes except for the concat axis. Layer shapes: [(None, 1, 64), (None, 64)]
</code></pre>
<p>Any thoughts on how I can resolve this?</p>
| 2 |
Angularjs : Using common service in different modules
|
<p>I am trying to use the same <strong>service</strong> for different modules. There are many modules so i tried to inject them in a parent module. Something like this: </p>
<pre><code>var app=angular.module('myapp',['module_1','module_2',....,'module_n']);
var module_1=angular.module('myapp1',[]);
var module_2=angular.module('myapp2',[]);
var module_3=angular.module('myapp3',[]);
.
.
.
var module_n=angular.module('myappN',[]);
</code></pre>
<p>and the service which is common to all the <em>n</em> modules is like this: </p>
<pre><code>.service('myService',function(){
...doing something here...
});
</code></pre>
<p>Now I am not able to figure out how to use this service for all the submodules.<br>
With which module should I associate this <em>service</em> ?<br>
I tried doing <code>app.service('myService',function(){...})</code>, but it did'nt work.<br>
Where am I going wrong?</p>
<p><strong>EDIT 1:</strong><br>
Moreover I am trying to share a variable with all these submodules using the <em>service</em>. I am not sure if, I am doing the right thing by using a <em>service</em> for sharing variable or should I use a <em>Provider</em> or <em>Factory</em> for this job. </p>
<p><strong>EDIT 2:</strong><br>
I found these links, but I could not grasp the answer. Refer to them and please provide my answer<br>
<a href="https://stackoverflow.com/questions/33921344/how-to-share-a-variable-between-multiple-modules-in-angularjs">How to share a variable between multiple modules in AngularJS</a><br>
<a href="https://stackoverflow.com/questions/22235301/passing-variable-between-controllers-which-are-on-different-modules">Passing variable between controllers which are on different modules</a></p>
| 2 |
Tensorflow max-margin loss training?
|
<p>I want to train a neural network in tensorflow with a max-margin loss function using one negative sample per positive sample:</p>
<blockquote>
<pre><code>max(0,1 -pos_score +neg_score)
</code></pre>
</blockquote>
<p>What I'm currently doing is this:
The network takes three inputs: <em>input1</em>, and then one positive example <em>input2_pos</em> and one negative example <em>input2_neg</em>. (These are indices to a word embeddings layer.) The network is supposed to calculate a score that expresses how related two examples are.
Here's a simplified version of my code:</p>
<pre><code>input1 = tf.placeholder(dtype=tf.int32, shape=[batch_size])
input2_pos = tf.placeholder(dtype=tf.int32, shape=[batch_size])
input2_neg = tf.placeholder(dtype=tf.int32, shape=[batch_size])
# f is a neural network outputting a score
pos_score = f(input1,input2_pos)
neg_score = f(input1,input2_neg)
cost = tf.maximum(0., 1. -pos_score +neg_score)
optimizer= tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
</code></pre>
<p>What I see when I run this, is that like this the network just learns which input holds the positive example - it always predicts a similar score along the lines of:</p>
<pre><code>pos_score = 0.9965983
neg_score = 0.00341663
</code></pre>
<p><strong>How can I structure the variables/training so that the network learns the task instead?</strong> </p>
<p>I want just one network that takes two inputs and calculates a score expressing the correlation between them, and train it with max-margin loss.</p>
<p>Calculating scores for positive and negative separately does not seem like an option to me, since then it won't backpropagate properly. Another option seems to be randomizing inputs - but then for the loss function I need to know which example is the positive one - inputting that as another parameter would give away the solution again?</p>
<p>Any ideas?</p>
| 2 |
fetching data from database and send as email attachment using php
|
<p>I want to send E-mail using php with an attachment(CSV file). it is working fine but i want to make that csv file from data of one of tables in my database.how can i do that??</p>
<pre><code><?php
require_once('\PHPMailer-master\class.phpmailer.php');
$email = new PHPMailer();
$email->From = '[email protected]';
$email->FromName = 'name';
$email->Subject = 'Message Subject';
$email->Body = "GO away";
$email->AddAddress( '[email protected]' );
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('serial', 'group','end'));
$rows = mysqli_query($db, 'SELECT * FROM list');
while ($row = mysqli_fetch_assoc($rows)) {
fputcsv($output, $row);
}
fclose($output);
mysqli_close($db);
$file_to_attach = 'data.csv';
$email->AddAttachment( $output , 'data.csv' );
return $email->Send();
?>
</code></pre>
| 2 |
Cannot read property of undefined - Ajax POST
|
<p>I'm trying to post data (uploading a music file) from ajax which then should save the data into my mongodb when I click on the 'upload' button. However, i keep getting fieldname is undefined. I think somewhere in my code, it is not picking up the data.</p>
<pre><code>$('#upload').on('click', function(){
var formData = new FormData($('#file')[0].files[0]);
$.ajax({
url: 'http://localhost:3000/api/',
method: 'POST',
// data: {
// file: $('#file')[0].files[0]
// },
data: formData,
contentType: false,
processData: false,
mimeType: "multipart/form-data",
success: function(data){ //if successful upon grabbing data
console.log(data);
console.log('Created music')
var id = $('<p>').text("Id:" + data[i]._id);
var title = $('<p>').text("Title:" + data[i].originalname);
var play = $('<button>').data('Data-id', data[i]._id).text('Play').on('click', playSong); //creates edit button with donut id and carries a function editDonut in which we will define later
var del = $('<button>').data('Data-id', data[i]._id).text('Delete').on('click', deleteMusic);
var container = $('<div>').attr('Data-id', data[i]._id);
$(container).append(id, title, play, del);
$('body').append(container)
// $('#new-form').hide();
}
})
})
</code></pre>
<p>index.html</p>
<pre><code><form id="new-form">
<input id="file" type="file" name="uploads">
<button id="upload">Upload</button>
</form>
</code></pre>
<p>Backend in Express - apiRouter.js</p>
<pre><code>var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads/'); //UPLOAD MUSIC PATH
},
filename: function (req, file, cb) {
var originalname = file.originalname;
var extension = originalname.split(".");
filename = Date.now() + '.' + extension[extension.length-1];
cb(null, filename);
}
});
router.post('/', multer({storage: storage}).single('uploads'), function(req,res){
console.log(req.body);
var music = new Music ({
fieldname: req.file.fieldname,
originalname: req.file.originalname,
encoding: req.file.encoding,
mimetype: req.file.mimetype,
destination: req.file.destination,
filename: req.file.filename,
path: './uploads/' + req.file.filename,//req.file.path, //PATH TO PLAY MUSIC
size: req.file.size
})
music.save(function(err){
if (err){console.log(err)}
else {
res.redirect('/');
}
})
});
</code></pre>
<p>in Express - app.js</p>
<pre><code>app.use('/api', apiRouter);
</code></pre>
<p>Error in the terminal</p>
<pre><code>TypeError: Cannot read property 'fieldname' of undefined
at /Users/will/pulse-express2-passport/config/apiRouter.js:72:24
at Layer.handle [as handle_request] (/Users/will/pulse-express2-passport/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/will/pulse-express2-passport/node_modules/express/lib/router/route.js:131:13)
at Array.<anonymous> (/Users/will/pulse-express2-passport/node_modules/multer/lib/make-middleware.js:52:37)
at listener (/Users/will/pulse-express2-passport/node_modules/on-finished/index.js:169:15)
at onFinish (/Users/will/pulse-express2-passport/node_modules/on-finished/index.js:100:5)
at callback (/Users/will/pulse-express2-passport/node_modules/ee-first/index.js:55:10)
at IncomingMessage.onevent (/Users/will/pulse-express2-passport/node_modules/ee-first/index.js:93:5)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:934:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
</code></pre>
| 2 |
Replace ViewController
|
<p>I would like to change between two View Controllers. Both of the ViewControllers inherit from CenterViewController. The code below is to add one ViewController (CertificatenViewController) to the stack:</p>
<pre><code>centerViewController = CertificatenViewController(nibName: "CertificatenViewController", bundle: nil)
centerViewController.delegate = self
centerNavigationController = UINavigationController(rootViewController: centerViewController)
view.addSubview(centerNavigationController.view)
addChildViewController(centerNavigationController)
centerNavigationController.didMoveToParentViewController(self)
</code></pre>
<p>This happens in the viewDidLoad and in the same class I have a switch statement to check which View has to be loaded, something like this:</p>
<pre><code> switch menuItem.getNibname() {
case "CertificatenViewController":
print(menuItem.getNibname())
centerViewController = CertificatenViewController(nibName: menuItem.getNibname(), bundle: nil)
centerViewController.delegate = self
case "SettingsViewController":
print(menuItem.getNibname())
centerViewController = SettingsViewController(nibName: menuItem.getNibname(), bundle: nil)
centerViewController.delegate = self
default: break
}
</code></pre>
<p>I don't know exactly what the problem is, but it seems to be that the view is not reloaded. I have tried popViewControllerAnimated but this is not working. Maybe you can help me solving this problem.</p>
<p><strong>Solution:</strong></p>
<pre><code> func changeView(menuItem: MenuItem){
self.centerNavigationController.viewControllers.removeAll()
switch menuItem.getNibname() {
case "CertificatenViewController":
print(menuItem.getNibname())
self.centerNavigationController.pushViewController(self.centerViewController, animated: false)
case "SettingsViewController":
print(menuItem.getNibname())
self.centerNavigationController.pushViewController(self.settingsViewController, animated: false)
case "MessagesViewController":
print(menuItem.getNibname())
self.centerNavigationController.pushViewController(self.messagesViewController, animated: false)
default: break
}
}
</code></pre>
| 2 |
Log4net with azure application insights
|
<p>I have azure cloud service project with <strong>web role</strong> and integrate <strong>log4netappender</strong> with <strong>application insights</strong>. How to show the logs on <strong>azure portal application insights</strong>?</p>
| 2 |
Fitting exponential decay
|
<p>I'm trying to solve the following linearized equation:</p>
<p><strong>ln{1−y/y}=ln(c)−b(x)</strong></p>
<p>Using python scipy curvefit or another similar method, could your please let me know how to do this?</p>
<p>Sample data:</p>
<pre><code>x = [15, 16, 17, 18, 19, 20]
y = [0.78, 0.67, 0.56, 0.41, 0.31, 0.20]
</code></pre>
<p>code I have tried so far:</p>
<pre><code>import numpy as np
import scipy as sp
import pylab
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import math
import warnings
def sigmoid(x,c,b):
y = np.log(c)-b*x
return y
def sigmoid_solve(y, c, b):
x = (np.log(c)+np.log((1-y)/y))/b
return x
y_new = []
x_data = [15, 16, 17, 18, 19, 20]
y_data = [0.78, 0.67, 0.56, 0.41, 0.31, 0.20]
for data in y_data:
y_new.append(np.log((1-data)/data))
popt, pcov = curve_fit(sigmoid, x_data, y_new)
ce50 = sigmoid_solve(0.5,popt[0],popt[1])
x = np.linspace(10,40,10)
y = 1/(1+np.exp(sigmoid(x, *popt)))
plt.plot(x, y, 'r',label='logistic exp curve fit')
plt.plot(x_data, y_data,'o',label='data plot')
plt.ylim(0, 1)
plt.xlim(10, 50)
plt.legend(loc='best')
plt.savefig('test.png')
plt.close("all")
</code></pre>
<p>Is there a better way of solving this?</p>
| 2 |
Pasting Copied Cells without overwriting previous data
|
<p>I am using file dialog to copy data from various excel files and paste them on a single worksheet. The second file however overwrites the data from the first file. The 1st data was pasted on range A2:E2710 on the destination workbook. If the 2nd set of data range is A2:A118, it will overwrite A2:A118 on the destination workbook. How do I get it to paste and not overwrite the previously pasted data? I've tried Selection.Insert Shift:=xlDown but that does not paste the data. Please help. </p>
<pre><code>Sub FASB_Select()
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Set ExcelSheet = CreateObject("Excel.Sheet")
'Declare a variable to contain the path
'of each selected item. Even though the path is a String,
'the variable must be a Variant because For Each...Next
'routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
'Use the Show method to display the File Picker dialog box and return the user's action.
'The user pressed the action button.
If .Show = -1 Then
Sheets("Data").Select
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
'vrtSelectedItem is a String that contains the path of each selected item.
'You can use any file I/O functions that you want to work with this path.
'This example simply displays the path in a message box.
ThisWorkbook.FollowHyperlink (vrtSelectedItem)
'Clear CutCopyMode
Application.CutCopyMode = False
'Wait some time
Application.Wait Now + TimeValue("00:00:01") ' wait 3 seconds
DoEvents
'IN Excel :
'SELECT ALL
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'EXIT (Close & Exit)
Application.Wait Now + TimeValue("00:00:01") ' wait 3 seconds
ActiveWorkbook.Close SaveChanges:=False
'Wait some time
Application.Wait Now + TimeValue("00:00:01") ' wait 3 seconds
Range("A2").Select
'Paste
ActiveSheet.Paste
Next vrtSelectedItem 'Loop for each file selected in the file dialog box
'Exit if the user pressed Cancel
Else
Exit Sub
End If
End With
'Set the object variable to Nothing
Set fd = Nothing
End Sub
</code></pre>
| 2 |
Auto generate serial number in data grid using wpf?
|
<p>How to auto generate serial number in datagrid using wpf?`</p>
<pre><code> <DataGridTextColumn Header="Sl#"
x:Name="serialnumber"
Binding="{Binding Serial}"/>
</code></pre>
| 2 |
DrawableLeft attribute on spinner on Android?
|
<p>When you have a <code>Button</code> for example, you can use <code>android:drawableLeft</code> to make it an icon at the left of the button:</p>
<p><a href="https://i.stack.imgur.com/gscsj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gscsj.png" alt="DrawableLeft in usage"></a></p>
<p>Now, is there an attribute to use it on <code>spinner</code>? <code>android:drawableLeft</code> is not an attribute in <code>Spinner</code>, so is it possible to have the same result, but in a <code>Spinner?</code></p>
| 2 |
cannot find module errors after upgrading to angular-2.0.0-rc.4
|
<p>I have updated my angular2 references with the following in Package.json, But after updating, now I am getting the following 404 errors in my browser console:</p>
<pre><code> Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/facade/async Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/facade/collection Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/facade/exceptions Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/core Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/platform/dom/dom_adapter Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/facade/promise Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/core/util/decorators Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/facade/collection Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/core/di/decorators Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/core/reflection/reflection Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/facade/exceptions Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/core Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/facade/lang Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/core/di/decorators Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/core/reflection/reflection Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/facade/async Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/facade/promise Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/platform/dom/dom_adapter Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:55413/angular2/src/core/util/decorators Failed to load resource: the server responded with a status of 404 (Not Found)
</code></pre>
<p>Though now it is compiling, still I am getting the following errors in the Visual Studio IDE.</p>
<pre><code>Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\bindCallback.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\bindNodeCallback.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\combineLatest.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\concat.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\defer.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\empty.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\forkJoin.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\from.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\fromEvent.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\fromEventPattern.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\fromPromise.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\interval.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\merge.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\never.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\of.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\race.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\range.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\timer.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\observable\zip.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\audit.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\auditTime.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\buffer.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\bufferCount.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\bufferTime.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\bufferToggle.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\bufferWhen.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\cache.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\catch.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\combineAll.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\combineLatest.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\concat.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\concatAll.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\concatMap.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\concatMapTo.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\count.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\debounce.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\debounceTime.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\defaultIfEmpty.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\delay.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\delayWhen.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\dematerialize.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\distinctUntilChanged.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\do.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\every.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\expand.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\filter.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\finally.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\first.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\groupBy.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\ignoreElements.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\last.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\let.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\map.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\mapTo.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\materialize.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\merge.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\mergeAll.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\mergeMap.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\mergeMapTo.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\multicast.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\observeOn.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\partition.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\pluck.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\publish.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\publishBehavior.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\publishLast.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\publishReplay.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\race.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\reduce.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\repeat.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\retry.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\retryWhen.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\sample.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\sampleTime.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\scan.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\share.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\single.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\skip.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\skipUntil.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\skipWhile.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\startWith.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\subscribeOn.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\switch.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\switchMap.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\switchMapTo.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\take.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\takeLast.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\takeUntil.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\takeWhile.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\throttle.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\throttleTime.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\timeout.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\timeoutWith.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\toArray.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\toPromise.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\window.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\windowCount.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\windowTime.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\windowToggle.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\windowWhen.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\withLatestFrom.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\zip.d.ts 2 Active
Error TS2664 Invalid module name in augmentation, module '../../Observable' cannot be found. TypeScript Virtual Projects ..\node_modules\rxjs\add\operator\zipAll.d.ts 2 Active
</code></pre>
<p>My PACKAGE.json file as follows:</p>
<pre><code> {
"name": "ASP.NET",
"version": "0.0.0",
"dependencies": {
"@angular/core": "2.0.0-rc.4",
"@angular/http": "2.0.0-rc.4",
"@angular/platform-browser": "^2.0.0-rc.4",
"bootstrap": "3.3.6",
"es6-promise": "3.2.1",
"es6-shim": "0.35.1",
"jquery": "3.0.0",
"reflect-metadata": "0.1.3",
"rxjs": "5.0.0-beta.6",
"systemjs": "0.19.31",
"zone.js": "0.6.12"
},
"devDependencies": {
"gulp": "3.9.1",
"gulp-concat": "2.6.0",
"gulp-cssmin": "0.1.7",
"gulp-uglify": "1.5.4",
"rimraf": "2.5.2"
}
}
</code></pre>
<p>My tsconfig.json file is as follows</p>
<pre><code>{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"noEmitOnError": true,
"noImplicitAny": false,
"outDir": "../wwwroot/appScripts/",
"removeComments": false,
"sourceMap": true,
"target": "es5"
},
"exclude": [
"node_modules",
"typings/browser/",
"typings/browser.d.ts"
]
}
</code></pre>
<p>What is it I am missing? Still should I need to add any other references?</p>
| 2 |
Deep Learning Framework for RNN with bi-directional LSTM and CTC output layer
|
<p>I hope you can help me. I was wondering if you could give me any hints which framework to use:</p>
<p>I am planning to set up a RNN with bidirectional LSTMs and a CTC output layer.</p>
<p>I have been working with Theano and Lasagne, but unfortunately there is no possibility of implementing a bi-directional LSTM with CTC out of the box.</p>
<p>Lasagne offers the possibiltiy of RNN:
<a href="http://lasagne.readthedocs.io/en/latest/modules/layers/recurrent.html" rel="nofollow">http://lasagne.readthedocs.io/en/latest/modules/layers/recurrent.html</a></p>
<p>And I also found an implementation of CTC:
<a href="https://github.com/skaae/Lasagne-CTC" rel="nofollow">https://github.com/skaae/Lasagne-CTC</a></p>
<p>Would you try to do this with Theano and Lasagne?
Or would you recommend a different framework.</p>
<p>Happy for all your feedback! </p>
| 2 |
pdf2htmlEX cannot open or read file
|
<p>I installed docker and run pdf2htmlEX through it</p>
<pre><code>alias pdf2htmlEX="docker run -ti --rm -v ~/pdf:/pdf bwits/pdf2htmlex pdf2htmlEX"
pdf2htmlEX -h
pdf2htmlEX --zoom 1.3 test.pdf
</code></pre>
<p>This is my path and the pdf's contained inside:</p>
<pre><code>~/Desktop/pdf$ ls
test.pdf testpdf.pdf
</code></pre>
<p>When running the following commands:</p>
<pre><code>df2htmlEX --zoom 1.3 test.pdf
df2htmlEX test.pdf
df2htmlEX pdf/test.pdf
df2htmlEX ~pdf/test.pdf
</code></pre>
<p>and other combinations with the full path before test.pdf I continue to get unable to read the file errors.</p>
<pre><code>I/O Error: Couldn't open file 'test.pdf': No such file or directory.
Error: Cannot read the file
</code></pre>
<p>I am not sure if permissions is a cause, but when checking on user permissions it has read and write:</p>
<pre><code>-rw-r--r--@ 1 test.pdf
-rw-r--r--@ 1 testpdf.pdf
</code></pre>
<p>Any idea on why it is not finding or cannot read the pdf file that is there? I am trying to convert it to .html</p>
| 2 |
SQLite query for n-th day of month
|
<p>Say, I have the following table:</p>
<pre><code>CREATE TABLE Data (
Id INTEGER PRIMARY KEY,
Value DECIMAL,
Date DATE);
</code></pre>
<p>Since the application is finance-related, user may choose, which day would be the first day of the month. For instance, if he receives salary every 10th of the month, he may set the first day of the month to be 10th.</p>
<p>I'd like to create a query, which returns average value for n-th day of month, as defined by user. For instance:</p>
<pre><code> Date | Value
---------------+------
10.01.2016 | 10
11.01.2016 | 15
10.02.2016 | 20
11.03.2016 | 10
</code></pre>
<p>Result of the query should be:</p>
<pre><code> Day | Average
----+--------
1 | 15
2 | 12.5
</code></pre>
<p>Note, that if user sets first day to 10th, 9th of the month may be 28th, 29th, 30th or 31st day of a month (depending on which month we're talking about). So this is not as simple as extracting day number from the date.</p>
| 2 |
Sending Java Client String to C# Server
|
<p>I am quite new to networking, and have so far managed to get my Android app (client) to connect with my Unity C# server, however I am getting a bit stuck with the Java sending the String and the server decoding it. </p>
<p>The C# client will read input, but when I Log the client message, it is black. So my best guess is that the problem lies with the Java string encoding or the decoding. </p>
<p>Let me know if anyone can spot where I am going wrong, or if anyone has better suggestions on how to handle the writers and the readers. </p>
<p>Many thanks in advance!</p>
<p>The java Client SendMsg Thread</p>
<pre><code> import android.os.AsyncTask;
import android.util.Log;
import java.io.DataOutputStream;
import java.net.Socket;
public class SendMsgToServer extends AsyncTask<Socket, Void, Void> {
@Override
protected Void doInBackground(Socket... sockets) {
Socket client = sockets[0];
//Check Connection is established
if (client.isConnected()){
try {
String msgToServer = "Pleasure doing business";
DataOutputStream data = new DataOutputStream(client.getOutputStream());
data.writeUTF(msgToServer);
// Source: http://stackoverflow.com/questions/11154367/socket-java-client-c-sharp-server
// PrintWriter outputMsg = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
// outputMsg.write("Message to the Server.");
Log.d("Server", data.toString());
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.d("Server", "Server Connection is not established");
}
return null;
}
}
</code></pre>
<p>The C# Server </p>
<pre><code>using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
public class clientTcp : MonoBehaviour {
static bool socketReady = false;
static TcpListener server = null;
static NetworkStream networkStream;
static StreamWriter writer;
static StreamReader reader;
static Byte[] bytes = new Byte[256];
static NetworkStream stream;
static TcpClient client;
String Host = "localhost";
Int32 port = 13000;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void setupSocketServer() {
//Create thread to accept the connection ; else Unity crashes
Thread acceptClient = new Thread(new ThreadStart(SocketClient));
acceptClient.Start();
}
//msg is from the textfield
public void writeSocket(string msg) {
if (socketReady == false) {
return;
}
String data = "hi";
byte[] msgToClient = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msgToClient, 100, msg.Length);
}
public void readSocket() {
Thread readClient = new Thread (new ThreadStart (ReadClient));
readClient.Start ();
}
static void ReadClient() {
Debug.Log ("ReadClient Thread started");
// http://stackoverflow.com/questions/29265430/socket-communication-between-java-and-c-sharp-application
int length = networkStream.ReadByte ();
byte[] buffer = new byte[length];
int size = networkStream.ReadByte ();
byte[] buff = new byte[size];
using (var memoryStream = new MemoryStream(buff,false)) {
using (var streamReader = new StreamReader(memoryStream, Encoding.UTF8)) {
var message = streamReader.ReadLine();
buff = Encoding.UTF8.GetBytes(message);
networkStream.Read(buffer, 0 ,buffer.Length);
Debug.Log (message);
networkStream.Flush();
}
}
}
//Thread to set up the Unity Server and await connection request from the Android App.
static void SocketClient() {
Int32 port = 13000;
IPAddress serverAddr = IPAddress.Parse("192.168.1.15");
//Establish Server
server = new TcpListener(serverAddr, port);
server.Start();
//Await connection
while (true) {
client = server.AcceptTcpClient ();
Debug.Log("Client Connected");
socketReady = true;
networkStream = client.GetStream();
writer = new StreamWriter(networkStream);
reader = new StreamReader(networkStream);
String data= null;
//Create a stream object for reading and writing
stream = client.GetStream();
Debug.Log("client.getStream");
// int i;
// while((i = stream.Read(bytes,0,bytes.Length)) != 0 ) {
// data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
// Debug.Log(data);
}
}
}
</code></pre>
| 2 |
Swift encode WhatsApp URL
|
<p>I would like to open a WhatsApp URL in my App, which I create in Swift. The URL scheme for WhatsApp is </p>
<pre><code>whatsapp://send?text=
</code></pre>
<p>and my code look like:</p>
<pre><code> let originalMessage = NSLocalizedString("Open following url ", comment: "") + " " + "http://<url>.<com>/?=test"
let escapedMessage = originalMessage.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
// Check if url will be opened
guard let whatsAppUrl = NSURL(string: "whatsapp://send?text=" + escapedMessage) else {
print("error")
return
}
// Open whatsapp url
if UIApplication.sharedApplication().canOpenURL(whatsAppUrl) {
print("ok")
}
</code></pre>
<p>My issue is, that I have in my String which will I open with WhatsApp a question mark character "?". I tried to escape the character like:</p>
<pre><code>"whatsapp://send?text=\"" + escapedMessage + "\""
</code></pre>
<p>But if I open the URL in WhatsApp, I get an empty String. Can someone help me or have a hint for me?</p>
| 2 |
Vagrant not allowing NatNetwork on adapter 1
|
<p>Vagrant is forcing network type <code>nat</code> on adapter 1 (eth0) even when I have the network set as <code>natnetwork</code> in Virutalbox.<br>
I can set up everything through Virtualbox manually and all my VMs can communicate with each other via eth0 as desired and port forwarding works as well. I would like to get Vagrant to work the same way for easy distribution among coworkers.</p>
<p>It looks like others have this problem and it's not being addressed by Vagrant:
<a href="https://github.com/mitchellh/vagrant/issues/2779" rel="nofollow">https://github.com/mitchellh/vagrant/issues/2779</a></p>
<p>Anyone know of a workaround?</p>
<p><strong>Details:</strong></p>
<pre><code>$ VBoxManage list natnetworks
NetworkName: ff_mgmt
IP: 10.0.2.1
Network: 10.0.2.0/24
IPv6 Enabled: No
IPv6 Prefix: fd17:625c:f037:2::/64
DHCP Enabled: No
Enabled: Yes
Port-forwarding (ipv4)
https1:tcp:[]:4441:[10.0.2.11]:443
https2:tcp:[]:4442:[10.0.2.12]:443
https3:tcp:[]:4443:[10.0.2.13]:443
ssh1:tcp:[]:2221:[10.0.2.11]:22
ssh2:tcp:[]:2222:[10.0.2.12]:22
ssh3:tcp:[]:2223:[10.0.2.13]:22
loopback mappings (ipv4)
127.0.0.1=2
</code></pre>
<p>Relevant part of <code>Vagrantfile</code>:</p>
<pre><code>boxes = [
{
:name => "ff1",
:ip => "10.0.2.11",
:ssh_port => "2221",
:https_port => "4441",
:mac => "0800270fa302",
:memory => "8192",
:cpus => "4"
},
{
:name => "ff2",
:ip => "10.0.2.12",
:ssh_port => "2222",
:https_port => "4442",
:mac => "0800270fb302",
:memory => "8192",
:cpus => "4"
},
{
:name => "ff3",
:ip => "10.0.2.13",
:ssh_port => "2223",
:https_port => "4443",
:mac => "0800270fc302",
:intnet2 => "seg5a",
:memory => "8192",
:cpus => "4"
}
]
Vagrant.configure(2) do |config|
boxes.each do |opts|
config.vm.define opts[:name] do |config|
config.vm.box = "ff"
#config.vm.box_version = 402
config.vm.hostname = opts[:name]
config.ssh.username = 'niska'
config.ssh.private_key_path = '/home/niska/.ssh/id_rsa'
config.vm.network :private_network, ip: opts[:ip]
config.vm.network :forwarded_port, guest: 22, guest_ip: opts[:ip], host: opts[:ssh_port], id: 'ssh'
config.vm.network :forwarded_port, guest: 443, host: opts[:https_port]
config.vm.provider "virtualbox" do |vb|
vb.gui = false
vb.memory = opts[:memory]
vb.cpus = opts[:cpus]
vb.customize ["modifyvm", :id, "--nic1", "natnetwork"]
vb.customize ["modifyvm", :id, "--nictype1", "virtio"]
vb.customize ["modifyvm", :id, "--macaddress1", opts[:mac]]
#vb.customize ["modifyvm", :id, "--intnet1", "ff_mgmt"]
end
end
end
</code></pre>
<p>Output of <code>vagrant up</code>. Notice override of <code>natnetwork</code>. Also port forwarding picks different ports and therefore fails to connect.</p>
<pre><code>$ vagrant reload ff1
==> ff1: Attempting graceful shutdown of VM...
ff1: Guest communication could not be established! This is usually because
ff1: SSH is not running, the authentication information was changed,
ff1: or some other networking issue. Vagrant will force halt, if
ff1: capable.
==> ff1: Forcing shutdown of VM...
==> ff1: Clearing any previously set network interfaces...
==> ff1: Preparing network interfaces based on configuration...
->>> ff1: Adapter 1: nat <<<--- (overrode w/ 'nat')
ff1: Adapter 2: hostonly
==> ff1: Forwarding ports...
ff1: 22 (guest) => 2221 (host) (adapter 1)
ff1: 443 (guest) => 4441 (host) (adapter 1)
==> ff1: Running 'pre-boot' VM customizations...
==> ff1: Booting VM...
==> ff1: Waiting for machine to boot. This may take a few minutes...
ff1: SSH address: 127.0.0.1:22
ff1: SSH username: niska
ff1: SSH auth method: private key
ff1: Warning: Authentication failure. Retrying...
...
Vagrant never connects
</code></pre>
| 2 |
form_for with non-model field
|
<p>I am using Rails's <code>form_for</code> feature to create a form that builds an object. Besides the fields that provide the object's parameters, I want to include a few non-model fields that I can then access in the controller. When I use a non-model symbol for the field, <code>f.check_box</code>, Rails throws an undefined method error. Can anyone explain a better way to do this?</p>
| 2 |
How to configure Jetty SSL Connector with Camel 2.17+
|
<p>I use Apache Camel 2.17.1 and I have some problems in setting up the SSL client authentication on Jetty component (<a href="http://camel.apache.org/jetty.html" rel="nofollow noreferrer">http://camel.apache.org/jetty.html</a>). The first part with the server SSL runs smoothly (setting up the server keystore and access an HTTPS endpoint from the browser). Now I try to enrich the application by adding another route (with a different http port) where the client certificate is required. </p>
<p>From the documentation, this can be achieved through, since the SSL properties aren't exposed directly by Camel: </p>
<pre><code><bean id="jetty" class="org.apache.camel.component.jetty.JettyHttpComponent">
<property name="sslSocketConnectors">
<map>
<entry key="8043">
<bean class="org.eclipse.jetty.server.ssl.SslSelectChannelConnector">
<property name="password"value="..."/>
<property name="keyPassword"value="..."/>
<property name="keystore"value="..."/>
<property name="needClientAuth"value="..."/>
<property name="truststore"value="..."/>
</bean>
</entry>
</map>
</property>
</code></pre>
<p></p>
<p>It seams like the documentation was not updated, because these field names doesn't exist anymore in SslContextFactory. I manage to find other candidates, but got the error:</p>
<pre><code>"org.eclipse.jetty.server.ssl.SslSelectChannelConnector" class doesn't exist anymore.
The JettyHttpComponent.setSslSocketConnectors() method accepts Connector interface objects.
</code></pre>
<p>Could someone help me in finding a solution based on the newer versions of the Apache Camel (like 2.17)?</p>
| 2 |
Float image to the top right in multi-line text
|
<p>I want the icon to stay at the top right. I have tried many things but nothing seems to work. It is only an issue when the text is really long or on a smaller device.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
float: left;
position: relative;
width: 50%;
}
.image-right {
float: right;
position: relative;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
<span class="image-right">
<img style="width:13px; height:13px" src="http://findicons.com/files/icons/2354/dusseldorf/32/plus.png">
</span>
</h3>
</div></code></pre>
</div>
</div>
</p>
| 2 |
How to add new font in PhpPresentation
|
<p>I am trying to make a presentation from Laravel using the PhpPresentation library.</p>
<p>I want to change the font of the presentation from default to "Century Gothic". </p>
<p>Using <code>->setName($pValue = 'Century Gothic');</code> is not working. </p>
| 2 |
Knockout Validation onlyif object no function and pattern validation
|
<p>I want to the priceMax was required, when title is empty.</p>
<p>I have code</p>
<pre><code>self.searchParameters = {
title: ko.observable().extend({
refreshCountOffers: 500
}),
priceMax: ko.observable().extend({
required: {
onlyIf: function() {
return title==null;
}
},
refreshCountOffers: 500
})
};
</code></pre>
<p>,but I get error 'title is not defined'.</p>
<p>How to disable option, which show error for pattern validation, when user input first letter?</p>
<pre><code>postCode: ko.observable().extend({
required: true,
pattern: {
message: 'Post code is not valid',
params: '[0-9]{2}-[0-9]{5}'
},
refreshCountOffers: 500
})
</code></pre>
<p>my <a href="https://jsfiddle.net/llukaszz92/ybamy0du/" rel="nofollow">jsfiddle</a> </p>
| 2 |
PhpStorm how to detect/highlight closing "tag" in PHP's alternate syntax of contol structures
|
<p>Pretty much what the title says. Is there a way to make PhpStorm highlight the closing "tag" when using PHP's alternate syntax for control structures?</p>
<p>Take a look at this sample code for example:</p>
<pre><code><?
if($x==5) {
echo "x is equal to 5";
}
?>
</code></pre>
<p>If i put the cursor next to or before the opening/closing brace, PhpStorm will automatically highlight the matching opening/closing brace.</p>
<p>Now, if we write the same code but this time using PHP's alternate syntax for control structures, we end up with something like this:</p>
<pre><code><? if ($x==5): ?>
x is equal to 5
<? endif; ?>
</code></pre>
<p>In this case, PhpStorm will not highlight either the opening "if" or the closing "endif;". Is there a way to make it highlight it?</p>
| 2 |
QT compile Error undefined reference to `qt_version_tag@Qt_5.7'
|
<p>I'm using a shared library in my project and when I try to compile my project in Qt I experienced error like this undefined reference to `qt_version_tag@Qt_5.7' related with shared lib so file. How can I fix it. I'm using use Qt version 5.6.1. Operating system Ubuntu, I compiled lib myself with qt 5.7. I experienced this error while ı'm trying to compile my project in qt 5.6.1. </p>
| 2 |
redirect exact url to another url
|
<p>There are a bazillion examples online of doing redirects via apache's htaccess, but I can't find any example of redirecting a full URL match to another full URL.</p>
<p>For instance, I have an existing website at </p>
<pre><code>https://example.com
</code></pre>
<p>How do I redirect some specific URLs for that domain to a different one:</p>
<pre><code>https://example.com/login --> https://my.example.com/login
https://example.com/register --> https://my.example.com/register
</code></pre>
<p>For every other every other path on example.com I need to remain untouched so my site still works fine (i.e. <code>/blog</code> shouldn't redirect somewhere else).</p>
| 2 |
Run command in other folder
|
<p>I have a php script that should run a command located in a certain subfolder, in another subfolder.</p>
<p>The command is in folder <code>Cmd</code>, and should be executed in folder <code>1.6.2</code>. So first I switch to the <code>1.6.2</code> directory, and then I use a relative path to call the command:</p>
<pre><code>exec("cd 1.6.2");
exec("..\Cmd\sencha app build production");
</code></pre>
<p>But this throws the error that the directory couldn't be found, because the second <code>exec</code> still executes in the main folder, where the calling index.php file resides.</p>
<p>The <a href="http://php.net/manual/en/function.exec.php" rel="nofollow">php manual on <code>exec</code></a> doesn't provide any possibility to execute in another directory. Am I missing something here?</p>
<p>The current system is a Windows, but I have to make it portable because it may be executed on linux in the future.</p>
| 2 |
Fat-Free-Framework: How to add/modify/delete records of related table using DB\SQL\Mapper
|
<p>Hi everyone I'm currently working on a form that includes rows from a related table and processing the form has presented a challenge: In F3, what is the best method to handle a form that may result in rows in a related table being added, modified or deleted?</p>
<p><strong>DB Schema</strong></p>
<pre class="lang-html prettyprint-override"><code>practitioner
------------------------------
id | int(10)
first_name | varchar(255)
last_name | varchar(255)
abn | char(11)
mobile | varchar(20)
email | varchar(255)
practice_site
------------------------------
id | int(10)
name | varchar(255)
provider_number
------------------------------
id | int(10)
practice_site_id | int(10)
practitioner_id | int(10)
provider_number | varchar(20)
</code></pre>
<p><strong>The Form</strong></p>
<ul>
<li>Provider numbers are added dynamically, form names are amended with <code>_n</code>, e.g. <code>provider_number_3</code></li>
<li>The delete button removes the row altogether, meaning there may be <code>provider_number_1</code> and <code>provider_number_3</code> but no <code>provider_number_2</code></li>
</ul>
<p><a href="https://i.stack.imgur.com/Jhiqb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jhiqb.png" alt="enter image description here"></a></p>
<p><strong>Form Output</strong></p>
<p>The provider numbers are transformed into something a bit more manageable than <code>*_n</code>.</p>
<p>Other fields, <code>id</code>, <code>first_name</code>, etc are easily updated thanks to <code>copyfrom()</code>.</p>
<pre class="lang-php prettyprint-override"><code>Array
(
[id] => 1
[first_name] => Jon
[last_name] => Doctor
[abn] => 12345678902
[mobile] => 0491729472
[email] => [email protected]
[provider_numbers] => Array
(
[0] => Array
(
[provider_number] => ASBDF24
[practice_site_id] => 2
)
[1] => Array
(
[provider_number] => 1249FBK
[practice_site_id] => 2
)
)
)
</code></pre>
<p><strong>The Problem</strong></p>
<p>A few conditions about provider numbers can occur when the form is submitted:</p>
<ul>
<li>A new provider number is added</li>
<li>A provider number is changed</li>
<li>A practice site is changed</li>
<li>A provider number is removed</li>
</ul>
<p>How would be the best way to go about this? (Preferably using Fat-Free-Framework's <code>DB\SQL\Mapper</code> class).</p>
<p>Possible solution:</p>
<ul>
<li>Do a <code>$db->exec()</code> to get an array of existing <code>provider_number</code> table where <code>provider_id = POST.id</code></li>
<li>Perform an <code>array_diff()</code> to find any records in database that aren't in form then do a <code>DELETE</code> statement on those records. Truncate the original array.</li>
<li>Traverse through array looking whether the <code>provider_number</code>s match. If they do, but <code>practice_site_id</code> is different, update. If <code>practice_site_id</code> is the same, do nothing.</li>
<li>How to accurately determine if a <code>provider_number</code> has changed for a particular <code>practice_site_id</code>?</li>
</ul>
<p>Another possibility:</p>
<ul>
<li>Change the form to include <code>provider_number.id</code>, when a new row is added, grab the newest available ID from the database</li>
</ul>
| 2 |
wildfly10: NoClassDefFoundError on deployment for cxf-rt-rs-extension-search
|
<p>I added apache cxf-rt-rs-extension-search to my pom.xml and get the following stacktrace on deployment to wildfly 10.</p>
<pre><code>09:08:07,503 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 159) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./mis2-web: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./mis2-web: java.lang.NoClassDefFoundError: Failed to link org/apache/cxf/jaxrs/ext/search/QueryContextProvider (Module "deployment.mis2-ear.ear.mis2-web.war:main" from Service Module Loader): org/apache/cxf/jaxrs/ext/ContextProvider
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:85)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.NoClassDefFoundError: Failed to link org/apache/cxf/jaxrs/ext/search/QueryContextProvider (Module "deployment.mis2-ear.ear.mis2-web.war:main" from Service Module Loader): org/apache/cxf/jaxrs/ext/ContextProvider
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:446)
at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:274)
at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:78)
at org.jboss.modules.Module.loadModuleClass(Module.java:605)
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at org.jboss.resteasy.spi.ResteasyDeployment.registerProvider(ResteasyDeployment.java:546)
at org.jboss.resteasy.spi.ResteasyDeployment.registration(ResteasyDeployment.java:342)
at org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:245)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.init(ServletContainerDispatcher.java:113)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.init(HttpServletDispatcher.java:36)
at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:117)
at org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor.init(RunAsLifecycleInterceptor.java:78)
at io.undertow.servlet.core.LifecyleInterceptorInvocation.proceed(LifecyleInterceptorInvocation.java:103)
at io.undertow.servlet.core.ManagedServlet$DefaultInstanceStrategy.start(ManagedServlet.java:231)
at io.undertow.servlet.core.ManagedServlet.createServlet(ManagedServlet.java:132)
at io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:526)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:101)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
... 6 more
</code></pre>
<p>The dependency in the pom of my web-module is as follows:</p>
<pre><code><dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-search</artifactId>
<version>3.1.4</version>
</dependency>
</code></pre>
<p>In the pom of my ear-module I added the dependency for the apache cxf service:</p>
<pre><code><archive>
<manifestEntries>
<ImplementationVersion>${project.version}</ImplementationVersion>
<Dependencies>org.apache.cxf services</Dependencies>
</manifestEntries>
</archive>
</code></pre>
<p>What am I doing wrong or what is missing here?
Thank you!</p>
| 2 |
Compile time replacement of string constants with integers
|
<p>I have a list of pre-defined mappings of string constants to numbers outside of
my code base. The integers map to data inside of the program but I want to use the far more readable string constants in my code. The resulting binary should only contain the numbers and not contain the string constants at all. Is it possible to replace the string constants with the mapped integer at compile time?</p>
<p>What I want to achieve is basically having this code:</p>
<pre><code>getData("a string constant here");
</code></pre>
<p>and I want to transform it into this:</p>
<pre><code>getData(277562452);
</code></pre>
<p>Is this possible via macros or constexpr?</p>
| 2 |
MySQL Alter table add column with default of 1
|
<p>I have read most of the posts concerning MySQL ALTER TABLE but can't find an answer to my issue.</p>
<p>I have a script that adds a new column to a table, this works fine but the issue I have is it is not setting the default value for the new column. Am I missing something:</p>
<pre><code>ALTER TABLE Hist ADD S1 VARCHAR( 5 ) DEFAULT '1', ADD comments_S1 TEXT
</code></pre>
<p>The above is the code I am using.</p>
<p>Any idea's</p>
<p>Many thanks in advance for your time.</p>
| 2 |
Programmatically change checked of a checkbox
|
<p>I have the following two checkboxes:</p>
<pre><code><input type="checkbox" id="id3"></input>
<input type="checkbox" id="id4"></input>
</code></pre>
<p>the desired behaviour is that when i click on id3, id4 should adopt.</p>
<p>that works fine for the first and second click but aftwerwards not anymore. any idea why?</p>
<p>here my script:</p>
<pre><code><script>
function test2()
{
var checked = this.checked;
if(checked)
$("#id4").attr("checked", "checked");
else
$("#id4").removeAttr("checked");
}
$("#id3").click(test2);
</script>
</code></pre>
<p>(or a working dojo here <a href="http://dojo.telerik.com/eviTi" rel="nofollow">http://dojo.telerik.com/eviTi</a>)</p>
| 2 |
Lua getting XOR key and decoding
|
<p>I'm trying to get the key of a xor file and decode it using said key.</p>
<pre><code>function GetKey(data)
local base = {'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x',
'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x',
'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x',
'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x',
'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x',
'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x',
'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'}
local key = ""
for i=0, 100 do
key = key .. string.char(bit32.bxor(data:sub(i+1,i+1):byte(), base[(i%(#base))+1]:byte()))
end
return key:sub(65,65) .. key:sub(34,64)
end
function Decode(s, key)
local i = 1
s = s:gsub("(.)", function(t)
if (i > key:len()) then
i = 1
end
k = bit32.bxor(t:byte(), key:sub(i,i):byte())
i = i + 1
return string.char(k)
end)
return s
end
local s = io.open(select(1,...), "rb"):read("*a")
local key = GetKey(s)
print("Key found: " .. key)
print("Decoding...")
s = Decode(s, key)
local outfile = io.open(select(1,...) .. ".xor", "wb")
print("Finished!")
</code></pre>
<p>This is the code I have for getting the key and decoding. At the moment it gets the wrong key and therefore decodes files incorrectly.</p>
<p>Anyone have any help or can give some pointers?</p>
<p>Thanks</p>
| 2 |
Sitecore Lucene Exclude Item From Index
|
<p>I'm trying to allow a content editor to have the option to exclude items from a search page. There is a checkbox on the template being searched which indicates whether or not it should show up or not. I've seen a few answer that involve inheriting from Sitecore.Search.Crawlers.DatabaseCrawler and overriding the AddItem method (<a href="https://stackoverflow.com/questions/6193990/excluding-items-selectively-from-sitecores-lucene-search-index-works-when-reb">Excluding items selectively from Sitecore's Lucene search index - works when rebuilding with IndexViewer, but not when using Sitecore's built-in tools</a>). This does not seem to be hit when rebuilding indexes from the control panel though. I have been able to hit a method in Sitecore.ContentSearch.SitecoreItemCrawler called RebuildFromRoot. Does anyone know exactly when the DatabaseCrawler method from that question is hit? I have a feeling I'll need to use both a custom SitecoreItemCrawler and DatabaseCrawler but I'm not positive. Any insight would be appreciated. I am using Sitecore 8.0 (rev. 150621).</p>
| 2 |
SQL Server stored procedure doesn't seem to work when run by SQL Server Agent
|
<p>I have an issue where a stored procedure I built to process some data doesn't seem to work correctly when being run by the SQL Server Agent. If I manually execute the job everything works fine. I also get no errors.</p>
<p>The basic process is I have three source tables (A,B,C), each are for a different type of service. They are used to calculate a value, and since the calculation process is different each year, there are multiple results, so ID B43 will have result15, and result16, corresponding to the 2014/15 and 2015/16 financial years. The final result is stored in a master table that contains the ID, Type, and both result values for each record. </p>
<p>To make this work, I have six stored procedures that run sequentially, first for the 14/15 calculation then for the 15/16 calculation.</p>
<p>The general structure of each stored procedure is to take the data, manipulate it based on some mapping tables and create a CalculationInput table, which is simply there to review the input into the calculation for audit checks. Once this is done, the actual calculation occurs with the result is stored in a temp table <code>#Results</code>. After the temp table is built, I create some indexes, and then call another stored procedure, passing in the financial year as a parameter, which takes the temp table and does a insert update on the master table. After that, the stored procedure ends, and the next one is called.</p>
<pre><code>StoredProcA15 -> InsUpdProc
StoredProcB15 -> InsUpdProc
StoredProcC15 -> InsUpdProc
StoredProcA16 -> InsUpdProc
StoredProcB16 -> InsUpdProc
StoredProcC16 -> InsUpdProc
</code></pre>
<p>As I said before, this works perfectly fine if I right click on the job and execute it. However if I then wait a week and look at the master table, new records won't be there, despite them being in the source table, as well as the CalculationInput table. If I then run the section of code that builds the temp table, the result appears there.</p>
<p>So my best guess at the source of the failure is the call to the insert/update procedure. Without knowing more about SQL Server concurrency, I am wondering if parent stored procedure isn't waiting for the insert/update procedure to finish before it ends and moves onto the next stored procedure.</p>
<p>Is this a possibility? And if so, what is the best way to fix it?</p>
| 2 |
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) ENUM type
|
<p>I am using postgres and sqlalchemy to setup a reservation table that holds information on specific job applications. When a user applies for a job, the default status of the application is 'pending.' Once the reservation is accepted, the status of the application changes. I'm implementing an enum type to switch between states. I'm receiving an error that says this ENUM type is not being handled properly with postgres. I'm in the process of switching my DB from SQLite to postgres so this many be a postgres syntax difference. Thank you in advance :~)</p>
<p>[SQL: "CREATE TYPE reservation_status_enum AS ENUM ('pending', 'confirmed', 'rejected')"]</p>
<p>Here is my model:</p>
<pre><code>class Reservation(db.Model):
__tablename__ = "reservations"
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
message = db.Column(db.String, nullable=False)
status = db.Column(db.Enum('pending', 'confirmed', 'rejected', name='reservation_status_enum'), default='pending')
anonymous_phone_number = db.Column(db.String, nullable=True)
guest_id = db.Column(db.Integer, db.ForeignKey('users.id'))
job_task_id = db.Column(db.Integer, db.ForeignKey('job_listings.id'))
guest = db.relationship("User", back_populates="reservations")
job_task = db.relationship("JobTask", back_populates="reservations")
def __init__(self, message, job_task, guest):
self.message = message
self.guest = guest
self.job_task = job_task
self.status = 'pending'
</code></pre>
<p>Here is my sqlalchemy setup:</p>
<pre><code>op.create_table('reservations',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('message', sa.String(), nullable=False),
sa.Column('status', sa.Enum('pending', 'confirmed', 'rejected', name='reservation_status_enum'),
nullable=True),
sa.Column('anonymous_phone_number', sa.String(), nullable=True),
sa.Column('guest_id', sa.Integer(), nullable=True),
sa.Column('job_task_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['guest_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['job_task_id'], ['job_listings.id'], ),
sa.PrimaryKeyConstraint('id')
)
</code></pre>
<p>Here is my stacktrace:</p>
<pre><code> File "/Users/shai/Development/Python/mask_num/gigaware/venv/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 450, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) type "reservation_status_enum" already exists [SQL: "CREATE TYPE reservation_status_enum AS ENUM ('pending', 'confirmed', 'rejected')"]
</code></pre>
| 2 |
JSON Weather Feed in PHP
|
<p>I am trying to display this weather information by pulling it from a JSON feed in PHP. I can't figure out why it is not printing. Here is the code:
<pre><code>$url="http://api.openweathermap.org/data/2.5/forecast?q=Albany,usl&APPID=5099c5feb579c7a17b030de0d009282f&units=metric";
$json=file_get_contents($url);
$data=json_decode($json);
echo '<h1>', $data->name, ' (', $data->sys->country, ')</h1>';
// the general information about the weather
echo '<h2>Temperature:</h2>';
echo '<p><strong>Current:</strong> ', $data->main->temp, '&deg; C</p>';
echo '<p><strong>Min:</strong> ', $data->main->temp_min, '&deg; C</p>';
echo '<p><strong>Max:</strong> ', $data->main->temp_max, '&deg; C</p>';
?>
</code></pre>
<p>My output is something like: </p>
<p>()</p>
<p>Temperature:</p>
<p>Current: ° C</p>
<p>Min: ° C</p>
<p>Max: ° C</p>
| 2 |
Why is const sometimes part of the function signature?
|
<p>Why does const create a different signature when its applied to a struct pointer as opposed to a struct?</p>
<p>E.g.</p>
<pre><code>typedef struct test_s {
int foo;
} test;
void foo(test *ptr){
return;
}
// This is ok
void foo(const test *ptr){
return;
}
void foo(test t){
return;
}
//This is an error
void foo(const test t){
return;
}
</code></pre>
<p>(tested on gcc version 4.9.2)</p>
<p>To be more specific, why is it that the bottom one is an error when the pair with the pointers is not an error. The referenced duplicate question (<a href="https://stackoverflow.com/questions/3682049/functions-with-const-arguments-and-overloading">Functions with const arguments and Overloading</a>) would also seem to argue that the case with the pointers should be duplicates.</p>
| 2 |
OkHttp upload progress is not in sync with the actual upload
|
<p>I'm trying to track the progress of an upload using OkHttp. I have created a custom <code>RequestBody</code> with the following body (courtesy of <a href="https://stackoverflow.com/questions/35528751/okhttp-3-tracking-multipart-upload-progress/36260692#36260692">this answer</a>) which writes to sink and publishes the progress.</p>
<pre><code>public class CountingFileRequestBody extends RequestBody {
private static final String TAG = "CountingFileRequestBody";
private final ProgressListener listener;
private final String key;
private final MultipartBody multipartBody;
protected CountingSink mCountingSink;
public CountingFileRequestBody(MultipartBody multipartBody,
String key,
ProgressListener listener) {
this.multipartBody = multipartBody;
this.listener = listener;
this.key = key;
}
@Override
public long contentLength() throws IOException {
return multipartBody.contentLength();
}
@Override
public MediaType contentType() {
return multipartBody.contentType();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
mCountingSink = new CountingSink(sink);
BufferedSink bufferedSink = Okio.buffer(mCountingSink);
multipartBody.writeTo(bufferedSink);
bufferedSink.flush();
}
public interface ProgressListener {
void transferred(String key, int num);
}
protected final class CountingSink extends ForwardingSink {
private long bytesWritten = 0;
public CountingSink(Sink delegate) {
super(delegate);
}
@Override
public void write(Buffer source, long byteCount) throws IOException {
bytesWritten += byteCount;
listener.transferred(key, (int) (100F * bytesWritten / contentLength()));
super.write(source, byteCount);
delegate().flush(); // I have added this line to manually flush the sink
}
}
}
</code></pre>
<p>The problem here is, the data is written to the sink immediately without actually sending the buffered bytes to the server. Meaning my progress reaches the end long before the actual upload.<br>
<strong><em>Note:</em></strong> <a href="https://stackoverflow.com/a/26376724/370073">Some say</a> that the sink needs to be flushed on every iteration for bytes to be actually uploaded but it's not working for me.</p>
| 2 |
Call a static C++/CLI method from C++
|
<p>In a C++CLI project I make a call to a native object on an event, I'd like to be able to call a C++/CLI function from the native C++ when this event is triggered. I have following code at the moment, but it returns the error that PickObjects() is not a member of ManagedClass. Is calling back to a static C++CLI method possible?</p>
<pre><code>#pragma once
#include "Stdafx.h"
#include "ManagedClass.h"
namespace Unmanaged
{
public class EventHandlers
{
public:
static void OnClick(customObject* caller, void *calldata)
{
//call managed method, can get here from CLI
ManagedClass::ManagedObject::PickObjects();
}
};
}
</code></pre>
<p>Here is the C++CLI code snippet, everything here appears to run fine:</p>
<pre><code>namespace ManagedClass
{
public ref class ManagedObject
{
public:
static void PickObjects()
{
//pick stuff when called
}
};
}
</code></pre>
<p>EDIT: Got it working, the error was definitely related to how Visual Studio compiled the files. Will update with solution momentarily. Thanks to Matthias for the help.</p>
| 2 |
Is libuv under the hood use epoll or select(2) in unix
|
<p>I have been reading around how nodejs uses libuv to perform asynchronous I/O. Reading more about it give me a feeling that it almost sound similar to how select(2) and epoll.</p>
<p>So, my question if I'm using libuv(via node) is it true internally I using select(2) or epoll.</p>
<p>Is libuv is wrapper over select(2) and epoll system call in unix.?</p>
| 2 |
df.loc to remove whole row based on condition
|
<p>Quick question,</p>
<p>How would I adapt </p>
<pre><code>df2.loc[df2['A'] ==0, 'B'] = np.NaN
</code></pre>
<p>To change to the whole row, aka B,C etc become np.Nan
Without a for loop as this would take too long</p>
<p>Many thanks</p>
| 2 |
Increment field based on foreign key (JPA, Hibernate, Oracle DB)
|
<p>Is it possible to have a field auto-increment based on a foreign key? I would like to achieve this with JPA (Hibernate) and Oracle DB. I've read it's not possible with <code>MySQL</code>'s <code>InnoDB</code> engine.</p>
<p>It is pretty much like the following questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/19786665/mysql-second-auto-increment-field-based-on-foreign-key">mysql-second-auto-increment-field-based-on-foreign-key</a></li>
<li><a href="https://stackoverflow.com/questions/3605085/mysql-auto-increment-based-on-foreign-key">mysql-auto-increment-based-on-foreign-key</a></li>
</ul>
<p>But these are only based on MySQL tables itself. Not JPA & Oracle DB.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/26146112/hibernate-autoincrement-non-primary-key-based-on-foreign-key">hibernate-autoincrement-non-primary-key-based-on-foreign-key</a></li>
</ul>
<p>Is exactly as I need, but sadly there is no answer.</p>
<p>As a concrete example, consider a simple example. Each <code>Student</code> has multiple <code>Book</code>s. The <code>Book</code> has a primary key (regular increment), but it also has a <code>followUpNumber</code>. This number starts at 1 and auto-increments for each added <code>Book</code> to a <code>Student</code>. Meaning every <code>Student</code> has a list of <code>Book</code> of which the <code>followUpNumber</code> starts at 1 everytime. Here's the <code>Book</code> table to display what i mean:</p>
<pre><code>|------|------------|-----------------|
| id | student_id | followup_number |
|------|------------|-----------------|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 1 |
| 5 | 1 | 4 |
| 6 | 1 | 5 |
| 7 | 2 | 2 |
| 8 | 3 | 1 |
| 9 | 3 | 2 |
|------|------------|-----------------|
</code></pre>
<ul>
<li><strong>id</strong> being the primary key</li>
<li><strong>student_id</strong> being the foreign key to student</li>
<li><strong>followup_number</strong> being the field which starts at 1 for every <em>student_id</em></li>
</ul>
<p>Is there something like a custom <a href="https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/GeneratedValue.html" rel="nofollow noreferrer"><code>@GeneratedValue</code></a> strategy that doesn't need to be placed on primary key fields? My current solution is just before adding a new <code>Book</code>, iterate over all <code>Book</code>s, get the highest followup_number and assign that number + 1 to the new book. But I feel there must be a cleaner, more elegant way to do this.</p>
| 2 |
AWS SNS dynamic subscriptions
|
<p>We have got a strange requirement and we would like to send SMS to our clients based on the assets they are monitoring. Each asset can have 100s of subscribers and there are 1000s of assets so obviously, we can not create one SNS topic per asset. We have the assets and their list of subscribers in a RDS instance on AWS.</p>
<p>Is there anyway with SNS to make the list of its subscribers dynamic, each time we publish a message to it we also supply the list of subscriber this message should be sent to? What are my other options or another AWS service? Lambda maybe? Please advise. thanks</p>
| 2 |
How to send the http post request in SWIFT?
|
<p>Please correct this code</p>
<pre><code>@IBAction func registeruser(sender: AnyObject) {
let usertext = useremail.text;
let myURL = NSURL(string: "http://advaluead.com/vishwa/index.php");
let request = NSMutableURLRequest(URL:myURL!);
request.HTTPMethod = "POST";
let poststring = "email=\(usertext)";
request.HTTPBody = poststring.dataUsingEncoding(NSUTF8StringEncoding);
}
</code></pre>
<p>My server is not getting any request from the App.</p>
| 2 |
OpenSSL C RSA library decryption
|
<p>I am using these functions to encrypt and decrypt a text file into an output text file using RSA_public_encrypt and RSA_private_decrypt</p>
<p>While launching the command line program taking as an input public key file name or private key file name, the encryption process is working just fine whereas decryption is always failing.</p>
<p>Below is the encryption file function I am calling that calls readRSAKeyFromFile to return RSA data type, to handle it later on.</p>
<p>If I am missing something here let me know.</p>
<p>I am kind of new to C, and I thought giving a shot trying to write something as a test to understand C basics.</p>
<p>Your help would be very appreciated</p>
<p>void enc_file(char *pub_key_name, char *file_name){</p>
<pre><code> RSA *rsa = readRSAKeyFromFile(pub_key_name, 1);
char *data_read_from_file;
long fileSize = 0;
unsigned char *encrypted_data = (unsigned char*)malloc( RSA_size(rsa) ) ;
FILE * stream = fopen (file_name, "rb");
//Seek to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);
//Allocate enough memory (add 1 for the \0, since fread won't add it)
data_read_from_file = malloc(fileSize+1);
//Read the file
size_t size=fread(data_read_from_file,1,fileSize,stream);
data_read_from_file[size]= 0; // Add terminating zero.
fclose(stream);
int result = public_key_encryption(data_read_from_file, encrypted_data, rsa);
free(data_read_from_file);
FILE * file = fopen("encrypted_data.txt","w+");
fputs((const char *)encrypted_data,file);
fclose(file);
printf(" %s \n", encrypted_data );
if( result == -1 ){
perror("Couldn't encrypt file");
}else{
printf("[*] Successfully encrypted data \n" );
}
}
void dec_file(char *priv_key_name, char *file_name){
RSA *rsa = readRSAKeyFromFile(priv_key_name, 0);
char *data_read_from_file;
long fileSize = 0;
unsigned char *decrypted_data = (unsigned char*)malloc( RSA_size(rsa) ) ;
FILE * stream = fopen (file_name, "rb");
//Seek to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);
//Allocate enough memory (add 1 for the \0, since fread won't add it)
data_read_from_file = malloc(fileSize+1);
//Read the file
size_t size=fread(data_read_from_file,1,fileSize,stream);
data_read_from_file[size]= 0; // Add terminating zero.
fclose(stream);
int result = private_key_decryption(data_read_from_file, decrypted_data, rsa);
free(data_read_from_file);
FILE * file = fopen("encrypted_data.txt","w+");
fputs((const char *)decrypted_data,file);
fclose(file);
printf(" %s \n", decrypted_data );
if( result == -1 ){
perror("Couldn't encrypt file");
}else{
printf("[*] Successfully decrypted data \n" );
}
}
RSA * readRSAKeyFromFile(char * filename,int is_public){
FILE * rsa_pkey_file = fopen(filename,"r");
if(rsa_pkey_file == NULL){
printf("ERROR opening file :: %s \n",filename);
return NULL;
}
// RSA * rsa_key= RSA_new();
RSA *rsa_pkey = NULL;
if(is_public == 1 ){
PEM_read_RSA_PUBKEY(rsa_pkey_file, &rsa_pkey, NULL, NULL);
}else{
PEM_read_RSAPrivateKey(rsa_pkey_file, &rsa_pkey, NULL, NULL);
}
return rsa_pkey;
}
int public_key_encryption( char *data, unsigned char *encrypted, RSA *rsa_key){
int result = RSA_public_encrypt( (int)strlen(data), (const unsigned char*)data, encrypted, rsa_key, RSA_PKCS1_PADDING ) ;
return result;
}
int private_key_decryption(char * data, unsigned char *decrypted, RSA *rsa_key){
int result = RSA_private_decrypt((int)strlen(data),(const unsigned char *)data,(unsigned char*)decrypted,rsa_key,RSA_PKCS1_PADDING);
return result;
}
</code></pre>
| 2 |
How to pass list of paths to a function?
|
<p>I want to pass list of directory names to function,
like so:</p>
<pre><code>use std::path::Path;
fn test(dirs: &Vec<Path>) {}
fn main() {
let dirs = vec![Path::new("/tmp"), Path::new("/var/tmp")];
test(dirs);
}
</code></pre>
<p>But it does not compile:</p>
<pre><code><anon>:3:5: 4:6 error: the trait bound `[u8]: std::marker::Sized` is not satisfied [E0277]
<anon>:3 fn test(dirs: &Vec<Path>) {
<anon>:4 }
<anon>:3:5: 4:6 help: see the detailed explanation for E0277
<anon>:3:5: 4:6 note: `[u8]` does not have a constant size known at compile-time
<anon>:3:5: 4:6 note: required because it appears within the type `std::sys::os_str::Slice`
<anon>:3:5: 4:6 note: required because it appears within the type `std::ffi::OsStr`
<anon>:3:5: 4:6 note: required because it appears within the type `std::path::Path`
<anon>:3:5: 4:6 note: required by `std::vec::Vec`
</code></pre>
<p>Looks like Path not <code>Sized</code>?</p>
<p>How should I fix this, if I do not want to pass <code>Vec<String></code> to function?
Maybe <code>PathBuf</code>? How to implement this in rusty way?</p>
| 2 |
Running a Powershell script on another server from a PHP script?
|
<p>Our company's system has two servers, one that handles web-side scripts, and another that contains all our Active Directory information. Let's call them "webServer" and "adServer".</p>
<p>I have a Powershell (V5) script on adServer that returns an AD account's password expiration date. I'm writing a PHP script on webServer where a user can input a username, then have that account's password expiration date printed to them. Thus, I need to call the Powershell script from this PHP script.</p>
<p>I know you use shell_exec() to run Powershell scripts in PHP, but how would I run a script on a different server? Assuming C:\pwdDate.ps1 is the file path on adServer, this is all I have right now:</p>
<pre><code>$pwdExpDate = shell_exec('powershell -File C:\pwdDate.ps1 -Username $username');
echo $pwdExpDate
</code></pre>
| 2 |
No api-ms-win-crt-runtime-l1-1-0.dll on Windows 10 after Visual C++ 2015 redistributable packages
|
<p>my WIX installer detects if installing VCRedist 14 (aka Microsoft Visual C++ 2015 redistributable packages) is required using the presence of <strong>api-ms-win-crt-runtime-l1-1-0.dll</strong>, because without it, my C++ app built with VStudio 2015 wouldn't run on Windows 7 / 8 / 8.1 with this famous error:</p>
<blockquote>
<p>The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is
missing from your computer. Try reinstalling the program to fix this
problem.</p>
</blockquote>
<p>However, my app runs fine on Windows 10 without VCRedist 14, although api-ms-win-crt-runtime-l1-1-0.dll doesn't exist.
I don't know how & why: even Dependency Walker (depends.exe) displayed the error "Cannot find <strong>api-ms-win-crt-runtime-l1-1-0.dll</strong>"</p>
<p>On Windows 10, even if I installed VCRedist 14, api-ms-win-crt-runtime-l1-1-0.dll was never copied to System32 directory. Anyone know why?</p>
<p>Also can anyone explain how any C++ app built with VS2015 doesn't require VCRedist 14 on Windows 10?</p>
| 2 |
References page truncated in RMarkdown ioslides presentation
|
<p>I prepare a ioslides presentation in RMarkdown via RStudio. As the presentation contains a lot of references they are truncated:
<a href="https://i.stack.imgur.com/CglGX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CglGX.png" alt="enter image description here"></a>
With <code>{.allowframebraks}</code>there seems to be a quick solution for <code>beamer</code> presentations as <a href="https://stackoverflow.com/questions/35677857/references-truncated-in-beamer-presentation-prepared-in-knitr-rmarkdown">this answer</a> shows.
Is there one for ioslides, too?</p>
| 2 |
Which is the best free data warehouse products
|
<p>I am developing a system which constains a lot of olap work. According to my research, column based data warehouse is the best choice. But I am puzzled to choose a good data warehouse product. </p>
<ol>
<li><p>All the data warehouse comparison article I see is befor 2012,and there seems little article about it. Is data warehouse out-of-date? Hadoop HBase is better?</p></li>
<li><p>As far as I know, InfiniDB is a high performance open source data warehouse product, but it has not been maintained for 2 years <a href="https://github.com/infinidb/infinidb" rel="nofollow">https://github.com/infinidb/infinidb</a>. And there is little document about InfiniDB . Has InfiniDB been abundanted by developers ?</p></li>
<li><p>Which is the best data warehouse product by now?</p></li>
<li><p>How do I incrementally move my Business data stored in the Mysql database to data warehouse ?</p></li>
</ol>
<p>Thank you for your answer!</p>
| 2 |
Publishing fails after unpublishing
|
<p>In my application I do the following steps:</p>
<ol>
<li>Publish audio only</li>
<li>Unpublish</li>
<li>Publish audio+video</li>
<li>Unpublish</li>
<li>Publish audio only</li>
</ol>
<p>At stage 5 it fails with the following error:</p>
<blockquote>
<p>index.js:460 OT.Publisher.onPublishingTimeoutonPublishingTimeout @
index.js:460(anonymous function) @ index.js:1472 index.js:332
OT.Publisher State Change Failed: 'Failed' cannot transition to
'MediaBound'stateChangeFailed @ index.js:332signalChangeFailed @
generate_simple_state_machine.js:38handleInvalidStateChanges @
generate_simple_state_machine.js:55set @
generate_simple_state_machine.js:65onPublishingTimeout @
index.js:477(anonymous function) @ index.js:1472 ot_error.js:341
OT.exception :: title: Unable to Publish (1500) msg:
ICEWorkflow_exceptionHandler @
ot_error.js:341OTError.handleJsException @
ot_error.js:412onPublishingTimeout @ index.js:493(anonymous function)
@ index.js:1472 handle.js:1071 1500 "Session.publish :: Could not
publish in a reasonable amount of time"</p>
</blockquote>
<p>I could reproduce this in all devices that were accessible to me at that time:</p>
<ul>
<li>Chrome on iMac</li>
<li>Firefox on iMac</li>
<li>Chrome on Macbook pro</li>
<li>Chrome on</li>
<li>Android 4.x</li>
</ul>
| 2 |
Test REST API from local server in ionic real android device
|
<p>I have a MongoDB server running locally on my laptop.
In my app I'm making HTTP get requests to the server with localhost:server_port.
Both my laptop and my phone are connected to the same WiFi.
When I'm testing my app with ionic serve I get a response when I make the requests. However, on my android phone it doesn't work.</p>
<p>I know there are a few possible solutions for this but I've tried them all with no success.</p>
| 2 |
Google Map Autocomplete API not adding address options
|
<p>I'm trying to implement this <a href="https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform" rel="nofollow">https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform</a> on a website built with asp.net to autofill an address field. The problem is when I start typing, nothing happens. I'll go into dev tools, theres an element added by the API with a class <code>pac-container</code>. I'll set its display to block and see that it displays a small white dropdown with "Powered by Google" in the corner. I see in the working example that there are a list of divs with a class <code>pac-item</code> that are inside the <code>pac-container</code> and contain the suggested addresses when you begin typing an address. Does anyone know why I am not getting this? Thank you.</p>
| 2 |
Combine 1 field from multiple rows via AmpScript
|
<p>I have a data extension which contains rows and columns such as:</p>
<pre><code>emailAddress orderNumber firstName lastName customerOrder
[email protected] 1111 Bill Adams 2 brown shoes
[email protected] 1111 Bill Adams 2 green socks
[email protected] 1111 Bill Adams 1 orange backpack
[email protected] 2222 Bill Adams 2 pink gloves
[email protected] 3333 David Sherwood 5 yellow hats
</code></pre>
<p>What I'm trying to do is to create an order received email from this data, preferably without altering it from the source. So ideally the email output would group the customerOrder for each customer, based on the orderNumber. Then the customerOrder is concatenated and inserted into an email (note the above is simplified quite a bit, the customerOrder is actually HTML for insertion into an HTML table within the email). </p>
<p>So far I've been able to make this much very basic progress:</p>
<pre><code>%%[
Set @customerOrder =
LookupOrderedRows("transactionsList",
"0",
"customerOrder",
"orderNumber",
"1111")
]%%
</code></pre>
<p>With this code I can see that I have 3 entries for order number 1111. But now I'm stuck. Do I need to create an if/then loop? Or is there some way to take the output from the LookupOrderedRows function and parse it for use in the HTML table within the email?</p>
| 2 |
R macros to enable user defined input similar to %let in SAS
|
<p>I am trying to automate a particular process in R, where essentially the code remains the same but the input files imported change- the path and most of the file name is the same only one word changes- and certain variable names change.
I would like to make these changes user defined: much like %let in SAS. where i can call a value with &.</p>
<p>For example if i have this particular import code:</p>
<pre><code>Category_sales<- read.csv("C:/Projects/Consumption curves/UKPOV/excel files/MSP_product_CC_2009_salespercap.csv")
</code></pre>
<p>Where I would like only the word MSP to change depending on what the user wants.
In SAS I would define a macrovariable like say %let metric=MSP</p>
<p>and replace the code as </p>
<pre><code>`C:/Projects/Consumption curves/UKPOV/excel files/&metric_product_CC_2009_salespercap.csv`
</code></pre>
<p>Also If I have a variable say <strong>MaxGNI</strong> and I would like only the GNI part to be user defined/replaced like <strong>Max&econvar</strong> where I could have <strong>econvar</strong> defined as <strong>%let econvar= GNI</strong> or any other metric.</p>
<p>I am looking for something similar in R however.</p>
| 2 |
Bash Jq parse json string
|
<p>I've to call a file and pass a json as parameters in this way
(suppose that my file is called test.sh), from bash I need to do something like this:</p>
<pre><code>./test.sh "[{\"username\":\"user1\",\"password\":\"pwd1\",\"group\":\"usergroup1\"},{\"username\":\"user2\",\"password\":\"pwd2\",\"group\":\"usergroup2\"},{\"username\":\"user3\",\"password\":\"pwd3\",\"group\":\"usergroup3\"}]"
</code></pre>
<p>and the content of test.sh is the following</p>
<pre><code>#!/bin/bash
#read the json
system_user="$1"
printf "$system_user"
accounts=($(jq -s ".[]" <<< $system_user))
printf "$accounts"
for account in "${accounts[@]}"
do
printf "\n\n$account\n\n"
done
</code></pre>
<p>the output of -> printf "$system_user" is</p>
<pre><code>[{"username":"user1","password":"pwd1","group":"usergroup1"},{"username":"user2","password":"pwd2","group":"usergroup2"},{"username":"user3","password":"pwd3","group":"usergroup3"}]
</code></pre>
<p>but the output of -> printf "$accounts" is something like this</p>
<p>[<br/>
[<br/>
{<br/>
"username":<br/>
"user1"<br/>
etc. etc. one object for each token :-( <br/><br/></p>
<p>and so on, but what I was expecting is an array of three object (like you can test on jqplay.org)</p>
<pre><code> {
"username": "user1",
"password": "pwd1",
"group": "usergroup1"
}
{
"username": "user2",
"password": "pwd2",
"group": "usergroup2"
}
{
"username": "user3",
"password": "pwd3",
"group": "usergroup3"
}
</code></pre>
<p>In this way I can make a foreach on ${accounts[@]}</p>
<p>What I'm doing wrong?
Thank you</p>
| 2 |
How to get IOwinContext in AspNet Core 1.0.0
|
<p>I'm using Owin and UseWsFederationAuthentication() in AspNetCore MVC 1.0.0. app. Authentication works perfectly but i cant SignOut the user.</p>
<p>This code</p>
<pre><code>public class AccountController : Controller
{
public async Task<IActionResult> SignOut()
{
await this.HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationType);
return RedirectToAction("Index", "Test");
}
}
</code></pre>
<p>Throws:</p>
<blockquote>
<p>InvalidOperationException: No authentication handler is configured to handle the scheme: Cookies</p>
</blockquote>
<p>The <code>HttpContext.Authentication</code> is set to <code>Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager</code></p>
<p>Startup.cs:Configure</p>
<pre><code> app.UseOwinAppBuilder(builder =>
{
var authConfig = new WsFederationAuthenticationSettings
{
MetadataAddress = this.Configuration.GetValue<string>("Eyc.Sdk:Authentication:WsFederation:MetadataAddress"),
Realm = this.Configuration.GetValue<string>("Eyc.Sdk:Authentication:WsFederation:Realm"),
UseCookieSlidingExpiration = this.Configuration.GetValue<bool>("Eyc.Sdk:Authentication:WsFederation:UseCookieSlidingExpiration"),
CookieExpireTimeSpan = this.Configuration.GetValue<string>("Eyc.Sdk:Authentication:WsFederation:CookieExpireTimeSpan")
};
builder.UseEycAuthentication(authConfig, app.ApplicationServices);
});
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseOwinAppBuilder(this IApplicationBuilder app, Action<global::Owin.IAppBuilder> configuration)
{
return app.UseOwin(setup => setup(next =>
{
var builder = new AppBuilder();
var lifetime = (IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));
var properties = new AppProperties(builder.Properties);
properties.AppName = app.ApplicationServices.GetApplicationUniqueIdentifier();
properties.OnAppDisposing = lifetime.ApplicationStopping;
properties.DefaultApp = next;
configuration(builder);
return builder.Build<Func<IDictionary<string, object>, Task>>();
}));
}
}
public static class AppBuilderExtensions
{
public static IAppBuilder UseEycAuthentication(
this IAppBuilder app,
WsFederationAuthenticationSettings authenticationSettings,
IServiceProvider serviceProvider,
bool authenticateEveryRequest = true)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (authenticationSettings == null)
{
throw new ArgumentNullException(nameof(authenticationSettings));
}
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
return app.ConfigureWsFederationAuthentication(serviceProvider, authenticationSettings, authenticateEveryRequest);
}
private static IAppBuilder ConfigureWsFederationAuthentication(
this IAppBuilder app,
IServiceProvider serviceProvider,
WsFederationAuthenticationSettings authenticationSettings,
bool authenticateEveryRequest = true)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(
new CookieAuthenticationOptions
{
SlidingExpiration = authenticationSettings.UseCookieSlidingExpiration,
ExpireTimeSpan = authenticationSettings.GetCookieExpireTimeSpan()
});
var wsFederationAuthenticationOptions = GetWsFederationAuthenticationOptions(authenticationSettings);
app.UseWsFederationAuthentication(wsFederationAuthenticationOptions);
var eycAuthenticationManager = (IEycAuthenticationManager)serviceProvider.GetService(typeof(IEycAuthenticationManager));
app.Use<EycAuthenticationOwinMiddleware>(eycAuthenticationManager);
// http://stackoverflow.com/questions/23524318/require-authentication-for-all-requests-to-an-owin-application
if (authenticateEveryRequest)
{
app.Use(async (owinContext, next) =>
{
var user = owinContext.Authentication.User;
if (!(user?.Identity?.IsAuthenticated ?? false))
{
owinContext.Authentication.Challenge();
return;
}
await next();
});
}
return app;
}
private static WsFederationAuthenticationOptions GetWsFederationAuthenticationOptions(WsFederationAuthenticationSettings settings)
{
var wsFederationAuthenticationNotifications = GetWsFederationAuthenticationNotifications(settings);
var wsFederationAuthenticationOptions = new WsFederationAuthenticationOptions
{
Wtrealm = settings.Realm,
MetadataAddress = settings.MetadataAddress,
TokenValidationParameters = new TokenValidationParameters
{
ValidAudiences = settings.Realms
},
Notifications = wsFederationAuthenticationNotifications
};
if (settings.UseCookieSlidingExpiration)
{
// this needs to be false for sliding expiration to work
wsFederationAuthenticationOptions.UseTokenLifetime = false;
}
return wsFederationAuthenticationOptions;
}
private static WsFederationAuthenticationNotifications GetWsFederationAuthenticationNotifications(WsFederationAuthenticationSettings settings)
{
var wsFederationAuthenticationNotifications = new WsFederationAuthenticationNotifications();
wsFederationAuthenticationNotifications.AuthenticationFailed = settings.AuthenticationFailed ?? wsFederationAuthenticationNotifications.AuthenticationFailed;
wsFederationAuthenticationNotifications.MessageReceived = settings.MessageReceived ?? wsFederationAuthenticationNotifications.MessageReceived;
wsFederationAuthenticationNotifications.RedirectToIdentityProvider = settings.RedirectToIdentityProvider ?? wsFederationAuthenticationNotifications.RedirectToIdentityProvider;
wsFederationAuthenticationNotifications.SecurityTokenReceived = settings.SecurityTokenReceived ?? wsFederationAuthenticationNotifications.SecurityTokenReceived;
wsFederationAuthenticationNotifications.SecurityTokenValidated = settings.SecurityTokenValidated ?? wsFederationAuthenticationNotifications.SecurityTokenValidated;
return wsFederationAuthenticationNotifications;
}
}
public class EycAuthenticationOwinMiddleware : OwinMiddleware
{
private readonly IEycAuthenticationManager _eycAuthenticationManager;
#region ctors
public EycAuthenticationOwinMiddleware(OwinMiddleware next, IEycAuthenticationManager eycAuthenticationManager)
: base(next)
{
if (eycAuthenticationManager == null)
{
throw new ArgumentNullException(nameof(eycAuthenticationManager));
}
this._eycAuthenticationManager = eycAuthenticationManager;
}
#endregion
public override Task Invoke(IOwinContext context)
{
if (context.Authentication.User != null)
{
context.Authentication.User =
this._eycAuthenticationManager.Authenticate(
context.Request.Uri.AbsoluteUri,
context.Authentication.User);
}
return this.Next.Invoke(context);
}
}
public class EycAuthenticationManager : ClaimsAuthenticationManager, IEycAuthenticationManager
{
private readonly IClaimsTransformer _claimsTransformer;
#region ctors
public EycAuthenticationManager(IClaimsTransformer claimsTransformer)
{
this._claimsTransformer = claimsTransformer;
}
#endregion
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (incomingPrincipal != null && !incomingPrincipal.Identity.IsAuthenticated)
{
return base.Authenticate(resourceName, incomingPrincipal);
}
return this._claimsTransformer.TransformIdentity(incomingPrincipal);
}
}
public class ClaimsTransformer : IClaimsTransformer
{
public ClaimsPrincipal TransformIdentity(IPrincipal principal)
{
if (!(principal is ClaimsPrincipal))
{
throw new Exception("The provided IPrincipal object is not of type ClaimsPrincipal.");
}
var user = (ClaimsPrincipal)principal;
var claims = user.Claims.ToList();
if (claims.All(x => x.Type != ClaimTypes.Email))
{
var upnClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.Upn);
if (upnClaim != null)
{
claims.Add(new Claim(ClaimTypes.Email, upnClaim.Value));
}
}
return new ClaimsPrincipal(new ClaimsIdentity(claims, principal.Identity.AuthenticationType));
}
}
</code></pre>
| 2 |
How to make a canvas fluid
|
<p>I have a canvas which gets its full-width size from the wrapper of the page. The canvas includes an image.</p>
<p>The wrapper is responsive but the canvas doesn't resize with the wrapper.</p>
<p>Here is the code I'm using:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas = document.getElementById("canvasTop");
// set the canvas element's width/height to cover #wrapper
var wrapper=document.getElementById('wrapper');
var wrapperStyle=window.getComputedStyle(wrapper,null);
canvas.width=parseInt(wrapperStyle.getPropertyValue("width"));
canvas.height=parseInt(wrapperStyle.getPropertyValue("height"));
//
var ctx = canvas.getContext("2d");
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.fillStyle = "skyblue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var img=new Image();
img.src= "els.png";
ctx.drawImage(img, (canvas.width-img.width)/2, (canvas.height-img.height)/2, 990,172);
// set "erase" compositing once at start of app for better performance
ctx.globalCompositeOperation = "destination-out";
var canvasOffset = $("#canvasTop").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var isDown = false;
function handleMouseDown(e) {
e.preventDefault();
startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);
isDown = true;
}
function handleMouseUp(e) {
e.preventDefault();
isDown = false;
}
function handleMouseOut(e) {
e.preventDefault();
isDown = false;
}
function handleMouseMove(e) {
if (!isDown) {
return;
}
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// Put your mousemove stuff here
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(mouseX, mouseY);
ctx.stroke();
startX = mouseX;
startY = mouseY;
}
$("#canvasTop").mousedown(function (e) {
handleMouseDown(e);
});
$("#canvasTop").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvasTop").mouseup(function (e) {
handleMouseUp(e);
});
$("#canvasTop").mouseout(function (e) {
handleMouseOut(e);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
position:relative;
margin:auto;
width:100%;
height:100%;
}
#container {
position:absolute;
width:80%;
height:80%;
left:0;
bottom:0;
margin-left:60px;
}
#canvasTop {
position:absolute;
top:0px;
left:0px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div id="container">
Stuff happen here ...
</div>
</div>
<canvas id="canvasTop" width=512 height=512></canvas></code></pre>
</div>
</div>
</p>
<p>Hope anyone can help!</p>
| 2 |
change color of div depending numeric value jquery
|
<p>I have 15 divs with the same class but different id and i want to change the color of the value.</p>
<p>For example, if one or five div's value is under 15 the color of the value will be red, if three or one the value of it is up to 15 but under 45 the color of the value is green and if the value of the div is up to 45 the color will be yellow but all of the colors i want to see at the same time.</p>
<p>My div's are like this:</p>
<pre><code><div id="listado">
<div id="cuautitlan" class="dfedo">15</div>
<div id="coacalco" class="dfedo">54</div>
<div id="atizapan" class="dfedo">65</div>
<div id="tlalne" class="dfedo">2</div>
<div id="tlalne2" class="dfedo">5</div>
<div id="naucalpan" class="dfedo">90</div>
<div id="neza" class="dfedo">105</div>
<div id="huixqui" class="dfedo">65</div>
<div id="azca" class="dfedo">75</div>
<div id="gustavo" class="dfedo">45</div>
<div id="miguel" class="dfedo">35</div>
<div id="cuauh" class="dfedo">2</div>
<div id="venus" class="dfedo">1</div>
<div id="coaji" class="dfedo">58</div>
<div id="alvaro" class="dfedo">5</div>
<div id="benito" class="dfedo">95</div>
<div id="izta" class="dfedo">43</div>
<div id="magda" class="dfedo">35</div>
<div id="coyoacan" class="dfedo">33</div>
<div id="iztapa" class="dfedo">65</div>
<div id="tlalpan" class="dfedo">89</div>
<div id="xochi" class="dfedo">99</div>
<div id="tlahuac" class="dfedo">9</div>
<div id="milpa" class="dfedo">0</div>
</div>
</code></pre>
<p>My jquery is like this</p>
<pre><code>$("div.dfedo").each(function()
{
$(this).value < 15 ? $(this).css('color','red');
});
</code></pre>
<p>My <a href="https://jsfiddle.net/pj4c40qq/" rel="nofollow">fiddle</a></p>
| 2 |
parse XML with multiple attributes to list
|
<p>I have an XMl file like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<subtests>
<subtest id="Detect" name="Device detection" />
<subtest id="DeviceType" name="Device type" />
<subtest id="VendorName" name="Vendor" />
<subtest id="VendorModelName" name="Vendor model name" />
<subtest id="ModelName" name="Customer model name" />
<subtest id="Serial" name="Serial number" />
<subtest id="getScannedSerial" name="Scanned serial number value" />
<subtest id="ScannedSerial" name="Scanned serial number" />
<subtest id="FirmwareVersion" name="Software version" />
<subtest id="IR_C" name="IR_C" customer="Rogers" />
<subtest id="EchoDct" name="Echo_DCT" customer="Rogers" />
<subtest id="FirmwareValidation" name="Firmware validation" />
</subtests>
</code></pre>
<p>I need to parse it to Java List. And i need to get the "id" and "name" options. So I tried to create a class like this, but have an error:</p>
<pre><code>@XmlRootElement(name="subtests")
public class Subtests {
private List<Subtest> subtests;
public List<Subtest> getSubtests() {
return subtests;
}
@XmlElement ( name = "subtest" )
public void setSubtests(List<Subtest> subtests) {
this.subtests = subtests;
}
@Override
public String toString() {
return "Subtests [subtests=" + subtests + "]";
}
}
</code></pre>
<p>Do how can i parse this file to get the attributes of this XML? I have got a Subtest class like this:</p>
<pre><code>@XmlRootElement ( name = "subtest" )
public class Subtest {
private String id;
private String name;
private String customer;
@XmlAttribute ( name = "id", required = true )
public String getId() {
return id;
}
@XmlAttribute ( name = "name", required = true )
public String getName() {
return name;
}
@XmlAttribute ( name = "customer", required = true )
public String getCustomer() {
return customer;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setCustomer(String customer) {
this.customer = customer;
}
}
</code></pre>
<p>and I need to get the list of such objects from the XML</p>
| 2 |
Aligning images with captions side by side
|
<p>So I've spent the last hour or so trying to figure out how to put captioned images next to each other. Most solutions/questions other people have don't work when I try to add text below it using figcaption or something of that sort.</p>
<p>I want the text to be underneath the images and move with the images but for some reason it moves the other image to another layer when I add text. Any help would be greatly appreciated. Thank you.</p>
<p>(This is only a small portion of it because there's a lot of other stuff not related to this issue in that style)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.gunimage {
display: inline-block;
margin-left: auto;
margin-right: auto;
width: 15%;
padding-left: 20px;
}
#images {
text-align: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="images">
<img class="gunimage" border="0" alt="idk" src="gg.png" /></a>
<p>this is text</p>
<img class="gunimage" border="0" alt="idk" src="gg2.png" /></a>
<p>this is also text</p>
</div></code></pre>
</div>
</div>
</p>
| 2 |
Unity 3d app crashing with message : Failure to initialize, your hardware does not support this application
|
<p>An apk built directly from a Unity 3d project or from a Unity exported Android Studio project crashes on some new Android models with the following error: </p>
<blockquote>
<p>Failure to initialize, your hardware does not support this application.</p>
</blockquote>
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.