input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
sort a table based on the column values <p>I want to sort a table when some button is clicked. If the button with id "easy" is clicked I want to sort by easy levels, if the button with id hard is clicked I want to sort by hard levels, in a descending order.</p>
<p>Im trying to do this for the easy button case and I already have the values in a array, but now Im not seeing how to sort this so the table can be sorted based on the easy values on the column "EasyLevels". Do you have some idea to help?</p>
<pre><code>$("#easy").each(function() {
if ($.inArray($(this).text(), arr) == -1)
arr.push($(this).text());
alert($(this).text());
});
</code></pre>
<p>I have a table in this format:</p>
<pre><code>ID | GameName | EasyLevels | HardLevels | TotalLevels
1 Stakeboard 32 28 60
....
</code></pre>
<p>The html is like below, I dont have any class or id in any <code><td></code>. </p>
<pre><code><button id="easy">Sort By Easy Levels</button>
<button id="hard">Sort By Hard Levels</button>
<button id="total">Sort By Total Levels</button>
<table>
<th>GameId</th>
<th>GameName</th>
<th>EasyLevels</th>
<th>HardLevels</th>
<th>TotalLevels</th>
<tr>
<td>Game Id</td>
<td>Game Title 1</td>
<td class="easy">12</td>
<td class="hard">30</td>
<td class="all">42</td>
</tr>
<tr>
<td>Game Title 2</td>
<td class="easy">10</td>
<td class="hard">26</td>
<td class="total">36</td>
</tr>
....
</table>
</code></pre>
| <p>You can achieve this using <a href="http://tablesorter.com/" rel="nofollow">tablesorter</a> jquery plugin:</p>
<pre><code>$(document).ready(function()
{
$("#myTable").tablesorter();
}
);
</code></pre>
|
How to get equal spaces within each property in JSON using GSON? <p>I am using Gson to play with JSON. In my below code:</p>
<pre><code>JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("fname", "john");
jsonObject.addProperty("lname", "cena");
System.out.println(jsonObject.toString());
</code></pre>
<p>It prints out like this: </p>
<pre><code>{"fname":"john","lname":"cena"}
</code></pre>
<p>How can I get stuff printed like this instead in the below format. As you can see, I have spaces and everything properly.</p>
<pre><code>{"fname" : "john", "lname" : "cena"}
</code></pre>
| <p>You can use Gson's pretty printing. JSON.org's library has something similar as well. (I'm sure Jackson does as well). Note: this will also format it so it's very readable.</p>
<pre><code>Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);
System.out.println(json);
</code></pre>
|
Nested Attribute Form Validation Bugs <p>I'm seeing an odd bug with a nested attribute form. I have two models, <strong>Parties</strong>, and <strong>Guests</strong>. Party has_many Guests, and Guest belongs_to Party. I have a form that creates Guests through Party.</p>
<p>The bug I'm seeing is as follows:</p>
<ul>
<li>When I first visit the form page, everything loads but I can't submit data. If I refresh the page as soon as it renders, then whatever I type in hits the database when I press submit. I discovered that the submit button changes to its active state when you click on it but it never leaves it when it's not working.</li>
</ul>
<p>Why do I have to refresh my page before the form will submit data? I'd appreciate some help unraveling this one. I'm not even sure which thread to start tugging on.</p>
<p><strong>party.rb</strong></p>
<pre><code>class Party < ApplicationRecord
belongs_to :event
has_many :guests, inverse_of: :party
accepts_nested_attributes_for :guests, :reject_if => proc { |attribute| attribute[:last_name].blank? }
validate :validate_nested_attributes
def validate_nested_attributes
guests.each do |guest|
errors.add(:first_name, "first name cannot be blank") if guest.first_name.blank?
errors.add(:email, "must be valid") if !email_is_valid(guest.email)
end
end
def email_is_valid(email)
email =~ /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
end
end
</code></pre>
<p><strong>guest.rb</strong></p>
<pre><code>class Guest < ApplicationRecord
belongs_to :party
belongs_to :event
end
</code></pre>
<p><strong>parties_controller.rb</strong></p>
<pre><code>class PartiesController < ApplicationController
def index
end
def new
@event = Event.friendly.find(params[:event_id])
@party = @event.parties.new
10.times {@party.guests.build}
end
def create
@event = Event.friendly.find(params[:event_id])
@party = @event.parties.new(party_params)
if @party.save
redirect_to event_guests_path(@event)
else
render 'new'
end
end
private
def party_params
params.require(:party).permit(:id, :party_name, guests_attributes: [:event_id, :id, :first_name, :last_name, :email, :phone])
end
end
</code></pre>
<p><strong>new.html.erb</strong></p>
<pre><code><div class="col-sm-10 col-sm-offset-1"><h2>Create a New Invitation Party</h2></div>
<div class="form-group col-sm-10 col-sm-offset-1 well" id="guests">
<ul>
<% if @party.errors.any? %>
<% @party.errors.each do |attribute, msg| %>
<li><%= "#{attribute} #{msg}" if @party.errors[attribute].first == msg %>
<% end %>
<% end %>
<%= form_for [@event, @party] do |f| %>
</ul>
<%= render :partial => 'guest_fields', :locals => { :f => f } %>
</div>
<div class="col-sm-8 col-sm-offset-2 pull-right">
<%= f.submit "Create Party", class: "btn btn-primary pull-right", style: "margin-right: 10%;" %>
<%= link_to "Back", event_guests_path(@event), class: "btn btn-danger pull-right", style: "margin-right: 5px;" %>
</div>
<% end %>
</code></pre>
<p><strong>_guest_fields.html.erb</strong></p>
<pre><code><%= f.fields_for :guests do |ff| %>
<%= ff.hidden_field :event_id, :value => @event.id %>
<div class="row">
<div class="form-group col-sm-3">
<%= ff.text_field :first_name, placeholder: "First Name", class: "form-control" %>
</div>
<div class="form-group col-sm-3">
<%= ff.text_field :last_name, placeholder: "Last Name", class: "form-control" %>
</div>
<div class="form-group col-sm-3">
<%= ff.text_field :email, placeholder: "Email Address", class: "form-control" %>
</div>
<div class="form-group col-sm-3">
<%= ff.text_field :phone, placeholder: "Phone Number", class: "form-control" %>
</div>
<hr>
</div>
<% end %>
</code></pre>
<p><strong>Rails server log for the GET request</strong></p>
<pre><code>Started GET "/events/2993Alexandro/parties/new" for -.-.-.- at 2016-10-11 23:00:56 +0000
Cannot render console from -.-.-.-! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by PartiesController#new as HTML
Parameters: {"event_id"=>"2993Alexandro"}
Event Load (0.5ms) SELECT "events".* FROM "events" WHERE "events"."path" = $1 ORDER BY "events"."id" ASC LIMIT $2 [["path", "2993Alexandro"], ["LIMIT", 1]]
Rendering parties/new.html.erb within layouts/application
Rendered parties/_guest_fields.html.erb (9.7ms)
Rendered parties/new.html.erb within layouts/application (15.9ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 6], ["LIMIT", 1]]
Rendered layouts/_left_bar.html.erb (1.4ms)
Completed 200 OK in 180ms (Views: 98.5ms | ActiveRecord: 0.8ms)
</code></pre>
| <pre><code> <%= form_for [@event, @party] do |f| %>
</ul>
</code></pre>
<p>Why is your open-form tag half inside the <code>ul</code> ? Where is the matching end? A form is a block-level component - it should be fully contained within the outer block - not half in one tag and half in another.</p>
<p>I don't know if this will solve your problem, but it will certainly fix your html. try something more like this:</p>
<pre><code><div class="col-sm-10 col-sm-offset-1"><h2>Create a New Invitation Party</h2></div>
<div class="form-group col-sm-10 col-sm-offset-1 well" id="guests">
<ul>
<% if @party.errors.any? %>
<% @party.errors.each do |attribute, msg| %>
<li><%= "#{attribute} #{msg}" if @party.errors[attribute].first == msg %>
<% end %>
<% end %>
</ul>
<%= form_for [@event, @party] do |f| %>
<%= render :partial => 'guest_fields', :locals => { :f => f } %>
<div class="col-sm-8 col-sm-offset-2 pull-right">
<%= f.submit "Create Party", class: "btn btn-primary pull-right", style: "margin-right: 10%;" %>
<%= link_to "Back", event_guests_path(@event), class: "btn btn-danger pull-right", style: "margin-right: 5px;" %>
</div>
<% end %>
</div>
</code></pre>
|
Changing ASP.NET Identity Password <p>I have a class that creates a user by searching for the email and making sure it doesn't exist and it creates a user:</p>
<pre><code>public async Task EnsureSeedDataAsync()
{
if (await _userManager.FindByEmailAsync("test@theworld.com") == null)
{
// Add the user.
var newUser = new CRAMSUser()
{
UserName = "test",
Email = "test@crams.com"
};
await _userManager.CreateAsync(newUser, "P@ssw0rd!");
}
}
</code></pre>
<p>I am trying create another class to change the password, with the same method but I am confused as to how to create a currentUser object to be passed into the RemovePassword and AddPassword calls. This is what I have so far :</p>
<pre><code> public async Task ChangePassword()
{
if (await _userManager.FindByEmailAsync("test@theworld.com") != null)
{
_userManager.RemovePasswordAsync(currentUser);
_userManager.AddPasswordAsync(currentUser, "newPassword");
}
}
</code></pre>
<p><strong>Can someone please direct me in the right direction as I am new to this and don't know how to transfer the currentUser object, that contains the email that is being searched.</strong></p>
| <p><code>FindByEmailAsyc</code> returns the user object, you need to save it to a variable and pass that to the other userManager calls. Also, the <code>RemovePassword</code> and <code>AddPassword</code> methods take the key value of your <code>User</code> object as a parameter, not the whole <code>User</code> object.</p>
<pre><code>public async Task ChangePassword()
{
var currentUser = await _userManager.FindByEmailAsync("test@theworld.com")
if (currentUser != null)
{
_userManager.RemovePasswordAsync(currentUser.Id);
_userManager.AddPasswordAsync(currentUser.Id, "newPassword");
}
}
</code></pre>
|
Error with picker view swift <p>I'm trying to change text font and color of picker view. But when i do that i get an error, please help. </p>
<pre><code>func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let attributedString = NSAttributedString(string: "some string", attributes: [NSForegroundColorAttributeName : UIColor.red])
return attributedString
}
</code></pre>
<p><img src="https://i.stack.imgur.com/Na9XF.png" alt="ErrorImage"></p>
| <p>i did something like that by providing a view like this </p>
<pre><code> func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let pickerLabel = UILabel()
pickerLabel.textColor = UIColor.black
pickerLabel.text = "\(dataSource[row])"
pickerLabel.font = UIFont(name: "OpenSans-Light", size: 70)
pickerLabel.textAlignment = NSTextAlignment.center
return pickerLabel
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataSource.count
}
</code></pre>
|
JS Regex: Remove anything (ONLY) after a word <p>I want to remove all of the symbols (The symbol depends on what I select at the time) after each word, without knowing what the word could be. But leave them in before each word.</p>
<p>A couple of examples:</p>
<p><code>!!hello! my! !!name!!! is !!bob!!</code> should return...</p>
<p><code>!!hello my !!name is !!bob</code> ; for <code>!</code></p>
<p>and</p>
<p><code>$remove$ the$ targetted$@ $$symbol$$@ only $after$ a $word$</code> should return...</p>
<p><code>$remove the targetted@ $$symbol@ only $after a $word</code> ; for <code>$</code></p>
| <p>You need to use capture groups and replace:</p>
<pre><code>"!!hello! my! !!name!!! is !!bob!!".replace(/([a-zA-Z]+)(!+)/g, '$1');
</code></pre>
<p>Which works for your test string. To work for any generic character or group of characters:</p>
<pre><code>var stripTrailing = trail => {
let regex = new RegExp(`([a-zA-Z0-9]+)(${trail}+)`, 'g');
return str => str.replace(regex, '$1');
};
</code></pre>
<p>Note that this fails on any characters that have meaning in a regular expression: []{}+*^$. etc. Escaping those programmatically is left as an exercise for the reader.</p>
<h2>UPDATE</h2>
<p>Per your comment I thought an explanation might help you, so:</p>
<p>First, there's no way in this case to replace only part of a match, you have to replace the <strong>entire</strong> match. So we need to find a pattern that matches, split it into the part we want to keep and the part we don't, and replace the whole match with the part of it we want to keep. So let's break up my regex above into multiple lines to see what's going on:</p>
<p>First we want to match any number of sequential alphanumeric characters, that would be the 'word' to strip the trailing symbol from:</p>
<pre><code>( // denotes capturing group for the 'word'
[ // [] means 'match any character listed inside brackets'
a-z // list of alpha character a-z
A-Z // same as above but capitalized
0-9 // list of digits 0 to 9
]+ // plus means one or more times
)
</code></pre>
<p>The capturing group means we want to have access to <em>just</em> that part of the match.
Then we have another group</p>
<pre><code>(
! // I used ES6's string interpolation to insert the arg here
+ // match that exclamation (or whatever) one or more times
)
</code></pre>
<p>Then we add the <code>g</code> flag so the replace will happen for <em>every</em> match in the target string, without the flag it returns after the first match. JavaScript provides a convenient shorthand for accessing the capturing groups in the form of automatically interpolated symbols, the '$1' above means 'insert contents of the first capture group here in this string'.</p>
<p>So, in the above, if you replaced '$1' with '$1$2' you'd see the same string you started with, if you did 'foo$2' you'd see foo in place of every word trailed by one or more !, etc.</p>
|
I have 4 sets of two numbers [1x2]. How do I add each corresponding row? <p>Here are the four [2x1] variables.</p>
<pre><code>A1 =
0.5653
0.5648
phi1 =
5.3637
5.3951
A2 =
0.6063
0.6057
phi2 =
3.1646
3.1961
</code></pre>
<p>I need to add all rows together.</p>
<p>I wrote the function below</p>
<pre><code>function [At] = somme_signaux(A, phi);
At=sum((A+phi));
end
[At] = somme_signaux([A1 A2],[phi1 phi2])
At =
2.3421 17.1195
</code></pre>
<p>The real answers are:</p>
<pre><code>0.5653+5.3637+0.6063+3.1646 = 9.6999
0.5648+5.3951+0.6057+3.1961 = 9.7617
</code></pre>
| <p>Found it!</p>
<p>function [At] = somme_signaux(A, phi)
At=sum(plus(A,phi),2);
end</p>
|
MySQL PHP Undefined offset Error <p>I have a table called <strong>lynked_v1</strong> and a column in MySQL called <strong>probability_single_free</strong></p>
<pre><code> +----------------------------------+
| id | probability_single_free |
| ---------------------------------|
| 0 | 100.00 |
| 1 | 100.00 |
| 2 | 100.00 |
| 3 | 100.00 |
| 4 | 100.00 |
| 5 | 100.00 |
| 6 | 100.00 |
| 7 | 100.00 |
+----------------------------------+
</code></pre>
<p>I am trying to echo each row with the following command:</p>
<pre><code><?php
error_reporting(-1);
ini_set('display_errors', true);
require_once ('/var/www/html/MySQL/mysqli_connect.php');
echo "Connected successfully";
$query = "SELECT probability_single_free FROM lynked_v1";
$response = @mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($response)) {
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
echo $row[4];
echo $row[5];
echo $row[6];
echo $row[7];
}
?>
</code></pre>
<p>$row[0] prints on the screen okay. But I get the following errors for the rest of the rows:</p>
<pre><code>Notice: Undefined offset: 1 in /var/www/html/index.php on line 56
Notice: Undefined offset: 2 in /var/www/html/index.php on line 57
Notice: Undefined offset: 3 in /var/www/html/index.php on line 58
Notice: Undefined offset: 4 in /var/www/html/index.php on line 59
Notice: Undefined offset: 5 in /var/www/html/index.php on line 60
Notice: Undefined offset: 6 in /var/www/html/index.php on line 61
Notice: Undefined offset: 7 in /var/www/html/index.php on line 62
</code></pre>
<p>How do I print each row separately? </p>
| <p>Use this code:</p>
<pre><code><?php
error_reporting(-1);
ini_set('display_errors', true);
require_once ('/var/www/html/MySQL/mysqli_connect.php');
echo "Connected successfully";
$query = "SELECT probability_single_free FROM lynked_v1";
$response = @mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($response)) {
echo $row["probability_single_free"];
}
?>
</code></pre>
<p>It will work like a charm)</p>
|
Converting url encode data from curl to json object in python using requests <p>What is the best way to convert the below curl post into python request using the requests module:</p>
<pre><code>curl -X POST https://api.google.com/gmail --data-urlencode json='{"user": [{"message":"abc123", "subject":"helloworld"}]}'
</code></pre>
<p>I tried using python requests as below, but it didn't work: </p>
<pre><code>payload = {"user": [{"message":"abc123", "subject":"helloworld"}]}
url = https://api.google.com/gmail
requests.post(url, data=json.dumps(payload),auth=(user, password))
</code></pre>
<p>Can anybody help. </p>
| <p>As the comment mentioned, you should put your <code>url</code> variable string in quotes <code>""</code> first.</p>
<p>Otherwise, your question is not clear. What errors are being thrown and/or behavior is happening?</p>
<p><a href="http://stackoverflow.com/questions/17936555/how-to-construct-the-curl-command-from-python-requests-module"> New cURL method in Python </a></p>
|
Angularfire2 AuthGuard Explanation <p>I am fairly new to Angular and I am trying to understand setting up an AuthGuard for blocking certain routes when a user is logged in or not. I found this code while searching around and it does work. However I do not fully understand what the code is doing. If anyone could just explain what everything is doing here it would be a huge help. Thank you!</p>
<pre><code>constructor(private auth: FirebaseAuth, private router: Router) {}
canActivate(): Observable<boolean> {
return this.auth
.take(1)
.map((authState: FirebaseAuthState) => !!authState)
.do(authenticated => {
if (!authenticated) this.router.navigate(['']);
});
}
</code></pre>
| <p>When the Angular 2 router tries to access a route, it evaluates the 'canActivate' method on all the guards added to the route in your configuration. </p>
<p>If one of these guards return false, or return an observable that evaluates to false when you subscribe to it, it prevents the router from accessing this page.</p>
|
Why is ServicePointManager.SecurityProtocol different in console application and IIS website on the same machine? <p>I am trying to update a set of projects to .NET 4.6.1 in order to get TLS 1.2 support. The solution contains a mix of class libraries, console applications, WebForms websites, and MVC websites.</p>
<p>I have already changed every project and website to target .NET 4.6.1, and recompiled everything.</p>
<p>Now, if I check the default value for ServicePointManager.SecurityProtocol in one of the console applications, then I get the following:</p>
<pre><code>Tls, Tls11, Tls12
</code></pre>
<p>But if I check the default value for ServicePointManager.SecurityProtocol in one of the WebForms websites running under IIS, then I get the following:</p>
<pre><code>Ssl3, Tls
</code></pre>
<p>So I can see different values for ServicePointManager.SecurityProtocol on the same machine when comparing a console application and a WebForms website under IIS.</p>
<p>I can confirm that the WebForms websites have the following in Web.config under "system.web":</p>
<pre><code><compilation debug="true" targetFramework="4.6.1">
</code></pre>
<p>But it appears as though IIS is ignoring the "targetFramework" attribute.</p>
<p>Is there something that I need to do in IIS to get this to work as expected?</p>
<p><strong>UPDATE:</strong></p>
<p>It appears that IIS is actually honoring the "targetFramework" attribute, but ServicePointManager.SecurityProtocol still returns a different default value under IIS when compared to a console application.</p>
| <p>OK - I worked it out.</p>
<p>To change a website's target framework, you right-click it, click "Property Pages", then change "Target Framework" on the "Build" page.</p>
<p>If you do this, then in will change the "targetFramework" attribute on the "compilation" node under the "system.web" node:</p>
<pre><code><compilation targetFramework="4.6.1" />
</code></pre>
<p>But this is not enough - you also need to change the "targetFramework" attribute on the "httpRuntime" node under the "system.web" node:</p>
<pre><code><httpRuntime targetFramework="4.6.1" />
</code></pre>
<p>And now, both the website under IIS and the console application report back the same thing for ServicePointManager.SecurityProtocol.</p>
|
Can I modify a variable within a string with another variable in PHP? <pre><code>$pet ='dog';
$action='My '. $pet . 'likes to run.';
//The part I would like to modify
$pet ='cat';
//Modify the $pet variable inside the $action variable
//after it has been defined.
echo $action;
</code></pre>
<p>This will output: My dog likes to run</p>
<p>Can I make it output: My cat likes to run</p>
<p>I also tried: </p>
<pre><code>$pet ='dog';
$action=sprintf('My %s likes to run.', $pet);
$pet ='cat';
echo $action;
</code></pre>
<p>I do know that this could be achieved by creating a function with an argument like below. But I'm a php beginner and curious about the other methods.</p>
<pre><code>function action($pet = "dog") {
$p = 'My'. $pet . 'likes to run.';
return $p;
}
$pet = 'cat';
echo action($pet);
</code></pre>
| <p>Well, I know that you probably weren't looking for this, but it is late and I am bored. </p>
<p>Disclaimer: this is a <em>bad idea</em>.</p>
<pre><code>class MyString
{
private $format, $pet;
public function __construct($format, &$pet)
{
$this->format = $format;
$this->pet = &$pet;
}
public function __toString()
{
return sprintf($this->format, $this->pet);
}
}
$myString = new MyString('This is my little %s, cool huh?', $pet);
$pet = 'cat';
echo $myString."\n";
$pet = 'dog';
echo $myString."\n";
$pet = 'goldfish';
echo $myString."\n";
</code></pre>
<p>Output:</p>
<pre><code>This is my little cat, cool huh?
This is my little dog, cool huh?
This is my little goldfish, cool huh?
</code></pre>
<p>Demo: <a href="https://3v4l.org/XmUEZ" rel="nofollow">https://3v4l.org/XmUEZ</a></p>
<p>Basically this class stores a reference to the <code>$pet</code> variable in it's fields. As such, when the <code>$pet</code> variable is updated, the reference in the class is updated as well.</p>
<hr />
<p>Another one for good measure:</p>
<pre><code>function mysprintf($format, &$variable)
{
return function() use ($format, &$variable) {
return sprintf($format, $variable);
};
}
$print = mysprintf('This is my little %s, cool huh?', $pet);
$pet = 'cat';
echo $print()."\n";
$pet = 'dog';
echo $print()."\n";
$pet = 'goldfish';
echo $print()."\n";
</code></pre>
<p><a href="https://3v4l.org/KJTKj" rel="nofollow">https://3v4l.org/KJTKj</a></p>
<p>(Ab)uses closures to save the reference. Probably even worse.</p>
<hr />
<p>Why is this a bad idea, you ask?</p>
<p>Consider solely this statement:</p>
<pre><code>$pet = 'goldfish';
</code></pre>
<p>This is a simple assignment. Most programmers assume that this statement has no side-effects. That means that this statement changes nothing in the execution flow besides creating a new variable.</p>
<p>Our <code>MyString</code> or <code>mysprintf</code> violate this assumption. <em>What should be a simple assignment, now has side-effects.</em> It violates a programmer's expectation in the worst way possible. </p>
|
I want to check object code with two versions of libQtCore.a <p>I am also making static library of Qt (qt.4.3.3) , the steps to do the same are</p>
<p>I downloaded a open source of qt-all-opensource-src-4.3.3. I built static libraries using following steps. The gcc version I am using is gcc 5.2.0</p>
<pre><code>cd qt-all-opensource-src-4.3.3
gmake conflcean
./configure -release -static -largefile -qt3support -qt-libpng -qt-libmng -qt-libtiff -qt-libjpeg -glib -platform linux-g++-64 -confirm-license -no-openssl -no-qdbus -prefix ./static_new -prefix-install -opengl -sm -lSM -lICE -xshape -lX11 -xinerama -lXinerama -xcursor -lXcursor -xfixes -lXfixes -xrandr -lXrandr -xrender -lXrender -fontconfig -lfontconfig -tablet -lXi -xkb -glib -lglib-2.0 -lXext -lz -lgthread-2.0
gmake
gmake install
</code></pre>
<p>I am getting following error message</p>
<p>from ../../corelib/codecs/qsimplecodec_p.h:36,
from ../../corelib/codecs/qsimplecodec.cpp:22:
../../../include/QtCore/../../src/corelib/thread/qatomic.h: In instantiation of ?QAtomicPointer::QAtomicPointer(T*) [with T = QByteArray]?:
../../corelib/codecs/qsimplecodec.cpp:592:74: required from here<br>
../../../include/QtCore/../../src/corelib/thread/qatomic.h:190:7: error: ?init? was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
../../../include/QtCore/../../src/corelib/thread/qatomic.h:190:7: note: declarations in dependent base ?QBasicAtomicPointer? are not found by unqualified lookup
../../../include/QtCore/../../src/corelib/thread/qatomic.h:190:7: note: use ?this->init? instead
gmake[1]: <strong>* [.obj/release-static/qsimplecodec.o] Error 1
gmake[1]: Leaving directory `/in/inndt69/Projects/oasys/QT/QT/qt-x11-commercial-src-4.3.3/qt-x11-commercial-src-4.3.3/src/tools/rcc'
gmake: *</strong> [sub-rcc-make_default-ordered] Error 2</p>
<p>After following the suggestions from <a href="http://stackoverflow.com/questions/39844038/what-is-correct-way-to-solve-the-build-error-while-making-static-libraries-of-qt">What is correct way to solve the build error while making static libraries of Qt</a></p>
<p>I did two experiments</p>
<pre><code>1) Experiment1 : compiled the Qt4.3.3 with -fpermissive flag and I got version of libQtCore.a
2) Experiment2 : corrected the code and used this-init insted of init at line 190 and build passed
</code></pre>
<p>Now I have to compare the object code generated with two versions of libQtCore (from two experiments) . I tried to use following command</p>
<pre><code>1) objdump -t /pathtoQt/experiment1/libQtCore.a | grep -i atomic
1) objdump -t /pathtoQt/experiment2/libQtCore.a | grep -i atomic
</code></pre>
<p>but I am not get any reference of QAtomicPointer in the objdumps . </p>
<p>Can someone guide me how to compare the object code generated with the -fpermissive flag against the corrected code that uses { this->init(t); } in the line that causes the error.</p>
| <p>You're facing the error because the very old Qt code that you're using is not valid C++: the old compilers were more permissive and accepted that invalid code. You have to patch your copy of Qt to fix the bug.</p>
|
Riotjs (Riot typescript) can't overwrite method on typescript class <p>This is weird. What am I doing wrong?</p>
<pre><code>class Store extends Riot.Observable {
trigger():void {
// shouldn't this be completely overwriting the trigger method on riot.observable?
console.log("my trigger....");
}
}
let store = new Store();
store.trigger();
</code></pre>
<p>Expected behaviour: "my trigger...." in the console. What I get is the original implementation of trigger on the Riot.Observable, which errors because of no parameters being passed.</p>
<p>If I poke the <code>store</code> object I can see on <code>store.__proto__</code> does have trigger on there, with my implementation. But <code>store</code> iself has its own (original) copy of <code>trigger()</code></p>
<p>Please see <a href="https://jsfiddle.net/sidouglas/5spbvpnn/" rel="nofollow">https://jsfiddle.net/sidouglas/5spbvpnn/</a></p>
<p>I referenced <a href="https://www.typescriptlang.org/play/#src=class%20A%20%7B%0A%09%2F%2F%20A%20protected%20method%0A%09protected%20doStuff()%0A%09%7B%0A%09%09alert(%22Called%20from%20A%22)%3B%0A%09%7D%0A%09%0A%09%2F%2F%20Expose%20the%20protected%20method%0A%09public%20callDoStuff()%0A%09%7B%0A%09%09this.doStuff()%3B%0A%09%7D%0A%7D%0A%0Aclass%20B%20extends%20A%7B%0A%09%0A%09%2F%2F%20Override%20the%20protected%20method%0A%09protected%20doStuff()%0A%09%7B%0A%09%09%2F%2F%20If%20we%20want%20we%20can%20still%20explicitely%20call%20the%20initial%20method%0A%09%09super.doStuff()%3B%0A%09%09alert(%22Called%20from%20B%22)%3B%0A%09%7D%0A%7D%0A%0Avar%20a%20%3D%20new%20A()%3B%0Aa.callDoStuff()%3B%20%2F%2F%20Will%20only%20alert%20%22Called%20form%20A%22%0A%0Avar%20b%20%3D%20new%20B()%0Ab.callDoStuff()%3B%20%2F%2F%20Will%20alert%20%22Called%20form%20A%22%20then%20%22Called%20from%20B%22" rel="nofollow">this with a very basic example</a>, and I don't know what's going on.</p>
| <p>Based on the <a href="https://github.com/nippur72/RiotTS/blob/master/riot-ts.js" rel="nofollow">source</a>, riot observables do not take advantage of prototypical inheritance. They work as mixins instead. The typescript wrapper class just calls the original riot mixin. To overwrite a function, you have to assign it to the instance:</p>
<pre><code>class Store extends Riot.Observable {
constructor() {
this.trigger = function() {
console.log("My trigger");
};
}
}
let store = new Store();
store.trigger();
</code></pre>
|
Global connection to 3rd party api Flask <p>I have a Flask app running on Heroku that connects to the Google Maps API during a request. Something like this:</p>
<pre><code>client = geocoders.GoogleV3(
client_id=self.config['GM_CLIENT_ID'],
secret_key=self.config['GM_SECRET_KEY']
)
client.do_geocoding(...)
</code></pre>
<p>Right now I am creating a new client for every request. How can I have one connection that persists across multiple requests?</p>
| <p>Turns out it's as simple as storing the client instance in a global variable.</p>
|
Delphi Application Main Form temporarly flicking to the front <p>We have a Delphi 2007 application and have recently enabled MainFormOnTaskBar for better support of Windows Aero. However because the main form would not come to the top of all child forms when clicked we added the following code.</p>
<pre><code>procedure TBaseForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
Params.WndParent := 0;
end;
</code></pre>
<p>One side effect of this is that when pressing an Alt+key hotkey on a child form that does not handle that particular hot key the main form flicks to the front and then back again. If the hot key is handled then this behavior does not occur, probably because the hotkey is swallowed.</p>
<p>Has anyone else experienced this behavior and can advise a workaround.</p>
<p>Thanks</p>
| <p>The observed behavior is the result of VCL's accelerator support for a possible main menu on the main form, so that you can select menu items from the main form's menu even when another form is active. </p>
<p>The activation of the main form takes place by a <code>SetFocus</code> call on the main form's handle while the "Application" is handling the <code>CM_APPSYSCOMMAND</code> message which is sent from the <code>WM_SYSCOMMAND</code> handler of a "WinControl" (secondary form) when command type is <code>SC_KEYMENU</code> (window menu activation - Alt key).</p>
<p>Note that this behavior is not a side effect of using <code>MainFormOnTaskBar</code> and then overriding <code>CreateParams</code> to have forms that can be brought to front. The same behavior occurs regardless of the setting of <code>MainFormOnTaskBar</code>. The only difference is that the activated main form cannot come in front of secondary forms when it is set, but the main form is activated all the same.</p>
<p>You can intercept to modify the behavior in a number of places, like a <code>WM_SYSKEYDOWN</code> handler on the secondary form, or in <code>OnKeyDown</code> of the secondary form. Semantically more correct override, IMO, should be done on the <code>IsShortCut</code> of the secondary form. As you have found out, when the secondary form handles a key combination, the processing of the system key terminates. You can, then, tell the VCL that your form requires the key:</p>
<pre><code>type
TSecondaryForm = class(TForm)
..
public
function IsShortCut(var Message: TWMKey): Boolean; override;
...
function TSecondaryForm.IsShortCut(var Message: TWMKey): Boolean;
begin
Result := True;
end;
</code></pre>
<p>Of course you can fine tune to conditionally return true depending on the parameter.</p>
|
PDO Loop in the Loop - How to make it proper way? <p>I'm shifting to PDO from MySql_ AND/OR MySqli_ and I need some advice on how to get the things right. (Learning Process). In this case I have to loop thru categories (links_cat) and return all the records responding to this category from another table.(links). Code i have is working, but sure can be improved. And I would like to do it as professional as I can (without making in to crazy too.. (: Just clean, solid and fast code. Thank you for your advice in advance.</p>
<pre><code><?php
// Get Link Categories
$links_cat = $pdo->prepare("SELECT * FROM links_cat");
$links_categories = array();
if ($links_cat->execute()) {
while ($row = $links_cat->fetch(PDO::FETCH_ASSOC)):
$links_categories[] = $row;
$link_cat_id = $row['id'];
$link_cat_name = $row['name'];
echo $link_cat_name . "<br/>";
// Get Links in current Category
$links = $pdo->prepare("SELECT * FROM links WHERE category = '$link_cat_id' ORDER BY name");
$links->execute();
while ($link_row = $links->fetch()):
echo $link_name = $link_row['name']. "<br/>";
endwhile;
endwhile;
}
$pdo = null;
?>
</code></pre>
<p><strong>UPDATE</strong></p>
<p>I joined tables and return all results but i would like to list category only once, not every record.</p>
<pre><code><?php
$links_cat = "SELECT links_cat.name AS linkcat, links.link AS linkname FROM links_cat INNER JOIN links ON links.category=links_cat.id";
foreach($pdo->query($links_cat) as $row) {
echo $row['linkcat'] . "<br>";
echo $row['linkname'] . "<br>";
}
?>
</code></pre>
<p>Listing right now is like this:</p>
<pre><code>Cat 1
- L1
Cat 1
- L2
Cat 2
- L3
Cat 2
- L4
</code></pre>
<p>I'm looking for listing like this:</p>
<pre><code>Cat 1
- L1
- L2
Cat 2
- L3
- L4
</code></pre>
| <p>Try changing your code like this</p>
<pre><code>// ensure record is ordered by category name
$links_cat = "SELECT links_cat.name AS linkcat, links.link AS linkname FROM links_cat INNER JOIN links ON links.category=links_cat.id ORDER BY links_cat.name";
$prevCat = '';
foreach($pdo->query($links_cat) as $row) {
// if category name different from previous, show it
if($row['linkcat'] != $prevCat) {
echo $row['linkcat'] . "<br>";
$prevCat = $row['linkcat'];
}
echo $row['linkname'] . "<br>";
}
</code></pre>
<p>SELECT N+1 issue is code issue where SELECT query is executed in a loop. If loop count is high, then it will degrade performance. It's called SELECT N+1 because query is executed N times in loop plus 1 for initial query.</p>
|
Redirect HTTP to HTTPS in Azure (With Load Balancer) <p>We have 2 Web servers in Azure that are Load balanced.
We just installed SSL in our these azure websites to convert it to HTTPS. </p>
<p>Now we want that any request coming in as HTTP should be changed/redirected to HTTPS connection. </p>
<p>So, I for testing I created a published website on my local machine, then added self signed
SSL certificate to get a secure site. Then I used URL rewrite to direct my HTTP site to HTTPS.
I used this in Web.config.</p>
<p>This works perfectly on my local published site. </p>
<p>But this fails on the Azure server and gives me an Internal Server Error.</p>
<p>Any ideas?</p>
<p><strong>I used the following in Web.config for the URL rewrite</strong></p>
<pre><code><rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="Off" />
<add input="{REQUEST_METHOD}" pattern="^get$|^head$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="SeeOther" />
</rule>
</rules>
</rewrite>
</code></pre>
| <p>Try this, taken from <a href="http://stackoverflow.com/questions/9823010/how-to-force-https-using-a-web-config-file">How to force HTTPS using a web.config file</a></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<clear />
<rule name="Redirect to https" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
</code></pre>
<p>Alternatively, if your app is an MVC one you can achieve this using a filter - the below will look for a setting in your application's settings (or web.config) and ensure RequireHttps is on if it's set to true - you can do the same by annotating your controllers with [RequireHttps] attribute declarations. </p>
<pre><code> string requireHttps = ConfigurationManager.AppSettings["RequireHttps"];
if (string.IsNullOrEmpty(requireHttps) || string.Compare(requireHttps, "false", true)!=0)
filters.Add(new RequireHttpsAttribute());
</code></pre>
|
C++11: Segfault with std::thread and lambda function <p>I've written a small application to demonstrate the issue, it is not pretty, but it does the job.</p>
<pre><code>#include <functional>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
class A {
public:
A() : thread_(), tasks_(), mutex_(), a_(99999) {}
void Start() {
thread_ = std::thread([this] () { Run(); });
}
private:
using Task = std::function<void()>;
public:
void AddTask(const Task& task) {
std::lock_guard<std::mutex> lock(mutex_);
tasks_.push(task);
}
bool Empty() {
std::lock_guard<std::mutex> lock(mutex_);
const bool empty = tasks_.empty();
return empty;
}
Task GetTask() {
std::lock_guard<std::mutex> lock(mutex_);
const auto& task = tasks_.front();
tasks_.pop();
return task;
}
int GetInt() { return a_; }
void Join() { thread_.join(); }
private:
void Run() {
while (Empty());
(GetTask())();
}
std::thread thread_;
std::queue<Task> tasks_;
std::mutex mutex_;
int a_;
};
template <class Base>
class B : public Base {
public:
using Base::Base;
void Start() {
Base::Start();
std::cout << "A: " << this << std::endl;
Base::AddTask([this] () { std::cout << "T: " << this << std::endl; Do(); });
}
void Do() {
std::cout << "Do: " << this << std::endl;
std::cout << "GetInt: " << Base::GetInt() << std::endl;
}
};
int main() {
B<A> app;
app.Start();
app.Join();
}
</code></pre>
<p>clang++ -std=c++11 -lpthread test_a.cpp</p>
<pre><code>A: 0x7ffeb521f4e8
T: 0x21ee540
Do: 0x21ee540
GetInt: 0
</code></pre>
<p>Notice the change in 'this' and the value of 0 for 'GetInt'.</p>
<p>I'm really lost here... Any help would be greatly appreciated,</p>
<p>Thanks.</p>
| <p>I reduced your reproduction to:</p>
<pre><code>#include <functional>
#include <iostream>
#include <queue>
struct foo {
using Task = std::function<void()>;
void Test() {
std::cout << "In Test, this: " << this << std::endl;
AddTask([this] { std::cout << "In task, this: " << this << std::endl; });
}
void AddTask(const Task& task) {
tasks_.push(task);
}
Task GetTask() {
const auto& task = tasks_.front();
tasks_.pop();
return task;
}
std::queue<Task> tasks_;
};
int main() {
foo f;
f.Test();
auto func = f.GetTask();
func();
}
</code></pre>
<p>Do you see the problem now? The issue lies with:</p>
<pre><code>const auto& task = tasks_.front();
tasks_.pop();
</code></pre>
<p>Here you grab a reference to an object, then you tell the queue to go ahead and delete that object. Your reference is now dangling, and chaos ensues.</p>
<p>You should move it out instead:</p>
<pre><code>Task GetTask() {
auto task = std::move(tasks_.front());
tasks_.pop();
return task;
}
</code></pre>
|
Do Javascript promises block the stack <p>When using Javascript promises, does the event loop get blocked? </p>
<p>My understanding is that using a await & async, makes the stack stop until the operation has completed. Does it do this by blocking the stack or does it act similar to a callback and pass of the process to an API of sorts?</p>
| <p>An <code>await</code> blocks only the current <code>async function</code>, the event loop continues to run normally. When the promise settles, the execution of the function body is resumed where it stopped.</p>
<p>Every <code>async</code>/<code>await</code> can be transformed in an equivalent <code>.then(â¦)</code>-callback program, and works just like that from the concurrency perspective. So while a promise is being <code>await</code>ed, other events may fire and arbitrary other code may run.</p>
|
What methods or actions we should avoid when build a wordpress site? <p>There are many tutorials talk about how to build wordpress site from a theme or scrath.</p>
<p>But I want to know what's the worst way to build a wordpress site?
I heard people saying: Using hooks instead of override. I am not sure if this is true. If this is true, then we should aoid override filesï¼</p>
| <p>The best way to build custom themes is to get a book and learn the right way to use template hierarchies and custom post types. Make use of the loop using <a href="https://codex.wordpress.org/Class_Reference/WP_Query" rel="nofollow">wp_query</a>. Use WordPress template tags , methods and functions if they exist rather than writing your own. </p>
<p>The worst way to build a theme is to reinvent the wheel, writing your own code for things that already exists. Not only will it take a lot longer, but it will more more likely to break during updates and harder for other people to understand.</p>
|
Testing ZK applications with Selenium Webdriver <p>I've recently started working on Selenium Webdriver (Chrome) for Java language. My application is developed using zk framework, hence its ID's are randomly generated. Eg:</p>
<pre><code>/div[@id='z_j0_7!cave']/form[@id='loginForm']/table[@id='z_j0_9']/tbody/tr[@id='z_j0_a!chdextr']/td/table[@id='z_j0_a']/tbody/tr[@id='z_j0_a!cave']/td[@id='z_j0_c!chdextr']/input[@id='z_j0_c']
</code></pre>
<p>How can I find xpath of such elements?</p>
<p>The zul file is like this:</p>
<pre><code><h:form id="loginForm" action="j_spring_security_check" method="POST">
<vbox sclass="login_grid z-grid" spacing="2px">
<hbox widths="7em, 8em">
<label value="${c:l('login')}:"/>
<textbox id="login" name="j_username" value="${LoginForm.login}" use="de.hybris.platform.cscockpit.components.login.LoginTextBox"/>
</hbox>
<hbox widths="7em, 8em">
<label value="${c:l('password')}:"/>
<textbox type="password" id="pw" name="j_password" value="${LoginForm.password}" use="de.hybris.platform.cscockpit.components.login.PasswordTextBox"/>
</hbox>
</vbox>
</h:form>
</code></pre>
<p>View as in developer mode: (For label user id and its input field)</p>
<pre><code><table id="z_38_a" z.type="zul.box.Box" class="z-hbox" z.zcls="z-hbox" cellpadding="0" cellspacing="0">
<tbody>
<tr id="z_38_a!cave" valign="top">
<td id="z_38_b!chdextr" z.coexist="true" align="left" style="width:7em"> <span id="z_38_b" class="z-label" z.zcls="z-label">ã¦ã¼ã¶ã¼ ID:</span>
</td>
<td id="z_38_b!chdextr2" class="z-hbox-sep">
</td>
<td id="z_38_c!chdextr" z.coexist="true" align="left" style="width:8em"> <input id="z_38_c" z.type="zul.vd.Txbox" class="z-textbox" z.zcls="z-textbox" type="text" name="j_username" value="admin">
</td>
</tr>
</tbody>
</table>
</code></pre>
| <blockquote>
<p>I'm looking for the xpath of login and password input fields.
Programming language is java and I using Chromedriver. </p>
</blockquote>
<p>There is no need to do extra stuff and use <code>xpath</code> to locate desire element, you can use <a href="https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/By.html#name-java.lang.String-" rel="nofollow"><code>By.name()</code></a> locator to locate easily desire element as well as below :-</p>
<pre><code>WebElement user = driver.findElement(By.name("j_username"));
WebElement password = driver.findElement(By.name("j_password"));
</code></pre>
|
ReflectionTestUtils not working with @Autowired in Spring Test <p>I am trying to add mock object in CourseServiceImpl's courseDao field but it is not working.</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = {"file:src/main/webapp/WEB-INF/config/servlet-config.xml"}
)
@ActiveProfiles("test")
public final class CourseServiceTest {
@Mock
private CourseDao courseDao;
@Autowired
private CourseService courseService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCourseServiceNotNull() {
assertNotNull(courseService);
assertNotNull(courseDao);
ReflectionTestUtils.setField(courseService, "courseDao", courseDao, CourseDao.class);
}
</code></pre>
<p>The reflection statement throws an error that field "courseDao" didn't found. But, when I create an object using new operator then it works fine.</p>
<pre><code>ReflectionTestUtils.setField(new CourseServiceImpl(), "courseDao", courseDao, CourseDao.class);
</code></pre>
<p><strong>servlet-config.xml</strong></p>
<p></p>
<pre><code><mvc:annotation-driven />
<mvc:resources location="pdfs" mapping="/pdfs/**" />
<security:global-method-security
pre-post-annotations="enabled" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/view/" p:suffix=".jsp" p:order="2" />
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"
p:contentNegotiationManager-ref="contentNegId" p:defaultViews-ref="defaultViewList"
p:order="1" />
<bean id="contentNegId"
class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
<bean
class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
<util:list id="defaultViewList">
<bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller"
p:autodetectAnnotations="true" />
</constructor-arg>
</bean>
</util:list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"
p:order="0" />
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"
p:defaultLocale="en" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages" />
<context:property-placeholder location="classpath:messages.properties" />
<import resource="/hibernate-config.xml" />
<import resource="/hibernate-config-test.xml" />
</code></pre>
<p><strong>hibernate-config-test.xml</strong></p>
<pre><code><bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/school-repo-test" p:username="user"
p:password="password" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="myDataSource" p:hibernateProperties-ref="hibernateProps"
p:annotatedClasses-ref="mapClasses">
</bean>
<util:list id="mapClasses">
<value>org.school.model.Course</value>
<value>org.school.model.Role</value>
<value>org.school.model.Staff</value>
<value>org.school.model.Student</value>
<value>org.school.model.Subject</value>
</util:list>
<util:properties id="hibernateProps">
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</util:properties>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
</code></pre>
<p>Apart from profile name, rest is same for hibernate-config file.</p>
<p><strong>CourseServiceImpl</strong></p>
<pre><code>@Service(value = "courseService")
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public class CourseServiceImpl implements CourseService {
@Autowired
private MessageSource messageSource;
@Autowired
private CourseDao courseDao;
@Autowired
private ApplicationContext context;
</code></pre>
<p>Please advise.</p>
| <p>Your <code>CourseServiceImpl</code> class has <code>@Transactional</code> annotation which means that bean instance wrapped with <code>"Transational"</code> proxy before it injected as dependency in <code>CourseServiceTest</code> and all other beans in Spring context. Such proxy instance hides all the <code>private</code> fields of original <code>CourseServiceImpl</code> instance.</p>
<p>So you cannot access fields you want because injected <code>courseService</code> instance is not the original <code>CourseServiceImpl</code> class any more, it is dynamic <code>cglib</code> or <code>JDK</code> proxy class.</p>
|
Django: Template Does Not Exist Error <p>In My django app I have a view called 'StatsView' given below:</p>
<pre><code>class StatsView(LoginRequiredMixin, View):
login_url = '/signin/'
def get(self, request, template='app_folder/ad_accounts/pixel_stats.html', *args, **kwargs):
#Code
return render(request, template, context)
</code></pre>
<p><code>app/urls.py</code></p>
<pre><code>url(
r'^ad_accounts/(?P<ad_account_id>[^/]+)/pixel_stats',
StatsView.as_view(),
name="pixel_stats"
),
</code></pre>
<p><strong>template</strong>
<code>pixel_stats.html</code></p>
<pre><code><p> test</p>
</code></pre>
<p>However when I go to <code>localhost:8000/ad_accounts/acctid/pixel_stats/</code> I keep running into a <code>Template DoesNotExist Error</code>. I cant seem to figure out where Im going wrong. Ive added a bunch of URLs and havent run into this issue for any one them.</p>
<p>My app structure is as follows:</p>
<pre><code>project/
app/
templates/
app_folder/
ad_accounts/
pixel_stats.html
views/
ad_accounts/
stats.py
</code></pre>
| <p>Silly mistake. Solved it by adding a <code>$</code> at the end in my <code>url</code>.</p>
<pre><code>url(
r'^ad_accounts/(?P<ad_account_id>[^/]+)/pixel_stats/$',
StatsView.as_view(),
name="pixel_stats"
),
</code></pre>
|
C# Inserting last 5 lines from a .csv file into datagrid <p>I am trying to pull that last 5 lines from a .csv file and display them in a datagrid on my form. How would I insert the data onto the datagrid? </p>
<p>Here is my current Code, </p>
<pre><code> int x = 5;
var buffor = new Queue<string>(x);
var log = new StreamReader(@"MyPath");
while (!log.EndOfStream)
{
string line = log.ReadLine();
if (buffor.Count >= x)
buffor.Dequeue();
buffor.Enqueue(line);
}
string[] lastLines = buffor.ToArray();
</code></pre>
<p>Thanks in advance.</p>
| <p>You can do this,</p>
<pre><code> public Form1()
{
InitializeComponent();
int x = 5;
var buffor = new Queue<string>(x);
foreach (var headerLine in File.ReadLines("C:/NewMap.csv").Take(1))
{
foreach (var headerItem in headerLine.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
dataGridView1.Columns.Add(headerItem.ToString().Trim(), headerItem.ToString());
}
}
var log = new StreamReader("C:/NewMap.csv");
while (!log.EndOfStream)
{
string line = log.ReadLine();
if (buffor.Count >= x)
buffor.Dequeue();
buffor.Enqueue(line);
}
foreach (var line in buffor)
{
if (line != string.Empty || line != string.Empty)
{
dataGridView1.Rows.Add(line);
}
}
}
</code></pre>
|
Redisplay div after display none <p>I'm hoping to do something simple and googling hasn't yielded results I could understand (I'm still something of a rookie.) I'm hoping to set display to none for a div, but then later make that div come back. I'm failing to do so. See the snippet attached, I've tried "Initial" and "Reset" but to no avail. Any suggestions?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function hideBtnClick(){
innerBlock.style.display = "none";
}
function showBtnClick(){
innerBlock.style.display = "reset";
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#outerBlock{
width: 100%;
height: 100px;
background-color: #FFCC33;
}
#innerBlock{
width: 50%;
height: 50px;
background-color: #FF0000;
margin: 0 auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="outerBlock">
<div id="innerBlock"></div>
</div>
<button type="button" onclick="hideBtnClick()">Hide</button>
<button type="button" onclick="showBtnClick()">Show</button></code></pre>
</div>
</div>
</p>
| <p>Use this for a div:</p>
<pre><code>innerBlock.style.display = "block";
</code></pre>
<p>Or this for a span:</p>
<pre><code>innerBlock.style.display = "inline";
</code></pre>
<p>For more information on CSS display options, visit:</p>
<p><a href="http://www.w3schools.com/cssref/pr_class_display.asp" rel="nofollow">http://www.w3schools.com/cssref/pr_class_display.asp</a></p>
<p>Using standard JavaScript (ES Script), you'll need to use:</p>
<pre><code>document.getElementById("innerBlock").style.display = "block";
</code></pre>
|
Home folder in Webapplication <p>Can somebody explain me what does this link mean? </p>
<pre><code><?php header("Location:user/#/home")?>
</code></pre>
<p>This line is inside index.php file, that exists at the same level as user folder and user folder has another folder called home inside. My query is what does this # sign mean and what is the purpose?</p>
<p>Thanks</p>
| <p>In PHP, the <a href="http://php.net/manual/en/function.header.php" rel="nofollow">header</a> method is how you send HTTP headers back to the user's browser. The Location header instructs the browser that the requested item has moved to a new location and thus the browser should redirect the user to the new location. In short, this is an HTTP redirect.</p>
<p>From the PHP side, your server will first see a request to the file above, and then a second request for the path "user/". Depending on how your web server is configured, this could go to the same PHP file, or to a different PHP file for processing.</p>
<p>Specifically the hash sign ("#"). This is a <a href="https://en.wikipedia.org/wiki/Fragment_identifier" rel="nofollow">fragment identifier</a> within a URL and is traditionally used to scroll a user to a specific portion of a page. So taking the example "user/#/home", this user would be redirected to page "user/", and then the browser would try to scroll to the anchor "/home" on the resulting page.</p>
|
How to handle urllib2 socket timeouts? <p>So the following has worked for other links that have timed out and has continued to the next link in the loop. However for this link I got an error. I am not sure why that is and how to fix it so that when it happens it just browses to the next image.</p>
<pre><code>try:
image_file = urllib2.urlopen(submission.url, timeout = 5)
with open('/home/mona/computer_vision/image_retrieval/images/'
+ category + '/'
+ datetime.datetime.now().strftime('%y-%m-%d-%s')
+ submission.url[-5:], 'wb') as output_image:
output_image.write(image_file.read())
except urllib2.URLError as e:
print(e)
continue
</code></pre>
<p>The error is:</p>
<pre class="lang-none prettyprint-override"><code>[LOG] Done Getting http://i.imgur.com/b6fhEkWh.jpg
submission id is: 1skepf
[LOG] Getting url: http://www.redbubble.com/people/crtjer/works/11181520-bling-giraffe
[LOG] Getting url: http://www.youtube.com/watch?v=Y7iuOZVJhs0
[LOG] Getting url: http://imgur.com/8a62PST
[LOG] Getting url: http://www.youtube.com/watch?v=DFZFiFCsTc8
[LOG] Getting url: http://i.imgur.com/QPpOFVv.jpg
[LOG] Done Getting http://i.imgur.com/QPpOFVv.jpg
submission id is: 1f3amu
[LOG] Getting url: http://25.media.tumblr.com/tumblr_lstla7vqK71ql5q9zo1_500.jpg
Traceback (most recent call last):
File "download.py", line 50, in <module>
image_file = urllib2.urlopen(submission.url, timeout = 5)
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1214, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1187, in do_open
r = h.getresponse(buffering=True)
File "/usr/lib/python2.7/httplib.py", line 1051, in getresponse
response.begin()
File "/usr/lib/python2.7/httplib.py", line 415, in begin
version, status, reason = self._read_status()
File "/usr/lib/python2.7/httplib.py", line 371, in _read_status
line = self.fp.readline(_MAXLINE + 1)
File "/usr/lib/python2.7/socket.py", line 476, in readline
data = self._sock.recv(self._rbufsize)
socket.timeout: timed out
</code></pre>
| <p>Explicitly catch the timeout exception: <a href="https://docs.python.org/3/library/socket.html#socket.timeout" rel="nofollow">https://docs.python.org/3/library/socket.html#socket.timeout</a></p>
<pre><code>try:
image_file = urllib2.urlopen(submission.url, timeout = 5)
except urllib2.URLError as e:
print(e)
continue
except socket.Timeouterror:
print("timed out")
# Your timeout handling code here...
else:
with open('/home/mona/computer_vision/image_retrieval/images/'+category+'/' + datetime.datetime.now().strftime('%y-%m-%d-%s') + submission.url[-5:], 'wb') as output_image:
output_image.write(image_file.read())
</code></pre>
<p>OP:
Thanks!
I had these thanks to your suggestion and my problem was solved for Python2.7:</p>
<pre><code>except socket.timeout as e:
print(e)
continue
except socket.error as e:
print(e)
continue
</code></pre>
|
Redirect a URL with RewriteRule in .htaccess <p>I want to redirect a URL like</p>
<pre><code>https://www.domain.com/#new
</code></pre>
<p>to</p>
<pre><code>https://www.domain.com/new.html
</code></pre>
<p>How can I use <code>.htaccess</code>?</p>
| <p>Unfortunately the <code>hash</code> part of the URL is not being sent by the browser to the server, so in the server you can't really use this part to do the redirect.</p>
<p>You will have to use <code>javascript</code> code for that:</p>
<pre><code>hash = window.location.hash
if (hash.length > 0) {
window.location = '/' + hash.substr(1) + '.html'
}
</code></pre>
|
Clustered index, order on single single, without order by clause <p>I have a transaction table (single primary key) with millions of records and everyday 100s of records are getting added.</p>
<p>This table is then further used in Reconciliation and Settlement which happens on newly inserted records only, without any order.</p>
<p>Although, I have created a clustered index on the ID column but not sure whether it should be ASC or DESC. As most of the processing happens on newly inserted records so I was thinking to order the index as DESC but not sure.</p>
<p>I have already checked on several blogs and questions on StackOverflow about this but all of them are discussing composite clustered index with order by clause. In my case there is single column clustered index and no requirement for order by.</p>
| <p>It depends... For some operations, like ORDER BY, it does not matter as index is bidirectional, so sorting is not needed.</p>
<p>But for other operations, like Ranking, Index Scan, etc., it matters. SQL Engine is designed to perform forward index scan with parallelism, but if query optimizer needs a reverse index scan, such operation is single-threaded. So it may affect the performance if you choose incorrect sort order.</p>
<p>It really depends on the data and queries in your database, so I'm suggesting to capture most frequent user queries (against that table) and check their execution plans and IO stats for two different sort orders.</p>
<p>Also it can cause index fragmentation if data are added not in the same order as index sort order.</p>
|
validating a phone number <p>How can I determine if an input is a valid home phone number (without area code)?</p>
| <p>Regex is the best option for validating a phone number.</p>
<p>you can use it on the html input tag like this (this may not be supported in all browsers):</p>
<pre><code><input id="phonenum" type="tel" pattern="^\d{3}-\d{4}$" required >
</code></pre>
<p>or you can test a regex string in you code like this (also, this is the correct format for you function above):</p>
<pre><code><script type="text/javascript">
//function\\
function validPhone(phoneNum) {
var reg = new RegExp("^\d{3}-\d{4}$");
if (reg.test(phoneNum)) {
return "True";
}
else {
return "False";
}
}
</script>
</code></pre>
<p>and if you want to make it short and sweet and you just need to return a bool value, you can do do this:</p>
<pre><code><script type="text/javascript">
//function\\
function validPhone(phoneNum) {
var reg = new RegExp("^\d{3}-\d{4}$");
return reg.test(phoneNum);
}
</script>
</code></pre>
|
java call method in constructor and abstract class? <pre><code>public class NewSeqTest {
public static void main(String[] args) {
new S();
new Derived(100);
}
}
class P {
String s = "parent";
public P() {
test();
}
public void test() { //test 1
System.out.println(s + " parent");
}
}
class S extends P {
String s = "son";
public S() {
test();
}
@Override
public void test() { //test 2
System.out.println(s + " son");
}
}
abstract class Base {
public Base() {
print();
}
abstract public void print();
}
class Derived extends Base {
private int x = 3;
public Derived(int x) {
this.x = x;
}
@Override
public void print() {
System.out.println(x);
}
}
</code></pre>
<p>//output is</p>
<pre><code> null son
son son
0
</code></pre>
<p>my question is<br>
1. why P constructor print " null son"; I think is "null parent" ?</p>
<p>2 why can abstract class Base execute abstract method print() in constructor?</p>
<p>sorry for the code format, I do not know how to use it correctly.</p>
| <ol>
<li><p>You've overriden the method <code>test</code> in your subclass <code>S</code> and you're constructing an object of type <code>S</code>. So in the superclass constructor, when <code>test()</code> is invoked, it invokes the overriden version of <code>test()</code> from the subclass <code>S</code>. That's the point of overriding.</p></li>
<li><p>Same as 1. The method <code>print</code> is <em>not</em> abstract in class <code>Derived</code>, and you're constructing in instance of <code>Derived</code>, not of <code>Base</code>. (It is illegal to say <code>new Base()</code> for the reason that you mentioned: you can't invoke an abstract method)</p></li>
</ol>
|
Remove an XML parent node keeping child nodes <p>If I have (for example) an XML file with the following structure:</p>
<pre class="lang-xml prettyprint-override"><code><Parent1>
<listChild>
<child>
<listchild2>
<child2>
<child2>
<child2>
</listchild2>
</child>
<child>
<listchild2>
<child2>
<child2>
<child2>
</listchild2>
</child>
</listchild>
</parent1>
</code></pre>
<p>I want to remove <code>listChild</code> and <code>listChild2</code>, with the expected output:</p>
<pre class="lang-xml prettyprint-override"><code> <Parent>
<child>
<child>
<child>
<child>
</child>
<child>
<child>
<child>
<child>
</child>
</parent>
</code></pre>
<p>I tried <code>System.Xml.Linq</code>, like this:</p>
<pre><code>public void removeParentNode(String filename)
{
XDocument xdoc = XDocument.Load(filename);
//remove parent1
var child= xdoc.Descendants("child");
XElement dcuManager = new XElement("parent1 ");
parent1 .Add(child);
XDocument xdoc1 = new XDocument(dcuManager);
}
</code></pre>
<p>But the code removes only the outer list.</p>
<p>Is there a way to remove the <code><listchild></code> and <code></listchild></code> tags only, keeping all its child nodes?</p>
<p>------------------------update-------------------------------------</p>
<p>above xml code is very simple example
my xml code is :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<DcuManager xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<listDcu>
<Dcu id="dcu1 id" mode="dcu1 mode" port="dcu1 port">
<modemMgr>
<listModem>
<Modem id="Modem1 id" port="modem 1 port" communicationStatus="modem 1 mode">
<meterManager>
<listMeter>
<Meter id="Meter 1 id" port="Meter 1 port" mac="Meter 1 mode" />
</listMeter>
</meterManager>
</Modem>
<Modem id="Modem2 id" port="modem 2 port" communicationStatus="modem 2 mode">
<meterManager>
<listMeter>
<Meter id="Meter 2 id" port="Meter 2 port" mac="Meter 2 mode" />
</listMeter>
</meterManager>
</Modem>
</listModem>
</modemMgr>
</Dcu>
<Dcu id="dcu2 id" mode="dcu2 mode" port="dcu2 port">
<modemMgr>
<listModem>
<Modem id="Modem3 id" port="modem 3 port" communicationStatus="modem 3 mode">
<meterManager>
<listMeter>
<Meter id="Meter 3 id" port="Meter 3 port" mac="Meter 3 mode" />
</listMeter>
</meterManager>
</Modem>
<Modem id="Modem4 id" port="modem 4 port" communicationStatus="modem 4 mode">
<meterManager>
<listMeter>
<Meter id="Meter 4 id" port="Meter 4 port" mac="Meter 4 mode" />
</listMeter>
</meterManager>
</Modem>
</listModem>
</modemMgr>
</Dcu>
<Dcu id="dcu3 id" mode="dcu3 mode" port="dcu3 port">
<modemMgr>
<listModem>
<Modem id="Modem5 id" port="modem 5 port" communicationStatus="modem 5 mode">
<meterManager>
<listMeter>
<Meter id="Meter 5 id" port="Meter 5 port" mac="Meter 5 mode" />
</listMeter>
</meterManager>
</Modem>
<Modem id="Modem6 id" port="modem 6 port" communicationStatus="modem 6 mode">
<meterManager>
<listMeter>
<Meter id="Meter 6 id" port="Meter 6 port" mac="Meter 6 mode" />
</listMeter>
</meterManager>
</Modem>
</listModem>
</modemMgr>
</Dcu>
</listDcu>
</DcuManager>
</code></pre>
<p>this code is convert c# class to xml.
i want remove dcuMgr, modemMgr, meterMgr keeping child nodes.
how do i?</p>
| <p>Your specification is not very clear. XML itself does not have the concept of a "list". Any element can contain any number of child elements, and XML doesn't care what the name of the elements are. Using the word "list" in an element doesn't actually make it a list.</p>
<p>In addition, in your example XML you show two different kinds of "child" nodes, the outer being named <code>child</code> and the inner being named <code>child2</code>. But in your desired output, you only have the name <code>child</code>. The <code>child2</code> nodes appear to have been replaced by <code>child</code> nodes.</p>
<p>Unfortunately, the XML you show isn't even valid XML. So it's pretty obvious you have not provided us with <em>real</em> XML examples, making it even more difficult to understand what you're trying to do.</p>
<p>So, with all that in mind, I'll point out that the basic approach you want, given that you want to apply the same algorithm to a series of nested objects, is one based on recursion. I.e. you want to recursively select the nodes you'll be keeping, and apply the same removal logic to them.</p>
<p>Here is a <a href="http://stackoverflow.com/help/mcve">Complete, Minimal, and Verifiable code example</a> (i.e. similar to what should have been included in the question in the first place) that illustrates this basic idea:</p>
<pre><code>class Program
{
const string _kxmlInput =
@"<parent1>
<listchild>
<child>
<listchild2>
<child/>
<child/>
<child/>
</listchild2>
</child>
<child>
<listchild2>
<child/>
<child/>
<child/>
</listchild2>
</child>
</listchild>
</parent1>";
static void Main(string[] args)
{
Console.WriteLine(removeParentNode(_kxmlInput));
}
static string removeParentNode(string xml)
{
StringReader reader = new StringReader(xml);
XDocument xdoc = XDocument.Load(reader);
//remove parent1
XDocument xdoc1 = new XDocument(KeepDescendants(xdoc.Root, "child"));
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings { Indent = true };
using (XmlWriter xmlWriter = XmlWriter.Create(sb, settings))
xdoc1.WriteTo(xmlWriter);
return sb.ToString();
}
private static XElement KeepDescendants(XElement node, string descendantName)
{
var child = node.Descendants(descendantName).Select(c => KeepDescendants(c, descendantName));
if (!child.Any())
{
return node;
}
XElement newParent = new XElement(node.Name);
newParent.Add(child);
return newParent;
}
}
</code></pre>
<p>If you have some other kind of behavior in mind, you should be able to adapt the basic technique shown above to accomplish whatever it is you actually want to do.</p>
|
Firebase returning Optional() with Swift 3.0 <p>This code is now displaying data in the app as Optional('data') since updating to Swift 3.0. Any idea? </p>
<pre><code>let ring1FightRef = FIRDatabase.database().reference().child("Ring1Fighting")
@IBOutlet weak var ring1Fighting: UILabel!
</code></pre>
<p>Here is the code in viewDidLoad</p>
<pre><code>ring1FightRef.observe(.value) { (snap: FIRDataSnapshot) in self.ring1Fighting.text = (snap.value as AnyObject).description
}
</code></pre>
| <p>You just need to unwrap the value that you recieve:- </p>
<pre><code>FIRDatabase.database().reference().child("Ring1Fighting").observe(.value) { (snap: FIRDataSnapshot) in
print((snap.value as! String))
}
</code></pre>
|
How to push object to key array javascript? <p>I have an object like this:</p>
<pre><code>var newService = new Service({
name: service.name,
description: service.description,
supplier: service.supplier,
price: service.price,
info_requires: []
});
</code></pre>
<p>Here is modal <code>Service</code></p>
<pre><code>var serviceSchema = new Schema({
name: String,
description: String,
supplier: String,
price: Number,
info_requires: [{
name: String,
type: Number, // 1-text 2-combobox 3-textarea
limit: []
}],
});
</code></pre>
<p>Here is my data:</p>
<p><code>var services = [{
name: "Test",
description: "Des",
supplier: "Sup",
price: 123,
icon: "icon",
type: 1,
open: 1,
info_requires: [
{
name: "Age",
type: 1,
limit: []
},
{
name: "Bla bla",
type: 1,
limit: []
}
]
}]</code></p>
<p>I push data to <code>info_requires[]</code> like this:</p>
<pre><code>newService.info_requires.push(service.info_requires[i])
</code></pre>
<p>or </p>
<p><code>newService.info_requires[i].name = (service.info_requires[i].name)</code>
But it did not work with error: <code>Cannot set property &#39;name&#39; of undefined</code>? Did I do anything wrong?</p>
| <p>In case the "Service" is a custom Object created by you, this might do the trick</p>
<pre><code>var service ={
name: "",
description: "",
supplier: "",
price: "",
info_requires: []
};
service.info_requires.push(some_object);
new Service(service);
</code></pre>
|
How can I get the google search snippets using Python? <p>I am now trying the python module google which only return the url from the search result. And I want to have the snippets as information as well, how could I do that?(Since the google web search API is deprecated)</p>
| <p>I think you're going to have to extract your own snippets by opening and reading the url in the search result.</p>
|
How to get select value from another php file? <p>How to get <code><select></code> value from another php file.
Example :</p>
<p>index.php</p>
<pre><code>$text = $_POST['text']
<select id="text">
<option> text 1</option>
<option> text 2</option>
<option> text 3</option>
</select>
</code></pre>
<p>data.php</p>
<pre><code>$sql= "SELECT column FROM table where $text='text 1'"
</code></pre>
<p>as you can read above, how to get value from <code>$text</code> in <code>index.php</code> and use it in <code>data.php</code></p>
| <p>I think you only forgot to add value for options itself</p>
<pre><code><form method="post" action="data.php">
<select name="text" id="text">
<option value="text 1"> text 1</option>
<option value="text 1"> text 2</option>
<option value="text 1"> text 3</option>
</select>
<input type="submit" value="Submit the form"/>
</form>
</code></pre>
<p>then add <code>$_GET</code> on your data.php</p>
<pre><code>$text = $_GET['text']
$sql= "SELECT column FROM table where $text='ABCDE'"
</code></pre>
|
Android Studio NullPointerException when I click a button to start a new activity? <p>Here is my main method:</p>
<pre><code>public class VideoViewDemo extends AppCompatActivity implements View.OnClickListener {
private Button loginButton;
private Button registerButton;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private android.content.Intent t;
private android.content.Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
setContentView( R.layout.activity_video_view_demo );
loginButton = (Button) findViewById( R.id.loginButton1 );
registerButton = (Button) findViewById( R.id.registerButton1 );
loginButton.setOnClickListener( this );
registerButton.setOnClickListener( this );
</code></pre>
<p>and here is what I use for the activity intent:</p>
<pre><code>@Override
public void onClick( View view) {
switch(view.getId()){
case R.id.loginButton1:
Intent i = new Intent(this.getApplicationContext(), SignUpActivity.class);
startActivity( i );
break;
case R.id.registerButton1:
Intent t = new Intent(this.getApplicationContext(), RegisterViewController.class);
startActivity( t );
break;
default:
break;
}
}
}
</code></pre>
<p>It's an intro screen for my app. The user can either click on register or login and it takes them to the corresponding activity. I've tried using just "this" and using "VideoViewDemo.class" at the beginning, but I keep getting a nullpointerexception. </p>
<p>EDIT: Here is the stack trace:</p>
<pre><code>1 21:29:59.049 17326-17326/com.example.ecohapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ecohapp, PID: 17326
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, com.android.systemui=overlay:system, com.android.systemui.navbar=overlay:system}
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.ecohapp/com.example.ecohapp.SignUpActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2361)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:139)
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4653)
at com.example.ecohapp.SignUpActivity.<init>(SignUpActivity.java:33)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2351)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)Â
at android.app.ActivityThread.-wrap11(ActivityThread.java)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:148)Â
at android.app.ActivityThread.main(ActivityThread.java:5461)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)Â
</code></pre>
<p>and the XML file:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_video_view_demo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example.ecohapp.VideoViewDemo">
<include layout="@layout/my_video_background"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:text="Login"
android:id="@+id/loginButton1"
android:layout_weight="1"
android:layout_marginLeft="74dp"
android:layout_marginStart="74dp"
android:layout_marginBottom="34dp"
android:elevation="0dp"
style="@android:style/Widget.Material.Light.Button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:visibility="visible"/>
<Button
android:text="Register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/registerButton1"
android:layout_alignBaseline="@+id/loginButton"
android:layout_alignBottom="@+id/loginButton"
android:layout_toRightOf="@+id/loginButton"
android:layout_toEndOf="@+id/loginButton"
android:layout_marginLeft="57dp"
android:layout_marginStart="57dp"
android:visibility="visible"/>
</LinearLayout>
</RelativeLayout>
</code></pre>
<p>And the SignUpActivity(Login activity, still have to change the name, sorry ik i'm kind of a noob at this)</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_sign_up );
Toolbar toolbar = (Toolbar) findViewById( R.id.toolbar );
setSupportActionBar( toolbar );
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
startActivity( t );
}
};
buttonSignUp = (Button) findViewById( R.id.email_sign_in_button );
userEmail = (EditText) findViewById( R.id.userEmail );
userPassword = (EditText) findViewById( R.id.userPassword );
buttonSignUp.setOnClickListener( this );
progressDialog = new ProgressDialog( this );
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder( this ).addApi( AppIndex.API ).build();
}
@Override
public void onStart() {
super.onStart();// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
mAuth.addAuthStateListener( mAuthListener );
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.start( client, getIndexApiAction() );
}
</code></pre>
| <p>It's difficult to answer this without seeing the stack trace to know exactly where the null pointer exception is happening. Some things I would refactor that might help:</p>
<p>Check to make sure actionBar is not null:</p>
<pre><code>Action actionBar = getSupportActionBar();
if (actionBar != null)
actionBar.hide();
</code></pre>
<p>Declare inner objects for your click handlers instead of having your activity implement OnClickListener:</p>
<pre><code>// Remove implements View.OnClickListener from your class declaration and remove the onClick method.
// Add these two methods instead, one for each button.
private View.OnClickListener mLoginClickListener = new View.OnClickListener() {
public void onClick(View v) {
login();
}
}
private View.OnClickListener mRegisterClickListener = new View.OnClickListener() {
public void onClick(View v) {
register();
}
}
</code></pre>
<p>Use the activity (this) as your context instead of the application context. This is safer in terms of avoiding memory leaks.</p>
<pre><code>private void login() {
Intent i = new Intent(this, SignUpActivity.class);
startActivity(i);
}
private void register() {
Intent i = new Intent(this, RegisterViewController.class);
startActivity(i);
}
</code></pre>
<p>And then back in onCreate register your click handlers like this instead:</p>
<pre><code>loginButton = (Button) findViewById( R.id.loginButton1 );
loginButton.setOnClickListener(mLoginClickListener);
registerButton = (Button) findViewById( R.id.registerButton1 );
registerButton.setOnClickListener(mRegisterClickListener);
</code></pre>
|
C++ code for improving quality of input raw image using point processing algorithm in image processing? <p>I want to enhance the image using point processing algorithm that is used in multimedia image processing </p>
| <p>Perhaps the best suggestion for you is to use OpenCV to do the job.It is Open source computer vision tools. The website is:
<a href="http://opencv.org/" rel="nofollow">http://opencv.org/</a></p>
<p>In this webiste, you can find all you need.
BTW, you can see this website:</p>
<p><a href="http://docs.opencv.org/2.4/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html" rel="nofollow">http://docs.opencv.org/2.4/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html</a></p>
|
move context on canvas <p>I need to make a web app that works like this <a href="http://courses.acs.uwinnipeg.ca/2909-001/assignments/A1Q4_drag.mp4" rel="nofollow">link </a>.
I know how to produce the rectangles on random places, but my problem is how to move them by mouse? We should be able to move any of them when we click-and-hold and drag. Here is what I did so far:</p>
<pre><code> <!doctype html>
<html lang="en">
<head>
<title>Question 2</title>
<meta charset="utf-8">
<style type="text/css">
canvas{border: 1px solid black;}
</style>
<script>
window.onload=function(){
var canvas=document.getElementById("can1");
var context=canvas.getContext("2d");
color=["red","blue","lime","linen","maroon","orange","purple","pink","orchid","navy","olive","salmon","peru","yellow","tan"];
for(var i=0;i<9000;i++)
{
var w=Math.floor(Math.random()*color.length);
var x=Math.floor(Math.random()*canvas.width);
var y=Math.floor(Math.random()*canvas.height);
context.fillStyle=color[w];
context.fillRect(x,y,20,20);
}
}
</script>
</head>
<body>
<canvas id="can1" width="6000" height="2000"></canvas>
</body>
</html>
</code></pre>
<p>This is a homework and I appreciate your help. Thanks </p>
| <p>I would suggest using HTML Div Elements for this, but if you must use HTML5 Canvas here are the basic ideas:</p>
<ol>
<li>Create an array of boxes as objects and add boxes to them</li>
<li>Draw the boxes every 16.666 (60fps) milliseconds or draw them when the user moves their mouse or drags a box, etc...</li>
<li>Determine if the user is clicking on a box when they press their mouse down (this is just math) and store the selected box.</li>
<li>Set up the <code>onmousemove</code> and <code>onmouseup</code> functions properly so the currently selected box is moved when the mouse is moved and is let go on mouse up.</li>
</ol>
<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-js lang-js prettyprint-override"><code>var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height;
var boxes = [];
for (var i = 0; i < 100; i++) { // Add boxes
boxes.push({
x: Math.random() * width,
y: Math.random() * height,
s: 25,
c: "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," +
Math.floor(Math.random() * 255) + ")"
});
}
window.onmousedown = function(e) {
var mx = e.clientX - canvas.getBoundingClientRect().left,
my = e.clientY - canvas.getBoundingClientRect().top;
// Since the drawing is done from lowest to highest index, we want to go backwards for selecting the box most visible (highest index)
for (var i = boxes.length - 1; i >= 0; i--) {
if (mx >= boxes[i].x && mx <= boxes[i].x + boxes[i].s &&
my >= boxes[i].y && my <= boxes[i].y + boxes[i].s) {
// Store the offset of the mouse position to the boxes position so dragging offset looks natural and stays offsetted
boxes.soffsetx = mx - boxes[i].x;
boxes.soffsety = my - boxes[i].y;
// Store the box index as the selected box
boxes.sbox = i;
return;
}
}
boxes.sbox = -1;
};
window.onmouseup = function(e) {
boxes.sbox = -1;
};
window.onmousemove = function(e) {
if (boxes.sbox === -1 || !boxes.sbox) {
return;
}
var mx = e.clientX - canvas.getBoundingClientRect().left,
my = e.clientY - canvas.getBoundingClientRect().top;
// Apply the offset to the currently selected box
boxes[boxes.sbox].x = mx - boxes.soffsetx;
boxes[boxes.sbox].y = my - boxes.soffsety;
};
(function update() { // Just draws the boxes
ctx.clearRect(0, 0, width, height);
for (var i = 0; i < boxes.length; i++) {
ctx.fillStyle = boxes[i].c;
ctx.fillRect(boxes[i].x, boxes[i].y, boxes[i].s, boxes[i].s);
}
setTimeout(function() {
requestAnimationFrame(update);
}, 1000 / 60);
})();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas" width="250" height="250"></canvas></code></pre>
</div>
</div>
</p>
|
How do I get CSV output when querying for IAM Groups and Users? <p>First time poster here. </p>
<p>I have created a small script that outputs group membership in AWS. </p>
<p>I have got the script to the point that it outputs the desired results but I require help getting the data in a readable format into a csv file. </p>
<pre><code>$awsgroupnames = Get-IAMGroups
$accountname = Get-IAMAccountAlias
foreach ($awsgroupname in $awsgroupnames) {
$groupuser = Get-IAMGroup -groupname ($awsgroupname.GroupName)
$usernames = $groupuser.users | select UserName
write-host $accountname ($awsgroupname.groupname) ($usernames.username)
}
</code></pre>
<p>The output looks like this. </p>
<pre><code>Account Alias - Group - User
aws-dxxxd-mxxer axx-admin xxhie sxxwj bhxxwk hxxv rxxerd cxxx axxw-sf-msdsmt
aws-dxxxd-mxxer aws-casesupport
aws-dxxxd-mxxer aws-readonly gixxxi mxxxxilj kxxng bxxnst txxxgd rxm kxxxrs
aws-dxxxd-mxxer billing-admin bsdffdk crcccdi
aws-dxxxd-mxxer Billing_Access
aws-dxxxd-mxxer vdc-axxxs mxxxab rxxxd cxxxmi aws-srxxxc-mxxt
aws-dxxxd-mxxer vpc-axxxn mxxxab mxxxj mxxxnr
</code></pre>
<p>How can I get this to export out to a csv in the following format?</p>
<pre><code>Account Alias - Group1 - User1
Account Alias - Group1 - User2
Account Alias - Group1 - User3
Account Alias - Group2 - User1
Account Alias - Group2 - User2
Account Alias - Group3 - User1
Account Alias - Group4 - Blank for no user
</code></pre>
<p>and so on.</p>
| <p>Here's an alternative solution for powershell v3.0+ that groups the data in a way that makes extraction to CSV a bit simpler.</p>
<p>Code:</p>
<pre><code>$alias = Get-IAMAccountAlias
Get-IAMGroups | % {
$group = $_;
(Get-IAMGroup -groupname $_.GroupName).Users | % {
[pscustomobject]@{
Alias = $alias;
GroupName = $group.groupname;
UserName = $_.UserName
}
}
} | ConvertTo-Csv -NoTypeInformation > mycsv.csv
</code></pre>
<p>Example Output:</p>
<pre><code>"Alias","GroupName","UserName"
"myacct","admins","myuser1"
"myacct","admins","myuser2"
"myacct","users","myuser3"
</code></pre>
<p>This script:</p>
<ul>
<li>iterates the output of Get-IAMGroups to get each GroupName</li>
<li>iterates the output of Get-IAMGroup to get each user, and their UserName</li>
<li>For each user, stores the Alias, GroupName, and UserName in a <a href="https://msdn.microsoft.com/en-us/library/system.management.automation.pscustomobject(v=vs.85).aspx" rel="nofollow">PSCustomObject</a> with properties of the same name.</li>
<li>Pipes the output collection of PSCustomObject to <code>ConvertTo-CSV</code> with <code>-NoTypeInformation</code> set to get the content in CSV format. Note here that if you want to change the delimiter, there is a <code>-Delimiter</code> flag that you can specify.</li>
<li>Redirects the output to <code>mycsv.csv</code> to write the file out to your file system</li>
</ul>
<p>A quick note from your attempt that probably gave you trouble: Stay away from using <code>Write-Host</code> to output data beyond your terminal; <code>Write-Host</code> does not write to the output stream. Here's a good <a href="https://blogs.technet.microsoft.com/heyscriptingguy/2014/03/30/understanding-streams-redirection-and-write-host-in-powershell/" rel="nofollow">blog post</a> on the subject for further reading.</p>
|
TypeError: 'NoneType' object is not iterable when trying to check for a None value <p>This is the error I receive:</p>
<pre class="lang-none prettyprint-override"><code>line 16, in main
definition, data = get_name ()
TypeError: 'NoneType' object is not iterable
</code></pre>
<p>I check for <code>None</code> type here:</p>
<pre><code>definition = get_word (name, gender)
if definition is None:
print ("\"" + non_lower + "\"", "not found.")
else:
return definition
</code></pre>
<p>Here is the code which will return <code>None</code> if the search term is not found:</p>
<pre><code>if x and new_line is not None:
return new_line, x
</code></pre>
<p>I am returning 2 values but it is returning one value and when I try to check that value for a <code>None</code> I get the error. If there anyway to check the variable for <code>None</code> correctly so if nothing is returned I can present a message?</p>
| <p>You have a double negative in the part that is returning <code>None</code> for the check later. Maybe try this:</p>
<pre><code>if x and new_line:
return new_line, x
else:
return None, None
</code></pre>
<p>Then when checking for <code>None</code> don't actually check for <code>None</code>, check the variable is something other than <code>None</code>, then catch <code>None</code> with the else statement?</p>
<pre><code>if definition:
return definition
else:
print ("\"" + non_lower + "\"", "not found.")
</code></pre>
|
sonarqube api/permission/add_group for project permission managenebt <p>Please advice what I did wrong with this api call for Sonarqube. </p>
<p>=> To give grp1 with issueadmin permission for myproj, I ran the command below</p>
<ol>
<li>curl -u admin:admin -X POST '<a href="http://localhost:9000/api/permissions/add_group?projectkey=mykey;groupId=4;permission=issueadmin" rel="nofollow">http://localhost:9000/api/permissions/add_group?projectkey=mykey;groupId=4;permission=issueadmin</a>'</li>
</ol>
<hr>
<pre><code> {"errors":[{"msg":"The 'permission' parameter for global permissions
must be one of admin, profileadmin, gateadmin, shareDashboard, scan,
provisioning. 'issueadmin' was passed."}]}
</code></pre>
<ol start="2">
<li>curl -u admin:admin -X POST '<a href="http://localhost:9000/api/permissions/add_group?projectkey=myproj;groupId=4;permission=issueadmin" rel="nofollow">http://localhost:9000/api/permissions/add_group?projectkey=myproj;groupId=4;permission=issueadmin</a>'</li>
</ol>
<hr>
<pre><code>{"errors":[{"msg":"The 'permission' parameter for global permissions must be
one of admin, profileadmin, gateadmin, shareDashboard, scan, provisioning.
'issueadmin' was passed."}]}
</code></pre>
<p>groupid = 4; </p>
<p>groupname = grp1</p>
<p>project name = myproj; </p>
<p>project id = 4; </p>
<p>project key = mykey</p>
| <p>Check out <code>api/permissions/add_group</code> documentation (<a href="http://sonarqube.com/web_api/api/permissions/add_group" rel="nofollow">here</a>) . The error messages you get talks about <strong>global</strong> permissions, so somehow the project key hasn't been interpreted correctly. Looking closer at the parameters:</p>
<blockquote>
<p><em>projectKey</em> - optional - Project key</p>
</blockquote>
<p>So typo it is. You've used <code>projectkey</code> instead of <code>projectKey</code>.</p>
<p>But then there's another problem in your URL: you're using <code>;</code> to separate parameters, instead of the standard <code>&</code>. All in all, this should do the trick:</p>
<blockquote>
<p>curl -u admin:admin -X POST '<a href="http://localhost:9000/api/permissions/add_group?projectKey=mykey&groupId=4&permission=issueadmin" rel="nofollow">http://localhost:9000/api/permissions/add_group?projectKey=mykey&groupId=4&permission=issueadmin</a>'</p>
</blockquote>
|
Efficiently adding large group of classes to a map array in C++ <p>So I have a huge amount of classes (20+ that I want to store into a map array as such:</p>
<pre><code>mapArray['ClassName'] = new ClassName();
</code></pre>
<p>I thought about doing something like</p>
<pre><code>App::setup() {
mapArray['ClassName1'] = new ClassName1();
mapArray['ClassName2'] = new ClassName2();
mapArray['ClassName3'] = new ClassName3();
}
</code></pre>
<p>However I think that is inefficient. I was thinking on how I would go about doing this, I was thinking to use preprocessor directives. Something like this</p>
<pre><code>#define DECLARE_CLASS(ClassName)
mapArray[ClassName] = new ClassName();
</code></pre>
<p>However, with this approach I would still need to to call that multiple time within the same function or something.</p>
<p>How would I go about adding all the classes to the same array but without calling the same code multiple time within the same function? So that the code isn't repetitive. </p>
| <p>Using</p>
<pre><code>App::setup() {
mapArray['ClassName1'] = new ClassName1();
mapArray['ClassName2'] = new ClassName2();
mapArray['ClassName3'] = new ClassName3();
}
</code></pre>
<p>is not a good idea (even after you fix the incorrect syntax of trying to use single quotes to define a string). It breaks the <a href="https://en.wikipedia.org/wiki/Open/closed_principle" rel="nofollow">Open/Closed Principle</a>. If you want to add <code>ClassNameN</code> to your system, you have to come back to modify a working function.</p>
<p>It's better to use a registration mechanism. Declare a function, <code>registerObject</code>, as:</p>
<pre><code>App::registerObject(std::string const& name, BaseClass* ptr);
</code></pre>
<p>and implement it as:</p>
<pre><code>static std::map<std::string, BaseClass*>& getClassMap()
{
static std::map<std::string, BaseClass*> theMap;
return theMap;
}
App::registerObject(std::string const& name, BaseClass* ptr)
{
getClassMap()[name] = ptr;
}
</code></pre>
<p>and then, in the source file that contains the implementation of <code>ClassNameN</code>, make sure to call</p>
<pre><code>App::registerObject("ClassNameN", new ClassNameN());
</code></pre>
<p>One way to register:</p>
<ol>
<li>Use a helper class called <code>Initializer</code>, which is defined in the .cpp file.</li>
<li>Make the call to <code>App::registerObject</code> in the constructor of `Initializer.</li>
<li>Create a file scoped <code>static</code> instance of <code>Initializer</code> in the .cpp file</li>
</ol>
<p>ClassName1.cpp:</p>
<pre><code>#include "ClassName1.hpp"
// You can use anonymous namespace but I prefer to use a named
// namespace. It makes names of the typeinfo object clearer.
namespace ClassName1NS
{
struct Initializer
{
Initializer();
};
}
static Initializer initializer
Initializer::Initializer()
{
App::registerObject("ClassName1", new ClassName1());
}
</code></pre>
|
How to hide navbar when when overlay appears <p>Using code from <a href="http://www.w3schools.com/howto/howto_js_sidenav.asp">W3schools</a> 'Sidenav Overlay' I'm trying to create the same effect in Bootstrap. I have the .navbar-toggle floating left and the navbar-toggle still shows when the overlay moves right. Not sure how to hide the navbar-toggle when the overlay appears. First post, Thanks</p>
<p>CSS</p>
<pre><code> .navbar {
webkit-box-shadow: 0px 2px 3px rgba(100, 100, 100, 0.49);
moz-box-shadow: 0px 2px 3px rgba(100, 100, 100, 0.49);
box-shadow: 0px 2px 3px rgba(100, 100, 100, 0.49);
background-color: white;
padding: 5px;
}
.navbar-brand {
position: absolute;
width: 100%;
left: 0;
top: 5px;
text-align: center;
margin: auto;
}
.navbar-toggle {
z-index:3;
border: none;
cursor: pointer;
float: left;
}
.navbar-toggle a:hover {
border: none;
background-color: none;
cursor: pointer;
}
/* The side navigation menu */
.sidenav {
height: 100%; /* 100% Full-height */
width: 0; /* 0 width - change this with JavaScript */
position: fixed; /* Stay in place */
z-index: 1; /* Stay on top */
top: 0;
left: 0;
background-color: #111; /* Black*/
overflow-x: hidden; /* Disable horizontal scroll */
padding-top: 60px; /* Place content 60px from the top */
transition: 0.5s; /* 0.5 second transition effect to slide in the sidenav */
}
/* The navigation menu links */
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s
}
/* When you mouse over the navigation links, change their color */
.sidenav a:hover, .offcanvas a:focus{
color: #f1f1f1;
}
/* Position and style the close button (top right corner) */
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
#main {
transition: margin-left .5s;
padding: 20px;
}
/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</code></pre>
<p>HTML</p>
<pre><code><header>
<div class="navbar navbar-default navbar-fixed-top" role="navigation" id="slide-nav">
<div class="container">
<div class="navbar-header">
<a class="navbar-toggle" onclick="openNav()">
<span class="sr-only" >Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="navbar-brand" href="#">Test Nav</a>
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
</div>
</div>
</div>
</header>
</code></pre>
<p>Javascript</p>
<pre><code>/* Set the width of the side navigation to 250px */
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
/* Set the width of the side navigation to 0 */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
</code></pre>
| <p>Add z-index as 99 instead of 1 to .sidenav class</p>
<pre><code>.sidenav {
background-color: #111;
height: 100%;
left: 0;
overflow-x: hidden;
padding-top: 60px;
position: fixed;
top: 0;
transition: all 0.5s ease 0s;
width: 0;
z-index: 99;
}
</code></pre>
|
Output ListBox as multiple line log <p>I have run into an issue when automating some of the error checking processes on a database. I need to output a log that is identical to an output to a ListBox, however my current (FreeFile) method, will overwrite the log file each time a new line is added to the box.</p>
<pre><code>Sub ExampleString (s As String)
Dim n as Object
n = FreeFile()
Open "C:\Path\TEST.txt" For Output As #n
If Not listBoxOut Is Nothing Then
With listBoxOut
' add items to List Box
Print #n, s
' iterate through List Box
Close #n
End With
End If
End Sub
</code></pre>
<p>How would I go about ouputting this text in an identical manner to how it is done in the ListBox, over multiple lines?</p>
<p>Thanks,</p>
<p>Neuw</p>
| <p>Dealing with the printing file statements only, you have to:</p>
<ul>
<li>change n type to <code>integer</code> </li>
<li>use <code>Append</code> keyword</li>
</ul>
<p>here's the revised code</p>
<pre><code>Sub ExampleString(s As String)
Dim n As Integer
n = FreeFile()
Open "C:\Path\TEST.txt" For Append As #n
If Not listBoxOut Is Nothing Then
With listBoxOut
' add items to List Box
Print #n, s
' iterate through List Box
Close #n
End With
End If
End Sub
</code></pre>
|
Bootstrap Navbar reducing height <p>I have a navbar, which is pretty standard, and I want to make it a bit thinner.</p>
<p>So I tried this:</p>
<p><a href="http://www.bootply.com/9VC5N55nJD" rel="nofollow">http://www.bootply.com/9VC5N55nJD</a></p>
<p>But the buttons remain too big. Click the drop down, and you'll see the issue. Is there a way to make the navbar thinner in one place? Or do you need to add css for the navbar and the buttons and what ever else may crop up?</p>
<p>Also, if I say it must be 30px in height - on a mobile, that might be too narrow, so do I need a media query for the different sizes?</p>
| <p><a href="http://www.bootply.com/B4CgVSZGMt#" rel="nofollow">Here</a> is a working fork of your code.</p>
<p><strong>Bootstrap</strong> by default uses a <code>padding-top: 15px</code> and <code>padding-bottom: 15px</code> for <code>.navbar-nav > li > a</code>. The following CSS will take care of this:</p>
<pre><code>.navbar-nav > li > a {
padding-top:10px;
padding-bottom:10px;
}
</code></pre>
<p>After reducing the screen size (and for mobile devices as you've mentioned) running a <strong>media query</strong> that resets them and kind of makes the <code>navbar</code> a bit larger will do the trick. The following is a <em>hacky</em> way to do so:</p>
<pre><code>@media (max-width: 768px) {
// enter css for mobile devices here
.topnav {
font-size: 14px;
}
.navbar {
min-height:50px;
max-height: 50px;
}
.navbar-nav > li > a {
padding-top:15px;
padding-bottom:15px;
}
}
</code></pre>
|
conditionally look up column names to populate new column in r <p>I have a data.frame that looks like this:</p>
<pre><code> A C G T
1 6 0 14 0
2 0 0 20 0
3 14 0 6 0
4 14 0 6 0
5 6 0 14 0
</code></pre>
<p>(actually, I have 1800 of the with varying numbers of rows..)</p>
<p>Just to explain what you are looking at:
Each row is one SNP, so it can either be one base (A,C,G,T) or another base (A,C,G,T)
SNP1âs Major allele is âGâ, which appears in 14 individuals, the minor allele is âAâ, which appears in 6 out of the 20 individuals in the dataset.
The 14 individuals that show G at SNP1 are the same the show A at SNP3, so there are two possibilities for the combination of bases along the 5 rows: one would be GGAAG and one would be AGGGA.
These can (theoretically) be built from the colnames of all the cells containing either 6 or 14 in the corresponding row, resulting in something like this:</p>
<pre><code> A C G T 14 6
1 6 0 14 0 G A
2 0 0 20 0 G G
3 14 0 6 0 A G
4 14 0 6 0 A G
5 6 0 14 0 G A
</code></pre>
<p>Is there an elegant way to achieve something like this?
I have a piece of code from the answer to a somewhat <a href="http://stackoverflow.com/questions/16905425/find-duplicate-values-in-r">related question</a> that will return positions of a specific value within a matrix. </p>
<pre><code> mat <- matrix(c(1:3), nrow = 4, ncol = 4)
[,1] [,2] [,3] [,4]
[1,] 1 2 3 1
[2,] 2 3 1 2
[3,] 3 1 2 3
[4,] 1 2 3 1
find <- function(mat, value) {
nr <- nrow(mat)
val_match <- which(mat == value)
out <- matrix(NA, nrow= length(val_match), ncol= 2)
out[,2] <- floor(val_match / nr) + 1
out[,1] <- val_match %% nr
return(out)
}
find(mat, 2)
[,1] [,2]
[1,] 2 1
[2,] 1 2
[3,] 0 3
[4,] 3 3
[5,] 2 4
</code></pre>
<p>I think I can figure out how to adjust this to where it returns the colname from the original data.frame, but it requires the value it is looking for as input. â There are potentially several of those in one data snippet (as seen in the example above, 14 and 6), and it is/they are different for each snippet of my data.
In some of them, there are no duplicates at all.
In addition, if one of the values hits 20, then the corresponding colname is automatically the one to choose (as seen in row 2 on the example above).</p>
<p><strong>EDIT</strong>
I have tried the code suggested by thelatemail, and it works fine on some of the data, but not on all of them.</p>
<p>This one, for example, produces results that I don't fully understand:
subset looks like this:</p>
<pre><code> A C G T
1 0 0 3 1
2 0 9 0 3
3 3 0 0 2
4 0 3 0 2
5 2 0 0 3
6 0 2 0 3
sel <- subset > 0
ord <- order(row(subset)[sel], -subset[sel])
haplo1 <- split(names(subset)[col(subset)[sel]][ord], row(subset)[sel][ord])
</code></pre>
<p>This produces </p>
<pre><code> 1
[1] "G" "T"
2
[1] "C" "T"
3
[1] "A" "T"
4
[1] "C" "T"
5
[1] "T" "A"
6
[1] "T" "C"
</code></pre>
<p>Since there is a 3 in every row, I don't understand why these are not all in one of these possibilities (which would result in GTACTT and TCTTAC instead).</p>
<p>I have also realized that I have a lot of missing alleles, were only one or two individuals were found to have a base in this locis.
Can a column with "missing" be included somehow? - I tried to just tack it on, which gave me an error about non-corresponding row numbers.</p>
| <p>In order to get my minimum function to work, I had to covert zero's to NA. For some reason, na.rm=TRUE doesn't work with which.min </p>
<p>See if this is helpful for you:</p>
<pre><code>A <- c(6,0,14,14,6)
C <- c(0,0,0,0,0)
G <- c(14,20,6,6,14)
T <- c(0,0,0,0,0)
mymatrix <- as.matrix(cbind(A,C,G,T))
mymatrix<-ifelse(mymatrix==0,mymatrix==NA,mymatrix)
mymatrix
major_allele <- colnames(mymatrix)[apply(mymatrix,1,which.max)] ; head(major_allele)
minor_allele <- colnames(mymatrix)[apply(mymatrix,1,which.min)] ; head(minor_allele)
myds<-as.data.frame(cbind(mymatrix,major_allele,minor_allele))
myds
> myds
A C G T major_allele minor_allele
1 6 <NA> 14 <NA> G A
2 <NA> <NA> 20 <NA> G G
3 14 <NA> 6 <NA> A G
4 14 <NA> 6 <NA> A G
5 6 <NA> 14 <NA> G A
</code></pre>
|
What is the last stable version of php 5.4 <p>Im currently working on php 5.3.13, and im thinking to upgrade my system for woocommerce im wondering what is the stable version in php 5.4? Is it 5.4.44?</p>
| <p>The LAST stable version of PHP 5.4 was 5.4.45, released at 09/2015.</p>
<p>You can get this info or download the files <a href="https://secure.php.net/releases/" rel="nofollow">here</a>.</p>
<p>The two CURRENT stable versions are PHP 7.0.11 and 5.6.26.</p>
|
Sorting strings with numbers in Python <p>I have this string: </p>
<pre><code>string = '9x3420aAbD8'
</code></pre>
<p>How can I turn string into:</p>
<pre><code>'023489ADabx'
</code></pre>
<p>What function would I use?</p>
| <p>You can just use the built-in function <a href="https://docs.python.org/3.5/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a> to sort the string lexographically. It takes in an iterable, sorts each element, then returns a sorted list. Per the documentation:</p>
<blockquote>
<p><code>sorted(iterable[, key][, reverse])</code></p>
<p>Return a new sorted list from the items in <em>iterable</em>.</p>
</blockquote>
<p>You can apply that like so:</p>
<pre><code>>>> ''.join(sorted(string))
'023489ADabx'
</code></pre>
<p>Since <code>sorted</code> returns a list, like so:</p>
<pre><code>>>> sorted(string)
['0', '2', '3', '4', '8', '9', 'A', 'D', 'a', 'b', 'x']
</code></pre>
<p>Just join them together to create the desired string.</p>
|
Save active record object without reference id <p>I have the following migrations: </p>
<pre><code> class CreateMothers < ActiveRecord::Migration[5.0]
def change
create_table :mothers do |t|
t.string :name
t.timestamps
end
end
end
</code></pre>
<p>and:</p>
<pre><code>class CreateSons < ActiveRecord::Migration[5.0]
def change
create_table :sons do |t|
t.string :name
t.references :mother
t.timestamps
end
end
end
</code></pre>
<p>Whenever I try to save a Son object with the mother_id field blank, I get the error: "Mother must exist"</p>
<p>Is there a way to save this without the mother_id field?</p>
| <p>In your <code>Son</code> model, just add the <code>optional</code> param to make it work:</p>
<pre><code>class Son < ApplicationRecord
belongs_to :mother, optional: true
end
</code></pre>
<p>In default, rails set it to be <code>true</code>, so let use <code>false</code> instead, the detail was described <a href="http://guides.rubyonrails.org/association_basics.html#optional" rel="nofollow">here</a></p>
|
Random generator to mix two numbers of a predetermined list into one with 100 unique results <p>I have 24 numbers (01, 02, 03, [...], 22, 23, 24). I need a generator that picks two numbers and mix them to one result (f.e.: 04 + 22 = 0422 or 2204). I need 100 unique results/combinations (no double results). Anyone knows, how to do this in a way which is really randomly (no manipulation, open source, etc...).</p>
| <p>Make an array with values 0..575 and use <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="nofollow">Fisher-Yates shuffle</a> approach. </p>
<pre><code>-- To shuffle an array a of n elements (indices 0..n-1):
for i from nâ1 downto 1 do
j â random integer such that 0 ⤠j ⤠i
exchange a[j] and a[i]
</code></pre>
<p>After every step (execute for-cycle 100 times) get <code>v=a[i]</code> element, and transform it into needed form:</p>
<pre><code> xx = ((v // 24) + 1) * 100 + ((v %% 24) + 1)
// - integer division and %% - modulo operations
</code></pre>
<p>then convert xx into length-4 string with leading zeros (like <code>%04d</code> printf specifier)</p>
|
Where is my below python code failing? <p>if the function call is like: backwardsPrime(9900, 10000) then output should be [9923, 9931, 9941, 9967]. Backwards Read Primes are primes that when read backwards in base 10 (from right to left) are a different prime. It is one of the kata in Codewars and on submitting the below solution, I am getting the following error: </p>
<p>Traceback:
in
File "./frameworks/python/cw-2.py", line 28, in assert_equals
expect(actual == expected, message, allow_raise)
File "./frameworks/python/cw-2.py", line 18, in expect
raise AssertException(message)
cw-2.AssertException: [1095047, 1095209, 1095319] should equal [1095047, 1095209, 1095319, 1095403]</p>
<pre><code>import math
def isPrime(num):
#flag = True
rt = math.floor(math.sqrt(num))
for i in range(2,int(rt)+1):
if num % i == 0:
return False
else:
return True
def Reverse_Integer(Number):
Reverse = 0
while(Number > 0):
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10
return Reverse
def backwardsPrime(start, stop):
s = list()
for i in range(start,stop):
if i>9 and i != Reverse_Integer(i):
if isPrime(i) and isPrime(Reverse_Integer(i)):
s.append(i)
else:
continue
return s
</code></pre>
<p>The Codewars have their own test functions. Sample test case below:</p>
<p>a = [9923, 9931, 9941, 9967]</p>
<p>test.assert_equals(backwardsPrime(9900, 10000), a) </p>
| <p>Looks like your code passes the test when run manually. Maybe they range to scan over is set wrong on the test causing it to miss the last one?</p>
<pre><code> backwardsPrime(1095000, 1095405)
[1095047, 1095209, 1095319, 1095403]
</code></pre>
<p>e.g. the second parameter is set to <code>1095400</code> or something.</p>
|
Is my UML Diagram Correct for the attached code? <p>My professor gave us this program but did not explain UML to us at all and I am wondering if I have made this diagram correctly.</p>
<p>CODE:</p>
<pre><code>package p1;
public class MyProg {
static int i = 5;
private Integer j = new Integer(10);
protected double k = 2.5;
public MyProg() {}
public static void main(String[] args) {
MyProg mp = new MyProg();
}
void m1(){
System.out.println("Hello World!");
}
void m1(String str, int n){
for(int k = 0; k < n; k++)
System.out.println(str);
}
public static int getI(){
return MyProg.i;
}
protected Integer getJ(){
return new Integer(j);
}
double getK(){
return new Double(k);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/AUFvI.png" rel="nofollow"><img src="https://i.stack.imgur.com/AUFvI.png" alt="enter image description here"></a></p>
| <p>On your diagram:</p>
<ul>
<li>As already mentioned i and j are not string</li>
<li>in main operation args parameter is some sort of array so you are missing the multiplicity indicator (asterisk in square brackets before closing round bracket). So the line should look like <code>+ main(in args: String[*])</code>. Of course underscored</li>
<li>in m1 operation n should have unspecified type</li>
<li>initial values should be specified as already mentioned in comments</li>
<li>you can use standard stereotype <> at MyProg operation to mark it as a constructor. Some books suggest not to model constructor unless it's non-standard (i.e. requires some parameters)</li>
<li>I would be very careful about in vs inout indicator for parameters. In Java the objects are passed through reference by default which means the parameter is inout, not in. In C++ it's the contrary situation, a parameter is passed through value i.e. it's in.</li>
</ul>
|
Grid Editing in shieldUI lite api <p>I have created a dynamic grid by using ShieldUI API and added dropdown boxes to each colunm. </p>
<p>Initial grid:
<a href="https://i.stack.imgur.com/Rr5sF.png" rel="nofollow"><img src="https://i.stack.imgur.com/Rr5sF.png" alt="enter image description here"></a></p>
<p>But when I am adding new row then previous rows values are being reset to null.According to my understanding this is happening because dropdown values are not being set into existing grid:</p>
<p><a href="https://i.stack.imgur.com/SSUto.png" rel="nofollow"><img src="https://i.stack.imgur.com/SSUto.png" alt="enter image description here"></a></p>
<p>And when I am clicking on grid anywhere then the grid row is freezing and row values are retained.</p>
<p>I am using custom editor for dropdown like:</p>
<pre><code>function subAccountCustomEditor(cell, item)
{
$('<div id="subAccount"/>')
.appendTo(cell)
.shieldDropDown({
dataSource: { data: [] },
value: !item["subAccount"] ? null : item["subAccount"].toString(),
textTemplate: "{value}",
valueTemplate: "{code}",
inputTemplate: "{value}"
}).swidget().focus();
}
</code></pre>
| <p>You can check out the following example:
<a href="http://demos.shieldui.com/web/grid-editing/editing-custom-editor" rel="nofollow">http://demos.shieldui.com/web/grid-editing/editing-custom-editor</a></p>
<p>To see how to initialize a custom editor. In this case it is a combo, but the same logic is applicable for a drop-down or any other widget. </p>
|
Java memory leak with Strings? Why is this consuming and crashing <p>Lists of Integer, Long, execute ok. However when using String the code below consumes over 5GB of memory when an entry at most should be in the neighborhood of 8 bytes per String, equating to only ~700MB. It also runs infinitely never throwing heap out of bounds. What is going on?</p>
<pre><code> List<List<String>> arrayList = new ArrayList<List<String>>();
long offset = 1000;
long size = 83886080;
int max = Integer.MAX_VALUE - 100;
long subloops = 1;
if(size > max)
{
subloops = size / max;
}
int temp = 0;
long count = 1;
long start = System.nanoTime();
for(int j=0; j<subloops; j++)
{
temp = (int)(size % max);
arrayList.add(new ArrayList<String>(temp));
List<String> holder = arrayList.get(j);
for (long i = 0; i < temp; i++)
{
holder.add(Long.toString(offset + count));
count++;
}
size -= temp;
}
long finalTime = System.nanoTime() - start;
System.out.println("Total time = " + finalTime);
System.out.println(count);
//for reference the max item length in bytes ends up being 8
System.out.println(Long.toString(offset+count).getBytes().length);
</code></pre>
| <p>Memory footprint of a <code>String</code> involves the memory overhead of an object plus the fields of the object. See this answer for detail: <a href="http://stackoverflow.com/a/258150/5221149">What is the memory consumption of an object in Java?</a></p>
<p>The <code>String</code> object has two instance fields in Java 8:</p>
<ul>
<li><code>char value[]</code></li>
<li><code>int hash</code></li>
</ul>
<p>Assuming 64-bit Java with compressed OOPS, that means memory is:</p>
<pre><code>String:
Object header: 12 bytes
Reference to char[]: + 4 bytes
Integer value: + 4 bytes
Data size: = 20 bytes
Total aligned size: 24 bytes
char[]:
Object header: 12 bytes
Array length: + 4 bytes
Characters: + 2 bytes * length
Data size (len=8): = 32 bytes
Total aligned size: 32 bytes
</code></pre>
<p>Add another 4 bytes for the reference to the string (stored in the <code>ArrayList</code>), and you get a total size for String of 8 characters: <strong><em>60 bytes</em></strong></p>
<p>Creating 83,886,080 strings then uses 5,033,164,800 bytes = <strong><em>4.7 Gb</em></strong>.</p>
|
Importing XLSX file into SAS <pre><code>OPTIONS NONOTES NOSTIMER NOSOURCE NOSYNTAXCHECK;
PROC IMPORT OUT= Census.taxp_lookupDATAFILE="C:\Users\Dhruv\Desktop\Book1.xlsx"
DBMS=xlsx REPLACE;
SHEET="tax_group";
GETNAMES=YES;
RUN;
ERROR: Physical file does not exist, /opt/sasinside/SASConfig/Lev1/SASApp/C:\Users\Dhruv\Desktop\/Book1.xlsx.
</code></pre>
<p>I am facing this error while importing excel file into sas. What do i need to change in my code</p>
| <blockquote>
<p>you basically need to specify the data to be read: DATAFILE=""</p>
</blockquote>
<pre><code>/** Import an XLSX file. **/
PROC IMPORT DATAFILE="<Your XLSX File>"
OUT=WORK.MYEXCEL
DBMS=XLSX
REPLACE;
RUN;
/** Print the results. **/
PROC PRINT DATA=WORK.MYEXCEL; RUN;
</code></pre>
<p><a href="https://i.stack.imgur.com/vnVTw.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/vnVTw.jpg" alt="here is how to find the right path for your folder"></a></p>
<p><a href="http://www.sas.com/apps/webnet/video-sharing.html?player=brightcove&width=640&height=360&autoStart=true&playerID=1873162645001&playerKey=AQ~~,AAABs_kuvqE~,9q03viSCCi8Qu-ec7KH7e-bapzBTKVDB&videoPlayer=4262543790001&emptyPage=false" rel="nofollow">Video on how to find the excel file and find the right path for SASstudio</a></p>
<blockquote>
<p>PS: to answer the questions: "basically you need to have the file already in My Folders and not path to your local desktop file, also if you are using a server than you need to import, I'm not sure if to SAS University Edition is the option Import on right click folder like in picture listed below: Screen for import is SAS Studio"</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/vAUH1.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/vAUH1.jpg" alt="Screen for import in SAS Studio"></a></p>
|
How to fix options request in node js <p>I am using react to send data to my API. Every POST request I make gives me an OPTIONS request, and I need to fix this. I think I might need to do some preflight structure but after reading about it I still do not know how to implement it.</p>
<p>At the moment I am connecting to my API as so...</p>
<pre><code>fetch('http://localhost:8080/login', {
method: 'POST',
mode:'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
});
</code></pre>
<p>This is called <code>onSubmit</code>. I am sending some data to my POST request so I am assuming I need those headers.</p>
<p>Now in my node js server API I have the following handler...</p>
<pre><code>var responseHeaders = {
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
"access-control-allow-headers": "content-type, accept",
"access-control-max-age": 10,
"Content-Type": "application/json"
};
app.post('/login', function(req, res, next) {
if (req.method == "OPTIONS") {
res.writeHead(statusCode, responseHeaders);
res.end();
}
console.log("hello");
...
</code></pre>
<p>This does not work however, when I make a request I get...</p>
<pre><code>OPTIONS /login 200 8.570 ms - 4
</code></pre>
<p>If I remove the headers the POST works but the data (username, password) is not passed through.</p>
<p>How can I bypass this OPTIONS problem?</p>
| <p>The browser sends a preflight Options requests to the server to check if CORS is enabled on the server. To enable cors on the server side add this to yor server</p>
<pre><code>app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
</code></pre>
|
App Store Publication and Update Process <p>I have following conditions:</p>
<p>We want to <strong>change app icon</strong> and <strong>add screenshots</strong>. Can it be done without upload new binary?</p>
<p>Currently no screenshots under 5.5" and 4.7" display when we want to upload new version of app. Do we need to upload screenshots prior to Submit for Review?</p>
| <p>App screenshots (device/size doesn't matter), app previews and app icons can <strong>only be changed</strong> with a new version/binary of your app. </p>
<p>Complete overview of all the fields and stuff you can edit in iTunes Connect is over here: <a href="https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Appendices/Properties.html#//apple_ref/doc/uid/TP40011225-CH26-SW1" rel="nofollow">https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Appendices/Properties.html#//apple_ref/doc/uid/TP40011225-CH26-SW1</a></p>
|
Uncaught ReferenceError: Searchbar is not defined <p>Sorry, i am new in React.
I have 2 components in my react application. Here is the parent:</p>
<pre><code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import './Searchbar';
const App =() => {
return (
<div className="App">
<div className="App-header">
<Searchbar></Searchbar>
<h2>Welcome to React</h2>
</div>
</div>
);
}
export default App;
</code></pre>
<p>and here is the searchbar component:</p>
<pre><code>import React,{Component} from 'react';
export default class Searchbar extends Component{
render(){
return <div>Here is search bar</div>;
}
}
</code></pre>
<p>Unfortunately, when the page loads it complains with the error:</p>
<pre><code>Uncaught ReferenceError: Searchbar is not defined
</code></pre>
<p>It seems that, it does not recognize the Searchbar component.
What is the problem?</p>
| <p>The solution is really simple. You are importing the searchbar wrongly in your file. You need to import it like <code>import Searchbar from './Searchbar';</code> , since you have exported it as default you also need to import it in default manner.</p>
<pre><code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Searchbar from './Searchbar';
const App =() => {
return (
<div className="App">
<div className="App-header">
<Searchbar></Searchbar>
<h2>Welcome to React</h2>
</div>
</div>
);
}
export default App;
</code></pre>
|
Django join on multiple foreign fields (left join) <p>I'm using django 1.10 and have the following two models</p>
<pre><code>class Post(models.Model):
title = models.CharField(max_length=500)
text = models.TextField()
class UserPost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
approved = models.BooleanField(default=False)
</code></pre>
<p>How do I get a list of all the posts including the 'approved' property for the logged in user if exists? So instead of multiple queries, it would be one left join query, pseudo-code:</p>
<pre><code>select * from posts as p
left join user_posts as up
on up.post_id = p.post_id
and up.user_id = 2
</code></pre>
<p>Output</p>
<pre><code>post_id | title | text | user_id | approved
1 | 'abc' | 'abc' | 2 | true
2 | 'xyz' | 'xyz' | null | null
3 | 'foo' | 'bar' | 2 | true
</code></pre>
<p>I created the models this way because the 'approved' property belongs to the user. Every user can approve/reject a post. The same post could be approved and rejected by other users. Should the models be setup differently?</p>
<p>Thanks</p>
<p><strong>Update:</strong>
I'm trying to create a webpage to display all available posts and highlight the ones that the current user approved. I could just list all posts and then for each post check if the 'UserPost' table has a value, if yes get the approved property else ignore. But that means if I have 100 posts I'm making 100 + 1 calls to the db. Is it possible to do 1 call using ORM? If this is not possible, should the models be setup differently?</p>
| <p>Then I think you need something like this:</p>
<pre><code>Post.objects.all().annotate(
approved=models.Case(
models.When(userpost_set__user_id=2,
then=models.F('userpost__approved')),
default=models.Value(False),
output_field=models.BooleanField()
)
)
</code></pre>
|
Temporary Public URL for IBM Bluemix Object Storage Service with NodeJs <p>Use case: File uploaded in to IBM Object Storage. Now want to provide temporary access via a signed URL that will expire after a certain delay.</p>
<p>Only SWIFT are being supported officially, need a workaround that works with JAVASCRIPT -> NodeJs.</p>
| <hr>
<p>You have to install SWIFT CLI and set a temporary key for your credentials. </p>
<p>This step is super important and CAN ONLY BE DONE BY USING THE SWIFT CLI as there is now way to do that currently with Bluemix Console.</p>
<p>STEP 0 - ************ MANDATORY *************
INSTALL SWIFT CLI</p>
<p>REF: <a href="https://new-console.ng.bluemix.net/docs/services/ObjectStorage/objectstorge_usingobjectstorage.html#using-swift-cli" rel="nofollow">https://new-console.ng.bluemix.net/docs/services/ObjectStorage/objectstorge_usingobjectstorage.html#using-swift-cli</a></p>
<p>STEP 1 - ************ MANDATORY *************
Generate a secret key, the longer the better.</p>
<p>$ swift post -m "Temp-URL-Key:2d2a3e9f12e87b1_SOMEKEY_2d2a3e9f12e87b1"</p>
<p>***You can retrieve it anytime by typing in the bash --> $ swift stat</p>
<hr>
<p>STEP 2 - ************ OPTIONAL *************
Install dotenv package
$ npm install --save dotenv</p>
<p>STEP 3 - ************ OPTIONAL *************
Create a .env file
$ touch .env</p>
<p>STEP 4 - ************ OPTIONAL *************
Edit the .env file and put those values in and save the file.</p>
<p><strong>(ref. --> as per STEP 1)</strong></p>
<p>META_TEMP_URL_KEY=b463af8f_SOMEVALUEKEY_b463af8fb463af8f </p>
<p><strong>(ref. --> The projectid as per provided by the Bluemix Console)</strong></p>
<p>PROJECTID=50e8a0e8SOMEVALUEKEYbb463af8f </p>
<pre><code>require('dotenv').config();
var crypto = require('crypto');
var META_TEMP_URL_KEY = process.env.META_TEMP_URL_KEY; // See Step 1
var baseUrl = 'https://dal.objectstorage.open.softlayer.com'; // Since my bucket is in DALLAS I am having this URL
var HTTPMethod = 'GET'; // Always GET - As the file has been already uploaded.
var containerName = 'expenses'; // Container Name as per in the Bluemix console - Ex: expenses
var objectName = 'report.pdf'; // The object filename - Ex: report.pdf
var seconds = 60; // Delay of the temporary URL to be valid.
var tempURL = getTempURL(baseUrl, HTTPMethod, containerName, objectName, seconds);
console.log(tempURL); // It should return in this case something like this:
// https://dal.objectstorage.open.softlayer.com/v1/AUTH_X0X0X0X0XX0X0XX0X0X/expenses/report.pdf?temp_url_sig=Z0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z0Z0&temp_url_expires=1476243544
function getTempURL(baseUrl, HTTPMethod, metaTempURLKey, projectID, containerName, objectName, seconds) {
var expires = Math.floor(Date.now() / 1000) + seconds;
var url = containerName + '/' + objectName;
var method = HTTPMethod;
var key = key;
var objectPath = '/v1/AUTH_' + process.env.PROJECTID + '/' + url;
var hmacBody = method + '\n' + expires + '\n' + objectPath;
var sig = crypto.createHmac('sha1', key).update(hmacBody).digest('hex');
var tempURL = baseUrl + objectPath + '?temp_url_sig=' + sig + '&temp_url_expires=' + expires;
return tempURL;
}
</code></pre>
|
Error in configuring Flume to Collect Data into HDFS from Twitter - org.apache.commons.cli.UnrecognizedOptionException: Unrecognized option: -conf <p>Executed the command:</p>
<pre><code>./bin/flume-ng agent -conf ./conf/ -f conf/flume.conf -Dflume.root.logger-DEBUG, console -n TwitterAgent
</code></pre>
<p>and got the following error:</p>
<blockquote>
<p>org.apache.commons.cli.UnrecognizedOptionException: Unrecognized
option: -conf</p>
</blockquote>
| <p>Change <strong>-conf</strong> to <strong>--conf</strong> , it should work.</p>
<p>The below is the syntax to start Flume.</p>
<pre><code>$ bin/flume-ng agent --conf conf --conf-file example.conf --name a1 -Dflume.root.logger=INFO,console
</code></pre>
|
Not able to execute pip commands even though pip is installed and added to PATH <p>I already have pip installed and added the corresponding path to my path,however I dont seem to be able to execute any pip commands(see below),what am I missing?</p>
<pre><code>C:\Python27\Lib\site-packages\pip>get-pip.py
You are using pip version 6.0.6, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Requirement already up-to-date: pip in c:\python27\lib\site-packages
C:\Python27\Lib\site-packages\pip>pip install subprocess32
'pip' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
| <p>You have <code>pip</code> installed but you don't have any command named <code>pip</code>.</p>
<p>try <code>python -m pip</code></p>
|
find the location of the cmd.exe file <p>I have built a c++ program that depends on "cmd.exe" to execute some of the tasks.
For now I and for test purposes the path to that file is "c:\windows\system32\cmd.exe".
My question is there any c++ API that returns the path of that file knowing that my program must work on win32 and on win64.</p>
| <p><code>GetSystemDirectory</code> is one option. For a 32-bit app, it will return the 32-bit system directory. For an x64 app, it will return the 64-bit native system directory.</p>
<p>You can also use <code>CreateProcess</code> or <code>ShellExecuteEx</code> with <code>cmd.exe</code> and it should find it without the path unless you are specifically concerned about someone manipulating the search path and getting the wrong <code>cmd.exe</code>.</p>
<p>If you are launching a <code>.cmd</code> file, then you can just do it with <code>ShellExecuteEx</code> with the <code>open</code> verb. Generally for a Windows desktop app, use of <code>ShellExecuteEx</code> is recommended for launching other programs. For example, here's some code that will launch the command prompt running the <code>test.cmd</code> script and wait for the result:</p>
<pre><code>#include <windows.h>
#include <stdio.h>
#pragma comment(lib,"shell32.lib")
void main()
{
SHELLEXECUTEINFOW info = {};
info.cbSize = sizeof( info );
info.lpVerb = L"open";
info.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS;
info.lpFile = L"test.cmd";
info.lpParameters = nullptr; // Command-line parameters
info.lpDirectory = nullptr; // Working directory to set
info.nShow = SW_SHOW;
if( !ShellExecuteExW( &info ) )
{
printf("ERROR\n");
}
else
{
// Wait for process to finish.
WaitForSingleObject( info.hProcess, INFINITE );
// Return exit code from process
DWORD exitcode;
GetExitCodeProcess( info.hProcess, &exitcode );
CloseHandle( info.hProcess );
printf("Finished with exit code %u\n", exitcode);
}
}
</code></pre>
<p>You can also use:</p>
<pre><code>info.lpFile = L"cmd.exe";
info.lpParameters = L"/c test.cmd";
</code></pre>
<blockquote>
<p>The primary reason to use <code>ShellExecuteEx</code> instead of <code>CreateProcess</code> is that <code>ShellExecuteEx</code> can handle admin elevation requests for exes with the proper <a href="https://blogs.msdn.microsoft.com/chuckw/2013/09/10/manifest-madness/" rel="nofollow">manifest elements</a>. <code>CreateProcess</code> would fail if the target EXE requires higher privileges than your current process.</p>
</blockquote>
|
How to implement INotifyPropertyChanged <p>I need help implementing INotifyPropertyChanged in my own data structure class. This is for a class assignment, but implementing INotifyPropertyChanged is an addition that I am doing above and beyond what the rubric requires.</p>
<p>I have a class named 'BusinessRules' that uses a SortedDictionary to store objects of 'Employee' type. I have a DataGridView showing all of my employees, and I want to use my BusinessRules class object as the DataSource for my DataGridView. The BusinessRules container is required for the assignment. I have tried to implement INotifyPropertyChanged in this class, with no success.</p>
<p>The DataSource that I have working is a BindingList. Presently, I am using that BindingList as a 'sidecar' container and setting that as my DataSource. Every change that I make to my BusinessRules class object is mirrored to my BindingList class object. But this is obviously sloppy programming, and I want to do better.</p>
<p>I have tried to implement INotifyPropertyChanged in BusinessRules, but when I set my instantiated BusinessRules object as the DataSource, the DataGridView shows nothing. What I suspect the problem to be is with the NotifyPropertyChanged() method. I do not know what to pass to this, nor what to do with what is passed in. Most examples deal with changing a name, but I am more concerned when a new object is added to the SortedDictionary.</p>
<pre><code> private void NotifyPropertyChanged( Employee emp )
{
PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( emp.FirstName ) );
}
</code></pre>
<p>What do I need to change in order to get this working? Will you explain why my attempt is not working?</p>
<p>I am notoriously bad about forming my questions on StackOverflow. This is not intentional. Please, let me know what other information you require, and I will provide it as quickly as I can.</p>
<p><a href="https://gist.github.com/AdamJHowell/3bfbbb48972825517ebc0dec367b462f" rel="nofollow">Here is a link to my BusinessRules source code</a>.</p>
| <p>It will be very helpful if you read tutorials on <a href="http://www.markwithall.com/programming/2013/03/01/worlds-simplest-csharp-wpf-mvvm-example.html" rel="nofollow">how to implement MVVM</a>.</p>
<p>You'd wanna have a base class that implements <code>INotifyPropertyChanged</code> interface. So all your view models should inherit from this base class.</p>
<pre><code>public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
// This sample class DelegateCommand is used if you wanna bind an event action with your view model
public class DelegateCommand : ICommand
{
private readonly Action _action;
public DelegateCommand(Action action)
{
_action = action;
}
public void Execute(object parameter)
{
_action();
}
public bool CanExecute(object parameter)
{
return true;
}
#pragma warning disable 67
public event EventHandler CanExecuteChanged;
#pragma warning restore 67
}
</code></pre>
<p>Your view model should look like this.</p>
<pre><code>public sealed class BusinessRules : ViewModelBase
</code></pre>
<p>Here's an example on how to utilize the <code>RaisePropertyChangedEvent</code>.</p>
<pre><code>public sealed class Foo : ViewModelBase
{
private Employee employee = new Employee();
private string Name
{
get { return employee.Name; }
set
{
employee.Name = value;
RaisePropertyChangedEvent("Name");
// This will let the View know that the Name property has updated
}
}
// Add more properties
// Bind the button Command event to NewName
public ICommand NewName
{
get { return new DelegateCommand(ChangeName)}
}
private void ChangeName()
{
// do something
this.Name = "NEW NAME";
// The view will automatically update since the Name setter raises the property changed event
}
}
</code></pre>
<p>I don't really know what you want to do so I'll leave my example like this. Better read different tutorials, the learning curve is a bit steep.</p>
|
NavigationView with DrawerLayout setCheckedItem not working <p>I want let <code>NavigationView</code> check one item when app startup. But i found <code>NavigationView.setCheckedItem(R.id.xxx)</code> not working. And i also tried <code>navigationView.getMenu().findItem(R.id.xxx).setChecked(true)</code>, same result.</p>
<p>I've already set checkableBehavior to single.</p>
<pre><code><item android:title="@string/sliding_menu_group_places">
<menu>
<group android:checkableBehavior="single">
<item
android:id="@+id/xxx"
android:icon="@drawable/xxx"
android:title="@string/xxx" />
<item
android:id="@+id/xxx"
android:icon="@drawable/xxx"
android:title="@string/xxx" />
...
</group>
</menu>
</item>
</code></pre>
<p>But there is one way worked:</p>
<pre><code>drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
@Override
public void onDrawerOpened(View drawerView) {
navigationView.setChecked(R.id.xxx);
}
@Override
public void onDrawerClosed(View drawerView) {
}
@Override
public void onDrawerStateChanged(int newState) {
}
});
</code></pre>
<p>The navigation item would be checked in onDrawerOpened callback. I've searched a lot in stackoverflow but none methods work for me. Who can help me about this.</p>
<p><strong>EDIT-1</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
</code></pre>
<p></p>
<pre><code><group android:checkableBehavior="single">
<item
android:id="@+id/xxx"
android:icon="@drawable/xxx"
android:title="@string/recent_display_name" />
<item android:title="@string/sliding_menu_group_places">
<menu>
<group android:checkableBehavior="single">
<item
android:id="@+id/xxx"
android:icon="@drawable/xxx"
android:title="@string/my_files_display_name" />
<item
android:id="@+id/nav_item_sdcard"
android:icon="@drawable/ic_nav_sdcard"
android:title="@string/storage_display_name" />
</group>
</menu>
</item>
<item android:title="@string/sliding_menu_group_tool">
<menu>
<group android:checkableBehavior="single">
<item
android:id="@+id/xxx"
android:icon="@drawable/xxx"
android:title="@string/clean_display_name" />
</group>
</menu>
</item>
<item android:title="@string/sliding_menu_group_settings">
<menu>
<group android:checkableBehavior="single">
<item
android:id="@+id/xxx"
android:icon="@drawable/xxx"
android:title="@string/settings_display_name" />
<item
android:id="@+id/xxx"
android:icon="@drawable/xxx"
android:title="@string/exit_display_name" />
</group>
</menu>
</item>
</group>
</code></pre>
<p></p>
| <p>Try this way :</p>
<pre><code> menuItem.setCheckable(true);
menuItem.setChecked(true);
if (mPreviousMenuItem != null && mPreviousMenuItem != menuItem) {
mPreviousMenuItem.setChecked(false);
}
mPreviousMenuItem = menuItem;
</code></pre>
|
Angularjs CRUD delete issue (GET called in DELETE method) <p>I am trying to consume my spring rest service using angularjs client following this <a href="http://websystique.com/springmvc/spring-4-mvc-angularjs-crud-application-using-ngresource/" rel="nofollow">link</a></p>
<p>Create,update and read parts are working. When I try to delete, its showing this error.</p>
<blockquote>
<p>Error: [$resource:badcfg] Error in resource configuration for action
<code>get</code>. Expected response to contain an object but got an array
(Request: GET <a href="http://localhost:8080/SpringRestExample/employee" rel="nofollow">http://localhost:8080/SpringRestExample/employee</a>)</p>
</blockquote>
<p>Why i am getting GET request in DELETE method?</p>
<p>employee_service.js</p>
<pre><code>'use strict';
App.factory('Employee', ['$resource', function ($resource) {
return $resource(
'http://localhost:8080/SpringRestExample/employee/:id',
{id: '@employeeId'},
{
update: {
method: 'PUT'
}
}
);
}]);
</code></pre>
<p>employee_controller.js</p>
<pre><code>'use strict';
App.controller('EmployeeController', ['$scope', 'Employee', function($scope, Employee) {
var self = this;
self.employee= new Employee();
self.employees=[];
self.fetchAllEmployees = function(){
self.employees = Employee.query();
};
self.createEmployee = function(){
self.employee.$save(function(){
self.fetchAllEmployees();
});
};
self.updateEmployee = function(){
self.employee.$update(function(){
self.fetchAllEmployees();
});
};
self.deleteEmployee = function(identity){
var employee = Employee.get({employeeId:identity}, function() {
employee.$delete(function(){
console.log('Deleting employee with id ', identity);
self.fetchAllEmployees();
});
});
};
self.fetchAllEmployees();
self.submit = function() {
if(self.employee.employeeId==null){
console.log('Saving New Employee', self.employee);
self.createEmployee();
}else{
console.log('Updating employee with id ', self.employee.employeeId);
self.updateEmployee();
console.log('Employee updated with id ', self.employee.employeeId);
}
self.reset();
};
self.edit = function(employeeId){
console.log('id to be edited', employeeId);
for(var i = 0; i < self.employees.length; i++){
if(self.employees[i].employeeId === employeeId) {
self.employee = angular.copy(self.employees[i]);
break;
}
}
};
self.remove = function(employeeId){
console.log('id to be deleted', employeeId);
if(self.employee.employeeId === employeeId) {//If it is the one shown on screen, reset screen
self.reset();
}
self.deleteEmployee(employeeId);
};
self.reset = function(){
self.employee= new Employee();
$scope.myForm.$setPristine(); //reset Form
};
}]);
</code></pre>
| <p>Your issue could be when you call <code>Employee.get({employeeId:identity}, ...)</code> prior to deleting the employee. This will load the employee before deletion and it will do a GET request on <code>'http://localhost:8080/SpringRestExample/employee/:id'</code>. </p>
<p>For this query to work properly, you need to provide <code>id</code>, which you haven't done, so it might just be leaving out that part of the URL. You provided <code>employeeId</code>, which is only used for mapping the id parameter to the <code>Employee</code> objects. Try replacing the query above with <code>{id: identity}</code>.</p>
|
How to show a dropdown inside ng-repeat <p>I am working on a project where I have a list of details.
I need to give a dropdown option on Delete button click. I have tried it but unable to show the dropdown inside ng-repeat. Can anyone guide me how to achieve this.</p>
<p>I want to show a dropdown list when I click on delete button.</p>
<p>Below is the code which I tried with no result: </p>
<pre class="lang-html prettyprint-override"><code><i class="fa fa-download tooltipped dropdown-button" data-activates='deleteList{{u.$index}}' data-position="top" data-tooltip="Downloads" aria-hidden="true" tooltip-loader></i>
<ul id='deleteList{{u.$index}}' class='dropdown-content' style="">
<li><a ng-click="deleteAll();">Delete all</a>
</li>
<li><a ng-click="deleteSelected();">Delete only selected</a>
</li>
</ul>
</code></pre>
<p><a href="http://jsfiddle.net/charms/eP7T8/61/" rel="nofollow">Fiddle</a></p>
| <p>i have created demo for dropdown:</p>
<p><strong>html:</strong></p>
<pre><code><button ng-model="show" ng-click="show=!show">
delete
</button>
<ul ng-show="show">
<li>Delete all</li>
<li>Delete only selected</li>
</ul>
</code></pre>
<p><strong>css:</strong></p>
<pre><code>ul{
padding:0;
margin:0;
border:1px solid #a6a6a6;
width:150px;
}
li{
list-style-type:none;
cursor:pointer;
}
li:hover{
background-color:#b3b3b3;
}
</code></pre>
<p>And here is jsfiddle: <a href="https://jsfiddle.net/exf72nmq/" rel="nofollow">Demo</a></p>
<p><strong>Dropdown in ng-repeat:</strong></p>
<p>And here is complete solution in your jsfiddle:
<a href="http://jsfiddle.net/eP7T8/116/" rel="nofollow">http://jsfiddle.net/eP7T8/116/</a></p>
|
overwrite attribute as function Django <p>I have <code>class A(models.Model)</code> with attr <code>name</code>. I use it in template and view as <code>obj_a.name</code>. I need overwrite <code>name</code> attr as function and when I write <code>obj_a.name</code> I would get response from function <code>getName</code>. How can I do it in <code>Django</code> and <code>Python</code> ?
In <code>Laravel PHP</code> it is <code>$this->getNameAttribute()</code> and I can overwrite returning <code>name</code> from object. <code>Name</code> is only example and I want use it with almost all attr given class.</p>
<pre><code>class Item(caching.base.CachingMixin, models.Model):
_name = models.CharField(_('Name'), max_length=100, db_column="name",
help_text=_('Item name'))
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
</code></pre>
| <p>You can achieve this behavior with <a href="https://docs.python.org/2/library/functions.html#property" rel="nofollow"><code>property</code></a>.</p>
<pre><code>class A(models.Model):
_name = Field()
@property
def name(self):
return self._name
</code></pre>
|
Bundle Error on macOS 10.12 Sierra <pre><code>Ignoring binding_of_caller-0.7.2 because its extensions are not built. Try: gem pristine binding_of_caller --version 0.7.2
Ignoring byebug-9.0.6 because its extensions are not built. Try: gem pristine byebug --version 9.0.6
Ignoring capybara-webkit-1.11.1 because its extensions are not built. Try: gem pristine capybara-webkit --version 1.11.1
Ignoring debug_inspector-0.0.2 because its extensions are not built. Try: gem pristine debug_inspector --version 0.0.2
Ignoring binding_of_caller-0.7.2 because its extensions are not built. Try: gem pristine binding_of_caller --version 0.7.2
Ignoring byebug-9.0.6 because its extensions are not built. Try: gem pristine byebug --version 9.0.6
Ignoring capybara-webkit-1.11.1 because its extensions are not built. Try: gem pristine capybara-webkit --version 1.11.1
Ignoring debug_inspector-0.0.2 because its extensions are not built. Try: gem pristine debug_inspector --version 0.0.2
Ignoring eventmachine-1.2.0.1 because its extensions are not built. Try: gem pristine eventmachine --version 1.2.0.1
Ignoring eventmachine-1.0.9.1 because its extensions are not built. Try: gem pristine eventmachine --version 1.0.9.1
Ignoring ffi-1.9.14 because its extensions are not built. Try: gem pristine ffi --version 1.9.14
Ignoring http_parser.rb-0.6.0 because its extensions are not built. Try: gem pristine http_parser.rb --version 0.6.0
Ignoring io-console-0.4.6 because its extensions are not built. Try: gem pristine io-console --version 0.4.6
Ignoring json-2.0.2 because its extensions are not built. Try: gem pristine json --version 2.0.2
Ignoring kgio-2.10.0 because its extensions are not built. Try: gem pristine kgio --version 2.10.0
Ignoring mysql2-0.4.4 because its extensions are not built. Try: gem pristine mysql2 --version 0.4.4
Ignoring nio4r-1.2.1 because its extensions are not built. Try: gem pristine nio4r --version 1.2.1
Ignoring nokogiri-1.6.8.1 because its extensions are not built. Try: gem pristine nokogiri --version 1.6.8.1
Ignoring pg-0.19.0 because its extensions are not built. Try: gem pristine pg --version 0.19.0
Ignoring psych-2.1.1 because its extensions are not built. Try: gem pristine psych --version 2.1.1
Ignoring puma-3.6.0 because its extensions are not built. Try: gem pristine puma --version 3.6.0
Ignoring raindrops-0.17.0 because its extensions are not built. Try: gem pristine raindrops --version 0.17.0
Ignoring rgeo-0.5.3 because its extensions are not built. Try: gem pristine rgeo --version 0.5.3
Ignoring rmagick-2.16.0 because its extensions are not built. Try: gem pristine rmagick --version 2.16.0
Ignoring sqlite3-1.3.11 because its extensions are not built. Try: gem pristine sqlite3 --version 1.3.11
Ignoring therubyracer-0.12.2 because its extensions are not built. Try: gem pristine therubyracer --version 0.12.2
Ignoring thin-1.5.1 because its extensions are not built. Try: gem pristine thin --version 1.5.1
Ignoring unf_ext-0.0.7.2 because its extensions are not built. Try: gem pristine unf_ext --version 0.0.7.2
Ignoring unicorn-5.1.0 because its extensions are not built. Try: gem pristine unicorn --version 5.1.0
Ignoring websocket-driver-0.6.4 because its extensions are not built. Try: gem pristine websocket-driver --version 0.6.4
The git source `git://github.com/plataformatec/devise.git` uses the `git` protocol, which transmits data without encryption. Disable this warning with `bundle config git.allow_insecure true`, or switch to the `https` protocol to keep your data secure.
The git source `git://github.com/jetthoughts/yaml_db.git` uses the `git` protocol, which transmits data without encryption. Disable this warning with `bundle config git.allow_insecure true`, or switch to the `https` protocol to keep your data secure.
</code></pre>
<p>Is there any way to solve this issue?</p>
| <p>Reinstall the version of Ruby you're using (via rbenv, rvm, etc.) and then run <code>gem pristine --all</code> to rebuild any gems using native extensions.</p>
|
Kendo Grid - Dynamic Column and Custom Template <p>I have a problem with kendo Grid and Custom template. The problem is, I need to check the value of the column</p>
<ul>
<li>if Value == 1, I need to change it to Icon Check</li>
<li>If Value == 0, I need to change it to Icon Delete</li>
<li>If Value == -1. I need to return empty html</li>
</ul>
<p>This is the Example Code : <a href="http://jsfiddle.net/hG6zR/16/" rel="nofollow">Fiddle</a></p>
<pre><code>var myFields = {
no: { },
section: { },
service: { }
};
for(var x = 0 ; x < dataList.length; x++){
myFields["data"+x] = { };
}
var no = 0;
var myColumns = [
{ title: "No", locked: true, width: 50, template: function(e){return ++no; } },
{ field: "section", title: "Hole Section", locked: true, width: 130 },
{ field: "service", title: "Services", locked: true, width: 200 }
/* other columns ... */
];
for(var x = 0 ; x < dataList.length; x++){
myColumns.push( { field: "data"+x, title: dataList[x], width: 100, locked: false});
}
</code></pre>
| <p>Here is a <strong><a href="http://jsfiddle.net/RajReddy/hG6zR/17/" rel="nofollow">Working Demo</a></strong></p>
<p><strong>Solution</strong>: You can change your data fed into the grid by <strong>replacing the numbers with a icon</strong>. I prefer using <strong><a href="http://fontawesome.io/icons/" rel="nofollow">FontAwesome Icons</a></strong> as it is very light weight. </p>
<p>CDN for font awesome. </p>
<p><a href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="nofollow">https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css</a></p>
<p>Code change to make changes into your data is as below. </p>
<pre><code>tableData[tableData.length - 1]["data"+c] = formatCellData(dataOffset[c].selected);
// replace you code with function call.
</code></pre>
<p>the function definition is as below.</p>
<pre><code>function formatCellData(value){
switch(value){
case 1: return "<i class='fa fa-check''></i>";break;
case 0: return "<i class='fa fa-trash''></i>";break;
case -1: return "";break;
default: return "";
}
}
</code></pre>
<p>Now this will make sure you get the HTML part instead of the numbers, </p>
<p>Now we need to make sure the HTML string is read as a regular HTML and icons are displayed and not the HTML string as is, So add this <code>encoded: false</code> attribute into your column data.</p>
<pre><code>for(var x = 0 ; x < dataList.length; x++){
myColumns.push( { field: "data"+x, title: dataList[x], width: 100, locked: false,encoded: false});
}
</code></pre>
<p>Hope this helps.</p>
|
parsing csv data in javascript not working in chrome <p>I am parsing the csv file in javascript using the below logic. The logic works correctly in firefox browser but on chrome browser, the output is different.</p>
<pre><code> var r = new FileReader();
r.onload = function (e) {
contents = e.target.result;
$scope.$apply(function () {
$scope.fileReader = contents;
contents = contents.replace(/\r\n+/g, ",");
reqObj.names = contents.split(",");
defer.resolve("Succesfully executed");
});
};
r.readAsText(file);
</code></pre>
<p>Output in Firefox :
names: ["pradeep", "naveen", "kiran"]
Output in Chrome :
names: ["pradeep\nnaveen\nkiran"]</p>
<p>Please let me know where I am going wrong.</p>
| <p>The <code>.replace(/\r\n+/g, ",")</code> part of code replaces multiple occurrences of a CR followed with one or more LF symbols with a comma. E.g., it will replace with a comma <code>"\r\n\n\n\n\n\n"</code> or <code>"\r\n"</code>, but will never find <code>"\n\n\n\n"</code>.</p>
<p>Since linebreaks can be defined as CRLF, CR, LF, you may change that part to</p>
<pre><code>.replace(/(?:\r?\n|\r)+/g, ",")
</code></pre>
<p>to replace CRLF/LF/CR type of linebreaks.</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 s = "pradeep\r\nnaveen\nkiran\rhere";
console.log(s.replace(/(?:\r?\n|\r)+/g, ","));</code></pre>
</div>
</div>
</p>
|
java.lang.NoClassDefFoundError: org/apache/commons/lang/text/StrLookup Exception While Running Spring Boot Application <p>This is my POM.XML</p>
<pre><code><parent>
<groupId>com.vonage.gunify</groupId>
<artifactId>gunify-ext-services-parent</artifactId>
<version>2016.7.0-RELEASE</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gunify-ext-services</artifactId>
<name>gunify-ext-services</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.jodatime</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
</plugins>
</build>
</code></pre>
<p></p>
<p>And my parent pom.xml</p>
<pre><code><parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<tomcat.version>8.0.3</tomcat.version>
</properties>
<modules>
<module>gunify-ext-services</module>
<module>dist</module>
</modules>
<pluginRepositories>
<pluginRepository>
<id>VSLPluginRepo</id>
<name>Vonage Service Layer Repository</name>
<url>http://maven.dev.s.vonagenetworks.net:8080/nexus-webapp/content/repositories/VSL/</url>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<releases>
<enabled>true</enabled>
<!-- <updatePolicy>always</updatePolicy> -->
</releases>
<id>VSL</id>
<name>Vonage Service Layer Repository</name>
<url>http://maven.dev.s.vonagenetworks.net:8080/nexus-webapp/content/repositories/VSL/</url>
<!-- <url>http://devserver-308.dev.s.vonagenetworks.net:7001/nexus-webapp/content/repositories/VSL/</url> -->
</repository>
<repository>
<releases>
<enabled>true</enabled>
</releases>
<id>VONAGE-M2</id>
<name>Vonage M2 Repository</name>
<url>http://maven.dev.s.vonagenetworks.net:8080/nexus/content/repositories/Vonage-m2/</url>
</repository>
<repository>
<id>com.springsource.repository.bundles.release</id>
<name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
<url>http://repository.springsource.com/maven/bundles/release</url>
</repository>
<repository>
<id>com.springsource.repository.bundles.external</id>
<name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
<url>http://repository.springsource.com/maven/bundles/external</url>
</repository>
<repository>
<id>org.springframework.data</id>
<name>Spring Data module for JPA repositories</name>
<url>https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa</url>
</repository>
<repository>
<id>JBossRepo</id>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
<repository>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>vonage.maven1</id>
<name>Vonage Maven1 Shadow Repository</name>
<url>http://maven.dev.s.vonagenetworks.net:8080/nexus-webapp/content/shadows/Vonage-m1-m2/</url>
</repository>
<repository>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
<id>VONAGE-SNAPSHOTS</id>
<name>Vonage Service Layer Repository</name>
<url>
http://maven.dev.s.vonagenetworks.net:8080/nexus-webapp/content/repositories/VONAGE-SNAPSHOTS/
</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>VSL</id>
<url>http://maven.dev.s.vonagenetworks.net:8080/nexus-webapp/content/repositories/VSL/</url>
</repository>
</distributionManagement>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Hopper-SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</code></pre>
<p></p>
<p>And I am also Installed STS in Eclipse .</p>
<p>But i got error while running spring spoot application.</p>
<blockquote>
<p>>
2016-10-12 11:03:08,432 ERROR [org.springframework.boot.SpringApplication] Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'routingFilter' defined in file [C:\Users\apptivo\Music\Gunify\Gunify-git\gunify-ext-services\gunify-ext-services\target\classes\com\vonage\gunify\extservices\filter\RoutingFilter.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.vonage.gunify.extservices.filter.RoutingFilter]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/lang/text/StrLookup
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1105) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1050) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:760) ~[spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:360) [spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:306) [spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185) [spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174) [spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at com.vonage.gunify.extservices.ExtensionServices.main(ExtensionServices.java:17) [classes/:?]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.vonage.gunify.extservices.filter.RoutingFilter]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/lang/text/StrLookup
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1098) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
... 17 more
Caused by: java.lang.NoClassDefFoundError: org/apache/commons/lang/text/StrLookup
at com.netflix.config.ConfigurationManager.createDefaultConfigInstance(ConfigurationManager.java:138) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.ConfigurationManager.getConfigInstance(ConfigurationManager.java:161) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.ConfigurationManager.getConfigInstance(ConfigurationManager.java:176) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.ConfigurationBasedDeploymentContext.(ConfigurationBasedDeploymentContext.java:108) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.ConfigurationManager.(ConfigurationManager.java:104) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.DynamicPropertyFactory.getInstance(DynamicPropertyFactory.java:277) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.zuul.ZuulFilter.(ZuulFilter.java:54) ~[zuul-core-1.1.0.jar:1.1.0]
at com.vonage.gunify.extservices.filter.AbstractZuulFilter.(AbstractZuulFilter.java:11) ~[classes/:?]
at com.vonage.gunify.extservices.filter.RoutingFilter.(RoutingFilter.java:6) ~[classes/:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_102]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_102]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_102]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_102]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1098) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
... 17 more
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.text.StrLookup
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[?:1.8.0_102]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[?:1.8.0_102]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[?:1.8.0_102]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[?:1.8.0_102]
at com.netflix.config.ConfigurationManager.createDefaultConfigInstance(ConfigurationManager.java:138) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.ConfigurationManager.getConfigInstance(ConfigurationManager.java:161) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.ConfigurationManager.getConfigInstance(ConfigurationManager.java:176) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.ConfigurationBasedDeploymentContext.(ConfigurationBasedDeploymentContext.java:108) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.ConfigurationManager.(ConfigurationManager.java:104) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.config.DynamicPropertyFactory.getInstance(DynamicPropertyFactory.java:277) ~[archaius-core-0.7.4.jar:0.7.4]
at com.netflix.zuul.ZuulFilter.(ZuulFilter.java:54) ~[zuul-core-1.1.0.jar:1.1.0]
at com.vonage.gunify.extservices.filter.AbstractZuulFilter.(AbstractZuulFilter.java:11) ~[classes/:?]
at com.vonage.gunify.extservices.filter.RoutingFilter.(RoutingFilter.java:6) ~[classes/:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_102]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_102]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_102]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_102]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1098) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
... 17 more</p>
</blockquote>
| <p>As the error message says : <code>java.lang.NoClassDefFoundError: org/apache/commons/lang/text/StrLookup</code></p>
<p>That means, that apache commons-lang is missing in your dependencies:</p>
<p>So you have to add the following to your pom:</p>
<pre><code><!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
</code></pre>
<p>In addition is to say, you are using commons-lang3 but that has an other package Name <code>org/apache/commons/lang3</code>...</p>
|
Python: display subarray divisible by k , how do I solve with hashtable? <p>I am looking for <strong>Python</strong> solution</p>
<p>For example, For A=[2, -3, 5, 4, 3, -1, 7]. The for k = 3 there is a subarray for example {-3, 5, 4}. For, k=5 there is subarray {-3, 5, 4, 3, -1, 7} etc.</p>
| <p>This is the solution. You can try to figure it out yourself.</p>
<pre><code>def solve(a, k):
tbl = {0 : -1}
sum = 0
n = len(a)
for i in xrange(n):
sum = (sum + a[i]) % k
if sum in tbl:
key = tbl[sum]
result = a[key+1: i+1]
return result
tbl[sum] = i
return []
</code></pre>
|
SWIFT - Cannot assign value of type '[(String, [String : Any])]' to type '[String : [String : Any]]' <p>How do I get rid of the "()" on the first value so I can assign to the next variable?</p>
<p>This is how I initialize my dictionary:</p>
<pre><code>var imagedata: [String: [String: Any]] = [:]
</code></pre>
<p>I load data into the dictionary and then I sort it</p>
<pre><code>imagedata = Array(imagedata).sort({ $0.0 < $1.0 })
</code></pre>
<p>but it gives me a value of type '[(String, [String : Any])]' instead of '[String : [String : Any]]' so it can't be assigned.</p>
| <p><code>var imagedata: [String: [String: Any]] = [:]</code> //imagedata is an dictionary.</p>
<p><code>imagedata = Array(imagedata).sort({ $0.0 < $1.0 })</code> Here you have added imagedata to Array and sorted. Because we can't sort dictionary.</p>
<p>The result of <code>sort({ $0.0 < $1.0 })</code> will be array with original array object types. So it returns <code>[(String, [String : Any])]</code>. So we can't assign to imagedata variable.</p>
<p>Actually <code>Array(imagedata).sort({ $0.0 < $1.0 })</code> does nothing. Because array has only one object. So it returns same thing.</p>
|
Why does python not have a awgn function like Matlab does? <p>I want to add noise to my synthetic data set in python. I am used to MATLAB but I noticed that python (nor numpy) the option of using <code>awgn</code> (which to my understanding can automatically determine the signal to noise ratio when adding Gaussian Noise, I guess this how it makes sure it doesn't destroy the signal by adding noise with too high variance by accident... not sure if there are other advantages of using it...). </p>
<p>I was wondering why is there no <code>awgn</code> function to add noise in python as there is MATLAB? Is there a profound reason or developer just don't think its not necessary for some reason? If that is the case, what is the reason?</p>
| <p>As per your link, <code>awgn</code> is part of the MATLAB Communications toolbox, <a href="https://www.mathworks.com/help/comm/ref/awgn.html" rel="nofollow">https://www.mathworks.com/help/comm/ref/awgn.html</a>. It isn't part of the basic MATLAB package.</p>
<p>Similarly, in Python you'll have to go looking at some third party package, something involving signals, communications. <code>numpy</code> is the package that implements MATLAB like arrays, and many specialized tasks are implemented in <code>scipy</code>, or even in an addon <code>scikit</code>.</p>
<p>So the proper question isn't <code>why does not Python have it?</code>, but rather, <code>is there some Python package that implements it?</code></p>
<p>And as Mahdi commented, there is a function of that name in <a href="https://github.com/veeresht/CommPy/blob/master/commpy/channels.py" rel="nofollow">https://github.com/veeresht/CommPy/blob/master/commpy/channels.py</a></p>
<p>It doesn't look very complicated, so others might have implemented it as well.</p>
<p>As this link shows, <a href="http://stackoverflow.com/questions/14058340/adding-noise-to-a-signal-in-python">adding noise to a signal in python</a>, <code>numpy</code> has a <code>np.random.normal</code>, which will do most of the work.</p>
<p>Python / Numpy / Scipy is not supported by an international company. Functionality like this gets added by individuals working on their own projects. I wouldn't be surprised if the MATLAB Communications package has its origin in some third-party project many years ago. </p>
<p>The <code>scipy.signal</code> docs has an example of adding normal noise to test case</p>
<p><a href="http://docs.scipy.org/doc/scipy/reference/tutorial/signal.html#periodogram-measurements" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/tutorial/signal.html#periodogram-measurements</a></p>
<pre><code>fs = 10e3
N = 1e5
amp = 2*np.sqrt(2)
freq = 1270.0
noise_power = 0.001 * fs / 2 time = np.arange(N) / fs
x = amp*np.sin(2*np.pi*freq*time)
x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
</code></pre>
|
Show Location string using latitude and longitude <p>I am using this method to show the string of location using current location latitude and longitude but it is showing differently </p>
<pre><code>NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",location.coordinate.latitude, location.coordinate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSData *data = [locationString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *dic = [[json objectForKey:@"results"] objectAtIndex:0];
NSArray* arr = [dic objectForKey:@"address_components"];
//Iterate each result of address components - find locality and country
NSString *cityName;
NSString *countryName;
for (NSDictionary* d in arr)
{
NSArray* typesArr = [d objectForKey:@"types"];
NSString* firstType = [typesArr objectAtIndex:0];
if([firstType isEqualToString:@"locality"])
cityName = [d objectForKey:@"long_name"];
if([firstType isEqualToString:@"country"])
countryName = [d objectForKey:@"long_name"];
}
NSString* locationFinal = [NSString stringWithFormat:@"%@,%@",cityName,countryName];
NSLog(@"Final Location %@ ",locationFinal);
</code></pre>
<p>but final location is showing this type :-</p>
<pre><code>Final Location à ¤¨à ¤ à ¤¦à ¤¿à ¤²à ¥à ¤²à ¥,India
</code></pre>
<p>Why it is showing this type? Can anyone know about this.</p>
| <p>Please supply the language with the API params. If language is not supplied, the geocoder attempts to use the preferred language as specified in the Accept-Language header, or the native language of the domain from which the request is sent.</p>
<p>So please replace the code as with the language parameter as like this.</p>
<pre><code>NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false&language=en",location.coordinate.latitude, location.coordinate.longitude];
</code></pre>
<p>and try again.</p>
|
Is there a better way to cast a variable to 'const' after assignments? <p>I always use <code>const</code> to guard values that should not be assigned. Anyway, there are some cases that I may need to initialize a variable and then use it as a <code>const</code> value, in the same function. For example:</p>
<pre><code>void foo() {
int flags;
/* ... */
if (condition1)
flags |= 1;
/* .... */
if (conditionX)
flags |= Y;
/* .... */
// start using flags as a const value
const flags; // <<= I want something like this.
const int c_flags = flags; // <<= What I have to do. The naming is annoying.
/* ... */
}
</code></pre>
<p>Is there any way to improve this? Could be coding styles or advanced language features.</p>
<hr>
<p>From @Potatoswatter: for C in gcc/clang (gnu style, say, -std=gnu11), Statement Expression can be used.</p>
<pre><code>foo() {
const int flags = ({
int f = 0;
if (X) f |= Y;
/* ... update f ... */
f;
});
/* use the `const` flags */
}
</code></pre>
| <p>Consider making a function that returns the value you want</p>
<pre><code>const int flags = getFlags();
</code></pre>
<p>Or more object oriented make a flags class that does that in the constructor.</p>
<pre><code>const Flags flags(condition1, ...);
</code></pre>
|
NetBeans IDE and project setup <p>I set-up three projects in NetBeans IDE, two are html projects and another one is php project. </p>
<p>When I test run, the project php's index.php (Main home page) is wanted to be loaded first. Then it will load another index.html files (two sub pages). </p>
<p>But now when I run, the first html project's index.html is always loaded first since it is at the first position at IDE because of alphabetical order in project name. </p>
<p>How can I load php project's index.php file? </p>
| <p>Whenever you create project on NetBeans, you can specify the URL of project in the "Project URL" field.
Please see the below screenshots that will help you.</p>
<p><a href="https://i.stack.imgur.com/eSvim.png" rel="nofollow">Screenshot : Here you can see "Project URL" field, with the help of this you can specify you project's index.php file</a></p>
|
Getting coordinates upon checking a checkbox <p>so I'm doing this school thingy and I'm trying to get the x and y coordinates of looped checkboxes when they are checked and display the X and Y coordinates in their respective input box, and I need help because at this point I don't really know what I'm doing.</p>
<p><strong>html.twig.</strong></p>
<pre><code>{% set cells = 10 %}
<div class="large-12">
<div class="large-6 columns">
<h6>Your Board</h6>
<table id="yours" class="ocean">
{% for i in 1..cells %}
<tr class="rowDiv">
{% for j in 1..cells %}
<td id="{{i}}col_{{j}}" rel="{{j}}" class="cell colDiv
{% for placement in yourships %}
{% for cell in placement %}
{% if cell.x_pos == i and cell.y_pos == j %}
{% if cell.hit == "hit" %}
hit
{% else %}
{{cell.class}}
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
">
<input class="pos-input" name="position" type="checkbox" value="{{j}}"/>
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<div class="large-12">
<div class="large-3 columns">
Y:<input type="text"/>
</div>
<div class="large-3 columns">
x:<input type="text"/>
</div>
<div class="large-3 columns">
<select>
<option>select</option>
<option>hit</option>
<option>miss</option>
</select>
</div>
<div class="large-3 columns">
<button>Initiate</button>
</div>
</div>
</div>
<script>
$('.chooser').click(function(){
$(this).removeClass('invisible');
var innerCheck = $(this).find('input[type=checkbox]')
innerCheck.prop('checked', true);
});
</script>
</code></pre>
| <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
$('.pos-input').on('click', function() {
if ($(this).is(':checked')) alert( $(this).data('x')+':'+ $(this).data('y') );
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
{% set cells = 10 %}
....
{% for i in 1..cells %}
<tr id="{{i}}" class="rowDiv">
{% for j in 1..cells %}
<td id="{{i}}col_{{j}}" rel="{{j}}" class="cell colDiv chooser invisible
{% for placement in yourships %}
{% for cell in placement %}
{% if cell.x_pos == i and cell.y_pos == j %}
hit
{% else %}
no-ship
{% endif %}
{% endfor %}
{% endfor %}
">
<input class="pos-input" name="position" type="checkbox" data-x="{{ j }}" data-y="{{ i }}" />
</td>
{% endfor %}
</tr>
{% endfor %}</code></pre>
</div>
</div>
</p>
|
Multiple COUNT and GROUP BY in a single Statement <p>I am using DISTINCT, LEFT JOIN, COUNT and GROUP BY in single statement, like this:</p>
<pre><code>SELECT distinct r.sid as sid, s.name as sname, s.image as simage,
COUNT(r.sid) as scount FROM batch_request r LEFT JOIN student_info s ON s.id = r.sid
WHERE r.tid='22' group by r.sid
</code></pre>
<p>Encoded JSON Looks like this:</p>
<pre><code>{ "students":
[
{
"sid":"1",
"sname":"Sonali Kohli",
"simage":"22",
"scount":"3",
"sconfirmed":null,
"sdeclined":null
},
{
"sid":"2",
"sname":"Sona Ali Khan",
"simage":"22",
"scount":"3",
"sconfirmed":null,
"sdeclined":null
}
],"success":1
}
</code></pre>
<p>Table:</p>
<p><a href="https://i.stack.imgur.com/23CIF.png" rel="nofollow"><img src="https://i.stack.imgur.com/23CIF.png" alt="enter image description here"></a></p>
<p>As you can see in above image, I have total 6 records in a table (3 for sid = 1 and 3 for sid = 2)</p>
<p>Status for sid 1 records (2 Confirmed [where value is 1] and 1 Declined [where value is 2]), in a same way Status for sid 2 records (1 Confirmed [where value is 1] and 2 Declined [where value is 2])</p>
<p>Same thing I want to get through my QUERY which I have posted above to encode data into JSON, as you can see, still I am getting null for both the JSON objects (i.e: Confirmed and Declined)</p>
<p><strong>QUESTION 1:</strong> What should be the <strong>values</strong> of <code>sconfirmed</code> and <code>sdeclined</code> for <em>both the objects</em> of <strong>JSON</strong> ?</p>
<p><strong>ANSWER 1:</strong> In case of <code>sid = 1</code> (<em>sconfirmed</em> = 2 and <em>sdeclined</em> = 1) and for <code>sid = 2</code> (<em>sconfirmed</em> = 1 and <em>sdeclined</em> = 2)</p>
<p><strong>QUESTION 2:</strong> What is <code>sconfirmed</code> and <code>sdeclined</code> in a database table ?</p>
<p><strong>ANSWER 2:</strong> <code>sconfirmed</code> is just the <strong>count</strong> of records where <em>status</em> is <code>1</code> for a particular <strong>sid</strong> and <code>sdeclined</code> is the <strong>count</strong> of records where <em>status</em> is <code>2</code> for a particular <strong>sid</strong></p>
| <p>Try something like this:</p>
<pre><code>SELECT distinct r.sid as sid, s.name as sname, s.image as simage, COUNT(r.sid) as scount,
SUM(CASE r.status WHEN 1 THEN 1 ELSE 0 END) as sconfirmed,
SUM(CASE r.status WHEN 2 THEN 1 ELSE 0 END) as sdeclined,
SUM(CASE r.status WHEN 0 THEN 1 ELSE 0 END) as spending
FROM batch_request r LEFT JOIN student_info s ON s.id = r.sid
WHERE r.tid='22'
GROUP BY r.sid
</code></pre>
|
How to create bootstrap labels like this? <p><a href="https://i.stack.imgur.com/A0nUt.png" rel="nofollow"><img src="https://i.stack.imgur.com/A0nUt.png" alt="enter image description here"></a></p>
<p>I wanted to create input like this. When you click the label, a violet line appears. When you click on the success input, green line appears below the label. When you click on the error line input, red line appears below the input. </p>
<p>i want to create using html and css</p>
| <p>This should be a bare minumum implementation.</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>input[type="text"] {
outline: none;
background: transparent;
border: none;
border-bottom: 1px solid gray;
margin: 5px 15px;
line-height: 1.4em;
}
.has-success input:focus, .has-success input:active {
border-bottom: 1px solid green;
color: green;
}
.has-error input:focus, .has-error input:active {
border-bottom: 1px solid red;
color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="has-success">
<input type="text" value="success">
</div>
<div class="has-error">
<input type="text" value="error">
</div></code></pre>
</div>
</div>
</p>
|
Why is a parameter parsed as a bool? <p>I usually use <a href="https://github.com/docopt/docopt" rel="nofollow"><code>docopt</code></a> to handle the command line parameters but I now have a case where the parameters is parsed unexpectedly (it must be a silly mistake of mine as it always works great)</p>
<pre><code>"""
API to do something
Usage:
api.py [options]
Options:
--port PORT port to listen on [default: 64645]
--url URL elasticsearch address [default: http://elk.example.com:9200]
"""
</code></pre>
<p>This is parsed via a <code>conf = docopt.docopt(__doc__)</code> call after which I have <code>conf</code> set to </p>
<pre><code>{
'--port': '64645',
'--url': False
}
</code></pre>
<p>The <code>--url</code> part is not correct but I cannot understand why.</p>
| <p>It is because there are too many spaces between <code>--url</code> and <code>URL</code>, try:</p>
<pre><code>"""
API to do something
Usage:
api.py [options]
Options:
--port PORT port to listen on [default: 64645]
--url URL elasticsearch address [default: http://elk.example.com:9200]
"""
</code></pre>
|
How to set the LED to turn off from the start (Arduino) <p>so am... I 'am new to Arduino and I'm currently trying to make this work.. but I'm already doing this for an hour with luck not in my side...
Here is the summary of what I'm doing: I have a Gizduino + 644 (a copy of Arduino with ATmega 644 here in Phil.), a IR Proximity Sensor (3 PIN - VCC, GRND, OUT), 2 LED's (Red and Yellow) and 2 100ohms Resistor. </p>
<p>So far, this is what I can do:</p>
<ul>
<li>In Arduino IDE, I have a case in which if I type 'QRIN' - the Proximity and the Red LED will turn on... if the proximity sense something within its range.. the Yellow LED will turn ON. If I type 'QROUT' - the Proximity will immediately turn off and the Red LED will turn on for 10 seconds and will turn off..</li>
</ul>
<p>And this is the problem:</p>
<ul>
<li>The Yellow LED always turns ON if it's the first run(I mean I just click the upload button in IDE).... and that's a very big problem... it will only turn off if I type the cases: 'QRIN' and 'QROUT'..</li>
</ul>
<p>In my code, the names are the following: </p>
<ul>
<li>Red LED - LOCK </li>
<li>Yellow LED - PROX_SENSOR_LED </li>
<li>Proximity - PROX</li>
</ul>
<p>This is my code in IDE:</p>
<pre><code>int LOCK = 13; //RED LED, in pin 13
int PROX = 12; //PROXIMITY, in pin 12
int ANALOG = 0; //OUT of Proximity, in Analog 0
int PROX_SENSOR_LED = 7; //Yellow LED, in pin 7
int val = 0; //value to store
void setup()
{
Serial.begin(9600);
pinMode(LOCK, OUTPUT); //set the pin # as output (VCC of the hardware)
pinMode(PROX, OUTPUT); //set the pin # as output (VCC of the hardware)
pinMode(PROX_SENSOR_LED, OUTPUT); //set the pin # as output (VCC of the hardware)
}
void loop()
{
digitalWrite(PROX_SENSOR_LED, LOW); //sets the output pin initially to LOW (but doesnt work.. T_T)
val = analogRead(ANALOG); //read the input pin 0 to 1023
if (val > 800) //if the sensor value is higher threshold set OUTPUT HIGH
{
digitalWrite(PROX_SENSOR_LED, HIGH); //sets output pin HIGH
delay(100); //waits for .1 second
}
char data = Serial.read(); //read 9600
switch (data) //start of case... like 'ON' 'OFF'
{
case 'QRIN': //this is my 'ON'
digitalWrite(PROX, HIGH); //turn the proximity to ON
digitalWrite(LOCK, HIGH); //turn the lock to ON
break;
case 'QROUT': //this is my off 'OFF'
digitalWrite(PROX, LOW); //turn the proximity to OFF
digitalWrite(LOCK, HIGH); //turn the lock to ON
delay(10000); //for 10 seconds
digitalWrite(LOCK, LOW); //then off
if (ANALOG = HIGH) // I need this 'if' condition because if
{ //this is not here... the Yellow LED is turn ON...
digitalWrite(PROX_SENSOR_LED, LOW); //I don't know why.. T_T
}
break;
}
}
</code></pre>
| <p>Put the line at the end of the setup():</p>
<pre><code>digitalWrite(PROX_SENSOR_LED, LOW);
</code></pre>
<p>Also <code>if (ANALOG = HIGH)</code> is a wrong statement and you assign HIGH to your ANALOG. Change it as <code>if (ANALOG == HIGH)</code>.</p>
|
Toggle ViewController Views <p>I am learning iOS with few sample projects. I have two view controllers in that first VC has few buttons and a mapview and the second VC has tableview showing a set of results. I have embed the both viewcontrollers in navigationViewController.By clicking a button from First VC i am able to show the tableview (using show segue) and able to go back to first VC through navigation. Now my query is I want to display the tableview (second VC) in place of one view object (map view) defined in firstVC rather than padding the tableview entirely in full screen. My problem is when showing another Viewcontroller i still want to see the few viewobjects from firstVC so I am trying to display the secondVC on top of mapview when i click on a button which triggers the segue.I have to use the single interface, so I need to load the tablview results from SecondVC into firstVC by replacing mapView's view with tableview.Please let me know your ideas if it is possible and any other ideas to achieve the same are most welcomed.</p>
| <p>Sreekanth Gundlapalli,</p>
<p>All you need to do is to add the TableView controller's view as subview to your view Controller. In order to simplify the process I personally prefer using the ContainerView,</p>
<p>Step 1 : Add a ContainerView to your View Controller and add the auto layout constraints to it, because your tableView will be loaded inside this container view you donate have to apply any auto layout constraint to your tableView to keep it in place :)</p>
<p>ex :
<a href="https://i.stack.imgur.com/t2v4n.png" rel="nofollow"><img src="https://i.stack.imgur.com/t2v4n.png" alt="enter image description here"></a></p>
<p>Step 2 : Drag an IBOutlet to the container view.lets call it as containerView :)</p>
<p>Step 3 : Now its up to you to have two view controller 1 for loading map and 1 for loading tableView, or you will have map view as your view controller subview and you will either hide it or remove it and add container view but I personally prefer having code clean n neat so I prefer having two different VCs</p>
<p>so lets create 2 VCs lets call them as viewController1 & viewController2 Savy ??</p>
<p>Step 4 :
lets write a method which actually loads VC and adds its view as subview to your ViewController</p>
<pre><code>func changeEmbededVC(for status : Int) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if status == 0 {
mehereButton.tag = 1
let vc = storyboard.instantiateViewController(withIdentifier: "viewController1")
vc.willMove(toParentViewController: self)
containerView.addSubview(vc.view)
self.addChildViewController(vc)
vc.didMove(toParentViewController: self)
}
else {
mehereButton.tag = 0
let vc = storyboard.instantiateViewController(withIdentifier: "viewController2")
vc.willMove(toParentViewController: self)
containerView.addSubview(vc.view)
self.addChildViewController(vc)
vc.didMove(toParentViewController: self)
}
}
</code></pre>
<p>I believe code is pretty self explanatory :D now what is <code>mehereButton.tag = 1</code> ?? Simple you want to toggle view on button press don't you :D hence I have created a IBOutlet for mehereButton and changing its tag :)</p>
<p>now finally in IBAction of mehereButton</p>
<pre><code>@IBAction func buttonTapped(_ sender: UIButton) {
self.changeEmbededVC(for: self.mehereButton.tag)
}
</code></pre>
<p>but we need to load one of the view by default isn't it :D
so change your viewDidAppear to</p>
<pre><code>override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.changeEmbededVC(for: 0)
}
</code></pre>
<p>Hope I answered your question In detail :P I know you can't neither up vote or accept answer as you don't have enough reputation :) but hope it will help somebody in future as well :)</p>
|
How do I use local state along with redux store state in the same react component? <p>I have a table that displays contacts and I want to sort the contacts by first name. The contacts array comes from the redux store, which will come then come through the props, but I want the local state to hold how those contacts are sorted, since it's local UI state. How do I achieve this? I so far have placed contacts into <code>componentWillReceiveProps</code> but for some reason it doesn't receive the props when it changes. How do I update the local state each time the redux store state changes?</p>
<pre><code>const Table = React.createClass({
getInitialState () {
return {contacts: []}
},
componentWillReceiveProps () {
this.setState({ contacts: this.props.data.contacts})
},
sortContacts (parameter, e){
...
},
render () {
return (
<table>
<thead>
<tr>
<th onClick={this.sortContacts.bind(this, "firstName")}>First Name</th>
</tr>
</thead>
<tbody>
{contactRows}
</tbody>
</table>
)
}
})
</code></pre>
<p><strong>update of current code that includes filtering</strong></p>
<pre><code>import React, {Component} from 'react'
import TableRow from './TableRow'
class Table extends Component {
constructor (props) {
super(props)
this.state = { sortBy: "fistName" }
}
sortContacts (parameter) {
console.log('in sortContacts')
this.setState({ sortBy: parameter })
}
sortedContacts () {
console.log('in sortedContacts')
const param = this.state.sortBy
return (
this.props.data.contacts.sort(function (a, b){
if (!a.hasOwnProperty(param)){
a[param] = " ";
}
if (!b.hasOwnProperty(param)){
b[param] = " ";
}
const nameA = a[param].toLowerCase(), nameB = b[param].toLowerCase();
if (nameA > nameB) {
return 1;
} else {
return -1;
}
})
)
}
filteredSortedContacts () {
console.log('in filteredSortedContacts')
const filterText = this.props.data.filterText.toLowerCase()
let filteredContacts = this.sortedContacts()
if (filterText.length > 0) {
filteredContacts = filteredContacts.filter(function (contact){
return (
contact.hasOwnProperty('lastName') &&
contact.lastName.toLowerCase().includes(filterText)
)
})
}
return filteredContacts
}
contactRows () {
console.log('in contactRows')
return this.filteredSortedContacts().map((contact, idx) =>
<TableRow contact={contact} key={idx}/>
)
}
render () {
return (
<div className="table-container">
<table className="table table-bordered">
<thead>
<tr>
<th className="th-cell" onClick={this.sortContacts.bind(this, "firstName")}>First Name</th>
<th onClick={this.sortContacts.bind(this, "lastName")}>Last Name</th>
<th>Date of Birth</th>
<th>Phone</th>
<th>Email</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
{this.contactRows()}
</tbody>
</table>
</div>
)
}
}
export default Table
</code></pre>
<p>The issue I'm seeing now is that <code>contactRows, filteredSortedContacts, sortedContacts</code> are being called multiple times, once for each TableRow. I don't see how this can be happening if I'm only calling <code>contactRows</code> once in the body.</p>
| <p>The <code>componentWillReceiveProps()</code> method is not called for the initial render. What could do, if you only intend to use the data from props as the initial data, is something like:</p>
<pre><code>getInitialState () {
return {
contacts: this.props.data.contacts
}
}
</code></pre>
<p>In the <a href="https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html" rel="nofollow">React docs</a> they suggest you name the props initialContacts, just to make it really clear that the props' only purpose is to initialize something internally.</p>
<p>Now if you want it to update when <code>this.props.contacts</code> change, you could use <code>componentWillReceiveProps()</code> like you did. But I'm not sure it's the best idea. From the docs:</p>
<blockquote>
<p>Using props to generate state in getInitialState often leads to
duplication of "source of truth", i.e. where the real data is. This is
because getInitialState is only invoked when the component is first
created.</p>
<p>Whenever possible, compute values on-the-fly to ensure that they don't
get out of sync later on and cause maintenance trouble.</p>
</blockquote>
|
Checking if an ArrayList contains a certain String while being case insensitive <p>How can i search through an ArrayList using the .contains method while being case insensitive? I've tried .containsIgnoreCase but found out that the IgnoreCase method only works for Strings.</p>
<p>Here's the method I'm trying to create: </p>
<pre><code> private ArrayList<String> Ord = new ArrayList<String>();
public void leggTilOrd(String ord){
if (!Ord.contains(ord)){
Ord.add(ord);
}
}
</code></pre>
| <p>The <code>List#Ccontains()</code> method check if the parameter is present in the list but no changes are made in the list elements </p>
<p>use streams instead</p>
<pre><code>public void leggTilOrd(String ordParameter) {
final List<String> ord = Arrays.asList(new String[]{ "a", "A", "b" });
final boolean ordExists = ord.stream().anyMatch(t -> t.equalsIgnoreCase(ordParameter));
System.out.println(ordExists);
}
</code></pre>
|
how to upload a file to asp.net core backend with http <p>Now I use Asp.net core as the server framework. I want to know how to upload a file to an Asp.net core server? I use web api but not the web application. So form submit is no use. The code below doesn't work.</p>
<pre><code>[HttpPost("uploadImage/{accountGuid}")]
public async Task<string> UploadTargetImage(ICollection<IFormFile> files,Guid accountGuid)
{
if (files == null) throw new Exception("File is null");
if (files.Count == 0) throw new Exception("File is empty");
}
</code></pre>
<p>I use fiddler to test the API. Like below:
<a href="https://i.stack.imgur.com/XQ8cU.png" rel="nofollow">see the fiddler post image</a></p>
<p>The result of api is File is empty.So the server didn't get the post file.
What should I do? It puzzles me for a long time.</p>
| <p>I hava just fix it! The input name in POST must be the same as method param in ASP.NET.</p>
|
Countdown timer not run when user close application <p>I had created countdown timer to display timeout it works well when user minimize application but it stops when user close application. i had added code below kindly help me it's an emergency. </p>
<p>this is MainActivity.java</p>
<pre><code>public static final String TAG = "Demo";
TextView t1 ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView)findViewById(R.id.t1);
startService(new Intent(this, count_servie.class));
}
private BroadcastReceiver br = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
updateGUI(intent);
}
};
public void onResume() {
super.onResume();
registerReceiver(br, new IntentFilter(count_servie.COUNTDOWN_BR));
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
t1.setText("Countdown seconds remaining: " + millisUntilFinished / 1000);
}
}
</code></pre>
<p>this is my count_servie.java</p>
<pre><code>public class count_servie extends Service {
public static final String COUNTDOWN_BR = "com.demo.DSemo.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
public void onCreate() {
super.onCreate();
cdt = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
public void onFinish() {
}
};
cdt.start();
}
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent arg0) {
return null;
}
</code></pre>
<p>Thanks in advance.</p>
| <p>You need to return <code>START_STCKY</code> in your <code>onStartCommand()</code> method for the service to run even when app is closed.</p>
<pre><code> ....
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STCKY;
}
....
</code></pre>
<p>You can refer <a href="https://developer.android.com/reference/android/app/Service.html" rel="nofollow">this</a>link for correctly implementing a service.</p>
<p>Alternatively, you can refer <a href="http://stackoverflow.com/questions/9093271/start-sticky-and-start-not-sticky">this</a> SO question.</p>
<p><strong>Update</strong>
Use a <code>Foreground Service</code> to avoid your Service being killed. In order to make your service Foreground, replace your <code>onStartCommand</code> code with this</p>
<pre><code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Timer")
.setContentText("Doing some work...")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
cdt = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
public void onFinish() {
stopForeground(true);
}
};
cdt.start();
return START_STICKY;
}
</code></pre>
<p><strong>Udpate 2:</strong> Counter using <code>Service</code> and <code>SharedPreferences</code></p>
<p>Replace your Actvity's code with this:</p>
<pre><code>import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v4.os.ResultReceiver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String SHARED_PREF = "MyPref";
private final static int MAX_COUNTER = 30;
public static final String KEY_COUNTER_SECONDS = "seconds";
public static final String KEY_SAVED_COUNTER = "saved_counter";
public static final String KEY_SAVED_TIME_MILLI = "saved_time_milli";
MyResultReceiver mReceiver;
TextView mTvCounter;
SharedPreferences mSharedPref;
long mMaxCounterValueInSeconds = MAX_COUNTER;
long mCurCounterValue = 0;
boolean mShouldSaveValues;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTvCounter = (TextView) findViewById(R.id.tv_counter);
mReceiver = new MyResultReceiver(null);
mSharedPref = getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
//register listener
MyService.registerReceiver(mReceiver);
//get values from shared pref
long savedCounter = mSharedPref.getLong(KEY_SAVED_COUNTER, -1);
long savedTime = mSharedPref.getLong(KEY_SAVED_TIME_MILLI, -1);
//if -1 counter was running when app was closed, get saved values from shared pref
if (savedTime != -1) {
//elapsedTime is the time spent in seconds while the app was in background
long elapsedTime = (getCurrentTimeInMilli() - savedTime)/1000; //convert to sec
mCurCounterValue = savedCounter + elapsedTime;
if(mCurCounterValue < MAX_COUNTER){
//calculate current counter value from values retrieved from shared pref
mMaxCounterValueInSeconds = MAX_COUNTER - mCurCounterValue;
//start the value with updated max count value
startService(mMaxCounterValueInSeconds);
}else{
mCurCounterValue = MAX_COUNTER;
}
}else{
//if counter was not running, start the service with max count value = MAX_COUNTER
startService(mMaxCounterValueInSeconds);
}
//update text view
mTvCounter.setText("" + mCurCounterValue);
}
private void startService(long maxCounter){
mShouldSaveValues = true;
Intent intent = new Intent(this, MyService.class);
Bundle bundle = new Bundle();
bundle.putLong(KEY_COUNTER_SECONDS, maxCounter);
intent.putExtras(bundle);
startService(intent);
}
@Override
protected void onPause() {
super.onPause();
//stop the service
stopService(new Intent(this, MyService.class));
//unregister listener
MyService.unregisterReceiver();
if(mShouldSaveValues) {//save the values only when counter has started
//save values in the shared preference
SharedPreferences.Editor editor = mSharedPref.edit();
Log.d(TAG, "saving counter: " + Long.parseLong(mTvCounter.getText().toString()));
editor.putLong(KEY_SAVED_COUNTER, Long.parseLong(mTvCounter.getText().toString()));
editor.putLong(KEY_SAVED_TIME_MILLI, getCurrentTimeInMilli());
editor.apply();
}
}
/**
* This method returns current time in milli seconds
*
* @return time in milliseconds
*/
private long getCurrentTimeInMilli() {
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
long timeInMilli = date.getTime();
return timeInMilli;
}
/**
* ResultReceiver is used to get values from MyService.class
* It is registered in onResume() &
* unregistered in onPause()
*/
class MyResultReceiver extends ResultReceiver {
public MyResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
String strMilliFinished = resultData.getString(MyService.KEY_MSG);
updateUI(Long.parseLong(strMilliFinished));
}
private void updateUI(final long milliFinished) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mCurCounterValue++;
mTvCounter.setText("" + mCurCounterValue);
if(milliFinished == 0) {
//resetting counter values
mShouldSaveValues = false;
mMaxCounterValueInSeconds = MAX_COUNTER;
mCurCounterValue = 0;
SharedPreferences.Editor editor = mSharedPref.edit();
editor.putLong(KEY_SAVED_COUNTER, -1);
editor.putLong(KEY_SAVED_TIME_MILLI, -1);
editor.apply();
}
}
});
}
}
}
</code></pre>
<p>Replace your Service code with this:</p>
<pre><code>import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.os.ResultReceiver;
import android.util.Log;
public class MyService extends Service {
public static final String KEY_MSG = "msg";
CountDownTimer cdt = null;
private static ResultReceiver mReceiver;
public MyService() {
}
public static void registerReceiver(ResultReceiver receiver) {
mReceiver = receiver;
}
public static void unregisterReceiver() {
mReceiver = null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
long maxCounterValueInSeconds = bundle.getLong(MainActivity.KEY_COUNTER_SECONDS);
long maxCounter = maxCounterValueInSeconds * 1000;
cdt = new CountDownTimer(maxCounter, 1000) {
public void onTick(long millisUntilFinished) {
sendMessage(1, "" + millisUntilFinished);
}
public void onFinish() {
sendMessage(1, "" + 0);
stopSelf();
}
};
cdt.start();
return START_STICKY;
}
private void sendMessage(int resultCode, String message) {
if (mReceiver != null) {
Bundle bundle = new Bundle();
bundle.putString(KEY_MSG, message);
mReceiver.send(resultCode, bundle);
}
}
@Override
public void onDestroy() {
super.onDestroy();
cdt.cancel();
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
</code></pre>
<p><strong>Note:</strong> I am using <code>ResultReceiver</code> instead of <code>BroadcastReciver</code></p>
|
Querying on DATE field <p>I would like to query the details of reports which will expire between specific dates. The expiration dates are filled in manually.</p>
<p>E.g. give me the reports which will expire between 01-11-2016 and 30-11-2016</p>
<p>I store the expiration dates as strings in the database; however, when I query on them I do not get the correct results.</p>
<p>I am wondering using the DATE type instead of string would give correct results..</p>
| <p>Remember never try to save the date and time in string. It creates problems later. But there is a solution, you can use converting it into date:</p>
<pre><code>SELECT * FROM Table WHERE
CONVERT(DATE, FromDate) >= CONVERT(DATE, '2016-10-01')
AND CONVERT(DATE, ToDate) <= CONVERT(DATE, '2016-10-10')
</code></pre>
|
Can't assign values to a 2d boolean array <p>I'm basically just starting with java and am struggling with a very basic porgram.
I have a 2d boolean array that I want to randomly be filled with...you won't guess it... booleans! This is the method I have right now, but it seems that the array is filled with just 'false' after running it.</p>
<pre><code>public static void randBoard() {
for(boolean[] item : board) {
for(boolean square : item) {
square = Math.random() < .5;
}
}
}
</code></pre>
| <p>As Kevin Esche stated: if you for each loop through the booleans you get value objects, but you want to set it at the reference. This means that the position in the list must be set.</p>
<p>It should work with the following code:</p>
<pre><code>public static void randBoard() {
Random random = new Random();
for(int i =0; i<board.length;i++) {
boolean[] item = board[i];
for(int j= 0;j<item.length;j++) {
item[j]= random.nextBoolean();
}
}
}
</code></pre>
|
Create Folder on onedrive using Oauth Authentication <p>I am trying to create a folder or file on OneDrive with using OAuth authorization flow, request and response details are as below,</p>
<p><strong>Request:</strong>-</p>
<pre><code>POST https://graph.microsoft.com/v1.0/me/drive/root/children?access_token=${access_token}
Content-Type: application/json
{
"name": "Test",
"folder": { }
}
</code></pre>
<p>I have got following <strong>error</strong></p>
<p><strong>Response</strong></p>
<pre><code>{
"error": {
"code": "unauthenticated",
"message": "The caller is not authenticated.",
"innerError": {
"request-id": "44a22daf-7c96-4a27-93d7-77df426c9229",
"date": "2016-10-12T06:32:43"
}
}
}
</code></pre>
<p><strong>For reference:-</strong>
<a href="http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_post_children" rel="nofollow">http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_post_children</a></p>
<p>I have generated refresh token for authentication process,still facing this authenticationerror issue.Could please help to resolve this problem.</p>
| <p>I've never used this API, but don't <a href="http://graph.microsoft.io/en-us/docs/platform/rest" rel="nofollow">the docs that you provided</a> state that the token should be sent in an Authorization HTTP header and not as a query param?</p>
<p>Like that:</p>
<pre><code>POST https://graph.microsoft.com/v1.0/me/drive/root/children
Content-Type: application/json
Authorization: Bearer put_your_token_here
{
"name": "Test",
"folder": { }
}
</code></pre>
|
I want to copy listview item on click to clipboard <p>I want copy text from the list view item to clipboard when the user clicks the item but I am stuck at using clipboard within the onitemclick function. How can I implement the same?</p>
<pre><code>public class SmsActivity extends Activity
implements AdapterView.OnItemClickListener
{
ListView a;
String[] c = { "Anniversary SMS", "Best Luck SMS", "Birthday SMS", "Broken Heart SMS", "Education SMS", "Emotion SMS", "Exam SMS" };
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a = ((ListView)findViewById(R.id.listView));
a.setOnItemClickListener(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.title, c);
a.setAdapter(adapter);
}
public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt, long paramLong)
{
}
}
</code></pre>
| <p>I hope my answer will be help full to you</p>
<pre><code>public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt, long
String s = a.getItemAtPosition(position)
ClipboardManager clipboard = (ClipboardManager)CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label",s);
clipboard.setPrimaryClip(clip);
}
</code></pre>
|
Clickable row only works on the first page in datatable <p>I need help. I have a page that displays records in bootstrap data table. The records are displayed 10 rows per page and each row has a checkbox on the left column. What I want to do is, when user clicks on the row, it will check the checkbox and enable the button placed after the table(user has to select at least a checkbox to activate/enable the button). I already implemented this but unfortunately it only works on the first page. When user go to second page and click on the table row, the checkbox is not checked. Anyone can help me? I appreciate it much.</p>
<pre><code>//disable button when no records are selected
var checkboxes = $("input[type='checkbox']");
var btn = $("#button");
btn.attr("disabled","disabled");
checkboxes.on('click', function(event) {
if($(this).prop('checked')){
btn.removeAttr('disabled');
} else {
btn.attr("disabled",!checkboxes.is(":checked"));
}
});
//this will check the checkbox whenever user clicks the table row
$('.clickable-row').click(function (event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
</code></pre>
| <p>When you use DataTables with jQuery, the plugin manages the rows that appear on the page by adding and removing elements from the DOM when you switch pages. When the table loads, the only rows that exist in the DOM are those appearing on that first page.</p>
<p>This means that your handler is only ever added to the first page's elements and once you switch pages, those elements are removed so when you go back to page 1, those will be newly created elements with no handlers attached. </p>
<p>Change your code to this:</p>
<pre><code>$('#some-table-id').on('click','.clickable-row', function (event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
</code></pre>
<p>This is called <a href="https://learn.jquery.com/events/event-delegation/" rel="nofollow">event delegation</a> </p>
<p>See also <a href="http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements">Event binding on dynamically created elements?</a></p>
|
How to debug iOS app executed in mobile not launched by Xcode with connection USB cable <p>I'm working on Application, where I'm connecting External Device through USB female connector in iPad. Whereas I've connected external device, I can't connect my Data cable with Mac to debug the work. Anyone have idea, how can I debug without USB cable connected through Mac to iPad.<br>
<strong>Anyway to I can check previous logs of Device.</strong></p>
| <p>Previous device logs are visible in devices tab, when selecting device, you'll see the device console.</p>
<p>If that's not enough, I suggest trying a logging framework such as <a href="https://github.com/mattt/Antenna" rel="nofollow">Antenna</a>.</p>
|
Crm 2015 Javascript Context is not defined from fetchxml <p>I want to get values from <code>fetchxml</code> using javascript in html web resource.I use crm 2015. The code block is in the attachment on <a href="https://i.stack.imgur.com/adLH2.jpg" rel="nofollow">picture</a>. </p>
<p>After the fetchxml, I try to get values with soap function.
it gives me the error </p>
<blockquote>
<p>Error: Contex is not available</p>
</blockquote>
<p>I added the <code>xrmservicetoolkit</code> for crm 2015 and jquery and json files. What is the problem? How can I solve this? Can anyone help me please?</p>
<pre><code>var fetch = "<fetch version='1.0' mapping='logical'><entity name='quote'>";
fetch += "<all-attributes />";
fetch += "<filter type='and'>";
fetch += "<condition attribute='new_anabayi' operator='eq' value='" + id + "' />";
fetch += "<condition attribute='statuscode' operator='eq' value='1' />";
fetch += "<condition attribute='customertypecode' operator='eq' value='7' />";
fetch += "</filter></entity></fetch>";
var fetchData = XrmServiceToolkit.Soap.Fetch(fetch);
</code></pre>
| <p>Add a reference to <a href="https://msdn.microsoft.com/en-us/library/gg328541.aspx" rel="nofollow">ClientGlobalContext.js</a> on your web resource. </p>
<pre><code><script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
</code></pre>
<p>I am assuming you already have referenced the following scripts too?</p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript" src="XrmServiceToolkit.js"></script>
</code></pre>
|
PHP tree level nested menu recursive function <p>I'm trying to display a set of data in tree level </p>
<p>For example this is my database record </p>
<p><a href="https://i.stack.imgur.com/3y06h.png" rel="nofollow"><img src="https://i.stack.imgur.com/3y06h.png" alt="enter image description here"></a></p>
<p>I wish to display it like </p>
<p><a href="https://i.stack.imgur.com/7FIel.png" rel="nofollow"><img src="https://i.stack.imgur.com/7FIel.png" alt="enter image description here"></a></p>
<p>and so on.</p>
<p>Of course above picture is manually key in by myself</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> <?php
require 'tree.php';
$tree = array(
'wwq' => array(
'Project4' => array(
'phase1',
),
'Project23' => array(
'phase23',
),
'Test1' => array(
'test1',
),
'Projecttest' => array(
'phasetest',
'testtest',
)
),
);
echo treeOut($tree);
?></code></pre>
</div>
</div>
</p>
<p>and my function is </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><?php
function treeOut($row_Recordset1){
$markup = '';
foreach ($row_Recordset1 as $branch => $twig){
$markup .= '<li>' . ((is_array($twig)) ? $branch . treeOut($twig) : $twig). '</li>';
}
return '<ul>' . $markup . '</ul>';
}
?></code></pre>
</div>
</div>
</p>
<p>So, my question is how I can make the array to for loop instead of I key in every data. </p>
<p>Thankss if anyone could help me!! If any question can ask me below comment. </p>
| <p>If it is about how you can prepare array in required format before passing it to <code>treeOut()</code> function then try adding these line before calling <code>treeOut()</code>:</p>
<pre><code>$tree = array();
$sql = "SELECT * FROM tbl_name ORDER BY companyName ASC, projectName ASC, phaseName ASC";
$result = mysql_query($connection, $sql);
while($data = mysql_fetch_array($result)){
$tree[ $data['companyName'] ][ $data['projectName'] ][] = $data['phaseName'];
}
echo treeOut($tree);
</code></pre>
<p>Hope this is what you're looking for and will help.</p>
|
Golang bson structs - use multiple field names for a single field in json but only one for writing to the database <p>I have a struct like this -</p>
<pre><code>type Address struct {
AddressLine1 string `json:"addressLine1" bson:"addressLine1"`
AddressLine2 string `json:"addressLine2" bson:"addressLine2"`
Landmark string `json:"landmark" bson:"landmark"`
Zipcode string `json:"zipcode" bson:"zipcode"`
City string `json:"city" bson:"city"`
}
</code></pre>
<p>Due to some compatibility issues between the previous build and the latest yet-to-be-released build, I want to make sure that if someone posts json data that decodes using this struct they should be able to use either 'zipcode' or 'pincode' as the field name in their json. But when this value is written to my database, the field name should only be 'zipcode'.</p>
<p>In short,</p>
<pre><code>{
"city": "Mumbai",
"zipcode": "400001"
}
</code></pre>
<p>or </p>
<pre><code>{
"city": "Mumbai",
"pincode": "400001"
}
</code></pre>
<p>should both appear inside the database as -</p>
<pre><code>{
"city": "Mumbai",
"zipcode": "400001"
}
</code></pre>
<p>How do I allow this?</p>
| <p>You can have both fields as pointer to string:</p>
<pre><code>type Address struct {
AddressLine1 string `json:"addressLine1" bson:"addressLine1"`
AddressLine2 string `json:"addressLine2" bson:"addressLine2"`
Landmark string `json:"landmark" bson:"landmark"`
Zipcode *string `json:"zipcode,omitempty" bson:"zipcode"`
Pincode *string `json:"pincode,omitempty" bson:"zipcode"`
City string `json:"city" bson:"city"`
}
</code></pre>
<p>As you may note we're using <strong>omitempty</strong> in the json tag, so if one of the fields is not present in the json it will be ignored as a <strong>nil</strong> pointer and it will not be present after <em>Marshal()</em> or <em>Unmarshal()</em></p>
<p><strong>Edit</strong>:</p>
<p>In this case all we have to do is implement the method <code>UnmarshalJSON([]byte) error</code> to satisfy the interface <a href="https://golang.org/pkg/encoding/json/#Unmarshaler" rel="nofollow">Unmarshaler</a>, the method <code>json.Unmarshal()</code> will always try to call that method and we can add our own logic after Unmarshal the struct, in this case we want to know if <em>pincode</em> is settled if it's we assigned to <em>zipcode</em>:
full example here: <a href="https://play.golang.org/p/zAOPMtCwBs" rel="nofollow">https://play.golang.org/p/zAOPMtCwBs</a></p>
<pre><code>type Address struct {
AddressLine1 string `json:"addressLine1" bson:"addressLine1"`
AddressLine2 string `json:"addressLine2" bson:"addressLine2"`
Landmark string `json:"landmark" bson:"landmark"`
Zipcode *string `json:"zipcode,omitempty" bson:"zipcode"`
Pincode *string `json:"pincode,omitempty"`
City string `json:"city" bson:"city"`
}
// private alias of Address to avoid recursion in UnmarshalJSON()
type address Address
func (a *Address) UnmarshalJSON(data []byte) error {
b := address{}
if err := json.Unmarshal(data, &b); err != nil {
return nil
}
*a = Address(b) // convert the alias to address
if a.Pincode != nil && a.Zipcode == nil {
a.Zipcode = a.Pincode
a.Pincode = nil // unset pincode
}
return nil
}
</code></pre>
<p>Note that the field <strong>Zipcode</strong> has a bson tag and <strong>Pincode</strong> not, also we have to create an alias of type address to avoid calling UnmarshalJSON recursively</p>
|
Changing slides using anchor tags or buttons from different div <p>I have a bootstrap carousel in my page and I want to change slides using anchor tags or buttons from different <code>div</code> how to do it?</p>
| <p>This can be done through jQuery.</p>
<pre class="lang-js prettyprint-override"><code>$('#nextButton').on('click', function() {
$('.carousel').carousel('next');
});
$('#previousButton').on('click', function() {
$('.carousel').carousel('prev');
}):
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.