input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Apache2 cant find /index.php error 404 <p>So I've set up an apache2 webserver on linux. Made a .php file but when I try to access <code>http://myhost/index.php</code> it gives me the <code>404 Not Found</code> Error. When I try to acccess <code>http://myhost</code> it gives me the ubuntu default page even though there is no <code>index.html</code> to be found in my directory <code>/var/www/html</code>. I have edited the <code>dir.conf</code> so <code>index.php</code> is up front. PS: making a phpinfo.</p>
| <p>To start, I would put a simple index.html with some kind of "hello world!" on your server, so when it does come up, it is a clear success.</p>
<h3>Things to check</h3>
<p>Try only the IP address of the server in the browser, this should give you either the index.php or index.html in the <code>/var/www/html</code>. This helps narrow down where the path breaks down (gets rid of hostname issues).</p>
<p>If it is a virtual server on your computer, you may have to use the port forwarding values like 127.0.0.1:8080, if port forwarding was set up.</p>
<p>Check the file permissions on /var/www/html, you can use this .sh script (might need to replace root with a username with root privs, depending on your setup):</p>
<pre><code>sudo find /var/www -exec chown root:www-data {} \;
sudo find /var/www -type d -exec chmod -v 750 {} \;
sudo find /var/www -type f -exec chmod -v 640 {} \;
</code></pre>
<p>If you put up a firewall, you need to double check port 80 is open.</p>
<p>As a last ditch effort, you can run <code>netstat -ant</code> on your server and you should see:</p>
<pre><code>tcp6 0 0 :::80 :::* LISTEN
</code></pre>
<p>Indicating that Apache is indeed listening on port 80. </p>
<p>Hopefully one of those things will help you figure it out, good luck!</p>
|
Active model Serializers does not work when i try to return a hash of multiple models via Rails? <p>I am working on Rails 5 api only app.</p>
<p>So this is my model serializer</p>
<pre><code>class MovieSerializer < ActiveModel::Serializer
attributes :id ,:name,:release_year,:story,:in_theater,:poster,:score,:user_count
belongs_to :age_rating
belongs_to :company
has_many :category , through: :movie_category
end
class CelebritySerializer < ActiveModel::Serializer
attributes :id, :first_name, :last_name
has_many :movie_celebrity
end
class MovieCelebritySerializer < ActiveModel::Serializer
attributes :id,:vacancy,:title
belongs_to :movie
belongs_to :celebrity
end
</code></pre>
<p>This is my controller</p>
<pre><code>class Api::V1::MoviesController < ApplicationController
# GET /v1/movies/:id
def show
movie = Movie.find_by(id: params[:id])
casts = MovieCelebrity.where(movie_id: params[:id],vacancy: "cast")
directors = MovieCelebrity.where(movie_id: params[:id],vacancy: "director")
render :json => {:movie => movie, :casts => casts , :directors => directors}
end
end
</code></pre>
<p>So this is what i got when i made a request</p>
<pre><code>{
"movie": {
"id": 1,
"name": "0 The Doors of Perception",
"release_year": 2007,
"story": "Non doloribus qui et eum impedit. Rerum mollitia debitis sit nesciunt. Vero autem quae sit aliquid rerum ex fugit. Eligendi assumenda et eos. Blanditiis hic ut. Commodi quo sunt voluptatem quasi.",
"in_theater": false,
"age_rating_id": 2,
"company_id": 5,
"created_at": "2016-10-12T12:45:26.213Z",
"updated_at": "2016-10-12T12:45:26.213Z",
"release_date": "2016-01-18",
"poster": "'http://cdn.mos.cms.futurecdn.net/15399e7a7b11a8c2ef28511107c90c6f.jpg',",
"score": 0,
"user_count": 6950
},
"casts": [
{
"id": 2,
"vacancy": "cast",
"title": "Pro x",
"movie_id": 1,
"celebrity_id": 56,
"created_at": "2016-10-12T12:45:28.001Z",
"updated_at": "2016-10-12T12:45:28.001Z"
},
{
"id": 3,
"vacancy": "cast",
"title": "Magneto",
"movie_id": 1,
"celebrity_id": 23,
"created_at": "2016-10-12T12:45:28.006Z",
"updated_at": "2016-10-12T12:45:28.006Z"
}
],
"directors": [
{
"id": 1,
"vacancy": "director",
"title": "",
"movie_id": 1,
"celebrity_id": 17,
"created_at": "2016-10-12T12:45:27.993Z",
"updated_at": "2016-10-12T12:45:27.993Z"
}
]
}
</code></pre>
<p>It seems like Active model serializer did not work.
Because if i only return one object it worked fine like this.</p>
<pre><code>def show
movie = Movie.find_by(id: params[:id])
casts = MovieCelebrity.where(movie_id: params[:id],vacancy: "cast")
directors = MovieCelebrity.where(movie_id: params[:id],vacancy: "director")
#render :json => { :movie => movie, :casts => casts , :directors => directors }
render :json => movie
end
{
"id": 1,
"name": "0 The Doors of Perception",
"release_year": 2007,
"story": "Non doloribus qui et eum impedit. Rerum mollitia debitis sit nesciunt. Vero autem quae sit aliquid rerum ex fugit. Eligendi assumenda et eos. Blanditiis hic ut. Commodi quo sunt voluptatem quasi.",
"in_theater": false,
"poster": "'http://cdn.mos.cms.futurecdn.net/15399e7a7b11a8c2ef28511107c90c6f.jpg',",
"score": 0,
"user_count": 6950,
"age_rating": {
"id": 2,
"name": "PG"
},
"company": {
"id": 5,
"name": "Gislason, Jacobs and Graham"
},
"category": [
{
"id": 4,
"name": "Biography"
},
{
"id": 16,
"name": "Mystery"
}
]
}
</code></pre>
<p>How can i fixed this and make the Active model serializer works fine with multiple models hash object?</p>
<p>Thanks!</p>
| <p>You need to set <a href="https://github.com/rails-api/active_model_serializers/blob/master/docs/general/rendering.md#explicit-serializer" rel="nofollow">explicit serializer</a> like this:</p>
<pre><code>render json: {movie: movie, casts: casts , directors: directors}, serializer: MovieCastDirectorSerializer
</code></pre>
<p>Because AMS doesn't know which serializer needed for your plain ruby object that you construct here. </p>
<p><strong>Update:</strong>
But even if you do so, AMS still will be unable to serialize that as it will be not ActiveModel object. <a href="https://blog.engineyard.com/2015/active-model-serializers" rel="nofollow">There is an example</a> of how to deal with that. But for me personally, it seems too much like a hack. I think you should not abuse REST so early and should separate serializers by actual end-points and only nest resources if they are nested in the real structure. Because later as your code matures it'll be really difficult to tell where you getting that data you see on display after all.</p>
|
Can someone help me with this if loop? <p>Can someone tell me how to make an <code>if</code> loop reset?
Here is my code</p>
<pre><code> import javax.swing.JOptionPane;
public class Piss {
public static void main(String[] args) {
int num1, num2 = 3, num3, num4, num5;
String question = JOptionPane.showInputDialog("Enter what you think number 2 is");
if (Integer.valueOf(question)!=(num2)){
JOptionPane.showMessageDialog(null, "Fel");
}else {
num1 = num2*num2;
num4 = num2+1;
num3=10-num2;
num5=14-num3;
JOptionPane.showMessageDialog(null, "Congrats, you solve it PIN="+num1+num2+num3+num4+num5);
}
}
}
</code></pre>
| <pre><code> public static void main(String[] args) {
int num1, num2 = 3, num3, num4, num5;
while(true)
{
String question = JOptionPane.showInputDialog("Enter what you think number 2 is");
if (Integer.valueOf(question)!=(num2)){
JOptionPane.showMessageDialog(null, "Fel");
}else {
num1 = num2*num2;
num4 = num2+1;
num3=10-num2;
num5=14-num3;
JOptionPane.showMessageDialog(null, "Congrats, you solve it PIN="+num1+num2+num3+num4+num5);
break;
}
}
}
</code></pre>
<p>EDIT: I Added the while loop and the break.</p>
<p>EDIT2: The while loop makes the question repeat and the break stops the loop when the users gets the answer correct.</p>
<p>Also, if you don't want the loops to be endless use <code>int x=3; while(x-->0){...</code></p>
|
Handle fail over in High avalibity? <p>Please consider below scenario.</p>
<p>I have implemented apache load balancer using mod jk. There are three tomcat behind apache load balancer. They all are in diffrerent machines. Let's say tomcat-1 is serving a request & before completing a request it goes down due to some issue.As Tomcat clustering has been configured, other two tomcat will handle further request. But how to handle that failed request which has already been accepted by tomcat-1. Is there any solution ?</p>
| <p>To have your proxy retry your request on another node after a failure, mod jk would need to know that a request was idemopotent.</p>
<p>I do see that adding this knowledge of idemoptency was discussed a long time ago. <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=39692" rel="nofollow">https://bz.apache.org/bugzilla/show_bug.cgi?id=39692</a></p>
<p>I doubt that they implemented this functionality.</p>
<p>I have seen other reverse proxy solutions implement an idempotency identifier. I seem to remember Weblogic having this ability. I have also seen it with certain hardware proxies.</p>
|
Writing to address based on its value <p>I was given a task to write numbers from the relative address 10h
numbers 0-255 in ascending order if the address is even
and numbers from 0-255 in descending order if the adress is not even</p>
<p>then we had to sum up all the numbers from address 10h to 210h
This is my code, I don't know why it doesn't work:</p>
<pre><code>;Write into Address
MOV SI,10h
MOV AL,0d
MOV BX,255
MOV CX,255
LOOP1:
TEST SI,00000001b
jnz notzero
jz zero
notzero:
MOV [SI],BX
DEC BX
INC SI
LOOP LOOP1
zero:
MOV [SI],AL
INC SI
INC AL
LOOP LOOP1
;Sum up address from 10h to 210h
MOV AL,0
MOV SI,10h
MOV cx,200
Loop1:
ADD AL,[SI]
INC SI
LOOP Loop1
</code></pre>
| <p>I would use just AX for all your math. </p>
<pre><code>MOV SI,10h
MOV AX,FF00h ;Or mov ax,0xff00 or however it is written
MOV CX,255 ;One memory write before the loop, 255 writes from the loop
WRITE_512_BYTES:
MOV [SI],AX
DEC AH
INC AL
ADD SI,2
LOOP WRITE_512_BYES
;Sum up address from 10h to 210h
MOV AX,0
MOV BX,0
MOV SI,10h
MOV CX,511 ;One iteration before the loop, 511 loops, 512 bytes summed.
SUM_LOOP:
MOV BL, [SI] ;populate lower byte of bx from memory
ADD AX, BX ;BH guaranteed to still be 0 from earlier MOV
INC SI
LOOP SUM_LOOP
</code></pre>
<p>Bugs that have been discussed in other comments:
1- BX versus BL. Even if you have the correct value in BX (say, 0005h), when you write BX to memory, you'll be writing both the 00 and the 05. In your code, you only want to write one byte. The code I have writes two bytes, but also adds two to SI. </p>
<p>2- Was pointed out, but it is unclear what memory "from 10h to 210h" is referring to. If you were told to check the values of the bytes "from 10h to 10h", you would assume you were checking one byte- an inclusive range, so 10h-10h+1=1. Likewise, 210h-10h+1 = 201h = 513 bytes. Since you are only writing 512 bytes, that's probably not correct. Your algorithm will populate bytes from 10h to 20Fh.</p>
<p>3- Was pointed out, but as you sum the numbers with </p>
<pre><code>ADD AL,[SI]
</code></pre>
<p>You will overflow your 8 bit register AL, because the sum of the numbers is too big for the 0-255 range. </p>
<p>4- As was pointed out, when LOOP runs out of cx to count with, it will continue with the next instruction underneath it. This means that your notzero case will begin executing the zero case. You could solve this with an unconditional jump, placed directly underneath the LOOP, to the sum section, which you'll need to label as such. </p>
<p>5- I don't know why you are getting an error with mov [si],bl. Are you sure it is typed correctly? That is a valid instruction. </p>
<p>Nits: </p>
<pre><code>TEST SI,00000001b
</code></pre>
<p>This does in fact AND SI with 1 and set flags, but it is odd to specify 1 as the 8 bit value "00000001b". The actual comparison is done as 16 bits, 32 bits, or 64 bits, depending on what mode you are running in. Consider just comparing it to 1 (and letting the assembler zero extend the value) instead of writing it out partially as an 8 bit value. </p>
<p>2- When you are doing a compare for one of two exclusive branches, you could get away with just testing one of the cases. For instance, if you do the test and then do the </p>
<pre><code>jz zero
</code></pre>
<p>You will conditionally jump to the zero case, and then you can just have the non-zero case without any further redirection: just eliminate the jnz instruction. </p>
<p>3- It would be kinda good to know where you are running this. In 16 bit DOS COM files, for instance, you would end up overwriting your own code when you wrote to bytes at 100h and above. I'm assuming that the memory addresses are safe for wherever you are writing this, because that was in your instructions.</p>
|
How to add indexing to maketable queries in MS Access? <p>So I work with a remote data source that refreshes daily, so I have to run a few make table queries to translate/process the most up to date snapshot into tables.</p>
<p>However I don't see any clear way to add indexing. Right now what I am doing is I use one query to pull from the data source and manipulate it (call the result of this SourceQuery). And then in my maketable query I'll do:</p>
<pre><code>SELECT SourceQuery.* INTO [Results Table] IN '\\path\to\dest\myDatabase.mdb' FROM SourceQuery;
</code></pre>
<p>But the resulting table has "No" in the index field for everything.</p>
<p>How can I modify the queries to add indexing to fields that are commonly used in joins?</p>
| <p>When you write <code>SELECT INTO</code> statement, the structure of the new table is defined by the attributes of the expressions in the select list, so you won't be able to get the indexes of the source table this way.</p>
<p>you should write create index in your query
<code>CREATE INDEX NewIndex ON [Results Table] (field1, field2)</code></p>
|
Push and pop operation for 2D matrix and displaying them in C++ <p>I am new to c++ and just learning stack push and pop operation. I have written a small program to push and pop some elements from stack. My sample program is given below:</p>
<pre><code>// stack::push/pop
#include <iostream> // std::cout
#include <stack> // std::stack
int main ()
{
std::stack<int> mystack;
for (int i=0; i<5; ++i) mystack.push(i);
std::cout << "Popping out elements...";
while (!mystack.empty())
{
std::cout << ' ' << mystack.top();
mystack.pop();
}
std::cout << '\n';
return 0;
}
</code></pre>
<p>But now I want to push multiple 3*3 matrix onto the stack and want to get each of them using mystack.top() and also pop each matrix using mystack.pop operation and display the whole matrix. How will I implement the stack for multiple matrix operation?</p>
<p>Sample matrix can be like this:</p>
<pre><code>float A[3][3]={{1.0,2.0,3.0},{1.0,2.0,3.0},{1.0,2.0,3.0}};
float B[3][3]={{1.0,2.0,4.0},{1.0,5.0,3.0},{8.0,2.0,3.0}};
</code></pre>
| <p>You can use <code>std::array<std::array<float,3>,3></code> for this. Plain arrays won't be copied automatically, and do not conform the needs of a data type stored in a <code>std::queue</code>:</p>
<pre><code>std::array<std::array<float,3>,3> A {{{1.0,2.0,3.0},{1.0,2.0,3.0},{1.0,2.0,3.0}}};
std::array<std::array<float,3>,3> B {{{1.0,2.0,4.0},{1.0,5.0,3.0},{8.0,2.0,3.0}}};
</code></pre>
<p>Then you can simply define your stack as:</p>
<pre><code>std::stack<std::array<std::array<float,3>,3>> myStack;
</code></pre>
<hr>
<p>To make it more readable and easier to type you can use <code>using</code> or a <code>typedef</code>:</p>
<pre><code>typedef std::array<float,3>,3> My3x3Matrix;
// ...
std::stack<My3x3Matrix> myStack;
myStack.push(A);
// ...
My3x3Matrix C = myStack.top();
myStack.pop();
</code></pre>
|
Spreading key value pairs into columns <p>I'm stuck with the following data wrangling problem. Each dataset has multiple values of <code>aValue</code> per one value of <code>aName</code>. This can be easily represented in a tidy data frame.</p>
<pre><code>someDatasets <- list(dataset1 = data.frame(aName = c("a", "a", "a", "b", "b"), aValue = 1:5, dataset = "ds1"),
dataset2 = data.frame(aName = c("a", "a", "a", "b", "c", "c"), aValue = (1:6)*10 , dataset = "ds2"),
dataset3 = data.frame(aName = c("a", "c", "c", "c"), aValue = (1:4)*100, dataset = "ds3"))
tidyData <- Reduce(dplyr::bind_rows, someDatasets)
</code></pre>
<p>I would like to "spread" the dataset variable into individual columns. (I was not able to use <code>tidyr::spread</code> to create desired output because of duplicate keys.)</p>
<pre><code>###
# Desired output
###
# aName ds1 ds2 ds3
# a 1 10 100
# a 2 20 NA
# a 3 30 NA
# b 4 40 NA
# b 5 NA NA
# c NA 50 200
# c NA 60 300
# c NA NA 400
</code></pre>
<p>Is there a tidy way to generate desired output ?</p>
<p>ps: I'm aware of <a href="http://stackoverflow.com/questions/39882107/r-spread-key-value-pairs-when-keys-are-in-different-columns-and-return-value-fr">spread-key-value-pairs-when-keys-are-in-different-columns</a> question but the solution </p>
<pre><code>dcast(melt(someDatasets, id = "aName", na.rm = TRUE), aName~value)
</code></pre>
<p>does not produce the desired output because an aggregate function <code>length</code> is used.</p>
| <p>As stated in comments by @lukeA and @A Handcart and Mohair, you can add an additional ID to your data to avoid the <strong>duplicate keys</strong> problem.</p>
<pre><code>library(dplyr)
library(tidyr)
tidyData = bind_rows(someDatasets) %>%
group_by(dataset, aName) %>%
mutate(id = paste0(aName, 1:n())) %>%
ungroup() %>%
select(-aName)
# head(tidyData)
# Source: local data frame [6 x 3]
#
# aValue dataset id
# <dbl> <chr> <chr>
# 1 1 ds1 a1
# 2 2 ds1 a2
# 3 3 ds1 a3
# 4 4 ds1 b1
# 5 5 ds1 b2
# 6 10 ds2 a1
</code></pre>
<p><code>id</code> is now unique within each group (dataset) so we can proceed with spreading:</p>
<pre><code>tidyData %>%
spread(dataset, aValue) %>%
mutate(id = substr(id, 1, 1))
# Source: local data frame [10 x 4]
#
# id ds1 ds2 ds3
# <chr> <dbl> <dbl> <dbl>
# 1 a 1 10 100
# 2 a 2 20 NA
# 3 a 3 30 NA
# 4 b 4 40 NA
# 5 b 5 NA NA
# 6 c NA 50 200
# 7 c NA 60 300
# 8 c NA NA 400
</code></pre>
|
JSON Loading in Java: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer <p>I'm trying out the example from <a href="https://www.mkyong.com/java/json-simple-example-read-and-write-json/" rel="nofollow">here</a>, and am using this code to write to a file: </p>
<pre><code> public void Write() {
FileWriter file = null;
try {
JSONObject o = new JSONObject();
JSONObject obj = new JSONObject();
obj.put("name", "mky4ong.com");
obj.put("age", new Integer(100));
JSONObject obj2 = new JSONObject();
obj2.put("name", "mk54yong.com");
obj2.put("age", new Integer(1800));
file = new FileWriter(filename);
JSONArray list = new JSONArray();
list.add(obj);
list.add(obj2);
o.put("messages", list);
file.write(o.toJSONString());
file.flush();
file.close();
} catch (IOException ex) {logger.error("{}", ex.getCause());} finally {try {file.close();} catch (IOException ex) {logger.info("{}",ex.getCause());}}
}
</code></pre>
<p>and using this code to read from the same file: </p>
<pre><code>public void Load() {
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(new FileReader(filename));
} catch (IOException | ParseException ex) {logger.info("{}", ex.getCause());}
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<JSONObject> iterator = msg.iterator();
while (iterator.hasNext()) {
JSONObject ob = iterator.next();
String name =(String) ob.get("name");
Integer age =(Integer) ob.get("age");
logger.info("name: {}, age: {}", name, age);
}
}
}
</code></pre>
<p>But although the data is written successfully as <code>{"messages":[{"name":"mky4ong.com","age":100},{"name":"mk54yong.com","age":1800}]}</code>, I have trouble while loading.
At this line <code>Integer age =(Integer) ob.get("age");</code> the compiler says "Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer". </p>
<p>I tried casting in multiple ways, but it doesn't work. Why does such an error happen? </p>
<p>ps: I'm using <code>compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'</code></p>
| <p>When you write your json file all additional information is lost (in your case the <code>Integer</code> type you used. When you read it the JSONParser will automatically use <code>Long</code> when it encounters a number without decimal points. Try using <code>Long</code> in your reader. Note that the reader knows <strong>nothing</strong> about the writer. It can only read a file and interpret it as it sees fit.</p>
<p>So to answer your question:</p>
<pre><code>Long age =(Long) ob.get("age");
</code></pre>
<p>will work.</p>
|
Determine what script a node process is running <p>I'm using PM2 on a Windows server to run a bunch of different scripts. I have found that sometimes when I issue a stop with PM2 it reports the process as stopped but the node process is still running.</p>
<p>I want to be able to determine what script is being run by the node process (as reported by Windows task manager). If I was binding to a port I could figure it out with net stat but these scripts don't listen on ports, rather they connect to Rabbit MQ.</p>
<p>If I can identify the task in Windows I can forcefully terminate it using task manager.</p>
| <p>I think you're looking for <code>tasklist /FI "Imagename eq node"</code> (or something similar)</p>
<p>Related: <a href="http://superuser.com/questions/18830/is-there-a-command-in-windows-like-ps-aux-in-unix">http://superuser.com/questions/18830/is-there-a-command-in-windows-like-ps-aux-in-unix</a></p>
<p>Docs for <code>tasklist</code>: <a href="https://technet.microsoft.com/en-us/library/bb491010.aspx" rel="nofollow">https://technet.microsoft.com/en-us/library/bb491010.aspx</a></p>
<p>Related, if your process is listening on a port and you know that number: <a href="http://stackoverflow.com/questions/48198/how-can-you-find-out-which-process-is-listening-on-a-port-on-windows">How can you find out which process is listening on a port on Windows?</a></p>
<p>If you're connected to RabbitMQ your PID will be in the Consumers section of the queue, something like this: <code>node-amqp-37997-0.5310617093928158</code> where 37997 is the PID of the process listening. </p>
|
Reorder Fields of FeinCMS Content Type in Page Admin <p>I let a content type inherit from <code>RichTextContent</code> and add a few fields, like a title.</p>
<pre><code>class SimpleTextContent(RichTextContent):
title = models.CharField(max_length=20)
...
</code></pre>
<p>Unfortunately, in the Page Admin the text field will appear on top of the corresponding inline admin. But it would be nicer to have the <code>title</code> appear first.</p>
<p>How can I change the order of the fields in a content type's inline admin?</p>
| <p>You have to define <code>feincms_item_editor_inline</code> on <code>SimpleTextContent</code> (<a href="https://feincms-django-cms.readthedocs.io/en/latest/admin.html#customizing-the-individual-content-type-forms" rel="nofollow">docs</a>):</p>
<pre class="lang-py prettyprint-override"><code>from feincms.admin.item_editor import FeinCMSInline
class SimpleTextInlineAdmin(FeinCMSInline):
fields = ('title', 'text', 'order', 'region')
class SimpleTextContent(RichTextContent):
feincms_item_editor_inline = SimpleTextInlineAdmin
title = models.CharField(max_length=20)
</code></pre>
<p>Take care to always include <code>order</code> and <code>region</code>, even though they're not displayed in the admin.</p>
|
Center images in masonry <p>I am using <a href="http://masonry.desandro.com/" rel="nofollow">masonry</a> to place my images nicely on a large screen like this:</p>
<pre><code> <div class="grid" >
<div class="grid-item"><img class='link img-link' src="images/image1.gif"></div>
<div class="grid-item"><img class='link img-link' src="images/image2.gif"></div>
<div class="grid-item"><img class='link img-link' src="images/image3.gif"></div>
</div>
</code></pre>
<p>and the following jQuery snipped</p>
<pre><code>$(document).ready(function(){
$('.grid').masonry({
columnWidth: 1,
itemSelector: '.grid-item'
});
});
</code></pre>
<p>However nice placing is not necessary when using a mobile phone.
Currently, on a mobile screen the images are not centered but all left aligned. Setting <code>text-align:center</code> to <code>grid</code> or <code>grid-item</code> does not help.
<strong>How can I center the images when they are all listed underneath?</strong> </p>
<p>The problem can be seen at <a href="http://www.kristianhammerstad.com/" rel="nofollow">http://www.kristianhammerstad.com/</a></p>
<p><a href="https://i.stack.imgur.com/VvvF4.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/VvvF4.jpg" alt="enter image description here"></a></p>
<p>This is how it looks in my case:</p>
<p><a href="https://i.stack.imgur.com/tYIJv.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/tYIJv.jpg" alt="enter image description here"></a></p>
| <p>You should find the pixels using from which you want to apply the rule and use the following:<br>
For example, if you want 360 pixels and below: use the following code at your css file: </p>
<pre><code>@media screen and (max-width: 360px) {
.box.col3.editorial , .box.col3.poster{
left: 0;
right: 0;
margin: 0 auto;
}
}
</code></pre>
|
Unity Networking [UNET]: Syncronizing static scene objects <p><strong>Hello everyone!</strong></p>
<p>I'm relatively new to Unity and currently working around new game project using UNET. I have stuck for a few days with this problem: <strong>how I can syncronize existing (not spawned) scene objects in Unity?</strong></p>
<p>I have object named "background" - it's a sprite. When server loads map it changes background's transform scale. All I want to do is to sync it with newly connected clients.</p>
<p>Documentation here says that it should be done automaticlly if object has NetworkIndentity and NetworkTransform components. But it doesn't work for me!
<a href="https://docs.unity3d.com/Manual/UNetSceneObjects.html" rel="nofollow">https://docs.unity3d.com/Manual/UNetSceneObjects.html</a></p>
<p>Here is the simplified project:
<a href="http://prntscr.com/csxoqd" rel="nofollow">http://prntscr.com/csxoqd</a>
I have sprite with scale 40;40.
Then in OnServerStart I change it to 100;100 - on the host or server only it works great!</p>
<pre><code>using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class NewBehaviourScript : NetworkBehaviour
{
// Use this for initialization
public override void OnStartServer()
{
this.transform.localScale = new Vector3(100, 100, 1);
}
// Update is called once per frame
void Update () {
}
}
</code></pre>
<p>But on client side anything happens. I tried adding <code>NetworkServer.SpawnObjects();</code> inside this method. Doesn't work.</p>
<p>Any suggestions?</p>
| <p>I'm afraid <code>transform.scale</code> synchronization is still not supported by UNET. It wasn't 1 year ago and it still is now :(</p>
<p>But luckily, you can workaround this problem by using <a href="https://docs.unity3d.com/ScriptReference/Networking.SyncVarAttribute.html" rel="nofollow">[SyncVar attribute]</a>.</p>
|
android - can't save text file <p>The question is pretty common and I have googled it but it still wont work. I'm simply trying to save a text file using the below code:</p>
<pre><code> String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Toast.makeText(getApplicationContext(), "Access denied", Toast.LENGTH_LONG).show();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/data";
File dir = new File(path);
dir.mkdirs();
File file = new File(path + "/savedFile.txt");
String saveText = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
try {
fos.write(saveText.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
break;
</code></pre>
<p>and in my manifest I have declared:</p>
<pre><code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code></pre>
<p>However everytime I try and run the code the app crashes with the error 'Unfortunately, APP_NAME has stopped." Can anyone tell me what is wrong with my code?</p>
| <pre><code>if ((checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)&& Build.VERSION.SDK_INT >= 23 ) {
Log.v(TAG,"Permission is granted");
return true;}
else{
ActivityCompat.requestPermissions(this, new String[]Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Toast.makeText(getApplicationContext(), "Access denied", Toast.LENGTH_LONG).show();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/data";
File dir = new File(path);
dir.mkdirs();
File file = new File(path + "/savedFile.txt");
String saveText = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
try {
fos = new FileOutputStream(file);
OutputStreamWriter ow = new OutputStreamWriter(fos);
ow.write(saveText.getBytes());
ow.append(saveText.getText());
ow.close();
fos.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
}} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
</code></pre>
<p>You need to use something like this code.Because you need to specify runtime permissions.Marshmallow needs you to check the permissions first to use respective resources.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app. It also gives the user more control over the app's functionality; for example, a user could choose to give a camera app access to the camera but not to the device location. The user can revoke the permissions at any time, by going to the app's Settings screen</p>
|
WP-Less, Less and PhpStorm compile <p>Im creating wp theme using Redux framework, WP-Less for compiling styles in LESS. Working in PhpStorm.</p>
<p>Now, i want to change some colors dynamically from Redux and pass them to my main style.less file which will be compiled in style.css. </p>
<p>The problem is, when i want to load my css, i NEED to do it using</p>
<pre><code>wp_enqueue_style('my-style', get_stylesheet_uri());
</code></pre>
<p>but it only loads css, not my less file. In my functions.php file i have defined my variables.</p>
<pre><code>add_filter('less_vars', 'my_less_vars', 10, 2);
</code></pre>
<p>function my_less_vars($vars, $handle)
{</p>
<pre><code>Redux::init('redux_qmakeup');
global $redux_qmakeup;
if (isset($redux_qmakeup['opt-typography']['font-family'])) {
$font_name = $redux_qmakeup['opt-typography']['font-family'];
} else {
$font_name = 'Montserrat';
}
if (isset($redux_qmakeup['opt-typography']['color'])) {
$font_color = $redux_qmakeup['opt-typography']['color'];
} else {
$font_color = '#d6451e';
}
if (isset($redux_qmakeup['opt-color-footer'])) {
$footer_color = $redux_qmakeup['opt-color-footer'];
} else {
$footer_color = '#414243';
}
// $handle is a reference to the handle used with wp_enqueue_style()
$vars["font-family"] = "'$font_name'";
$vars["font-color"] = "$font_color";
$vars["footer-color"] = "$footer_color";
return $vars; }
</code></pre>
<p>In WP-LESS documentation it says that now i can use @footer-color in my .less file and PhpStorm will compile it automatically. But it wont, compiling is broken because my @footer-color is not defined. And if i define it as a empty var, it wont take my redux color but will keep that empty var.</p>
| <p>You are using WordPress filter add_filter('less_vars', 'my_less_vars', 10, 2); to add your less variables.</p>
<p>I'm using Netbeans and I'm sure it is the same in PhpStorm. Netbeans compiler can't use WP filters, simple as that. You can't use PhpStorm compiler to compile unless all vars are in written in the less files.</p>
<p>One solution is to compile file using WP-LESS only when you have some changes in less files or variables (which will be changed after you change some theme option related to it).</p>
<p>Hope this helps :)</p>
|
C# MongoDB Query - Filter where a match exists in Array <p>When I modified my filter to only select an ArtistDocument whose artist_ID contains a match in the artistIds array, I get the following error.</p>
<p>"The expression tree is not supported: {document}{artist_ID}" System.Exception {System.NotSupportedException}</p>
<p>Any help here would be appreciated! \m/ \m/</p>
<pre><code> // array.
string[] artistsIds = new string[] { "123ABC", "456XYZ" };
// filter.
var filter = Builders<ArtistsDocument>.Filter.Where(p => p.artist_ID.Any(b => artistsIds.Contains(b.ToString())));
filter = filter & Builders<ArtistsDocument>.Filter.Eq("genre", "Rock");
filter = filter & Builders<ArtistsDocument>.Filter.Lt(x => x.transactionDate, DateTime.Now.AddSeconds(Math.Abs(30) * (-1)));
// update.
var update = Builders<ArtistsDocument>.Update.Set("status", "Processing");
// options.
var options = new FindOneAndUpdateOptions<ArtistsDocument>
{
Sort = Builders<ArtistsDocument>.Sort.Ascending(x => x.fileName).Ascending(x => x.priority),
ReturnDocument = ReturnDocument.After
};
// document.
var doc = await artistsCollection.FindOneAndUpdateAsync(filter, update, options);
</code></pre>
| <p>I believe you can achieve what you want with ElemMatch</p>
<pre><code>Builders<ArtistsDocument>.Filter.ElemMatch
</code></pre>
<p>something like this:</p>
<pre><code>var elemMatchFilter = Builders<YourModel>
.Filter
.ElemMatch(x => x.YourArray, x => x.ArrayField1 == field1 && x.x.ArrayField2 == field2);
</code></pre>
|
Apache doesn't redirect react requests with more than 2 slashes in url correctly <p>I need to respond every react-app request with the same <code>js/bundle.js</code> file but do not do actual redirect - leave the url the same. Because after <code>bundle.js</code> returns - react-router will get any page it needs from this <code>bundle.js</code> file. </p>
<p>When in the url there is one "/" - reloading of the page <code>/welcome</code> or any else works fine. </p>
<p>But when i try to reload <code>/auth/login</code> (two slashes) it tries to find <code>bundle.js</code> from <code>auth/js/bundle.js</code> and gives an error. </p>
<p>I'm using </p>
<pre><code> RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ /index.html [L]
</code></pre>
<p>But it doesn't help.<br>
Here is my react-router </p>
<pre><code>function requireAuth(nextState, replace) {
if (!localStorage.mazoomToken) {
replace({
pathname: '/auth/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
function hasAuth(nextState, replace) {
if (localStorage.mazoomToken) {
replace({
pathname: '/',
state: { nextPathname: nextState.location.pathname }
})
}
}
const router = (
<Provider store={store}>
<Router history={history}>
<Route path="/" onEnter={requireAuth} component={App}>
<IndexRoute component={Events}/>
<Route path="welcome" component={WelcomePage} onEnter={requireAuth}/>
<Route path="contacts" component={Contacts} onEnter={requireAuth}/>
<Route path="profile" component={Account} onEnter={requireAuth}/>
</Route>
<Route path="/auth/" component={Auth} onEnter={hasAuth}>
<Route path="sign_up" component={SignUp} onEnter={hasAuth}/>
<Route path="login" component={Login} onEnter={hasAuth}/>
<Route path="forgot_pass" component={ForgotPassword} onEnter={hasAuth}/>
<Route path="password/:token" component={NewPassword} onEnter={hasAuth}/>
</Route>
</Router>
</Provider>
);
</code></pre>
<p>Thanks in advance for any help!</p>
| <p>The problem was in index.html - when linking script js/bundle.js I didn't put slash before js - /js/index.js. </p>
|
D3.js: Drawing rectangles underneath text <p>I am working on a radial collapsible tree in using d3.js. Here is how it looks so far: <a href="https://i.stack.imgur.com/iyPbz.png" rel="nofollow"><img src="https://i.stack.imgur.com/iyPbz.png" alt="enter image description here"></a>
As you can see highlighted in red is the fact that text overlaps the links. I would like the text to be "highlighted" in the background color, so that the links will not appear where the text is.</p>
<p>So far, I have tried highlighting the text using <strong>background-color</strong> in CSS and in .style() of the text. </p>
<pre><code>.node text {
background-color: yellow;
font: 12px sans-serif;
}
</code></pre>
<p>I have also tried <strong>drawing a rectangle</strong> of the size of the text before drawing the text, as seen in Mike Bostock's <a href="http://bl.ocks.org/mbostock/7341714" rel="nofollow">bar chart</a>. However, when I execute the code, the rectangles are nowhere to be found, even in the source code via chrome's developer tool (there is a <code><circle></code> tag for the circles, but no rectangle tag).</p>
<p>Here is a <a href="https://jsfiddle.net/h05r2w6d/" rel="nofollow">JSFiddle</a> of part of the code. I have made the rectangle in yellow in the CSS to see better in case it works, though I haven't been able to make it work.</p>
<p>The code of the rectangles are the following:</p>
<pre><code>.node rect {
fill: yellow;
}
nodeEnter.select("rect")
.attr("height", 15)
.attr("width", 200)
.attr("transform", function(d) { return d.x < 180 ? "translate(0)" : "rotate(180)translate(-" + (d.name.length + 50) + ")"; })
//.style("fill","yellow")
;
</code></pre>
<p>and </p>
<pre><code>nodeUpdate.select("rect")
.attr("height", 15)
.attr("width", 200)
.attr("transform", function(d) { return d.x < 180 ? "translate(0)" : "rotate(180)translate(-" + (d.name.length + 50) + ")"; })
//.style("fill","yellow")
;
</code></pre>
| <p>You have to <code>append</code> the rectangle in the enter selection, not <code>select</code>ing it:</p>
<pre><code>nodeEnter.append("rect")
</code></pre>
<p>Here is your fiddle: <a href="https://jsfiddle.net/wLwn9p98/" rel="nofollow">https://jsfiddle.net/wLwn9p98/</a></p>
|
Complex Xpage takes long for partial refreshs <p>I have a complex xpage with lots of nested custom controls. Everytime I execute a partial refresh it takes over 4 seconds to finish. If I remove the complexity it works just fine and is fast as wished.</p>
<p>I put a test on this complex Xpage and even with partial execution mode this simple test takes over 4 seconds to finish.</p>
<pre><code><xp:button value="Label" id="button1">
<xp:eventHandler event="onclick" submit="true" refreshMode="partial" refreshId="refreshPanel" disableValidators="true" execMode="partial" execId="inputText1">
</xp:eventHandler>
</xp:button>
<xp:div id="refreshPanel">
<xp:inputText id="inputText1"></xp:inputText>
</xp:div>
</code></pre>
<p><a href="https://i.stack.imgur.com/YiMbF.png" rel="nofollow">execution time of partialrefresh</a></p>
<p>Does anyone have a hint on this? Any server settings which can be adjusted?</p>
| <p>Even though it is a partial refresh <em>all</em> XPage controls' values are submitted to server. "partial" means in this case that only the label1 part returns to client. But it is a full <em>submit</em> and this might take time...</p>
<p>You can submit partially though. Add </p>
<pre><code>execMode="partial" execId="button1"
</code></pre>
<p>to your eventHandler properties. This time only the execId's value gets submitted. Put in execId the id that needs to be submitted (maybe a panel) for this partial refresh. </p>
<p><a href="https://i.stack.imgur.com/YZTL7.png"><img src="https://i.stack.imgur.com/YZTL7.png" alt="enter image description here"></a></p>
<p>Have a look <a href="http://www.intec.co.uk/understanding-partial-execution-part-two-execution/">here</a> for more information on partial execution mode .</p>
|
Why is there no output showing in this python code? <pre><code>man=[]
other=[]
try:
data=open('sketch.txt')
for each_line in data:
try:
(role,line_spoken) = each_line.split(':',1)
line_spoken= line_spoken.strip()
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!')
try:
man_file=open('man_data.txt','w')
other_file=open('other_data.txt','w')
print(man, file=man_file)
print(other, file=other_file)
man_file.close()
other_file.close()
except IOError:
print('File error.')
</code></pre>
<p>Shouldn't it create man_data and other_data file?
There is no error message or any kind of input in the idle.</p>
<p><a href="https://i.stack.imgur.com/V0pD3.png" rel="nofollow"><img src="https://i.stack.imgur.com/V0pD3.png" alt="enter image description here"></a></p>
| <p>The indentation in your screenshot is different from your question. In your question you claimed your code was this (with some bits trimmed out):</p>
<pre><code>try:
# Do something
except IOError:
# Handle error
try:
# Write to man_data.txt and other_data.txt
except IOError:
# Handle error
</code></pre>
<p>But your screenshot shows that you actually ran this code:</p>
<pre><code>try:
# Do something
except IOError:
# Handle error
try:
# Write to man_data.txt and other_data.txt
except IOError:
# Handle error
</code></pre>
<p>The whole of the second <code>try</code>/<code>except</code> block is within the <code>except</code> clause of the first one, so it will only be executed if there is an exception in the first <code>try</code> block. The solution is to run the code that is in your question i.e. unindent the second <code>try</code>/<code>except</code> block so that it is at the same level as the first one.</p>
|
child_process not returning correct exit code from batch file <p>I'm trying to get the correct exit code from a batchfile using nodejs on Windows.</p>
<p>When run from the command line I see the expected error code:</p>
<pre><code>ml.bat profile bootstrap
</code></pre>
<blockquote>
<p>ERROR: [".../deploy/lib/RoxyHttp.rb:362:in <code>block in request'", ".../deploy/lib/RoxyHttp.rb:352:in</code>loop'", ".../deploy/lib/RoxyHttp.rb:352:in <code>request'", ".../deploy/lib/MLClient.rb:110:in</code>go'", ".../deploy/lib/server_config.rb:1963:in <code>get_sid'", ".../deploy/lib/server_config.rb:2056:in</code>execute_query_7'",".../deploy/lib/server_config.rb:510:in <code>execute_query'",".../deploy/lib/server_config.rb:709:in</code>bootstrap'", "deploy/lib/ml.rb:168:in `'"</p>
</blockquote>
<p>I verify that there exit code was non-zero:</p>
<pre><code>echo %errorlevel%
</code></pre>
<blockquote>
<p>12</p>
</blockquote>
<p>Below is the correspoinding code I use in NodeJS - which always gives an exit code of 0:</p>
<pre><code>var stdout = "";
let proc = child_process.spawn("ml.bat", ["profile", "bootstrap"], {shell:true});
proc.stdout.on('data', d => stdout += d.toString() + '\n';);
proc.on('close', exitcode => {
console.log(stdout);
if (exitcode !== 0) {
console.log('ERROR in command');
process.exit();
}
});
</code></pre>
<p>I have tried using several variations (exec, execSync, spawnSync) and options (shell, "cmd.exe /c") but I can never get a non-zero code using node. The program does not print any output on stderr.</p>
<p>Any idea how to get back the right error code in NodeJS?</p>
| <p>If you want Node to return the child process error code, you need to pass it to the exit function.... </p>
<p>process.exit(exitcode);</p>
<p>As Tom mentions in his comment, "code" is undefined, so that needs to be fixed.</p>
<p>See <a href="https://nodejs.org/api/process.html#process_process_exitcode" rel="nofollow">Node Docs: process_process_exitcode</a></p>
|
Jasmin Mock $http (then, catch) <p>Ive been using the following code for ages to test the following code example.</p>
<pre><code>function loadAccounts() {
return AccountCaller.loadAccounts()
.then(function(response){
AccountsModel.accounts = response.accounts;
})
.catch(function(error){
ErrorHandler.raise(error);
});
}
var spy= spyOn(mock, 'loadAccounts').andCallFake(function () {
return {
then: function (callback) {
return callback(response);
}
};
});
</code></pre>
<p>The above code works fine on the '.then' but i recently introduced the '.catch' and now my tests fails 'TypeError: Cannot read property 'catch' of undefined'.</p>
<p>Any ideas on how i can deal with the '.catch' element, if i remove it then the code test runs fine !!!</p>
<p>Cheers</p>
| <p>In your spy of <code>then</code> you have <code>return callback(response);</code>, but your callback does not return anything, which is why you get the <code>undefined</code> in your error. The thing you're returning will need to at least have a <code>catch</code> method of some kind attached to it. You can test that with something like this:</p>
<pre><code>var spy= spyOn(mock, 'loadAccounts').andCallFake(function () {
return {
then: function (callback) {
callback(response);
return {catch: function() {}};
}
};
});
</code></pre>
<p>^^ This isn't necessarily how I'd do that, but it should get you moving in the right direction. Consider returning the result of <code>callback(response)</code> wrapped in a <code>Promise</code>.</p>
|
How to highlight a given word inside hbs? <p>Is there any way to highlight a given word inside an ember template?</p>
<p>Example:</p>
<pre><code>var givenWord = "hello"
</code></pre>
<p>ember template is as follows:</p>
<pre><code><div>
<p>some text here, some another text with hello, again hello</p>
</div>
</code></pre>
<p>I want to apply specific CSS to the word <code>hello</code> (this word is dynamic)
Appreciate any help!</p>
| <p>There is no builtin easy mechanism.You can try implement the below stuff in Ember.<br>
<a href="https://markjs.io/" rel="nofollow">https://markjs.io/</a></p>
|
Set size of image in `ImageView` in button where image is set using css <p>I used <code>fitWidth</code> and <code>preserveRatio</code> to size the <code>ImageView</code> in the FXML, but the image does not scale to it but instead shows its full size (too big in my case). How do I set the size of the image using FXML or css?</p>
<p><strong>FXML</strong></p>
<pre><code><Button
fx:id="buttonUp"
GridPane.columnIndex="0"
GridPane.rowIndex="0"
onAction="#buttonUp">
<graphic>
<ImageView fitWidth="10.0" pickOnBounds="true" preserveRatio="true">
</ImageView>
</graphic>
</Button>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>#buttonUp {
-fx-graphic: url('up.png');
}
#buttonUp:pressed {
-fx-graphic: url("up_pressed.png");
}
</code></pre>
<p>I don't want a JavaFX code solution because I want to keep my styling in the fxml and css.</p>
<p>If this really isn't possible in FXML or css then I'd concede in doing it with java, in that case just leave a comment.</p>
<p><strong>Image in FXML</strong></p>
<p>When I try</p>
<pre><code><ImageView id="buttonDownImage" fitHeight="40.0" fitWidth="40.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="resources/down.png" />
</image>
</ImageView>
</code></pre>
<p>Then there follows an <code>java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found</code> while I'm sure the file is there (the css could find it) and the IntellJ autocomplete even suggested to start with <code>resources</code> in the url.</p>
| <p>Not tested, but try using the CSS on the <code>ImageView</code> itself:</p>
<pre class="lang-xml prettyprint-override"><code><Button
fx:id="buttonUp"
GridPane.columnIndex="0"
GridPane.rowIndex="0"
onAction="#buttonUp">
<graphic>
<ImageView id="buttonUpGraphic" fitWidth="10.0" pickOnBounds="true" preserveRatio="true">
</ImageView>
</graphic>
</Button>
</code></pre>
<p>and then in CSS:</p>
<pre class="lang-css prettyprint-override"><code>#buttonUp #buttonUpGraphic {
-fx-image: url('up.png');
}
#buttonUp:pressed #buttonUpGraphic {
-fx-image: url('up_pressed.png');
}
</code></pre>
|
rails routing, add path name also keep old urls working <p>in my routes file, when i change</p>
<pre><code>resources :foobar
</code></pre>
<p>to </p>
<pre><code>resources :foobars, path: "foo-bars"
</code></pre>
<p>the urls become <code>example.com/foo-bars</code>, <code>example.com/foo-bars/1</code> etc.
this is ok. </p>
<p>but how can i also keep the old urls, <code>example.com/foobars</code>, <code>example.com/foobar/3</code> also working?</p>
<p>i know, i can hardcode it,</p>
<pre><code>get "foobars", to: 'foobar#index'
get "foobar/:id", to: 'foobar#show'
...
</code></pre>
<p>but is there a clean way to implement this? </p>
| <p>Define both of them</p>
<pre><code>resources :foobars, path: "foo-bars"
resources :foobars, path: "foobars"
</code></pre>
<p><strong>EDIT:</strong></p>
<p>For custom actions instead of declaring them twice for each path like this,</p>
<pre><code>resources :foobars, path: "foo-bars"
collection do
get 'bulk_new'
patch 'bulk_create'
get 'bulk_edit'
patch 'bulk_update'
end
end
resources :foobars, path: "foobars"
collection do
get 'bulk_new'
patch 'bulk_create'
get 'bulk_edit'
patch 'bulk_update'
end
end
</code></pre>
<p>Create common block and pass it to both resource method calls.</p>
<pre><code>common_block = lambda do
collection do
get 'bulk_new'
patch 'bulk_create'
get 'bulk_edit'
patch 'bulk_update'
end
end
resources :foobars, path: "foo-bars", &common_block
resources :foobars, path: "foobars", &common_block
</code></pre>
|
Sparx Enterprise Architect: undo get all latest <p>I have Sparx EA setup with version control. Prior to checking in updates to my model I did a get all latest. But doing so has completely mangled one of my diagrams. This is particularly odd as:</p>
<ol>
<li>The packages that contained the diagram and all the components in the diagram were checked out by me - so there is no way these should ever be updated the get all latest.</li>
<li>In any case I'm the only one who has ever worked on this model.</li>
</ol>
<p>What appears to have happened is that that I refactored a large diagram into three separate ones, buy cutting and pasting some components from the original into new diagram, leaving the original with a subset of the original components. The get all latest seems to have re-inserted all the original components and connections back into the original diagram and even re-locating some of the components in the original diagram, leaving an utter mess.</p>
<p>Is there any way to undo the actions of what I can only assume is a pretty serious bug?</p>
<p>many thanks in advance.</p>
| <p>No, you can not undo that unless you have a database backup. If you have not committed your work before, it's your own fault.</p>
<p>FWIW: Get All Latest is meant to be used in single distributed EAP files (or RDBMS remote to a central repos). It will erase all work and replace it with what has been stored in the VC system.</p>
<p><strong>Edit</strong>: Although the help states</p>
<blockquote>
<p>The Get All Latest command does not update any package that is checked-out (to anybody) in the currently loaded project; otherwise, any changes not yet committed to version control would be discarded</p>
</blockquote>
<p>this may affect current diagraming work. The simple reason is that a diagram content can well rely on other packages being altered during a Get All Latest. It also depends on whether one saves diagram changes which are otherwise held in memory and can cause trouble. </p>
<p>Anyhow, there is no undo for Get All Latest for sure. Go into a dark chamber, cry out loud and start doing it once again. Just revert to an older commit first.</p>
|
SQL - pick current date from machine and compare the year <p><strong>Scenario 1: Current Year</strong></p>
<p>Always code needs to pick </p>
<blockquote>
<p>The last Sunday of January for the current year. For ex(31-01-2016)</p>
</blockquote>
<p><em>Current code - picks 1st of Jan 2016</em></p>
<pre><code>convert(date,DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0))
</code></pre>
<p><strong>Scenario 2: Last Year</strong></p>
<p>Always code needs to pick </p>
<blockquote>
<p>The last Sunday of January for the Previous year. For ex(01-02-2015)</p>
</blockquote>
<p><em>Current code - picks 1st of Jan 2015</em></p>
<pre><code>convert(date,DATEADD(yy, DATEDIFF(yy, 0, dateadd(YEAR, - 1, getdate())), 0))
</code></pre>
<p>Instead of hard coding the date. I would like to pick date from machine and compare.</p>
<p><strong>Week start from Sunday and ends Saturday</strong>. Any help please?</p>
| <pre><code>-- Sample Demonstrative Data/Test Results
Declare @YourTable table (SomeDate date)
Insert Into @YourTable values ('2000-06-15'),('2001-06-15'),('2002-06-15'),('2003-06-15'),('2004-06-15'),('2005-06-15'),('2006-06-15')
,('2007-06-15'),('2008-06-15'),('2009-06-15'),('2011-06-15'),('2012-06-15'),('2013-06-15'),('2014-06-15'),('2015-06-15'),('2016-06-15')
,('2017-06-15'),('2018-06-15'),('2019-06-15'),('2020-06-15')
-- To Confirm Results
Select Year = year(SomeDate)
,LastSundayDate = DateAdd(DD,-DatePart(DW,DateFromParts(Year(SomeDate),12,31))+1,DateFromParts(Year(SomeDate),12,31))
,LastSundayName = DateName(DW,DateAdd(DD,-DatePart(DW,DateFromParts(Year(SomeDate),12,31))+1,DateFromParts(Year(SomeDate),12,31)))
From @YourTable
</code></pre>
<p>Returns</p>
<pre><code>Year LastSundayDate LastSundayName
2000 2000-12-31 Sunday
2001 2001-12-30 Sunday
2002 2002-12-29 Sunday
2003 2003-12-28 Sunday
2004 2004-12-26 Sunday
2005 2005-12-25 Sunday
2006 2006-12-31 Sunday
2007 2007-12-30 Sunday
2008 2008-12-28 Sunday
2009 2009-12-27 Sunday
2011 2011-12-25 Sunday
2012 2012-12-30 Sunday
2013 2013-12-29 Sunday
2014 2014-12-28 Sunday
2015 2015-12-27 Sunday
2016 2016-12-25 Sunday
2017 2017-12-31 Sunday
2018 2018-12-30 Sunday
2019 2019-12-29 Sunday
2020 2020-12-27 Sunday
</code></pre>
|
Removing Try failures in collection using flatMap <p>I have a Map[String, String]</p>
<p>How can I simply this expression using flatMap?</p>
<pre><code> val carNumbers = carMap.keys.map(k => Try(k.stripPrefix("car_number_").toInt)).toList.filter(_.isSuccess)
</code></pre>
<p>Note: I want to remove the Failure/Success wrapper and just have a List[Int].</p>
| <p>It looks like you just want to convert <code>Try</code> to <code>Option</code>:</p>
<pre><code>for {
key <- carMap.keys
t <- Try(key.stripPrefix("car_number_").toInt).toOption
} yield t
</code></pre>
<p>this will result <code>Iterable</code> and you can convert it to list with <code>.toList</code> method.</p>
<p>Also you can go with oneliner like this:</p>
<pre><code>carMap.keys.flatMap(k => Try(k.stripPrefix("car_number_").toInt).toOption)
</code></pre>
|
minimum and maximum of moving window, better implementation? <p>I am trying to find a min-max of a moving window by using queues. I was able to create a solution but this feels very slow.</p>
<p>Here is my solution:</p>
<pre><code>def min_max(value:T, windowSize: Int):(T,T) = {
val queue = new scala.collection.mutable.Queue[A]() //I added the creation of this queue here for you to see
if(queue.size == windowSize) queue.dequeue
queue.enqueue(value)
var min = queue.head
var max = queue.head
for(i <- queue) {
if(i<min) min = i
if(i>max) max = i
}
(min, max) // returns the min and max in a tuple
}
</code></pre>
| <p>It depends on how your queue is constructed and populated, and how large it is. In short, you can make scanning for min/max faster, but it'll make adding elements to the queue slower, or incur some upfront cost.</p>
<p>What you are doing is linear, which is about as good as you can do with a linear data struct, but you could write it in a more idiomatic manner (and also I am not sure what's the deal with <code>dequeue</code> in the beginning, and what you expect to happen when the queue size is less or larger than the parameter):</p>
<pre><code> queue
.take(windowSize)
.foldLeft(Option.empty[A] -> Option.empty[A]) {
case ((None, None), x) => Some(x) -> Some(x)
case ((x, y), z) => x.map(x min z) -> y.map(y max z)
}
</code></pre>
<p>This also assumes that there is no race (nobody is adding data to the queue while you are traversing it). All this stuff would be a lot easier to reason about if you adopted the functional approach of not using mutable structures unless you absolutely have to.</p>
|
Spring UnsatisfiedDependencyException after upgrading spring from 3.1.1 to 4.3.3 <p>I'm trying to upgrade my application to the latest version of Spring & Camel, but im getting the exception listed below. I also listed the config section that spring is having an issue with. FYI, my application, including this config element, is working fine with the older versions of the libraries. Why can't spring 4.3.3 find that class when Spring 3.1.1 finds it without any issues?</p>
<p>These are the libraries im updating:</p>
<ul>
<li>Spring 3.1.1 to 4.3.3</li>
<li>Camel 2.13.4 to 2.17.3</li>
<li>cglib 2.2.2 to 3.2.4</li>
<li>cxf 2.6.1 to 3.1.7</li>
</ul>
<p>I really only changed the pom.xml & a couple minor changes due to the library updates. Can anyone point me in the right direction on how to resolve this?</p>
<p><strong>Spring is having an issue here</strong></p>
<pre><code><bean id="test.format" class="org.apache.camel.dataformat.bindy.fixed.BindyFixedLengthDataFormat">
<constructor-arg value="com.application.businessobject.test" />
</bean>
</code></pre>
<p><strong>Exception</strong></p>
<pre><code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'test.format' defined in class path resource [trs.application.finance.businessactivities.watchers.externaldata.xml]: Unsatisfied dependency expressed through constructor parameter 0: Could not convert argument value of type [java.lang.String] to required type [java.lang.Class]: Failed to convert value of type [java.lang.String] to required type [java.lang.Class]; nested exception is java.lang.IllegalArgumentException: Cannot find class [com.application.businessobject.test]
</code></pre>
| <p><a href="https://github.com/apache/camel/blob/master/components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/fixed/BindyFixedLengthDataFormat.java" rel="nofollow">https://github.com/apache/camel/blob/master/components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/fixed/BindyFixedLengthDataFormat.java</a></p>
<p>Apparently in earlier CAMEL versions there was a constructor of this class that expected packages as a String... vararg parameter, but has been since removed with this commit</p>
<p><a href="https://github.com/apache/camel/commit/ce6bf6e6feb5f425cd544c4c1edfa2eb34641907" rel="nofollow">https://github.com/apache/camel/commit/ce6bf6e6feb5f425cd544c4c1edfa2eb34641907</a></p>
<p>So your bean declaration is not valid any more and results in the above exception</p>
<pre><code>Could not convert argument value of type [java.lang.String] to required type [java.lang.Class]:
</code></pre>
<p>Should be declared instead</p>
<pre><code><bean id="test.format" class="org.apache.camel.dataformat.bindy.fixed.BindyFixedLengthDataFormat">
<constructor-arg>
<value type="java.lang.Class">com.application.businessobject.Test</value>
</constructor-arg>
</bean>
</code></pre>
|
At which pixel do I draw these frequencies lines? <p>I need to plot on a C++ GUI Display some "lines" that identify frequency "bands". Such as these:</p>
<p><a href="https://i.stack.imgur.com/z3SqW.png" rel="nofollow"><img src="https://i.stack.imgur.com/z3SqW.png" alt="enter image description here"></a></p>
<p>Since my working frequency range will be between 20 hz and 20 khz, frequency is logaritmic and my C++ Display width is 270 pixels, at which pixel should I draw 100hz, 1 khz and 10 khz lines?</p>
<p>I can't get the math scaling.</p>
| <p>You need to find coefficients <code>a</code> and <code>b</code> of equation</p>
<pre><code> x = a + b * Log(f)
</code></pre>
<p>for two border cases <code>f=20, x=0</code> and <code>f=20000, x=269</code> </p>
|
Href passing page options <p>My current URL is something like this:</p>
<pre><code>http://127.0.0.1:8000/browse/?name=&status=any
</code></pre>
<p>On it I have a paginator which allows me to browse by page number. How would I set the href so it goes to the next page, while passing in the <code>name</code> and <code>status</code> options? So for example the href for <code>page2</code> should be:</p>
<pre><code>http://127.0.0.1:8000/browse/?name=&status=any&page=2
</code></pre>
<p>But if I set </p>
<pre><code><a href="?page={{ paginator.previous_page_number }}">
</code></pre>
<p>Then the URL is </p>
<pre><code>http://127.0.0.1:8000/browse/?page=2
</code></pre>
<p>Does anyone know how I can get this done?</p>
| <p>From what I can see you for got the rest. So..</p>
<p>in: </p>
<pre><code><a href="?page={{ paginator.previous_page_number }}">
</code></pre>
<p>should be</p>
<pre><code><a href="?name=&status=any&page={{ paginator.previous_page_number }}">
</code></pre>
<p>Right? I think? Reason is because the paginator part only provides the page number. So you need the rest to go with it.</p>
|
node.js: get variable's name <pre><code>let f = function(list) //'list' is an array [o1, o2, etc.]
{
list.forEach(function(e)
{
console.log('name ', ??);
};
};
</code></pre>
<p>just wonder how to get current elm's name to have output like that:
o1
o2</p>
<p>thnx</p>
<p>p.s. toString() puts [object Object]</p>
| <p>Referencing forEach here:
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach</a></p>
<p>Doing a forEach you get access (in the callback) to three pieces of information. The currentValue, the index and the whole array. I'm unsure exactly of what you are looking for, but given that it is an array you really only have 2 key pieces, the index and the value.</p>
<p>Changing your code up you can output both of those pieces of data like this:</p>
<pre><code>let f = function(list) { //'list' is an array [o1, o2, etc.]
list.forEach(function(val, ind) {
console.log('value at index(%d): %o', ind, val)
})
}
</code></pre>
<p>Note that I use <code>%o</code> for the value as it is the best catch-all for handling multiple different types of objects when using console.</p>
|
C# nullify a delegate reference <p>let's say I've a class to manage a stack of delegates. For some reason, at some point I need to invalidate a random delegate on the stack so, since I pass a variable of a delegate as reference, I expect that setting to null that variable, will prevent the stack to invoke that method just testing if it is null, but instead happens that the reference to the method is still there and therefore will be called. Here some silly code to show what I mean:</p>
<pre><code>public delegate void DlgtVoidVoid();
public class TestPile {
Pile pileStack = new Pile();
DlgtVoidVoid _delvar1 = null;
DlgtVoidVoid _delvar2 = null;
public void Main()
{
_delvar1 = voidmethod1;
_delvar2 = voidmethod2;
pileStack.PushItem(ref _delvar1);
pileStack.PushItem(ref _delvar2);
//trying to invalidate the first delegate handler
_delvar1 = null;
pileStack.InvokeAndPop();//invoke 2
pileStack.InvokeAndPop();//shouldn't voidmethod1 call fail?
//but instead also voidmethod1 will be called: why?
}
void voidmethod1()
{
Console.WriteLine("calling void method one");
}
void voidmethod2()
{
Console.WriteLine("calling void method two");
}
}
</code></pre>
<p>and this is a little stack manager just for an example:</p>
<pre><code>public class Pile {
DlgtVoidVoid[] thepile = new DlgtVoidVoid[10];
int pileindex = -1;
public void PushItem(ref DlgtVoidVoid item)
{
thepile[++pileindex] = item;
}
public DlgtVoidVoid PeekItem()
{
return thepile[pileindex];
}
public DlgtVoidVoid PopItem()
{
return thepile[pileindex--];
}
public void InvokeAndPop()
{
if(pileindex >= 0) {
if(PeekItem() != null)
PopItem().Invoke();
}
}
}
</code></pre>
<p>It is obvious that passing with ref a reference variable in c# don't work as I would expect, let's say, in C++ or some, therefore is there a way to achieve that in C# or I must change that code logic?</p>
| <p>I find your code not very well-designed... Setting local variable to NULL will not make anyone expect any changes in some other classes internal data. It will definitely lead to bugs sooner or later even if you could achieved this.</p>
<p>It would be better to just use a <code>List<DlgtVoidVoid></code> instead of array in the <code>Pile</code> class. And instead of nulling the delegate reference, you better create a special method "<code>Remove</code>" which will subsequently call corresponding method of the <code>List</code>.</p>
<pre><code>public class Pile {
private List<DlgtVoidVoid> thepile = new List<DlgtVoidVoid>();
public void PushItem(DlgtVoidVoid item)
{
thepile.Add(item);
}
public DlgtVoidVoid PeekItem()
{
return thepile[thepile.Count-1];
}
public DlgtVoidVoid PopItem()
{
var item = thepile[thepile.Count-1];
thepile.RemoveAt(thepile.Count-1);
return item;
}
public void InvokeAndPop()
{
PopItem()();
}
public void Remove(DlgtVoidVoid deletageToRemove) {
thepile.Remove(deletageToRemove);
}
}
//...
public void Main()
{
_delvar1 = voidmethod1;
_delvar2 = voidmethod2;
pileStack.PushItem(ref _delvar1);
pileStack.PushItem(ref _delvar2);
//trying to invalidate the first delegate handler
pileStack.Remove(_delvar1);
pileStack.InvokeAndPop();//invoke 2
pileStack.InvokeAndPop();//Now it will throw you IndexOutOfRange exception. You could handle it better inside of the Pile methods
}
</code></pre>
|
How can I compose a query such as (A || B || C) && (X || Y) in MongoDB Java Driver 3.2 <p>Unfortunately, I cannot find an example for Mongo 3.2 java driver for query like "(A or B or C) and (D or E or F or G)" </p>
<p>Number of parameters inside parentheses will be variable - <strong>up to hundred</strong>.</p>
<p>Funny thing that I've found example for "(A && B) || (X && Y)" but it doesn't help me.</p>
<p><a href="http://stackoverflow.com/questions/36753254/how-to-execute-queries-with-both-and-and-or-clauses-in-mongodb-with-java">How to execute queries with both AND and OR clauses in MongoDB with Java</a></p>
<p>My code produces error:</p>
<p><strong>MongoQueryException: Query failed with error code 2 and error message '$or/$and/$nor entries need to be full objects'</strong></p>
<pre><code>List<Document> docs = new ArrayList<>();
for (Integer ln: input.getLastnames()) {
docs.add(new Document("lastname",ln));
}
Document queryLN = new Document(
"$or", Arrays.asList(docs)
);
docs.clear();
for (Integer fn: input.getFirstnames()) {
docs.add(new Document("firstname",fn));
}
Document queryFN = new Document(
"$or", Arrays.asList(docs)
);
Document query = new Document(
"$and", Arrays.asList(queryFN,queryLN));
List<Document> result = collectionMain.find(query).into(new ArrayList<Document>());
</code></pre>
| <p>You should use an "in" query in such condition when you have a long unknown list of OR conditions.</p>
<p>An example code:</p>
<pre><code>try {
MongoClient mongo = new MongoClient();
DB db = mongo.getDB("so");
DBCollection coll = db.getCollection("employees");
List<Integer> ageList = new ArrayList<>();
ageList.add(30);
ageList.add(35);
List<String> nameList = new ArrayList<>();
nameList.add("Anna");
BasicDBObject query = new BasicDBObject("$and", Arrays.asList(
new BasicDBObject("age", new BasicDBObject("$in", ageList)),
new BasicDBObject("name", new BasicDBObject("$in", nameList)))
);
DBCursor cursor = coll.find(query);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
}catch (Exception ex){
ex.printStackTrace();
}
</code></pre>
<p>To experiment with the above code, you can add the following entries in your MongoDB:</p>
<pre><code>db.employees.insert({"name":"Adma","dept":"Admin","languages":["german","french","english","hindi"],"age":30, "totalExp":10});
db.employees.insert({"name":"Anna","dept":"Admin","languages":["english","hindi"],"age":35, "totalExp":11});
db.employees.insert({"name":"Bob","dept":"Facilities","languages":["english","hindi"],"age":36, "totalExp":14});
db.employees.insert({"name":"Cathy","dept":"Facilities","languages":["hindi"],"age":31, "totalExp":4});
db.employees.insert({"name":"Mike","dept":"HR","languages":["english", "hindi", "spanish"],"age":26, "totalExp":3});
db.employees.insert({"name":"Jenny","dept":"HR","languages":["english", "hindi", "spanish"],"age":25, "totalExp":3});
</code></pre>
<p>The above code produces this query:</p>
<pre><code>db.employees.find({"$and":[{"age":{"$in":[30, 35]}},{"name":{"$in":["Anna"]}}]});
</code></pre>
<p>And the output is:</p>
<pre><code>{ "_id" : { "$oid" : "57ff3e5e3dedf0228d4862ad"} , "name" : "Anna" , "dept" : "Admin" , "languages" : [ "english" , "hindi"] , "age" : 35.0 , "totalExp" : 11.0}
</code></pre>
<p>A good article on this topic: <a href="https://www.mkyong.com/mongodb/java-mongodb-query-document/" rel="nofollow">https://www.mkyong.com/mongodb/java-mongodb-query-document/</a></p>
<p>Read these as well: <a href="http://stackoverflow.com/a/8219679/3896066">http://stackoverflow.com/a/8219679/3896066</a> and <a href="http://stackoverflow.com/a/14738878/3896066">http://stackoverflow.com/a/14738878/3896066</a></p>
|
$location.path takes time to work after bootstrap modal hide (hide.bs.modal) event is fired <pre><code> // show mymodal
// register an event to route to a different page once modal is closed
$('#myModal').on('hide.bs.modal', function() {
if ($location.path() == '/') {
$location.path('/ser/mynewpath');
alert("fired"); // just to check the event was fired
}
});
// open the modal
$('#myModal').modal('show');
</code></pre>
<p>I'm calling the bootstrap modal #myModal using JavaScript. Once I close the modal I want to direct the page to a different path. The problem is it takes 30sec - 1 min to direct the page after closing the modal. I added an alert to check if the event is getting late to fire, but I get the alert the moment I close the modal, but the page is only directed after a long wait.</p>
<p>Sometimes when I click somewhere else it will get fired. But this is not happening always - at times the long wait is inevitable.</p>
<p>My initial guess was since I'm using the bootstrap modal and using the $location, angular might not detect it the moment modal gets closed. But now it seems like a dumb guess. I also tried changing the event trigger to 'hidden.bs.modal' but got the same result.</p>
<p>I will try adding angular $modal and see if this solves, will post the updates. But meanwhile I'm thrilled to understand the cause behind this delay in this setup.</p>
<p>Thank you.</p>
| <p>Since it is <code>jquery</code> event <code>angular</code> will not be aware of this event immediately. It will have to wait till the next digest cycle and that is causing the delay. You try using <code>$scope.$apply</code></p>
<pre><code>$scope.$apply(function() {
if ($location.path() == '/') {
$location.path('/ser/mynewpath');
alert("fired"); // just to check the event was fired
}
}
</code></pre>
|
IP Check Via List <p>I have an ip list file for my country, as like this (txt document):</p>
<pre><code>45.123.116.0/22
5.2.80.0/21
5.11.128.0/17
5.23.120.0/21
5.24.0.0/14
etc
</code></pre>
<p>i have two question about that.</p>
<p>1- can i forward the user, if he is in that list via .htaccess file? (if he is, use this adress.. if not this adress)</p>
<p>2- how can i check 'if the user is in my country' via PHP? i mean, how can i say something like that..</p>
<pre><code>if (strstr('list.txt',$_SERVER['REMOTE_ADDR']))
</code></pre>
| <p><strong>*1).htaccess file</strong></p>
<p>The visitor blocking facilities offered by the Apache Web Server enable us to deny access to specific visitors, or allow access to specific visitors. This is extremely useful for blocking unwanted visitors, or to only allow the web site owner access to certain sections of the web site, such as an administration* </p>
<pre><code>ErrorDocument 403 /specific_page.html
area.*
order allow,deny
deny from 255.0.0.0
deny from 123.45.6.
allow from all
</code></pre>
<p>When using the "Order Allow,Deny" directive the requests must match either Allow or Deny, if neither is met, the request is denied.</p>
<p>doc 1)<a href="http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order" rel="nofollow">http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order</a></p>
<p>doc 2)<a href="http://www.htaccess-guide.com/deny-visitors-by-ip-address/" rel="nofollow">http://www.htaccess-guide.com/deny-visitors-by-ip-address/</a></p>
<p><strong>2) Proof of Concept (can't say this works as is....)</strong></p>
<pre><code>$current_ip = $_SERVER['REMOTE_ADDR'];
$valid_ip = false;
// Convert IPs to Regex
foreach($cfg['ipallowed'] as $index=>$ip);
{
$ip = str_replace('.', '\\.', $ip);
$ip = str_replace('*', '[0-9]|^1?\\d\\d$|2[0-4]\\d|25[0-5]');
if (preg_match($ip, $current_ip)
{
$valid_up = true;
break;
}
}
if ($valid_ip)
</code></pre>
|
Codeigniter: common funcs. vs multiple funcs. DB query performance <p>I hope to get answers based on experience and knowledge based on Codeigniter for this question.
Lets say I have 10 tables in a database and I want to query all the rows in the 10 tables at the same time in the same controller.
and there are two ways of doing this,</p>
<p><strong>Case 01</strong> - Use common query function like below,</p>
<p><strong>Controller</strong></p>
<pre><code>sample_function(){
'table1_data' => $this->common_model->get_table( 'table1' ),
'table2_data' => $this->common_model->get_table( 'table2' ),
...
'table9_data' => $this->common_model->get_table( 'table9' ),
'table10_data' => $this->common_model->get_table( 'table10' )
}
</code></pre>
<p>and then in the common_model</p>
<pre><code>function get_table( $table_name ){
$this->db->select()->from( $table_name );
$sql_stmt = $this->db->get();
return $sql_stmt->result();
}
</code></pre>
<p>so in this case the <code>get_table( $table_name )</code> will run 10 times.</p>
<p><strong>Case 02</strong> - Use seperate functions for each 10 tables like below,</p>
<p><strong>Controller</strong></p>
<pre><code>sample_function(){
'table1_data' => $this->common_model->get_table1(),
'table2_data' => $this->common_model->get_table2(),
...
'table9_data' => $this->common_model->get_table9(),
'table10_data' => $this->common_model->get_table10()
}
</code></pre>
<p>so that the common_model will be like this and here we have 10 functions not like use the same function in Case01</p>
<pre><code>function get_table1()
{
$this->db->select()->from( 'table1' );
$sql_stmt = $this->db->get();
return $sql_stmt->result();
}
function get_table2()
{
$this->db->select()->from( 'table2' );
$sql_stmt = $this->db->get();
return $sql_stmt->result();
}
....
function get_table9()
{
$this->db->select()->from( 'table9' );
$sql_stmt = $this->db->get();
return $sql_stmt->result();
}
function get_table10()
{
$this->db->select()->from( 'table10' );
$sql_stmt = $this->db->get();
return $sql_stmt->result();
}
</code></pre>
<p>in this case 10 seperate functions run one time each.</p>
<p>It is obvious the Case 01 is the best when we consider code usability but my quiestion is when we consider the performance,</p>
<ol>
<li><p>Which one is the best case in Codeigniter?</p></li>
<li><p>When it comes to Case 01, the get_table will run simultaniously or one at a time?</p></li>
<li><p>Whis case is the best for performance in CI?</p></li>
</ol>
<p>Thnaks</p>
| <p>Wild guess based on years of experience in backend development: Both will run equally fast/slow depending on how many rows you have in your tables.</p>
<p>As you already have the code, just give it a try with a suitable benchmark. Let both routines run a couple thousand times and take the average.</p>
|
How to create zip file deflate all the entry <p>I have a zip file that i think it was created by zip, but when i unzip it, and try to create a zip from those unziped file, it diferent from zipinfo command.
this is result when I do zipinfo command on linux of source file:</p>
<pre><code>root@TLBBServer:/home/web/Patch/u# zipinfo u1.zip
Archive: u1.zip
Zip file size: 662378 bytes, number of entries: 3
-rw-a-- 2.3 ntf 3133736 bx defX 08-Jan-28 07:20 Data/LaunchSkin.axp
-rw-a-- 2.3 ntf 1196154 bx defX 08-Feb-03 03:52 (version)
-rw-a-- 2.3 ntf 36 bx defX 08-Feb-03 03:53 (command)
3 files, 4329926 bytes uncompressed, 661972 bytes compressed: 84.7%
</code></pre>
<p>this is result when i do with a clone file:</p>
<pre><code>root@TLBBServer:/home/web/Patch/u# zipinfo u.zip
Archive: u.zip
Zip file size: 661897 bytes, number of entries: 3
-rw---- 2.3 ntf 1217589 tx defX 08-Feb-03 03:52 (version)
-rw---- 2.3 ntf 3135715 bx defX 08-Jan-28 07:20 Data/LaunchSkin.axp
-rw---- 2.3 ntf 38 tx stor 08-Feb-03 03:53 (command)
3 files, 4353342 bytes uncompressed, 661255 bytes compressed: 84.8%
</code></pre>
<p>this is source file:
<a href="https://github.com/HadesD/TLBB-Web/raw/master/u1.zip" rel="nofollow">https://github.com/HadesD/TLBB-Web/raw/master/u1.zip</a></p>
| <p>So? Why do you care?</p>
<p>A different zip program, or the same zip program with different settings, or a different version of the same zip program with the same settings can all produce different output. However they will all be valid, decompressible zip files, assuring that the contents are uncompressed exactly.</p>
<p>The only guarantee of the lossless compressor is that compression followed by decompression will always give you exactly the same thing back. There is no guarantee, and there does not need to be a guarantee, that decompression followed by compression will give you the same thing back.</p>
|
Spark Connector MongoDB - Python API <p>I'd like pull data from Mongo by Spark, especially by PySpark..
I have found official guide from Mongo <a href="https://docs.mongodb.com/spark-connector/python-api/" rel="nofollow">https://docs.mongodb.com/spark-connector/python-api/</a></p>
<p>I have all prerequisites:</p>
<ul>
<li>Scala 2.11.8</li>
<li>Spark 1.6.2</li>
<li><p>MongoDB 3.0.8 (not on same device where is Spark)</p>
<p>$ pyspark --conf
"spark.mongodb.input.uri=mongodb://mongo1:27019/xxx.xxx?readPreference=primaryPreferred"
--packages org.mongodb.spark:mongo-spark-connector_2.11:1.1.0</p></li>
</ul>
<p>and PySpark showed me this:</p>
<pre><code>Python 3.4.2 (default, Oct 8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
Ivy Default Cache set to: /root/.ivy2/cache
The jars for the packages stored in: /root/.ivy2/jars
:: loading settings :: url = jar:file:/usr/local/spark/lib/spark-assembly-1.6.2-hadoop2.6.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
org.mongodb.spark#mongo-spark-connector_2.11 added as a dependency
:: resolving dependencies :: org.apache.spark#spark-submit-parent;1.0
confs: [default]
found org.mongodb.spark#mongo-spark-connector_2.11;1.1.0 in central
found org.mongodb#mongo-java-driver;3.2.2 in central
:: resolution report :: resolve 280ms :: artifacts dl 6ms
:: modules in use:
org.mongodb#mongo-java-driver;3.2.2 from central in [default]
org.mongodb.spark#mongo-spark-connector_2.11;1.1.0 from central in [default]
---------------------------------------------------------------------
| | modules || artifacts |
| conf | number| search|dwnlded|evicted|| number|dwnlded|
---------------------------------------------------------------------
| default | 2 | 0 | 0 | 0 || 2 | 0 |
---------------------------------------------------------------------
:: retrieving :: org.apache.spark#spark-submit-parent
confs: [default]
0 artifacts copied, 2 already retrieved (0kB/9ms)
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
16/10/12 16:35:46 INFO SparkContext: Running Spark version 1.6.2
16/10/12 16:35:47 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/10/12 16:35:47 INFO SecurityManager: Changing view acls to: root
16/10/12 16:35:47 INFO SecurityManager: Changing modify acls to: root
16/10/12 16:35:47 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(root); users with modify permissions: Set(root)
16/10/12 16:35:47 INFO Utils: Successfully started service 'sparkDriver' on port 35485.
16/10/12 16:35:48 INFO Slf4jLogger: Slf4jLogger started
16/10/12 16:35:48 INFO Remoting: Starting remoting
16/10/12 16:35:48 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriverActorSystem@192.168.28.194:39860]
16/10/12 16:35:48 INFO Utils: Successfully started service 'sparkDriverActorSystem' on port 39860.
16/10/12 16:35:48 INFO SparkEnv: Registering MapOutputTracker
16/10/12 16:35:48 INFO SparkEnv: Registering BlockManagerMaster
16/10/12 16:35:48 INFO DiskBlockManager: Created local directory at /tmp/blockmgr-1e9185bd-fd1a-4d36-8c7e-9b6430e9f5c6
16/10/12 16:35:48 INFO MemoryStore: MemoryStore started with capacity 511.1 MB
16/10/12 16:35:48 INFO SparkEnv: Registering OutputCommitCoordinator
16/10/12 16:35:48 INFO Utils: Successfully started service 'SparkUI' on port 4040.
16/10/12 16:35:48 INFO SparkUI: Started SparkUI at http://192.168.28.194:4040
16/10/12 16:35:48 INFO HttpFileServer: HTTP File server directory is /tmp/spark-c1d32422-8241-411f-a751-e01e5f6e2b5c/httpd-d62ed1b8-e4ab-4891-9b61-5f0f5ae7eb6e
16/10/12 16:35:48 INFO HttpServer: Starting HTTP Server
16/10/12 16:35:48 INFO Utils: Successfully started service 'HTTP file server' on port 34716.
16/10/12 16:35:48 INFO SparkContext: Added JAR file:/root/.ivy2/jars/org.mongodb.spark_mongo-spark-connector_2.11-1.1.0.jar at http://192.168.28.194:34716/jars/org.mongodb.spark_mongo-spark-connector_2.11-1.1.0.jar with timestamp 1476282948892
16/10/12 16:35:48 INFO SparkContext: Added JAR file:/root/.ivy2/jars/org.mongodb_mongo-java-driver-3.2.2.jar at http://192.168.28.194:34716/jars/org.mongodb_mongo-java-driver-3.2.2.jar with timestamp 1476282948898
16/10/12 16:35:49 INFO Utils: Copying /root/.ivy2/jars/org.mongodb.spark_mongo-spark-connector_2.11-1.1.0.jar to /tmp/spark-c1d32422-8241-411f-a751-e01e5f6e2b5c/userFiles-549541b8-aaba-4444-b2eb-438baa7e82e8/org.mongodb.spark_mongo-spark-connector_2.11-1.1.0.jar
16/10/12 16:35:49 INFO SparkContext: Added file file:/root/.ivy2/jars/org.mongodb.spark_mongo-spark-connector_2.11-1.1.0.jar at file:/root/.ivy2/jars/org.mongodb.spark_mongo-spark-connector_2.11-1.1.0.jar with timestamp 1476282949018
16/10/12 16:35:49 INFO Utils: Copying /root/.ivy2/jars/org.mongodb_mongo-java-driver-3.2.2.jar to /tmp/spark-c1d32422-8241-411f-a751-e01e5f6e2b5c/userFiles-549541b8-aaba-4444-b2eb-438baa7e82e8/org.mongodb_mongo-java-driver-3.2.2.jar
16/10/12 16:35:49 INFO SparkContext: Added file file:/root/.ivy2/jars/org.mongodb_mongo-java-driver-3.2.2.jar at file:/root/.ivy2/jars/org.mongodb_mongo-java-driver-3.2.2.jar with timestamp 1476282949029
16/10/12 16:35:49 INFO Executor: Starting executor ID driver on host localhost
16/10/12 16:35:49 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 43448.
16/10/12 16:35:49 INFO NettyBlockTransferService: Server created on 43448
16/10/12 16:35:49 INFO BlockManagerMaster: Trying to register BlockManager
16/10/12 16:35:49 INFO BlockManagerMasterEndpoint: Registering block manager localhost:43448 with 511.1 MB RAM, BlockManagerId(driver, localhost, 43448)
16/10/12 16:35:49 INFO BlockManagerMaster: Registered BlockManager
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version 1.6.2
/_/
Using Python version 3.4.2 (default, Oct 8 2014 10:45:20)
SparkContext available as sc, HiveContext available as sqlContext.
</code></pre>
<p>then i put this code:</p>
<pre><code>df = sqlContext.read.format("com.mongodb.spark.sql.DefaultSource").load()
</code></pre>
<p>and there was this:</p>
<pre><code>16/10/12 16:40:51 INFO HiveContext: Initializing execution hive, version 1.2.1
16/10/12 16:40:51 INFO ClientWrapper: Inspected Hadoop version: 2.6.0
16/10/12 16:40:51 INFO ClientWrapper: Loaded org.apache.hadoop.hive.shims.Hadoop23Shims for Hadoop version 2.6.0
16/10/12 16:40:51 INFO HiveMetaStore: 0: Opening raw store with implemenation class:org.apache.hadoop.hive.metastore.ObjectStore
16/10/12 16:40:51 INFO ObjectStore: ObjectStore, initialize called
16/10/12 16:40:51 INFO Persistence: Property hive.metastore.integral.jdo.pushdown unknown - will be ignored
16/10/12 16:40:51 INFO Persistence: Property datanucleus.cache.level2 unknown - will be ignored
16/10/12 16:40:51 WARN Connection: BoneCP specified but not present in CLASSPATH (or one of dependencies)
16/10/12 16:40:51 WARN Connection: BoneCP specified but not present in CLASSPATH (or one of dependencies)
16/10/12 16:40:53 INFO ObjectStore: Setting MetaStore object pin classes with hive.metastore.cache.pinobjtypes="Table,StorageDescriptor,SerDeInfo,Partition,Database,Type,FieldSchema,Order"
16/10/12 16:40:53 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:53 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:54 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:54 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:54 INFO MetaStoreDirectSql: Using direct SQL, underlying DB is DERBY
16/10/12 16:40:54 INFO ObjectStore: Initialized ObjectStore
16/10/12 16:40:55 WARN ObjectStore: Version information not found in metastore. hive.metastore.schema.verification is not enabled so recording the schema version 1.2.0
16/10/12 16:40:55 WARN ObjectStore: Failed to get database default, returning NoSuchObjectException
16/10/12 16:40:55 INFO HiveMetaStore: Added admin role in metastore
16/10/12 16:40:55 INFO HiveMetaStore: Added public role in metastore
16/10/12 16:40:55 INFO HiveMetaStore: No user is added in admin role, since config is empty
16/10/12 16:40:55 INFO HiveMetaStore: 0: get_all_databases
16/10/12 16:40:55 INFO audit: ugi=root ip=unknown-ip-addr cmd=get_all_databases
16/10/12 16:40:55 INFO HiveMetaStore: 0: get_functions: db=default pat=*
16/10/12 16:40:55 INFO audit: ugi=root ip=unknown-ip-addr cmd=get_functions: db=default pat=*
16/10/12 16:40:55 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MResourceUri" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:55 INFO SessionState: Created local directory: /tmp/8733297b-e0d2-49cf-8557-62c8c4e7cc4a_resources
16/10/12 16:40:55 INFO SessionState: Created HDFS directory: /tmp/hive/root/8733297b-e0d2-49cf-8557-62c8c4e7cc4a
16/10/12 16:40:55 INFO SessionState: Created local directory: /tmp/root/8733297b-e0d2-49cf-8557-62c8c4e7cc4a
16/10/12 16:40:55 INFO SessionState: Created HDFS directory: /tmp/hive/root/8733297b-e0d2-49cf-8557-62c8c4e7cc4a/_tmp_space.db
16/10/12 16:40:55 INFO HiveContext: default warehouse location is /user/hive/warehouse
16/10/12 16:40:55 INFO HiveContext: Initializing HiveMetastoreConnection version 1.2.1 using Spark classes.
16/10/12 16:40:55 INFO ClientWrapper: Inspected Hadoop version: 2.6.0
16/10/12 16:40:55 INFO ClientWrapper: Loaded org.apache.hadoop.hive.shims.Hadoop23Shims for Hadoop version 2.6.0
16/10/12 16:40:56 INFO HiveMetaStore: 0: Opening raw store with implemenation class:org.apache.hadoop.hive.metastore.ObjectStore
16/10/12 16:40:56 INFO ObjectStore: ObjectStore, initialize called
16/10/12 16:40:56 INFO Persistence: Property hive.metastore.integral.jdo.pushdown unknown - will be ignored
16/10/12 16:40:56 INFO Persistence: Property datanucleus.cache.level2 unknown - will be ignored
16/10/12 16:40:56 WARN Connection: BoneCP specified but not present in CLASSPATH (or one of dependencies)
16/10/12 16:40:56 WARN Connection: BoneCP specified but not present in CLASSPATH (or one of dependencies)
16/10/12 16:40:57 INFO ObjectStore: Setting MetaStore object pin classes with hive.metastore.cache.pinobjtypes="Table,StorageDescriptor,SerDeInfo,Partition,Database,Type,FieldSchema,Order"
16/10/12 16:40:58 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:58 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:59 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MFieldSchema" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:59 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MOrder" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:59 INFO Query: Reading in results for query "org.datanucleus.store.rdbms.query.SQLQuery@0" since the connection used is closing
16/10/12 16:40:59 INFO MetaStoreDirectSql: Using direct SQL, underlying DB is DERBY
16/10/12 16:40:59 INFO ObjectStore: Initialized ObjectStore
16/10/12 16:40:59 INFO HiveMetaStore: Added admin role in metastore
16/10/12 16:40:59 INFO HiveMetaStore: Added public role in metastore
16/10/12 16:40:59 INFO HiveMetaStore: No user is added in admin role, since config is empty
16/10/12 16:40:59 INFO HiveMetaStore: 0: get_all_databases
16/10/12 16:40:59 INFO audit: ugi=root ip=unknown-ip-addr cmd=get_all_databases
16/10/12 16:40:59 INFO HiveMetaStore: 0: get_functions: db=default pat=*
16/10/12 16:40:59 INFO audit: ugi=root ip=unknown-ip-addr cmd=get_functions: db=default pat=*
16/10/12 16:40:59 INFO Datastore: The class "org.apache.hadoop.hive.metastore.model.MResourceUri" is tagged as "embedded-only" so does not have its own datastore table.
16/10/12 16:40:59 INFO SessionState: Created local directory: /tmp/cc4f12a5-e5b2-4a22-a240-04e1ca3727ae_resources
16/10/12 16:40:59 INFO SessionState: Created HDFS directory: /tmp/hive/root/cc4f12a5-e5b2-4a22-a240-04e1ca3727ae
16/10/12 16:40:59 INFO SessionState: Created local directory: /tmp/root/cc4f12a5-e5b2-4a22-a240-04e1ca3727ae
16/10/12 16:40:59 INFO SessionState: Created HDFS directory: /tmp/hive/root/cc4f12a5-e5b2-4a22-a240-04e1ca3727ae/_tmp_space.db
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/spark/python/pyspark/sql/readwriter.py", line 139, in load
return self._df(self._jreader.load())
File "/usr/local/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__
File "/usr/local/spark/python/pyspark/sql/utils.py", line 45, in deco
return f(*a, **kw)
File "/usr/local/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o24.load.
: java.lang.NoSuchMethodError: scala.Predef$.$conforms()Lscala/Predef$$less$colon$less;
at com.mongodb.spark.config.MongoCompanionConfig$class.getOptionsFromConf(MongoCompanionConfig.scala:209)
at com.mongodb.spark.config.ReadConfig$.getOptionsFromConf(ReadConfig.scala:39)
at com.mongodb.spark.config.MongoCompanionConfig$class.apply(MongoCompanionConfig.scala:101)
at com.mongodb.spark.config.ReadConfig$.apply(ReadConfig.scala:39)
at com.mongodb.spark.sql.DefaultSource.createRelation(DefaultSource.scala:67)
at com.mongodb.spark.sql.DefaultSource.createRelation(DefaultSource.scala:50)
at com.mongodb.spark.sql.DefaultSource.createRelation(DefaultSource.scala:36)
at org.apache.spark.sql.execution.datasources.ResolvedDataSource$.apply(ResolvedDataSource.scala:158)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:119)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
at py4j.Gateway.invoke(Gateway.java:259)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:209)
at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p>I have tried a lot of possible option to pull data from Mongo by Spark..Any tips?</p>
| <p>It looks like an error I'd expect to see if I were using code compiled in a different version of Scala. Have you tried running it with <code>--packages org.mongodb.spark:mongo-spark-connector_2.10:1.1.0</code>?</p>
<p>By default in Spark 1.6.x is compiled against Scala 2.10 and you have to manually build it for Scala 2.11 like so:</p>
<pre><code>./dev/change-scala-version.sh 2.11
mvn -Pyarn -Phadoop-2.4 -Dscala-2.11 -DskipTests clean package
</code></pre>
|
Rearranging column order in SELECT statement on MySql <p>I'm using the MySql C API and doing various queries I found it very inconvenient to go check the query each time to see the column ordering. Moreover, this approach is very prone to errors in case of a query edit.</p>
<p><strong>Is there anything I can do to assign by query each column ordinal?</strong></p>
<p>If not, is there a more convenient way to retrieve results via the C API? (currently using <code>mysql_fetch_row</code> and accessing the column id with the subscript operator).</p>
<p>Please not that I read the similar question <a href="http://stackoverflow.com/questions/34583349/is-it-possible-to-sort-the-order-in-which-columns-are-returned-in-a-mysql-select">Is it possible to sort the order in which columns are returned in a mysql SELECT statement?</a>, but I found it different from my case as I need to assign an arbitrary number of column ordinals.</p>
<p><strong>Edit:</strong></p>
<p><strong>Current situation</strong></p>
<p>query: <code>SELECT A.a, A.b, A.c FROM tbl1 A INNER JOIN tbl2 B ON B.id = A.B_id</code></p>
<p>c code: </p>
<pre><code>...
MYSQL_ROW row = mysql_fetch_row(result);
unsigned long *lengths = mysql_fetch_lengths(result);
...
int field1 = atoi(row[0]);
memcpy(row[1], field2, lengths[1]);
..continue for each row..
</code></pre>
<p><strong>Desired situation</strong></p>
<p>query: <code>SELECT A.a ORDINAL 1, A.b ORDINAL 2, A.c ORDINAL 3 FROM tbl1 A INNER JOIN tbl2 B ON B.id = A.B_id</code></p>
<p>c code: same as above.</p>
<p>Where <code>ORDINAL</code> statements are pseudo-SQL statements that would allow the returned columns to be ordered at wish.</p>
| <p>It's been a long time since I've coded C, and I'm sorry to answer and not comment (not enough points), but perhaps <code>mysql_fetch_field_direct()</code> (<a href="http://dev.mysql.com/doc/refman/5.7/en/mysql-fetch-field-direct.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.7/en/mysql-fetch-field-direct.html</a>) might be of help?</p>
|
Matlab checking if user input is a point on my plot <p>I've been trying to figure out how to do this now for a couple of hours. I have two equations that become plotted in an (x,y) format</p>
<pre><code>x = v*cosd(theta)*t;
y = -(g*t.^2)/2 + v*sind(theta)*t;
plot(x,y)
</code></pre>
<p>Variables v, theta, xanimal, yanimal are filled by user input once the program is ran. xanimal and yanimal are basically where the single point will be while v and theta are variables that go into to equations above that creates the trajectory.
What I'm looking for is some conditional statement that determines if the point (xanimal, yanimal) is on the plot or within 0.5 of the plot (x,y).
The plot (x,y) is ever changing since the values for the equation is filled via user input. </p>
<p>I've tried different things which none have worked. </p>
<pre><code> One Attempt
for i=1:max(x)
if xanimal == x(i) && yanimal == y
disp('Success')
end
end
</code></pre>
<p>This method also did not work</p>
<pre><code>Second Attempt
Xmax_animal = xanimal +.5;
Xmin_animal = x-.5;
Ymax_animal = y+.5
Ymin_animal = y-.5
Y_animal = linspace(max(y),min(y),1)
if(Y_animal>max1)
disp('food fight')
else
a = find(y >= Y_animal);
b = x(a);
d = b(1);
c1 = b(end);
if (Xmax_animal >= d) && (d >= Xmin_animal)
set(handles.edit5, 'String', 'Success')
</code></pre>
<p>Thanks in advance!</p>
| <p>You need a distance function that uses both coordinates instead of each coordinate separately. The following should work:</p>
<pre><code>function d = dist(x , y, xpoint, ypoint)
d = sqrt( (x - xpoint).^2 + (y - ypoint).^2 );
end
</code></pre>
<p>You can call this point giving it your x and y vectors and your xanimal and yanimal points to produce an array of distances. Then use</p>
<pre><code>if sum(d < 0.5) > 0
disp('Close enough!');
else
disp('too far away');
end
</code></pre>
|
Show top N items from dropdown-menu with jQuery Slice <p>I am trying to show only the top 10 results of each list in my navigation. I have about 5 UL's and want to show the top 10 results of each. code below works only the first list. What am I missing here.</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>$(document).ready(function() {
var elements = $(".dropdown .dropdown-menu li");
var index = 0;
var showFirstTen = function(index) {
if (index >= elements.length) {
index = 0;
}
console.log(index);
elements.hide().slice(index, index + 10).show();
}
showFirstTen(0);
});</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>
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories</a>
<ul class="dropdown-menu">
<li><a href="/">Music Accessories</a></li>
<li><a href="/">Devices &amp; Accessories</a></li>
<li><a href="/">Desk Accessories</a></li>
<li><a href="/">Home Automation</a></li>
<li><a href="/">Camera Accessories</a></li>
<li><a href="/">Mobility Accessories</a></li>
<li><a href="/">Monitors Accessories</a></li>
<li><a href="/">Tablet Accessories</a></li>
<li><a href="/">Phone Accessories</a></li>
<li><a href="/">Scanner Accessories</a></li>
<li><a href="/">Projector Accessorie</a></li>
<li><a href="/">Storage Accessories</a></li>
<li><a href="/">Communications Accessories</a></li>
</ul>
</li>
</ul></code></pre>
</div>
</div>
</p>
| <p>You can use <code>css</code> for that:</p>
<pre><code>li:nth-child(n+11) {
display: none;
}
</code></pre>
<p>This will make sure only the first 10 <code>li</code> elements will be displayed.</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>ul li:nth-child(n+11) {
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav navbar-nav">
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
</ul></code></pre>
</div>
</div>
</p>
<p>Here is an example (with background-change instead of hiding), just to see how it works (every <code>li</code> that it's pos>5 will get green background).</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul li:nth-child(n+6) {
background: green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav navbar-nav">
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories 1</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories 2</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories 3</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories 4</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories 5</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories 6</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories 7</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories 8</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="/accessories.aspx" target="" data-toggle="">Accessories 9</a>
<ul class="dropdown-menu">
<li>
<a href="/" >Music Accessories</a>
</li>
<li>
<a href="/">Devices &amp; Accessories</a>
</li>
<li>
<a href="/" >Desk Accessories</a>
</li>
<li>
<a href="/">Home Automation</a>
</li>
<li>
<a href="/" >Camera Accessories</a>
</li>
<li>
<a href="/">Mobility Accessories</a>
</li>
<li>
<a href="/" >Monitors Accessories</a>
</li>
<li>
<a href="/">Tablet Accessories</a>
</li>
<li>
<a href="/">Phone Accessories</a>
</li>
<li>
<a href="/">Scanner Accessories</a>
</li>
<li>
<a href="/">Projector Accessorie</a>
</li>
<li>
<a href="/">Storage Accessories</a>
</li>
<li>
<a href="/">Communications Accessories</a>
</li>
</ul>
</li>
</ul></code></pre>
</div>
</div>
</p>
|
How to clone blob container and contents <p><strong>Summary</strong><br>
I have picked up support for a fairly old website which stores a bunch of blobs in Azure. What I would like to do is duplicate all of my blobs from live to the test environment so I can use them without affecting users. </p>
<p><strong>Architecture</strong><br>
The website is a mix of VB webforms and MVC, communicating with an Azure blob service (e.g. <a href="https://x.blob.core.windows.net/LiveBlobs" rel="nofollow">https://x.blob.core.windows.net/LiveBlobs</a>).</p>
<p>The test site mirrors the live setup, except it points to a different blob container in the same storage account (e.g. <a href="https://x.blob.core.windows.net/TestBlobs" rel="nofollow">https://x.blob.core.windows.net/TestBlobs</a>)</p>
<p><strong>Questions</strong> </p>
<ul>
<li>Can I copy all of the blobs from live to test without downloading
them? They would need to maintain the same names.</li>
<li>How do I work out what it will cost to do this? The live blob
storage is roughly 130GB, but it should just be copying the data within the same data centre right?</li>
</ul>
<p><strong>Things I've investigated</strong><br>
I've spent quite some time searching for an answer, but what I've found deals with <a href="http://stackoverflow.com/questions/8582145/copying-storage-data-from-one-azure-account-to-another">copying between storage accounts</a> or <a href="http://stackoverflow.com/questions/14152087/copying-one-azure-blob-to-another-blob-in-azure-storage-client-2-0">copying single blobs</a>.</p>
<p>I've also found <a href="https://azure.microsoft.com/en-us/documentation/articles/storage-use-azcopy/#_blob-copy" rel="nofollow">AzCopy</a> which <a href="http://pcfromdc.blogspot.co.uk/2015/07/copying-blobs-between-azure-storage.html" rel="nofollow">looks promising</a> but it looks like it would copy the files one by one so I'm worried it would end up taking a long time and costing a lot.</p>
<p>I am fairly new to Azure so please forgive me if this is a silly question or I've missed out some important details. I'm more than happy to add any extra information should you need it.</p>
| <blockquote>
<p>Can I copy all of the blobs from live to test without downloading
them? They would need to maintain the same names.</p>
</blockquote>
<p>Yes, you can. Copying blob is an <code>asynchronous server-side</code> operation. You simply tell the blob service the blobs to copy & destination details and it will do the job for you. No need to download first and upload them to destination.</p>
<blockquote>
<p>How do I work out what it will cost to do this? The live blob storage
is roughly 130GB, but it should just be copying the data within the
same data centre right?</p>
</blockquote>
<p>So there are 3 things you need to consider when it comes to costing: 1) <code>Storage costs</code>, 2) <code>transaction costs</code> and 3) <code>data egress costs</code>. </p>
<p>Since the copied blobs will be stored somewhere, they will be consuming storage and you will incur storage costs. </p>
<p>Copy operation will perform some read operations on source blobs and then write operation on destination blobs (to create them), so you will have to incur transaction costs. At very minimum for each blob copy, you can expect 2 transactions - read on source and write on destination (though there can be more transactions). </p>
<p>You incur data egress costs if the destination storage account is not in the same region as your source storage account. As long as both storage accounts are in the same region, you would not incur this.</p>
<p>You can use <a href="https://azure.microsoft.com/en-in/pricing/calculator/?service=storage" rel="nofollow"><code>Azure Storage Pricing Calculator</code></a> to get an idea about how much it is going to cost you.</p>
<blockquote>
<p>I've also found AzCopy which looks promising but it looks like it
would copy the files one by one so I'm worried it would end up taking
a long time and costing a lot.</p>
</blockquote>
<p>Blobs are always copied one-by-one. Copying across storage accounts is always async server side operation so you can't really predict how much time it would take for the copy operation to complete but in my experience it is quite fast. If you want to control when the blobs are copied, you would need to download them first and upload them. <a href="https://blogs.msdn.microsoft.com/windowsazurestorage/2015/01/13/azcopy-introducing-synchronous-copy-and-customized-content-type/" rel="nofollow">AzCopy supports this mode as well</a>.</p>
<p>As far as costs are concerned, I think it is a relative term when you say it is going to cost a lot. But in general Azure Storage is very cheap and 130 GB is not a whole lot of data. </p>
|
SQL join statement on 2 tables <p>i am creating a join between two tables Product_Tree and Product on the two columns Model_Number and Manufacturer to return the matching columns.</p>
<p>Here are the 2 tables:</p>
<p><strong>Table : Product_Tree</strong></p>
<pre><code>Col1,Col2,Model_Number,Col3,Manufacturer,Col4
111111,Pepsi,aaa,111111,aaa,description
222222,Miranda,bbb,222222,bbb,'description
333333,Cola,bbb,333333,bbb,description
</code></pre>
<p><strong>Table : Product</strong></p>
<pre><code>Model_Number,Manufacturer
a,a
b,b
c,c
d,d
</code></pre>
<p>Here is the query:</p>
<pre><code>SELECT Product_Tree.col0,Product_Tree.col1,Product_Tree.col2,Product_Tree.col3,Product_Tree.Model_Number,Product_Tree.Manufacturer
FROM Product_Tree
JOIN Product ON Product.model_number LIKE ''''%''''Product_Tree.MODEL_NUMBER''''%''''
AND Product.manufacturer LIKE ''''%''Product_Tree.MANUFACTURER''''%'''';
</code></pre>
<p><strong>I am getting this error:</strong></p>
<pre><code>ORA-00911: invalid character
</code></pre>
| <p>You'll need to use a concatenation operator to concatenate your <code>%</code> wildcard to your column <code>product_tree.manufacturer</code>:</p>
<pre><code>SELECT Product_Tree.col0,Product_Tree.col1,Product_Tree.col2,Product_Tree.col3,Product_Tree.Model_Number,Product_Tree.Manufacturer
FROM Product_Tree
JOIN Product ON Product.model_number LIKE '%' || Product_Tree.MODEL_NUMBER || '%'
AND Product.manufacturer LIKE '%' || Product_Tree.MANUFACTURER || '%';
</code></pre>
<p>I'm guessing that this query is inside a script and is quoted using single quotes <code>'</code> which is why you have single quotes all over the place in here. If that's the case then your quoted SQL statement would be: </p>
<pre><code>SELECT Product_Tree.col0,Product_Tree.col1,Product_Tree.col2,Product_Tree.col3,Product_Tree.Model_Number,Product_Tree.Manufacturer
FROM Product_Tree
JOIN Product ON Product.model_number LIKE ''%'' || Product_Tree.MODEL_NUMBER || ''%''
AND Product.manufacturer LIKE ''%'' || Product_Tree.MANUFACTURER || ''%'';
</code></pre>
|
Mule SMTP not connecting due to password contains special character <p>I need to connect to a gmail account to send an email using the SMTP component in Mule.</p>
<p>The password for the account contains the @ sign and it throws the error shown below. How can I resolve this without changing the password? The account was set up by the test team so I'm not the owner of the email account so unable to change.</p>
<p>Error message (password changed):</p>
<pre><code>2016-10-12 15:43:47,827 ERROR Attempted to append to non-started appender Forced-Console
ERROR 2016-10-12 15:43:47,813 [main] org.mule.module.launcher.application.DefaultMuleApplication: null
java.net.URISyntaxException: Illegal character in authority at index 7: smtp://test:"Password@1"@smtp.gmail.com:25
at java.net.URI$Parser.fail(URI.java:2848) ~[?:1.8.0_66]
at java.net.URI$Parser.parseAuthority(URI.java:3186) ~[?:1.8.0_66]
at java.net.URI$Parser.parseHierarchical(URI.java:3097) ~[?:1.8.0_66]
at java.net.URI$Parser.parse(URI.java:3053) ~[?:1.8.0_66]
at java.net.URI.<init>(URI.java:588) ~[?:1.8.0_66]
</code></pre>
<p>Thanks</p>
| <p>Thanks. Changing @ to %40 worked</p>
|
Is there a way to exact match "truthy" and "falsey" values in ColdFusion <p>I recently had the need to match against two strings in ColdFusion and ran into this scenario during my loop:</p>
<pre><code><cfif "0" IS NOT "NO">
</code></pre>
<p>Generally during the loop it looks something like this:</p>
<pre><code><cfif "AM" IS NOT "BA">
</code></pre>
<p>Now both of these values were variables (I wasn't just typing it out for fun) and I was using "0" as a default value for the first variable to match against (since the second variables would never be 0) but both of these values changed in the loop I was running. I easily fixed this by setting my default value to <code>--</code> instead of <code>0</code> but I tried researching and found nothing indicating there was a way to get around the falsey nature of strings when evaluating them.</p>
<p>Is there no Operator or trick to match on the strings themselves and ignore their truthyness or falseyness in ColdFusion?</p>
| <p>The compare function will help you. This:</p>
<pre><code>writedump(compare("0", "NO"));
</code></pre>
<p>returns -1.</p>
<p><a href="http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7f84.html" rel="nofollow">This page</a> will tell you what that means.</p>
|
Mac 10.10.5 throwing error sudo: gpasswd: command not found <p>I have requirement to add jenkins user on "mac mini" to docker group and trying below </p>
<p>which sudo
/usr/bin/sudo</p>
<p>Not working
sudo gpasswd -a jenkins docker</p>
<p>Not working
/usr/bin/sudo gpasswd -a jenkins docker
sudo: gpasswd: command not found</p>
<p>.bash_profile entries</p>
<h1>------------------------------------------------------------</h1>
<pre><code>export PATH="$PATH:/usr/local/bin/"
export PATH="/usr/local/git/bin:/sw/bin/:/usr/local/bin:/usr/local/:/usr/local/sbin:/usr/local/mysql/bin:$PATH"
export PATH=/usr/bin:/usr/sbin:/bin:/usr/local/bin:/sbin:/opt/x11/bin:$PATH
</code></pre>
<p>Current logged user is administrator on this Mac. I'm not sure what may be going wrong here ?</p>
<p>Thanks,
Vikram</p>
| <p><a href="http://superuser.com/questions/214004/how-to-add-user-to-a-group-from-mac-os-x-command-line">http://superuser.com/questions/214004/how-to-add-user-to-a-group-from-mac-os-x-command-line</a></p>
<p>answered in above link.</p>
<p>The command which I was trying is not applicable for Mac OS</p>
|
Use interpolation in the route-href attribute <p>I'm trying to create a dynamic menu by looping over all routes of the router.</p>
<p>Simplified class (TypeScript flavour):</p>
<pre class="lang-js prettyprint-override"><code>@inject(Router)
export class NavBar {
constructor(private router: Router) {}
}
</code></pre>
<p>Simplified view:</p>
<pre class="lang-html prettyprint-override"><code><div repeat.for="route in router.routes">
<a route-href="route: ${route.name}">${route.title}</a>
</div>
</code></pre>
<p>Although it works if I simply print out the properties of the routes in the loop, the approach doesn't seem to be working for the <code>route-href</code> attribute. Any ideas how I can make this work?</p>
| <p>In the nav bar you do not need to use route-href, you could do:</p>
<pre><code><ul class="nav navbar-nav">
<li repeat.for="route of router.navigation" class="${row.isActive ? 'active' : ''}">
<a data-toggle="collapse" data-target="#bs-example-navbar-collapse-1.in" href.bind="route.href">${route.title}</a>
</li>
</ul>
</code></pre>
<p>A route-href can be used however if you want the user to click on a specific link that requires a parameter.</p>
<pre><code><tr repeat.for="log of logs">
<td><a route-href="route: log-details; params.bind: { logId: log.id }">${log.id}</a></td>
</tr>
</code></pre>
|
Data.table: dynamically creating variables over various subsets of data and grouping by variable x, subsetting final results <p>I am creating three types of variables over multiple time periods for individual customer IDs in my data. These new variables include the sum of a price vector, the mean of a price vector, and the mean difference between successive dates in a date vector. </p>
<p>Using data.table, I am looping through multiple time periods, subsetting the data in each period, and calculating those variables for individual customer IDs. Each of these variables are named dynamically as I loop over the time periods. As it stands, these variables are being computed correctly.</p>
<p>Here is where I am getting stuck: after all of these variables are computed, I would like to subset the data to include the new aggregated variables along with the most recent purchase.price and date elements for each customer. </p>
<p>I thought that data.table might replicate the computed totals over all rows corresponding to each customer. However, it only replicates those totals in rows corresponding to the period intervals specified in the table's i index. Since it does not replicate those totals over all rows for each customer, my final dplyr block does not do the trick.</p>
<p>In the second and third code blocks I will give the output of the final dplyr code and then what the output I would like to achieve.</p>
<p>This question stems from a similar problem noted where we are <a href="http://stackoverflow.com/questions/39989688/data-table-creating-new-variables-subsetting-by-date-periods-grouping-by-seco">subsetting over fewer variables that are not being created dynamically</a>.</p>
<pre><code>library(lubridate)
library(data.table)
library(dplyr)
data <- data.frame(custid = c(rep(1, 25), rep(2, 25), rep(1, 25), rep(2, 25)),
purchase.price = seq(1, 200, by=2),
date = seq.Date(from=as.Date("2015-01-01"), to=as.Date("2015-04-10"), by="days"))
period_intervals <- list(period_one = interval(as.Date("2015-01-01"), as.Date("2015-01-30")),
period_two = interval(as.Date("2015-02-01"), as.Date("2015-02-28")),
period_three = interval(as.Date("2015-03-01"), as.Date("2015-03-31")),
period_four = interval(as.Date("2015-04-01"), as.Date("2015-04-28")))
data <- as.data.table(data)
data <- data[order(date)]
setkey(data, custid)
time_periods <- c(1:4)
for(i in time_periods[1]:max(time_periods)){
data <- data[date %within% period_intervals[[i]],
paste("period", i, "price.sum", sep="."):= sum(purchase.price),
by = custid]
data <- data[date %within% period_intervals[[i]],
paste("period", i, "price.mean", sep="."):= mean(purchase.price),
by = custid]
data <- data[date %within% period_intervals[[i]],
paste("period", i, "mean.diff.date", sep="."):= mean(as.numeric(diff(purchase.price))),
by = custid]
}
data_sub <- data %>%
group_by(custid) %>%
arrange(desc(date)) %>%
filter(row_number() == 1)
</code></pre>
<p>Current result from dplyr subsetting (showing the first 7 columns):</p>
<pre><code> custid purchase.price date period.1.price.sum period.1.price.mean period.1.mean.diff.date period.2.price.sum ...
<dbl> <dbl> <date> <dbl> <dbl> <dbl> <dbl> ...
1 2 199 2015-04-10 NA NA NA NA ...
2 1 149 2015-03-16 NA NA NA NA ...
</code></pre>
<p>Here is what I was hoping for (showing first 7 columns): </p>
<pre><code> custid purchase.price date period.1.price.sum period.1.price.mean period.1.mean.diff.date period.2.price.sum ...
<dbl> <dbl> <date> <dbl> <dbl> <dbl> <dbl> ...
1 2 199 2015-04-10 625 25 2 981 ...
2 1 149 2015-03-16 275 55 2 1539 ...
</code></pre>
<p>Note: </p>
<p>In my complete dataset, I am looping over anywhere between 10-20 time periods. The number of periods to be computed over is subject to change, thus my approach to dynamically create the new variables. </p>
| <p>We can use <code>Map</code> as in the previous post</p>
<pre><code>nm1 <- sprintf("%s.%d.%s", "period", seq_along(period_intervals), "price.sum")
nm2 <- sprintf("%s.%d.%s", "period", seq_along(period_intervals), "price.mean")
nm3 <- sprintf("%s.%d.%s", "period", seq_along(period_intervals), "mean.diff.date")
data[, c(rbind(nm1, nm2, nm3)) := unlist(Map(function(x,y) {
x1 <- purchase.price[x %within% y]
list(sum(x1), mean(x1), mean(as.numeric(diff(x1))))},
list(date), period_intervals), recursive = FALSE), by = custid]
data[order(custid, -date)][,.SD[1] , custid]
</code></pre>
|
Angularjs <div ng-controller override second ng-controller <p>I'm using AngularJS for my charts. </p>
<p>I have to create two charts, they both use the same nav-bar. </p>
<p>I am able to display both charts on the screen, however; only <code><div ng-controller="first "></code> work with nav-bar. My second <code><div ng-controller="second"></code> get overridden.</p>
<pre><code><div ng-controller="first">
<div ng-controller="second ">
</code></pre>
<p>This is how I have it on my HTML,</p>
<p>If I replace <code><div ng-controller="second "></code> with <code><div ng-controller="first"></code>, ng-controller="second" will work just fine with dropdownm but "first" will be overridden </p>
<p>Here is my <a href="http://jsbin.com/qezepi/edit?html,js,output" rel="nofollow">JSBIN</a></p>
<p>I have also tried this <a href="http://stackoverflow.com/questions/27781172/multiple-ng-controller-directives-using-controller-as-x-on-the-same-element">answer on SO</a> either it didn't work for me or I couldn't get it to work.</p>
<p>My goal is to update both charts after making selection from dropdown menu. Right only one works because of the <code><div></code> issue</p>
| <p>So you want to have same filters for two charts, created from the data available in two different controllers.</p>
<p>Your current approach will just update the values attached with ng-model for the second controller. Instead, try using a service. Lets call it <code>chart.service</code></p>
<p>Now this service can have the values for filters like date, month year etc. Let both the controllers use this service and on update from UI, update the values in the service using your controllers. Since service will have a single instance, both controllers will now have the same value of filters and both your charts will be correctly shown. </p>
|
SQL server remote access <p>I am trying to connect to a remote SQL database.</p>
<p>I have the access and the sql server is configured for remote login.
I can login to the server from another machine (B) but not from my machine (A).</p>
<p>Both the machines (A and B) are on same domain. None have their IP white-listed.</p>
<p>In short, I do not think there is an issue on sql server side.</p>
<p>On my side,
I tried modifying DTC and firewall properties. (Not sure if the modifications are correct).</p>
<p>Could anybody please help.</p>
| <p>Are you trying to connect through software? You said "SQL Server" so I'll assume you're talking about using SSMS to connect to a server? </p>
<p>You said that you can login to the SQL server from the box that the server is on but not from a remote computer. This sounds like a permissions problem to me. </p>
<p>Is the account you created setup for Windows authentication? Should you be using a local SQL server account instead? </p>
<p>Some more information could help everyone troubleshoot.</p>
|
Getting Paper Size of a PDF <p>I am using PDFsharp to read / write PDF in our application. I am trying to get the paper size of a page to show in metadata window. I am using following code to do the same:</p>
<pre><code> // read PDF document into memory
ââââââvar pdfDocument = PdfReader.Open(pdfPath);
ââââââ// if PDF document has more than one page, then try to get the page size from first page
ââââââif (pdfDocument.Pages.Count > 0)
ââââââ{
ââââââââvar pageSize = pdfDocument.Pages[0].Size.ToString();
ââââââ} // if
</code></pre>
<p>But every time it returns 'Undefined', I even tried to create A4 page document for MS Word. But still it returns 'Undefined'.</p>
<p>I also created a PDF from HTML but then also page size comes as undefined.</p>
<pre><code>static void Main(string[] args)
{
// create PDF config to generate PDF
var config = new PdfGenerateConfig()
{
PageSize = PageSize.Letter,
PageOrientation = PageOrientation.Landscape
};
// load the HTML file
var html = System.IO.File.ReadAllText(@"C:\Users\mohit\Desktop\Temp\Ekta\Test.html");
// generate the PDF
var pdf = PdfGenerator.GeneratePdf(html,
PageSize.Letter);
// get the paper size of first page
var size = pdf.Pages[0].Size;
// save the pdf document
pdf.Save(@"C:\Users\mohit\Desktop\Temp\Ekta\A13.pdf");
Console.ReadKey();
}
</code></pre>
| <p>The properties you have to use are <code>Width</code> and <code>Height</code>. Convert them to millimeter or inch if you do not want to show the size in points.</p>
<p>The property <code>Size</code> is a convenient way to set standard page sizes for new pages as you can specify A4 or Letter. It will not be set for imported PDF files.</p>
|
Getting the count of a Filtered Result in a template on Django <p>Im trying to access a related model on the template like this:</p>
<pre><code>course.course_set.all.0.section_set.all.0.student_assignation.count
</code></pre>
<p>The problem is that I would like to count all the student assignations which have an <code>active = True</code> property.</p>
<p>I would like to be able to do something like this:</p>
<pre><code>course.course_set.all.0.section_set.all.0.student_assignation(active=True).count
</code></pre>
<p>How can I accomplish this on the django template?</p>
| <p>Django templates are note meant for such complex queries.
There are a few ways you can handle this</p>
<p>One, create a custom <a href="https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#custom-template-tags-and-filters" rel="nofollow">django template tag</a></p>
<p>Two, create a class method which would provide this info.</p>
<p>Example</p>
<pre><code>class Course:
...
def sutdent_assign_count(self):
#Your query goes here..
</code></pre>
|
How to avoid ExecutorService from overridding Security Principal of a Runnable <p>When the first runnable is submitted is an inject ExecutorService, the security Principal is correctly set for that runnable. Each subsequently submitted runnable is given the security principal of the original user instead of keeping the current runnable. My development machine is running Wildfly 8.2 .</p>
<p>I am creating a reporting system for asynchronous processing. I created a service that checks which user created the task and ensures that only that user can start or complete the task. The code for the service is below.</p>
<pre><code>@Stateless
public class ReportingService {
//EE injection security context
@Resource
SessionContext context;
//CDI security Principal
@Inject
Principal principal;
//this method handles getting the username for EE injection or CDI
private String getCurrentUser() {
if (context != null) {
return context.getCallerPrincipal().getName();
}
if (principal != null) {
return principal.getName();
}
return null;
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Transactional
public void registerTask(String taskId) {
//Create task
//set task.submittedBy = getCurrentUser()
//persist task
//code has been omitted since it is working
}
private void validateCurrentUserRegisteredJob(String taskId) {
String user = //get user that created task with id = id from DB
String currentUser = getCurrentUser();
if (!user.equals(currentUser)) {
throw new EJBAccesException("Current user "+currentUser+" did not register task");
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Transactional
public void startTask(String taskId) {
validateCurrentUserRegisteredJob(taskid);
//retrieve task entity, set start time to now, and merge
}
...
}
</code></pre>
<p>Below is my Runnable code</p>
<pre><code>public TaskRunner() implements Runnable {
//CDI principal
@Inject
Principal principal;
@Inject
ReportingService rs;
private taskId;
public void setTaskId() {...}
public void run() {
log.debug("Inside Runner Current User: "+principal.getName());
rs.startTask(taskId);
....
}
}
</code></pre>
<p>The following is the code from the Stateless Bean that is called by a REST endpoint that kicks off the process</p>
<pre><code>@Stateless
public ProjectService() {
@Inject
Instance<TaskRunner> taskRunner;
@Inject
ReportingService reportingService;
//ExecutorService that is create from Adam Bien's porcupine project
@Inject
@Dedicated
ExecutorService es;
//method that is called by rest enpoint to kick off
public void performAsynchAction(List<String> taskIds, ...rest of args...) {
taskIds.stream().forEach(t -> {
//registers task with user that made REST call
reportingService.registerTask(t);
TaskRunner runner = taskRunner.get();
runner.setTaskId(t);
log.debug("Created runner. Principal: "+runner.principal.getName());
es.submit(runner);
});
}
}
</code></pre>
<p>Here is the chart of the call flow</p>
<pre><code>REST -> ProjectService.performAsynchAction(...)
-> reportingService.registerTask(...)
-> create CDI injected Runnable
-> submit runner to executor service
-> ExecutorService calls Runner.run()
-> rs.startTask(taskId)
</code></pre>
<p>I call the Rest end point as user1 for the first time and register tasks: 1-2. They all work as expected and I get the following output in my log.</p>
<pre><code>Created runner. Principal: user1
Created runner. Principal: user1
Inside Runner Current User: user1
Inside Runner Current User: user1
</code></pre>
<p>The next time I make the same REST call as user2 and I get the following output in the log</p>
<pre><code>Created runner. Principal: user2
Inside Runner Current User: user1
EJBAccessException Current user user1 did not register task
</code></pre>
<p>It appears that the Security Principal of the Runnable is correctly set the first time a Runnable is submitted to the ExecutorService. But for each subsequent Runneable that is submitted to the ExecutorService uses the security Principal of the first submitted runnable. Is this a bug or the intended behavior? Does anyone know of a potential work around?</p>
<p>EDIT: I figure out that the porcupine project I was using to create the ExecutorService was not being managed by the container. Once I switched to a ManagedExecutorService, the SessionContext was being properly propagated.</p>
<pre><code>@Resource(lookup = "java:jboss/ee/concurrency/executor/customExecutor")
private ManagedExecutorService es;
</code></pre>
| <p>I figured out the issue. I looked into the porcupine code and found out that the ExecutorService was not being managed by the Container. I created a ManagerExecutorService and the SessionContext was then being properly propogated.</p>
<pre><code>@Resource(lookup = "java:jboss/ee/concurrency/executor/customExecutor")
private ManagedExecutorService es_;
</code></pre>
|
List all category and all posts in wordpress <p>how do can i list all category and all posts in wordpress, like the example below:</p>
<pre><code>CATEGORY1
POSTS
CATEGORY2
POSTS
CATEGORY3
POSTS
</code></pre>
| <p>Try below code :</p>
<pre><code> <?php // get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= $cat->term_id;
// Make a header for the cateogry
echo â<h2>â.$cat->name.â</h2>â;
// create a custom wordpress query
query_posts(âcat=$cat_id&post_per_page=100â³);
if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php // create our link now that the post is setup ?>
<a href=â<?php the_permalink();?>â><?php the_title(); ?></a>
<?php echo â<hr/>â; ?>
<?php endwhile; endif;
// done our wordpress loop. Will start again for each category ?>
<?php } // done the foreach statement ?>
</code></pre>
|
How to scale iOS app for different sizes <p>I'm writing an iOS app and I want app looks similar in iPhone 5 and iPhone 6 Plus.
I know about Auto Layouts, Adaptive Layout and Size Classes.
Is there any other way to scale view from iPhone 5 to larger screen sizes?</p>
<p>It is not so hard to write simple view container scaling for different screen sizes but... how to scale table cells, fonts in buttons, labels?</p>
<p>Thanks for help :)</p>
| <p>Have you heard about <a href="http://asyncdisplaykit.org" rel="nofollow">AsyncDisplayKit</a>? It has its own unique approach to the question of <a href="http://asyncdisplaykit.org/docs/layout2-conversion-guide.html" rel="nofollow">layouts</a>, sizes and etc. It also has its own implementation of tables, collections, labels... It took me not much time to replace UICollectionView in existing project with ASCollectionNode.</p>
<p>Hope this helps (:</p>
|
AJAX variable sending no data (variable returns "0" not required data) <p>I've been trying to use AJAX to send across a variable from a JS file and trigger a PHP file in Wordpress. The function connects to the PHP file however the variable it sends across stores the value "0" . I've tried many solutions, but I can't quite nail down this problem. The JS code is below:</p>
<pre><code>function data_transfer(){
alert(calc_price);
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
action: 'data_sender',
data:
({result: calc_price}),
dataType: 'json',
cache: false,
success:function(calc_price){
alert(calc_price);
},
error: function(jqXHR,textStatus,errorThrown, exception){
alert('error');
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
//alert(errorThrown);
//alert(textStatus);
}
});
}
</code></pre>
<p>The value <code>calc_price</code> is calculated prior in an if statement, but the value shown in the alert in the success function is "0".</p>
<p>The PHP and Wordpress hooks are show below:</p>
<pre><code>add_action('wp_ajax_datasender', 'datasender_callback');
add_action('wp_ajax_nopriv_datasender', 'datasender_callback');
function datasender_callback() {
alert("PHP function successful");
}
</code></pre>
<p>Any ideas on how to solve this problem would be great. Thanks in advance, Kate.</p>
| <p><code>alert</code> is JavaScript, try using <code>echo</code>, as in </p>
<pre><code>echo json_encode($_POST['result']);
</code></pre>
<p>also action needs to be part of your data parameter</p>
<pre><code> data:({result: calc_price, action: 'data_sender'}),
</code></pre>
|
Lookup "Text" Variable between dates <p><em>Let me preface this question with: The data that I was provided is not in the most logical order and the work involved in scrubbing to a more uniform it would be time consuming.</em></p>
<p>I am compiling a sales sheet to collect an overall yearly view of each product's revenue. I am currently attempting to search for the product name within the sheets required within a main sheet (all within the same workbook).</p>
<p><strong>See sample output below:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Year
2014 Jan Feb Mar ... Nov Dec
Product 1
Product 2
Product 3
2015 Jan Feb Mar ... Nov Dec
Product 1
Product 2
Product 3</code></pre>
</div>
</div>
</p>
<p><strong>Sample Input</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>... F ... N ... T ...
... Date ... Product ... Amount ...
------------------------------------------------------
10/03/15 ... Prod. 1 ... $1000.00 ...
04/05/15 ... Prod. 3 ... $3000.00 ...
02/09/15 ... Prod. 1 ... $2000.00 ...</code></pre>
</div>
</div>
</p>
<p>I would like to break it down based on month and product which is where I am running into issues. Currently I am (attempting) using: </p>
<pre><code>=SUMIFS('2015'!R:R,'2015'!F:F,"Product 1",">=1/1/2015",'2015'!F:F,"<=1/31/2015")
</code></pre>
<p>Any help provided would be greatly appreciated!</p>
| <p>SUMIFS() is the best way to go. But one can make the criteria more dynamic so the formula can be copied from cell to cell instead of having the values "hard coded" in the formula.</p>
<p>To do such ensure that your month row is Actual dates that have a number format of <code>mmm</code> instead of text.</p>
<p><a href="https://i.stack.imgur.com/vc1q8.png" rel="nofollow"><img src="https://i.stack.imgur.com/vc1q8.png" alt="enter image description here"></a></p>
<p>As you can see the <code>Jan</code> cell is actually <code>1/1/2015</code>. We could have made this a little more dynamic also. Instead of the year being hard coded, since I put the year in A2, I could have used this formula:</p>
<pre><code>=DATE($A$2,Column(A:A),1)
</code></pre>
<p>And drag/copied across. This would have put the first day of each month.</p>
<p>Again do a custom format of <code>mmm</code></p>
<p>Then the formula would be:</p>
<pre><code>=SUMIFS('2015'!$T:$T,'2015'!$N:$N,$A3,'2015'!$F:$F,">=" & EOMONTH(B$2,-1)+1,'2015'!$F:$F,"<=" & EOMONTH(B$2,0))
</code></pre>
<p>This formula then is dragged/copied across and down.</p>
<p><a href="https://i.stack.imgur.com/IV9ai.png" rel="nofollow"><img src="https://i.stack.imgur.com/IV9ai.png" alt="enter image description here"></a></p>
|
ngrok FTP tunneling issue <p>I have installed many FTP Servers on a Windows machine and set ngrok for FTP tunneling.</p>
<pre><code>C:\path\to\ngrok> ngrok tcp 21
</code></pre>
<p>Using linux, i am able to establish an FTP connection and browse the directories ONLY with the installed ftp client.</p>
<pre><code>$ ftp
ftp> open 0.tcp.ngrok.io port_here
</code></pre>
<p>The problem is that FileZilla, Classic FTP File Transfer Software, Chrome & Firefox extensions, failed.</p>
<p>FileZilla output: </p>
<pre><code>Command: LIST
Response: 150 Opening ASCII mode data connection
Error: Connection timed out after 20 seconds of inactivity
Error: Failed to retrieve directory listing
</code></pre>
<p>I wonder why i can't browse using FileZilla, but with the ftp Linux command works well.</p>
<p>Thank you.</p>
| <p>Problem solved in FileZilla via : </p>
<p>Edit > Settings > Connection > FTP > Passive mode, and select "Fall back to active mode" and Bingo !</p>
<p>The same technique can be applied to the other FTP clients.</p>
|
Oracle - query failed statements <p>Is there a view (or other method) in Oracle, from which I can extract the failed sql statements, which were executed by the user? I tried to check v$sql but, as it turned out, it contains only the successful ones. I'm using Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production.</p>
<p>Thank You.</p>
| <p>Blaim me if I'm wrong but as far as I understand sql gets logged on shared pool check and statements Laszlo mentioned <code>select nonexistingcolumn from dual;</code> failed on semantic check. My answer is you won't find invalid statements in DB.
<a href="https://docs.oracle.com/database/121/TGSQL/tgsql_sqlproc.htm#TGSQL178" rel="nofollow">https://docs.oracle.com/database/121/TGSQL/tgsql_sqlproc.htm#TGSQL178</a></p>
|
Limit displayed depth of gradle dependencies task <p>Using <code>gradle dependencies</code> I get a huge list of all dependencies. Showing all dependencies the projects I depend on have. Is it possible to limit the depth of the shown list?<br>
Example:</p>
<pre><code>+--- com.company.common:e-common-junit:0.29.0-SNAPSHOT
| +--- junit:junit:4.11 (*)
| \--- commons-io:commons-io:2.4
\--- org.slf4j:slf4j-log4j12:1.7.6
+--- org.slf4j:slf4j-api:1.7.6
\--- log4j:log4j:1.2.17
</code></pre>
<p>Limited to only <code>+--- com.company.common:e-common-junit:0.29.0-SNAPSHOT</code><br>
From the gradle site:</p>
<pre><code>dependencies - Displays all dependencies declared in root project 'projectReports'.
api:dependencies - Displays all dependencies declared in project ':api'.
webapp:dependencies - Displays all dependencies declared in project ':webapp'.
</code></pre>
<p>It even mentiones that these reports can get large at <a href="https://docs.gradle.org/current/userguide/tutorial_gradle_command_line.html#sec:listing_dependencies" rel="nofollow">this official source</a>.<br>
Stating that I should use <code>--configuration</code>, but as far as my understanding of this article goes it would only limit it to <code>compile</code>, <code>testCompile</code> and so on, not in depth.<br>
Version in use <code>gradle 2.11</code></p>
| <p>Use grep:</p>
<ul>
<li><p>Show only top level dependencies:<br>
<code>gradle dependencies --configuration compile | grep -v '| '</code></p></li>
<li><p>Show two levels:<br>
<code>gradle dependencies --configuration compile | grep -v '| | '</code></p></li>
</ul>
<p>etc</p>
|
Unity saving foreach? <p>I'm a bit new to unity please help me.</p>
<p>How can i save something like this?</p>
<pre><code>public float GetMoneyPerSec()
{
float tick = 0;
foreach (UpgradeManager item in items)
{
tick += item.tickValue;
}
return tick;
}
</code></pre>
| <p>To 'save' the data in a file you can serialize to a text document using either xml or JSON and deserialize it when the game runs. This is more convenient than player prefs as you can duplicate or edit the values in any text editor with ease. </p>
<p>To persist data between scenes just ensure the class that holds the data is a static class(use the singleton method) or on a class which is set to 'don't destroy on load'.</p>
|
PHP function file_exists not working when using .htaccess rewrite rule <p>I am using following in my .htaccess file</p>
<pre><code>RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^shopping-bag/?$ shoppingbag.php [L,QSA]
</code></pre>
<p>This changes the url</p>
<blockquote>
<p><a href="http://www.domain.com/foldername/shoppingbag.php" rel="nofollow">http://www.domain.com/foldername/shoppingbag.php</a></p>
</blockquote>
<p>to </p>
<blockquote>
<p>www.domain.com/foldername/shopping-bag/</p>
</blockquote>
<p>All my content is placed in </p>
<blockquote>
<p>/www/foldername/</p>
</blockquote>
<p>I fixed all the css and js files by declaring a global variable with value <code>http://www.domain.com/foldername/</code> and place this variable before the path of css and js files. Since file_exists won't work on a URL I tried doing the following</p>
<blockquote>
<p>../uploads/image.jpg</p>
</blockquote>
<p>The actual path of the image file is </p>
<blockquote>
<p>/www/foldername/uploads/image.jpg</p>
</blockquote>
<p>I tried doing</p>
<pre><code>var_dump(../uploads/image.jpg)
</code></pre>
<p>on </p>
<blockquote>
<p><a href="http://www.domain.com/foldername/shopping-bag/" rel="nofollow">http://www.domain.com/foldername/shopping-bag/</a></p>
</blockquote>
<p>but didn't work. And I don't want to use <code><base href=""></code></p>
| <p><code>foldername/shoppingbag.php</code> is the file you're running and <code>foldername/uploads/image.jpg</code> is the file it's interested in. The relative path should just be <code>uploads/image.jpg</code>.</p>
<p>What does this give?</p>
<pre><code>var_dump('uploads/image.jpg');
</code></pre>
|
How to modify a message in Log4J 2? <p>I'm trying to MODIFY, not DENY, certain messages before being logged using Log4J 2. I'm currently trying to use a <code>Filter</code>, but I can't seem to be able to modify a message from any of it's methods.
Please be patient with me as I'm totally new to Log4j.</p>
| <p>Log4j purposely does not let you modify the LogEvent as it might get passed on to other Filters and Appenders that expected the original event. However, the RewriteAppender will let you create a copy of the LogEvent that is modified and then pass that to a subordinate Appender. The RoutingAppender also supports a RewritePolicy that does the same thing.</p>
|
DataTable.ImportSheet operation failed.Invalid file <p>I'm running Excel tests on UFT and sometimes I get the error number 20012 which is "DataTable.ImportSheet operation failed.Invalid file".</p>
<p>This is my way of importing the script:</p>
<pre><code>DataTable.ImportSheet filepath,scriptname,"Action2"
</code></pre>
<ul>
<li><p>filepath is the path of my workbook which conatins many excel sheets (scripts)</p></li>
<li><p>scriptname: the name of the script that I want to run</p></li>
<li><p>Action2: contains all the call of all possible keywords that may script can contains.</p></li>
</ul>
<p>Any help please, why I'm getting this error.</p>
<p>The problem is that this is working well for some scripts and for others not after 3 or 4 run times.</p>
<p>I think the problem is on Excel itself and not on the code, are there any problems when working with Excel 2016 and UFT 12 ? </p>
| <p>UFT syntax for importing a worksheet is:</p>
<pre><code>DataTable.ImportSheet FileName, vtSrcSheet, vtDstSheet
</code></pre>
<p>This means you need to pass as parameters the filename (and path) to the excel file, the name (or index) of the source sheet you want to import, and then the destination you want this sheet to be (for example "Global" or "Action1" etc)</p>
<p>Unless <code>scriptname</code> happens to be the exact name of the worksheet you are trying to import you will get this error.</p>
<p>If you want to import the whole file use <code>Datatable.Import</code> instead of <code>Datatable.ImportSheet</code></p>
|
Is there an Umbraco plugin to give CRM-type capabilities? <p>In looking at the <a href="https://docs.kentico.com/display/K9/Organizing+contacts+into+accounts" rel="nofollow">Kentico documentation for account and contact management</a>, it seems to give us the ability to create a hierarchy for accounts, such as Account (Client) / Organizational Unit (store locations) / Contact (person at location).</p>
<p>I am looking for a way to accomplish this in Umbraco. We would also want to add multiple fields to the Contact, as they may exist in multiple organizational units.</p>
<p>Is it possible to accomplish this with Umbraco, and if so, how?</p>
| <p>There is a free and open-source (according to the latest update from the creator: <a href="https://twitter.com/theotron/status/784372313773006849" rel="nofollow">https://twitter.com/theotron/status/784372313773006849</a>) plugin called <strong>Pipeline CRM</strong>: <a href="https://www.pipelinecrm.co.uk" rel="nofollow">https://www.pipelinecrm.co.uk</a>. Source code and installation details are also available on Github: <a href="https://github.com/theotron/PipelineCRM" rel="nofollow">https://github.com/theotron/PipelineCRM</a>.</p>
<p>There's also <strong>uSightly</strong>, which integrates with Insightly:
<a href="https://our.umbraco.org/projects/collaboration/usightly/" rel="nofollow">https://our.umbraco.org/projects/collaboration/usightly/</a></p>
<p>I've not used either personally, so I don't know if they would meet your requirements. You can also integrate with other CRM systems yourself if you wish, I know of developers who've integrated with CRMs like Salesforce and Dynamics from Umbraco.</p>
<p>Hope that helps!</p>
|
r grep with or statment <p>I've been working on a r function to filter a large data frame of baseball team batting stats by game id, (i.e."2016/10/11/chnmlb-sfnmlb-1"), to create a list of past team matchups by season.</p>
<p>When I use some combinations of teams, output is correct, but others are not. (output contains a variety of ids) </p>
<p>I'm not real familiar with grep, and assume that is the problem. I patched my grep line and list output together by searching stack overflow and thought I had it till testing proved otherwise.</p>
<pre><code>matchup.func <- function (home, away, df) {
matchups <- grep(paste('[0-9]{4}/[0-9]{2}/[0-9]{2}/[', home, '|', away, 'mlb]{6}-[', away, '|', home, 'mlb]{6}-[0-9]{1}', sep = ''), df$game.id, value = TRUE)
df <- df[df$game.id %in% matchups, c(1, 3:ncol(df))]
out <- list()
for (n in 1:length(unique(df$season))) {
for (s in unique(df$season)[n]) {
out[[s]] <- subset(df, season == s)
}
}
return(out)
}
</code></pre>
<p>sample of data frame:</p>
<pre><code>bat.stats[sample(nrow(bat.stats), 3), ]
date game.id team wins losses flag ab r h d t hr rbi bb po da so lob avg obp slg ops roi season
1192 2016-04-11 2016/04/11/texmlb-seamlb-1 sea 2 5 away 38 7 14 3 0 0 7 2 27 8 11 15 0.226 0.303 0.336 0.639 0.286 R
764 2016-03-26 2016/03/26/wasmlb-slnmlb-1 sln 8 12 away 38 7 9 2 1 1 5 2 27 8 11 19 0.289 0.354 0.474 0.828 0.400 S
5705 2016-09-26 2016/09/26/oakmlb-anamlb-1 oak 67 89 home 29 2 6 1 0 1 2 2 27 13 4 12 0.260 0.322 0.404 0.726 0.429 R
</code></pre>
<p>sample of errant output:</p>
<pre><code>matchup.func('tex', 'sea', bat.stats)
$S
date team wins losses flag ab r h d t hr rbi bb po da so lob avg obp slg ops roi season
21 2016-03-02 atl 1 0 home 32 4 7 0 0 2 3 2 27 19 2 11 0.203 0.222 0.406 0.628 1.000 S
22 2016-03-02 bal 0 1 away 40 11 14 3 2 2 11 10 27 13 4 28 0.316 0.415 0.532 0.947 0.000 S
47 2016-03-03 bal 0 2 home 41 10 17 7 0 2 10 0 27 9 3 13 0.329 0.354 0.519 0.873 0.000 S
48 2016-03-03 tba 1 1 away 33 3 5 0 1 0 3 2 24 10 8 13 0.186 0.213 0.343 0.556 0.500 S
141 2016-03-05 tba 2 2 home 35 6 6 2 0 0 5 3 27 11 5 15 0.199 0.266 0.318 0.584 0.500 S
142 2016-03-05 bal 0 5 away 41 10 17 5 1 0 10 4 27 9 10 13 0.331 0.371 0.497 0.868 0.000 S
</code></pre>
<p>sample of good:</p>
<pre><code>matchup.func('bos', 'bal', bat.stats)
$S
date team wins losses flag ab r h d t hr rbi bb po da so lob avg obp slg ops roi season
143 2016-03-06 bal 0 6 home 34 8 14 4 0 0 8 5 27 5 8 22 0.284 0.330 0.420 0.750 0.000 S
144 2016-03-06 bos 3 2 away 38 7 10 3 0 0 7 7 24 7 13 25 0.209 0.285 0.322 0.607 0.600 S
209 2016-03-08 bos 4 3 home 37 1 12 1 1 0 1 4 27 15 8 26 0.222 0.292 0.320 0.612 0.571 S
210 2016-03-08 bal 0 8 away 36 5 12 5 0 1 4 4 27 9 4 27 0.283 0.345 0.429 0.774 0.000 S
</code></pre>
<p>On the good it gives a list of matchups as it should, (i.e. S, R, F, D), on the bad it outputs by season, but seems to only give matchups by date and not team. Not sure what to think. </p>
| <p>I think that the issue is that regex inside <code>[]</code> behaves differently than you might expect. Specifically, it is looking for <em>any</em> matches to those characters, and in any order. Instead, you might try</p>
<pre><code>matchups <- grep(paste0("(", home, "|", away, ")mlb-(", home, "|", away, ")mlb")
, df$game.id, value = TRUE)
</code></pre>
<p>That should give you either the home or the away team, followed by either the home or away team. Without more sample data though, I am not sure if this will catch edge cases.</p>
<p>You should also note that you don't have to match the entire string, so the date-finding regex at the beginning is likely superfluous.</p>
|
Find item in array using weighed probability and a value <p>Last week I had some problems with a simple program I am doing and somebody here helped me. Now I have run into another problem.
I currently have this code:</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 findItem = function(desiredItem) {
var items = [
{ item: "rusty nail", probability: 0.25 },
{ item: "stone", probability: 0.23 },
{ item: "banana", probability: 0.20 },
{ item: "leaf", probability: 0.17 },
{ item: "mushroom", probability: 0.10 },
{ item: "diamond", probability: 0.05 }
];
var possible = items.some( ({item, probability}) =>
item === desiredItem && probability > 0 );
if (!possible) {
console.log('There is no chance you\'ll ever find a ' + desiredItem);
return;
}
var sum = items.reduce( (sum, {item, probability}) => sum+probability, 0 );
while (true) {
var value = Math.random() * sum;
var lootedItem = items.find(
({item, probability}) => (value -= probability) <= 0 ).item;
if (lootedItem === 'diamond') break;
console.log("Dang! A " + lootedItem + " was found...");
}
console.log("Lucky! A " + desiredItem + " was found!");
}
findItem('diamond');</code></pre>
</div>
</div>
</p>
<p>Now I would like to expand on this by adding another value called <code>category</code> to the <code>items</code> array. I want the categories to have a value of either <code>2</code>, <code>5</code> or <code>10</code>. So let's say the <code>diamond</code> item would belong to <code>category: 10</code>, and when <code>findItem</code> is executed only items that belong to the same category can be found. I have been trying for a couple of days now but can't seem to get my head around it. Maybe someone can help push me in the right direction? Thanks in advance</p>
| <p>You could use this update to that code:</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>// Pass the item list and the desired category as arguments:
var findItem = function(items, category, desiredItem) {
// apply filter to items, so only those of the given category remain:
items = items.filter( item => item.category == category );
// rest of code remains the same:
var possible = items.some( ({item, probability}) =>
item === desiredItem && probability > 0 );
if (!possible) {
console.log('There is no chance you\'ll ever find a ' + desiredItem);
return;
}
var sum = items.reduce( (sum, {item, probability}) => sum+probability, 0 );
var t = 10;
while (true) {
var value = Math.random() * sum;
var lootedItem = items.find(
({item, probability}) => (value -= probability) <= 0 ).item;
if (lootedItem === desiredItem) break; // fixed this condition!
console.log("Dang! A " + lootedItem + " was found...");
t--; if (t <= 0) throw "loop";
}
console.log("Lucky! A " + desiredItem + " was found!");
}
// Define items here with their category
var items = [
{ item: "rusty nail", probability: 0.25, category: 2 },
{ item: "stone", probability: 0.23, category: 2 },
{ item: "banana", probability: 0.20, category: 2 },
{ item: "leaf", probability: 0.17, category: 5 },
{ item: "mushroom", probability: 0.10, category: 5 },
{ item: "diamond", probability: 0.05, category: 10 }
];
// Call function with extra arguments:
findItem(items, 5, 'mushroom');
console.log('second run:');
// This will obviously give a hit immediately, as there is only one possible item:
findItem(items, 10, 'diamond');</code></pre>
</div>
</div>
</p>
<p>The changes are:</p>
<ul>
<li>Pass more arguments to your function: the items list and the desired category</li>
<li>Apply a filter on the items list as first action in the function</li>
<li>Fix an issue concerning the <code>lootedItem</code> test -- it had "diamond" hard-coded.</li>
<li>Define the items list outside of the function and add category values to each element.</li>
<li>Adapt the call of the function to pass the extra arguments.</li>
</ul>
|
Define file name via macro <p>I have the following piece of code to save a pdf file from an existing excel file.</p>
<pre><code>Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = ThisWorkbook.FullName
If FSO.FileExists(s(0)) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF,_
_ Filename:=sNewFilePath, Quality:=xlQualityStandard,_
_ IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
</code></pre>
<p>Since the code has to be run recursively, I'd would like add to the file name the week number, contained in a given cell (B2) in the sheet.</p>
<p>I tried replacing</p>
<pre><code>s(0) = ThisWorkbook.FullName & Cells(2,2)
</code></pre>
<p>but it is not working. Where is the error?</p>
| <p><code>FullName</code> property returns the full path & filename & extension. Appending <code>Cells(2,2)</code> to that will give you a value like <code>"c:\path\to\filename.xlsx" & Cells(2,2).Value</code>.</p>
<p>You need to insert the week number (<code>Cells(2,2)</code>) <em>before</em> the file extension part.</p>
<p>You can probably do that like so:</p>
<pre><code>sNewFilePath = Replace(s(0), s(1), Cells(2,2).Value & ".pdf")
</code></pre>
<p>Or, without using FileSystemObject:</p>
<pre><code>Dim fullName As String, weekNum As String
Dim sNewFilePath As String
weekNum = Cells(2,2).Value
fullName = ThisWorkbook.FullName
'If the file exists, the `Dir` function will return the filename, len != 0
If Len(Dir(fullName)) <> 0 Then
'remove the extension using Mid/InstrRev functions, _
build the new filename with weeknumber & pdf extension
sNewFilePath = Mid(fullName, 1, InstrRev(fullName,".")-1) & weekNum & ".pdf"
'Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF,_
_ Filename:=sNewFilePath, Quality:=xlQualityStandard,_
_ IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
</code></pre>
|
How to highlight function in all project with Eclipse (C/C++) by default? <p>This is the use case:
You have a project where specific function is being called all over the files, you don't care about it but visually sometimes is annoying. Is there a way to highlight occurrence of this specific function by default in the project? </p>
<p>I tried looking at eclipse preferences, TextEditor>Syntax Coloring. You can change colors of functions, enums, variables, etc. but not specific function. Mark Occurrences also not good for this use-case since no matter what you search for, I would like to see this function with diff color. </p>
<p>Example: </p>
<pre><code>careless_func_check(arg1, arg2, arg2);
MyImportantFunction1(arg1);
careless_func_check(arg1, arg2, arg2);
careless_func_check(arg1, arg2, arg2);
MyImportantFunction2(arg1);
careless_func_check(arg1, arg2, arg2);
careless_func_check(arg1, arg2, arg2);
MoreNiceFunctions___1(arg1);
careless_func_check(arg1, arg2, arg2);
careless_func_check(arg1, arg2, arg2);
MyImportantFunction__2(arg1);
careless_func_check(arg1, arg2, arg2);
</code></pre>
<p>When certain code is not compiling, the code will be highlighted to different color (e.g. pink) to facilitate you distinguish it. I would like to process the function above: "careless_func_check" to be highlighted with other color, so for me would be easier to look at the code (careless_func_check is used in the code, just not important to me).</p>
<p>Any idea if it is possible?? I know is an specific nice-to-have option but wanted to try here to see if someone knows.</p>
| <p>Check these two ways:</p>
<h3>File wide</h3>
<p>Change the mark occurrences annotations background color/Text preferences as shown below.</p>
<p><a href="https://i.stack.imgur.com/thHy9.png" rel="nofollow"><img src="https://i.stack.imgur.com/thHy9.png" alt="enter image description here"></a></p>
<p>But it applies to every occurrences ex; variable, functions etc not limited to your own function.</p>
<h3>Project/workspace wide(Changing search results annotations background color)</h3>
<p>Change the Search result occurrences annotations background color/Text preferences[Refer above image].</p>
<p>Then search your function <code>careless_func_check</code> in C/C++ search dialog(<code>Search > C/C++</code>). Remember search result will be highlighted till next search or manual removal of search results in Search view.</p>
<p><a href="https://i.stack.imgur.com/9RQcE.png" rel="nofollow"><img src="https://i.stack.imgur.com/9RQcE.png" alt="enter image description here"></a></p>
|
Difference between constant time and effective constant time complexity <p>I understand "constant time complexity O(1)" , but when i came across the the term effective constant time complexity , i am very much confused . I got below sentence from Scala cook book about effective constant time . </p>
<blockquote>
<p>The operation takes effectively constant time, but this might depend
on some assumptions, such as maximum length of a vector, or
distribution of hash keys.</p>
</blockquote>
<p>But what i believe is above examples are not effective constant time , rather Amortize constant time .</p>
<p>Will you please give a clear difference between constant time and effective constant time . This will be very helpful .Thanks!!</p>
| <p>It means pretty much exactly what the quote says: it is not constant time, but, under some reasonable assumptions, it is only marginally worse than constant time, not enough to be noticeable.</p>
<p>So, it's not constant time, but it's so close that the difference doesn't matter, which effectively makes it (almost) constant time,</p>
<p>For example, implementing an array data structure as a 32-way tree technically makes it O(log n) instead of O(1). But an array with 4 billion entries will only be 6.4 levels deep, so it's basically less than 7 times slower than a traditional mutable contiguous array.</p>
|
disjunctive syllogism in prolog <p>I am using swi-prolog. I want to model following statements in program.
<em>"Either a or b is criminal. b is not criminal."</em> </p>
<p>After modeling these statements. following query should work.</p>
<pre><code>?-c(X).
X=a.
</code></pre>
<p>But,
when I wrote above statements in prolog:</p>
<pre><code>c(a);c(b).
not(c(b)).
</code></pre>
<p>this code does not compile and shows error:</p>
<pre><code>No permission to modify static procedure `(;)/2'
</code></pre>
<p>How to model above two statements in prolog?</p>
| <p>afaik Prolog does not work this way. It tries to match your expression with all statements. So if you want to model "a is a criminal and b is not", then you can write</p>
<pre><code>criminal(a).
not(criminal(b)).
</code></pre>
<p>but you can't say criminal(b) and in the next line not(criminal(b)), because this would lead to a contradiction.</p>
<p>the second line of my code ('not(criminal(b))') is actually redundant, because if Prolog doesn't find any matches of your term it will result in false, and backtrack for another solution. This means that you can simply omit all facts of not-criminals in this case.</p>
<p>you can then just ask Prolog which atoms it knows as criminals:</p>
<pre><code>criminal(X).
</code></pre>
<p>and it will clearly tell you that</p>
<blockquote>
<p>X=a.</p>
</blockquote>
<p>whereas b is not part of the solution.</p>
|
Linq "Object reference not set to an instance of an object." <p>Am a little lost on this one. Getting the error <code>Object reference not set to an instance of an object.</code> on the line <code>db.EntityRichContents.DeleteAllOnSubmit(q);</code> at runtime. Project builds fine.</p>
<pre><code>protected override void ControllerOnEntityDeleted(EntityObj forEntity, EntityDeletionController.DeletionAction newStatus)
{
if (newStatus == EntityDeletionController.DeletionAction.HardDelete)
{
if(forEntity == null) throw new Exception();
using (var db = new DBContext())
{
var q = db.EntityRichContents.Where(c => c.C3Entity == ForEntity.TypeID && c.C3EntityRecordID == ForEntity.ID);
db.EntityRichContents.DeleteAllOnSubmit(q);
db.SubmitChanges();
}
}
}
</code></pre>
<p>Checking <code>q.Any()</code> or <code>q == null</code> doesn't help in any way (q isn't null).</p>
| <p>I see there are two similar variables: one is <strong>ForEntity</strong> (possibly a class property property?) and the second being <strong>forEntity</strong> (method parameter). Is that a typo?</p>
<p>Either way, given that the <em>Where</em> method is enumerated lazily I would assume that one of the lambda parameters in
<code>(c => c.C3Entity == ForEntity.TypeID && c.C3EntityRecordID == ForEntity.ID)</code>
is null. Try adding null-checks for every parameter and/or property to avoid exceptions.</p>
|
When Using Youtube Embed Code with start end and rel=0 attributes video goes back to zero when it ends not start offset <p>Here is my embed code with responsive wrapper:</p>
<pre><code><div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;"><iframe style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" src="https://www.youtube.com/embed/G64faDylbgc?feature=oembed&start=605&end=11704&rel=0" frameborder="5px" allowfullscreen="allowfullscreen"></iframe></div>
</code></pre>
<p>The video starts at the correct time and ends at the correct time however when it reaches the end it goes back to the beginning at time=0 instead of going back to time=start. I do not have access to javascript nor will I ever.
Is this behavior by design or is it a bug? What am I missing?</p>
| <p>Yes this behaviour is by design.</p>
<p>And to my knowledge, you cannot override the replay button, so the easiest thing is probably to add a line of text saying when it starts.</p>
|
How to render parent data of nested object via Active model serializers for Rails? <p>I am working on Rails 5 api only app.</p>
<p>So this is my model serializer</p>
<pre><code>class MovieSerializer < ActiveModel::Serializer
attributes :id ,:name,:release_year,:story,:in_theater,:poster,:score,:user_count
belongs_to :age_rating
belongs_to :company
has_many :categories
has_many :movie_celebrities
end
class MovieCelebritySerializer < ActiveModel::Serializer
attributes :id,:vacancy,:title
belongs_to :celebrity
end
class CelebritySerializer < ActiveModel::Serializer
attributes :id, :first_name, :last_name
has_many :movie_celebrities
end
</code></pre>
<p>My controller</p>
<pre><code>class Api::V1::MoviesController < ApplicationController
# GET /v1/movies/:id
def show
movie = Movie.find_by(id: params[:id])
render json: movie
end
end
</code></pre>
<p>So this is what i got</p>
<pre><code>{
"id": 1,
"name": "0 The Doors of Perception",
"release_year": 2007,
"story": "Non doloribus qui et eum impedit. Rerum mollitia debitis sit nesciunt. Vero autem quae sit aliquid rerum ex fugit. Eligendi assumenda et eos. Blanditiis hic ut. Commodi quo sunt voluptatem quasi.",
"in_theater": false,
"poster": "'http://cdn.mos.cms.futurecdn.net/15399e7a7b11a8c2ef28511107c90c6f.jpg',",
"score": 0,
"user_count": 6950,
"age_rating": {
"id": 2,
"name": "PG"
},
"company": {
"id": 5,
"name": "Gislason, Jacobs and Graham"
},
"categories": [
{
"id": 4,
"name": "Biography"
},
{
"id": 16,
"name": "Mystery"
}
],
"movie_celebrities": [
{
"id": 1,
"vacancy": "director",
"title": ""
},
{
"id": 2,
"vacancy": "cast",
"title": "Pro x"
},
{
"id": 3,
"vacancy": "cast",
"title": "Magneto"
}
]
}
</code></pre>
<p>By the problem is i need a celebrity data inside each <code>movie_celebrities</code> object like this.</p>
<pre><code>[
{
"id": 1,
"vacancy": "director",
"title": "",
"celebrity": {
"id": 17,
"first_name": "Jannie",
"last_name": "Stiedemann"
}
},
{
"id": 2,
"vacancy": "cast",
"title": "Pro x",
"celebrity": {
"id": 56,
"first_name": "Diego",
"last_name": "Hickle"
}
},
{
"id": 3,
"vacancy": "cast",
"title": "Magneto",
"celebrity": {
"id": 23,
"first_name": "Myrtie",
"last_name": "Lebsack"
}
}
]
</code></pre>
<p>So how can i make this situation working?
Thanks!</p>
| <p>You should add <code>ActiveModelSerializers.config.default_includes = '**'</code> to <code>config/initializers/active_model_serializers.rb</code>. See documentation <a href="https://github.com/rails-api/active_model_serializers/blob/master/docs/general/configuration_options.md#default_includes" rel="nofollow">here</a>. Or <a href="https://github.com/rails-api/active_model_serializers/blob/master/docs/general/adapters.md#included" rel="nofollow">set</a> <code>included</code> for render right way in case you prefer more granular control.</p>
|
Composite bitmaps with transparency <p>I have 2 bitmaps which I wish to overlay one on the other but using <code>Graphics</code> or <code>Magick.net</code> does not give the desired effect.</p>
<p>Graphics gave the closest effect and fastest but the transparency seems to mess up.</p>
<pre><code>using (Graphics gfcs = Graphics.FromImage(spiral))
{
Point placement = new Point(19,19);
gfcs.DrawImage(astronaut, placement);
}
</code></pre>
<p>I want to combine:<br>
<a href="https://i.stack.imgur.com/JMQMB.png" rel="nofollow"><img src="https://i.stack.imgur.com/JMQMB.png" alt="Yellow BG Spiral"></a> & <a href="https://i.stack.imgur.com/tHUSZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/tHUSZ.png" alt="Astronaut"></a></p>
<p>To create:<br>
<a href="https://i.stack.imgur.com/3OEci.png" rel="nofollow"><img src="https://i.stack.imgur.com/3OEci.png" alt="enter image description here"></a></p>
<p>But I get:<br>
<a href="https://i.stack.imgur.com/7sr9T.png" rel="nofollow"><img src="https://i.stack.imgur.com/7sr9T.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/H4txp.png" rel="nofollow"><img src="https://i.stack.imgur.com/H4txp.png" alt="enter image description here"></a><br>
Graphics | Magick.net</p>
<p>Surrounding source:</p>
<pre><code> public static void generateGIF()
{
int smileyID = 71;
int goldBorder = 1;
List<Bitmap> images = new List<Bitmap>();
Bitmap aura = new Bitmap(Image.FromFile("1511_Player_Aura.png"));
Bitmap smilies = new Bitmap(Image.FromFile("1559_items.ItemManager_smiliesBM.png"));
Bitmap smiley = new Bitmap(26, 26);
for (int y = 0; y < 26; y++)
{
for (int x = 0; x < 26; x++)
{
smiley.SetPixel(x, y, smilies.GetPixel(smileyID * 26 + x, goldBorder * 26 + y));
}
}
int i = 0;
for (int j = 9; j < 15; j++)
{
Bitmap tmp = new Bitmap(64, 64);
for (int y = 0; y < 64; y++)
{
for (int x = 0; x < 64; x++)
{
tmp.SetPixel(x * zoom, y * zoom, aura.GetPixel(i * 64 + x, j * 64 + y));
using (Graphics gfcs = Graphics.FromImage(tmp)) //this ---v
{
smiley.PixelFormat = PixelFormat.
Point placement = new Point(19, 19);
gfcs.DrawImage(smiley, placement);
}
}
}
// ^--- should be here
images.Add(tmp);
tmp.Save($"{j}.png");
}
//GIF stuff
}
</code></pre>
| <p>I was writing the astronaut to the image 4096 times which looked like transparency was messing up.</p>
<pre><code> public static void generateGIF()
{
int zoom = 1;
int smileyID = 71;
int goldBorder = 1;
Console.WriteLine("Starting");
List<Bitmap> images = new List<Bitmap>();
Bitmap aura = new Bitmap(Image.FromFile("1511_Player_Aura.png"));
Bitmap smilies = new Bitmap(Image.FromFile("1559_items.ItemManager_smiliesBM.png"));
Bitmap smiley = new Bitmap(26, 26);
using (Graphics gfcs = Graphics.FromImage(smiley))
{
Point placement = new Point(smileyID * -26, goldBorder * -26);
gfcs.DrawImage(smilies, placement);
}
int i = 0;
for (int j = 9; j < 15; j++)
{
Bitmap tmp = new Bitmap(64, 64);
using (Graphics gfcs = Graphics.FromImage(tmp))
{
Point placement = new Point(i * -64, j * -64);
gfcs.DrawImage(aura, placement);
}
using (Graphics gfcs = Graphics.FromImage(tmp))
{
Point placement = new Point(19, 19);
gfcs.DrawImage(smiley, placement);
}
images.Add(tmp);
}
//GIF stuff
}
</code></pre>
|
Set Toggle switch based on condition on page load <p>Here is my code - </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function () {
$(document).ready(function () {
$('.switch-input').on('change', function () {
var isChecked = $(this).is(':checked');
var selectedData;
var $switchLabel = $('.switch-label');
if (isChecked) {
selectedData = $switchLabel.attr('data-on');
} else {
selectedData = $switchLabel.attr('data-off');
}
if (selectedData === 'ACTIVE') {
selectedData = 'A';
} else {
selectedData = 'C';
}
$('#h-status').val(selectedData);
$('#form_filterBillItems').submit();
});
});
})();</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>
<label class="switch">
<input class="switch-input" type="checkbox"/>
<span id ="tglInp" class="switch-label" data-on="CANCEL" data-off="ACTIVE"></span> <span class="switch-handle"></span>
</label></code></pre>
</div>
</div>
</p>
<p>I have this toggle switch that displays a filtered list based on the switch value : 'ACTIVE' or 'CANCEL'</p>
<p>This is on a Razor view. The grid that displays the list is in a partial view. But the toggle switch is on the full view. </p>
<p>The issue is when I return to this view, the grid is filtered based on the condition but the switch goes back to its default state. For example, if I go to the next view from Toggle switch state Cancel, when I return it should be still on Cancel but the toggle switch is on Active. </p>
<p>How do I do that. Any help would be highly appreciated! This is my first question, so if I made any mistakes, in posting, I apologize.</p>
<p>Thank you!</p>
| <p>I added another javascript function to check for the toggle switch value and change it based on the condition. </p>
<p>Here is my updated code - </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>$(document).ready(function () {
var data = @Html.Raw(Json.Encode(ViewData["bi_status"]));
if (data==='A'){ data = 'ACTIVE'; } else{ data = 'CANCEL'; }
$('.switch-input').on('change', function () {...});
});
})();
function setSwitch(args) {
var $switchLabel = $('.switch-label');
var $switchInput = document.getElementById('tglInp');
var dataOn = $switchLabel.attr('data-on');
var dataOff = $switchLabel.attr('data-off');
if (args === 'CANCEL') {
$switchInput.checked = true;
$switchLabel.attr('data-on', dataOn);
} else {
$switchInput.checked = false;
$switchLabel.attr('data-off', dataOff);
}
}</code></pre>
</div>
</div>
</p>
<p>-- For anyone looking for an answer to a similar issue. Cheers!</p>
|
undefined reference error when trying to implement abstract class <p>I have an abstract class that is meant to be an interface:</p>
<pre><code>//hpp
#ifndef IMOVABLE_HPP_INCLUDED
#define IMOVABLE_HPP_INCLUDED
#include "StaticMovementPath.hpp"
class IMovable{
protected:
StaticMovementPath *staticMovementPath;
public:
IMovable();
virtual setStaticMovementPath(StaticMovementPath *staticmovementPath) = 0;
};
#endif // IMOVABLE_HPP_INCLUDED
//cpp
#include "IMovable.hpp"
#include "StaticMovementPath.hpp"
IMovable::IMovable()
{
staticMovementPath = new StaticMovementPath();
}
//hpp
#ifndef STATICMOVEMENTPATH_HPP_INCLUDED
#define STATICMOVEMENTPATH_HPP_INCLUDED
class StaticMovementPath{
public:
StaticMovementPath();
};
#endif // STATICMOVEMENTPATH_HPP_INCLUDED
//cpp
#include "StaticMovementPath.hpp"
StaticMovementPath::StaticMovementPath(){
};
//hpp
#ifndef CAMERA_HPP
#define CAMERA_HPP
#include "IMovable.hpp"
class Camera: public IMovable{
public:
Camera();
};
#endif // CAMERA_HPP
//cpp
#include "Camera.hpp"
#include "IMovable.cpp"
Camera::Camera() : IMovable(){
}
</code></pre>
<p>Compiling this will throw:</p>
<pre><code>||=== Build: Debug in mapEditor (compiler: GNU GCC Compiler) ===|
obj\Debug\src\Camera.o||In function `ZN8IMovableC2Ev':|
...\src\IMovable.cpp|8|undefined reference to `StaticMovementPath::StaticMovementPath()'|
||error: ld returned 1 exit status|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
</code></pre>
<p>If I don't define constructors (so the default ones are called), I get no error. However, I get the same error with constructors that have one or more parameters.</p>
<p>How do I make this work?</p>
<p>I know most of the code seems pointless, but I stripped it down as much as I could. The same error was thrown with the (more) complete code.</p>
| <p>The StaticMovementPath.cpp wasn't targeted for debug nor release, so it wasn't compiling at all.</p>
|
Overflow Error in Excel VBA with Type Double <p>I have run into an overflow error in Excel VBA and cannot find my way around it. While Microsoft's documentation indicates that the range for doubles should reach ~1.8E308, I am receiving an overflow error for numbers significantly lower than that threshold. My code is as follows:</p>
<pre><code>Public Function Fixed_Sample_Nums(ByVal n As Long, seed As Long) As Double()
Dim x() As Double, y() As Double, i As Long
ReDim y(1 To n)
ReDim x(1 To n)
x(1) = (CDbl(48271) * seed) Mod CDbl(2 ^ 31 - 1)
For i = 2 To n
x(i) = (CDbl(48271) * CDbl(x(i - 1))) Mod (CDbl(2 ^ 31 - 1))
y(i) = CDbl(x(i)) / CDbl(2 ^ 31 - 1)
Next i
Fixed_Sample_Nums = y
End Function
'I receive the error in the first iteration of the for loop with
'seed equal to any value >= 1 (i.e. w/ seed = 1):
Debug.Print((CDbl(48271) * CDbl(48271)) Mod (CDbl(2 ^ 31 - 1)))
'results in an overflow error
</code></pre>
<p>I am attempting to create a pseudo-random number generator that can take in any 'seed' value up to and including 2 ^ 31 - 1. The for loop should be able to iterate at least 9,999 times (i.e. n = 10000). If the overflow error is not encountered within the first few iterations, it most likely will not be encountered for any subsequent iteration. </p>
<p>As you can see, I am converting each integer to a double before any calculation. I am aware of the fact that arrays substantially increase the byte size of the calculation, but that does not appear to be the current issue as I directly copied the example calculation above into the immediate window and still received the overflow error. My attempts to find a solution online have resulted in no avail, so I would really appreciate any input. Thanks in advance!</p>
| <p>Try using Chip Pearson's <code>XMod</code> function:</p>
<pre><code>x(i) = XMod((CDbl(48271) * seed), CDbl(2 ^ 31 - 1))
</code></pre>
<p>As he notes:</p>
<blockquote>
<p>You can also get overflow errors in VBA using the Mod operator with
very large numbers. For example,</p>
<pre><code>Dim Number As Double
Dim Divisor As Double
Dim Result As Double
Number = 2 ^ 31
Divisor = 7
Result = Number Mod Divisor ' Overflow error here.
</code></pre>
</blockquote>
<p>Code for the function:</p>
<pre><code>Function XMod(ByVal Number As Double, ByVal Divisor As Double) As Double
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' XMod
' Performs the same function as Mod but will not overflow
' with very large numbers. Both Mod and integer division ( \ )
' will overflow with very large numbers. XMod will not.
' Existing code like:
' Result = Number Mod Divisor
' should be changed to:
' Result = XMod(Number, Divisor)
' Input values that are not integers are truncated to integers. Negative
' numbers are converted to postive numbers.
' This can be used in VBA code and can be called directly from
' a worksheet cell.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Number = Int(Abs(Number))
Divisor = Int(Abs(Divisor))
XMod = Number - (Int(Number / Divisor) * Divisor)
End Function
</code></pre>
<p>Additional details:</p>
<p><a href="http://www.cpearson.com/excel/ModFunction.aspx" rel="nofollow">http://www.cpearson.com/excel/ModFunction.aspx</a></p>
|
Remove newline characters that appear between curly brackets <p>I'm currently writing a text processing script which contains static text and variable values (surrounded by curly brackets). I need to be able to strip out newline characters but only if they appear between the curly brackets:</p>
<p><code>Some text\nwith a {variable\n} value"</code></p>
<p>to:</p>
<p><code>Some text\nwith a {variable} value"</code></p>
<p>Further down in the processing I'm already doing this:</p>
<p><code>re.sub(r'\{.*?\}', '(.*)', text, flags=re.MULTILINE|re.DOTALL)</code></p>
<p>But I'm not sure how to target just the newline character and not the entirely of the curly bracket pair. There is also the possibility of multiple newlines:</p>
<p><code>Some text\nwith a {variable\n\n\n} value"</code></p>
<hr>
<p>Using Python 3.x</p>
| <p>You may pass the match object to a lambda in a <code>re.sub</code> and replace all newlines inside <code>{...}</code>:</p>
<pre><code>import re
text = 'Some text\nwith a {variable\n} value"'
print(re.sub(r'{.*?}', lambda m: m.group().replace("\n", ""), text, flags=re.DOTALL))
</code></pre>
<p>See <a href="http://ideone.com/ElV2ph" rel="nofollow">online Python 3 demo</a></p>
<p>Note that you do not need <code>re.MULTILINE</code> flag with this regex as it has no <code>^</code>/<code>$</code> anchors to redefine the behavior of, and you do not need to escape <code>{</code> and <code>}</code> in the current expression (without excessive backslashes, regexps look cleaner).</p>
|
Not sure how to print this? <p>I'm supposed to modify code that I've written for an assignment: </p>
<pre><code>public class ToweringStrings2 {
public static final int H = 2; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print("+");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("@");
}
System.out.println();
}
}
</code></pre>
<p>so that it prints sequential numbers starting at 1, instead of +s. Currently, it prints:</p>
<p><img src="https://i.stack.imgur.com/7ylSh.png" alt=""></p>
<p>This is what the new code is supposed to print:
<img src="https://i.stack.imgur.com/Etumv.png" alt=""></p>
<p>and so on. </p>
<p>For some reason I'm just really stuck and can't figure it out.</p>
| <p>You can create an extra variable to print and increment</p>
<p>Like that:</p>
<pre><code>public class ToweringStrings2 {
public static final int H = 10; //constant for the tower
public static void main(String[] args) {
drawTowers(H);
}
public static void drawTowers(int H) {
int count = 1;
for (int i = 1; i <= H; i++) {
System.out.print(" ");
for (int j = 1; j <= i; j++) {
System.out.print(count++ + " ");
}
System.out.println();
}
for (int k = 1; k <= H + 2; k++) {
System.out.print("@ ");
}
System.out.println();
}
}
</code></pre>
|
redux-form Migration to v6 throwing error in getValues.js <p>I'm attempting to use v6 of redux-form but running into some pretty undescriptive errors. The setup is straight forward, the reducer verbatim from the site:</p>
<pre><code>import { combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form';
export default combineReducers({
form: formReducer,
});
</code></pre>
<p>Then, I create a straight forward component without any fields (I get the exact same error when I have fields too).</p>
<pre><code>import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
class LoginForm extends Component {
render() {
const { handleSubmit, pristine, reset, submitting } = this.props;
return (
<div>
Form
</div>
);
}
}
export default reduxForm({
form: 'login' // a unique name for this form
})(LoginForm);
</code></pre>
<p>When I navigate to my component, I get this error:</p>
<pre><code>Uncaught TypeError: Cannot read property 'reduce' of undefined
</code></pre>
<p>The error is pointing to redux-form's getValues.js, and specifically this area of the code:</p>
<pre><code>var getValues = function getValues(fields, state) {
return fields.reduce(function (accumulator, field) {
getValue(field, state, accumulator);
return accumulator;
}, {});
};
</code></pre>
<p>One idea came from the very bottom of redux-form's <a href="http://redux-form.com/6.1.0/docs/MigrationGuide.md/" rel="nofollow">v6 migration page</a> about upgrading react-hot-loader, so I upgraded to 3.X but that didn't work. </p>
| <p>You are using <code>v6</code> syntax but the version in your <code>node_modules/redux-form</code> is <code>v5</code>. That <code>getValues</code> function no longer exists in <code>v6</code>.</p>
<pre><code>rm -rf node_modules/redux-form
npm install --save redux-form
</code></pre>
|
How to determine if a QPushButton's released signal is the result of auto repeat or an actual mouse release <p>I have a QPushButton that performs two actions. One action should occur every time the button's pressed slot is called, including calls through autoRepeat. The second action should be performed starting when the button is first pressed, and ending only when it is no longer held by the User. </p>
<p>The problem is that autoRepeat triggers the button's pressed, released, and clicked signals. This results in the second action ending and starting again on every repeat rather then persisting for the duration the button is held. How can I determine if the button was actually released by the User using only the existing pressed and released slots?</p>
<p>Example code:</p>
<pre><code>void MyClass::on_button_pressed()
{
startHeldAction();
doRepeatedAction();
}
void MyClass::on_button_released()
{
stopHeldAction();
}
</code></pre>
| <p>I found that taking the following steps provided a relatively simple solution that did not require any additional event handling:</p>
<ol>
<li>Create a class member <code>isHeld</code> of type bool that defaults to false.</li>
<li>Within the pressed slot, check <code>isHeld</code>. If if is false, set <code>isHeld</code> to true and call <code>startHeldAction()</code>.</li>
<li>Within the released slot, check the <a href="http://doc.qt.io/qt-5/qabstractbutton.html#down-prop" rel="nofollow">down property</a> of the button. If it is false, set isHeld to false and call <code>stopHeldAction()</code>.</li>
</ol>
<p>Making these changes produces the following code:</p>
<pre><code>void MyClass::on_button_pressed()
{
if( !isHeld )
{
isHeld = true;
startHeldAction();
}
doRepeatedAction();
}
void MyClass::on_button_released()
{
if( !ui->button->isDown() )
{
isHeld = false;
stopHeldAction();
}
}
</code></pre>
<p>This works because <code>isDown()</code> will return true in the released slot unless the User has actually released the mouse button.</p>
|
How get coordinates from Mediawiki <p>i have to do a web interface with a map inside...this map should take the coordinates of some place/city/or something else from the wikipedia database.
I read something about mediawiki api but i can't understand how to use it.
At this moment i found this code to take a text from wikipedia and to put it in a div:</p>
<pre><code>$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page=Rome&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var blurb = $('<div></div>').html(markup);
$('#list').html($(blurb).find('p'));
},
error: function (errorMessage) {
}
});
</code></pre>
<p>So i have to change the url request but i don't understand how.
Thank you</p>
| <p>You should be able to get coordinate data out of Wikidata, using the <a href="https://query.wikidata.org" rel="nofollow">Wikidata Query Service</a> (WDS).</p>
<p>For example, the <a href="https://query.wikidata.org/#SELECT%20%2a%20WHERE%20%7B%0A%20%20%3Fplace%20wdt%3AP625%20%3Flocation%20.%0A%20%20%3Fplace%20rdfs%3Alabel%20%3Flabel%20.%0A%20%20FILTER%28LANG%28%3Flabel%29%20%3D%20%22en%22%29%20.%0A%20%20FILTER%28STR%28%3Flabel%29%20%3D%20%22Rome%22%29%20.%0A%20%20%3Farticle%20schema%3Aabout%20%3Fplace%20.%0A%20%20%3Farticle%20schema%3AinLanguage%20%22en%22%20.%0A%20%20%3Farticle%20schema%3AisPartOf%20%3Chttps%3A%2F%2Fen.wikipedia.org%2F%3E%20.%0A%20%20%23filter%28lang%28%3Fplace%29%20%3D%20%22en%22%29%20.%0A%20%20%23filter%28str%28%3Farticle%29%20%3D%20%22https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FRome%22%29%0A%7D%20LIMIT%2010%0A" rel="nofollow">following query</a> (not very tested) will return some information about things called Rome that have coordinates:</p>
<pre><code>SELECT * WHERE {
?place wdt:P625 ?location .
?place rdfs:label ?label .
FILTER(LANG(?label) = "en") .
FILTER(STR(?label) = "Rome") .
?article schema:about ?place .
?article schema:inLanguage "en" .
?article schema:isPartOf <https://en.wikipedia.org/> .
} LIMIT 10
</code></pre>
<p>You can get the JSON representation of this with a URL like:</p>
<pre><code>https://query.wikidata.org/bigdata/namespace/wdq/sparql?query=<URL-encoded query here>
</code></pre>
|
Failed network error while downloading the files from Google Chrome <p>I written the below c# code for downloading the attachments in my application, when i run the code i can download the files using Mozilla, internet explorer but this is not working in Google Chrome.</p>
<pre><code> string base64FileString = result;
byte[] binaryFile = Convert.FromBase64String(base64FileString);
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", String.Format("attachment; filename=\"{0}\"", Request.QueryString["FILENAME"]));
Response.Clear();
Response.BufferOutput = false;
Response.ClearContent();
Response.BinaryWrite(binaryFile);
Response.Flush();
Response.Close();
</code></pre>
<p>Can anyone please help me what changes need to do for downloading in Chrome</p>
| <p>Google Chrome will not open a "file save" window for you if <code>"application/octet-stream"</code> is your response from a form. </p>
<p>The content-type should be whatever it is known to be, if you know it. E.g. <code>"application/pdf"</code>, <code>"image/png"</code> or whatever. See <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types" rel="nofollow">Complete list of MIME types</a></p>
<p>See this question <a href="http://webmasters.stackexchange.com/questions/21658/what-could-keep-chrome-from-downloading-files" title="What could keep Chrome from downloading files?">What could keep Chrome from downloading files?</a> for more information.</p>
|
django: how to make two models share one unique primary key <p>In my case, I have two models: Equipment and Asset, they both have their own fields but they should share one unique field: asset_number. By sharing, I mean that when creating a equipment, the asset_number user inputted would be check against both Equipment and Asset database. If it already exist in any, then there is going to be prompt telling the user that this is not unique.</p>
<p>For only one model, this is easily done by setting unique = True. However if I would like to do for two models, how should I proceed?</p>
<p>TIA</p>
| <p>I think the best solution would be to make a parent class and make both <code>Asset</code> and <code>Equipment</code> inherit from it. </p>
<p>For example, you could make a <code>BaseAsset</code> class with an <code>asset_id</code> unique field. As both classes will share the same table for <code>asset_id</code>, there's no way they will collide.</p>
<pre><code>class BaseAsset(models.Model):
asset_id = models.IntegerField(unique=True)
class Asset(BaseAsset):
.
.
.
class Equipment(BaseAsset):
.
.
.
</code></pre>
|
Universal Windows App - Auto Startup <p>We have developed a Universal Windows App mainly focusing for Desktops.
We are able to install and run the app without any issue.</p>
<p>Now our client is asking for Auto Startup facility, whenever the machine is started or restarted, the app should run automatically.</p>
<p>We could not find an option for enabling the same while creating package.</p>
<p>Can you please suggest a solution for achieving the auto start up?</p>
| <p>Hello I think it could better for you enable kiosk mode for your app here is the doc </p>
<p><a href="https://msdn.microsoft.com/en-us/library/windows/hardware/mt633799(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/hardware/mt633799(v=vs.85).aspx</a></p>
|
How to clear cin Buffer in c++ <p>I have gone through many existing answers here StackOverflow, but I am still stuck.</p>
<p>code:</p>
<pre><code>int c;
cin >> c;
if(cin.fail()) {
cout << "Wrong Input";
cin.clear();
cin.ignore(INT_MAX, '\n');
}
else
{
cout << c*2;
}
</code></pre>
<p>If I enter wring input e.g <code>s</code> instead of an integer, it outputs <code>Wrong Input</code>. However, if I enter an integer, and then I enter a string, it ignores the string and keep outputting the previous integer result, hence it does not clears the cin buffer, and the old value of <code>c</code> keeps on executing.
Can anyone please suggest the best way other than <code>cin.ignore()</code> as it does not seem to work.
and yeah for me, the max() in <code>cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');</code> gives error. So this does not work either.</p>
| <p>the max() function needs to be defined in the beginning of the file. <code>cin.ignore()</code> works very well to clear the buffer, however you need the numeric limits function max(), which in my case was giving error.</p>
<p>Solution:</p>
<pre><code>#ifdef max
#define max
#endif
</code></pre>
<p>add these lines on the top, and a function such as following will work fine.</p>
<pre><code>int id;
bool b;
do {
cout << "Enter id: ";
cin >> id;
b = cin.fail();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while ( b == true);
</code></pre>
<p>P.S: Thanks @Nathan</p>
|
Excel VBA copy pasting each named range to word <p>I have dynamic named range of cell. I need to paste each named range in one page of word and move to next page for next named range. I tried copule of code, I am unable to do.Each named range data is overlapping each other. Can anyone help me, please.</p>
<pre><code>Set wbBook = ActiveWorkbook
Set rs = wbBook.Names(1).RefersToRange
For i = 2 To wbBook.Names.Count
Set rs = Union(rs, wbBook.Names(i).RefersToRange)
Next
rs.Copy
With wd.Range
.Collapse Direction:=0
.InsertParagraphAfter
.Collapse Direction:=0
.PasteSpecial False, False, True
Application.CutCopyMode = False
End With
</code></pre>
| <p>It sounds like you want to copy each range onto different pages so I'm not sure why you're using a union. Here is a quick example of copying each named range 'name' onto a new sheet in a word document. Note: I created a new doc for simplicity.</p>
<p><strong>Edit</strong> - I added copy/paste functionality of data to the end. Formatting and such depends on what you have or want.</p>
<pre><code>Sub main()
'Create new word document
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.documents.Add()
Dim intCounter As Integer
Dim rtarget As Word.Range
Dim wbBook As Workbook
Set wbBook = ActiveWorkbook
'Loop Through names
For intCounter = 1 To wbBook.Names.Count
Debug.Print wbBook.Names(intCounter)
With objDoc
Set rtarget = .Range(.Content.End - 1, .Content.End - 1)
'Insert page break if not first page
If intCounter > 1 Then rtarget.insertbreak Type:=wdPageBreak
'Write name to new page of word document
rtarget.Text = wbBook.Names(intCounter).Name & vbCr
'Copy data from named range
Range(wbBook.Names(intCounter)).Copy
Set rtarget = .Range(.Content.End - 1, .Content.End - 1)
rtarget.Paste
End With
Next intCounter
End Sub
</code></pre>
<p><strong>Excel</strong></p>
<p><a href="https://i.stack.imgur.com/ISD1u.png" rel="nofollow"><img src="https://i.stack.imgur.com/ISD1u.png" alt="enter image description here"></a></p>
<p><strong>Resulting Word Document</strong></p>
<p><a href="https://i.stack.imgur.com/8j62l.png" rel="nofollow"><img src="https://i.stack.imgur.com/8j62l.png" alt="enter image description here"></a></p>
|
Android error during build - "default public constructor with no argument must be declared". What's the cause? <p>Android studio returned an error during build, even after running Clean, and rebuilding:</p>
<blockquote>
<p>A default public constructor with no argument must be declared if a
custom constructor is declared.</p>
</blockquote>
<p>I could not find a line number, nor a file referenced. I have no idea what causes this, as there's no indication from the build where or what the cause of this is.</p>
| <p>Example :</p>
<pre><code>public class ModelResult {
String Ques;
String Ans;
public String getQues() {
return Ques;
}
public void setQues(String ques) {
Ques = ques;
}
public String getAns() {
return Ans;
}
public void setAns(String ans) {
Ans = ans;
}
public ModelResult(String ques, String ans) {
super();
Ques = ques;
Ans = ans;
}
public ModelResult() {
super();
// TODO Auto-generated constructor stub
}
}
</code></pre>
<p>your missing part may be this</p>
<pre><code>public ModelResult() {
super();
// TODO Auto-generated constructor stub
}
</code></pre>
|
zip error - Nothing to do <p>I try to zip all folders in given directory. So I wrote this</p>
<pre><code>find /home/user/rep/tests/data/archive/* -maxdepth 0 -type d -exec zip -r "{}" \;
</code></pre>
<p>but got</p>
<pre><code>zip error: Nothing to do! (/home/user/rep/tests/data/archive/tmp.zip)
zip error: Nothing to do! (/home/user/rep/tests/data/archive/tmp_dkjg.zip)
</code></pre>
<p>here is what this contains</p>
<pre><code>user@machine:~$ ls /home/aliashenko/rep/tests/data/archive/
tmp tmp_dkjg tmp_dsf
</code></pre>
| <p>The issue is that you have not provided a name for the zip-files it will create.</p>
<pre><code>find /home/user/rep/tests/data/archive/* -maxdepth 0 -type d -exec zip -r "{}" "{}" \;
</code></pre>
<p>This will create separate zipped directories for each of the subfolders <code>tmp</code> <code>tmp_dkjg</code> and <code>tmp_dsf</code></p>
|
Google Play services out of date. Requires 9683000 but found 9452230 <p>I've been testing my android app on a phone with Android 5.1.1 and everything's been working fine, but today I tested it on a tablet with Android 5.0.2 and I'm getting the following warning and the app won't run its service: </p>
<p><code>GooglePlayServicesUtil: Google Play services out of date. Requires 9683000 but found 9452230</code></p>
<p>Here's my gradle.build file, everything seems to be up to date. I've already checked the tablet for updates and there seem to be none. </p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "alpha"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0.2"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError false
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.google.android.gms:play-services-location:9.6.1'
testCompile 'junit:junit:4.12'
testCompile 'org.powermock:powermock-api-mockito:1.6.4'
testCompile 'org.mockito:mockito-core:1.10.19'
}
</code></pre>
<p>Any ideas on how to fix the problem, thank you!</p>
<p><strong>EDIT</strong></p>
<p>Here's the full logcat from the adb shell in case its any help:</p>
<pre><code>W/ResourceType: Failure getting entry for 0x01080ad0 (t=7 e=2768) (error -75)
D/PhoneWindow: *FMB* installDecor mIsFloating : false
D/PhoneWindow: *FMB* installDecor flags : 8454400
V/ActivityThread: updateVisibility : ActivityRecord{37623128 token=android.os.BinderProxy@149bad0e {alpha.MainActivity}} show : true
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@149bad0e time:8624348
W/GooglePlayServicesUtil: Google Play services out of date. Requires 9683000 but found 9452230
</code></pre>
| <p>If the tablet's Google Play Services is up-to-date, you may not have the latest SDK versions. </p>
<ul>
<li>Go to the SDK Manager and open the stand alone SDK Manager</li>
<li>Update the Android SDK Tools, The Android SDK Platform-tools and Android SDK Build-tools. </li>
</ul>
<p>Hopefully the referenced libraries will be checked and you'll not encounter the issue after this.</p>
|
Filtering nested array in Mongo Java driver <p>Following NoSQL query returns all reviews of a particular user : </p>
<pre><code>db.getCollection('catalog-review').aggregate([
{
$project: {
reviews: {
$filter: {
input: "$reviews",
as: "review",
cond: { $eq: [ "$$review.userId", 121 ] }
}
}
}
}
])
</code></pre>
<p>This is query works fine but if I implement this in Java using Mongo driver, the "$$" doesn't work.</p>
<pre><code>List<CatalogReview> reviews = collection.aggregate(Arrays.asList(
new Document("$project", new Document("reviews", new Document("$filter", new Document("input", "$reviews")
.append("as", "review").append("cond", new Document("$eq", Arrays.asList(new Document("$$review.userId", 121)))))))
)).into(new ArrayList<>());
</code></pre>
<p>The error message:</p>
<pre><code>com.mongodb.MongoCommandException: Command failed with error 15999: 'invalid operator '$$review.userId'' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "invalid operator '$$review.userId'", "code" : 15999 }
</code></pre>
<p>Does Mongo driver supports aggregate functions ?</p>
| <p>The problem is <code>Arrays.asList(new Document("$$review.userId", 121))</code>. It should be <code>Arrays.asList("$$review.userId", 121)</code>. </p>
<p><code>Arrays.asList(new Document("$$review.userId", 121))</code> = <code>[ { "$$review.userId" : 121 } ]</code></p>
<p><code>Arrays.asList("$$review.userId", 121)</code> = <code>[ "$$review.userId", 121 ]</code></p>
<p>The snippet should be like below:</p>
<pre><code>List<CatalogReview> reviews = collection.aggregate(Arrays.asList(
new Document("$project", new Document("reviews", new Document("$filter", new Document("input", "$reviews")
.append("as", "review").append("cond", new Document("$eq", Arrays.asList("$$review.userId", 121))))))
)).into(new ArrayList<>());
</code></pre>
|
PHP json_encode returning single row only <p>So I have an associative array <code>$_SESSION['cart_items'])</code> This is the current output when I <code>print_r($_SESSION['cart_items'])</code>:</p>
<pre><code>Array
(
[3] => 23
[5] => 5
[4] => 1
)
</code></pre>
<p>In the output above, the first one for example [3]=>23 where [3] is the id and 23 is the quantity I entered from a form:</p>
<p>My current data:</p>
<p><a href="https://i.stack.imgur.com/ORGa9.png" rel="nofollow"><img src="https://i.stack.imgur.com/ORGa9.png" alt="enter image description here"></a></p>
<p>Note that in the image above, the quantity column is different from the quantity I'm entering from a form.</p>
<p>So far this is the code I've tried:</p>
<pre><code>$statement = $conn->query("SELECT id, name, price, quantity FROM product WHERE id IN (".implode(',',$_SESSION['cart_items']).")");
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
print json_encode($data);
</code></pre>
<p>And this is the output:</p>
<pre><code>[{"id":"5","name":"ballpen","price":"23","quantity":"13"}]
</code></pre>
<p>As you can see it works, though I only get a single row which should be three. </p>
<p>Is there something wrong with my query?</p>
| <p>You show that the array keys in the session array match the <code>id</code>s in the database. <code>implode()</code> implodes/joins the values in the array. So you need to implode the keys:</p>
<pre><code>implode(',', array_keys($_SESSION['cart_items']))
</code></pre>
<p>Or flip the array:</p>
<pre><code>implode(',', array_flip($_SESSION['cart_items']))
</code></pre>
|
Linked List using generics, getting "not applicable arguments for parameters" error <p>My Node class:</p>
<pre><code>public class Node<T>
{
protected T data;
protected Node<T> next;
protected Node<T> previous;
public Node()
{
this.data = null;
this.next = null;
this.previous = null;
}
public Node(T data)
{
this.data = data;
this.next = null;
this.previous = null;
}
public Node(T data, Node<T> next, Node<T> previous)
{
this.data = data;
this.next = next;
this.previous = previous;
}
public T getData()
{
return data;
}
public void setData(T data)
{
this.data = data;
}
public Node<T> getNext()
{
return next;
}
public void setNext(Node<T> next)
{
this.next = next;
}
public Node<T> getPrevious()
{
return previous;
}
public void setPrevious(Node<T> previous)
{
this.previous = previous;
}
}
</code></pre>
<p>My LinkedList class:</p>
<pre><code>public class LinkedList<T extends Node<T>>
{
private Node<T> head;
private Node<T> tail;
private Node<T> currNode;
public LinkedList()
{
head = null;
tail = null;
currNode = null;
}
public LinkedList(Node<T> head)
{
this.head = head;
tail = head;
currNode = head;
}
public void resetHead()
{
currNode = head;
}
public void add(T data)
{
Node<T> newNode = new Node<T>(data);
newNode.next = null;
if(head == null)
{
head = newNode;
}
else
{
tail.next = newNode;
newNode.previous = tail;
tail = newNode;
}
}
public void addHead(T data)
{
Node<T> newNode = new Node<T>(data);
newNode.next = head;
head.previous = newNode;
head = newNode;
}
public void addAfter(T data, Node<T> previousNode)
{
Node<T> newNode = new Node<T>(data);
newNode.next = previousNode.next;
previousNode.next = newNode;
}
public void addBefore(T data, Node<T> nextNode)
{
Node<T> newNode = new Node<T>(data);
newNode.next = nextNode;
nextNode.previous = newNode;
}
public void delete(Node<T> nodeToDelete)
{
(nodeToDelete.getNext()).setPrevious(nodeToDelete.getPrevious());
(nodeToDelete.getPrevious()).setNext(nodeToDelete.getNext());
nodeToDelete.setNext(null);
nodeToDelete.setPrevious(null);
}
public boolean hasNext()
{
if(head == null)
{
return false;
}
else if(currNode.next != null)
{
currNode = currNode.getNext();
return true;
}
else
{
return false;
}
}
public boolean hasPrevious()
{
if(tail == null)
{
return false;
}
else if(currNode.previous != null)
{
currNode = currNode.getPrevious();
return true;
}
else
{
return false;
}
}
public Node<T> getHead()
{
return head;
}
public void setHead(Node<T> head)
{
this.head = head;
}
public Node<T> getTail()
{
return tail;
}
public void setTail(Node<T> tail)
{
this.tail = tail;
}
public Node<T> getCurrNode()
{
return currNode;
}
public void setCurrNode(Node<T> currNode)
{
this.currNode = currNode;
}
}
</code></pre>
<p>The error crops up when attempting to use any of the add/insert methods in LinkedList. For example, if I try to use the <code>add(T data)</code> method, like so: <code>listOfChars.add('B');</code>, I get the following error: <code>The method add(Node) in the type LinkedList is not applicable for the arguments (char)</code>. What I expect it to do is to accept the data (in this case, the char 'B'), create a new node with 'B' as the data, and then put it in the linked list after the last node in the list. From my understanding, the method is expecting a Node instead of any generic data type, such as a char. </p>
<p>After doing some researching, I think somewhere in my TestLinkedList class, I have declared the LinkedList object incorrectly: </p>
<pre><code>public class TestLinkedList
{
public static void main(String[]args)
{
Node<Character> n1 = new Node<Character>('A');
LinkedList listOfChars = new LinkedList(n1);
listOfChars.add('B');
}
}
</code></pre>
<p>but I can't figure out how to declare it correctly. I've tried <code>LinkedList<Character></code>, <code>LinkedList<Node></code>, <code>LinkedList<Node<T>></code>, and <code>LinkedList<Node<Character>></code>, but none of them are correct. Any help would be appreciated as this is my first time using generics and I am just trying to learn how to apply it to a Linked List I've made. </p>
| <p>You need to fix two things. First, the class declaration of LinkedList says:</p>
<pre><code>public class LinkedList<T extends Node<T>> {
</code></pre>
<p>which means that T has to be both a Node and the element of a Node. This doesn't work with Character since a Character is not an instance of Node. If you remove the constraint so that T can be any value, it works with Character.</p>
<pre><code>public class LinkedList<T> {
</code></pre>
<p>Next you should add the generic part to the main file for the listOfChars as well:</p>
<pre><code>LinkedList<Character> listOfChars = new LinkedList<Character>(n1);
</code></pre>
<p>Also make sure that you have imported the right LinkedList and not the java standard class.</p>
|
Get the number of passed and failed tests with their name from command line <p>I am writing Python script which will run <code>mvn test</code> on different folders, and I want to get number of passed test and failed tests and their names from script.</p>
<p>Now I just have managed to run process and get it output</p>
<pre><code>proc = subprocess.run(["mvn", "test", "-f", PROJ_PATH])
print(proc.stdout)
</code></pre>
<p>output:</p>
<pre><code> Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.715 s
[INFO] Finished at: 2016-10-12T18:59:11+03:00
[INFO] Final Memory: 10M/212M
[INFO] ------------------------------------------------------------------------
</code></pre>
<p>I know that I can use regexp and try to parse output, but may be there are some more appropriate ways to incorporate with Maven from Python or Bash.</p>
| <p>There are multiple solutions, but no direct one... they would all involve some parsing (XML or text file).</p>
<h3>XML reports</h3>
<p>This is probably the safest and simple route. Surefire generates by default XML reports inside <a href="https://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#reportsDirectory" rel="nofollow"><code>target/surefire-reports</code></a>. There is one XML file per test class, and this file contains the results of the execution of the tests in that class. This XML follows <a href="https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd" rel="nofollow">a pre-defined XSD</a> and guarantees a stable output.</p>
<p>Each XML file (for each test class) inside <code>target/surefire-reports</code> is named <code>TEST-${testClass}.xml</code> where <code>${testClass}</code> is replaced with the fully qualified name of the test class. Its relevant content for a test class of <code>my.test.MyTest</code> would be:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<testsuite name="my.test.MyTest" tests="4" errors="1" skipped="1" failures="1">
<properties> <!-- omitted, contains system properties for the test --> </properties>
<testcase name="test" classname="my.test.MyTest" time="0.096">
<failure></failure>
</testcase>
<testcase name="test2" classname="my.test.MyTest" time="0.001">
<error></error>
</testcase>
<testcase name="test3" classname="my.test.MyTest" time="0.002"/>
<testcase name="test4" classname="my.test.MyTest" time="0">
<skipped/>
</testcase>
</testsuite>
</code></pre>
<p>(There are other attributes but they are not relevant here). Basically, the <code><testsuite></code> says there were 4 tests, which resulted in an error for 1, a failure for 1 and a skip for 1; so the remaining 1 was a success. More precisely, each <code><testcase></code> represent a test method through the <code>name</code> attribute, and the element inside represent its result. This can be parsed quite simply with regard to the 4 possible outcome for a test:</p>
<ul>
<li>failure (the assertions made in it were not verified): there is a <code><failure></code> element inside <code><testcase></code>.</li>
<li>error (an exception was thrown, and it wasn't expected): there is a <code><error></code> element inside <code><testcase></code>.</li>
<li>skip: there is a <code><skipped></code> element inside <code><testcase></code>.</li>
<li>success: there is no element inside <code><testcase></code>.</li>
</ul>
<p>If you want the fully qualified name of the test method, append the <code>classname</code> attribute (which is the qualified name of the test class) to the <code>name</code> attribute (which is the name of the test method).</p>
<h3>Logs</h3>
<p>If you configure the Surefire Plugin with the <code>plain</code> <a href="https://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#reportFormat" rel="nofollow"><code>reportFormat</code></a> with</p>
<pre><code><plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<reportFormat>plain</reportFormat>
</configuration>
</plugin>
</code></pre>
<p>the logs will contain all the info wanted:</p>
<pre class="lang-none prettyprint-override"><code>Running my.test.MyTest
Tests run: 4, Failures: 1, Errors: 1, Skipped: 1, Time elapsed: 0.169 sec <<< FAILURE! - in my.test.MyTest
test(my.test.MyTest) Time elapsed: 0.112 sec <<< FAILURE!
java.lang.AssertionError
at my.test.MyTest.test(my.test.MyTest.java:16)
test2(my.test.MyTest) Time elapsed: 0.001 sec <<< ERROR!
java.lang.IllegalArgumentException: Exception
at my.test.MyTest.test2(my.test.MyTest.java:21)
test3(my.test.MyTest) Time elapsed: 0.002 sec
test4(my.test.MyTest) skipped
</code></pre>
<p>You can then have lots of fun greping this file with a regular expression looking for <code>(.*)\((.*)\)\s+(?|(skipped)|Time elapsed:.*<<< (.*))</code>: method name of the test is in group 1, fully qualified class name in group 2 and group 3 contains the result; if group 3 is null, then it's a success.</p>
|
SQL Server - Convert table data to xml <p>Hi I have the following table data I need to convert to Xml in SQl Server. Any ideas?</p>
<p>Thanks in advance</p>
<p>From</p>
<pre><code>Party_Id HomePhoneNumber WorkPhoneNumber
62356 6314993578
62356 6314590922
62356 6313795488
</code></pre>
<p>To</p>
<pre><code><HomePhoneNumber>6314993578</HomePhoneNumber>
<WorkPhoneNumber>6314590922</WorkPhoneNumber>
<WorkPhoneNumber>6313795488</WorkPhoneNumber>
</code></pre>
| <p>Convert the empty values into NULLs. These NULL values will be excluded from the XML.</p>
<pre><code>Declare @YourTable table (Party_Id int,HomePhoneNumber varchar(25),WorkPhoneNumber varchar(25))
Insert Into @YourTable values
(62356,'6314993578',''),
(62356,'','6314590922'),
(62356,'','6313795488')
Select HomePhoneNumber=case when HomePhoneNumber='' then null else HomePhoneNumber end
,WorkPhoneNumber=case when WorkPhoneNumber='' then null else WorkPhoneNumber end
From @YourTable
For XML Path('')
</code></pre>
<p>Returns</p>
<pre><code><HomePhoneNumber>6314993578</HomePhoneNumber>
<WorkPhoneNumber>6314590922</WorkPhoneNumber>
<WorkPhoneNumber>6313795488</WorkPhoneNumber>
</code></pre>
|
Detecting the locations of circles and crosses in an image <p>I'm new to OpenCV and was wondering if anybody could direct me to the most suitable algorithm(s) to tackle the challenge of identifying the locations of circles and crosses in images that look like the following . . </p>
<p>[<img src="https://i.stack.imgur.com/TY1hJ.png" alt="enter image description here"></p>
<p>Sometimes there are lines connecting . . </p>
<p>[<img src="https://i.stack.imgur.com/a3pHB.png" alt="enter image description here">
<a href="https://i.stack.imgur.com/AtvLB.png" rel="nofollow"><img src="https://i.stack.imgur.com/AtvLB.png" alt="enter image description here"></a></p>
<p>They might even be hand drawn like this one . . </p>
<p><a href="https://i.stack.imgur.com/NLUnR.png" rel="nofollow"><img src="https://i.stack.imgur.com/NLUnR.png" alt="enter image description here"></a></p>
<p>So far I have looked at the template matching example, but it is probably not the correct approach, and it doesn't scale the sizes of the templates to the images. </p>
<p>So given the following observations . . . </p>
<ul>
<li>The crosses and circles may overlap. </li>
<li>If the diagram is in colour,
the colours will be identical for crosses and identical for circles. </li>
<li>Sometimes they will be joined by lines, sometimes not. </li>
<li>There may be other shape symbols in the plots </li>
<li>They symbols will be of similar size and shape, but might not be computer generated, so will not necessarily be identical.</li>
</ul>
<p>Where should I begin my adventure?</p>
| <p>Not an easy task.</p>
<p>For the colored case, you should start by separating the color planes. There is some chance that you can get the markers apart.</p>
<p>But for the b&w case, there is no escape, you must go deeper.</p>
<p>I would try to detect the grid lines first, for example using a Hough line detector, as accurately as possible. Then erase those lines.</p>
<p>Then try to find the crosses, which are short oblique line segments (most of the time broken by the previous operations).</p>
<p>The circles might be detected by a Hough circle detector, using a small range of radii.</p>
<p>Alternatively, a rige or edge detector can be used to get short segments and short curved arcs. You may have to add some filtering criteria to avoid the joining lines.</p>
|
How can I compare a master list of serial numbers and compare it to a seperate list and have it mark duplicates? <pre><code>Sheets("Die Sizes").Select
Columns("A:A").Select
Selection.FormatConditions.Add Type:=xlTextString, String:= _
"=cells(i,ForgeSchedule!B2)", TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.399945066682943
End With
Selection.FormatConditions(1).StopIfTrue = False
</code></pre>
<p>This is what I have so far. This will compare the specific cells in the secondary list to the master list. This means I would have to rerun this one at a time changing the "B2" to B3 all the way to B3200. How can I get it to do that automatically? I'm very new to VBA.</p>
| <p>Sounds like you just need a loop. Perhaps something like this (air code):</p>
<pre><code>Dim lngRow As Long
Sheets("Die Sizes").Select
Columns("A:A").Select
For lngRow = 2 To 3200
Selection.FormatConditions.Add Type:=xlTextString, String:= _
"=cells(i,ForgeSchedule!B" & lngRow & ")", TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.399945066682943
End With
Selection.FormatConditions(1).StopIfTrue = False
Next lngRow
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.