input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
How to Convert UInt8 to Anyobject in Swift 2.3 <p>I am trying in CryptoSwift and i tried to UInt8 to Anyobject .</p>
<p>How to Convert this </p>
<p>let encrypted:[UInt8]!</p>
<pre><code> encrypted = try AES(key: value, iv: iv, blockMode: .CBC, padding: PKCS7()).encrypt(myArray)
let mynObject:AnyObject = encrypted as! AnyObject
</code></pre>
<p>Could not cast value of type 'Swift.Array>' (0x11a6062e8) to 'Swift.AnyObject' (0x119d3d018).</p>
<p>Anyone help really Appreciated</p>
<p>Thank you</p>
| <p><strong>Example</strong></p>
<pre><code>let anInt:UInt8 = 20
let anObject:AnyObject = anInt as AnyObject
</code></pre>
<p>The key part you want to pay attention to is <code>anInt as AnyObject</code> this is how you convert a Uint8 to AnyObject.</p>
|
Exponent has no digits <p>I m integrating google sign in my iOS app using manually installed SDK. I got the .plist file and the client id but when i put client id in appdelegte.m it shows an error "Exponent has no digits". Any Solution???</p>
| <p>From <a href="https://developers.google.com/identity/sign-in/ios/sign-in" rel="nofollow">your link</a>:</p>
<blockquote>
<p>Note: If you manually installed the SDK, you should instead configure the GIDSignIn object directly, using the client ID found in the GoogleService-Info.plist file:
[GIDSignIn sharedInstance].clientID = kClientID; </p>
</blockquote>
<p>Do the following as first thing within your <code>AppDelegate</code>:</p>
<pre><code> let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist")!
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)
let plist:[String:AnyObject] = try PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil)
GIDSignIn.sharedInstance.clientID = plist["CLIENT_ID"]
</code></pre>
<p>Objective-C:</p>
<pre><code>NSString *filePath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"];
NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:filePath];
[GIDSignIn sharedInstance].clientID = plist["CLIENT_ID"]
</code></pre>
|
Populating a lookup table <p>I have a site set up to sell my photographic prints. The photos are in categories and are available in a number of sizes, so I have a photos, categories and sizes table, joined by a category_photo and photo_size table.</p>
<p>Up to now I have been adding new photos to the site using PHPMyAdmin, but manually updating three tables is a bit of a pain, so I am building a little backend to make it quicker. I can add a new photo to the photos table easily enough, but when it comes to populating the lookup tables for category and size I am running into a problem with the table names.</p>
<p>Here is my code for populating the category_photo table:</p>
<pre><code>foreach($request->category as $category)
{
$catphoto = new Category_Photo(['photo_id' => $photo->id, 'category_id' => $category]);
$photo->categories()->save($catphoto);
}
</code></pre>
<p>However, when I run this, I get the error:</p>
<pre><code>SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.category__photos' doesn't exist (SQL: insert into `category__photos` (`photo_id`, `category_id`) values (50, 1))
</code></pre>
<p>It is looking for a table called category__photos rather than category_photo. How can I rectify this? Or is there a better way to achieve what I'm trying to do?</p>
| <p>In your <code>Category_Photo</code> model class add <code>protected $table = 'category_photo';</code> Because by default laravel use plural version of model for table.</p>
|
Python Django Template cannot get name from model function <p>While I understood that I can call a function definition from our models, I can't seem to extract the file name of my uploaded document. Below I tried the following template format but either results from my desired output:</p>
<p><strong><em>.html Version 1</em></strong></p>
<pre><code><form action="." method="GET">
{% if documents %}
<ul>
{% for document in documents %}
<li> {{ document.docfile.filename }}
<input type = "submit" name="load-data" value="Add to Layer"/>
</li>
{% endfor %}
</ul>
</code></pre>
<p><em>Result: It just shows the button.</em></p>
<p><strong><em>.html Version 2</em></strong></p>
<pre><code><form action="." method="GET">
{% if documents %}
<ul>
{% for document in documents %}
<li> {{ document.filename }}
<input type = "submit" name="load-data" value="Add to Layer"/>
</li>
{% endfor %}
</ul>
</code></pre>
<p><em>Result: It just shows the button.</em></p>
<p><strong><em>.html Version 3</em></strong></p>
<pre><code><form action="." method="GET">
{% if documents %}
<ul>
{% for document in documents %}
<li> {{ document.docfile.name }}
<input type = "submit" name="load-data" value="Add to Layer"/>
</li>
{% endfor %}
</ul>
</code></pre>
<p><em>Result: Prints the complete pathname (eg: /documents/2016/10/08/filename.csv) together with the button</em></p>
<p>Here's the rest of my code:</p>
<p><strong><em>models.py</em></strong></p>
<pre><code>class Document(models.Model):
docfile = models.FileField(upload_to='document/%Y/%m/%d')
def filename(self):
return os.path.basename(self.file.name)
</code></pre>
<p><strong><em>views.py</em></strong></p>
<pre><code>documents = Document.objects.all()
return render(request, 'gridlock/upload-data.html',
{
'documents' : documents,
'form': form
})
</code></pre>
<p>I hope someone can explain why everything I tried:
<code>{{ document.docfile.filename }}</code> or <code>{{document.file.filename}}</code> or <code>{{document.filename}}</code> won't work either for me? Thanks!</p>
| <p>I think you got pretty close with <code>{{ document.filename }}</code>, except in your models you need to change </p>
<pre><code>def filename(self):
return os.path.basename(self.file.name)
</code></pre>
<p>into</p>
<pre><code>def filename(self):
# try printing the filename here to see if it works
print (os.path.basename(self.docfile.name))
return os.path.basename(self.docfile.name)
</code></pre>
<p>in your models the field is called docfile, so you need to use self.docfile to get its value.</p>
<p>source: <a href="http://stackoverflow.com/questions/2683621/django-filefield-return-filename-only-in-template">django filefield return filename only in template</a></p>
|
Send method in new Vue is not called when form is submitted <pre><code><!DOCTYPE html>
</code></pre>
<p></p>
<pre><code><head>
<meta charset=" UTF-8">
<title> Document</title>
</head>
<body id="chat">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.5.0/socket.io.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.min.js"></script>
<form v-on="submit: send">
<input v-model="message">
<button>Send</button>
</form>
<script>
var socket = io();
new Vue({
el: '#chat',
date: {
message: ''
},
methods: {
send: function(e)
{
e.preventDefault();
alert("a");
}
}
})
</script>
</body>
</code></pre>
<p></p>
<p>I want to call the send method defined in new Vue when the form is submitted ,
But when i submit the form, page is reloading.</p>
<p>I have created a Vue object and linked it to the chat element. </p>
<p>I guess e.preventDefault() is not working.</p>
| <p>Okay, what about this</p>
<pre><code><form @submit.prevent="send">
<input v-model="message">
<button>Send</button>
</form>
</code></pre>
<p>And then you can remove preventing default browser action from your <code>send()</code> method</p>
|
How to display images in pdf using fpdf library? <p>Currently I am working on opencart. And I have to display data in pdf for that I use FPDF.</p>
<p>my function looks like</p>
<pre><code>public function exportPDF(){
require_once(DIR_SYSTEM . 'lib/fpdf.php');
$pdf = new fpdf();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',12);
$category_id = $this->request->get['id'];
$this->load->model('catalog/product');
$this->load->model('tool/image');
$temp_data = $this->model_catalog_product->getProductscsv($category_id);
foreach($temp_data as $data)
{
if ($data['image']) {
$image = $this->model_tool_image->resize($data['image'], 178, 276);
} else {
$image = $this->model_tool_image->resize('placeholder.png', 178, 276);
}
$data2[] = array(
'product_id' =>$data['product_id'],
'model' =>$data['model'],
'name' =>$data['name'],
'price' =>$data['price'],
'image' =>$image,
);
}
$row = array();
$pdf->SetFont('Arial','',12);
$pdf->Ln();
$pdf->Cell(35,10,'id',1);
$pdf->Cell(35,10,'model',1);
$pdf->Cell(35,10,'name',1);
$pdf->Cell(35,10,'price',1);
$pdf->Cell(35,10,'image',1);
foreach($data2 as $row)
{
$pdf->SetFont('Arial','',10);
$pdf->Ln();
foreach($row as $column)
$pdf->Cell(35,50,$column,1);
}
$pdf->Output();
}
</code></pre>
<p>And current output pdf looks like:
<a href="https://i.stack.imgur.com/qRJEs.png" rel="nofollow"><img src="https://i.stack.imgur.com/qRJEs.png" alt="enter image description here"></a></p>
<p>My need is I need to display the images in image column instead of link. how can it make possible. I am new to this, and trying for long time.
How to use <strong>$pdf->Image();</strong> in the <strong>$data2 array</strong>. How to display images in image column in the pdf.</p>
| <p>Try this, </p>
<pre><code>foreach($data2 as $row)
{
$pdf->SetFont('Arial','',10);
$pdf->Ln();
foreach($row as $key=>$column)
{
if($key == "image"){
$pdf->Cell(35,50,$this->Image($column,$this->GetX(),$this->GetY()),1);
}else{
$pdf->Cell(35,50,$column,1);
}
}
}
</code></pre>
<p>and also read this : <strong><a href="http://www.fpdf.org/en/doc/image.htm" rel="nofollow">reference</a></strong> </p>
|
Haskell Record function constraints <p>What is the way in Haskell to express something like:</p>
<pre><code>data SinkBuilder
{ openSink :: MonadIO m => m Sink
}
data Sink = Sink
{ writeSink :: MonadIO m => Value -> m ()
, closeSink :: MonadIO m => m ()
}
</code></pre>
<p>I guess what I need is a set of functions that are conveniently "bundled" together in a data type so this datatype is created and is passed around as one thing?</p>
<p>It seems useful for composition reasons, for example, I could implement something like</p>
<pre><code>(:+:) :: SinkBuilder -> SinkBuilder -> SinkBuilder
a :+: b = SinkBuilder $ do
sa <- openSink a
sb <- openSink b
return $ Sink (\v -> writeSink sa >> writeSink sb) (closeSink sa >> closeSink sb)
</code></pre>
<p>It doesn't work because I can't have constraints on record functions, but it also looks very ugly, so I am pretty sure there should be a much better way of doing it.</p>
| <p>This compiles, but I have no clear idea about what you really want to do. I fear that this is not what you want.</p>
<pre><code>{-# LANGUAGE ScopedTypeVariables, RankNTypes #-}
import Control.Monad.Trans
type Value = Int
data SinkBuilder = SB
{ openSink :: forall m. MonadIO m => m Sink
}
data Sink = Sink
{ writeSink :: forall m. MonadIO m => Value -> m ()
, closeSink :: forall m. MonadIO m => m ()
}
(#+#) :: SinkBuilder -> SinkBuilder -> SinkBuilder
a #+# b = SB $ do
sa <- openSink a
sb <- openSink b
return $ Sink (\v -> writeSink sa v >> writeSink sb v) (closeSink sa >> closeSink sb)
</code></pre>
|
Hibernate Validator does not work with Jackson write_only access <p>I have an endpoint where a user can register with her email/password. However I, want to check that the password is not empty, but I also want to only deserialize the password, because I do not want to send it back to the client.</p>
<p>Domain</p>
<pre><code>public class User {
@NotEmpty
private String email;
@JsonProperty(access = Access.WRITE_ONLY)
@NotEmpty
private String password;
// Getters and setters
...
}
</code></pre>
<p>Endpoint</p>
<pre><code>@Path("/register")
@POST
public Response register(@Valid User user) {
...
}
</code></pre>
<p>Instead of the <code>Access.WRITE_ONLY</code> I've also tried <code>@JsonIgnore</code> on the getter and <code>@JsonProperty</code> on the setter.</p>
<p>The problem is Hibernate Validator keeps complaining that the password is empty, even when I POST a user with password set:</p>
<pre><code>"{"errors":["password may not be empty"]}"
</code></pre>
<p>How can I fix this? Or do I have to implement my own NotEmpty validation logic in the endpoint?</p>
| <p>This can be done using validation groups. Here is how you would achieve this: </p>
<pre><code>public class GroupValidationTest {
public static void main(String[] args) {
Validator v = Validators.newValidator();
Model m = new Model();
m.user = "Harry";
m.password = "Potter";
Set<ConstraintViolation<Model>> validate = v.validate(m, INPUT.class);
System.out.println(validate.size());
validate = v.validate(m, INPUT.class, OUTPUT.class);
System.out.println(validate.size());
validate = v.validate(m, OUTPUT.class);
System.out.println(validate.size());
m.password = null;
validate = v.validate(m, INPUT.class, OUTPUT.class);
System.out.println(validate.size());
validate = v.validate(m, OUTPUT.class);
System.out.println(validate.size());
}
public static class Model {
@NotEmpty(groups={INPUT.class, OUTPUT.class})
public String user;
@NotEmpty(groups={INPUT.class})
public String password;
}
public interface INPUT {}
public interface OUTPUT {}
}
</code></pre>
<p>This outputs: </p>
<pre><code>0 -> Full object, validate INPUT
0 -> Full object, validate INPUT + OUTPUT
0 -> Full object, validate OUTPUT
1 -> null password, validate INPUT + OUTPUT
0 -> null password, validate OUTPUT
</code></pre>
<p>Explenation: </p>
<p>Hibernate validator framework supports groups for validation constraints. They are used to tell the validator which groups to validate in a specific validation attempt. You can read all about it here: </p>
<p><a href="https://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/validator-usingvalidator.html#example-group-interfaces" rel="nofollow">https://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/validator-usingvalidator.html#example-group-interfaces</a></p>
<p>What I did in my code example is: </p>
<ul>
<li>Define 2 groups <code>INPUT</code> and <code>OUTPUT</code></li>
<li>Mark the user property to be validated for both groups</li>
<li>Mark the password property to be validated only on input </li>
</ul>
<p>For the REST aspect (different question), usually validation of input and ouput is done by an interceptor, typically the MessageBodyReader and Writer class. These are responsible for reading user input and writing it out. You can read about that on the jersey docs page. </p>
<p>You can then implement your own validation reader/writer that knows to only validate <code>INPUT</code> when reading user input, while only validating <code>OUTPUT</code> when writing the serialised body back. </p>
<p>I hope that helps,</p>
<p>artur </p>
|
AJAX success response fires error callback <p>I spent yesterday wondering around in SO for something that would suit me i haven't found anything appropriate.
I'm having a quite common problem with the response of an ajax call from a razor view.
For test purpose i'm forcing a success response to be returned as a Json response:</p>
<p><strong>Controller</strong></p>
<pre><code> public ActionResult Save(int order){
. . .
var response = new {Order = order, ResultCode = 0, ResultMessage = "Positive!", Success = true };
var json = Json(response, JsonRequestBehavior.AllowGet);
return json;
</code></pre>
<p>Ajax call as follows:</p>
<pre><code> $(document).ready(function () {
$("#save_ahref").click(
function () {
$.ajax({
method: "GET",
url: "/MyController/Save",
dataType: "application/json",
data: { order: $("#hid_order").val() },
success: onSuccess,
error: onError
});
}
);
});
function onSuccess(response) {
//never reached
}
function onError(response) {
var res = JSON.parse(response.responseText);
//do other stuff
}
</code></pre>
<p>My response from Chrome console looks correct:</p>
<pre><code> Object {readyState: 4, responseText: "{"Order":12345678,"Success":true,"ResultCode":0,"ResultMessage":"Positive!"}", status: 200, statusText: "OK"}
</code></pre>
<p>and the result of the JSON.parse(response.responseText) as well (jsonlint says so).</p>
<p>Although i followed the hints found here in SO and other forums (they all basically say to use application/json instead of json as dataType, and try to parse correctly the object) i still get the error event fired and i can't seem to get why.</p>
<p>I would be grateful for any idea!</p>
| <p>Your data in the <code>ajax</code> call should look like this:</p>
<pre><code>data : JSON.stringify({ order: $("#hid_order").val() }),
</code></pre>
|
How to restart particular IIS site from Multiple IIS sites? <p>In our company we have multiple projects in single IIS server and I am working on build automation via using CruisControl. My question is I have to restart a particular IIS site after deployment without entering into server or Via using CruiseControl jobs.</p>
<p>Does anyone have any idea?</p>
| <p>You can start an individual Web site without affecting the operation of any other Web site that is being that is supported by a server that is maintained by Internet Services Manager. </p>
<p>To start an individual Web site that has previously been stopped:</p>
<ul>
<li><p>Log on to the Web server computer as an administrator.</p></li>
<li><p>Click Start, point to Settings, and then click Control Panel.</p></li>
<li><p>Double-click Administrative Tools, and then double-click Internet
Services Manager.</p></li>
<li><p>Right-click the Web site that you want to start in the left pane, and
then click Start.</p></li>
</ul>
<p><strong><em>CommandLine:</em></strong></p>
<p>Command Line
To start or stop a Web site, use the following syntax:</p>
<pre><code>appcmd start | stop site /site.name:string
</code></pre>
<p>The variable string is the name of the Web site that you want to start or stop.
For example, to stop a Web site named contoso, type the following at the command prompt, and then press ENTER:</p>
<pre><code>appcmd stop site /site.name: contoso
</code></pre>
<p><strong><em>Hoping this will help you :)</em></strong></p>
|
How to make a list without quotes from string? python3 <p>I want to make a program in which i input a string then make it into list and then use list.count. To do this i need list without colons.</p>
<pre><code>a=("44, 4, 5, 6, 7, 8 ")
a=[a]
print(a)
-> ['44, 4, 5, 6, 7, 8 ']
</code></pre>
<p>but i want this:</p>
<pre><code>[44, 4, 5, 6, 7, 8]
</code></pre>
<p>i tried this:</p>
<pre><code>b=map(int, a)
print(b)
</code></pre>
<p>but then get this -></p>
<pre><code><map object at 0x00537810>
</code></pre>
<p>and don't know what to do next</p>
| <p>It's even easier than that:</p>
<pre><code>>>> a=("44, 4, 5, 6, 7, 8 ")
>>> my_list = [int(s) for s in a.split(", ")]
>>> my_list
[44, 4, 5, 6, 7, 8]
>>>
</code></pre>
|
How to add a sum of a column and all other rows of a table <p>I have table as </p>
<pre><code> name quentity
pramo 1000
ladkat 2000
</code></pre>
<p>And I want select output as total new row with sum </p>
<pre><code> name quentity
pramod 1000
ladkat 2000
total 3000
</code></pre>
| <p>Try using UNION like:</p>
<pre><code>(SELECT *
FROM your_table)
UNION
(SELECT sum(quentity) as "total"
FROM your_table)
</code></pre>
|
Reset svg fill in css <p>I want to have all my svgs to have the same plain color. So I use</p>
<pre><code>svg *{
fill: #ccc;
}
</code></pre>
<p>But I want to get default fills on :hover. How can I disable the fills and get defaults back?</p>
| <p>You can do this using <code>:not()</code> and effectively style "not hovered".</p>
<pre><code>svg *:not(:hover){
fill: #ccc;
}
</code></pre>
<p>The above might work, here's a quick CodePen that you can play with: <a href="http://codepen.io/anon/pen/rrqyAx" rel="nofollow">http://codepen.io/anon/pen/rrqyAx</a></p>
<p>You can learn more on the <a href="https://developer.mozilla.org/en/docs/Web/CSS/:not" rel="nofollow">Mozilla Dveloper Network entry for :not()</a></p>
<p>Alternatively (I was curious) you could use fill:inherit - which is just as valid.</p>
<pre><code>svg *:hover{
fill : inherit;
}
</code></pre>
<p>I've added an svg styled in this manner to the CodePen.</p>
|
Linked list segmentation fault 11 <p>I'm having a problem with one of my homeworks. I need to do a linked list concat, but after redefining the operator+, I have segmentation fault.
Here is the code:</p>
<p>In main.cpp:</p>
<pre><code>case CONCAT:
do
{
std::cout << "Which two list do you want to concat?(1-3) ";
std::cin >> s;
std::cin >> g;
selectedlist =atoi(s.c_str());
selectedlist2 =atoi(g.c_str());
} while ((
selectedlist== 0 &&
s != "0" &&
(selectedlist > 3 || selectedlist < 1)
) &&
(
selectedlist2== 0 &&
g != "0" &&
(selectedlist2 > 3 || selectedlist2 < 1)
)
);
Lista[selectedlist-1]+Lista[selectedlist2-1];
std::cout<<"Ready";
break;
</code></pre>
<p>In the header file:</p>
<pre><code>class lista
{
public:
enum Exceptions{EMPTY};
lista() : first(NULL),last(NULL),current(NULL){ first = new Elem(0,0);}
virtual ~lista();
lista(const lista& s);
int Current() const {return current->Adat;}
void First() {current = first->next;}
bool End() const {return current==NULL;}
void Next() {current = current->next;}
void Vegere(int e);
void Elejerol();
bool Urese();
int Eleje();
friend std::ostream& operator<<(std::ostream& s, const lista& a);
friend lista operator+(lista& a, lista& b);
private:
struct Elem{
int Adat;
Elem* next;
Elem(int c, Elem* n): Adat(c), next(n){};
};
Elem* first;
Elem* last;
Elem* current;
};
</code></pre>
<p>And in the lista.cpp:</p>
<pre><code>lista operator+(lista& a, lista& b)
{
if(b.first->next!=NULL && a.first->next!=NULL)
{
a.last->next = b.first->next;
a.last = b.last;
b.first = new lista::Elem(0,0);
b.last = NULL;
b.current = NULL;
}
else
{
throw lista::EMPTY;
}
return a;
}
void lista::Vegere(int e) {
Elem* p = new Elem(e,0);
if(last==NULL) {
first -> next = p;
last = p;
}
else {
last -> next = p;
last = p;
}
}
</code></pre>
<p>It complains, and all the other functions(empty, add numbers, etc..) works fine. What am I doing wrong?</p>
<pre><code>void lista::Vegere(int e)
{
Elem* p = new Elem(e,0);
if(last==NULL)
{
first -> next = p; last = p;
}
else
{
last -> next = p; last = p;
}
}
</code></pre>
<p>Destructor:</p>
<pre><code>lista::~lista()
{
Elem *p, *v;
p = first;
v = first -> next;
while( v!=NULL)
{
delete p;
p = v;
v = v -> next;
}
delete p;
}
</code></pre>
<p>I have figured it out.
I havent posted this part of the code here, but after some debugging I've got it.</p>
<p>Here is the error:</p>
<pre><code> lista::lista(const lista& s){
if(s.first->next==NULL)
{
first->next = last = NULL;
}
else
{
Elem* q = new Elem(s.first->Adat,NULL);
first = q;
for(Elem* p=s.first->next;p!=NULL;p=p->next)
{
q = new Elem(p->Adat,NULL);
q->next = q;
}
last = q;
}
current = first;
THIS PART is the error:
[
while(current!=NULL && current->Adat!=s.current->Adat)
{
current=current->next;
}
]
}
</code></pre>
<p>I've just deleted it, and it works. :)</p>
| <p>The problem is </p>
<pre><code>lista operator+(lista& a, lista& b)
{
...
return a;
}
</code></pre>
<p>This creates a <em>copy</em> of <code>a</code> which is then immediately destroyed (because you don't save it anywhere). You haven't defined a copy constructor, so you get the compiler defined one (which just copies the pointers). The destructor of the temporary will delete the memory pointed to by <code>a.first</code>, and then when you come to call the destructor of <code>a</code>, everything will blow up.</p>
<p>If your destructor is freeing memory, you need to declare a copy constructor and and a copy assignment operator. The simplest such definition is to just delete them (with trailing <code>= delete;</code>) - you will then need to change the definition of <code>operator +</code> (probably by changing the function name to <code>append()</code>).</p>
|
Fill texture brush using image, not tile <p>I have a texture brush that uses a certain image to make the texture to be displayed like this:</p>
<pre><code>Image image = new Bitmap("Untitled.png");
for (int i = 0; i < points.Count; i++)
{
using (TextureBrush tbr = new TextureBrush(image))
{
tbr.RotateTransform(i * 4);
var p = PointToClient(Cursor.Position);
tbr.Transform = new Matrix(
75.0f / 640.0f,
0.0f,
0.0f,
75.0f / 480.0f,
0.0f,
0.0f);
e.Graphics.FillEllipse(tbr, p.X - 50, p.Y - 50, 100, 100);
Pen p3 = new Pen(tbr);
e.Graphics.DrawEllipse(Pens.DeepSkyBlue, p.X - 50, p.Y - 50, 100, 100);
}
}
</code></pre>
<p>and here's the image it is using:</p>
<p><a href="https://i.stack.imgur.com/I31nn.png" rel="nofollow"><img src="https://i.stack.imgur.com/I31nn.png" alt="Image"></a></p>
<p>This is how it turns out:</p>
<p><a href="https://i.stack.imgur.com/dIjfm.gif" rel="nofollow"><img src="https://i.stack.imgur.com/dIjfm.gif" alt="Initial"></a></p>
<p>I want the image to fill the circle so that it looks like this(edited image):</p>
<p><a href="https://i.stack.imgur.com/bdSCt.png" rel="nofollow"><img src="https://i.stack.imgur.com/bdSCt.png" alt="Final"></a></p>
<p>Any Help would be appreciated.</p>
| <p>You need to scale using the correct numbers.</p>
<p>If you want an image with a size = width * height pixels to fill a circle of diameter you should scale like this:</p>
<pre><code> int diameter = 100;
Image image = new Bitmap(yourImage);
float scaleX = 1f * diameter / image.Size.Width;
float scaleY = 1f * diameter / image.Size.Height;
</code></pre>
<p>Note however that your <code>TextureBrush</code> will always reveal a <strong>tiling</strong> made from your image. This seemed ok for your <a href="http://stackoverflow.com/questions/40058030/fill-a-circle-that-follows-the-cursor-with-more-small-circles">original question</a>, especially when rotating the images in the tail to get rid of any artifacts.</p>
<p>But here it may simply not be what you want.</p>
<p>If you want the image to follow the mouse you need to draw it.</p>
<p>Here is an example, that uses a checkbox to <strong>switch</strong> between <strong>tiling</strong> and <strong>drawing</strong>. The animation uses only one frame:</p>
<p><a href="https://i.stack.imgur.com/fGq3v.gif" rel="nofollow"><img src="https://i.stack.imgur.com/fGq3v.gif" alt="enter image description here"></a></p>
<pre><code> for (int i = 0; i < points.Count; i++)
{
using (TextureBrush tbr = new TextureBrush(image))
{
tbr.RotateTransform(i * 4); // optional
var p = PointToClient(Cursor.Position);
tbr.Transform = new Matrix(
scaleX,
0.0f,
0.0f,
scaleY,
0.0f,
0.0f);
// any tile mode will work, though not all the same way
tbr.WrapMode = WrapMode.TileFlipXY;
if (cbx_tileFunny.Checked)
e.Graphics.FillEllipse(tbr, p.X - diameter/2,
p.Y - diameter/2, diameter, diameter);
else
{
((Bitmap)image).SetResolution(e.Graphics.DpiX, e.Graphics.DpiY); // (**)
e.Graphics.ScaleTransform(scaleX, scaleY);
e.Graphics.DrawImage( image, (p.X - diameter/2) / scaleX,
(p.Y - diameter/2 ) / scaleY);
e.Graphics.ResetTransform();
}
/// ? Pen p3 = new Pen(tbr);
e.Graphics.DrawEllipse(Pens.DeepSkyBlue, p.X - diameter/2,
p.Y - diameter/2, diameter, diameter);
}
}
</code></pre>
<p>Do note the extra scaling needed here (**) if the image has a different dpi setting than your screen.</p>
<p>Also: While it is usually a good idea to create and dispose Pens and Brushes quickly, when so much effort is put into creating the Brush and/or Image caching them or even a series of them seems rather preferrable, imo.</p>
|
ELKI: Normalization undo for result <p>I am using the ELKI MiniGUI to run LOF. I have found out how to normalize the data before running by <code>-dbc.filter</code>, but I would like to look at the original data records and not the normalized ones in the output. </p>
<p>It seems that there is some flag called <code>-normUndo</code>, which can be set if using the command-line, but I cannot figure out how to use it in the MiniGUI.</p>
| <p>This functionality used to exist in ELKI, but <strong>has effectively been removed</strong> (for now).</p>
<ol>
<li>only a few normalizations ever supported this, most would fail.</li>
<li>there is no longer a well defined "end" with the visualization. Some users will want to visualize the normalized data, others not.</li>
<li>it requires carrying over normalization information along, which makes data structures more complex (albeit the hierarchical approach we have now would allow this again)</li>
<li>due to numerical imprecision of floating point math, you would frequently <em>not</em> get out the exact same values as you put in</li>
<li>keeping the original data in memory may be too expensive for some use cases, so we would need to add another parameter "keep non-normalized data"; furthermore you would need to choose which (normalized or non-normalized) to use for analysis, and which for visualization. This would not be hard with a full-blown GUI, but you are looking at a command line interface. (This is easy to do with Java, too...)</li>
</ol>
<p>We would of course <strong>appreciate patches</strong> that contribute such functionality to ELKI.</p>
<p>The easiest way is this: <strong>Add a (non-numerical) label column, and you can identify the original objects, in your original data, by this label.</strong></p>
|
Laravel complex query <p>I have the following tables:</p>
<p><strong>Dishes</strong></p>
<pre><code>id
name
</code></pre>
<p><strong>Customers</strong></p>
<pre><code>id
name
</code></pre>
<p><strong>Ingredients</strong></p>
<pre><code>id
name
</code></pre>
<p><strong>Dishes_Ingredients</strong> (table to put in relation dishes and ingredients)</p>
<pre><code>id
dish_id
ingredient_id
</code></pre>
<p><strong>Customers_Allergic_Ingredients</strong> (customers are allergic to certain ingredients)</p>
<pre><code>id
customer_id
ingredient_id
</code></pre>
<p><strong>Customers_Intolerance_Ingredients</strong> (customers are intolerant to certain ingredients)</p>
<pre><code>id
customer_id
ingredient_id
</code></pre>
<p>I need to get the following information from the database: for a given <code>customer_id</code>, I want to retrieve all the dishes which the customer is <strong>not</strong> allergic to and not intolerant to, using Laravel Query Builder.</p>
<p>This is what I tried so far:</p>
<pre><code>$dishes = DB::table('dishes')
->join('dishes_ingredients', 'dishes.id', '=', 'dishes_ingredients.dish_id')
->join('customers_allergic_ingredients', 'dishes_ingredients.ingredient_id', '<>', 'customers_allergic_ingredients.ingredient_id')
->join('customers_intolerance_ingredients', 'dishes_ingredients.ingredient_id', '<>', 'customers_intolerance_ingredients.ingredient_id')
->where('customers.id', 1)
->select('dishes.id', 'dish_translations.name')
->get();
</code></pre>
| <p>I don't know Laravel but if you just want to solve your problem:</p>
<pre><code>SELECT *
FROM Dishes d
WHERE d.id NOT IN
(
SELECT DISTINCT dish_id
FROM Dishes_Ingridients
WHERE ingredient_id IN
(SELECT DISTINCT ingredient_id FROM Customers_Allergic_Ingredients cai WHERE cai.customer_id = ?)
OR
ingredient_id IN
(SELECT DISTINCT ingredient_id FROM Customers_Intolerance_Ingredients cii WHERE cii.customer_id = ?)
)
</code></pre>
|
Sass sourcemap on Firefox Ubuntu 16.04 <p>How can I set sourcemaps for sass files on Firefox - Firebug (I'm having Ubuntu 16.04 on VirtualBox), so I can inspect the sass code for ruby-on-rails or php projects? I 'm not entirely sure, but I guess would be a system or a firefox setting, right?</p>
| <p>Firebug does <strong>not</strong> have <a href="https://github.com/firebug/firebug/issues/5894" rel="nofollow">support for source maps</a> and it is <a href="https://blog.getfirebug.com/2016/06/07/unifying-firebug-firefox-devtools/" rel="nofollow">not working anymore once multi-process Firefox is enabled</a>.</p>
<p>Therefore I suggest you use the Firefox DevTools, which support <a href="https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map" rel="nofollow">source mapping</a>.</p>
|
What is the difference between MessagePack, Protobuf and JSON ? Can anyone tell me which one to use when <p>I need to understand the difference between
- message pack
- protocol buffers
- JSON</p>
| <p>Without having jumped in deeply into the matter I'd say the following:</p>
<p>All three are data formats that help you serialize information in a structured form so you can easily exchange it between software components (for example client and server). </p>
<p>While I'm not too familiar with the other two, JSON is currently a quasi-standard due to the fact that it is practically built into JavaScript - it's not a coincidence it is called JavaScript Object Notation. The other two seem to require additional libraries on both ends to create the required format.</p>
<p>So when to use which? Use JSON for REST services, for example if you want to publish your API or need different clients to access it. JSON seems to have the broadest acceptance.</p>
|
alternately appending elements from two lists <p>I have three lists with elements :</p>
<pre><code>a = [[0,1],[2,3],...]
b = [[5,6],[7,8],...]
c = []
</code></pre>
<p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p>
<pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ]
</code></pre>
| <p>Basic approach:</p>
<pre><code>>>> a = [[0,1],[2,3]]
>>> b = [[5,6],[7,8]]
>>> c = []
>>> for pair in zip(a,b):
... c.extend(pair)
...
>>> c
[[0, 1], [5, 6], [2, 3], [7, 8]]
>>>
</code></pre>
<p>This breaks if the lengths aren't equal. But you can deal with that case as an exercise.</p>
|
Azure App Service Owin Instagram and other Auth providers <p>Ive just upgraded my old Azure mobile services app which had various other auth methods other than the facebook, google, twitter etc.. </p>
<p>I think it owin 2.01.</p>
<p>They looked like this : </p>
<p>So implemented Microsoft.WindowsAzure.Mobile.Service.Security.LoginProvider:</p>
<pre><code> public static class WebApiConfig
{
public static void Register()
{
// Use this class to set configuration options for your mobile service
ConfigOptions options = new ConfigOptions();
options.PushAuthorization = AuthorizationLevel.User;
options.LoginProviders.Add(typeof(FacebookLoginProvider));
options.LoginProviders.Add(typeof(InstaLoginProvider));
options.LoginProviders.Add(typeof(TwitterLoginProvider));
// Use this class to set WebAPI configuration options
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
// Set default and null value handling to "Include" for Json Serializer
config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Include;
Database.SetInitializer(new app_name_mobile_appInitializer());
}
</code></pre>
<p>}</p>
<p>Provider implementation: </p>
<pre><code>using System;
using System.Security.Claims;
using System.Threading.Tasks;
using app_name_mobile_appService.DataObjects;
using app_name_mobile_appService.Models;
using Microsoft.WindowsAzure.Mobile.Service;
using Microsoft.WindowsAzure.Mobile.Service.Security;
using Newtonsoft.Json.Linq;
using Owin;
using Owin.Security.Providers.Instagram;
using System.Linq;
namespace app_name_mobile_appService.Auth.ExtraLogins.Instagram
{
public class InstaLoginProvider : LoginProvider
{
internal const string ProviderName = "Instagram";
public InstaLoginProvider(IServiceTokenHandler tokenHandler)
: base(tokenHandler)
{
}
public override string Name
{
get { return ProviderName; }
}
public override void ConfigureMiddleware(IAppBuilder appBuilder,
ServiceSettingsDictionary settings)
{
InstagramAuthenticationOptions options = new InstagramAuthenticationOptions()
{
ClientId = settings["InstagramClientId"],
ClientSecret = settings["InstagramClientSecret"],
AuthenticationType = this.Name,
Provider = new InstaLoginAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
ben_coomber_mobile_appContext mainContext = new app_name_mobile_appContext();
Account account = mainContext.Accounts.SingleOrDefault(a => a.UserIdWithProvider == context.Id);
if (account == null)
{
Account newAccount = new Account
{
Id = Guid.NewGuid().ToString(),
Username = context.UserName,
InstagramToken = context.AccessToken,
UserIdWithProvider = context.Id,
ProviderType = "instagram"
};
mainContext.Accounts.Add(newAccount);
mainContext.SaveChanges();
}
return Task.FromResult(0);
}
}
};
options.Scope.Add("likes");
options.Scope.Add("comments");
appBuilder.UseInstagramInAuthentication(options);
}
public override ProviderCredentials CreateCredentials(
ClaimsIdentity claimsIdentity)
{
Claim name = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
Claim providerAccessToken = claimsIdentity
.FindFirst(ServiceClaimTypes.ProviderAccessToken);
InstaCredentials credentials = new InstaCredentials()
{
UserId = this.TokenHandler.CreateUserId(this.Name, name != null ?
name.Value : null),
AccessToken = providerAccessToken != null ?
providerAccessToken.Value : null
};
return credentials;
}
public override ProviderCredentials ParseCredentials(JObject serialized)
{
return serialized.ToObject<InstaCredentials>();
}
}
}
</code></pre>
<p>InstagramAuthenticationProvider implementation:</p>
<pre><code> using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Mobile.Service.Security;
using Owin.Security.Providers.Instagram.Provider;
namespace app_name_mobile_appService.Auth.ExtraLogins.Instagram
{
public class InstaLoginAuthenticationProvider :InstagramAuthenticationProvider
{
public override Task Authenticated(InstagramAuthenticatedContext context)
{
context.Identity.AddClaim(
new Claim(ServiceClaimTypes.ProviderAccessToken, context.AccessToken));
return base.Authenticated(context);
}
}
}
</code></pre>
<p>ProviderCredentials implementation: </p>
<pre><code>using Microsoft.WindowsAzure.Mobile.Service.Security;
namespace app_name_mobile_appService.Auth.ExtraLogins.Instagram
{
public class InstaCredentials : ProviderCredentials
{
public InstaCredentials()
: base(InstaLoginProvider.ProviderName)
{
}
public string AccessToken { get; set; }
}
}
</code></pre>
<p>So whats the correct way to do this using the newer stuff in the Azure App Service? </p>
<p>Im ashumming its some libs and extra things added here but i cant find any docs any where (would be helpful just ot know where docs are):</p>
<pre><code>using System.Web.Http;
using Microsoft.Azure.Mobile.Server.Authentication;
using Microsoft.Azure.Mobile.Server.Config;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(ben_coomber_mobile_appService.OwinStartUp))]
namespace app_name_mobile_appService
{
public class OwinStartUp
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
HttpConfiguration config = new HttpConfiguration();
new MobileAppConfiguration()
.UseDefaultConfiguration()
.ApplyTo(config);
app.UseWebApi(config);
AppServiceAuthenticationOptions options = new AppServiceAuthenticationOptions();
app.UseAppServiceAuthentication(options);
}
}
}
</code></pre>
<p>any help appreciated thank you :)</p>
| <p>If I understand you correctly, I assume that you provide three methods (Facebook, Instagram,Twitter) for Authentication. And you have implemented LoginProvider for Instagram by yourself in your old Azure mobile services app.</p>
<p>From <a href="https://azure.microsoft.com/en-us/documentation/articles/app-service-authentication-overview/" rel="nofollow">Authentication and authorization in Azure App Service</a>, we could find that:</p>
<blockquote>
<p>App Service supports five identity providers out of the box: Azure Active Directory, Facebook, Google, Microsoft Account, and Twitter. To expand the built-in support, you can integrate another identity provider or <a href="https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-dotnet-backend-how-to-use-server-sdk/#custom-auth" rel="nofollow">your own custom identity solution</a>.</p>
</blockquote>
<p>For using <code>IAppBuilder.UseAppServiceAuthentication</code>, you could try to follow this official <a href="https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-dotnet-backend-how-to-use-server-sdk/#custom-auth" rel="nofollow">tutorial</a> and this sample <a href="https://github.com/Azure/azure-mobile-apps-net-server/tree/master/samples/SampleApp" rel="nofollow">azure-mobile-apps-net-server</a>.</p>
|
kendo mvc ajax grid sending Viewbag or ViewData variable as a parameter in client Template Column <p>I'm using Telerik Kendo MVC Grid ,and i need to use client template as a link.
The Question is : How to send ViewBag Variable or ViewData as a parameter within the link?</p>
| <p>Just the syntax for creating a ClientTemplate using a ViewBag field?</p>
<pre><code>@{
ViewBag.Data = "kendo-mvc-ajax-grid-sending-viewbag-or-viewdata-variable-as-a-parameter-in-clien";
}
@(Html.Kendo().Grid<GridViewModel>()
.Name("grid")
.Columns(cols =>
{
cols.Bound(c => c.Field1);
cols.Bound(c => c.Field2);
cols.Bound(c => c.Field2);
.ClientTemplate(
"<a href='http://stackoverflow.com/questions/40106180/" + ViewBag.Data + "' target='_blank'>Click Here</a>" );
})
}
...rest of grid config....
)
</code></pre>
<p>Otherwise, you need to provide more specific details of what you are asking.</p>
|
Unable to use custom post type taxonomy template in the plugin <p>I am working on a plugin and that creates a custom post type and <code>custom taxonomy</code> for that post type. I simple created single page template that worked fine and now trying to use <code>taxonomy template</code> and that's never working for me. While I pasted that template in my theme folder and it works like a charm, can any one tell me how to use taxonomy template in the plugin ?</p>
<p>Here is my post type name: <code>portfolio</code></p>
<p>single page template is: <code>single-portfolio</code></p>
<p>taxonomy name is: <code>portfolio_category</code></p>
<p>Taxonomy template is: <code>taxonomy-portfolio_category</code></p>
<p>All those files are living in plugins main folder. Can any one point out why taxonomy works in theme folder but not in plugin folder ???.</p>
| <p>I believe your question is answered here:
<a href="http://wordpress.stackexchange.com/questions/51022/default-taxonomy-template-in-plugin-override-in-theme">http://wordpress.stackexchange.com/questions/51022/default-taxonomy-template-in-plugin-override-in-theme</a>, you only need to do something in reverse...</p>
<p>To use a taxonomy template from your plugin directory if one exists, otherwise fall back to the template in theme directory you would do something like this:</p>
<pre><code>function override_tax_template($template){
// is your portfolio_category specific custom taxonomy being shown?
$taxonomy_array = array('portfolio_category');
foreach ($taxonomy_array as $taxonomy_single) {
if ( is_tax($taxonomy_single) ) {
if (file_exists(trailingslashit(BASE_PLUGIN_DIR) . 'taxonomy-'.$taxonomy_single.'.php')) {
$template = trailingslashit(BASE_PLUGIN_DIR) . 'taxonomy-'.$taxonomy_single.'.php';
} else {
$template = trailingslashit(get_stylesheet_directory()) . 'taxonomy-'.$taxonomy_single.'.php';
}
break;
}
}
return $template;
}
add_filter('template_include','override_tax_template');
</code></pre>
|
Spark Naive Bayes Model - No such method error <p>I'm new to Spark and am trying to run the Naive Bayes Java example in Eclipse. It gives a <strong>No such method</strong> error when trying to save the model. </p>
<pre><code>SparkConf sparkConf = new SparkConf().setAppName("JavaNaiveBayesExample").setMaster("local");
JavaSparkContext jsc = new JavaSparkContext(sparkConf);
String path = "SPARK_HOME\\data\\mllib\\sample_libsvm_data.txt";
JavaRDD<LabeledPoint> inputData = MLUtils.loadLibSVMFile(jsc.sc(), path).toJavaRDD();
JavaRDD<LabeledPoint>[] tmp = inputData.randomSplit(new double[]{0.6, 0.4});
JavaRDD<LabeledPoint> training = tmp[0]; // training set
JavaRDD<LabeledPoint> test = tmp[1]; // test set
final NaiveBayesModel model = NaiveBayes.train(training.rdd(), 1.0);
JavaPairRDD<Double, Double> predictionAndLabel =
test.mapToPair(new PairFunction<LabeledPoint, Double, Double>() {
public Tuple2<Double, Double> call(LabeledPoint p) {
return new Tuple2(model.predict(p.features()), p.label());
}
});
double accuracy = predictionAndLabel.filter(new Function<Tuple2<Double, Double>, Boolean>() {
public Boolean call(Tuple2<Double, Double> pl) {
return pl._1().equals(pl._2());
}
}).count() / (double) test.count();
// Save and load model
model.save(jsc.sc(), "PATH_TO_FOLDER\\myNaiveBayesModel");
NaiveBayesModel sameModel = NaiveBayesModel.load(jsc.sc(), "PATH_TO_FOLDER\\myNaiveBayesModel");
jsc.close();
</code></pre>
<p>The error occurs in <strong>model.save()</strong> line.</p>
<p>The stack trace is as below:</p>
<pre><code>Exception in thread "main" java.lang.NoSuchMethodError: scala.reflect.api.JavaUniverse.runtimeMirror(Ljava/lang/ClassLoader;)Lscala/reflect/api/JavaMirrors$JavaMirror;
at org.apache.spark.mllib.classification.NaiveBayesModel$SaveLoadV2_0$.save(NaiveBayes.scala:205)
at org.apache.spark.mllib.classification.NaiveBayesModel.save(NaiveBayes.scala:170)
at AppMain.main(AppMain.java:42)
</code></pre>
<p>How can I resolve this? Any help is appreciated.</p>
<p>Running Spark 2.0.1 and Scala 2.11.8.</p>
<p>Dependencies added for spark-core_2.11 and spark-mllib_2.10.</p>
| <blockquote>
<p>Dependencies added for spark-core_2.11 and spark-mllib_2.10.</p>
</blockquote>
<p>Please use spark mllib compiled with Scala 2.11 to resolve the issue.</p>
|
Disable expired resharper and restore keybindings <p>I am waiting on licenses to arrive from licensing team for Resharper I have <code>suspended</code> it in <code>Tools -> Options -> ReSharper</code>.</p>
<p>However all the key combinations are still bound to ReSharper. </p>
<p><a href="https://i.stack.imgur.com/lM9CM.png" rel="nofollow"><img src="https://i.stack.imgur.com/lM9CM.png" alt="enter image description here"></a></p>
<p><strong>How do I completely shut down ReSharper and get my old VS keyboard shortcuts?</strong></p>
| <p>Just go to Visual Studio' Tools → Options → Keyboard and click Reset.</p>
|
Rule not recognized in makefile? <p>I have a basic makefile to compile C files necessary for compiling a shared library, I have an error because the makefile is not recognized: </p>
<pre><code> SOURCES=/home/test/project/sources
OBJECTS=/home/test/project/objects
$(OBJECTS)/%.o:$(SOURCES)/%.c
$(CC) -fPIC -c $^ -o $@
sharedlib: $(OBJECTS)/%.o
$(CC) -shared -o libsharedlib.so $<
</code></pre>
<p>When I run make I get that there is no rule for target: <code>$(OBJECTS)/%.o</code> needed by <code>sharedlib</code>. While the rule is written right before sharedlib.</p>
| <p>The main problem is that nowhere you are <em>explicitly</em> telling make what your source files are. Start by doing that:</p>
<pre><code>SOURCEDIR=/home/test/project/sources
SOURCES=$(wildcard $(SOURCEDIR)/*.c)
</code></pre>
<p>Then, derive the object file names from the source file names by substituting <code>.c</code> for <code>.o</code>:</p>
<pre><code>OBJECTDIR=/home/test/project/objects
OBJECTS=$(patsubst $(SOURCEDIR)/%.c,$(OBJECTDIR)/%.o,$(SOURCES))
</code></pre>
<p>You can still keep your generic rule to build object files:</p>
<pre><code>$(OBJECTDIR)/%.o: $(SOURCEDIR)/%.c
$(CC) -fPIC -c $^ -o $@
</code></pre>
<p>But you give the explicit list of object files to the rule to make <code>sharedlib</code>:</p>
<pre><code>libsharedlib.so: $(OBJECTS)
$(CC) -shared -o $@ $<
</code></pre>
<p>Note that I made the name of the rule the same as the file that is being generated. That's important, because calling make twice in a row will then skip building the library a second time. You can always add an alias if you want:</p>
<pre><code>sharedlib: libsharedlib.so
</code></pre>
<p>In that case, it's also good to tell make that <code>sharedlib</code> is not a real file:</p>
<pre><code>.PHONY sharedlib
</code></pre>
<p>This prevents weird things from happening if you ever did have a file called <code>sharedlib</code> in the directory.</p>
|
How to convert properly weekly to shorter span data? <p>I have a data frame of containing weekly time series data.
i need to convert it in daily interpolated values with linear approx.</p>
<pre><code>DATE VALUE1 VALUE2 VALUE3 VALUE4 VALUE5 VALUE6 VALUE7 VALUE8 VALUE9 VALUE10
02-01-2014 95.58 -22.43 73.16 0.09 0.3 1.53 7.14 67.17 7.33 74.5
09-01-2014 113.65 -41 72.65 0.07 0.65 1.77 8.14 65.56 7.47 73.02
16-01-2014 85.87 -15.29 70.59 0.13 0.18 1.78 6.19 65.88 7.5 73.38
</code></pre>
<p>I need to have values for </p>
<pre><code>02-01-2014
03-01-2014
04-01-2014
05-01-2014
06-01-2014
07-01-2014
08-01-2014
09-01-2014
10-01-2014
</code></pre>
<p>any suggestions?</p>
| <p>You could use <code>na.approx</code> function from <code>zoo</code> library for transforming weekly to daily frequency with linear interpolation
for intermediate values</p>
<p>Adapting an example from <code>?zoo</code> page:</p>
<pre><code>library("zoo")
weeklyDF = read.table(text="DATE VALUE1 VALUE2 VALUE3 VALUE4 VALUE5 VALUE6 VALUE7 VALUE8 VALUE9 VALUE10
02-01-2014 95.58 -22.43 73.16 0.09 0.3 1.53 7.14 67.17 7.33 74.5
09-01-2014 113.65 -41 72.65 0.07 0.65 1.77 8.14 65.56 7.47 73.02
16-01-2014 85.87 -15.29 70.59 0.13 0.18 1.78 6.19 65.88 7.5 73.38",header=TRUE,stringsAsFactors=FALSE)
weeklyDF$DATE = as.Date(weekDF$DATE,format="%d-%m-%Y")
weeklyZoo = zoo(x=weeklyDF[,-1],order.by=weeklyDF[,1])
weeklyZoo
# VALUE1 VALUE2 VALUE3 VALUE4 VALUE5 VALUE6 VALUE7 VALUE8 VALUE9 VALUE10
#2014-01-02 95.58 -22.43 73.16 0.09 0.30 1.53 7.14 67.17 7.33 74.50
#2014-01-09 113.65 -41.00 72.65 0.07 0.65 1.77 8.14 65.56 7.47 73.02
#2014-01-16 85.87 -15.29 70.59 0.13 0.18 1.78 6.19 65.88 7.50 73.38
dailyZoo = na.approx(weeklyZoo, xout = seq(start(weeklyZoo), end(weeklyZoo), by = "day"))
dailyZoo
# VALUE1 VALUE2 VALUE3 VALUE4 VALUE5 VALUE6 VALUE7 VALUE8 VALUE9 VALUE10
#2014-01-02 95.58000 -22.43000 73.16000 0.09000000 0.3000000 1.530000 7.140000 67.17000 7.330000 74.50000
#2014-01-03 98.16143 -25.08286 73.08714 0.08714286 0.3500000 1.564286 7.282857 66.94000 7.350000 74.28857
#2014-01-04 100.74286 -27.73571 73.01429 0.08428571 0.4000000 1.598571 7.425714 66.71000 7.370000 74.07714
#2014-01-05 103.32429 -30.38857 72.94143 0.08142857 0.4500000 1.632857 7.568571 66.48000 7.390000 73.86571
#2014-01-06 105.90571 -33.04143 72.86857 0.07857143 0.5000000 1.667143 7.711429 66.25000 7.410000 73.65429
#2014-01-07 108.48714 -35.69429 72.79571 0.07571429 0.5500000 1.701429 7.854286 66.02000 7.430000 73.44286
#2014-01-08 111.06857 -38.34714 72.72286 0.07285714 0.6000000 1.735714 7.997143 65.79000 7.450000 73.23143
#2014-01-09 113.65000 -41.00000 72.65000 0.07000000 0.6500000 1.770000 8.140000 65.56000 7.470000 73.02000
#2014-01-10 109.68143 -37.32714 72.35571 0.07857143 0.5828571 1.771429 7.861429 65.60571 7.474286 73.07143
#2014-01-11 105.71286 -33.65429 72.06143 0.08714286 0.5157143 1.772857 7.582857 65.65143 7.478571 73.12286
#2014-01-12 101.74429 -29.98143 71.76714 0.09571429 0.4485714 1.774286 7.304286 65.69714 7.482857 73.17429
#2014-01-13 97.77571 -26.30857 71.47286 0.10428571 0.3814286 1.775714 7.025714 65.74286 7.487143 73.22571
#2014-01-14 93.80714 -22.63571 71.17857 0.11285714 0.3142857 1.777143 6.747143 65.78857 7.491429 73.27714
#2014-01-15 89.83857 -18.96286 70.88429 0.12142857 0.2471429 1.778571 6.468571 65.83429 7.495714 73.32857
#2014-01-16 85.87000 -15.29000 70.59000 0.13000000 0.1800000 1.780000 6.190000 65.88000 7.500000 73.38000
</code></pre>
|
How can you do SQL joins on dates between specific dates? <p>This may be incredibly hard or incredibly simple, I don't know which but I'm stuck.</p>
<p>How do I join data that happened between specific days? How do I write that? The tricky thing is that every row would have a different time period, a unique period for every user. Example:</p>
<p>Table A
<a href="https://i.stack.imgur.com/7w0j9.png" rel="nofollow"><img src="https://i.stack.imgur.com/7w0j9.png" alt="enter image description here"></a></p>
<p>Table B</p>
<p><a href="https://i.stack.imgur.com/D5ZWb.png" rel="nofollow"><img src="https://i.stack.imgur.com/D5ZWb.png" alt="enter image description here"></a></p>
<p>Table C (the one I would like to get)</p>
<p><a href="https://i.stack.imgur.com/Axxbe.png" rel="nofollow"><img src="https://i.stack.imgur.com/Axxbe.png" alt="enter image description here"></a></p>
<p>I am using Google BigQuery if anyone is wondering</p>
| <p>Below is for BigQuery Standard SQL (see <a href="https://cloud.google.com/bigquery/sql-reference/enabling-standard-sql" rel="nofollow">Enabling Standard SQL</a>) </p>
<pre><code>SELECT
a.User_Id, Start_date, End_Date,
(SELECT IFNULL(SUM(clicks),0) FROM TableB WHERE user_Id = a.User_Id
AND date BETWEEN Start_date AND End_date) AS Clicks_from_tableB
FROM TableA AS a
ORDER BY user_Id
</code></pre>
<p>or </p>
<pre><code>SELECT
a.User_Id, Start_date, End_Date,
SUM(IFNULL(clicks, 0)) AS Clicks_from_tableB
FROM TableA AS a
LEFT JOIN TableB AS b
ON a.User_Id = b.User_Id
AND b.date BETWEEN Start_date AND End_date
GROUP BY 1, 2, 3
ORDER BY user_Id
</code></pre>
|
Mail Merge several similar attachments in one email <p>I need to send request forms to GP Practices in the area for patient information, and many of them want it in email. There are usually more than one requests per practice.
I have an Excel file with the base demographics of the patients, the practices' code and email address. The Mail Merge works perfectly fine for the ones who want them in snailmail, the output of the merge is OK.</p>
<p>To the ones who want it electronically, I would like to send the single email with either
A: in one email multiple different attachments (one attachment per single page request form)
B: one attachment with every merged form on a different page (I assume I would need to change the form), automatically sent to the email addresses.</p>
<p>I would need to be able to customise the subject field (either a fix one, they don't need to be different for every email, or I can just add a column to the Excel file).</p>
<p>The Merge could potentially done separately, and the individual documents saved with a filename like "GP Practice - Patient Number". This would allow a program/script to differentiate between the attachment but know which ones to group, but I still don't know how to approach this. </p>
<p>Every option I've come across requires me to install a third party program (an .exe file) which I cannot do on the Trust's computers, or sends all attachments separately (Practice staff probably won't be happy with 10-30 new emails flooding their account).</p>
<p>Any suggestions?</p>
<p>Thanks very much.</p>
| <p>Partial answer to show the loop structure to add one or more attachments. This adds one or more reports to an email based on a <code>FileCell.Value</code> and builds the location and detail of the file in the first part of the code.</p>
<pre><code>For Each FileCell In Rng.SpecialCells(xlCellTypeConstants)
myloop = myloop + 1
If Dir(FileCell.Value) <> "" Then
If Dir(strLocation) <> "" Then
strAddMe = strLocation & FileCell.Value & strNamePart & ".docx"
strAddMeToo = strLocation & FileCell.Value & strNameMissing & ".xlsx"
If myloop > 1 Then
.Subject = "All Reports"
Else
.Subject = "Single Report: " & FileCell.Value
End If
.Attachments.Add strAddMe
.Attachments.Add strAddMeToo
End If
End If
Next FileCell
</code></pre>
|
Using lambda in default initializer gcc vs clang <pre><code>#include <cassert>
int main()
{
struct point_of_parabaloid
{
double x, y;
double z = [&] { return x * x + y * y; }();
};
point_of_parabaloid p = {1.0, 2.0};
assert(p.z == 5.0);
}
</code></pre>
<p>Works fine for <code>clang++</code> from trunk, but for <code>g++</code> from trunk fails with error message (<a href="http://melpon.org/wandbox/permlink/jte2oFAbGp8cWD3D" rel="nofollow">link</a>):</p>
<blockquote>
<p>error: 'this' was not captured for this lambda function</p>
</blockquote>
<p>Definition of <code>point_of_parabaloid</code> in namespace scope works fine for both.</p>
<p>Slightly modified definition with <code>[this]</code> lambda capture works fine also for both in either global or local scope.</p>
<p>Which compiler is right?</p>
| <p>That's a gcc bug.</p>
<pre><code>int main() {
struct A {
int x, i = [&] { return x; }();
} a{0};
}
</code></pre>
<p>This fails, but if weâ¦</p>
<ul>
<li>change <code>&</code> to <code>this</code>, or</li>
<li>declare <code>A</code> as having namespace scope,</li>
</ul>
<p>it works. Neither of these should have any effect on the well-formedness, though.</p>
<p>Reported: <a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78019" rel="nofollow">#78019</a>.</p>
|
One XMPP connection for more than one GCM/FCM app <p>I have a bunch of <code>FCM</code> projects and I'd like to use the same XMPP connection to send messages for all those projects. The <code>FCM</code> <a href="https://firebase.google.com/docs/cloud-messaging/server#implementing-the-xmpp-connection-server-protocol" rel="nofollow">docs</a> say that each connection needs to authenticate with the app id and server key, meaning I can use one XMPP connection for one project only. Is there any way around this?</p>
| <p>I'm not sure what the question is here. Just use the corresponding Sender ID and Server Key from your Firebase Project. However, do note of the connection limitation mentioned in the docs you linked:</p>
<blockquote>
<p>For each sender ID, FCM allows 1000 connections in parallel.</p>
</blockquote>
<p>I don't really see any issue here, so long as you're using the same Firebase Project for FCM on all of your apps, you're good to go.</p>
<p>Unfortunately, if you have multiple projects, the only workaround I can only see that you can do is for you to use only a single project for your FCM processes.</p>
|
Relationship and referential integrity constraint using JPA <p>I started to design my Java EE application using MySQL and JPA for persistence, so I have a doubt to how implent it for database design.</p>
<p>So I defined my database tables e.g: employees and departments with his relationship</p>
<p>Using JPA I defined relationship following some tutorials but I can't understand if foreign keys and constraints have to be defined too for database tables or left it without as:</p>
<pre><code>CREATE TABLE `thejavageek`.`employee` (
`idemployee` INT NOT NULL,
`firstname` VARCHAR(45) NULL,
`lastname` VARCHAR(45) NULL,
# ...
PRIMARY KEY (`idemployee`)
);
</code></pre>
<p>And JPA entities:</p>
<pre><code>@Entity
public class Employee{
@Id
@GeneratedValue( strategy= GenerationType.AUTO )
private int eid;
private String ename;
private double salary;
private String deg;
@ManyToOne
private Department department;
public Employee(int eid, String ename, double salary, String deg) {
super( );
this.eid = eid;
this.ename = ename;
this.salary = salary;
this.deg = deg;
}
public Employee( ) {
super();
}
public int getEid( ) {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname( ) {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getSalary( ) {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDeg( ) {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
@Entity
public class Department {
@Id
@GeneratedValue( strategy=GenerationType.AUTO )
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName( ){
return name;
}
public void setName( String deptName ){
this.name = deptName;
}
}
</code></pre>
<p>lefting relationship and constraint management to JPA?</p>
<p>thanks in advance!</p>
| <p>In your code system will create a new table by name <code>employee_department_mapping</code> (with <code>employee_id</code>, <code>department_id</code> columns in it) which will contain a mapping of every employee to its department.</p>
<p>However, if you want to handle it as a foreign key in employee table, mark your <code>department</code> field with <code>@JoinColumn</code> and tell the name of foreign key column</p>
<pre><code>@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
</code></pre>
<p>And set <code>hibernate.hbm2ddl.auto</code> to <code>update</code></p>
<p>Now if you will restart the application, it will automatically generate the foreign key column by name department_id in the employee table.</p>
|
Rest api documentation automatic generation <p>I recently started recearching the Rest API documentation and i am really interested in automatic documentation of my APIs. </p>
<p>Are there any automatic tools that can generate documentation for standard methods of an API? I am particullary interested in open source tools but i wouldn't say no to a paid solution if it fits my needs. Also a huge plus would be if an automatic xml documentation was included.</p>
<p>Are there any solutions that would make the documentation fun and easy to use?</p>
| <p>There are many options available that will do this. <a href="https://opencredo.com/rest-api-tooling-review/" rel="nofollow">This article</a> provides a list of a small number of popular options:</p>
<ul>
<li><a href="http://swagger.io/" rel="nofollow">Swagger</a></li>
<li><a href="https://projects.spring.io/spring-restdocs/" rel="nofollow">Spring REST Docs</a></li>
<li><a href="https://raml.org/" rel="nofollow">RAML</a></li>
<li><a href="http://apidocjs.com/" rel="nofollow">ApiDocJS</a></li>
<li><a href="https://bitbucket.org/tritales/springrestdoc/overview" rel="nofollow">SpringRestDoc</a></li>
</ul>
<p>Googling for "self documenting REST framework" gives many more options. I recommend you do some research on each option and I'm sure you will find one that fits your needs.</p>
|
NSexception with sigbart error <p>I am trying to fetch the result from json web service. For string values it is working fine. When I try to fetch the integer value It throwing nsexeption with sigbart error.</p>
<p>My json result loos like this.</p>
<pre><code>[{"CaseId":81,"ApplicantName":"test","ApplicantContactNo":"teas","PropertyAddress":"ewae","BankName":"Bank of India","ReportDispatcher":null,"PropertyType":"test","AssignedAt":"2016-10-07T13:01:20","Status":"Open","PropertyId":62,"EmployeeName":null,"StatusId":1}
</code></pre>
<p>When I try to capture the CaseId and AssignedAt it throwing error.</p>
<p>here is my code.</p>
<pre><code>NSString * caseid = @"CaseId";
NSString * assigned = @"AssignedAt";
for (NSDictionary *dataDict in jsonObjects) {
NSString *caseid1 = [dataDict objectForKey:@"CaseId"];
NSString *assigned1 = [dataDict objectForKey:@"AssignedAt"];
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
caseid1,caseid,assigned1,assigned, nil];
[myObject addObject:dictionary];
}
cell.caseid.text=[tmpDict objectForKey:@"CaseId"];
cell.days.text=[tmpDict objectForKey:@"AssignedAt"];
</code></pre>
<p>Any help will be appreciated.</p>
| <p>This should work for you:</p>
<pre><code>NSString *caseIdValue = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"CaseId"]];
NSString *assignedAtValue = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"AssignedAt"]];
</code></pre>
|
Empty Multiple UILabel values <p>I have multiple uilabels values.
I need to empty the UILabels self.lbl_title when I click on button NEXT.</p>
<p>How can I do this?</p>
<p><code>self.lbl_title.hidden=true</code> not working in this case.</p>
<pre><code>-(void)fetchdata
{
int y=10;
if(arrayquestion.count!=0){
for (int i=0;i<arrayquestion.count;i++)
{
CGSize textsize = [[[arrayquestion objectAtIndex:i] valueForKey:@"question_title"] sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(850, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
self.lbl_title=[[UILabel alloc] init];
self.lbl_title.frame= CGRectMake(60,y-3,900,textsize.height+5);
self.lbl_title.text=[[arrayquestion objectAtIndex:i] valueForKey:@"question_title"];
self.lbl_title.backgroundColor=[UIColor clearColor];
self.lbl_title.numberOfLines=0;
self.lbl_title.font=[UIFont systemFontOfSize:18];
y=y+textsize.height+30;
[self.scrll_vw addSubview:self.lbl_title];
}
}
else{
NSLog(@"%s","Yes");
self.lbl_title.hidden = YES;
}
}
-(IBAction)Next:(id)sender
{
[arrayquestion removeAllObjects];
[self fetchdata];
}
</code></pre>
| <p>If you want to just clear the label text, you can use </p>
<pre><code>self.lbl_title.text = @"";
</code></pre>
|
Crash accesing a string inside pointer stored in vector <p>I cannot imagine a single reason for this... here is my base class</p>
<pre><code>class TextureElement
{
public:
TextureElement(std::wstring mname);
std::wstring file;
std::wstring name;
TexMode texmode;
};
</code></pre>
<p>And this is a basic usage:</p>
<pre><code>TextureElement* textureElement = new TextureElement(prename);
mClass->textures.push_back(textureElement);
textureElement->file = path;//<<here crashes if inheritance is done
</code></pre>
<p>obviously prename and path are wstrings, mstruct mClass contains several vectors including this one that stores TextureElement* type</p>
<p>This works ok but if I inherit TextureElement from Element</p>
<pre><code>class Element
{
public:
Element(std::wstring mname, ElementType t);
Element(){};
~Element();
ElementType type;
std::wstring name;
};
</code></pre>
<p>It crashes.</p>
<p>I've tried implementing copy method for TextureElement (I was almost sure it was unnecessary) but it didn't worked.
Any idea on this? Thank you in advance</p>
| <p>If you are inheriting from <code>Element</code>, you may want to declare a <strong><code>virtual</code> destructor</strong> for proper cleanup:</p>
<pre><code>virtual ~Element() {}
</code></pre>
<p>Moreover, pay attention when you put <em>raw owning pointers</em> in <code>std::vector</code>. Consider a vector of <em>smart</em> pointers, like <code>vector<unique_ptr<T>></code> or <code>vector<shared_ptr<T>></code> instead.</p>
<hr>
<p><strong>EDIT</strong></p>
<p>This code compiles just fine and seems to work (tested on VS2015 with Update 3):</p>
<pre><code>#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
enum class ElementType
{
Texture,
Foo,
Bar
};
class Element
{
public:
Element(const wstring& name, ElementType type)
: Name(name), Type(type)
{}
virtual ~Element() {}
ElementType Type;
wstring Name;
};
class TextureElement : public Element
{
public:
explicit TextureElement(const wstring &name)
: Element(name, ElementType::Texture)
{}
wstring File;
};
int main()
{
vector<shared_ptr<Element>> v;
auto p = make_shared<TextureElement>(L"Test");
v.push_back(p);
p->File = L"C:\\Some\\File";
wcout << p->File;
}
</code></pre>
|
How to add property "Alternate" to an image file on server? <p>I'm using asp.net core and web api for uploading images.</p>
<p>On server:</p>
<pre><code>[Produces("application/json")]
[Route("api/Upload")]
public class UploadApiController : Controller
{
private readonly IHostingEnvironment _environment;
public UploadApiController(IHostingEnvironment environment)
{
_environment = environment;
}
[HttpPost]
public async Task Post(ICollection<IFormFile> files)
{
//...
}
}
</code></pre>
<p>On client:</p>
<pre><code>// Files is an array that contains all temporary images for uploading.
let Files = [];
let image_preview = function (file) {
file['Alternate'] = 'alternate_text';
Files.push(file);
// other implements...
};
$('button#upload').click(function () {
let formData = new FormData();
for (let i = 0; i < Files.length; i++) {
formData.append('files', Files[i])
}
let xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload', true);
xhr.onload = function () {
console.log('uploading...')
};
xhr.send(formData);
});
</code></pre>
<p>Snapshot:</p>
<p><a href="https://i.stack.imgur.com/IkqHO.png" rel="nofollow"><img src="https://i.stack.imgur.com/IkqHO.png" alt="1"></a></p>
<p>My question: how to add new property "Alternate" to <code>ICollection<IFormFile> files</code> to detect property <code>Alternate</code> that is sent from client (formData)?</p>
| <p>It's not the answer for question <code>How to add property âAlternateâ to an image file on server?</code> but it seems like solving the problem (sending image file with alternate text).</p>
<p>On server:</p>
<pre><code>using Newtonsoft.Json;
[HttpPost]
public async Task Post(ICollection<IFormFile> files, IList<string> alts)
{
IDictionary<string, string> _alts = new Dictionary<string, string>();
foreach (var alt in alts)
{
IDictionary<string, string> temp = JsonConvert.DeserializeObject<Dictionary<string, string>>(alt);
foreach (var item in temp)
{
_alts.Add(item.Key, item.Value);
}
}
}
</code></pre>
<p>On client:</p>
<pre><code>for (let i = 0; i < Files.length; i++) {
formData.append('files', Files[i]);
let name = Files[i]['name'],
alt = {};
alt[name] = 'alt_text';
formData.append('alts', JSON.stringify(alt));
}
</code></pre>
<p>We would never get duplicate key in the dictionary because <code>Files[i]['name']</code> is always primary and cannot be changed (hacking by someone) if we've checked duplicate uploading file before.</p>
<p>Then, we can merge the file name (in <code>files</code>) with <code>Key</code> in <code>_alts</code> to get Alternate text.</p>
<p>Snapshot:</p>
<p><a href="https://i.stack.imgur.com/5ckDC.png" rel="nofollow"><img src="https://i.stack.imgur.com/5ckDC.png" alt="2"></a></p>
<p><strong>UPDATE:</strong> The code in the snapshot was wrong.</p>
|
Spring Boot - webservice: Connection Refused <p>I am trying to implement spring boot webservice application as given in spring docs :</p>
<p><a href="https://spring.io/guides/gs/consuming-web-service/" rel="nofollow">https://spring.io/guides/gs/consuming-web-service/</a></p>
<p>Build was successful, request and response java files was created and , but when executed spring-boot:run , it gives </p>
<pre><code>Caused by: org.springframework.ws.client.WebServiceIOException: I/O error: Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:561)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)
at hello.WeatherClient.getCityForecastByZip(WeatherClient.java:30)
at hello.Application.main(Application.java:20)
</code></pre>
<p>But the URL is accessible via web browser in eclipse. Kindly help me solve this issue</p>
| <p>The web Service URL you are trying to call may be not reachable or it gets timeout. Ensure the web Service URL path is correct and is listening. also verify the timeout duration set and the time taken from your request.</p>
<p><code>PS. Also check if there is some firewall issue at Server side.</code></p>
<p>For firewall issue, you might need to provide proxy details(proxyHost and proxyPort) In client code.</p>
<p>EDIT:</p>
<p>I am not able to find appropriate blog or something which explains it better. but found one question on stackoverflow which has similar answer : <a href="http://stackoverflow.com/questions/33543414/spring-mvc-giving-connection-refused-when-connecting-to-rest-service-with-https">here</a> </p>
|
Rails 4, SQ Lite 3: Access model through model without an association <p>I've got two tables:<br><br>
<em>item</em><br>
<em>recipe</em><br><br></p>
<p>In this example I've got an item object <code>item</code> with the id <code>1</code>.
The <code>item</code> table has one column named <code>recipe_id</code>. For this object it has the value <code>2</code>.<br><br>
<code>recipe</code> has a column named <code>title</code>.<br><br>
How can I get for example the <code>title</code> from the <code>recipe</code> of which the <code>id</code> is linked in <code>item</code>, if I have the item?<br><br>
Something like...?</p>
<pre><code>= item.recipe_id.title
</code></pre>
<p>Thanks in advance for any help!</p>
| <p>you'd use your own SQL to find records in a tableusing find_by_sql. The find_by_sql method will return an array of objects even if the underlying query returns just a single record. For example you could run this query:</p>
<p>for example </p>
<pre><code> Recipe.joins("INNER JOIN item ON <your_conditions_to_get_recipe_related_to_item>")
</code></pre>
<p>or</p>
<pre><code> Recipe.find_by_sql("SELECT * FROM recipe
INNER JOIN item ON <your_conditions_to_get_recipe_related_to_item>")
</code></pre>
<p>acording to your case</p>
<p>for example </p>
<pre><code> Recipe.joins("INNER JOIN item ON item.recipe_id = recipe.id and item.id = 1 and recipe.id = 2")
</code></pre>
<p>with params</p>
<pre><code> Recipe.joins("INNER JOIN item ON item.recipe_id = recipe.id").where("item.id = ? and recipe.id = ?", item_id, recipe_id)
</code></pre>
<p>these are some ways to access to the database and retrieve a model or models instances without associations ways.</p>
|
Retrieve Just A Element From Mongodb <p>I'm trying to retrieve just a lesson from a classes collection based on it's id. I put together the following from previous answers, but it doesn't return anything. Can someone point me in the right direction?</p>
<p><em>My Code</em></p>
<pre><code>Class.aggregate([
{$match: {'lessons._id': id}},
{$project: {
lessons: {$filter: {
input: '$lessons',
as: 'lesson',
cond: {$eq: ['$$lesson._id', id]}
}},
_id: 0
}}
])
</code></pre>
<p><em>Example</em></p>
<pre><code>{
"_id" : ObjectId("14354"),
"title" : "Easy Math",
"instructor_id" : "2454",
"lessons" : [
{
"lesson_body" : "2 + 2 = 4",
"lesson_title" : "Addition",
"_id" : ObjectId("3456")
},
{
"lesson_body" : "4 - 2 = 2",
"lesson_title" : "Subtraction",
"_id" : ObjectId("4456")
}
],
"__v" : 0
}
{
"_id" : ObjectId("5345"),
"title" : "Harder Math",
"instructor_id" : "6345",
"lessons" : [
{
"lesson_body" : "2 * 2 = 4",
"lesson_title" : "Multiplication",
"_id" : ObjectId("7454")
}
],
"__v" : 0
}
</code></pre>
| <p>Shouldn't it be <code>lessons</code> instead of <code>lesson</code></p>
<p>on this line :
<code>cond: {$eq: ['$$lessons._id', id]}</code></p>
|
FFMPEG binaries throw error : Undefined Symbols for Architecture x86_64 <p>I have created a cocoa app that uses FFMPEG libraries for streaming.</p>
<p>Uptill now i was using FFMPEG version 3.1.1 and i had libraries available to me. Now i downloaded the latest FFMPEG version 3.1.4.</p>
<p>I executed the shell script and libraries were generated but when i use the with my xcode [6.1 or any] I get error as shown in attached image.</p>
<p>Can anybody plz guide me about solving this issue.</p>
<p>Thanks in advance..</p>
<p><a href="https://i.stack.imgur.com/mJb3c.png" rel="nofollow"><img src="https://i.stack.imgur.com/mJb3c.png" alt="enter image description here"></a></p>
<p>Other Linker Flags :</p>
<p><a href="https://i.stack.imgur.com/yrwfo.png" rel="nofollow"><img src="https://i.stack.imgur.com/yrwfo.png" alt="enter image description here"></a></p>
| <p>I added Frameworks :</p>
<p>AudioToolBox.framework and VideoToolBox.framework</p>
<p>How i understood : Undefined symbol for architecture x86_64 : <strong>A</strong> referenced from <strong>B</strong> in <strong>xyz.o</strong></p>
<p>Add <strong>xyz.framework</strong></p>
<p>and its Done :)</p>
|
Cant get @media screen to work <p>Earlier I asked question about my profile design, I am said I was not gone use the same design on mobile phone but I've changed my mind, howere i use <code>height:10%;</code> on the banner in the main style but when using <code>@media all and (max-width:1024;){}</code> and having same class but with <code>height:30%;</code> it wont change. I have a different css where I do the same thing but there it works (most of the times).</p>
<p>html:</p>
<pre><code><?php if($user_visible == 'a'){ ?>
<!--Profile picture, banner, and main information-->
<div class="profile-wrapper">
<?php if(isset($user_avatar)){ echo'<img class="banner" src="/assets/images/banner/'.$user_banner.'" />'; }else{ echo'<img class="banner" src="/assets/images/banner/default.png" />'; }?>
<!--profile picture-->
<?php if(isset($user_avatar)){ echo'<img class="avatar" src="/assets/images/users/'.$user_avatar.'" />'; }else{ echo'<img class="avatar" src="/assets/images/users/default.png" />'; }?>
<!--user information-->
<div class="user-information">
<p><?php echo $user_name; ?><br />
<?php echo $user_firstname; ?>&nbsp;<?php echo $user_lastname; ?></p>
</div>
</div>
</code></pre>
<p>css:</p>
<pre><code>/* **************************************************************************************
///////////////////////Main Style////////////////////////////////////////////////////////
**************************************************************************************Â */
@media all and (min-width:1024px;) {
.avatar {
border: 2px solid #fff;
border-radius:5px;
margin-top:-10%;
margin-left: 5%;
width:15%;
height:auto;
}
.banner {
border: 2px solid #fff;
border-radius:5px;
margin-top: 20px;
height:10%;
width:100%;
}
.profile-wrapper {
margin:0 auto;
width:90%;
}
}
/* **************************************************************************************
///////////////////////Tablet////////////////////////////////////////////////////////////
**************************************************************************************Â */
@media all and (max-width: 1024px) {
.banner { height:30%; }
}
/* **************************************************************************************
///////////////////////Phone/////////////////////////////////////////////////////////////
**************************************************************************************Â */
@media all and (max-width: 768px) {
.banner { height:30%; }
}
</code></pre>
| <p>These are the most universal media queries out there as they will help you to cover most of the different screen sizes decently:</p>
<pre><code>@media(max-width:767px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}
</code></pre>
<p>So try these media queries for your banner:</p>
<pre><code> @media(min-width:992px){
.banner {
height: 30%;
}
}
@media(min-width:1200px){
.banner {
height: 10%;
}
}
</code></pre>
|
php preg_match_all avoid quotation mark <p>inside Moodle core, when sending a query to the database there's a call to <strong>preg_match_all</strong> looking for : (colon), in order to find query's parameters. </p>
<p>I have a string (inside " ") composed of digits, a colon and a letter <strong>("102516101:t")</strong>.</p>
<p>Of course it's not impling for a parameter. still the Moodle expects one because of the colon(:).</p>
<p>How can I prevent <strong>preg_match_all</strong> looking inside a Quotation mark?
or has anyone gut another idea?</p>
| <p>According to the comments left above, you should explicity specify the variables used in your SQL statement. In other words you should not be constructing your SQL statement by hand, or the minimum required.</p>
<p>Example:</p>
<pre><code>$sql = "SELECT * FROM {groups} WHERE name = :name";
$params = array('name' => '102516101:t');
$DB->execute($sql, $params);
</code></pre>
<p>You'll also note that table names are specified like this: <code>{table_name}</code>, they are automatically expanded with the right prefix.</p>
|
[Ansible][Fedora 24] DNF Module Requires python2-dnf but it is Already Installed <p>I have computers on an internal network that is not connected to the internet, and have copied the relevant rpm packages into my local dnf repository. I'm trying to get ansible's DNF module to install a program on another computer but it pops up an error message stating that python2-dnf is not installed. But when I try to install the program it is already installed. Anyone have an idea whats going wrong?</p>
<p>I've placed the error code below.</p>
<hr>
<p>Background: </p>
<pre><code>Ansible Control machine: Fedora 24 4.5.5-300.fc24.x86_64 GNU/LINUX
Ansible Client machine: Fedora 24 4.5.5-300.fc24.x86_64 GNU/LINUX
yum/dnf local repository: Centos 7 3.10.0-327.28.3.el7.x86_64 GNU/LINUX
</code></pre>
<hr>
<p>[root@localhost ansible]# ansible all -m dnf -a "name=vim state=present" </p>
<pre><code>192.168.10.10 | FAILED! => {
"changed": false,
"failed": true
, "msg": "python2-dnf is not installed, but it is required for the Ansible dnf module."
}
</code></pre>
<p>[root@localhost ansible]# yum install python2-dnf </p>
<pre><code>Yum command has been deprecated, redirecting to '/usr/bin/dnf install python2-dnf'.
See 'man dnf' and 'man yum2dnf' for more information.
To transfer transaction metadata from yum to DNF, run:
'dnf install python-dnf-plugins-extras-migrate && dnf-2 migrate'
Last metadata expiration check: 0:12:08 ago on Tue Oct 18 04:57:11 2016.
Package python2-dnf-1.1.9-2.fc24.noarch is already installed, skipping.
Dependencies resolved.
Nothing to do.
Complete!
</code></pre>
| <p>As pointed out by @GUIDO you need <code>python2-dnf</code> on the target host.</p>
<p><a href="http://docs.ansible.com/ansible/dnf_module.html" rel="nofollow">Ansible module documentation</a> states:</p>
<blockquote>
<p>Requirements (on host that executes module)</p>
<pre><code> python >= 2.6
python-dnf
</code></pre>
</blockquote>
<p><em>on host that executes module</em> means in the context of <code>Ansible</code> the <em>target</em> host of the play, not the control host.</p>
|
Product files not deleting after WIX upgrade <p>We use a managed bootstrapper.</p>
<p>We have two products in our bundle (let's call it <code>BundleName</code>) - <code>ProductA</code> and <code>ProductB</code>.
We install both products and it works fine.</p>
<p>Next we change a version of <code>BundleName</code> from <code>1.0.0.0</code> to <code>2.0.0.0</code> and the MSI version of <code>ProductA</code> from <code>1.0.0.0</code> to <code>2.0.0.0</code>.</p>
<p>Performing upgrade. It completes successfully but in the log of <code>BundleName 1.0.0.0</code> (previous version of bundle that should be uninstalled) we have:</p>
<pre><code>Will not uninstall package: ProductA, found dependents: 1
Found dependent: {ffe63ad2-5155-4958-91cc-b0aac330cdb6}, name: BundleName
Will not uninstall package: ProductB, found dependents: 1
Found dependent: {ffe63ad2-5155-4958-91cc-b0aac330cdb6}, name: BundleName
</code></pre>
<p>Nevertheless, it works fine.</p>
<p>The problem appears when we remove the upgraded <code>2.0.0.0 BundleName</code>. The bundle removes it successfully and logs are clear, <strong>but it does not remove any files and registry keys of <code>ProductA</code>.</strong></p>
<p>One more thing we noticed in <code>2.0.0.0</code> logs also a bit strange:</p>
<p><code>Planned package: ProductA, state: Present, default requested: Present, ba requested: Present, execute: **MinorUpgrade**, rollback: None, cache: Yes, uncache: Yes, dependency: Register</code></p>
<p>We changed the first number of version, so it should be <code>MajorUpgrade</code> not <code>MinorUpgrade</code>.</p>
<p>Here is our configuration:</p>
<pre><code><Product
Id="$(var.ProductCode)"
UpgradeCode="$(var.UpgradeCode)"
Name="$(var.ProductName)"
Language="1033"
Version="$(var.ProductVersion)"
Manufacturer="$(var.Manufacturer)">
<Upgrade Id="$(var.UpgradeCode)" />
<MajorUpgrade DowngradeErrorMessage="A newer version of $(var.ProductName) is already installed."
Schedule="afterInstallInitialize"
AllowSameVersionUpgrades="yes" />
...
</code></pre>
<p>Could somebody please explain what we missed out?</p>
| <p>Found the problem.
<code>ProductCode</code> in <code>Product</code> element was fixed, not <code>*</code>.</p>
<p><a href="http://wixtoolset.org/documentation/manual/v3/howtos/updates/major_upgrade.html" rel="nofollow">How To: Implement a Major Upgrade In Your Installer</a></p>
<p><a href="http://wixtoolset.org/documentation/manual/v3/howtos/general/generate_guids.html" rel="nofollow">How To: Generate a GUID</a></p>
|
Mamp localhost on mac not working correctly <p>I need to make my localhost have openssl so i follow this steps here: </p>
<p><a href="https://gist.github.com/jonathantneal/774e4b0b3d4d739cbc53" rel="nofollow">https://gist.github.com/jonathantneal/774e4b0b3d4d739cbc53</a></p>
<p>After following steps the mamp home page is working fine:
<a href="https://localhost/MAMP/?language=English" rel="nofollow">https://localhost/MAMP/?language=English</a></p>
<p>but when trying <a href="https://localhost/anysite" rel="nofollow">https://localhost/anysite</a> or <a href="https://localhost" rel="nofollow">https://localhost</a> is not working</p>
<p>How can i solve it please? thank you.</p>
| <p>Solved!
add this inside Applications/MAMP/conf/apache/httpd.conf</p>
<pre><code>Alias /Yoursite "/Applications/MAMP/htdocs/yoursite"
<Directory "/Applications/MAMP/htdocs/yoursite">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</code></pre>
|
Running R script in Java <p>I have a working R script which creates a .csv file and I want that script to run in java.
I'm using <code>Rcaller</code> for that. Somewhere on SO I got code similar to this.</p>
<pre><code>Random random = new Random();
RCaller caller = new RCaller();
RCode code = new RCode();
caller.setRscriptExecutable("C:\\Program Files\\R\\R-3.3.1\\bin\\Rscript.exe");
code.R_require("TTR");
code.R_source("C:\\Users\\lenovo\\Desktop\\R_trial\\script.R");
caller.runOnly();
</code></pre>
| <p>Sure, you can do it with:</p>
<p><code>Runtime.getRuntime().exec("Rscript myScript.R");</code></p>
<p>Answered already <a href="http://stackoverflow.com/questions/8844451/calling-r-script-from-java">here</a></p>
|
Deserializing JSON Object containing another object <p>I'm trying to deserialize this JSON string using Newtonsoft.Json library. But the returned deserialized object allways returns null. I think it's related to the address object inside the player object.</p>
<p>This is the JSON string</p>
<pre><code>{
"player":{
"id":"ed704e61-f92b-4505-b087-8a47ca4d1eaf",
"firstName":"Jack",
"lastName":"Russel",
"nickname":"Barky",
"dateOfBirth":"1995-08-16T00:00:00",
"sex":"m",
"address":{
"street":"Elmstreet",
"number":"5",
"alphaNumber":"",
"poBox":"",
"postalCode":"90001",
"city":"Los Angeles",
"country":"United States"
},
"email":[
"barky@dog.com",
"barky@mydogpension.com"
],
"phone":[
"0123 45 67 89 10"
]
},
"requestReference":2000,
"requestStatus":"Request OK",
"requestDetails":null
}
</code></pre>
<p>These are the RootObject, Player and Address classes. It's the RootObject's Player object which keeps returning a null value for the JSON string above. So upon calling offcourse a nullreference exception is being thrown:</p>
<pre><code>public class RootObject
{
public Player player { get; set; }
public int requestReference { get; set; }
public string requestStatus { get; set; }
public string requestDetails { get; set; }
}
public class Address
{
public string street { get; set; }
public string number { get; set; }
public string alphaNumber { get; set; }
public string poBox { get; set; }
public string postalCode { get; set; }
public string city { get; set; }
public string country { get; set; }
}
public class Player
{
public Guid id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string nickname { get; set; }
public DateTime dateOfBirth { get; set; }
public string sex { get; set; }
public Address address { get; set; }
public List<string> email { get; set; }
public List<string> phone { get; set; }
}
</code></pre>
<p>This is the line of code used to Deserialize:</p>
<p><code>RootObject playerRoot = JsonConvert.DeserializeObject<RootObject>(_the_json_string_shown_above);</code></p>
| <p>I was using Newtonsoft.Json 8.0.2.19309.
I had to add a JsonProperty attribute to the Address object inside the Player class. Then the object gets deserialized just fine.</p>
<pre><code>public class Player
{
public Guid id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string nickname { get; set; }
public DateTime dateOfBirth { get; set; }
public string sex { get; set; }
[JsonProperty]
public Address address { get; set; }
public List<string> email { get; set; }
public List<string> phone { get; set; }
}
</code></pre>
|
Turn textbox text into string with code in it <p>So I've made a function called <code>Something(string text)</code> that needs a <code>string</code>.
Now I have a button that onclick does <code>Something(textBox1.Text)</code>.</p>
<p>I want the <code>textBox.Text</code> to be able to be something like <code>"test " + (5+2).toString()</code></p>
<p>Now the function will get <code>""test " + (5+2).toString()"</code> (for example) as input and it'll treat that like a big string.</p>
<p>What I want it to do is get <code>test 7</code> and not treat it like one big string.</p>
<p>How would I go about doing that?</p>
<p>Thanks in advance!
-Tim</p>
<p>EDIT:</p>
<p>This would be my function:</p>
<pre><code>private void Something(string text)
{
MessageBox.Show(text);
}
</code></pre>
<p>If I then do</p>
<pre><code>Something(textBox1.Text);
</code></pre>
<p>When textBox1 looks like</p>
<pre><code>__________________
| "hi " + "test" |
------------------
</code></pre>
<p>It will do make a MessageBox that says <code>"hi" + "test"</code> and not <code>hi test</code>.</p>
| <p>You need to compile the string in your textbox and run the code before giving it to your <code>Something</code>-method. </p>
<p>Take a look at <a href="https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples#expr" rel="nofollow">Roslyn</a> to easily evaluate the expression from the textbox.</p>
<p>Then you'll get:</p>
<pre><code>string result = await CSharpScript.EvaluateAsync<string>("\"test \" + (5+2).toString()");
Something(result);
</code></pre>
|
Javascript Count how many garages have carmake1 <p>I have an oject of data represented as garages.
I need to for example count the number of garages that have carmake1</p>
<p>I have tried this:</p>
<pre><code>count = obj.garages.filter(function(item) { return item === "carmake1" }).length;
</code></pre>
<p>but this returns 0 and we know there are actual carmake1's in the data.</p>
<p>Here is the data:</p>
<pre><code>obj = {
"garages": [
{
"id": "1",
"carId": "1",
"tags": {
"483": "carmake1",
"485": "carmake3"
}
},
{
"id": "2",
"carId": "1",
"tags": {
"483": "carmake1",
"485": "carmake3"
}
},
{
"id": "3",
"carId": "2",
"tags": {
"484": "carmake2",
"485": "carmake3"
}
},
{
"id": "4",
"carId": "2",
"tags": {
"483": "carmake1",
"485": "carmake3"
}
},
{
"id": "5",
"carId": "3",
"tags": {
"484": "carmake2",
"485": "carmake3"
}
},
]
};
</code></pre>
<p>How can I get that?</p>
| <p>You could count it with the check of the property.</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 obj = obj = { "garages": [{ "id": "1", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "2", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "3", "carId": "2", "tags": { "484": "carmake2", "485": "carmake3" } }, { "id": "4", "carId": "2", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "5", "carId": "3", "tags": { "484": "carmake2", "485": "carmake3" } }, ] },
count = obj.garages.filter(function(item) {
return item.tags[483] === "carmake1"
}).length;
console.log(count);</code></pre>
</div>
</div>
</p>
<p>Or check all properties in <code>tags</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 obj = obj = { "garages": [{ "id": "1", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "2", "carId": "1", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "3", "carId": "2", "tags": { "484": "carmake2", "485": "carmake3" } }, { "id": "4", "carId": "2", "tags": { "483": "carmake1", "485": "carmake3" } }, { "id": "5", "carId": "3", "tags": { "484": "carmake2", "485": "carmake3" } }, ] },
count = obj.garages.filter(function (item) {
return Object.keys(item.tags).some(function (k) {
return item.tags[k] === "carmake1"
});
}).length;
console.log(count);</code></pre>
</div>
</div>
</p>
|
synonym for active databaseconnection <p>In VB.NET (Visual Studio 2008) I want to scroll through the records of a datatable. I tried like this:</p>
<pre><code> Dim cnnNWind As New ADODB.Connection
Dim rstNwind As New ADODB.Recordset
Dim Test As String
cnnNWind.ConnectionString = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\Users\Vitali\Desktop\aktuelle_Projekte\Berolina\Berolina_EIS\Berolina_EIS\Berolina_EIS\BerolinaDB.sdf"
rstNwind.Open("select Nachname from T_Mitarbeiter", ActiveConnection:=cnnNWind) ':=cnnNWind
With rstNwind
Do Until .EOF
Test = .Fields("Nachname").Value
MsgBox(Test)
.MoveNext()
Loop
End With
rstNwind.Close()
</code></pre>
<p>Now I get a connection error, must be because there is already a database connection in the form. What is the right term to use the current connection? In Access it can be used <code>currentproject.connection</code> is there anything like this?
Name of my database: BerolinaDB.sdf
There also is a tableAdapter for the wanted Table, it is used for a dataview element, the name is: T_MitarbeiterTableAdapter</p>
<p>EDIT: Error Message
"Die Verbindung kann nicht verwendet werden, um diesen Vorgang auszuführen. Sie ist entweder geschlossen oder in diesem Zusammenhang ungültig."</p>
| <p>The suggestion adding cnnNWind.Open() eliminated the error. For my former question, if the already opened connection could be used I found the solution by trying different things. I can use:</p>
<p>Dataset.Tableadapter.property</p>
|
Using Javascript to change an image on a webpage <p>I've been working on this code for a while and for some reason I can't tell its not changing the image displayed when I press the change image button. Can anyone help?</p>
<p>This is the Javascript file</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 imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = "images/img/red.gif";
imgArray[1] = new Image();
imgArray[1].src = "images/img/red_and_yellow.gif";
imgArray[2] = new Image();
imgArray[2].src = "images/img/green.gif";
imgArray[3] = new Image();
imgArray[3].src = "images/img/yellow.gif";
imgArray[4] = new Image();
imgArray[4].src = "images/img/red.gif";
/*------------------------------------*/
function nextImage(element) {
var img = document.getElementById(element);
for (var i = 0; i < imgArray.length; i++) {
if (imgArray[i].src == img.src) // << check this
{
if (i === imgArray.length) {
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i + 1].src;
break;
}
}
}</code></pre>
</div>
</div>
And this is the HTML.
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<body>
<h1> Press the button to change the lights. </h1>
<div id="lights">
<img src="red.gif" alt="" id="mainImg">
</div>
<div id="imglist">
<a href="javascript:nextImage('mainImg')">
<img src="next_img.png" alt="">
</a>
</body>
</html></code></pre>
</div>
</div>
Any help would be appreciated.</p>
| <p>Inside the outer <code>for-loop</code> check if the <code>img.src</code> is a part of <code>imgArray[i]</code></p>
<pre><code>if (imgArray[i].src.indexOf(img.src)!= -1) // notice the change here
{
//rest of the code remains same
}
</code></pre>
<p>or simply prepend the <code>images/img/</code> to img.src before comparison</p>
<pre><code>if (imgArray[i].src == ( "images/img/" + img.src ) ) // notice the change here
{
//rest of the code remains same
}
</code></pre>
|
Will my Apple Wallet Pass generator work after my Apple Developer subscription is expired? <p>I created an server side application which is generating PkPass files using Apple WWDRCA and Pass Type ID cert. My certificates are installed on the server and they are valid until end of 2017 but my Apple Developer account will expire in a few days. I'm wondering will my application continue to work without any issues or I will need to renew my subscription.</p>
<p>Thanks.</p>
| <p>You will continue to be able to issue and update passes until your certificate expires. However, we have experienced problems with clients who have let their developer account lapse and have subsequently lost the PassTypeID.</p>
<p>If you anticipate the need to issue or update these particular passes after the expiry of your certificate, then I'd strongly recommend to renew your Apple developer account now.</p>
|
Multiple file append in response object in node js <pre><code>gfs.files.find({}).toArray(function(err, file) {
if (!err) {
console.log('file length ', file.length);
if (file.length > 0) {
file.forEach(function(each) {
process.setMaxListeners(0);
var mime = 'image/jpeg';
res.set('Content-Type', mime);
read_stream = gfs.createReadStream({ "filename": each.filename });
read_stream.pipe(res, { end: false });
done++;
});
read_stream.on('end', function() {
process.setMaxListeners(0);
if (done === file.length) {
res.send();
}
});
} else {
res.json('File Not Found');
}
}
});
</code></pre>
<p>It is not work properly.Only one file is shown in browser.what i do now?It will be without any zip file.</p>
| <p>If your target clients are web browsers, then you can't, as the http protocol does not allow for multiple downloads for a single request.</p>
<p>May be you can think of creating an archive(zip) with requested files and send it.</p>
|
How to fix this 400 Bad status error? <p>The following image shows the error and the <code>cfdump</code> output, </p>
<p><a href="http://i.imgur.com/SZLider.png" rel="nofollow"><img src="http://i.imgur.com/SZLider.png" alt="enter image description here"></a> </p>
<p>Here is my JSON Response :</p>
<pre><code>{
"properties": [{
"property": "email",
"value": "testingapis@hubspot.com"
}, {
"property": "firstname",
"value": "Adrian"
}, {
"property": "lastname",
"value": "Mott"
}, {
"property": "website",
"value": "http://hubspot.com"
}, {
"property": "company",
"value": "HubSpot"
}, {
"property": "phone",
"value": "555-122-2323"
}, {
"property": "address",
"value": "25 First Street"
}, {
"property": "city",
"value": "Cambridge"
}, {
"property": "state",
"value": "MA"
}, {
"property": "zip",
"value": "02139"
}]
}
</code></pre>
<p>Here is the code I am using. I am setting values using <code>cfset</code> and then posting the data using <code>cfhttp</code>, </p>
<pre><code><cfset stFields='{
{
"properties": [
{
"property": "email",
"value": "testingapis@hubspot.com"
},
{
"property": "firstname",
"value": "Adrian"
},
{
"property": "lastname",
"value": "Mott"
},
{
"property": "website",
"value": "http://hubspot.com"
},
{
"property": "company",
"value": "HubSpot"
},
{
"property": "phone",
"value": "555-122-2323"
},
{
"property": "address",
"value": "25 First Street"
},
{
"property": "city",
"value": "Cambridge"
},
{
"property": "state",
"value": "MA"
},
{
"property": "zip",
"value": "02139"
}
]
}
}'>
<cfhttp url="https://api.hubapi.com/contacts/v1/contact/?hapikey=demo" method="post" result="httpResp" timeout="60">
<cfhttpparam type="header" name="Content-Type" value="application/json" />
<cfhttpparam type="body" value="#serializeJSON(stFields)#">
</cfhttp>
<cfdump var="#httpResp#" label="HTTP response">
</code></pre>
<p>After the dump, it shows the error <code>400 Bad request Access</code>.<br>
Please help me to rectify this Error.</p>
| <p>Create a structure instead of a string. Use CFDump to see it is correct. Like so:</p>
<pre><code><cfset stFields = {
"properties": [
{
"property": "email",
"value": "testingapis@hubspot.com"
},
{
"property": "firstname",
"value": "Adrian"
},
{
"property": "lastname",
"value": "Mott"
},
{
"property": "website",
"value": "http://hubspot.com"
},
{
"property": "company",
"value": "HubSpot"
},
{
"property": "phone",
"value": "555-122-2323"
},
{
"property": "address",
"value": "25 First Street"
},
{
"property": "city",
"value": "Cambridge"
},
{
"property": "state",
"value": "MA"
},
{
"property": "zip",
"value": "02139"
}
]
}>
<cfdump var="#stfields#">
</code></pre>
<p>Then in your cfhttp use the serialized version of that structure. You can CFDump that as a test as well.</p>
<pre><code><cfdump var="#serializeJSON(stfields)#">
</code></pre>
|
How can I get rid of these extra entries in my lookup table? <p>I am making a simple back end to add photos to my website. Each photo can be in multiple categories and is available in multiple sizes, so I have lookup tables to join the photos, categories and sizes together.</p>
<p>Here is my code for populating the lookup tables:</p>
<pre><code>foreach($request->category as $category)
{
$catphoto = new Category_Photo(['photo_id' => $photo->id, 'category_id' => $category]);
$photo->categories()->save($catphoto);
}
foreach($request->size as $size)
{
$photosize = new Photo_Size(['photo_id' => $photo->id, 'size_id' => $size]);
$photo->sizes()->save($photosize);
}
</code></pre>
<p>Here's an example of the data passed in the request:</p>
<pre><code>"category" => array:3 [â¼
0 => "1"
1 => "2"
2 => "3"
]
"size" => array:4 [â¼
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]
</code></pre>
<p>However, while the insertions work and the lookup tables are populated, every other inserted row contains the id of the previously inserted entry, e.g:</p>
<pre><code>id photo_id category_id
85 55 1
86 55 85
87 55 2
88 55 87
89 55 3
90 55 89
</code></pre>
<p>What's happening and how can I fix it?</p>
| <p>You should not create a new entry in your pivot table. instead you can use <code>attach()</code></p>
<pre><code>foreach($request->category as $category)
{
$photo->categories()->attach($category);
// ----- OR ---------
$cat = Category::where('id',$category)->first();
$photo->categories()->save($cat);
}
</code></pre>
<p>You can read more from laravel documentation <a href="https://laravel.com/docs/5.3/eloquent-relationships#updating-many-to-many-relationships" rel="nofollow">here</a></p>
|
How do I DRY-ly handle multiple upload types with Carrierwave? <p>I want to allow my users to be able to upload videos, documents & images to s3.</p>
<p>I was thinking that rather than having a model for each and then having 3 different uploader classes, I would just have 1 generic uploader and just whitelist all of those filetypes.</p>
<p>But I am not sure if that's the best approach, from a security perspective?</p>
<p>Also, there may be small variations with each type. For instance, with <code>video</code> a user should be able to both upload a video, or alternatively provide a YouTube link.</p>
<p>What's the most Rails/DRY-way to approach this?</p>
| <p>You could create a generic type then have sub types using STI (<a href="http://eewang.github.io/blog/2013/03/12/how-and-when-to-use-single-table-inheritance-in-rails/" rel="nofollow">Single Table Inheritance</a>). Unless you feel that the sub types would be so different from one another that there will be a lot of empty columns in some sub-types and not others this seems like the best way to go. From a security standpoint I donât see how there is really any significant impact in that regards.</p>
<pre><code>class FileUpload < ActiveRecord::Base
end
class Video < FileUpload
end
class Image < FileUpload
end
class Document < FileUpload
end
</code></pre>
<p>There is however a reasonable case for not doing this. Usually the rule of thumb for inheritance is if something is a type of, but in this case there is some gray area. The ambiguity comes from the fact that yes a document is a type of uploadable file but its not a type of video. So you want it to have the behavior of an uploadable file just like video but thats where the similarities cease. So the better route is probably to create an upload able <a href="http://ruby-doc.com/docs/ProgrammingRuby/html/tut_modules.html" rel="nofollow">module</a> that has all the desire share behavior and include that in the three models and let them all be their on thing.</p>
<pre><code>module Uploadable
end
class Video < ActiveRecord::Base
include Uploadable
end
class Image < ActiveRecord::Base
include Uploadable
end
class Document < ActiveRecord::Base
include Uploadable
end
</code></pre>
|
finding a special path string in HTML text in python <p>I'm trying to extract a path in an HTML file that I read.
In this case the path that I'm looking for is a logo from google's main site.</p>
<p>I'm pretty sure that the regular expression I defined is right, but I guess I'm missing something.</p>
<p>The code is:</p>
<pre><code>import re
import urllib
a=urllib.urlopen ('https://www.google.co.il/')
Text = a.read(250)
print Text
print '\n\n'
b= re.search (r'\"\/[a-z0-9 ]*',Text)
print format(b.group(0))
</code></pre>
<p>The actual text that I want to get is:</p>
<p><strong>/images/branding/googleg/1x/googleg_standard_color_128dp.png</strong></p>
<p>I'd really appreciate it if someone could point me in the right direction</p>
| <p>this can help you:</p>
<pre><code>re.search(r'\"\/.+\"',Text).group(0)
</code></pre>
<p>result:</p>
<pre><code>>>> re.search(r'\"\/.+\"',Text).group(0)
'"/images/branding/googleg/1x/googleg_standard_color_128dp.png"'
</code></pre>
|
How to do multiple Select Where in Linq <p>I'm new in Linq, and I want to convert this sql Query to Linq Format.</p>
<p>This is the SQL format</p>
<pre><code>select *
from investorwallets iw
where transactionid in
(select investordepositid from investordeposits)
or transactionid in
(select withdrawalid from investorwithdrawals)
or transactionid in
(select paymentdistributionid from paymentdistributions)
</code></pre>
<p>I've looked on this <a href="http://stackoverflow.com/questions/4026542/how-to-do-where-in-in-linq">SO</a> Question too, but no luck for me</p>
<p><strong>EDIT</strong></p>
<p>This is what I have tried. I use Linqpad for testing it</p>
<pre><code>from iw in Investorwallets
where (
from id in Investordeposits // I got error from here
select id.investordepositid
)
</code></pre>
<p>Anyone can help me?</p>
<p>Thank you</p>
| <p>The most direct is:</p>
<pre><code>from iw in investorwallets
where investordeposits.Any(iten => item.investordepositid == iw.transactionid) ||
investorwithdrawals.Any(iten => item.withdrawalid == iw.transactionid) ||
paymentdistributions.Any(item => item.paymentdistributionid == iw.transactionid)
select iw;
</code></pre>
<p>However you can also union the results and then do <code>.Contains</code>:</p>
<pre><code>var ids = investorwithdrawals.Select(item => item.investordepositid)
.Union(investorwithdrawals.Select(item => item.withdrawalid))
.Union(paymentdistributions.Select(item => item.paymentdistributionid));
var result = investorwallets.Where(item => ids.Contains(item.transactionid));
</code></pre>
|
Sequelize adding extra quotes to LIKE <p>It is a conditional query. So that's why the code begins with:</p>
<pre><code>var where = [];
</code></pre>
<p>Then I always put the ID for searching:</p>
<pre><code>where.push({myId: myId});
</code></pre>
<p>I then check if conditions are met and in that case add a LIKE:</p>
<pre><code>if(req.query.search !== undefined && req.query.search != ''){
where.push({name: {$like: req.query.search}});
}
</code></pre>
<p>When looking at the generated query I see:</p>
<pre><code>SELECT "id", "name" FROM "MyTable" WHERE ("MyTable"."myId" = 1 AND "MyTable"."name" LIKE '''%''ABCD''%''');
</code></pre>
<p>As you can see a lot of quotes are added.</p>
<p>If I manually remove all the quotes but the first and the last, then the query executes well.</p>
<p>Why is sequelize adding all those quotes? Am I using the LIKE operator in the wrong way?</p>
| <p>By bad. I changed $like with like and all the quotes disappeared.</p>
|
Why cant first and last be used? <p>Hey guys I cant run due to the private strings "first" and "last" not being "used." </p>
<p>Any idea why to what is causing the problem? thanks!</p>
<pre><code>public class Bananas{
private String first;
private String last;
private static int members = 0;
public Bananas(String fn, String ln){
first = fn;
last = ln;
members++;
System.out.printf("Constructor for %s %s, members in the club: %d\n", members);
}
}
</code></pre>
<p><strong>Separate classes</strong></p>
<pre><code>public class clasone {
public static void main(String[] args){
Bananas member1 = new Bananas ("Ted","O'Shea");
Bananas member2 = new Bananas ("John","Wayne");
Bananas member3 = new Bananas ("Hope","Go");
}
}
</code></pre>
| <p>This isn't a compilation error, it's a runtime error. As it states, your <code>printf</code> formatting is incorrect - it expects three arguments (two strings and an int) while you're only passing onw (<code>members</code>). From the context, I assume you meant to pass <code>first</code> and <code>last</code> there too:</p>
<pre><code>System.out.printf("Constructor for %s %s, members in the club: %d\n",
first, last, members);
// -- Here -------^------^
</code></pre>
|
Drawing the human silhouette with bezier point in Processing <p>I'm new here ... I need help with an issue Bezier Point in Processing, I apologize in advance for the English, I'm from Brazil, I write with the help of Google Translator ...</p>
<p>I tried to draw the "silhouette" of the human body, ie not need to have defined the face traits, etc. (I know this is complicated), only need the face outlines, body, finally simpler ...</p>
<p>The problem is that I would do it in 3D, so you can rotate, zoom effects, etc ...</p>
<p>Below we have two programs, one in 2D, which would be near what I need to do.</p>
<p>In the second program as a sketch do it in 3D, but could not develop the idea of ââhow to make the mesh of body contours, that's what I need help.</p>
<p>Could someone give some hint of any algorithm that can be translated into Processing, to draw this fabric of the human body (silhouette)?</p>
<p>I thank the attention, I apologize if the text was a little long, but I thought I should try to explain the best.</p>
<pre class="lang-java prettyprint-override"><code>int neckThick, headShape, shoulderSize, armSize, hipSize, lowerSize, upperSize, thighSize, handSize, legSize, footSize;
void setup() {
size(displayWidth, displayHeight, P3D);
smooth();
strokeWeight(2);
noFill();
stroke(10,50,255,80);
atualizaPontos();
}
void draw() {
background(255);
desenhaCorpo();;
}
void atualizaPontos(){
neckThick = 3;
headShape = 0;
shoulderSize = 5;
armSize = -1;
hipSize = -3;
lowerSize = -5;
upperSize = 2;
thighSize = -5;
handSize = 15;
legSize = 0;
footSize = 14;
}
void desenhaCorpo() {
head(headShape);
neck(neckThick);
shoulders(shoulderSize);
upperArms(armSize);
hips(hipSize);
lowerBody(lowerSize);
upperBody(upperSize);
thighs(thighSize);
kneecaps();
hands(handSize);
legs(legSize);
feet(footSize);
}
void head(int headSize) {
bezier(300, 70, 308, 30, 372, 30, 385, 70); //scalp
bezier(300, 70, 300-headSize, 120, 315-headSize, 135, 320, 140); //side
bezier(385, 70, 385+headSize, 120, 370+headSize, 135, 365, 140); //side
bezier(320, 140, 340, 155, 345, 155, 365, 140); //chin
}
void neck(int neckWidth) {
bezier(320, 140, 325-neckWidth, 170, 320-neckWidth, 180, 315, 180); //left neck
bezier(365, 140, 355+neckWidth, 170, 365+neckWidth, 180, 365, 180); //right neck
}
void shoulders(int shoulderWidth) {
bezier(210, 200, 305, 190-shoulderWidth, 310, 185-shoulderWidth, 315, 180); //left trapezius
bezier(365, 180, 370, 190-shoulderWidth, 380, 195-shoulderWidth, 480, 200); //right trapezius
bezier(210, 200, 205, 205, 205, 205, 200, 220); // left shoulder
bezier(480, 200, 485, 205, 485, 205, 490, 220); // right shoulder
}
void upperBody(int upperWidth) {
bezier(240, 250, 245-upperWidth, 300+upperWidth, 250-upperWidth, 325+upperWidth, 275, 325); //left pectoral
bezier(450, 250, 450+upperWidth, 300+upperWidth, 430+upperWidth, 325+upperWidth, 415, 325); //right pectoral
bezier(330, 300, 325, 320, 320, 320, 300, 325); //inner boob
bezier(360, 300, 370, 320, 375, 320, 390, 325); //inner boob
}
void lowerBody(int lowerWidth) {
bezier (260, 320, 260-lowerWidth, 350+lowerWidth/2, 270-lowerWidth, 380+lowerWidth/2, 265, 415); // left side
bezier (430, 320, 430+lowerWidth, 350+lowerWidth/2, 420+lowerWidth, 380+lowerWidth/2, 425, 415); // right side
}
void hips(int hipWidth) {
bezier(265, 410, 265-hipWidth, 430, 255-hipWidth, 435, 260, 450); //left hip
bezier(425, 410, 425+hipWidth, 430, 435+hipWidth, 435, 430, 450); //left hip
}
void thighs(int thighWidth) {
bezier(260, 450, 240-thighWidth, 500, 250-thighWidth, 525, 270, 650); //left thigh side
bezier(335, 480, 340+thighWidth, 500, 330+thighWidth, 525, 320, 650); //right thigh side
bezier(430, 450, 445+thighWidth, 500, 440+thighWidth, 525, 420, 650); //left thigh side
bezier(360, 480, 355-thighWidth, 500, 355-thighWidth, 525, 370, 650); //right thigh side
bezier(335, 480, 340, 483, 340, 483, 360, 480);
}
void kneecaps() {
bezier(270, 650, 270, 655, 265, 655, 270, 690); // left kneecap side
bezier(320, 650, 320, 655, 325, 655, 320, 690); // right kneecap side
bezier(420, 650, 420, 655, 425, 655, 420, 690); // left kneecap side
bezier(370, 650, 370, 655, 365, 655, 370, 690); // right kneecap side
}
void upperArms(int armWidth) {
bezier(200, 220, 190-armWidth, 300, 200-armWidth, 310, 200, 350); // left forearm side
bezier(200, 350, 180-armWidth, 425, 200-armWidth, 500, 200, 500); // left arm side
bezier(240, 250, 240+armWidth, 300, 235+armWidth, 310, 235, 350); // left forearm inside
bezier(235, 350, 240+armWidth, 425, 230+armWidth, 450, 225, 500); // left arm inside
bezier(490, 220, 500+armWidth, 300, 490+armWidth, 310, 490, 350); // right forearm
bezier(490, 350, 510+armWidth, 425, 490+armWidth, 500, 490, 500); // right arm
bezier(450, 250, 450-armWidth, 300, 455-armWidth, 310, 455, 350); // right forearm inside
bezier(455, 350, 460-armWidth, 425, 455-armWidth, 450, 465, 500); // right arm inside
}
void hands(int handWidth) {
bezier(200, 500, 210-handWidth, 530, 175-handWidth, 560, 220, 575); // left hand
bezier(220, 575, 225+handWidth, 575, 220+handWidth, 560, 225, 500); // left hand
bezier(490, 500, 480+handWidth, 530, 500+handWidth, 560, 490, 575); // right hand
bezier(465, 500, 460-handWidth, 575, 455-handWidth, 560, 490, 575); // right hand
}
void legs(int legWidth) {
bezier(270, 690, 255-legWidth, 775, 265-legWidth, 800, 275, 850); //left calf
bezier(320, 690, 320+legWidth, 775, 300+legWidth, 800, 300, 850); //left calf
bezier(420, 690, 435+legWidth, 775, 415+legWidth, 800, 405, 850); //right calf
bezier(370, 690, 370-legWidth, 775, 380-legWidth, 800, 380, 850); //left calf
}
void feet(int footWidth) {
bezier(275, 850, 250-footWidth, 900+footWidth, 280-footWidth, 900+footWidth, 300, 850); // left foot
bezier(405, 850, 430+footWidth, 900+footWidth, 400+footWidth, 900+footWidth, 380, 850); // left foot
}
</code></pre>
<p>Second program - got in the Forum Processing - Requires proscenium Library</p>
<pre><code>import remixlab.proscene.*;
Scene scene;
float px[], py[], mesh[][][];
void setup() {
size(displayWidth, displayHeight, P3D);
smooth(); //Suavição de Contorno
lights(); //Inicia Luzes no ambiente
//Inicia ambiente para Cena
scene = new Scene(this);
scene.setAxesVisualHint(false);
scene.setGridVisualHint(false);
scene.showAll();
//Cria Matriz para a malha
px = new float[40];
py = new float[40];
float t = 0;
for(int i = 0; i < px.length; i++) {
px[i] = bezierPoint(50, 130, 130, 50, t);
py[i] = bezierPoint(450, 350, 150, 50, t);
//px[i] = bezierPoint(300, 308, 370, 300, t);
//py[i] = bezierPoint(70, 30, 30, 70, t);
t += (1.0/(float)(px.length-1));
ellipse(px[i], py[i], 5, 5);
println(t);
}
//Cria Malha
mesh = createMesh(px,py,20, -60,60);
//mesh = createMesh(px,py,170, -360,360);
scene.startAnimation();
}
void draw() {
background(0);
ambientLight(128, 128, 128);
directionalLight(255, 255, 255, 0, 1, -100);
//head(-3);
stroke(255);
//noStroke();
//fill(255,120,0);
drawMesh(mesh);
}
void head(int headSize) {
fill(255);
bezier(300, 70, 30, 308, 30, 30, 372, 30, 30, 385, 70, 30); //scalp
bezier(300, 70, 30, 300-headSize, 120, 30, 315-headSize, 135, 30, 320, 140, 30); //side
bezier(385, 70, 30, 385+headSize, 120, 30, 370+headSize, 135, 30, 365, 140, 30); //side
bezier(320, 140, 30, 340, 155, 30, 345, 155, 30, 365, 140, 30); //chin
}
//Desenha Malha
void drawMesh(float mesh[][][]) {
//println(mesh.length+" "+mesh[0].length+" "+mesh[0][0].length);
for(int i = 0; i < mesh.length-1; i++) {
beginShape(QUAD_STRIP);
for(int j = 0; j < mesh[0].length; j++) {
vertex(mesh[i][j][0], mesh[i][j][1], mesh[i][j][2]);
vertex(mesh[i+1][j][0], mesh[i+1][j][1], mesh[i+1][j][2]);
}
endShape();
}
}
//Cria malha
float [][][] createMesh(float px[],float py[],int numrot, float startDeg,float endDeg) {
float deg, x, z;
double cosval, sinval, tmp1, tmp2;
float [][][] mesh = new float[numrot][px.length][3];
endDeg -= startDeg;
for(int i = 0; i < numrot; i++) {
deg = radians(startDeg + (endDeg/(float)(numrot-1)) * (float)i);
for(int j = 0; j < px.length; j++) {
x = px[j];
z = 0;
cosval = Math.cos(deg);
sinval = Math.sin(deg);
tmp1 = x * cosval - z * sinval;
tmp2 = x * sinval + z * cosval;
mesh[i][j][0] = (float) tmp1;
mesh[i][j][1] = py[j];
mesh[i][j][2] = (float) tmp2;
}
}
return mesh;
}
</code></pre>
<p>Thank you so much</p>
| <p>Instead of trying to hammer code you found on the internet into submission, I highly recommend you start a little smaller and try to focus on one small thing at a time.</p>
<p>Instead of trying to get your whole figure working, focus only on the head, or only on one line of the head.</p>
<p>The <code>bezier()</code> function can either take 2D coordinates like you're currently using, or it can take 3D coordinates by simply providing a Z value for each coordinate. More info can be found in <a href="https://processing.org/reference/bezier_.html" rel="nofollow">the reference</a>.</p>
<p>Think about it this way: right now you're using 3D coordinates, but the Z value for every point is 0. Go through each line and think about what the Z value should be for each coordinate.</p>
<p>This is going to be a pretty manual process, but it's going to save you a ton of headaches over trying to get random code to work. Good luck.</p>
|
My header image won't show <p>I am making a small website (school project), but my background won't appear at all! I have tried moving the image/path, adding it to the body instead. Is there something wrong with the code, or something else?</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>* {
box-sizing: inherit;
padding: 0;
margin: 0;
}
body {
padding: 0;
margin: 0;
background-color: #FFF;
-webkit-font-smoothing: antialiased;
}
a {
color: hsla(37, 39%, 72%, 1.00);
text-decoration: none;
}
li {
list-style: none;
}
.header {
background: url(img/background.jpg);
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
width: 100vw;
height: 100vh;
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
<section class="logo">&Bscr;</section>
<section class="nav-icon">
<span class="icon"></span>
</section>
<section class="nav-overlay"></section>
<nav class="navigation">
<ul class="navigation__ul">
<li><a href="#">Banan</a></li>
<li><a href="#">Eple</a></li>
<li><a href="#">Druer</a></li>
<li><a href="#">Pære</a></li>
<li><a href="#">Appelsin</a></li>
</ul>
</nav>
</header>
<main class="main-content">
</main></code></pre>
</div>
</div>
</p>
<p>Thanks in advance :)</p>
| <p>Try and change the background tag to background-image</p>
<pre><code>background-image: url(img/background.jpg);
</code></pre>
|
ASP .NET MVC 5 + Bootstrap modal with form POST <p>I've got problem with posting bootstrap modal in ASP .NET MVC 5 web application.
I'm using partial view for modal:</p>
<pre><code> @model Presentation.APP.MyAPP.Portal.Models.DocumentAndFilesManager.AddDocumentTypeModel
<script>
$(document).ready(function () {
$("#addDocumentTypeModal").on("submit", "#form-adddocumenttype-appt", function (e) {
e.preventDefault(); // prevent standard form submission
var form = $(this);
$.ajax({
url: form.attr("action"),
method: form.attr("method"), // post
data: form.serialize(),
success: function (partialResult) {
$('#addDocumentTypeModal').modal('toggle');
$("#form-container").html(partialResult);
}
});
});
});
</script>
<div class="modal fade" id="addDocumentTypeModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h3 class="modal-title" id="addDocumentTypeModalLabel">Add document type</h3>
</div>
@using (Html.BeginForm("AddDocumentType", "WebManager", FormMethod.Post, new { id = "form-adddocumenttype-appt" }))
{
<div class="modal-body" id="form-container">
<div class="row">
<div class="col-sm-12">
Input unique NAME and unique REFERENCE NUMBER of new Document.
</div>
</div>
<div class="row">
<br />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.DocumentTypeTitle, new { @class = "col-sm-12 control-label" })
<div class="col-sm-8">
@Html.TextBoxFor(m => m.DocumentTypeTitle, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.DocumentTypeTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.DocumentTypeReferenceNumber, new { @class = "col-sm-12 control-label" })
<div class="col-sm-8">
@Html.TextBoxFor(m => m.DocumentTypeReferenceNumber, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.DocumentTypeReferenceNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Add</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
</code></pre>
<p>Then I have parent view where partial view is rendered:</p>
<pre><code><div id="form-container">
@Html.Partial("_AddDocumentTypeModal")
</div>
</code></pre>
<p>And finally my controler action method:</p>
<pre><code>[HttpPost]
public ActionResult AddDocumentType(AddDocumentTypeModel model) {
if (ModelState.IsValid) {
if (!documentManagementFacade.AddDocumentType(model.DocumentTypeReferenceNumber, model.DocumentTypeTitle)) {
ModelState.AddModelError("", "Document type with this title and/or reference number already exists!");
}
else
{
return Json(new { success = true });
}
}
return PartialView("_AddDocumentTypeModal", model);
}
</code></pre>
<p>Validation in form works fine, but there is a problem with modal after post: modal is still present after successful POST as well as after post with error.
How can I display some message after post with error/hide modal after successful post?</p>
<p>Many thanks.</p>
| <pre><code>$.ajax({
url: form.attr("action"),
method: form.attr("method"), // post
data: form.serialize(),
success: function (partialResult) {
$('#addDocumentTypeModal').modal('hide');
$('#addDocumentTypeModal').find("#errorMsg").hide();
$("#form-container").html(partialResult);
}
error:function (error) {
$('#addDocumentTypeModal').find("#errorMsg").html(error).show();
}
</code></pre>
<p>});</p>
<p><strong>Inside modal body add a error div</strong></p>
<pre><code><div class="modal-body" id="form-container">
<div class="alert alert-danger" id="errorMsg" style="display:none" >Oops! Some error.....</div>
....
....
</div>
</code></pre>
|
How to drop the response of an Observable <p>With the help of <a href="http://stackoverflow.com/questions/39994096/start-first-call-of-intervalobservable-instant">Observable.timer(0, 1000)</a> I am making continuous requests to my server in a defined time pattern. After I processed the content of the response it is possible under special conditions that I need to drop the response and therefore do not pass it to the subscriber of the service:</p>
<pre><code>@Injectable()
export class LoggerService {
constructor(private http: Http) { }
private apiURL = 'assets/file.json';
getList() {
return Observable.timer(0, 1000)
.concatMap(() => this.http.get(this.apiURL))
.map(this.extractData)
.catch(this.handleError););
}
private extractData(res: Response) {
var fooot = new Foo();
fooot.fillFromJSON(JSON.stringify(res.json()));
if(fooot.getProperty()){
//DROP IT
}
return fooot;
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
}
</code></pre>
<p>The <code>getList()</code> method is then called from <code>ngOnInit</code> of a component.
At the moment there are two possible solutions I can think of, buy maybe there is a better/clearer approach to solve this problem:</p>
<ol>
<li><p>If I have to drop the response I create a special object which is recognized by the subscriber of <code>getList()</code> and then specifically handled. But this solution would be very ugly because the dropped response leaves my service and I need to extra write code outside of the service to handle this case.</p></li>
<li><p>I throw an exception when I have to drop the response. Then the exception is caught, recognized (to differ it from other cases) and then dropped without any notice/output. Afterwards the observable is restarted. The advantage of this approach is that the observable which should be dropped to not leave the service, but I do not like the usage of exceptions in this case for the control flow.</p></li>
</ol>
<p>I tried both solutions and they are working, but I hope there are some better approaches.</p>
| <p>If I understand correctly, you are looking for the <code>switchMap</code> operator. </p>
<p>If no response arrives within 1 second (the specified interval) the HTTP request is silently canceled, and another one is started.</p>
<p>Update:</p>
<p>If you are looking to cancel the HTTP request manually, you have to create a <code>cancelSubject: Subject</code> and define a <code>takeUntil(cancelSubject)</code> on the HTTP request.</p>
<p>To cancel the HTTP request, you simply call <code>cancelSubject.next(true)</code>, which in turn will cancel the HTTP request, because <code>takeUntil</code> takes effect.</p>
<p>Keep in mind, that after a second, the request will be restarted. If you want to cancel the timer, you will have to put the <code>.takeUntil(cancelSubject)</code> on the outer observable.</p>
|
guide to dependency ranges when developing a Haskell library <p>As a Haskell beginner, I'm working on a small library that I want to make public. One problem I have is that I don't know what I should do about the ranges of the dependencies I have. Does it make sense to set the range to the current MAJOR version, for example</p>
<pre><code>network >= 2.6 && < 2.7
</code></pre>
<p>Should I consider testing with lower MAJOR versions?</p>
| <p>The <a href="http://pvp.haskell.org/" rel="nofollow">Package Versioning Policy</a> document specifies besr approaches to assigning versions for your own package.</p>
<p>If you don't want to get too deep into this, you can omit all version constrains on packages you are depending on and then ask <a href="https://www.stackage.org/" rel="nofollow">Stackage team</a> to include your package in their releases (see <strong>Authors</strong> section). Once your package gets in, it would be Stackage's responsibility to make sure it builds fine.</p>
|
Detecting gibberish in off_topic intent with IBM Watson Conversation service <p>When constructing an intent designed to capture off topic questions, should we include gibberish phrases (such as 'fgufeu ewe qeweuwe' or other non-valid English)? I'm unsure whether including such words increases or decreases the likelihood of the off topic intent being matched. I'm pretty confident users will try mashing the keyboard to see how the bot responds, but what they enter would never be an exact match for the example gibberish I provide. </p>
| <p>The best answer is to test your model after you have created it. I've seen some instances where people have done this and it appears to work. </p>
<blockquote>
<p>I'm pretty confident users will try mashing the keyboard to see how the bot responds,</p>
</blockquote>
<p>From experience you will find that what you believed the user would do, and what they actually do tends to be very different. Especially if you have never done any user testing as you go. </p>
<p>Most users have a clear goal in mind when they hit a chat bot/conversational agent. They will use the bot normally up to the point where they achieve that. Even so someone mashing the keyboard should expect a wrong answer or "I don't know".</p>
|
How to use function pointer inside arduino interrupt service routine to modify the ISR? <p>I'm trying to design a simple Arduino interrupt service routine that uses a function pointer in it so that it can effectively be modified from the <code>main()</code> function. The following is my code.</p>
<pre><code>#include <stdio.h>
#include <util/delay.h>
#include "gpio.h" // "gpio.h" is my own library that contains the
// definitions of digital_write, digital_read,
// pin_mode, analog_write, etc.
// It also configures all the timer/counter
// circuits to operate in fast-PWM mode
// with an undivided input clock signal.
// This library has been tested.
/* Two interrupt service routines */
void INT_1(void);
void INT_2(void);
/* Function pointer to choose any one of the above defined ISRs */
void (* interrupt)(void) = NULL;
/* main */
int main(void) {
pin_mode(3, OUTPUT);
pin_mode(4, OUTPUT);
cli();
TIMSK0 |= _BV(TOIE0); // Enable Timer0 overflow interrupt
sei();
while(1)
{
interrupt = INT_1; // For 10 ms, INT_1 executes on interrupt
_delay_ms(10);
interrupt = INT_2; // For next 10 ms, INT_2 executes on interrupt
_delay_ms(10);
}
return 0;
}
ISR(TIMER0_OVF_vect) { // Execute the function pointed to by
// "interrupt" on every overflow on timer 0
if(interrupt != NULL)
{
interrupt();
}
}
void INT_1(void) {
digital_write(3, LOW);
digital_write(4, HIGH);
}
void INT_2(void) {
digital_write(3, HIGH);
digital_write(4, LOW);
}
</code></pre>
<p>LEDs are connected to pins 3 and 4. These should light up alternately for 10 milliseconds each. However, on flashing this program onto the Arduino, I see that each LED lights up for approximately 2 seconds. Can anyone tell me why? </p>
| <p>As usual, you have to use <code>volatile</code> modifier for variable used in both <code>ISR</code> and rest of code.</p>
<p>The <code>void (* volatile interrupt)(void) = NULL;</code> should do the trick. </p>
|
unable to hit service from IIS <p>when i hit a service using localhost the application run properly but when i hit it with IIS it doesnot reach to that service code</p>
<p>code run properly when hit with localhost .. similarly when use iis , it doesnot even hit the service</p>
<p>1.var urlreport = "<a href="http://localhost:57451/Service1.svc/" rel="nofollow">http://localhost:57451/Service1.svc/</a>";
2.var urlreport = "<a href="http://206.19.38.20/report/Service1.svc/" rel="nofollow">http://206.19.38.20/report/Service1.svc/</a>";</p>
<p>when the first link use to hit the service application run properly ..
problem occur when i use 2nd link(2).</p>
<p>thanks in advance .</p>
| <p>i think incorrect url become
<a href="http://206.19.38.20/Service1.svc/" rel="nofollow">http://206.19.38.20/Service1.svc/</a>" as per "<a href="http://localhost:57451/Service1.svc/" rel="nofollow">http://localhost:57451/Service1.svc/</a>"
remove the report from given code.</p>
|
How to get read/write disk speed in Python? <p>In a Pyhton program I need to get the accumulated read/write speeds of all disks on the host. I was doing it with <code>subprocess.check_output()</code> to call the following Linux shell command:</p>
<pre><code>$ sudo hdparm -t /dev/sda
</code></pre>
<p>This gives as a result:</p>
<pre><code>/dev/sda:
Timing buffered disk reads: 1488 MB in 3.00 seconds = 495.55 MB/sec
</code></pre>
<p>then I can parse the 495.55. OK, so far so good.</p>
<p>But on the man page of <code>hdparm</code> i found this explanation for the <code>-t</code> flag that basically says that when performing measurements no other process should read/write to disk at same time:</p>
<blockquote>
<p>Perform timings of device reads for benchmark and comparison purposes. For meaningful results, this operation should be repeated 2-3 times on an otherwise inactive system (no other active processes) with at least a couple of megabytes of free memory. This displays the speed of reading through the buffer cache to the disk without any prior caching of data. This measurement is an indication of how fast the drive can sustain sequential data reads under Linux, without any filesystem overhead. To ensure accurate measurements, the buffer cache is flushed during the processing of -t using the BLKFLSBUF ioctl.</p>
</blockquote>
<p><strong>The question is</strong>:</p>
<p>How can I ensure that no other process is accessing disk at the same time when measurements are performed?</p>
| <p>According to <a href="http://unix.stackexchange.com/questions/55212/how-can-i-monitor-disk-io">http://unix.stackexchange.com/questions/55212/how-can-i-monitor-disk-io</a> the most usable solution includes the tool sysstat or iostat (same package).</p>
<p>But seriously, since you have sudo permissions on the host, you can check yourself whether any IO intensive tasks are going on using any of the popular system monitoring tools. You cannot kill all IO effectively without your measurements also going nuts. Over a longer time the measurements should give you reasonable results nonetheless, since the deviations converge towards stable background noise.</p>
<p>Aside from that what would you need artificial measurements for? If you simply want to test the hardware capabilities without any RL context, <strong>do not mount the disk</strong> and test it in binary mode. A measurement while real traffic is going on usually gives you results that are closer to what you can actually expect at load times.</p>
|
SQL Server error when trying to connect <p>So I am having a problem connecting to my sql server.</p>
<p>I know 100% its working and accepting connections, but for some reason I keep getting an error.</p>
<p>I can browse the server just fine in Server Browser, and If I bind the datasource to a datagrid, I can preview the table as well. So I know it's working fine inside VS, but not runtime.</p>
<p>From my knowledge and experience, if VS can connect to the server and display all the good stuff, then it should be able to do it during runtime??</p>
<p>Any help and advice is much appreciated.</p>
<p><strong>Non Duplicate Reason</strong>
The reason I believe my question is not a duplicate, is because my application is not a ASP or an MVC app. It's a winforms application. So many of the suggestions do not work for me.
I have written 2 c# programs now (one wpf and one winform) to access our SAP database and they work just fine. The SAP database is located on the same server as the one I am trying to connect to.
I can browse the server perfectly fine in SQL-Server Management Studio on my machine. I can also browse the server perfectly fine in Visual Studios server browser. But When I debug the program, it halts with this error.</p>
<p>My Connection code</p>
<pre><code>public string connectionString = @"Data Source=ENGSRV\SIGMANEST;Initial Catalog=SNDBase10;Persist Security Info=True;User ID=XXXXX;Password=XXXXX";
private void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
try
{
try
{
connection.Open();
MessageBox.Show("Connected");
}
catch (Exception ex)
{
throw;
//MessageBox.Show(ex.Message, "Database Error!");
}
}
catch (Exception ex)
{
throw;
//MessageBox.Show(ex.Message, "Connection Error!");
}
}
</code></pre>
<p>Error Code</p>
<blockquote>
<p>An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in ProductionOrderQuery.exe</p>
<p>Additional information: A network-related or instance-specific error
occurred while establishing a connection to SQL Server. The server was
not found or was not accessible. Verify that the instance name is
correct and that SQL Server is configured to allow remote connections.
(provider: SQL Network Interfaces, error: 26 - Error Locating
Server/Instance Specified)</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/SDxCg.png" rel="nofollow">Server Explorer Screen Shot</a></p>
<p><a href="https://i.stack.imgur.com/0kioK.png" rel="nofollow">Table Data Rows Screen Shot</a></p>
<p><strong>Update:</strong>
So after thinking about it tonight, I believe it has to do with my firewall and nothing to do with the sql server or the firewall on the server.
Here's why,
My VB.Net application that can successfully connect to the sql server is not a standalone application. It's a plugin for a CAD software called Rhinocreos 5. All our CAD Designers have 0 problems pulling data from the sql server from within Rhino... Visual Studio can connect with 0 problems in the Server Explorer...
Which now leaves me to believe that the application(plugin), is piggy-backing of a firewall rule Rhinocreos 5 made during its installation. If I change the connection string to the one I posted here, it connects perfectly. But it will not find the sql server instance in my standalone application.</p>
<p>That being said, I guess I need to research on how to promaticaly add my program to the clients firewall rules to access the network.</p>
<p>Thanks to everyone that has helped my solve this. If anyone has any tips or pointers to allowing my program through firewalls on any client it's installed on, let me know.</p>
| <p>Problem was within our network.</p>
<p>Our IT guy decided to have all our computers "My Documents" on a separate server and NOT on our own machines.</p>
<p>So Visual Studio by default saved my project to this server and not to my own computer. This was causing the block to the SQL Server.</p>
<p>I solved this by simply moving my project to my actual documents folder on my computer.</p>
<p>Thanks everyone for the help and pointers!</p>
|
Android.SMSthief.A2e76 (PUP) in Classes.dex <p>I recently updated my Android Studio to the latest build and I am facing one issue
which is Android.SMSthief.A2e76 (PUP).</p>
<p>I don't know what does this mean but it's being detected by Quick Heal Total Security and I don't know what to do. please let me know what can I do ? and is it really the virus or what. as I am having this issue in my all PC. I also checked with a fresh installation of Windows with no data on the HDD.</p>
| <p>It looks a trajon .. see this :<a href="http://www.solvusoft.com/en/malware/trojans/android-smsthief-a/" rel="nofollow">http://www.solvusoft.com/en/malware/trojans/android-smsthief-a/</a></p>
|
Linkedin inbox API <p>I tried to search a lot but seems like what i am trying to do has not been done before. Here is what I am trying. I am trying to figure out a way to make a script that takes a linkedin profile url as input and checks if I have sent any message to that profile in past. If I have sent script gives me "true" if no message in past has been sent to that script gives me "false". I tried to search linkedin API for same but I could not find any help on that. Any opinion from all your experts out there please? Many thanks in advance. </p>
| <p>Not sure what exactly you are asking.</p>
<p>But the Linkedin API is terrible and should be avoided, they have a track record of screwing over 3rd party apps. AFAIK you cannot get any data about a user except their basic profile info and even that is unpredictable, sometimes you'll get like 4 fields at most. Don't let this page fool you: <a href="https://developer.linkedin.com/docs/fields/basic-profile" rel="nofollow">https://developer.linkedin.com/docs/fields/basic-profile</a></p>
<p>If you want you can try your luck and apply for their 'partner' program or as i like to call it: lets-see-if-we-can-steal-your-idea-before-you-get-big-enough-that-we-are-forced-to-compete/acquire-you</p>
|
how to add virtual host? <p>for windows open this path</p>
<pre><code>c:\Windows\System32\drivers\etc\hosts
</code></pre>
<p>open in notpad or texteditor
show hidden files Must be on to open this path</p>
<p>host file view some thing like this</p>
<pre><code># Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 localhost
</code></pre>
<p>Add your host ip and host name </p>
<pre><code>192.168.10.88 myhost
</code></pre>
| <p>Please find below url which might help you out for creating virtual host on window </p>
<p><a href="http://stackoverflow.com/questions/2658173/setup-apache-virtualhost-windows">ReferenceLink</a></p>
|
How do I set up ADB to send commands to mulitple Android devices WINDOWS <p>I build a script for work so that installing Android phones becomes automatic. The problem I encounter is that I can't run commands if I connect 2 or more phones to my computer. Is there a way that I can run the same script on multiple Android devices?</p>
<p>They don't have to go simultaneously, but if it's possible I'd rather have them run simultaneously than run after each other.</p>
<p>I did a lot of research, but I just can't find the answer anywhere. I tried copying some peoples own made scripts without luck. </p>
<p>I found some post about installing apk's, but i'm looking for a way to input every command available. I did found out about this though:</p>
<pre><code>@echo off
cls
FOR /F "tokens=1,2" %%a IN ('adb.exe devices') DO (
IF "%%b" == "device" (
start /b adb.exe -s %%a {Command} -r %1
)
)
</code></pre>
<p>When i put let's say {reboot} in, then multiple devices reboot. But whenever i put in shell input tap xxx xxx it doesn't work.</p>
| <p>Okay i finally figured it out. </p>
<pre><code>@echo off
cls
FOR /F "tokens=1,2" %%a IN ('adb.exe devices') DO (
IF "%%b" == "device" (
start /b adb.exe -s %%a {Command}
)
)
</code></pre>
<p>When i remove the -r %1 the input tap command works. I'm happy to see it also works when i attach one device to my computer.</p>
|
Create rails routes only for localhost <p>I'd like certain rails routes to only be accessible from localhost. In other words if you attempted to access that url from a non localhost connection you would be given a response equivalent to the route not existing.</p>
<p>Optimally some way of specifying routes as local in the routes.rb itself would be the cleanest solution but if there is some way to filter the request later at the controller level for example thats okay too.</p>
| <p>The file <code>routes.rb</code> contains special DSL for routes, but it's <em>still ruby</em>.
So, did you try put your routes in simple condition?</p>
<pre><code># routes.rb
if Rails.env.development?
# your special local routes definition
end
</code></pre>
|
How to hide SVG elements with JavaScript on a button click? <p>I have tried doing that with this code:</p>
<pre><code>svgElement.style.display = "none";
</code></pre>
<p>but it didn't work. How is it possible to do it with <code>getElementById</code>? </p>
| <p>Use the SVG visibility attribute.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/visibility" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/visibility</a></p>
<p>The visibility attribute lets you control the visibility of graphical elements. With a value of hidden or collapse the current graphics element is invisible
[update]
However display: none; and opacity: 0 work too.</p>
<p>But know that opacity (MDN Link) is the most computationally expensive (as it keeps the elements click event alive even though the element isn't displayed visually),</p>
<p>then visibility,</p>
<p>then display, <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/display" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/display</a>.</p>
<p>But rushing to use display isn't always the best because we get more control over the elements with visibility (i.e., "If you are trying to hide an entire group, except for one particular member of that group, use 'visibility' as it is overrideable in inheritance." link)</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute" rel="nofollow">SVG Resource</a></p>
|
Convert json column data into table in sql server 2012 <p>I have json stored in table with 3 million rows.
A single row contains json in below format</p>
<pre><code>[
{
"Transaction":[
{
"ProductInfo":[
{
"LINE_NO":"1",
"STOCKNO":"890725471381116060"
},
{
"LINE_NO":"2",
"STOCKNO":"890725315884216020"
}
]
}
],
"Payment":[
{
"ENTSRLNO":"1",
"DOCDT":"08/25/2016"
}
],
"Invoice":[
{
"SALES_TYPE":"Salesinvoice",
"POS_CODE":"A20",
"CUSTOMER_ID":"0919732189692",
"TRXN_TYPE":"2100",
"DOCNOPREFIX":"CM16",
"DOCNO":"1478",
"BILL_DATE":"08/25/2016 03:59:07"
}
]
}
]
</code></pre>
<p>I want to dump above json in three different table </p>
<ol>
<li>ProductInfo</li>
<li>Payment table</li>
<li>Invoice</li>
</ol>
<p>How to perform above task in a optimise way?</p>
| <p>Well most efficient way will be to write a procedure and use open json in sql server
check below link:
<a href="https://msdn.microsoft.com/en-IN/library/dn921879.aspx" rel="nofollow">https://msdn.microsoft.com/en-IN/library/dn921879.aspx</a></p>
|
how to update all the keys in mongoDb document <p>Hi I have a collection that has a complex structure, and the documents in this structures are different in the structure. I want to update all the keys <code>V</code> to have value <code>0</code> in this collection.
Example:</p>
<pre><code> {
"_id" : ObjectId("5805dfa519f972b200ea2955"),
"s" : {
"id" : NumberLong(36435)
},
"a" : [
{
"XX-(random value)" : {
"V" : 4
},
"V" : 4,
"u" : {
"YY-(random value)" : {
"V" : 4,
"ZZ-(random value)" : {
"V" : 4,
"WW-(random value)" : {
"V" : 4
}
}
}
}
}
]
}
</code></pre>
| <p>You can do this with a short javascript. You need to iterate through each property of each document, checking the name of the property. If it matches the name "V" then update it with the value 0. This can be done recursively using a loop. The following javascript code should do the needful:</p>
<pre><code>function checkProperties(doc) {
for (var propertyName in doc) {
if (typeof doc[propertyName] == "object") {
checkProperties(doc[propertyName]);
} else {
if (propertyName == "V") {
doc[propertyName] = 0;
print(doc[propertyName]);
}
}
}
}
db.<your_collection_name>.find({}).forEach(function(doc) {
checkProperties(doc);
db.<your_collection_name>.save(doc);
});
</code></pre>
<p>If you save this code in a .js file you can then run it against your mongo database:</p>
<pre><code>> mongo --host <host> --port <port> <script_name>.js
</code></pre>
|
spark parallelize writes using list of dataframes <p>I have a list of dataframe created using jdbc. Is there a way to write them in parallel using parquet?</p>
<pre><code>val listOfTableNameAndDf = for {
table <- tableNames
} yield (table, sqlContext.read.jdbc(jdbcUrl, table, new Properties))
</code></pre>
<p>I can write them sequentially, but is there a way to parallelize the writes or make it faster.</p>
<pre><code>listOfTableNameAndDf.map { x => {
x._2.write.mode(org.apache.spark.sql.SaveMode.Overwrite).parquet(getStatingDir(x._1))
}
}
</code></pre>
| <p>You can future to perform write actions asynchronously:</p>
<pre class="lang-scala prettyprint-override"><code>dfs.map { case (name, table) =>
Future(table.write.mode("overwrite").parquet(getStatingDir("name")))
}
</code></pre>
<p>but I doubt it will result in any significant improvement. In case like yours there a few main bottlenecks:</p>
<ul>
<li>Cluster resources - if any job saturates available resources remaining jobs will be queued as before.</li>
<li>Input source throughput - source database have to keep up with the cluster. </li>
<li>Output source IO - output source have to keep with the cluster.</li>
</ul>
<p>If source and output are the same for each job, jobs will compete for the same set of resources and sequential execution of the driver code is almost never an issue. </p>
<p>If you're looking for improvements in the current code I would recommend starting with using reader method with a following signature:</p>
<pre class="lang-scala prettyprint-override"><code>jdbc(url: String, table: String, columnName: String,
lowerBound: Long, upperBound: Long, numPartitions: Int,
connectionProperties: Properties)
</code></pre>
<p>It requires more effort to use but typically exhibits much better performance because reads (and as a result data) are distributed between worker nodes.</p>
|
How does boost::multi_index work with member functions? <p>If I have a boost::multi_index as follows,</p>
<pre><code>typedef multi_index_container<
employee,
indexed_by<
hashed_unique<mem_fun<employee, std::string, &employee::getname> >,
hashed_unique<mem_fun<employee, int, &employee::getage> >
>
> employee_set;
</code></pre>
<p>I understand that the objects of class "employees" that are inserted into this container are stored in such a way that it can be retrieved in O(1) time(as a hash map). </p>
<p>How will it be stored when the member variables(name, age) are updated during the course of the program(like maybe with something like setname or setage) and still be hashed using those values? Am I understanding something wrong?</p>
<p>TIA</p>
<p>-R</p>
| <p>From the <a href="http://www.boost.org/doc/libs/1_61_0/libs/multi_index/doc/tutorial/basics.html#iterator_access" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>The iterators provided by every index are constant, that is, the elements they point to cannot be mutated directly. This follows the interface of <code>std::set</code> for ordered indices but might come as a surprise for other types such as sequenced indices, which are modeled after <code>std::list</code>, where this limitation does not happen. This seemingly odd behavior is imposed by the way <code>multi_index_container</code>s work; if elements were allowed to be mutated indiscriminately, we could introduce inconsistencies in the ordered indices of the <code>multi_index_container</code> without the container being notified about it. Element modification is properly done by means of <a href="http://www.boost.org/doc/libs/1_61_0/libs/multi_index/doc/tutorial/basics.html#ord_updating" rel="nofollow">update operations</a> on any index.</p>
</blockquote>
<p>In other words, you only have <code>const</code> access to your stored objects, unless you use the container's updating functions, at which point it can hook into the call and adjust the hashes on-the-fly.</p>
|
How to represent a Mongo based NumberLong() in org.springframework.data.mongodb.repository.Query() <p>I need to fetch records from a MongoDB which has a set of documents. I am using Spring Boot and MongoRepository to do the CRUD operations. I am using a Query annotation to pass my Mongo query.But Spring is unable to parse the query that I have written. I am new to MongoDB, so please excuse me if this is a silly question. Any help is appreciated, Thanks.</p>
<p>This is the Query I am using:</p>
<pre><code>@Query("{ '_id.AID' : ?0, '_id.STS' : {'$gte': NumberLong(1475778600)}, '_id.ETS':{'$lte': NumberLong(1475781659)}}")
List<AggregatedData> findByAidAndStartTimeAndEndTime(String aid);
</code></pre>
<p>The exception I am getting:</p>
<pre><code>Caused by: com.mongodb.util.JSONParseException:
{ '_id.AID' : "_param_0", '_id.STS' : {'$gte': NumberLong(1475778600)}, '_id.ETS':{'$lte': NumberLong(1475781659)}}
^
at com.mongodb.util.JSONParser.read(JSON.java:301) ~[mongodb-driver-3.2.2.jar:na]
at com.mongodb.util.JSONParser.parse(JSON.java:180) ~[mongodb-driver-3.2.2.jar:na]
</code></pre>
<p>Mongo record structure:</p>
<pre><code>{
"_id" : {
"SiteId" : "JATH",
"AID" : "JA04",
"STS" : NumberLong(1475778600),
"ETS" : NumberLong(1475781659)
},
"TS" : [
1475820600,
1475779200,
1475779800,
1475780400,
1475781000,
1475781600
],
"Tags" : {
"ActivePower" : {
"Max" : [
1181.5,
1181.5,
1181.5,
1181.5,
1181.5,
1181.5
],
"Min" : [
73.5,
73.5,
73.5,
73.5,
73.5,
73.5
],
"Sum" : [
224430,
224430,
224430,
224430,
224430,
224430
],
"Avg" : [
374.05,
374.05,
374.05,
374.05,
374.05,
374.05
],
"Count" : [
600,
600,
600,
600,
600,
600
],
"Std" : [
175.242871942532,
175.242871942532,
175.242871942532,
175.242871942532,
175.242871942532,
175.242871942532
]
}
}
}
</code></pre>
| <p>Try this:</p>
<pre class="lang-spring prettyprint-override"><code>@Query(value = "{ '_id.AID' : ?0 }", fields = {"_id.STS' : {'$gte': NumberLong(1475778600)}, '_id.ETS':{'$lte': NumberLong(1475781659)}}")
</code></pre>
|
How to include template file in ngcordova Isoffline()? <p>I am new to ionic app development . I am developing a app in which i am using ng Cordova network information plugin to check whether app is connected to internet or not . if internet is connected I want to display template file. is it possible to do it ?? if so how can I ??</p>
<pre><code>if ($cordovaNetwork.isOffline()) {
$ionicPopup.confirm({
title: "Internet Disconnected",
content: "The internet is disconnected on your device."
})
ionic.Platform.exitApp()
</code></pre>
| <p>You can do it from run method, more info in <a href="http://ionicframework.com/docs/api/service/$ionicPopup/" rel="nofollow">Ionic PopUp Service</a></p>
<pre><code>.run(function($window, $rootScope, $cordovaNetwork, $ionicPopup) {
if ($cordovaNetwork.isOffline()) {
var myPopup = $ionicPopup.show({
template: '<b>Hello!</b>',
title: 'Internet lost',
subTitle: 'Connection lost',
scope: $scope,
buttons: [
{ text: 'Cancel' }, {
text: '<b>Ok</b>',
type: 'button-positive',
onTap: function(e) {
//click Ok button
}
}
]
});
}
)}
</code></pre>
<p>OR</p>
<pre><code>$ionicModal.fromTemplateUrl('templates/internet_info.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
$scope.closeInternetInfo = function() {
$scope.modal.hide();
};
// Open the login modal
$scope.OpenInternetInfo = function() {
$scope.modal.show();
};
</code></pre>
<p>Your template should be something like this:</p>
<pre><code><ion-modal-view>
<ion-header-bar>
<h1 class="title">Internet</h1>
<div class="buttons">
</div>
</ion-header-bar>
<ion-content>
</ion-content>
</ion-modal-view>
</code></pre>
|
Can we use `const` instead of `let` everywhere? <p>With <code>flowtype</code> we prefer <code>const</code> against <code>let</code></p>
<p>I have function that needs to be worked in most performant way and it's works well for me, it's compare two arrays, so it's cool example for my question:</p>
<pre><code>/**
* @function compare
* @description function compares two arrays with ids to figure out: are they equal? (elements position can be different)
* @param arraFrom {Array}
* @param arraTo {Array}
* @param compareFunction {Function}
* @returns {Boolean}
*/
function compare(arraFrom, arraTo, compareFunction) {
let notEqual = true;
if(arraFrom.length !== arraTo.length) return false;
for (let i = 0; i < arraFrom.length; i++) {
notEqual = true;
for (let j = 0; j < arraTo.length; j++) {
if (compareFunction ?
compareFunction(arraFrom[i], arraTo[j]) :
arraFrom[i] === arraTo[j]) {
notEqual = false;
break;
}
}
if (notEqual) return false;
}
return true;
}
</code></pre>
<p>Question is: how can we implement it without using <code>let</code> in the most performant way?</p>
<p>Thank you!</p>
| <p>Instead of iterating the arrays by mutating index variables, you can use <code>forâ¦of</code> loops:</p>
<pre><code>function compare(arraFrom, arraTo, compareFunction) {
let notEqual = true;
if(arraFrom.length !== arraTo.length) return false;
for (const a of arraFrom) {
notEqual = true;
for (const b of arraTo) {
if (compareFunction ? compareFunction(a,b) : a === b) {
notEqual = false;
break;
}
}
if (notEqual) return false;
}
return true;
}
</code></pre>
<p>Instead of that mutable <code>notEqual</code> flag, you can simply return early:</p>
<pre><code>function compare(arraFrom, arraTo, compareFunction) {
if (arraFrom.length !== arraTo.length) return false;
outer: for (const a of arraFrom) {
for (const b of arraTo) {
if (compareFunction ? compareFunction(a,b) : a === b) {
continue outer;
}
}
return false;
}
return true;
}
</code></pre>
<p>But that's pretty unreadable. I'd recommend to use the following:</p>
<pre><code>function compare(arrayFrom, arrayTo, compareFunction) {
if (arrayFrom.length !== arrayTo.length) return false;
const test = typeof compareFunction == "function"
? a => b => compareFunction(a, b)
: a => b => a === b;
return arrayFrom.every(a => arrayTo.some(test(a)));
}
</code></pre>
|
I want get checked multiple record id in yii2 <p>I am new here can anyone tell me how to get checked record id from index for remove selected record using <strong>Ajax</strong> and <strong>Jquery</strong> this is my form and ajax script for select this code does not do any action so let me know </p>
<pre><code><div class="usermaster-model-index">
<input type="button" class="btn btn-info pull-right" value="Delete Multiple" id="MyButton" >
<h1><?= Html::encode($this->title) ?></h1>
<?php
?>
<p>
<?= Html::a('Create Usermaster Model', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'class' => ActionColumn::className(),
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'user_fname',
'user_id',
'user_lname',
'user_mobile',
['class' => 'yii\grid\ActionColumn'],
[ 'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' => ["attribute" => 'user_id'],
],
],
]);
?>
</div>
<script>
$(document).ready(function () {
$('#MyButton').click(function () {
alert('hello');
var HotId = $('#user_id').yiiGridView('getSelectedRows');
$.ajax({
type: 'POST',
cache: false,
url: Url::toRoute('usermaster/MultipleDelete'),
data: {user_id: HotId},
success: function () {
$(this).closest('tr').remove();
}
});
});
});
</script>
</code></pre>
<p>and here my controller action which delete multiple data function to get selected id and delete </p>
<pre><code>public function actionMultipleDelete()
{
$data = Yii::$app->request->post('user_id');
foreach ($data as $key => $value)
{
$sql = "DELETE FROM usermaster WHERE user_id = $value";
$query = Yii::$app->db->createCommand($sql)->execute();
}
return $this->redirect(['index']);
}
</code></pre>
| <p>In your gridview add <code>id</code> option</p>
<pre><code>GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'id'=> your-id //set your id here and use this is in jquery
//'class' => ActionColumn::className(),
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'user_fname',
'user_id',
'user_lname',
'user_mobile',
['class' => 'yii\grid\ActionColumn'],
[ 'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' => ["attribute" => 'user_id'],
],
],
]);
</code></pre>
<p>and in Jquery replace <code>user_id</code> with your new id as follows.</p>
<pre><code><script>
$(document).ready(function () {
$('#MyButton').click(function () {
alert('hello');
var HotId = $('#your-id').yiiGridView('getSelectedRows'); // modify this line
$.ajax({
type: 'POST',
cache: false,
url: Url::toRoute('usermaster/MultipleDelete'),
data: {user_id: HotId},
success: function () {
$(this).closest('tr').remove();
}
});
});
});
</script>
</code></pre>
|
The Android build FFMPEG encounter problems <p>I write an Android test App on Ubuntu, the NDK - BUILD, appeared</p>
<p>/ home/lee/Work/Android/the NDK/Android - the NDK - r10e toolchains/arm - Linux - androideabi - 4.8 / prebuilt/Linux - x86_64 / bin /../ lib/GCC/arm - Linux - androideabi / 4.8 /../../../../ arm - Linux - androideabi/bin/ld: error: always find - lGLESv2
Collect2: error: ld returned 1 exit status
Make: * * * [obj/local/armeabi/libffmpeg so] Error 1</p>
<p>FFmpeg is version 3.1.4,and the NDK version is r10e</p>
| <p>This works with 3.1.4 although it doesn't build a single library.</p>
<pre><code>#!/bin/bash
NDK=$HOME/Android/Sdk/ndk-bundle
SYSROOT=$NDK/platforms/android-19/arch-arm/
TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64
CPREFIX=$TOOLCHAIN/bin/arm-linux-androideabi-
function build_it {
./configure \
--prefix=$PREFIX \
--disable-static \
--enable-shared \
--disable-doc \
--disable-ffmpeg \
--disable-ffplay \
--disable-ffprobe \
--disable-ffserver \
--disable-avdevice \
--disable-doc \
--disable-symver \
--cross-prefix=$CPREFIX \
--target-os=linux \
--arch=arm \
--enable-cross-compile \
--enable-gpl \
--sysroot=$SYSROOT \
--extra-cflags="-Os -fpic $ADDI_CFLAGS" \
--extra-ldflags="$ADDI_LDFLAGS" \
$ADDITIONAL_CONFIGURE_FLAG
make clean
make -j9
make install
}
CPU=arm
PREFIX=$(pwd)/android/$CPU
ADDI_CFLAGS="-marm"
</code></pre>
<p>Building a single library is more trouble than it's worth, just ensure you load the libraries in the correct order:</p>
<pre><code>avutil, avcodec, avformat, swscale, swresample, postproc
</code></pre>
<p>Also, to get the libraries to build with the correct version numbers change these lines in the ./configure file</p>
<p>from</p>
<pre><code>SLIBNAME_WITH_VERSION='$(SLIBNAME).$(LIBVERSION)'
SLIBNAME_WITH_MAJOR='$(SLIBNAME).$(LIBMAJOR)'
LIB_INSTALL_EXTRA_CMD='$$(RANLIB) "$(LIBDIR)/$(LIBNAME)"'
SLIB_INSTALL_NAME='$(SLIBNAME_WITH_VERSION)'
SLIB_INSTALL_LINKS='$(SLIBNAME_WITH_MAJOR) $(SLIBNAME)'
</code></pre>
<p>to</p>
<pre><code>SLIBNAME_WITH_VERSION='$(SLIBNAME).$(LIBVERSION)'
SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
LIB_INSTALL_EXTRA_CMD='$$(RANLIB) "$(LIBDIR)/$(LIBNAME)"'
SLIB_INSTALL_NAME='$(SLIBNAME_WITH_MAJOR)'
SLIB_INSTALL_LINKS='$(SLIBNAME)'
</code></pre>
<p>EDIT:</p>
<p>The issue you're having with regards to GLES, can you show more info?</p>
|
Can I scan a website for all it's text articles? <p>Is it possible to scan every text news article of a specific website?
I mean, I known about text extraction techniques but can I do it for the whole website?</p>
<p><strong><em>For example</em></strong>: I have some sentences and I want to know if they match to a specific article on the news website!</p>
<p>I appreciate your help.</p>
| <p>with PHP the simplest way would be using the <a href="http://www.w3schools.com/php/func_filesystem_file_get_contents.asp" rel="nofollow">file_get_contents()</a> function, it would retrieve the page's source code and from there you could parse it to get the specific text you want.</p>
<p>Another possibility would be using <a href="http://php.net/manual/en/curl.examples-basic.php" rel="nofollow">cURL</a>.</p>
|
magento 2 collection gives empty data? <p>below is my code:</p>
<p>$transObj = $this->_objectManager->create('Magento\Sales\Model\Order\Payment\Transaction');</p>
<pre><code> $order_id = 9706;
$trans_result = $transObj->getCollection()
->addAttributeToSelect(
'order_id'
)
->addAttributeToSelect(
'payment_id'
)
->addAttributeToSelect(
'is_closed'
)
->addAttributeToSelect(
'txn_id'
)
->addAttributeToSelect(
'transaction_id'
)
->addFieldToFilter(
'order_id',
array("eq" => $order_id)
);
var_dump($trans_result->getData());
echo "\n Query:".$trans_result->getSelect();
</code></pre>
<p>below i am getting the out put as :</p>
<p>array(0) {
}</p>
<p>Query :SELECT <code>main_table</code>.<code>order_id</code>, <code>main_table</code>.<code>payment_id</code>, <code>main_table</code>.<code>is_closed</code>, <code>main_table</code>.<code>txn_id</code>, <code>main_table</code>.<code>transaction_id</code> FROM <code>sales_payment_transaction</code> AS <code>main_table</code> WHERE (<code>order_id</code> = 9706)</p>
<p>when i run the query in the Mysql , i am getting the data fetched properly.</p>
<p>But when i check the output of the result ($trans_result) using getData();
i am getting empty data.</p>
<p>Any help will be appreciated.?
Thanks in advance.</p>
| <p>I'm pretty sure its within the attributes. Make it simpler.</p>
<pre><code> $order_id = 9706;
$trans_result = $transObj->getCollection()
->addFieldToFilter('order_id', array('eq' => $order_id))
</code></pre>
<p>You should the same value because you're using all columns from the table, so there's no necesity to addfielters on SELECT clause. Although if you want to Select an scpecific column use </p>
<pre><code> $trans_result = $trans_result->addFieldToSelect('payment_id')
</code></pre>
<p>Note I'm using addFieldToSelect instead of addAttributeToSelect</p>
|
How to implement styling in page? <p>I am making custom h1 styling menu for customize panel in wordpress site but I don't know how to include the custom h1 styles in html structure of page.</p>
<pre><code>$wp_customize->add_section( 'h1_styles' , array(
'title' => __('H1 Styles','wptthemecustomizer'),
'panel' => 'design_settings',
'priority' => 100
) );
$wp_customize->add_setting(
'wpt_h1_color',
array(
'default' => '#222222',
'transport' => 'postMessage'
)
);
$wp_customize->add_control(
new WP_Customize_Color_Control(
$wp_customize,
'custom_h1_color',
array(
'label' => __( 'Color', 'wptthemecustomizer' ),
'section' => 'h1_styles',
'settings' => 'wpt_h1_color'
)
)
);
</code></pre>
<p>I know I have to do something like this :-</p>
<pre><code> if( get_theme_mod( 'wpt_h1_color') != "" ):
/* code */
endif;
</code></pre>
<p>But I want to know should I apply styles directly in html in head section with the above code or It can be done through function in functions.php.</p>
<p>Thanks for your help !</p>
| <p>You can do it directly in html outputing <code><style></style></code> and some css in there (which is faster than loading external files, and Google Speed Insights maybe not recommends, but approves that way). You can also wp_enqueue_style() if you want to.</p>
|
Painting a line out of circles <p>Im not having any type of syntax error, but more something on the mathematical/logic side. So Im trying to draw a line out of circles, giving only the start and the end point. My problem lies in getting the slope of the line. Here is my code for getting the slope and painting the line: </p>
<pre><code>public void setVectorX(){
xVector = difX/difY;
}
public void setVectorY(){
yVector = difY/difX;
}
public void makeLine(){
setVectorX();
setVectorY();
double prevX;
double prevY;
for(int i = 0; i < d; i++){
if(i == 0){
prevX = startX;
prevY = startY;
} else {
Circle prev = line.get(i-1);
prevX = prev.getX();
prevY = prev.getY();
}
Circle circ = new Circle(prevX+xVector,prevY+yVector,thickness,color);
line.add(circ);
}
}
</code></pre>
<p>The problem with this is, the closer the end point gets to being on once of the same axis, there are larger spaces in between each of the circles, until no circles are actually painted. Does anyone know a more effective way to do this so the line paints how it should 100% of the time?</p>
<p>Thanks in advance!</p>
<p>Heres what it should look like:</p>
<p><a href="https://i.stack.imgur.com/2vLhu.png" rel="nofollow"><img src="https://i.stack.imgur.com/2vLhu.png" alt="enter image description here"></a></p>
<p>Heres what it looks like as one of the axis at the end approaches the same axis as the start:</p>
<p><a href="https://i.stack.imgur.com/8Jw02.png" rel="nofollow"><img src="https://i.stack.imgur.com/8Jw02.png" alt="enter image description here"></a></p>
<p>Here is the code for declaring d, difX, and difY as requested:</p>
<pre><code>public Line(int nStartX, int nStartY, int nEndX, int nEndY, int nThickness,Color nColor){
startX = nStartX;
startY = nStartY;
endX = nEndX;
endY = nEndY;
thickness = nThickness;
d = Math.sqrt(Math.pow((startX-endX), 2)+Math.pow((startX-endX), 2));
color = nColor;
difX = endX-startX;
difY = endY-startY;
makeLine();
}
</code></pre>
| <p>I noticed the dots get more spaced as the difference between difX and difY becomes large. adding this method then calling it after setting the vectors should fix it.
here is the method:</p>
<pre><code>public void rescale(){
double hyp = Math.sqrt(Math.pow(xVector,2) + Math.pow(yVector,2));
xVector /= hyp;
yVector /= hyp;
}
</code></pre>
<p>now change:</p>
<pre><code>setVectorX();
setVectorY();
</code></pre>
<p>to</p>
<pre><code>setVectorX();
setVectorY();
rescale();
</code></pre>
<p>also, you should change</p>
<pre><code>xVector = difX/difY;
</code></pre>
<p>to</p>
<pre><code>xVector = difX
</code></pre>
<p>same for yVector</p>
<p>the second problem is you accidentally used difX twice. you did:</p>
<pre><code>d = Math.sqrt(Math.pow((startX-endX), 2)+Math.pow((startX-endX), 2));
</code></pre>
<p>when it should be:</p>
<pre><code>d = Math.sqrt(Math.pow((startX-endX), 2)+Math.pow((startY-endY), 2));
</code></pre>
|
SQl cmd.ExecuteReader() what does it return <p>I'm studying ASP.NET. I wondered if <code>cmd.ExecuteReader()</code>'s output could be temporally stored into something, like a temp variable, to later re-use it or alter it. I often use temp variables to store stuff.</p>
<p>How can I let a <code>dropbox</code> and a <code>gridview</code> both work with the result of <code>cmd.exectuteReader</code>. I don't want to create a new SQL connection for it.</p>
<p>A variable <code>t</code> might keep the content, but obviously I'm wrong here since it doesn't work. It executes the reader twice, and on the second run there is no data to fill the dropdown box.</p>
<p>How should i do that ?</p>
<pre><code> protected void Page_Load(object sender, EventArgs e)
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; // reading by name DBCS out of the web.config file
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select * from tblEmployees", con);
con.Open();
var t = cmd.ExecuteReader();
GridView1.DataSource = t;// cmd.ExecuteReader();
GridView1.DataBind();
// DropDownList2.DataSource = cmd.ExecuteReader();
DropDownList2.DataSource = t;//cmd.ExecuteReader();
DropDownList2.DataTextField = "Name";
DropDownList2.DataValueField = "EmployeeId";
DropDownList2.DataBind();
}
}
</code></pre>
| <p><a href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx" rel="nofollow">SqlDataReader</a> is a forward-only stream of rows from a SQL Server database.</p>
<p>You can bind a SqlDataReader to a GridView in the following ways:</p>
<p>Simple Examples:</p>
<pre><code> connection.Open();
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
</code></pre>
<p>Or:</p>
<pre><code> DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt;
</code></pre>
<p>Don't forget to configure the columns inside the Gridview control.</p>
|
How to setup Netflix Eureka <p>is there any tutorial/example which shows me step by step how to setup a eureka server cluster and a eureka zuul cluster which forwards my requests to my microservices? The netflix documentation is sometimes a bit old and overall very bad and the spring cloud integration does not show any clustered examples.</p>
| <p>I couldn't find one guide that showed both Zuul and Eureka but there were two Spring guides that cover both topics. With a little magic I don't think it would be too hard to understand how Zuul and Eureka can work together.</p>
<p><a href="https://spring.io/guides/gs/service-registration-and-discovery/" rel="nofollow">https://spring.io/guides/gs/service-registration-and-discovery/</a></p>
<p><a href="https://spring.io/guides/gs/routing-and-filtering/" rel="nofollow">https://spring.io/guides/gs/routing-and-filtering/</a></p>
|
Typescript & Uglify Tasks <p>Ok, so I am playing around with typescript and was hoping to use it to minify my code but as I understand it, typescript does not do that. So I I built my Gruntfile like this, </p>
<pre><code>module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
ts: {
default: {
files: {
'/js/builds/admin.js': ['/typescript/admin/*.ts'],
'/js/builds/main.js': ['/typescript/main/*.ts'],
'/js/builds/public.js': ['/typescript/public/*.ts']
}
},
options: {
fast: 'never',
sourceMap: false
},
},
'uglify': {
options: {
preserveComments: 'some',
},
my_target: {
files: {
//Libs Files
'/assets/js/libs.js': [
'/js/libs/jquery-3.1.1.min.js',
'/js/libs/underscore-1.8.3.min.js',
'/js/libs/backbone-1.3.3.min.js',
],
//Plugin Files
'/assets/js/plugins.js': [
'/js/plugins/alertify.min.js',
],
//Admin Build
'/assets/js/our_admin.js': [
'/js/builds/admin.js'
],
//Main Build
'/assets/js/main.js': [
'/js/builds/main.js'
],
//Public Build
'/assets/js/public.js': [
'/js/builds/public.js'
]
}
}
},
watch: {
'TypeFiles': {
files: ['/typescript/**/*.ts'],
tasks: ['ts'],
options: {
spawn: false
},
},
'JSFiles': {
files: ['/js/**/*.js'],
tasks: ['uglify'],
options: {
spawn: false,
},
},
}
});
grunt.loadNpmTasks("grunt-ts");
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
};
</code></pre>
<p>and what I was trying to do was get typescript to build into standard javascript and then auto run the my uglify task. </p>
<p>As it stands, it works if I added / edit any lib or plugin files (as they have nothing to do with my typescript) but when I edit the typescript files, it will build the JS files, but not run the uglify task?</p>
<p>So how do I get it to do the uglify task after the ts task is completed?</p>
<p>Many thanks.</p>
| <p>I think I have a solution to this issue. I added the TS task to my JSFiles watch task and added the typescript files to the list of files it should watch for, like so:</p>
<pre><code> 'JSFiles': {
files: ['/js/**/*.js', '/typescript/**/*.ts'],
tasks: ['ts', 'uglify'],
options: {
spawn: false,
},
},
</code></pre>
<p>Now this might to be the best option, as it will take some time to complete the typescript and the minify tasks. But I have set this project up in Symfony2 and I prefer to set up my new project pointing to the prod. files.</p>
<p>Thanks </p>
|
java script html element scrape using a scrapy on phython 2.7.11 i get like these <pre><code>[root@Imx8 craigslist_sample]# scrapy crawl spider
/root/Python-2.7.11/craigslist_sample/craigslist_sample/spiders/test.py:1: ScrapyDeprecationWarning: Module `scrapy.spider` is deprecated, use `scrapy.spiders` instead
from scrapy.spider import BaseSpider
/root/Python-2.7.11/craigslist_sample/craigslist_sample/spiders/test.py:6: ScrapyDeprecationWarning: craigslist_sample.spiders.test.MySpider inherits from deprecated class scrapy.spiders.BaseSpider, please inherit from scrapy.spiders.Spider. (warning only on first subclass, there may be others)
class MySpider(BaseSpider):
2016-10-18 18:23:30 [scrapy] INFO: Scrapy 1.2.0 started (bot: craigslist_sample)
2016-10-18 18:23:30 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'craigslist_sample.spiders', 'SPIDER_MODULES': ['craigslist_sample.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'craigslist_sample'}
Traceback (most recent call last):
File "/usr/local/bin/scrapy", line 11, in <module>
sys.exit(execute())
File "/usr/local/lib/python2.7/site-packages/scrapy/cmdline.py", line 142, in execute
_run_print_help(parser, _run_command, cmd, args, opts)
File "/usr/local/lib/python2.7/site-packages/scrapy/cmdline.py", line 88, in _run_print_help
func(*a, **kw)
File "/usr/local/lib/python2.7/site-packages/scrapy/cmdline.py", line 149, in _run_command
cmd.run(args, opts)
File "/usr/local/lib/python2.7/site-packages/scrapy/commands/crawl.py", line 57, in run
self.crawler_process.crawl(spname, **opts.spargs)
File "/usr/local/lib/python2.7/site-packages/scrapy/crawler.py", line 162, in crawl
crawler = self.create_crawler(crawler_or_spidercls)
File "/usr/local/lib/python2.7/site-packages/scrapy/crawler.py", line 190, in create_crawler
return self._create_crawler(crawler_or_spidercls)
File "/usr/local/lib/python2.7/site-packages/scrapy/crawler.py", line 194, in _create_crawler
spidercls = self.spider_loader.load(spidercls)
File "/usr/local/lib/python2.7/site-packages/scrapy/spiderloader.py", line 43, in load
raise KeyError("Spider not found: {}".format(spider_name))
KeyError: 'Spider not found: spider'
</code></pre>
| <p>your should set name='spider' in craigslist_sample/craigslist_sample/spiders/test.py </p>
<pre><code>class MySpider(Spider):
name = 'spider'
def parse(self,response):
#....
</code></pre>
|
Show dateTime column from MySql Database to GridView in C# <p>I am having problems with displaying a column from mysql database to a gridView. The column is DateTime in sql format is a such "2016-03-09 05:09:00". The problem i am facing is that other column gets displayed to the gridView but not the dateTime from Mysql database.</p>
<p>Here is the code for getting the columns from the database:</p>
<pre><code>string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT app_number, app_datetime, app_confirm, pat_ID, rec_ID, doc_ID FROM appointment"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
</code></pre>
<p>This is the gridView :
</p>
<pre><code> <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
</code></pre>
<p> </p>
<p>
</p>
<pre><code> <asp:BoundField DataField="app_number" HeaderText="App#" ReadOnly="true" />
<asp:TemplateField HeaderText="App Date">
<ItemTemplate>
<%# Eval("app_datetime")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtApp_datetime" Text='<%# Eval("app_datetime")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<%# Eval("app_confirm")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtConfirm" Text='<%# Eval("app_confirm")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="pat_ID" HeaderText="Patient ID" ReadOnly="true" />
<asp:BoundField DataField="rec_ID" HeaderText="Receptionist" ReadOnly="true" />
<asp:BoundField DataField="doc_ID" HeaderText="Doctor" ReadOnly="true" />
</Columns>
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</code></pre>
<p>
The output i Get
<a href="https://i.stack.imgur.com/vxaqq.png" rel="nofollow"><img src="https://i.stack.imgur.com/vxaqq.png" alt="Data that is Displayed in gridView"></a></p>
| <p>Please Use this Instead of your Text hope this works,</p>
<pre><code>Text='<%# Eval("app_datetime", "{0:dd/MM/yyyy}") %>' />
</code></pre>
|
Understaning of static objects in main function <p>I am trying to build application, where it will be choosen according to console argument if its gonna be gui application or console.</p>
<pre><code>int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QCommandLineParser parser;
parser.setApplicationDescription("Test");
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption guiOption(QStringList() << "g" << "gui", "Gui");
parser.addOption(guiOption);
parser.process(app);
bool isGUI = parser.isSet(guiOption);
APPstub stub(0,isGUI);
if (isGUI) { //GUI APP
static APP_Window ui(&stub); ////*****THIS
ui.show();
}
else { // CONSOLE APP
static APP_Console con(&stub); ////*****THIS
con.showMenu();
}
return app.exec();
}
</code></pre>
<p>I figured out that I need those objects created in condition(////*****THIS)
needs to be static, but I dont understand why?
The thing is: when I had for example APP_Window ui(&stub) outside of the condition, it worked and showed gui.
If I have it inside the condition, Window pops and go away quickly.</p>
<p>I am confused about that... could you help me understand that problem?
Thank you :)</p>
| <p>Because when your code goes out of braces:"con" and "ui" objects will be destroyed because their scope limited by braces if they are not static.</p>
|
How to deal with logic error with async? <p>As I use async in my work. I will send a ajax requst, and then receive.</p>
<p>I will write like this.</p>
<pre><code>const API = {
init() {
this.initIndexData();
},
async initIndexData() {
try {
let data = await this.getData();
} catch (e) {
console.log(e);
}
},
getData() {
new Promise((resolve, reject) => {
$.ajax({
url: 'xx.json',
success(res) {
if (res.success) {
resolve(res);
} else {
reject(res);
}
}
})
});
}
}
API.init();
</code></pre>
<p>As I don't like wirte code with <code>try..catch</code>. Is there any solutions to deal with <code>reject</code> without using <code>try catch</code>.</p>
<p>I think I can always use <code>reolve</code> whenever what happens. Like this.</p>
<pre><code>if (res.success) {
resolve(res);
} else {
reject(res);
}
...
let data = await this.getData();
if (data.success) {
// do sth success logic
} else {
// do sth error logic
}
</code></pre>
<p>Above is a solution to deal with <code>reject</code> without <code>try catch</code>, but this code isn't semantic.</p>
| <p>You can use the ordinary <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch" rel="nofollow"><code>.catch</code> method</a> of promises:</p>
<pre><code>async initIndexData() {
let data = await this.getData().catch(e => {
console.log(e);
});
},
async getData() {
const res = await $.ajax({
// ^^^^^ much better than `new Promise`
// as it does not ignore the ajax error handler
url: 'xx.json',
});
if (res.success) {
return res;
} else {
throw res;
}
}
</code></pre>
|
DBPedia missing some English abstracts and comments <p>I'm aware that DBpedia had a new release last week. It appears as if that release is missing some English abstract and comment fields.</p>
<p>For example, last week I was able to get the abstract for George Washington, now there are eight abstracts but none are in English.</p>
<p>sparql query:</p>
<pre><code> SELECT ?abstract
WHERE {
<http://dbpedia.org/resource/George_Washington> dbo:abstract ?abstract .
FILTER langMatches( lang(?abstract), "en" )
}
</code></pre>
<p><a href="http://dbpedia.org/snorql/?query=%20%20%20%20SELECT%20%3Fabstract%0D%0A%20%20%20%20WHERE%20%7B%20%0D%0A%20%20%20%20%20%20%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FGeorge_Washington%3E%20dbo%3Aabstract%20%3Fabstract%20.%0D%0A%20%20%20%20%20%20FILTER%20langMatches%28%20lang%28%3Fabstract%29%2C%20%22en%22%20%29%0D%0A%20%20%20%20%7D" rel="nofollow">sparql results</a></p>
<p>Perhaps that data moved somewhere else? Any ideas on how to get that data now?</p>
| <p>Short term, you might try the <a href="http://lod.openlinksw.com/sparql?default-graph-uri=&qtxt=PREFIX%20%20dbo%3A%20%20%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2F%3E%0D%0A%0D%0ASELECT%20%3Fabstract%0D%0AWHERE%20%7B%20%0D%0A%20%20%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FGeorge_Washington%3E%20dbo%3Aabstract%20%3Fabstract%20.%0D%0A%20%20FILTER%20langMatches%28%20lang%28%3Fabstract%29%2C%20%22en%22%20%29%0D%0A%7D&format=text%2Fhtml&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&debug=on" rel="nofollow">LOD Cloud Cache</a> (also provided by my employer, <a href="http://www.openlinksw.com/" rel="nofollow">OpenLink Software</a>, long-term sponsor of the <a href="http://dbpedia.org/sparql" rel="nofollow">public DBpedia endpoint</a>) where I've just confirmed you'll currently find <a href="http://lod.openlinksw.com/sparql?default-graph-uri=&query=PREFIX%20%20dbo%3A%20%20%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2F%3E%0D%0A%0D%0ASELECT%20%3Fabstract%0D%0AWHERE%20%7B%20%0D%0A%20%20%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FGeorge_Washington%3E%20dbo%3Aabstract%20%3Fabstract%20.%0D%0A%20%20FILTER%20langMatches%28%20lang%28%3Fabstract%29%2C%20%22en%22%20%29%0D%0A%7D&format=text%2Fhtml&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&debug=on" rel="nofollow">the abstract you're looking for</a>.</p>
<p>Longer term, there are <a href="https://github.com/dbpedia" rel="nofollow">multiple GitHub projects/pages for DBpedia</a>. I suggest instead, <a href="https://sourceforge.net/p/dbpedia/mailman/dbpedia-discussion/" rel="nofollow">dbpedia-discussion</a>, <a href="https://twitter.com/DBpedia" rel="nofollow">@DBpedia</a>, and/or <a href="https://twitter.com/OpenLink" rel="nofollow">@OpenLink</a>. </p>
|
Is there any tool through which i can join data from two tables - One in hive & Other in cassandra. Also I have to run this job through oozie <p>I have one table in hive & one table in cassandra.
I want to join them, then based on result, store some data into cassandra.</p>
<pre><code>Ques 1) Is it possible?
Ques 2) Suggest the solution that can be run through oozie.
</code></pre>
<p>Thanks in advance </p>
| <p>Yes, this is possible.</p>
<p>You have to export the data from Hive(delimited data) and export them into cassandra and then apply join and vice versa.</p>
<p>These are possible in Oozie.</p>
|
allow user to change text in div <p>Hello guys I am trying to create a function in js that will allow user to edit a text inside a div. here's my view:</p>
<pre><code>@endsection
<div onload="InitEditable ();" id="content-link2"></div>
@show
</code></pre>
<p>Here's my HTML file loaded inside div id="content-link2"::</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Template 1</title>
<link href="http://localhost/fyproject/public/templates/css.css" rel="stylesheet" type="text/css">
</head>
<body class="pink">
<div contenteditable="true" id="content" class="draggable ui-widget-content pink"><p>hello</p></div>
<div id="comments">
<form name="forma">
<textarea name="commentUser" id="commentUser" cols="40" rows="5">
Comments here...
</textarea><br>
<input type="submit" value="Ready!" onClick="writeComment(e);" />
</div>
</form>
</body>
</html>
</code></pre>
<p>JS::</p>
<pre><code>var editorDoc;
function InitEditable () {
var editor = document.getElementsById('content-link2');
editorDoc = editor.contentWindow.document;
var editorBody = editorDoc.div;
// turn off spellcheck
if ('spellcheck' in editorBody) { // Firefox
editorBody.spellcheck = false;
}
if ('contentEditable' in editorBody) {
// allow contentEditable
editorBody.contentEditable = true;
}
else { // Firefox earlier than version 3
if ('designMode' in editorDoc) {
// turn on designMode
editorDoc.designMode = "on";
}
}
}
</code></pre>
<p>I will explain a process. Customer clicks on image which loads a html file inside a div. I then allow user to move div around which is with html file and now I want to allow customer to change text inside that div</p>
<p><a href="https://i.stack.imgur.com/tPwfD.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/tPwfD.jpg" alt="So I want to change text inside a red div"></a></p>
| <p>Why don't you try <code>contenteditable</code>. </p>
<p>For example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div contenteditable="true">Type to edit...</div></code></pre>
</div>
</div>
</p>
<p>As it says in <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content" rel="nofollow">MDN - Making Content Editable</a>:</p>
<blockquote>
<p>In HTML, any element can be editable. By using some JavaScript event
handlers, you can transform your web page into a full and fast rich
text editor. This article provides some information about this
functionality.</p>
</blockquote>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.