text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Javadocs and jdk mismatch on NavigableSet/Map?
The NavigableSet API docs state that methods headSet,tailSet(E),headSet(E) and subSet(E, E) return a NavigableSet.
In Eclipse, I get a type mismatch error, although I use the 1.6_20 jdk and have my compiler compliance set to 1.6, so I have to "downgrade" the return value to SortedSet.
Am I missing something?
A:
You may have misread the javadoc. There two headSet methods, one returns SortedSet and the other returns NavigableSet. The same for the other methods you mentioned.
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel 5.1 App\Http\Controllers\JWT class not found
I am working with JWT for authentication in my angular - laravel application. Everything is working fine except when the token needs to be generated, I get an error
App\Http\Controllers\JWT
I've tried adding the following lines in the AuthController :-
use Tymon\JWTAuth\Providers\JWTAuthServiceProvider;
and
use App\Http\Controllers\JWT;
and
use JWT;
but nothing seems to work
My composer.json :-
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.1.*",
"tymon/jwt-auth": "0.5.*"
},
AuthController -
$payload = [
'sub' => $user->id,
'iat' => time(),
'exp' => time() + (2 * 7 * 24 * 60 * 60)
];
return JWT::encode($payload, Config::get('app.token_secret'));
public function signup(Request $request){
$user = new User;
$user->name = $request->input('displayName');
$user->email = $request->input('email');
/*$user->password = Hash::make($request->input('password'));*/
$user->password = $request->input('password');
$user->save();
return response()->json(['token' => $this->createToken($user)]);
}
A:
Try,
JWTAuth;
However, JWTAuth::encode does not exist, If you must use encode method then try this,
use Tymon\JWTAuth\JWTManager as JWT;
Then you can access encode method
$customClaims = [
'sub' => $user->id,
'iat' => time(),
'exp' => time() + (2 * 7 * 24 * 60 * 60)
];
$payload = app('tymon.jwt.payload.factory')->make($customClaims);
return JWT::encode($payload, Config::get('app.token_secret'));
| {
"pile_set_name": "StackExchange"
} |
Q:
Generating Reports in C#
I am creating a windows application.
I am now concentrating on the Reporting Module of my Application.
I have two ideas to do this task.
Either through Crystal Reports or using the Windows Forms and placing the Data Grid View.
Can any one suggest me which option should I choose?
Also the report should be able to Export in the Excel and PDF format and even it should be Printable.
I heard from others that Crystal Reports gives some problem at the time of Deployment.
Please suggest me. I am very much confused.
Thanks in advance!
A:
Visual Studio 2005 and later comes with Microsoft Reporting tools that are so nice and, for me, better than Crystal Reports.
Update: You can install the Microsoft Report Viewer Redistributable 2005 or 2008.
A:
Yes, I would advise not to use Crystal Reports (or Crusty Reports as they have unfortunately become known as in my department). We have had a whole load of problems from reports being corrupted and requiring recreating to simply being clunky and slow.
As our applications are being upgraded we are moving over to MS Report Viewer, which is far better. You can export to Excel from the report viewer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Were these duplicates deleted correctly, or would keeping them around add value?
Edit: it looks like these deletions were justified, and more intensely peer-reviewed than it seemed - see the comments.
In an unrelated Meta question two questions came to light that had recently been deleted by several users:
https://stackoverflow.com/questions/42054478/calling-string-intern-before-first-literal-occurence
https://stackoverflow.com/questions/42052932/sort-list-of-objects-based-on-objects-variable-frequency-in-descending-order
Those may be duplicates, but they are very decently worded. They certainly add value for future Googlers. The reason for keeping duplicate questions around is that the more different ways you have to describe the same problem, the better - as long as they point to a good original question.
Has this changed recently, is this some new policy I've missed?
A:
We have an effort going on in the SOCVR chat room to clean up the site. Most of us there concentrate on close voting and others flagging. I've mostly concentrated on java, voting to close off-topic and duplicate posts.
On top of that, some of us, who have the appropriate privilege, have taken it a step further. java has degenerated into a lot of garbage (maybe like other tags). Everything has been asked before. Everything is a duplicate. Most of my close votes each day are for duplicates.
Every day, I also submit a list of previously closed posts to these users in SOCVR and we review whether they deserve deletion. In this case and many others, we thought they did.
The first post is a combination of reference equality (in general and with String) and the behavior of intern, both of which have been asked thousands of times (the former maybe being the most asked question on SO, can we get some stats on number of dupes of How do I compare strings in Java? ?)
The second post is a duplicate in the sorting category. The canonical shows you how to write a Comparator or Comparable and how to use it. Their question of how to do it comes with no evidence of effort. Adding a different post for each sorting technique seems counterproductive to me. Maybe I was wrong on that one, but it doesn't strike me as a useful post to keep on this site.
Vote as you think is appropriate. That's what I did.
I'll definitely hear you out for voting to undelete/reopen. We're always pingable in the chat room. I want to see quality in java and I don't think those are.
A:
I take umbrage with this question's closure and deletion, specifically because:
It's not asking the same question as was linked in the duplicate. The duplicate asks for differences of the intern() method between Java versions, whereas this is asking for clarification about the use of intern() in general.
The answer provided doesn't take or read similar to any of the solutions in the proposed duplicate.
Had a duplicate come along that answered the question of intern()'s general use, I wouldn't be so bothered. But, since that duplicate doesn't, I genuinely feel like a mistake was made in its review.
A:
Both of these questions were mentioned in a review list maintained by @SotiriosDelimanolis. This list is shared regularly in the SOCVR, and is reviewed regularly by room members there.
Question with id #42052932 was mentioned in this revision
Question with id #42054478 was mentioned in this revision
Both questions were reviewed and deleted by members of the SOCVR. If this review process were to fail for any reason (we trust our members but recognize that people make mistakes), there is a recently deleted posts review queue in the 10k+ tools where users can review all recent deletions.
The SOCVR is always open to anyone, including those who may disagree with—or have questions about—any action taken by any member of the room. When actions are called out on meta, it is expected that the members involved will account for their actions on meta.
| {
"pile_set_name": "StackExchange"
} |
Q:
In app purchase not working: item not available for purchase
Using in app purchase in my application. I have double checked the products are listed at playstore and in active states. plus the application is published but in beta testing. product ids using in my code is very same as in playstore. I'm testing the signed apk on phone.
Problem: whenever i click the button and try to get product it endup like this.
please help. thanks
A:
Step you need to follow, once launches an inapp products in your application.
You have latest In-app Billing Version configured in application
Apk is in published state but in beta testing or any other testing
List the products with unique ids at play store panel
Change the state of products to active state
Product ids are same in source code as well in play store (double check)
You have signed apk installed in phone
versionCode of published apk & testing apk must be same
you have added a tester at play store under same apk
You need to test inapp from very same email, you have added at google play store (as tester)
once i followed all steps this error is gone. In my case it is because of tester's email :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Handle the button list in UITableViewCell
I’m continuing to the last ViewController in my movie booking project. Because I’m new on iOS so please apologize if my question is so popular and very basic. Thank you in advance!.
So I have trouble to solve problem with the list of buttons in the cell.
E.g:
I have the swift class file for the button:
class ButtonReverse: UIButton {
require.init()
//something here. Color, etc.
}
class TypeOfSeat {
var normalSeat: Bool
var coupleSeat: Bool
var reversedSeat: Bool
var reversingSeat: Bool
// something here
}
class Total: TypeOfSeat {
var priceOfSeat: Int
func invoice () -> Int {
/// something here to return total of invoice.
// return total }
In the UITableViewCell.
I have list of the buttons to be ordered vertically.
How can I loop over the cell and create list of the buttons in one cell and random the button color that I have defined before be implement the function:
cellForRows at: IndexPath
All of buttons will be sorted in just one cell. Red is reversed seats. Yellow is reversing seat. And Green is available seat ready for reverse.
I have idea to use uicollectionview. But I want to use it with tableview only because i’m just starting with uitableview.
To handle the button in the cell I’m just using simple function to call delegate for UIAlert and show message: the seat is reversed or show the total......when user touch the button.
Many thanks,
A:
To achieve your desired result you can follow these steps :
Use CollectionView.
Take your colors in an array and use random to get color randomly and make an array for your collection (say dataArray).
If you are using buttons just to click, then don't use them instead you can give cell's content view (or you can take one view in cell) corner radius to make them circle and assign the color.
Then implement didSelectItem method to get the click item of particular cell (or color) and fetch the data from your dataArray based on indexPath.item as index.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to debug a faulty power button?
I've got an android tablet which can't be turn on anymore: Pushing the power button does nothing, screen stays black.
I've checked the battery with the multimeter which gives me a reading and there's the LED indicating a correct charge. So I suspect the problem is with the power button itself.
There is no problem of continuity between the PWR on the board and the PWR on the little circuit.
How can I check where the problem is now for this power button which seems faulty?
A:
To test if the button works use your multimeter in continuity test mode( or resistance mode if you don't have continuity test mode) and measure the two pins of the button. When you press the button you have to hear the beep in continuity mode (or see 0 ohms in resistence mode). If you don't see this the button is broken and you have to replace it.
Another test you can do is short circuit the PWR and GND pads briefly, that's what the button do to power the device. If the device don't start doing this, then the problem is not the button, is elsewhere.
| {
"pile_set_name": "StackExchange"
} |
Q:
String Builder Appending value in middle of existing appendage
I have Dims I am referencing to Append a String, however my requirement requests that I split up one of my previous Dims I am appending. Please see the example below to show you what i am trying to get at. Basically i need a way for my newest Dim added to go smack dab in the middle of an existing Dim that's already been appended. **Note: Dim a can be dynamic so I don't know the number of characters it will return.
I am using the StringBuilder functionality in VB.
Dim sb = New StringBuilder()
Dim a = someValueForA
Dim b = someValueForB
Dim c = someValueForC
Dim d = someValueForD
sb.AppendFormat("-{0}",a)
sb.AppendFormat("-{0}",b)
sb.AppendFormat("-{0}",c)
result = "someValueAsomeValueBsomeValueC"
now i need to insert d right in the middle of "C" so as to look something like this:
result = "someValueAsomeValueBsomesomeValueDValueC"
A:
You need to calculate the position and then use sb.Insert:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sb = New StringBuilder()
Dim a = "someValueA"
Dim b = "someValueB"
Dim c = "someValueC"
Dim d = "someValueD"
sb.AppendFormat("-{0}", a)
sb.AppendFormat("-{0}", b)
sb.AppendFormat("-{0}", c)
sb.Insert(sb.Length - (c.Length \ 2), d)
MessageBox.Show(sb.ToString())
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Parse query string ordering with locale swift
I am querying the database like below. However, orderbyAscending does not work properly, the accented letters are all sorted at the bottom. Is there any way Parse sorts it by locale? Or do I have to sort in the code? The string array is not long, about 40 words.
var query = PFQuery(className: RFIstanbulDistrictsClassKey)
query.whereKey(RFIstanbulDistrictsDistrictKey, notEqualTo: "")
query.orderByAscending(RFIstanbulDistrictsDistrictKey)
// constants are defined as follows:
// let RFIstanbulDistrictsClassKey = "IstanbulDistricts"
// let RFIstanbulDistrictsDistrictKey = "district"
A:
It turns out I need to sort the array after loading it from Parse:
districts.removeAll(keepCapacity: true)
let query = PFQuery(className: RFIstanbulDistrictsClassKey)
query.whereKey(RFIstanbulDistrictsDistrictKey, notEqualTo: "")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
districts = objects.map { String($0[RFIstanbulDistrictsDistrictKey] as! String) }
districts.sort { return $0 < $1 } // sort ascending
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using underscores with namedtuples
I'm working on building a SQL emulator in Python and to store the rows, I'd like to use namedtuples since I can easily handle complex queries with select, order by, and where. I started with normal tuples but I often found myself looking for an attribute of a row and needing to maintain the order of the columns, so I arrived at namedtuples.
The issue is that some of my column names have leading underscores which causes me to end up with ValueError: Field names cannot start with an underscore: '_col2'
I'm looking for either a way to use namedtuples with underscores (maybe some type of override) or a suitable alternative container that allows me to easily convert to a tuple of values in original column order or to access individual values by their field names.
I thought about appending a leading character string to every tuple and then writing a middleware function to serve as the getattr function but by first removing the leading character string - but that seems incredibly hacky.
A:
You can avoid ValueError using rename=True argument
from collections import namedtuple
a = namedtuple("Table", "_col1 _col2 _col3 col4", rename=True)
print(a._fields)
('_0', '_1', '_2', 'col4')
@Edit1 You might want to keep track of which fields have changed
from collections import namedtuple
columns = "_col1 _col2 _col3 col4"
a = namedtuple("Table", columns, rename=True)
old_feilds = columns.split()
new_feilds = a._fields
mapper = {}
for f1,f2 in zip(old_feilds, new_feilds):
mapper[f1] = f2
print(mapper)
{'_col3': '_2', '_col1': '_0', 'col4': 'col4', '_col2': '_1'}
| {
"pile_set_name": "StackExchange"
} |
Q:
Count the usage of a many to many field in Django for string representation
My Topic model has a ManyToMany Relation to the Post modell. As part of it's string representation I wanted to have its usage count but I'm unsure how to query that.
class Topic(models.Model):
posts = models.ManyToManyField(Post)
name = models.CharField(max_length=100, blank=False)
def __str__(self):
return self.name
so in addition to self.name I'd like to return the count how often that very Topic is used on Posts.
A:
Try to use self.posts.count():
def __str__(self):
return '{}, posts count: {}'.format(self.name, self.posts.count())
| {
"pile_set_name": "StackExchange"
} |
Q:
Primefaces selectOneRadio ajax
I'm trying to display validation messages everytime the user clicks on a radio button.
This only works when I click on the submit button, but not when I click on the radio button:
<h:form id="form">
<p:panel id="panel">
<ui:repeat value="#{questionsBean}" var="question">
<h:panelGrid columns="3" style="margin-bottom:10px" cellpadding="5">
<h:outputText value="#{question.questionText}" />
<p:selectOneRadio id="question" value="#{question.response}"
validator="#{question.validate}" required="true">
<f:selectItem itemLabel="Yes" itemValue="Yes" />
<f:selectItem itemLabel="No" itemValue="No" />
<p:ajax update="msgQuestion" event="change"/>
</p:selectOneRadio>
<p:message for="question" id="msgQuestion" />
</h:panelGrid>
</ui:repeat>
<p:commandButton id="btn" value="Save" update="panel" partialSubmit="true"/>
</p:panel>
</h:form>
A:
The HTML DOM change event is the wrong event when you want to listen on whether the radio button (or checkbox) is clicked. You should be using the click event for this.
The value of the radio button (and checkbox) basically never changes. It has always the same value. The question is more whether that value will be sent to the server side or not. This is determined by the "checked" state which is usually triggered by the DOM click event.
The actual behaviour of the change event on radiobuttons/checkboxes is dependent on the webbrowser used. The behaviour is particulary inconsistent in the IE browser. It not only depends on the version used, but also in the rendering mode used (quirks mode vs standards mode). Perhaps you were actually using IE while testing.
The default event type of the PrimeFaces <p:ajax> (and the standard JSF <f:ajax>), which is valueChange already automatically covers this:
<p:ajax update="msgQuestion" event="valueChange" />
This will autogenerate the right change event handler in text inputs and dropdowns and the click event handler in radiobuttons and checkboxes.
But as said, it's the default event type already. Just omit it altogether.
<p:ajax update="msgQuestion" />
| {
"pile_set_name": "StackExchange"
} |
Q:
Count Relation in Eloquent Query
Hello I have the following block of code:
$categories = EventCategory::select('id', 'name', 'thumbnail_url', 'slug')
->with(['events' => function ($query) {
$query->whereRaw("DATE_FORMAT(`sales_end_date`, '%Y-%m-%d') >= DATE_FORMAT(curdate(), '%Y-%m-%d')")
->whereRaw("DATE_FORMAT(`date`, '%Y-%m-%d') >= DATE_FORMAT(curdate(), '%Y-%m-%d')")
->count();
}])
->where('is_active', 1)
->get();
Now what this does is it returns a list of event categories, however I want it to return a count of all events in each category as well.
The above code just returns all the categories with all their events instead of just the count.
I had something else I was using in my model which worked but I was unable to apply a where clause on it, furthermore I didn't want to put where clauses n my model in the first place:
class EventCategory extends Model implements SluggableInterface
{
use SluggableTrait;
protected $sluggable = [
'build_from' => 'name',
'save_to' => 'slug',
'on_update' => true,
];
protected $table = 'event_categories';
//protected $appends = ['counter'];
public function events() {
return $this->hasMany('App\Models\EventDetails', 'category_id');
}
public function getCounterAttribute() {
return $this->events->count();
}
}
A:
foreach($categories as $category)
{
$category->event_count = count($category->events);
}
Your custom SQL should be built into the relation, not your specific instance, and if the relation logic proposed:
$query->whereRaw("DATE_FORMAT(`sales_end_date`, '%Y-%m-%d') >= DATE_FORMAT(curdate(), '%Y-%m-%d')")
->whereRaw("DATE_FORMAT(`date`, '%Y-%m-%d') >= DATE_FORMAT(curdate(), '%Y-%m-%d')")
->count();
Only applies to one function of the website, then you should build that functionality into a model interface (repository) to "override" the default functionality of the relationship.
Refer to:
Laravel - many-to-many where the many-to-many table is (part-) polymorph
| {
"pile_set_name": "StackExchange"
} |
Q:
Pandas - check columns before join/merge dataframes
I have a dataframe containing users, each with multiple ids:
df_id = pd.DataFrame({'group': ['a','a','b','b','a','a','b','b','a','a','b','b'],
'id1': ['erd','hgf','ewr','fgv','nbg','axc','bcv','ijh','plh','wqe','mnf','iud'],
'id2': ['dfg','bcw','urz','fwq','nfg','dfo','hiy','fgl','vcw','erq','dfi','vcs']})
df_id
group id1 id2
0 a erd dfg
1 a hgf bcw
2 b ewr urz
3 b fgv fwq
4 a nbg nfg
5 a axc dfo
6 b bcv hiy
7 b ijh fgl
8 a plh vcw
9 a wqe erq
10 b mnf dfi
11 b iud vcs
2 other dataframes containing partial user ids:
df_1 = pd.DataFrame({'uid1': ['ewr','nbg','hiy','dfg','wqe'],
'q': [1,1,0,1,0]
})
df_1
q uid1
0 1 ewr
1 1 nbg
2 0 hiy
3 1 dfg
4 0 wqe
df_2 = pd.DataFrame({'uid2': ['urz','nbg','axc','fgl','vcw'],
'q': ['low','high','low','high','high']
})
df_2
q uid2
0 low urz
1 high nbg
2 low axc
3 high fgl
4 high vcw
I'd like to merge all 3 together based on the id, however, uidx could match either id1 or id2 in df_id so I cant join on a single column. Furthermore, df_id contains more users than either of the other 2 dataframes, so I'm expecting a lot of NaN
The only way I can think to do this merge/join is to iterate through df_id and check both id columns and manually add values from the other dataframes, but this is very slow. Whats the correct way to do this merge/join given that the value I want to join on could be in either id column?
The desired output is:
group id1 id2 q_1 q_2
0 a erd dfg 1.0 NaN
1 a hgf bcw NaN NaN
2 b ewr urz 1.0 low
3 b fgv fwq NaN NaN
4 a nbg nfg 1.0 high
5 a axc dfo NaN low
6 b bcv hiy 0.0 NaN
7 b ijh fgl NaN high
8 a plh vcw NaN high
9 a wqe erq 0.0 NaN
10 b mnf dfi NaN NaN
11 b iud vcs NaN NaN
My actual data has hundreds of columns per dataframe, where the column names vary drastically, so I'm look for a way that doesn't require me to handle each column individually/manually. In other words, I'm looking for a general approach that doesn't require me to manually specify column/dataframe names
A:
generally:
df_1 = df_1.set_index('uid1')
q_a = df_id.join(df_1,on='id1')
q_b = df_id.join(df_1,on='id2')
df_id['q_1'] = q_a['q'].fillna(q_b['q'])
Repeat this operation on df_2, or extract a function and apply it on df_2. Maybe use iloc to avoid using column names.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract all matching substrings in bash
Looking for a solution in bash (will be part of a larger script).
Given a variable containing information of the form
diff -r efb93662e8a7 -r 53784895c0f7 diff.txt
--- diff.txt Fri Jan 23 14:48:30 2009 +0000
+++ b/diff.txt Fri Jan 23 14:49:58 2009 +0000
@@ -1,9 +0,0 @@
-diff -r 9741ec300459 myfile.c
---- myfile.c Thu Aug 21 18:22:17 2008 +0000
-+++ b/myfile.c Thu Aug 21 18:22:17 2008 +0000 -@@ -1,4 +1,4 @@
- int myfunc()
- {
-- return 1;
-+ return 10;
- }
I wish to extract both (here diff.txt and myfile.c, but future cases will not be limited to this number) filenames to a string of the form "edited: filename1 filename2 ... filenameN".
To clarify, I wish to extract multiple matching filenames to a string.
The command "$(expr "$editing" : '.*---[[:space:]]\([[:graph:]]*\)[[:space:]]')" returns the last filename correctly but not previous instances.
EDIT: Require the ability to identify edited filenames (possibly including spaces) i.e. filenames appearing after "---" and before the day "Fri/Thu...".
Thanks for your help (and to the many people have replied thus far).
A:
A solution using only bash built-ins, no external programs is:
res="edited: "; var="${var#* --- } --- "
while test -n "$var";do res="$res ${var%% *}"; var="${var#* --- }";done
echo "$res"
It iterates on all occurences of " --- ".
The trick is to prepare the string by first trimming garbarge from the start
(up to first ---)
and appending a " --- " at the end to be able to have a simpler logic in the while loop afterwards.
This is by using bash most useful feature, the # and % to trim strings
| {
"pile_set_name": "StackExchange"
} |
Q:
how can i fix my javascript calculation which is not working?
the problem is the "total price" is not working.when i pick the "pickup date" and "drop date" it will show the value in the input form. i have to key in the number in "number of days" then the total price will calculate. i need the "total of price" is auto calculate. i have try various event of javascript. here i will attach my code. hope someone will help me. thanks in advance.
function sum() {
var txtFirstNumberValue = document.getElementById('num1').value;
var txtSecondNumberValue = document.getElementById('numdays2').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('num3').value = result;
}
}
function GetDays() {
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("drop_date")) {
document.getElementById("numdays2").value = GetDays();
}
}
<label for="total">Price per day:</label>
<input type="text" name="price" id="num1" onkeyup="sum();" value="3" readonly>
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" onchange="cal()" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" onchange="cal()" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<input type="text" id="numdays2" name="numdays" oninput="sum();" />
<label for="total">Total Price (RM)</label>
<input type="text" name="test" placeholder="Total Price" value="" id="num3">
i expect that the total price can automatically calculate.
A:
You just need to make sure your sum function (or in the example just cal) is being called when your inputs are complete and valid. Since you may want to restrict the user from manually setting the number of days I've demonstrated how you might do this by firing a change event programmatically. It's also current practice to attach events to elements programmatically instead of using the inline HTML5 event notation (e.g. "onchange=foo"), see Why are inline event handler attributes a bad idea in modern semantic HTML?
function setDate(event) {
var days = getDays();
// if the number of days is valid
if (!isNaN(days)) {
var nod = document.getElementById("numdays2");
nod.value = days;
// programmatically setting a value will not fire a change event
nod.dispatchEvent(new Event("change"));
}
}
function getDays() {
// returns NaN if either date does not hold a valid date
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
var pricePerDay = document.getElementById("pricePerDay").value;
if (0 == (pricePerDay = parseInt(pricePerDay))) { return } // TODO needs to handle decimal values
document.getElementById("total").value = parseInt(document.getElementById("numdays2").value) * pricePerDay;
}
function init() {
document.getElementById("drop_date").addEventListener("change", setDate);
document.getElementById("pick_date").addEventListener("change", setDate);
document.getElementById("numdays2").addEventListener("change", cal);
}
document.addEventListener("DOMContentLoaded", init);
<label for="total">Price per day:</label>
<input type="text" name="price" id="pricePerDay" value="" placeholder="Manually enter a value">
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<!-- numdays2 is readonly to ensure the date pickers are used -->
<input type="text" id="numdays2" name="numdays" readonly placeholder="Select dates above" />
<label for="total">Total Price (RM)</label>
<input id="total" type="text" readonly name="test" placeholder="Total Price" value="" id="num3">
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
An OpenGL qeustion:why doesn't glutSwapBuffer() function work?
This code is from the red book, example 2-15 (well, the code is not exactly the one in the book). Take care of the note I noted.
#include <fstream>
#include <stdlib.h>
#include <GL/glew.h>
#include <GL/glut.h>
#pragma comment(lib,"glew32.lib")
using namespace std;
#define BUFFER_OFFSET(offset) ((GLubyte *)NULL+offset)
#define XStart -0.8
#define XEnd 0.8
#define YStart -0.8
#define YEnd 0.8
#define NumXPoints 11
#define NumYPoints 11
#define NumPoints (NumXPoints * NumYPoints)
#define NumPointsPerStrip (2*NumXPoints)
#define NumStrips (NumYPoints-1)
#define RestartIndex 0xffff
void display(void)
{
int i,start;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1,1,1);
glDrawElements(GL_TRIANGLE_STRIP,NumStrips*(NumPointsPerStrip+1),GL_UNSIGNED_SHORT,BUFFER_OFFSET(0));
//glFlush();//it works,show a white square with black backgroud
glutSwapBuffers();///it doesn't work,show what tha area looked like before
}
void init (void)
{
GLuint vbo,ebo;
GLfloat *vertices;
GLushort *indices;
glewInit();
glGenBuffers(1,&vbo);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER,2*NumPoints*sizeof(GLfloat),NULL,GL_STATIC_DRAW);
vertices=(GLfloat *)glMapBuffer(GL_ARRAY_BUFFER,GL_WRITE_ONLY);
if(vertices==NULL)
{
fprintf(stderr,"Unable to map vertex buffer\n");
exit(EXIT_FAILURE);
}
else
{
int i,j;
GLfloat dx=(XEnd-XStart)/(NumXPoints-1);
GLfloat dy=(YEnd-YStart)/(NumYPoints-1);
GLfloat *tmp=vertices;
int n=0;
for(j=0;j<NumYPoints;++j)
{
GLfloat y=YStart+j*dy;
for(i=0;i<NumXPoints;++i)
{
GLfloat x=XStart + i*dx;
*tmp++=x;
*tmp++=y;
}
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glVertexPointer(2,GL_FLOAT,0,BUFFER_OFFSET(0));
glEnableClientState(GL_VERTEX_ARRAY);
}
glGenBuffers(1,&ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,NumStrips*(NumPointsPerStrip+1)*sizeof(GLushort),NULL,GL_STATIC_DRAW);
indices=(GLushort *)glMapBuffer(GL_ELEMENT_ARRAY_BUFFER,GL_WRITE_ONLY);
if(indices==NULL)
{
fprintf(stderr,"Unable to map index buffer\n");
exit(EXIT_FAILURE);
}
else
{
int i,j;
GLushort *index=indices;
for(j=0;j<NumStrips;++j)
{
GLushort bottomRow=j*NumYPoints;
GLushort topRow=bottomRow+NumYPoints;
for(i=0;i<NumXPoints;++i)
{
*index++=topRow+i;
*index++=bottomRow+i;
}
*index++=RestartIndex;
}
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
}
glPrimitiveRestartIndex(RestartIndex);
glEnable(GL_PRIMITIVE_RESTART);
}
void reshape (int w, int h)
{
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D (-1,1,-1,1);
glViewport (0,0,w,h);
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(0);
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (200, 200);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc (keyboard);
glutMainLoop();
return 0;
}
as the http://www.opengl.org/resources/libraries/glut/spec3/node21.html says:
An implicit glFlush is done by glutSwapBuffers before it returns. Subsequent OpenGL commands can be issued immediately after calling glutSwapBuffers, but are not executed until the buffer exchange is completed.
If the layer in use is not double buffered, glutSwapBuffers has no effect.
How do I know whether the layer in use is double buffered?give an double buffered example.is this code I wrote is double buffered?
A:
In your main function, you call
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
That needs to be GLUT_DOUBLE. See the documentation for glutInitDisplayMode().
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get list of unanswered question for all interesting tags at once?
It's probably being new here, but I can't seem to filter unanswered questions by all of me "interested" tags at once. Instead I need to filter them tag by tag, one at a time.
Is there a better way?
A:
Unanswered -> my tags
| {
"pile_set_name": "StackExchange"
} |
Q:
how to check the status(online/offline) of a person in a chat application in windows phone?
I have developed a chat application and now I want to update the status of my buddies (my friends list) with the message online or offline based on their status. How frequent I should update status of user to the db and how frequent my client application should check for their status ?
A:
Are you sure you want to update the status at regular intervals? Depending on your server side, you can find a solution that will not poll the server, and notify the client. In any case, the implementation long polling pattern will positively affect the performance of your application. I had server side on PHP and use control WebBrowser in my WP App to subscribe to status updates, etc.. The client code was written in Java Script and it works fine. But there are more interesting solutions, I advise you to read about the library http://signalr.net/.
| {
"pile_set_name": "StackExchange"
} |
Q:
How many reviewers see a given article in the 'First Posts' queue?
The 'First Posts' queue is presumably a way to keep noobs on track with best practices by making comments. It also gives the reviewer the opportunity to vote on the question or answer.
My question is if Person 'A' makes a first post and then reviewer 'R' examines it in the queue, is the post also presented to reviewer 'R2'? If so, how many reviewers will see the first post?
If it is shown only to the person who is working the queue, why is that? It seems preferable to have several people examine it, like the way everything else works.
A:
First posts used to get three reviewers, but it looks like they now get only one. Some people disagree with that decision:
Please require more reviewers on First Posts
“Late Answers” and “First Posts” encouraging unnecessary actions
First-Post “No Action Needed” should not count to review stats
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I remove specify string words with php
How can I remove string . I want to find string that've 2018 then I want to delete string until ,
{"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,"2019-1-1":0,"2019-1-15":0}
How can I display like this
{"2019-1-1":0,"2019-1-15":0}
Note I want to remove "2018-1-8":0,"2018-1-9":0,"2018-1-10":0,
A:
This string is valid JSON which you can parse using json_decode(). You can then modify the data as you want:
// Your string
$json = '{"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,"2019-1-1":0,"2019-1-15":0}';
// Get it as an array
$data = json_decode($json, true);
// Pass by reference
foreach ($data as $key => &$value) {
// Remove if key contains '2018'
if (strpos($key, '2018') !== false) {
unset($data[$key]);
}
}
// Return the updated JSON
echo json_encode($data);
// Output: {"2019-1-1":0,"2019-1-15":0}
Another solution using array_walk():
$data = json_decode($json, true);
array_walk($data, function ($v, $k) use (&$data) {
if (strpos($k, '2018') !== false) { unset($data[$k]); }
});
echo json_encode($data);
// Output: {"2019-1-1":0,"2019-1-15":0}
See also:
passing by reference
strpos()
unset()
json_encode()
| {
"pile_set_name": "StackExchange"
} |
Q:
How to index child on top of parent's brother's children
I'm having troubled with indexing in Actionscript 3.0. Basically I have two objects that are spawned on the stage. One is dock and the other a ball object. How it works is that when a ball object is over the dock, a info window appears on the screen. The ball object has a wrapper called Container.
So the objects are: MainClass, Dock, Container, BallObject, InfoWindow.
So from back to front it's: MainClass > Dock > InfoWindow > Container > BallObject.
Dock and Container are added in the Main class, and infoWindow is added in the Dock class and BallObject from the Container class.
What I want to achieve is to have the InfoWindow on top of the BallObjects, without the Dock being in front of the Container or BallObjects.
Here is an image to help illustrate things out.
d = dock c = container B = ballobject I = infowindow
The image on the left is what I want to achieve and the one right is what I have right now.
A:
With your hierarchy it is impossible, as the DisplayList is a tree as a whole, and is rendered depth first. So, put Container under Dock, and give it child index less than InfoPanel.
dock.addChild(container);
dock.addChild.infoPanel);
container.addChild(ball);
main.addChild(dock);
This approach will net you the requested goal. In case you need to add another layer, say between Container and InfoPanel, add another container between them, and add required stuff to that container.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Update everytime column hits x number rows
I have table call question with two columns, it contains more than 160K rows, example:
id | questionID
1 | 1
2 | 2
3 | 3
4 | 4
5 | 5
6 | 6
7 | 7
8 | 8
9 | 9
10 | 10
...
I would like to update the questionID column so it will look like the example below. For every x number rows it need update to set from 1 again. The final result should be something like this:
id | questionID
1 | 1
2 | 2
3 | 3
4 | 4
5 | 1
6 | 2
7 | 3
8 | 4
9 | 1
10 | 2
...
The table contains some many rows, so its not an option do it manually.
What could be the easiest way to update the table?
Any help will be appreciated. Thanks
A:
If you are going to use the modulus operator. Both SQL Server and MySQL support %:
UPDATE question
SET questionID = 1 + ((id - 1) % 4);
If the numbers have gaps, then you need to do something different. In that case, the solution is highly database dependent.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending mails with grails application error
I'm trying to send mail from my Grails app with mail plugin. It worked in the development enviroment and for the default settings for gmail smtp. I have now deployed app on Windows server running Tomcat 7 and trying to send mail via Exchange. I am getting this error:
These are mail properties in config.groovy:
grails {
mail {
host = "mail.something.com"
port = 25
username = "[email protected]"
password = "xxx"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"25",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}
javax.mail.AuthenticationFailedException: No authentication mechansims supported by both server and client
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:590)
at javax.mail.Service.connect(Service.java:291)
at grails.plugin.mail.MailMessageBuilder.sendMessage(MailMessageBuilder.groovy:102)
at grails.plugin.mail.MailMessageBuilder$sendMessage.call(Unknown Source)
at grails.plugin.mail.MailService.sendMail(MailService.groovy:39)
at grails.plugin.mail.MailService$sendMail.call(Unknown Source)
at org.helpdesk.RequestController$_closure12.doCall(RequestController.groovy:240)
at org.helpdesk.RequestController$_closure12.doCall(RequestController.groovy)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
What should I do? Thanks.
A:
It is clearly stated what's wrong:
javax.mail.AuthenticationFailedException: No authentication mechansims supported by both server and client
Your Gmail SMTP settings won't work with Exchange server. You need to change settings. Just search for it. Here is one question involving Java Mail and Exchange server: JavaMail Exchange Authentication and you might be interested in this topic in Java Mail FAQ: http://www.oracle.com/technetwork/java/faq-135477.html#Exchange-login .
| {
"pile_set_name": "StackExchange"
} |
Q:
Group objects in category of groups
I am trying to show that a group object in the category of Groups is an abelian group (which, to a beginner, reads as a peculiar statement!)
So here is what I know:
Let $\mathscr{C}$ be a category having (finite) products and a terminal object $Z$. A group object in $\mathscr{C}$ is an object $G$ and morphisms $\mu: G \times G \to G$, $\eta:G \to G$ and $\epsilon: Z \to G$ such that the diagrams for associativity, identity and inverse commute (apologies, it is too hard to draw them without xymatrix here)
Here I think of (hopefully correctly), $\eta$ as the inversion $g \mapsto g^{-1}$
In the category of groups we have that the terminal object is any trivial group, which I will just call $0$.
Then to show the result, I would need to take $g_1,g_2 \in G$ and show that $\mu(g_1,g_2) = \mu(g_2,g_1)$
I am a bit unsure where to go from here. The problem, I guess, is that I don't see what makes the category of groups lead to abelian group objects. For example, in the category of Sets the group objects are just groups.
A:
The main point is that you require the inverse $\eta$ to be a group homomorphism (i.e. a morphism in the category of groups). You can easily check that this forces $G$ to be abelian, using the compatibility between multiplication $\mu$ and inversion $\eta$ (I will use the usual group notation, you can convert it into $\mu$-$\eta$-ology): $(gh)^{-1} = h^{-1}g^{-1}$, and that is supposed to be equal to $g^{-1}h^{-1}$ by the requirement that $\eta$ is a morphism.
Another issue is: why does the morphism $\mu$ have to be the group structure on $G$ that already comes from $G$ being an element of $\textbf{Grp}$? This is known as the Eckmann-Hilton argument.
| {
"pile_set_name": "StackExchange"
} |
Q:
CircularGauge displayed incorectly - its size is tiny
I am learning to style QML's Circural Gauge and here is my code chunk:
Now, the background property of CircuralGauge is basicly
identical to example's one:
background: Canvas
{
onPaint:
{
var ctx=getContext("2d");
ctx.reset();
ctx.beginPath();
ctx.strokeStyle="steelblue";
ctx.lineWidth=outerRadius*0.02;
ctx.arc(outerRadius,
outerRadius,
outerRadius-ctx.lineWidth/2,
degreesToRadians(valueToAngle(80)-90),
degreesToRadians(valueToAngle(100)-90));
ctx.stroke();
} // onPaint
} // background
however, I get abnormal gauge (tiny one) as you can see:
Why/what am I missing?
A:
I've managed to solve problem. It was not problem in Circural Gauge itself, but in other component's Layout with settings: Layout.fillHeight: true. I've set it to false and now works. Here is complete code for Item:
import QtQuick 2.7
import QtQuick.Layouts 1.3
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Extras 1.4
Item
{
id: ueDisplayBrightnessSettingsWindow
width: parent.width
height: parent.height
RowLayout
{
anchors.fill: parent
ColumnLayout
{
Layout.fillWidth: true
Layout.fillHeight: true
Layout.alignment: Qt.AlignHCenter|Qt.AlignVCenter
CircularGauge
{
Layout.fillWidth: true
Layout.fillHeight: true
Layout.alignment: Qt.AlignHCenter|Qt.AlignTop
value: ueDisplayBrightnessSlider.maximumValue-ueDisplayBrightnessSlider.value
minimumValue: 0
maximumValue: ueDisplayBrightnessSlider.maximumValue
style: CircularGaugeStyle
{
tickmarkStepSize: 1.00
labelStepSize: 10
function degreesToRadians(degrees)
{
return degrees*(Math.PI/180);
} // degreesToRadians
needle: Rectangle
{
y: outerRadius*0.15
implicitWidth: outerRadius*0.03
implicitHeight: outerRadius*0.90
antialiasing: true
gradient: Gradient
{
GradientStop
{
position: 0.00
color: "lightsteelblue"
} // GradientStop
GradientStop
{
position: 0.80
color: "steelblue"
} // GradientStop
} // gradient
} // needle
tickmark: Rectangle
{
visible: styleData.value<80||styleData.value%10==0
implicitWidth: outerRadius*0.02
implicitHeight: outerRadius*0.06
antialiasing: true
color: styleData.value>=80?"steelblue":"lightsteelblue"
} // tickmark
minorTickmark: Rectangle
{
visible: styleData.value<80
implicitWidth: outerRadius*0.01
implicitHeight: outerRadius*0.03
antialiasing: true
color: "lightsteelblue"
} // minorTickmark
tickmarkLabel: Text
{
font.pixelSize: Math.max(6, outerRadius*0.1)
text: styleData.value
color: styleData.value>=80?"steelblue":"lightsteelblue"
antialiasing: true
} // tickmarkLabel
foreground: Rectangle
{
width: outerRadius*0.2
height: width
radius: width/2
anchors.centerIn: parent
gradient: Gradient
{
GradientStop
{
position: 0.00
color: "steelblue"
} // GradientStop
GradientStop
{
position: 0.70
color: "#191919"
} // GradientStop
} // gradient
} // foreground
background: Canvas
{
onPaint:
{
var ctx=getContext("2d");
ctx.reset();
ctx.beginPath();
ctx.strokeStyle="steelblue";
ctx.lineWidth=outerRadius*0.02;
ctx.arc(outerRadius,
outerRadius,
outerRadius-ctx.lineWidth/2,
degreesToRadians(valueToAngle(80)-90),
degreesToRadians(valueToAngle(100)-90));
ctx.stroke();
} // onPaint
} // background
} // style
} // CircularGauge
Slider
{
id: ueDisplayBrightnessSlider
Layout.fillWidth: true
Layout.fillHeight: false
Layout.alignment: Qt.AlignHCenter|Qt.AlignBottom
updateValueWhileDragging: true
tickmarksEnabled: true
stepSize: 1
minimumValue: 0
maximumValue: 100
style: SliderStyle
{
handle: Rectangle
{
width: ueDisplayBrightnessSettingsWindow.width/10
height: width
radius: height
antialiasing: true
color: control.pressed?"lightsteelblue":"steelblue"
} // handle
groove: Rectangle
{
width: ueDisplayBrightnessSettingsWindow.width
height: ueDisplayBrightnessSettingsWindow.width/35
gradient: Gradient
{
GradientStop
{
position: 0.00
color: "steelblue"
} // GradientStop
GradientStop
{
position: 0.50
color: "lightsteelblue"
} // GradientStop
GradientStop
{
position: 1.00
color: "steelblue"
} // GradientStop
} // gradient
} // groove
} // syle
} // Slider
} // ColumnLayout
} // RowLayout
} // Item
| {
"pile_set_name": "StackExchange"
} |
Q:
R: Construct a file path from user input
I have two variables, work.dir and my.file. This means the user would like to save my.file to work.dir. User is asked to enter work.dir path and this is where it gets tricky. If user enters work.dir path
c:/temp/
and I try to paste this with a my.name, I will get
c:/temp/my.file.
But if the user enters
c:/temp
I will get
c:/tempmy.file.
So far I've been battling this with extracting various parts of the work.dir and sticking it together to achieve consistency, but I was wondering if there's another way (that would be perhaps more resilient)?
So far this has been my solution of getting a consistent directory that can be used to be pasted together with a file name.
work.dir <- "c:/temp"
work.dir <- paste(dirname(work.dir), basename(work.dir), sep = "")
A:
James rightfully points out that in most cases the directory will be interpreted correctly. In case this doesn't satisfy you and assuming your user knows he or she shouldn't use backslashes in his directory, you can use file.path() to solve your problem, eg like this:
makepath <- function(path,file){
path <- as.list(strsplit(path,'/')[[1]])
do.call(file.path,c(path,file))
}
If your user might use Windows backslashes (and forget he has to escape them with another backslash), you can add the following controls:
makepath <- function(path,file){
if(grepl('[^[:graph:]]',path))
stop("Invalid characters. Check you didn't use a single \\")
win <- grepl('\\\\',path)
sep <- if(win) '\\\\' else '/'
path <- as.list(strsplit(path,sep)[[1]])
do.call(file.path,c(path,file))
}
This gives :
> makepath('c:\\temp','myfile')
[1] "c:/temp/myfile"
> makepath('c:\\temp\\','myfile')
[1] "c:/temp/myfile"
> makepath('c:/temp','myfile')
[1] "c:/temp/myfile"
> makepath('c:/temp/','myfile')
[1] "c:/temp/myfile"
| {
"pile_set_name": "StackExchange"
} |
Q:
Looping through FileList declaration
I am trying to wrap my mind around a particular for loop declaration, but I had no success so far. The code snippet allows you to read a file input and loop through all the objects thanks to a for loop:
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
Now, I wonder when does this for loop
for (var i = 0, f; f = files[i]; i++)
stops. Shouldn't the second parameter be a comparison parameter like " === , < , > " and so on ?
I can see that on each loop it is assigning to the variable 'f' the value of every object input in files[i], but I don't get why it is declared like that and how does it works.
What is the difference between the aforementioned and this?
var f;
for (var i = 0;i<files.length; i++) {
f = files[i];
}
A:
Assigment always returns the assigned value, so the statement f = files[i] returns the file, which is a truthy value, until there are no more files in the fileList, then it returns undefined, which is falsy, and the loop stops.
The reason it stops is because a for loop consists of three expressions
for ([initialization]; [condition]; [final-expression]) { statement
The "condition" is an expression to be evaluated before each loop iteration.
If this expression evaluates to true, the statement is executed, if it evaluates to false, like undefined would, the statement is not executed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unmarshalling arrays in JSON structure
Stackoverflow:
I've been struggling to unmarshal what I wouldn't consider an especially complex
JSON response in GO. (which I'm fairly new to). Example below:
{ "eventId": "tevtNKIsHrFQTyyMeYDMc5jgQ1459184873000",
"sessionId": "1016Q-vnpnlQwCiLiyH7e_cNg",
"targets":
[ { "id": "00u34k73otQGIAFUALPR", "displayName": "okta admin", "login": "[email protected]", "objectType": "User" } ] }
I tried representing this as an array of structs, but it never seems to connect.
I put my code on the GO Lang playground, if anyone can take a look I'd be very
appreciative.
https://play.golang.org/p/TVYeYe7e_I
A:
For big json documents I recommend you to use this tool: https://mholt.github.io/json-to-go/
You will get something like:
type AutoGenerated struct {
EventID string `json:"eventId"`
SessionID string `json:"sessionId"`
RequestID string `json:"requestId"`
Published time.Time `json:"published"`
Action struct {
Message string `json:"message"`
Categories []string `json:"categories"`
ObjectType string `json:"objectType"`
RequestURI string `json:"requestUri"`
} `json:"action"`
Actors []struct {
ID string `json:"id"`
DisplayName string `json:"displayName"`
Login string `json:"login,omitempty"`
ObjectType string `json:"objectType"`
IPAddress string `json:"ipAddress,omitempty"`
} `json:"actors"`
Targets []struct {
ID string `json:"id"`
DisplayName string `json:"displayName"`
Login string `json:"login"`
ObjectType string `json:"objectType"`
} `json:"targets"`
}
Full example: https://play.golang.org/p/Q8PwwtS_QZ
Also you can always start with a map[string]interface{} instead of a struct.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why did Jango Fett have a son via cloning instead of through natural reproductive processes?
Why did Jango Fett choose to have his son, Boba Fett, created via cloning, rather than having a child by a woman?
Did he want a son and was either unwilling or unable to do so with a mate?
A:
Canonically, we don't know because we don't know of any romantic relationships Jango had with either men or women. The fact that Jango did not have a child with a woman does not really indicate he's homosexual -- he is willing to have a son but perhaps he never found a suitable woman to be the mother.
In Legends, he is heterosexual. He has a romantic relationship with a woman named Sheeka Tull.
Legends also provides the backstory for Jango's recruitment as clone template. The ending to the video game Star Wars Bounty Hunter includes a scene in which Darth Tyranus first recruits Jango. Tyranus sells the idea to Jango as a chance for "immortality", and to pass on his ways to the clone army. This convinced Jango to become the clone template for the army and possibly for Boba (he could pass on his ways to Boba in particular), but when Tyranus asks him why he wanted an unaltered clone Jango refuses to answer. So even Legends only hints at why Jango wanted a son.
A:
Because he wanted an exact replica of himself.
A:
I don't think Jango Fett actively sought to have a son via cloning. Rather, thinks happened the other way around.
The Republic approached him and bought his DNA to produce a clone army. In return, Fett decided that, if they were going to clone him, he wanted one to raise as his own. In other words, the opportunity to have a son presented itself through the clone process, so he took advantage of it.
If he truly wanted a son, it wouldn't have mattered if he was homosexual or not. There are plenty of options for "natural born" children other than heterosexual sex, including adoption or artificial insemination.
(Having said that, there's no indication that he's homosexual, and as @Null points out, at least one non-canon case of his having a heterosexual relationship. Again, that's not proof -- homosexual men in the real world do sometimes "fake it" for various reasons. It merely shows that we just don't know enough about him to know.)
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery animate is very slow in both IE and Firefox
I am using a jQuery animate() function to show a small text becoming larger and larger, until it disappear.
I have the jQuery code here:
function Gain() {
/* Using multiple unit types within one animation. */
$("#block").animate({
width: "80%",
opacity: 0.0,
marginLeft: "2.6in",
fontSize: "15em",
borderWidth: "10px"
}, 2000, function () {
$("#block").removeAttr("style");
$("#block").html("");
$("#block").css("color", "White");
$("#block").css("position", "absolute");
$("#block").css("z-index", "-5");
});
}
The code I use to fire the function:
string script = "$('#block').html('Yes!<br/>" + xpReward.ToString() + "xp!');";
ScriptManager.RegisterStartupScript(ButtonListUpdate, typeof(string), "startup",
"xpGain(); " + script, true);
This code is run everytime I select an option in a RadioButtonList (ASP.NET).
Now, I have this issue:
Chrome - Works REALLY well
Safari - Works REALLY well
iPhone Browser - Works OK
Internet Explorer - Horrible
Firefox - Sometimes great, other times horrible
I would like to ignore Internet Explorer, but as they have a very large market share, I have to deal with the issue.
You can try the animation yourself
Go to http://www.GameLearner.com
Click the large "Play now" button
Click "Play right away"
Answer a question correctly. The first question might take ~5-10s
So my question is....
How to make this work in Internet Explorer? Right now it is horrible. I don't expect it to work really good, but just "playable" would be really awesome...
Thanks a lot!
Lars
A:
Just a thought - you're using %, em, px and in as units of measurement. Perhaps if you standardised on only one measurement unit, things might work faster. I really don't know though, just having a guess.
Also in the function that runs when the animation's complete, you could chain together all the actions on the $('#block') element, e.g.
$("#block").removeAttr("style").html("").css("color", "White").css("position", "absolute").css("z-index", "-5");
| {
"pile_set_name": "StackExchange"
} |
Q:
Front end for CLIPS
I have just been introdcude to the CLIPS expert system. Does anyone know how difficult it is to integrate a GUI in Java or C++ for this tool?
A:
Some years ago I developed a CLIPS application using Java AWT graphics and it was not difficult at all. It was a JFrame Application and painting in a Canvas class. I no longer have the code though.
But if I would started today. I would probably use Processing to show the results. It is java based , easy to paint graphics and you can integrate any java code or library with it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can we promote better writing skills in academic education?
This question may be too wide or in some perspective perceived as unclear but covers a key issue (for me) in academia, namely, academic writing.
Students start their academic career with varying skills in writing. Often, and this the case in my department, there is no thought through progression to go from beginner through novice and proficient to expert level (the latter perhaps in graduate school) or some such scale.
My question is therefore how to get students to progress in appropriate steps through an education. In other words what is a reasonable progression of writing skills through an education. I am looking for suggestions of appropriate expectations for, say, an annual or semester wise increase in difficulty or complexity of exercises with the aim of learning academic writing skills through an education including graduate school.
A:
In my lab, we were required to produce three-to-four page white papers, including figures, every time we presented at a lab meeting (approx. every 6 weeks).
This had two significant effects. Firstly, it forced the student to write down their progress, which was invariably ridiculously useful when the student actually started writing their thesis. Staple together a few of these sections and the methods, and often a good part of the background, was written for you.
Secondly, it gave everyone a chance to practice their professional writing in a casual lab setting. No one felt threatened and everyone improved. We would even review the articles being written by the lab professor, as there were always improvements we could suggest to him as well.
I strongly recommend this practice.
A:
HAVE them write. A lot of times students don't write because they simply aren't asked to. (Keep in mind the corollary to this is you're going to have to do some reading!)
Have them research! Many times students don't make the leap on their own between reading, writing, and then (hopefully) thinking that's incredibly obvious to those of us who have devoted our lives to teaching. I've seen a lot of lightbulbs go on when I've been able to help a student make the connection between research, writing, and work output.
As gman started to say above, if your school has an academic writing center go there and ask lots and lots of questions. Usually people who work in these departments have thought far more deeply about your question than you might ever be able to. They might even be able to give you exercises or assign a tutor to monitor your class. At the very least, make sure the students know the writing center is there and that you expect them to use it!
A:
As a grad-student I really appreciate this question. As a Humanities student most of our writing is text. I found even at under-graduate level a substantial amount of time could be taken up going over the same writing issues (usually after assignment hand-backs) over a number of course modules. It amazed me that there was not a module to at least give the basics in academic writing.
I have noticed though in Ireland(my home country) that there is a number of Academic Writing Centres starting to set up in Universities. At the moment they are voluntarily drop in centres where you can get advice on your writing.
In the case of the university I attend
The AWC offers free one-on-one tutorials on essay writing for NUIG students. Last year, AWC tutors helped over 500 students to overcome recurrent problems with grammar, punctuation, spelling, and essay structure.
They also run group workshops at certain times of the year for different levels within the University, so some are aimed at under-graduate and some at post-graduate. Normally at these workshops you bring some of your writing and as a group you give each other advice on improving our writing style.
Finally they run an online course which works in the following way.
Online students are assigned weekly writing tasks and editing tasks. Editing tasks consist of specific questions which assist students in providing constructive feedback rather than criticism. Guided editing tasks help students to re-evaluate and improve their own writing. Students then rate the usefulness of the critique they received. In this way, points are awarded for effort rather than existing ability or experience. The entire process is strictly anonymous. The AWC takes on a supportive role for the duration of the course. Students receive weekly readings and emails.
A number of other universities also have a academic writing centre in place. See here and here
While this is by no means a perfect model because it requires the student to want to participate it is a step in the right direction for improving a persons writing skills.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it allowed to scatter human cremains (ashes) from an aircraft?
A serious question, here: There's gotta be a pilot out there somewhere who has done a memorial request to spray someone's ashes over a city street. I'm gonna do it out of spite for a lousy little mill town in Central Pa. There seems to be no laws against it on the books. 500' fly-overs are okay, spreading ashes falls under no FAA rule that I can find. When I go (soon, I'm an AO affected Vietnam Vet), I plan to have a contract with a crop-duster or acrobatic pilot for a decent show. Aside from (moral) advice, can someone comment, please? I wish to know of any known regulations governing this, especially any against.
A:
AOPA has an entire article on it that's worth reading and while it's generally fine with the FAA (assuming the pilot isn't being careless or reckless), there may be other regulations or laws that apply. The article mentions:
Permission needed for scattering over federal land
Permission needed for scattering over water (federal and local regulations)
State burial requirements
But there are two specific aviation regulations that might apply to the flight. First, 14 CFR 91.15:
§91.15 Dropping objects.
No pilot in command of a civil aircraft may allow any object to be
dropped from that aircraft in flight that creates a hazard to persons
or property. However, this section does not prohibit the dropping of
any object if reasonable precautions are taken to avoid injury or
damage to persons or property.
Second, you said that you plan to have a "contract" with someone to scatter the ashes, which implies that you're going to pay the pilot. If that's the case, then the pilot may not use an experimental aircraft for the flight. That's because the FAA considers carrying human ashes to be carrying property (Harris interpretation, 2009) and 91.319(a) doesn't allow carrying property for compensation in experimental aircraft:
(a) No person may operate an aircraft that has an experimental
certificate—
(1) For other than the purpose for which the certificate was issued;
or
(2) Carrying persons or property for compensation or hire.
Finally, note that accidents can and do happen and in at least one case two people died while spreading ashes (although to be fair, the toxicology data was fairly 'interesting' in that one).
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ To C# - One little function
Can you help me to transfer that code to C#?
HWND Notepad = FindWindowEx( GetDesktopWindow( ), 0, "Notepad", 0 );
SendMessage( GetDlgItem( Notepad, MB_TYPEMASK ), WM_SETTEXT, 0, (LPARAM)"Hello Notepad, what's up?" );
Thank you in advance
UPDATE:
I want to send key presses to background window.
I don't want to use SendKeys.Send because I want that window to be in background.
SendKeys requires that window is active.
A:
As far as I know such a low level funcionality is not available in WinForms, hence you should call WinApi via pinvoke which will result in almost literal rewrite of this code to c#
Start here
GetDlgItem
GetDesktopWindow
FindWindowEx
| {
"pile_set_name": "StackExchange"
} |
Q:
In-App Purchase in new version of the App
I have a live app on the App Store, which is currently version 1.0 with 5 in-app.
I just created the version 1.1 in the iTunes Connect but I was not able to configure my in-apps for my new version. Will my existing in-apps assigned to my new version automatically or do I have to configure it ? And If so, how?
Thanks
A:
Existing In-App purchase will continue to work, you don't have to do anything special with that.
If you're introducing new In-App purchases you have to create these and put together with the update into review.
| {
"pile_set_name": "StackExchange"
} |
Q:
Laravel - Saving new related member doesn't update parent
I've got these two models (changed the names for this example because they aren't in english):
Task:
public function times() {
return $this->hasMany('TaskTime', 'id');
}
TaskTime:
public function task() {
return $this->belongsTo('Task', 'task_id');
}
Also, inside the model Task, I've got this method:
public function start() {
$now = Carbon\Carbon::now();
$time = new TaskTime;
$time->task()->associate($this);
$time->beginning = $now->toDateTimeString();
$time->save();
// testing
echo $this->times()->get()->toJson();
echo '<br/><br/>';
echo $this->toJson();
die();
}
When I call the start() method, it correctly saves a new row in the TaskTime's corresponding table, with the foreign key correctly set to the Task.
The line echo $this->tempos()->get()->toJson(); correctly prints the rows, including the new one.
The line echo $this->toJson(); doesn't print the new row! Only prints the old ones.
I've tried save() and push() in both $this and $time and it still doesn't print the updated data!
Any idea of what can be causing this? I've been trying to debug this thing since yesterday and I ran out of ideas...
A:
The problem is, that Eloquent does not update relation on the already loaded models after attaching, saving, associating etc.
It creates the relation, ie. inserts/updates necessary tables (attach, save, saveMany) or sets the relation on the model without saving anything in db (associate).
So in your case $this has no idea that newly created $tempo has been associated to it.
Now,
`$this->tempos()->get()->toJson();`
runs a new query to fetch related tempos, this is why you get correct result, but
`$this->tempos;
must have been loaded before associating new one, so they won't be reloaded from the db, thus you get 'old' result.
What you need is this:
public function start() {
// do what you need with $time
$tempo->task()->associate($this);
$tempo->save();
$this->load('tempos'); // reloads relation from db
// or:
$this->tempos->add($tempo); // manually add newly created model to the collection
}
Mind thought, that latter solution will cause unexpected result if $this->tempos have not been already loaded.
| {
"pile_set_name": "StackExchange"
} |
Q:
Scraping website that uses javascript
I'm trying to scrape this page: http://stats.nba.com/playerGameLogs.html?PlayerID=2544&pageNo=1&rowsPerPage=100
I'm wanting to get the table into a pandas DataFrame. I've tried BeautifulSoup and it's obvious that won't work. I tried to use selenium, but I'm not having luck with it. I'm hoping someone has a better solution before I continue going down the selenium path, as it at least opens up the browser and shows the correct output, Firefox just force closes after. I also prefer to not have to physically open up the browser either, as I would be doing this for 1000s of pages.
A:
There is no need for scraping HTML, or using a high-level selenium approach.
Simulate the underlying XHR request(s) going to the server and returning the JSON data that is used to fill up the table on the page.
Here's an example using requests:
import requests
url = 'http://stats.nba.com/stats/playergamelog'
params = {
'Season': '2013-14',
'SeasonType': 'Regular Season',
'LeagueID': '00',
'PlayerID': '2544',
'pageNo': '1',
'rowsPerPage': '100'
}
response = requests.post(url, data=params)
print response.json()
Prints the JSON structure containing the player game logs:
{u'parameters': {u'LeagueID': u'00',
u'PlayerID': 2544,
u'Season': u'2013-14',
u'SeasonType': u'Regular Season'},
u'resource': u'playergamelog',
u'resultSets': [{u'headers': [u'SEASON_ID',
u'Player_ID',
u'Game_ID',
u'GAME_DATE',
u'MATCHUP',
u'WL',
u'MIN',
u'FGM',
u'FGA',
u'FG_PCT',
u'FG3M',
u'FG3A',
u'FG3_PCT',
u'FTM',
u'FTA',
u'FT_PCT',
u'OREB',
u'DREB',
u'REB',
u'AST',
u'STL',
u'BLK',
u'TOV',
u'PF',
u'PTS',
u'PLUS_MINUS',
u'VIDEO_AVAILABLE'],
u'name': u'PlayerGameLog',
u'rowSet': [[u'22013',
2544,
u'0021301192',
u'APR 12, 2014',
u'MIA @ ATL',
u'L',
37,
10,
22,
0.455,
3,
7,
0.429,
4,
8,
0.5,
3,
5,
8,
5,
0,
1,
3,
2,
27,
-13,
1],
[u'22013',
2544,
u'0021301180',
u'APR 11, 2014',
u'MIA vs. IND',
u'W',
35,
11,
20,
0.55,
2,
4,
0.5,
12,
13,
0.923,
1,
5,
6,
1,
1,
1,
2,
1,
36,
13,
1],
[u'22013',
2544,
u'0021301167',
u'APR 09, 2014',
u'MIA @ MEM',
u'L',
41,
14,
23,
0.609,
3,
5,
0.6,
6,
7,
0.857,
1,
5,
6,
5,
2,
0,
5,
1,
37,
-8,
1],
...
}
Alternative solution would be to use an NBA API, see several options here:
https://stackoverflow.com/questions/57106/anyone-know-of-an-nfl-or-nba-api
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift 4 download Swedens radio channels
I got the same error when I try to get previous and song that play right now for every channel. I think something is wrong in my struct Root and playlist because data is not in the correct format.I am using Swift 4 and trying to learn JSON, but its hard. Previous struct is same as Song struct.
How do I fix my error?
My code looks now:
*struct Root : Decodable {
let copyright : String
let channels : [Channel]
let pagination : Pagination
//let playlists : [Playlist]
}
struct Channel : Decodable {
let image : String
let imagetemplate : String
let color : String
let tagline : String?
let siteurl : String
let id : Int
let url : URL?
let statkey : String?
let scheduleurl : String
let channeltype : String
let name : String
}
struct Pagination : Decodable {
let page, size, totalhits, totalpages : Int
let nextpage : URL
}
struct Playlist : Decodable{
let id : Int
let name :String
let prev : [previoussong]
let song : [Song]
}
struct Song : Decodable {
let title : String
let description : String
let artist : String
let composer :String
let conductor : String
let albumname : String
let recordlabel : String
let lyricist : String
let producer : String
let starttimeutc : String
let stopttimeutc : String
}
var tests = [Channel]()
var pl = [Playlist]()
func downloadStations(){
let test2 = "http://api.sr.se/api/v2/channels?format=json"
let play = "http://api.sr.se/api/v2/playlists/rightnow?format=json"
let url = URL(string: test2) /// play instead of test2
URLSession.shared.dataTask(with: url!){ (data , response, error) in
do{
let root = try JSONDecoder().decode(Root.self, from: data!)
self.tests = root.channels
//self.pl = root.playlists
for eachStations in self.tests {
DispatchQueue.main.async {
self.tableV.reloadData()
}
}
} catch {
print(error.localizedDescription)
}
}.resume()*
A:
It doesn't return the array of channels. It returns an object:
{
"copyright": "somestring",
"pagination": {},
"channels": []
}
So, copyright is not a part of channel and you have an object with field channels.
| {
"pile_set_name": "StackExchange"
} |
Q:
Transfer value of Form to Usercontrol
I create a user control and add a textbox to it. In my windows form I add the user control i created and add a textbox and a button. How to copy the text I input from the textbox of Form to textbox of Usercontrol and vice versa. Something like
usercontrol.textBox1.text = textBox1.text
A:
From Form to Usercontrol
Form Code
public string ID
{
get { return textBox1.Text; }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
userControl11.ID = ID;
}
Usercontrol Code
public string ID
{
set { textBox1.Text = value; }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to move 2 rows and 2 columns into 1 row on smaller screens but correct columns in order
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<style>
/* SECTION WITH LINES */
.section > div {
border: 2px solid rgba(0,0,0,0.1);
padding: .3em .8em;
margin-top: 2em;
position: relative;
text-transform: uppercase;
font-size: 1.2em;
color: #555;
font-weight: 600;
text-align: center;
}
.section > div:before {
content: '';
position: absolute;
top: 50%;
right: 100%;
border-bottom: 2px solid;
width: 90%;
margin: 0 20px;
color: rgba(0,0,0,0.1);
}
.section > div:after {
content: '';
position: absolute;
top: 50%;
left: 100%;
border-bottom: 2px solid;
width: 90%;
margin: 0 20px;
color: rgba(0,0,0,0.1);
}
/* HALF SECTION WITH LINES */
.h-section > span {
border: 2px solid rgba(0,0,0,0.1);
padding: .3em .8em;
margin-top: 2em;
margin-bottom: 2em;
position: relative;
text-transform: uppercase;
font-size: 1.3em;
color: #555;
font-weight: 600;
z-index: 1;
text-align: center;
float: left;
height: 50px;
}
.h-section > span:before {
content: '';
position: absolute;
top: 50%;
right: 100%;
border-bottom: 2px solid;
width: 40%;
margin: 0 20px;
color: rgba(0,0,0,0.1);
}
.h-section > span:after {
content: '';
position: absolute;
top: 50%;
left: 100%;
border-bottom: 2px solid;
width: 40%;
margin: 0 20px;
color: rgba(0,0,0,0.1);
}
</style>
<div class="container">
<div class="d-flex justify-content-center section col-lg-4 offset-lg-4 col-md-6 offset-md-3 col-sm-6 offset-sm-3 col-xs-6">
<div>What service do you require?</div>
</div>
<div class="container">
<div class="row">
<div class="d-flex-lg justify-content-between">
<div class="d-flex justify-content-center col-lg-6 h-section"><span>What we offer</span></div>
<div class="justify-content-center col-lg-6">
Blah
</div>
<div class="d-flex justify-content-center col-lg-6 h-section"><span>Our benefits</span></div>
<div class="d-flex justify-content-center col-lg-6">
Blah 2
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<style>
/* HALF SECTION WITH LINES */
.h-section > span {
border: 2px solid rgba(0,0,0,0.1);
padding: .3em .8em;
margin-top: 2em;
margin-bottom: 2em;
position: relative;
text-transform: uppercase;
font-size: 1.3em;
color: #555;
font-weight: 600;
z-index: 1;
text-align: center;
float: left;
height: 50px;
}
.h-section > span:before {
content: '';
position: absolute;
top: 50%;
right: 100%;
border-bottom: 2px solid;
width: 40%;
margin: 0 20px;
color: rgba(0,0,0,0.1);
}
.h-section > span:after {
content: '';
position: absolute;
top: 50%;
left: 100%;
border-bottom: 2px solid;
width: 40%;
margin: 0 20px;
color: rgba(0,0,0,0.1);
}
</style>
<div class="container">
<div class="row">
<div class="d-flex-lg justify-content-between">
<div class="d-flex justify-content-center col-lg-6 h-section"><span>What we offer</span></div>
<div class="justify-content-center col-lg-6">
Blah
</div>
<div class="d-flex justify-content-center col-lg-6 h-section"><span>Our benefits</span></div>
<div class="d-flex justify-content-center col-lg-6">
Blah 2
</div>
</div>
</div>
</div>
</div>
Currently it works as expected on smaller displays but on larger displays, both rows are on different lines. When I try to get them on the same line, it breaks it working correctly on smaller displays
I added the style and my question contains more code so this is adding more text so that it will post. Thanks
A:
The columns show besides eachother in large screen and on top of eachother in a small screen.
There were some mistakes in your HTML/Bootstrap, most notably that you were trying to have more than 12 col units in one row.
Here is the solution:
CSS:
.column_title {
border: 2px solid rgba(0,0,0,0.1);
padding: .3em .8em;
margin-top: 2em;
margin-bottom: 2em;
position: relative;
text-transform: uppercase;
font-size: 1.3em;
color: #555;
font-weight: 600;
z-index: 1;
text-align: center;
float: left;
height: 50px;
}
.column_title:before {
content: '';
position: absolute;
top: 50%;
right: 100%;
border-bottom: 2px solid;
width: 40%;
margin: 0 20px;
color: rgba(0,0,0,0.1);
}
.column_title:after {
content: '';
position: absolute;
top: 50%;
left: 100%;
border-bottom: 2px solid;
width: 40%;
margin: 0 20px;
color: rgba(0,0,0,0.1);
}
.column_text {
float:left;
clear:left;
}
HTML:
<div class="container">
<div class="row">
<div class="col-lg-6">
<div class="column_title">What we offer</div>
<div class="column_text">Blah 1</div>
</div>
<div class="col-lg-6">
<div class="column_title">Our benefits</div>
<div class="column_text">Blah 2</div>
</div>
</div>
</div>
Good luck and let me know how it turned out!
| {
"pile_set_name": "StackExchange"
} |
Q:
Display a view for 404 error in CodeIgniter
The CodeIgniter has a very simple default error 404 message:
404 Page Not Found
The page you requested was not found.
Instead of using this error message on totally blank page, I want to wrap this message in between my header and footer view, so that the error message have similar look to the other pages.
For that purpose, I have created an error view? For example:
my404_view.php
<? $this->load->view('header'); ?>
404 Page Not Found
The page you requested was not found.
<? $this->load->view('footer'); ?>
Now, How can I use this my404_view.php as a default view to display 404 messages instead of using the CodeIgniter default error message.
A:
You should change your routes.php. For example:
in application/config/routes.php
$route['404_override'] = 'welcome/_404';
in application/controllers/welcome.php
function _404(){
$this->load->view("my404_view");
}
And this should be sufficient in the current version of CI.
A:
Including headers and footers in the default error 404 page seems to be a common problem for CodeIgniter users. I would like to add this link: Simon Emms's comments at http://www.simonemms.com/2011/05/06/codeigniters-404-override-problem/ because he describes the problem so clearly.
I have tried the suggestions at http://maestric.com/doc/php/codeigniter_404 and played around with Simon Emms's ideas, and others, but just can't implement them. I'm a bit of a novice at PHP and CodeIgniter, so that might be because of ignorance. That said, it is difficult to ensure that you put the suggested subclasses in the right places and configure, for instance, routes.php correctly. After 3 days of trying the various rather complicated ideas, it occurred to me that I could just use an include statement in the default error 404 page. The only difficulty was figuring out the path to pass to the include statement.
In /system/core/Exceptions.php line 146, I found the CodeIgniter developers use APPPATH. You then just have to append the path to the header and footer pages you want to include.
My new default error 404 page now looks like this:
<?php
include APPPATH.'/views/templates/header.php';
?>
<div id="container">
<h1><?php echo $heading; ?></h1>
<?php echo $message; ?>
</div>
<?php
include APPPATH.'/views/templates/footer.php';
?>
This seems a much easier solution to me than trying to change the core classes in CodeIgniter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Evaluate this and also the indefinite case
$$
\mbox{How to evaluate this integral ?:}\quad
\int_{-1}^{1}\left[\,x^{2012}\sin\left(\,x\,\right) +
\frac{1}{x^{2} + 1}\,\right]\mathrm{d}x
$$
A:
HINT:
Use $\displaystyle I=\int_a^bf(x)\ dx=\int_a^bf(a+b-x)\ dx$
$$\displaystyle I+I=\int_a^b\{f(x)+f(a+b-x)\}\ dx$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Error: "VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results"
I'm running WAMP v2.0 on WindowsXP and I've got a bunch of virtual hosts setup in the http-vhosts.conf file.
This was working, but in the last week whenever I try & start WAMP I get this error in the event logs:
VirtualHost *:80 -- mixing * ports and
non-* ports with a NameVirtualHost
address is not supported, proceeding
with undefined results.
and the server won't start. I can't think of what's changed.
I've copied the conf file below.
NameVirtualHost *
<VirtualHost *:80>
ServerName dev.blog.slaven.net.au
ServerAlias dev.blog.slaven.net.au
ServerAdmin [email protected]
DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/"
ErrorLog "logs/blog.slaven.localhost-error.log"
CustomLog "logs/blog.slaven.localhost-access.log" common
<Directory "c:/Project Data/OtherProjects/slaven.net.au/blog/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
EDIT: I meant to add, if I change the NameVirtualHosts directive to specify a port, i.e
NameVirtualHost *:80
I get this error:
Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80
A:
NameVirtualHost *:80
I get this error:
Only one usage of each socket address (protocol/network address/port) is normally >permitted. : make_sock: could not bind to address 0.0.0.0:80
I think this might be because you have somthing else listening to port 80. Do you have any other servers (or for example Skype) running?
(If it was Skype: untick "Tools > Options > Advanced > Connection > Use port 80 and 443 as alternatives for incoming connections")
| {
"pile_set_name": "StackExchange"
} |
Q:
Div's Positioning Change on Click
I have four Div's one after the other inside a main div and aligned vertically.
Like:
DIV1
DIV2
DIV3
DIV4
I want that clicking on any of the DIV, the div whose is clicked comes on the top and the other slide down. How can i do it using jQuery?
E.g.
If DIV3 was clicked the divs reorder themselves like this:
DIV3
DIV1
DIV2
DIV4
Any help is appreciated.
A:
Here's a vertical animated version, that is relatively positioned and fairly flexible.
http://jsfiddle.net/bryanjamesross/RgGyF/
| {
"pile_set_name": "StackExchange"
} |
Q:
Does cmake use convention over configuration?
Maven is said to employ a form of Convention over Configuration.
I don't want to draw any wrong comparisons but as far as I understand cmake can fill a similar roll for a C++ project as maven can for a Java project.
So, does cmake have some Conventions over Configuration, or is each project configured uniquely? (Wrt. file layout, test layout, build output, etc.)
A:
After experiencing the elegance of Maven 3, I also looked for a convention over configuration C maven style system. ...
I also checked out CMAKE, after creating a skeleton a few things stood out.
CMAKE is sometimes declarative, sometimes procedural, and your always going to end up with an ugly mix. AKA, it's ANT for C without brackets.
CMAKE itself IS portable, alas your project will need platform specifics handled and you better know them in advance. CMAKE modules exist to supposedly help with this, unfortunately their re-usability appears more like the promise of Ansible roles... Theoretically possible, but in practice they end up as decent way for you to organize all that complexity required.
In other words, CMAKE is in no shape or form like Maven. It's more like a lower level ANT, that allows you to use the "Cross-platform" DSL to generate platform specific makefiles.
| {
"pile_set_name": "StackExchange"
} |
Q:
WordPress - Getting Posts by Custom Post Type and Category, with each category automatically encased in a DIV
Sorry for the long question title. I was attempting to be accurate.
I need to devise a WordPress query that will automatically get posts from a certain custom post type, detect how each post is categorized, and then output the posts, by category onto a page, with each category encased in its own DIV.
For example, I have a custom post type called "Map Data". Within this custom post type, I have a heirarchial taxonomy that I have named "Categories", and within that taxonomy, a number of categories, "Category #1", "Category #2", so on and so forth. Each Category has a number of posts.
So, the query should get a list of all of the categories within the custom post type, and then output something like this:
<div id="category-1">
<div class="post">This is a post in Category 1</div>
<div class="post">This is another post in Category 1</div>
</div>
<div id="category-2">
<div class="post">This is a post in Category 1</div>
<div class="post">This is another post in Category 1</div>
</div>
I have the following code which works with the default WordPress Category system, however, I either need to re-write it, or update it so that it can work with custom post types and their taxonomies.
<?php
$cat_args=array();
$categories=get_categories($cat_args);
foreach($categories as $category) {
$args=array(
'category__in' => array($category->term_id),
);
$posts=get_posts($args);
if ($posts) {
echo '<div class="cat" id="' . $category->slug.'" name="' . $category->name.'">';
foreach($posts as $post) {
setup_postdata($post);
?>
<?php the_title();?>
<?php the_content();?>
<?php
} // foreach($posts
echo '</div>';
} // if ($posts
} // foreach($categories
?>
If anyone could provide updated code for me to try, or a working example, it would be very much appreciated.
A:
i did this it gets all taxonomies but it could easily be modified to active what your trying
// for a given post type, return all
$post_type = 'shows';
$tax = 'show-topic';
$tax_terms = get_terms($tax, array('orderby' => 'id', 'order' => 'ASC', 'exclude' => '135, 49, 25, 24, 54'));
if ($tax_terms) {
foreach ($tax_terms as $tax_term) {
$args = array(
'post_type' => $post_type,
"$tax" => $tax_term->slug,
'post_status' => 'publish',
'posts_per_page' => - 1,
'orderby' => 'title',
'order' => 'ASC',
'caller_get_posts' => 1
); // END $args
$my_query = null;
$my_query = new WP_Query($args);
if ($my_query->have_posts()) {
echo '<h3>' . $tax_term->name . '</h3>';
while ($my_query->have_posts()) : $my_query->the_post();
?>
<div class="post row" id="post-<?php the_ID(); ?>">
<div class="thumb-box three column">
<?php
$src = wp_get_attachment_image_src(get_post_thumbnail_id());
if (has_post_thumbnail()) {
the_post_thumbnail();
} else {
if (get_post_meta($post->ID, "thumbnail", true)):
?>
<a href="<?php the_permalink() ?>" rel="bookmark"><img src="<?php echo get_post_meta($post->ID, "thumbnail", true); ?>" alt="<?php the_title(); ?>" /></a>
<?php else: ?>
<a href="<?php the_permalink() ?>" rel="bookmark"><img src="<?php bloginfo('stylesheet_directory'); ?>/images/insp-tv-small.png" alt="<?php the_title(); ?>" /></a>
<?php endif;
}
?>
</div>
<div class="post-content nine columns">
<h4 class="posttitle archiveposttitle">
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php _e('Permanent Link to', 'buddypress') ?> <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</h4>
<div class="entry">
<?php the_excerpt(); ?>
</div>
</div>
</div>
<?php
endwhile;
} // END if have_posts loop
wp_reset_query();
} // END foreach $tax_terms
} // END if $tax_terms
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do GeoJSON features appear like a negative photo of the features themselves?
I have a pretty standard code thats reads a GeoJSON file and renders its features using D3.js. It works fairly well except with this file: https://github.com/regiskuckaertz/d3/blob/master/circonscriptions.json
The file doesn't look weird or anything, in fact you can preview it on GitHub or geojsonlint.com. However, D3 draws paths that look like the features were used as a clipping mask, i.e. all the shapes are negatives of the features themselves. The code is pretty standard though:
var proj = d3.geo.mercator()
.scale(25000)
.center([6.08642578125,49.777716951563754])
.rotate([-.6, -.2, 0]);
var path = d3.geo.path().projection(proj);
function ready(error, luxembourg) {
svg
.selectAll("path")
.data(luxembourg.features)
.enter().append("path")
.attr("d", path)
.attr("class", function(d) { return quantize(rateById.get(d.properties.name)); })
}
You can have a look here: http://jsfiddle.net/QWZXd/
The same code works with another file, which comes from the same source.
A:
For some reason, the points in these polygons are in reverse order - they ought to be clockwise, but are defined as counterclockwise, and d3 follows the right-hand rule for polygon interpretation.
To fix, reverse the points, either in the file or in JS:
luxembourg.features.forEach(function(feature) {
feature.geometry.coordinates[0].reverse();
});
Fixed fiddle: http://jsfiddle.net/nrabinowitz/QWZXd/1/
| {
"pile_set_name": "StackExchange"
} |
Q:
Distribution of compound Poisson process
Suppose a compound Poisson process is defined as $X_{t} = \sum_{n=1}^{N_t} Y_n$, where $\{Y_n\}$ are i.i.d. with some distribution $F_Y$, and $(N_t)$ is a Poisson process with parameter $\alpha$ and also independent from $\{Y_n\}$.
Is it true that as
$t\rightarrow \infty, \, \frac{X_{t}-E(X_{t})}{\sigma(X_t)
\sqrt(N_t)} \rightarrow \mathbf{N}(0, 1)$ in distribution, where the limit is a standard Gaussian distribution? I am considering
using Central Limit Theorem to show it, but the
theorem I have learned only applies when $N_t$ is
fixed and deterministic instead of
being a Poisson process.
A side question: is it possible to derive the
distribution of $X_{t}$, for each $t\geq 0$? Some book that has the derivation?
Thanks!
A:
Let $Y(j)$ be i.i.d. with finite mean and variance, and set
$\mu=\mathbb{E}(Y)$ and $\tau=\sqrt{\mathbb{E}(Y^2)}$.
If $(N(t))$ is an independent Poisson process with rate $\lambda$,
then the compound Poisson process is defined as
$$X(t)=\sum_{j=0}^{N(t)} Y(j).$$
The characteristic function of $X(t)$ is calculated as follows:
for real $s$ we have
\begin{eqnarray*}
\psi(s)&=&\mathbb{E}\left(e^{is X(t)}\right)\cr
&=&\sum_{j=0}^\infty \mathbb{E}\left(e^{is X(t)} \ | \ N(t)=j\right) \mathbb{P}(N(t)=j)\cr
&=&\sum_{j=0}^\infty \mathbb{E}\left(e^{is (Y(1)+\cdots +Y(j))} \ | \ N(t)=j\right) \mathbb{P}(N(t)=j)\cr
&=&\sum_{j=0}^\infty \mathbb{E}\left(e^{is (Y(1)+\cdots +Y(j))}\right) \mathbb{P}(N(t)=j)\cr
&=&\sum_{j=0}^\infty \phi_Y(s)^j {(\lambda t)^j\over j!} e^{-\lambda t}\cr
&=& \exp(\lambda t [\phi_Y(s)-1])
\end{eqnarray*}
where $\phi_Y$ is the characteristic function of $Y$.
From this we easily calculate $\mu(t):=\mathbb{E}(X(t))=\lambda t \mu$
and $\sigma(t):=\sigma(X(t))= \sqrt{\lambda t} \tau$.
Take the expansion $\phi_Y(s)=1+is\mu -s^2\tau^2 /2+o(s^2)$ and substitute it into
the characteristic function of the normalized random variable ${(X(t)-\mu(t)) /\sigma(t)}$ to obtain
\begin{eqnarray*}
\psi^*(s) &=& \exp(-is(\mu(t)/\sigma(t))) \exp(\lambda t [\phi_Y(s/\sigma(t))-1]) \
&=& \exp(-s^2/2 +o(1))
\end{eqnarray*}
where $o(1)$ goes to zero as $t\to\infty$. This gives the central limit theorem
$${X(t)-\mu(t)\over\sigma(t)}\Rightarrow N(0,1).$$
We may replace $\sigma(t)$, for example, with $\tau \sqrt{N(t)}$ to get
$${X(t)-\mu(t)\over\tau \sqrt{N(t)}}= {X(t)-\mu(t)\over\sigma(t)} \sqrt{\lambda t \over N(t)} \Rightarrow N(0,1),$$
by Slutsky's theorem, since $\sqrt{\lambda t \over N(t)}\to 1$ in probability by the law of large numbers.
Added: Let $\sigma=\sqrt{\mathbb{E}(Y^2)-\mathbb{E}(Y)^2}$ be the standard deviation of $Y$,
and define the sequence of standardized random variables
$$T(n)={\sum_{j=1}^n Y(j) -n\mu\over\sigma\sqrt{n}},$$
so that
$${X(t)-\mu N(t)\over \sigma \sqrt{N(t)}}=T(N(t)).$$
Let $f$ be a bounded, continuous function on $\mathbb{R}$. By the usual
central limit theorem we have $\mathbb{E}(f(T(n)))\to \mathbb{E}(f(Z))$ where
$Z$ is a standard normal random variable.
We have for any $N>1$,
$$\begin{eqnarray*}
|\mathbb{E}(f(T(N(t)))) - \mathbb{E}(f(Z))|
&=& \sum_{n=0}^\infty |\mathbb{E}(f(T(n)) - \mathbb{E}(f(Z))|\ \mathbb{P}(N(t)=n) \cr
&\leq& 2\|f\|_\infty \mathbb{P}(N(t)\leq N) +\sup_{n>N} |\mathbb{E}(f(T(n)))- \mathbb{E}(f(Z)) |.
\end{eqnarray*}
$$
First choosing $N$ large to make the right hand side small, then letting $t\to\infty$ so
that $\mathbb{P}(N(t)\leq N)\to 0$, shows that
$$ \mathbb{E}(f(T(N(t)))) \to \mathbb{E}(f(Z)). $$
This shows that $T(N(t))$ converges in distribution to a standard normal as $t\to\infty$.
A:
Derivation of the formula for the distribution of $X_t$. The formula
$$
P_{X_t } = e^{ - t\nu (\mathbb{R})} \sum\nolimits_{k = 0}^\infty {(k!)^{ - 1} t^k \nu ^k } ,
$$
where $\nu$ is the L\'evy measure of $X$ and $\nu^k$ is the $k$-fold convolution of $\nu$, is very easy to derive. Indeed, using the notation in the question, the law of total probability gives
$$
{\rm P}(X_t \in B) = \sum\limits_{k = 0}^\infty {{\rm P}(X_t \in B|N_t = k){\rm P}(N_t = k)} .
$$
Thus,
$$
{\rm P}(X_t \in B) = \sum\limits_{k = 0}^\infty {{\rm P}(Y_1 + \cdots + Y_k \in B)\frac{{e^{ - \alpha t} (\alpha t)^k }}{{k!}}} = e^{ - \alpha t} \sum\limits_{k = 0}^\infty {(k!)^{ - 1} t^k \alpha ^k F_Y^k (B) } ,
$$
where $F_Y^k$ is the $k$-fold convolution of $F_Y$. Now, since the corresponding L\'evy measure $\nu$ is given by $\nu (dx) = \alpha F_Y (dx)$, it holds $\nu(\mathbb{R}) = \alpha$ and $\nu^k = \alpha^k F_Y ^k$, and so the original formula is established.
Remark. As should be clear, the distribution of $X_t$ is very complicated in general.
A:
The distribution of $X_t$ is given by
$$
P_{X_t } = e^{ - t\nu (\mathbb{R})} \sum\nolimits_{k = 0}^\infty {(k!)^{ - 1} t^k \nu ^k } ,
$$
where $\nu$ is the L\'evy measure of $X$, and $\nu^k$ is the $k$-fold convolution of $\nu$. This is contained in Remark 27.3 in the book [L\'evy Processes and Infinitely Divisible Distributions], by Sato.
For a compound Poisson process with rate $\alpha$ and jump distribution $F_Y$, the L\'evy measure $\nu$ is finite and given by $\nu(dx)=\alpha F_Y (dx)$.
EDIT:
For the first question, note that if $t =n \in \mathbb{N}$, then
$$
X_t = X_n = (X_1 - X_0) + (X_2 - X_1) + \cdots + (X_n - X_{n-1})
$$
(note that $X_0 = 0$). Thus, $X_t$ is a sum of $n$ i.i.d. variables, each with expectation ${\rm E}(X_1)$ and variance ${\rm Var}(X_1)$. Now, as is well known and easy to show,
$$
{\rm E}(X_1) = \alpha {\rm E}(Y_1) = \alpha \int {xF_Y (dx)}
$$
and
$$
{\rm Var}(X_1) = \alpha {\rm E}(Y_1^2) = \alpha \int {x^2 F_Y (dx)},
$$
provided that $Y_1$ has finite second moment. Thus, by the central limit theorem,
$$
\frac{{X_t - n\alpha {\rm E}(Y_1 )}}{{\sqrt {\alpha {\rm E}(Y_1^2 )} \sqrt n }} \to {\rm N}(0,1),
$$
as $n \to \infty$.
EDIT: Put it another way,
$$
\frac{{X_t - {\rm E}(X_t )}}{{\sqrt {{\rm Var}(X_t )} }} \to {\rm N}(0,1)
$$
(shown here for the case $t \to \infty$ integer).
EDIT: Some more details in response to the OP's request.
A compound Poisson process is a special case of a L\'evy process, that is, a process $X=\{X_t: t \geq 0\}$ with stationary independent increments, continuous in probability and having sample paths which are right-continuous with left limits, and starting at $0$. In particular, for any $t \geq 0$ and any $n \in \mathbb{N}$, $X_t$ can be decomposed as a sum of $n$ i.i.d. random variables, which means that $X_t$ is infinitely divisible. There is a vast literature available online on this important topic.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i handle with DWR.. if my java class return xml data
StockDetails.java
public class StockDetails {
public String getDetailsBySymbol(String symbol){
StockQuote stockQuote = new StockQuote();
StockQuoteSoap stockQuoteSoap = stockQuote.getStockQuoteSoap();
return stockQuoteSoap.getQuote(symbol);
}
}
and it returns stockquote in xml format
in client side jsp file index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Dwr Example</title>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script type='text/javascript' src='dwr/interface/StockDetails.js'>
</script>
<script>
function getMessageFromServer()
{
var symbol = DWRUtil.getValue("companySymbol");
DWRUtil.setValue("response", "");
StockDetails.getDetailsBySymbol(gotResult, symbol);
}
function gotResult(symbol)
{
DWRUtil.setValue("response", symbol);
}
</script>
</head>
<body>
<p>
<input type="text" id="companySymbol"></input><br>
<button onclick="getMessageFromServer()">Click</button><br><br>
</p>
<p>
<span id="response">Response appear here..</span>
</p>
</body>
</html>
it displays like a normal text how can i display in for structural format like
Company name :
Start price :
closed price :
any idea?
A:
You can use downloadxml.js to parse data, built a html table and after fill fields with jquery
`var xml = xmlParse(data);
for (var i=0; i < data.length; i++ ){
$("#fila"+i).find("#field1").text(data[i].field1);
$("#fila"+i).find("#field2").text(data[i].field2);
...........
}
`
| {
"pile_set_name": "StackExchange"
} |
Q:
Access violation error when releasing SparseMat
I'm working on 3D sparse matrices in OpenCV and I get this Access Violation Error when I try to call release method of cv::SparseMat (http://docs.opencv.org/modules/core/doc/basic_structures.html#sparsemat-release).
Also some notes on OpenCV's memory management: http://docs.opencv.org/modules/core/doc/intro.html#automatic-memory-management
Here's the isolated version of my problem:
int main(int argc, char *argv[])
{
cv::SparseMat smat2;
smat2 = Test();
smat2.release(); //access violation error
}
cv::SparseMat Test()
{
const int sizes[] = {480, 640, 3000};
cv::SparseMat mat(3, sizes, CV_8SC1);
return mat;
}
And the internal code where the error occurs is:
inline void SparseMat::release()
{
if( hdr && CV_XADD(&hdr->refcount, -1) == 1 )
delete hdr; // <--- HERE!
hdr = 0;
}
It's been some time for me with memory management and C++. Any help is much appreciated. Thanks.
A:
It had something to do with my misconfiguration of dynamic libraries of OpenCV. When I copied correct dlls (opencv_core245.dll under \Release, opencv_core245d.dll under \Debug and so on) problem solved.
It's still interesting though, I changed my %PATH% variable to contain C:\opencv\build\x64\vc11\bin folder, which contains both release and debug dll's, yet I had to manually copy dll files to corresponding project folders.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display column name and column comment, when try DML
I'm try use DML operations on table, when insert or update. I need to show column name and column comment when the operation failed. For example code:
CREATE TABLE test_test(col1 VARCHAR2(10), col2 VARCHAR2(100) not null);
DECLARE
ex_insert_null EXCEPTION;
PRAGMA EXCEPTION_INIT(ex_insert_null, -1400);
ex_value_too_large EXCEPTION;
PRAGMA EXCEPTION_INIT(ex_value_too_large, -12899);
BEGIN
INSERT INTO test_test
(col1
,col2)
SELECT CASE
WHEN LEVEL = 8 THEN
(LEVEL + 1) || 'qqqqqqqqqqqq'
ELSE
(LEVEL + 2) || 'qqq'
END AS col1
,CASE
WHEN LEVEL = 7 THEN
NULL
ELSE
(LEVEL + 3) || 'wwwwwww'
END AS col2
FROM dual
CONNECT BY LEVEL <= 10;
COMMIT;
EXCEPTION
WHEN ex_insert_null THEN
ROLLBACK;
dbms_output.put_line('ex_insert_null at ' || ' ' /* || column_name || ' ' || column_comment */);
WHEN ex_value_too_large THEN
ROLLBACK;
dbms_output.put_line('ex_value_too_large at ' || ' ' /* || column_name || ' ' || column_comment */);
END;
/
A:
As APC has pointed out, you could use "existing Oracle exceptions" eg if you had something like ...
procedure insert_( col1 varchar2, col2 varchar2 )
is
v_errorcode varchar2(64) ;
v_errormsg varchar2(128) ;
begin
insert into t ( c1, c2 ) values ( col1, col2 ) ;
exception
when others then
if sqlcode = -1400 or sqlcode = -12899 then
v_errorcode := sqlcode;
v_errormsg := substr( sqlerrm, 1, 128 );
dbms_output.put_line( v_errorcode || ' ' || v_errormsg ) ;
raise;
end if;
end insert_ ;
... you could get error messages such as these:
-1400 ORA-01400: cannot insert NULL into ("MYSCHEMA"."T"."C2")
-12899 ORA-12899: value too large for column "MYSCHEMA"."T"."C1" (actual: 13, maximum: 10)
If this is enough information for you, fine. However, you also want to see the COMMENTS for the columns. Although we could get the column names from the SQLERRM strings, it may be more reliable to use user-defined exceptions (as you have hinted).
As a starting point, the following DDL and PACKAGE code may be of use for you. ( see also: dbfiddle here )
Tables:
drop table t cascade constraints ;
drop table errorlog cascade constraints ;
create table t (
c1 varchar2(10)
, c2 varchar2(64) not null
) ;
comment on column t.c1 is 'this is the column comment for c1';
comment on column t.c2 is 'this is the column comment for c2';
create table errorlog (
when_ timestamp
, msg varchar2(4000)
) ;
Package spec
create or replace package P is
-- insert into T, throwing exceptions
procedure insert_( col1 varchar2, col2 varchar2 );
-- use your example SELECT, call the insert_ procedure
procedure insert_test ;
-- retrieve the column comments from user_col_comments
function fetch_comment( table_ varchar2, col_ varchar2 ) return varchar2 ;
end P ;
/
Package body
create or replace package body P is
procedure insert_( col1 varchar2, col2 varchar2 )
is
ex_value_too_large exception ; -- T.c1: varchar2(10)
ex_insert_null exception ; -- T.c2: cannot be null
v_errorcol varchar2(32) := '' ;
v_comment varchar2(128) := '' ;
v_tablename constant varchar2(32) := upper('T') ;
begin
if length( col1 ) > 10 then
v_errorcol := upper('C1') ;
raise ex_value_too_large ;
end if;
if col2 is null then
v_errorcol := upper('C2') ;
raise ex_insert_null ;
end if ;
insert into t ( c1, c2 ) values ( col1, col2 ) ;
exception
when ex_value_too_large then
dbms_output.put_line( ' ex_value_too_large @ '
|| v_errorcol || ' (' || fetch_comment( v_tablename, v_errorcol ) || ')' );
when ex_insert_null then
dbms_output.put_line( ' ex_insert_null @ '
|| v_errorcol || ' (' || fetch_comment( v_tablename, v_errorcol ) || ')' );
when others then
raise ;
end insert_ ;
procedure insert_test
is
begin
for rec_ in (
select
case
when level = 8 then ( level + 1 ) || 'qqqqqqqqqqqq'
else ( level + 2 ) || 'qqq'
end as col1
, case
when level = 7 then null
else ( level + 3 ) || 'wwwwwww'
end as col2
from dual
connect by level <= 10
) loop
insert_( rec_.col1, rec_.col2 ) ;
end loop;
commit;
end insert_test;
function fetch_comment( table_ varchar2, col_ varchar2 ) return varchar2
is
v_comment varchar2(4000) ; -- same datatype as in user_tab_comments
begin
select comments into v_comment
from user_col_comments
where table_name = table_
and column_name = col_ ;
return v_comment ;
end fetch_comment ;
end P ;
/
For testing the package code, execute the following anonymous block:
begin
P.insert_test ;
end;
/
-- output
ex_insert_null @ C2 (this is the column comment for c2)
ex_value_too_large @ C1 (this is the column comment for c1)
-- Table T contains:
SQL> select * from T;
C1 C2
3qqq 4wwwwwww
4qqq 5wwwwwww
5qqq 6wwwwwww
6qqq 7wwwwwww
7qqq 8wwwwwww
8qqq 9wwwwwww
11qqq 12wwwwwww
12qqq 13wwwwwww
In the dbfiddle, all output will be written to T and ERRORLOG, respectively. You can also use dbms_output.put_line (which is commented out in the dbfiddle) if needed. Notice that the cursor for loop in the insert_test procedure is inefficient (we could use BULK operations). Also, you need to decide where and how the exceptions are handled. As mentioned, this example is just a starting point - which will probably need lots of refinements.
| {
"pile_set_name": "StackExchange"
} |
Q:
What happened to the first three questions posted on Stack Overflow?
What happened to the first three questions posted on Stack Overflow?
https://stackoverflow.com/questions/1
https://stackoverflow.com/questions/2
https://stackoverflow.com/questions/3
I can see there are some screen grab references to the questions (and answers) in What was the first question asked that still exists on Stack Overflow?
Is there an official story anywhere?
A:
Well, the first question (and its answers) are still there, but as the question has been deleted, you need >10k reputation to see it:
| {
"pile_set_name": "StackExchange"
} |
Q:
Assocating BDD Scenarios with results of Silverlight Tests
I work with a team that uses Behaviour Driven Development(BDD) to deliver our applications. We have started delivering Silverlight applications.
I would like to associate the agreed BDD Scenarios written in plain text to the results of the automated tests for our silverlight application. So when a scenario is met in the application there is a simple report showing this mapped to the original text. This is so our stakeholders (aka product owner) can quickly gain feedback on what acceptance criteria have been tested and delivered.
Previously I have used Fitnesse and Cucumber along with xUnit/rSpec to help communication between the the product owner and the developers when using BDD to deliver web applications.
My problem is I do not see an easy way of plugging the Silverlight test framework results and the BDD scenario text using one of these reporting tools.
My Question: Has anyone delivering these kind of "reports" in a BDD project using Silverlight? If so how did you do it?
A:
If you're using the Silverlight Test Framework that ships in the Silverlight Toolkit, you unfortunately won't find any trivial extensibility points to report this kind of information back today.
| {
"pile_set_name": "StackExchange"
} |
Q:
Annihilator of image $T$ equals to $\text{ker}(T^*)$
Let $T:V\to W$ be a linear transformation, then $\text{Ann}(\text{Im}T)=\text{ker}T^*$.
How one could start to prove it?
Many thanks.
A:
$\phi\in Ann(ImT)$ iff $\phi(Tx)=0$ for all $x\in v$ iff $T^*(\phi) x=0$ for all $x\in V$ iff $\phi\in Ker(T^*)$
| {
"pile_set_name": "StackExchange"
} |
Q:
calculating the mean speed by the hour in R
I have a large Data set of cars speeds measured in a high way for one year.
the file have the following columns:
1.TimeStamp- 31/12/13 23:48:51
2.Speed- 97.6
I want to calculate the mean speed in each hour of the day, like that:
*23:00-00:00- 110.8
*00:00-01:00- 96.17
how can I do that in R?
in R I have the folowing columns:
$ TimeStamp : POSIXct, format: "2012-12-31 23:48:41
$ Speed : num 97.2
$ Date : Date, format: "2012-12-31"
$ Time :Class 'times' atomic [1:100000] 0.992 0.992 0.992 0.992 0.993 ...
.. ..- attr(*, "format")= chr "h:m:s"
I ran dput(test2[1:3,])
> dput(test2[1:3,])
structure(list(RoadId = c(12L, 12L, 12L), UnitId = c(283398L,
283398L, 283398L), TimeStamp = structure(c(1356990521, 1356990531,
1356990541), class = c("POSIXct", "POSIXt"), tzone = ""), Speed = c(97.2,
97.2, 97.2), VehicleType = c(214L, 214L, 214L)), .Names = c("RoadId",
"UnitId", "TimeStamp", "Speed", "VehicleType"), row.names = c(NA,
3L), class = "data.frame")
A:
May be this helps
res <- do.call(`data.frame`, aggregate(Speed~
cbind(Hour=format(TimeStamp,'%H')), test2, mean))
res$Hour
#Hour
# 16
#Levels: 16
res$Hour <- as.numeric(as.character(res$Hour))
with(res, plot(Hour, Speed))
| {
"pile_set_name": "StackExchange"
} |
Q:
Get the waypoint on the street instead of the original position in here maps?
I am requesting a route with the android premium sdk. Works as intened, but my waypoints for the request can be away from a street, for example the request was made with a location inside a building.
How can i get the mapped waypoints in the android SDK?
I saw something in the rest api.
waypoint": [
{
"linkId": "-1200551084",
"mappedPosition": {
"latitude": 47.0243827,
"longitude": 15.48219
},
"originalPosition": {
"latitude": 47.0243825,
"longitude": 15.48219
},
"type": "stopOver",
"spot": 0.2363636,
"sideOfStreet": "neither",
"mappedRoadName": "",
"label": "",
"shapeIndex": 0
}]
A:
You can use the Route Object to get these values.
Using Route. getRouteWaypoints(), you can then get either the RouteWaypoint getNavigablePosition() or getOriginalPosition().
| {
"pile_set_name": "StackExchange"
} |
Q:
graphlab adding variable columns from existing sframe
I have a SFrame e.g.
a | b
-----
2 | 31 4 5
0 | 1 9
1 | 2 84
now i want to get following result
a | b | c | d | e
----------------------
2 | 31 4 5 | 31|4 | 5
0 | 1 9 | 1 | 9 | 0
1 | 2 84 | 2 | 84 | 0
any idea how to do it? or maybe i have to use some other tools?
thanks
A:
Using pandas:
In [409]: sf
Out[409]:
Columns:
a int
b str
Rows: 3
Data:
+---+--------+
| a | b |
+---+--------+
| 2 | 31 4 5 |
| 0 | 1 9 |
| 1 | 2 84 |
+---+--------+
[3 rows x 2 columns]
In [410]: df = sf.to_dataframe()
In [411]: newdf = pd.DataFrame(df.b.str.split().tolist(), columns = ['c', 'd', 'e']).fillna('0')
In [412]: df.join(newdf)
Out[412]:
a b c d e
0 2 31 4 5 31 4 5
1 0 1 9 1 9 0
2 1 2 84 2 84 0
Converting back to SFrame:
In [498]: SFrame(df.join(newdf))
Out[498]:
Columns:
a int
b str
c str
d str
e str
Rows: 3
Data:
+---+--------+----+----+---+
| a | b | c | d | e |
+---+--------+----+----+---+
| 2 | 31 4 5 | 31 | 4 | 5 |
| 0 | 1 9 | 1 | 9 | 0 |
| 1 | 2 84 | 2 | 84 | 0 |
+---+--------+----+----+---+
[3 rows x 5 columns]
If you want integers/floats, you can also do:
In [506]: newdf = pd.DataFrame(map(lambda x: [int(y) for y in x], df.b.str.split().tolist()), columns = ['c', 'd', 'e'])
In [507]: newdf
Out[507]:
c d e
0 31 4 5.0
1 1 9 NaN
2 2 84 NaN
In [508]: SFrame(df.join(newdf))
Out[508]:
Columns:
a int
b str
c int
d int
e float
Rows: 3
Data:
+---+--------+----+----+-----+
| a | b | c | d | e |
+---+--------+----+----+-----+
| 2 | 31 4 5 | 31 | 4 | 5.0 |
| 0 | 1 9 | 1 | 9 | nan |
| 1 | 2 84 | 2 | 84 | nan |
+---+--------+----+----+-----+
[3 rows x 5 columns]
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I allow a "SPACE" character in an AutoComplete JavaFX uneditable ComboBox?
When I type a SPACE character in an AutoComplete ComboBox, I can get the space character to be accepted except the addEventFilter code I'm using to manage it multiplies and inserts a space for each character previously typed prior to the space. You can see a screen shot example below where 3 spaces were added after the 3 characters (ive), then 4 spaces added after I include an additional charater (t), each after typing a single SPACE, and the spaces only appear after I type the next character (e.g. 'm').
I did try this with the ContolsFX AutoComplete, but it cannot handle the uneditable ComboBox - and couldn't find anything to the contrary. In the online cases I research, it was recommended to use the ComboBox's popup skin - addEventFilter to manage the SPACE character event. In nearly all the cases it was to consume() and prevent the space from selection and closing. I did not find anything that strictly allowed the space to be entered. I've tried adding the SPACE in code prior to and after this Event Code but the addEventFilter event.consume() will remove it. The SPACE character will only appear if I manage its addition within the addEventFilter method. I've tried different events such as KeyEvent.ANY, KeyEvent.KEY_TYPED, and KeyEvent.KEY_RELEASE and read the documentation on the KeyEvent, but only KeyEvent.KEY_PRESSED seems to allow the SPACE character, it just multiplies the number of spaces, and doesn't insert until the next text character.
ComboBoxListViewSkin cbSkin = cbSkin = new ComboBoxListViewSkin(cmb);
// cmb is the ComboBox
cbSkin.getPopupContent().addEventFilter(KeyEvent.KEY_PRESSED, (event) -> {
if(event.getCode() == KeyCode.SPACE){
filter += " ";
event.consume();}
});
A:
I was able to solve my problem. The event code needed to be a part of the ComboBoxAutoComplete constructor and not part of the onKeyPressed event.
private ComboBoxListViewSkin cbSkin;
public ComboBoxAutoComplete(ComboBox<T> cmb) {
this.cmb = cmb;
cbSkin = new ComboBoxListViewSkin(cmb);
originalItems = FXCollections.observableArrayList(cmb.getItems());
cmb.setOnKeyPressed(this::handleOnKeyPressed);
cmb.setOnHidden(this::handleOnHiding);
cmb.setSkin(cbSkin);
cbSkin.getPopupContent().addEventFilter(KeyEvent.KEY_PRESSED, (event) -> {
if(event.getCode() == KeyCode.SPACE){
filter += " ";
event.consume();}
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change a Checkbox attribute on click of parent
I need small suggestion from you.
Onclick of the checkbox attribute inside that should be changed.There is also a inside the
HTML Code:
<table>
<tr>
<td class="answer"><input tabindex="4" type="checkbox" name="Dum1_4" id="Dum1_4" value="1"/></td>
<td class="answerlabel"><label for="Dum1_4" id="Dum1_4_label"><table class="sample"><tr><td><img src="/ThumbsV2/2200000999-f.png"></td></tr><tr><td><b>Product 4</b></td></tr><tr><td>Product Description 4</td></tr><tr><td><b>Price 4</b></td></tr></table></label></td>
</tr>
<tr>
<td class="answer"><input tabindex="5" type="checkbox" name="Dum1_5" id="Dum1_5" value="1"/></td>
<td class="answerlabel"><label for="Dum1_5" id="Dum1_5_label"><table class="sample"><tr><td><img src="/ThumbsV2/2200001080-f.png"></td></tr><tr><td><b>Product 5</b></td></tr><tr><td>Product Description 5</td></tr><tr><td><b>Price 5</b></td></tr></table></label></td>
</tr>
</table>
Here is my code:
$('.sample').click(function()
{
row =$this.parents("td");
row.siblings().find("input:checkbox").attr("checked","checked" );
}
});
});
Please someone help me!
A:
$('TABLE > TBODY > TR').click(function()
{
$('input:checkbox', $(this)).prop("checked", "checked");
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make NAnt send an email using a real account
First of all, I have already seen this post: nant mail issues but the only answer is not satisfactory (i.e.: doesn't work for me).
I am using NAnt to get latest version of source, upgrade version of the libraries and application, build the application, build the setups... all the usual things, I bet. I would like NAnt to send an email to some people confirming the conclusion of the build process; I've already checked the official (pretty ugly, IMHO) documentation for the task, but the example, once copied and customized, doesn't work.
This are the NAnt target and task I'm using:
<target name="sendMail" >
<mail
from="[email protected]"
tolist="[email protected];[email protected]"
subject="Subject of email"
mailhost="smtp.gmail.com"
message="Your new release is ready!">
</mail>
</target>
The error message I get is:
530 5.7.0 Must issue a STARTTLS
command first.
It looks like that the task was designed for use by an account whose provider doesn't need authentication; but what can I do if I must use an external smtp server which requires authentication (telling my boss I need an smtp server in house is not an option)?
Can anybody help/teach me?
Thanks in advance...
A:
Looking at the code currently in the nant-trunk, the nant task doesn't feature authentication.
According to this knowledge base article, it can be done even with the System.Web.Mail class which nant is currently using, but the nant task doesn't expose the necessary properties.
So to answer your question, I think you have the following choices:
add support for authentication to the current nant task via the technique described in the knowledge base article (be sure to add
"http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"
to the message fields), re-compile it and use it via the loadtasks-task
create your own email task via the Smtp client class (since the System.Web.Mail might be deprecated for a reason) and use it via the loadtasks-task.
Update:
I just changed the implementation of the mail task and submitted a patch to the NAnt guys at sourceforge. If you are interested you can download the file there, so you don't have to implement it yourself.
| {
"pile_set_name": "StackExchange"
} |
Q:
Semi-Automatic Classification Plugin Scipy Dependency Error
I've been using QGIS with the Semi-Automatic Classification plugin (SCP) at work, and am attempting to install and use it at home. Unfortunately, I am encountering an error which causes QGIS to crash when installing, disabling, or uninstalling SCP.
Upon opening QGIS 2.18.6, I get the following messages:
Semi-Automatic Classification Plugin: Please, restart QGIS for executing the Semi-Automatic Classification Plugin. Possible missing dependecies: SciPy
Semi-Automatic Classification Plugin: Please, restart QGIS for executing the Semi-Automatic Classification Plugin
From investigating the plugin's source, it looks like it is trying the following import before throwing the SciPy dependency exception:
import scipy.stats.distributions as statdistr
I tried the same import from the OSGeo4W Shell, and get the following traceback:
Taceback (most recen call last):
File "<stdin>", line 1, in <module>
File "C:\OSGEO4~1\apps\Python27\lib\site-packages\scipy\stats\__init__.py", line 334,
in <module> from .stats import *
File "C:\OSGEO4~1\apps\Python27\lib\site-packages\scipy\stats\stats.py", line 181,
in <module> import scipy.special as special
File "C:\OSGEO4~1\apps\Python27\lib\site-packages\scipy\special\__init__.py", line 546,
in <module> from ._ufuncs import *
Additionally, doing a pip list does not display scipy but does display numpy and matplotlib, the other two dependencies for the plugin.
I've attempted to reinstall QGIS and supporting apps / libraries using the advanced and express installers, but run into the same problem each time I try to install SCP. The error also causes QGIS to crash and write a minidump on close. I'm also using Windows 10.
I am able to import scipy from the OSGeo4W Shell, but any module imports do not work, i.e. import scipy.stats or import scipy.linalg
How can I resolve this specific Scipy dependency issue within QGIS?
A:
Was able to resolve the issue by forgoing the installation of Scipy through the OSGeo4W advanced installer, and instead installing it directly via Pip (installed via OSGeo4W) and a Scipy .whl gotten from:
http://www.lfd.uci.edu/~gohlke/pythonlibs/
I grabbed:
numpy‑1.12.1+mkl‑cp27‑cp27m‑win_amd64.whl and
scipy‑0.19.0‑cp27‑cp27m‑win_amd64.whl
Then used the OSGeo4W Shell to install directly:
pip install "C:\path\to\numpy‑1.12.1+mkl‑cp27‑cp27m‑win_amd64.whl"
pip install "C:\path\to\scipy‑0.19.0‑cp27‑cp27m‑win_amd64.whl"
I wanted to make sure that the Numpy installation was also correct because it is a dependency for Scipy, so that's the reason for installing both.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I can get path for dict in dict in Python?
There is dictionary which is generated by adding some data:
some_dict = {'some_value1': {}, 'dict1': {'qwerty': None, 'bar': {}}}
I know that I can add there some data by using update method:
some_dict['dict1']['bar'].update({'some_key': value})
But what if a part of the code doesn't know correct way to update 'bar'?
like:
some_dict[???]['bar'].update({'some_key': value})
How can I update it correctly?
A:
As far as I know, there is no standard Python function to do what you want. You will need to implement some kind of search algorithm yourself. Broadly speaking you will have the choice between a depth-first search or breadth-first search strategy.
A possible implementation of the former would be something along the lines of:
some_dict = {'some_value1': {}, 'dict1': {'qwerty': None, 'bar': {}}}
def get_nested_dict(d, name):
stack = [d]
while stack:
for k, v in stack.pop().items():
if k == name:
return v
if isinstance(v, dict):
stack.append(v)
print(some_dict)
get_nested_dict(some_dict, 'bar')['new'] = 1
print(some_dict)
Producing:
{'some_value1': {}, 'dict1': {'qwerty': None, 'bar': {}}}
{'some_value1': {}, 'dict1': {'qwerty': None, 'bar': {'new': 1}}}
| {
"pile_set_name": "StackExchange"
} |
Q:
Build an entity, based on a defined model by comparing table column to entity names and building
Can I optimize the BuildEntity method more?
protected IEnumerable<GroupTitle> BuildProductGroup()
{
var productGroups = new List<GroupTitle>();
using (var connection = new SqlConnection(_dbConnection))
using (var command = new SqlCommand(_getProductGroups, connection))
{
connection.Open();
command.CommandType = CommandType.StoredProcedure;
using (var reader = command.ExecuteReader())
while(reader.Read())
{
var productGroup = new GroupTitle();
BuildEntity<GroupTitle>(reader, ref productGroup);
productGroups.Add(productGroup);
}
}
return productGroups;
}
protected TEntity BuildEntity<TEntity>(IDataReader reader, TEntity model)
{
var type = model.GetType();
var table = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();
foreach (var column in table)
{
var matchColumnToProperty = type.GetProperties().FirstOrDefault(property => String.Compare(property.Name, column, true) == 0);
if (matchColumnToProperty != null && !reader.IsDBNull(reader.GetOrdinal(matchColumnToProperty.Name)))
matchColumnToProperty.SetValue(model, reader.GetValue(reader.GetOrdinal(matchColumnToProperty.Name)), null);
}
return model;
}
A:
I ended up improving performance and tidying the code up a bit by doing the following:
public IList<TEntity> List<TEntity>(string query, CommandType commandType, params SqlParameter[] parameters) where TEntity : class, new()
{
using (var connection = new SqlConnection(dbConnection))
using (var command = new SqlCommand(query, connection))
{
connection.Open();
command.CommandType = commandType;
foreach (var parameter in parameters)
command.Parameters.Add(parameter);
return BuildEntity(command, new TEntity());
}
}
Then BuildEntity would be as follows:
public List<TEntity> BuildEntity<TEntity>(SqlCommand command, TEntity entity) where TEntity : class, new()
{
var collection = new List<TEntity>();
var properties = GetColumnDataFromProperty<TEntity>();
using (var reader = command.ExecuteReader())
while(reader.Read())
collection.Add(MapEntity<TEntity>(reader, properties));
return collection;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Array.prototype.forEach() not working when called on a proxy with a get handler
I have the following proxy:
const p = new Proxy({
[Symbol.iterator]: Array.prototype.values,
forEach: Array.prototype.forEach,
}, {
get(target, property) {
if (property === '0') return 'one';
if (property === '1') return 'two';
if (property === 'length') return 2;
return Reflect.get(target, property);
},
});
It's an array-like object, because it has numeric properties and the length property specifying the amount of elements. I can iterate it using a for...of loop:
for (const element of p) {
console.log(element); // logs 'one' and 'two'
}
However, the forEach() method is not working.
p.forEach(element => console.log(element));
This code doesn't log anything. The callback function is never called. Why isn't it working and how can I fix it?
Code snippet:
const p = new Proxy({
[Symbol.iterator]: Array.prototype.values,
forEach: Array.prototype.forEach,
}, {
get(target, property) {
if (property === '0') return 'one';
if (property === '1') return 'two';
if (property === 'length') return 2;
return Reflect.get(target, property);
},
});
console.log('for...of loop:');
for (const element of p) {
console.log(element);
}
console.log('forEach():');
p.forEach(element => console.log(element));
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.16.0/polyfill.min.js"></script>
A:
One of the differences between a for...of loop and Array.prototype.forEach() is that the former uses the @@iterator property to loop over the object, while the latter iterates the properties from 0 to length, and executes the callback only if the object has that property. It uses a [[HasProperty]] internal method, which in this case returns false for every array element.
The solution is to add also the has() handler, which will intercept the [[HasProperty]] calls.
Working code:
const p = new Proxy({
[Symbol.iterator]: Array.prototype.values,
forEach: Array.prototype.forEach,
}, {
get(target, property) {
if (property === '0') return 'one';
if (property === '1') return 'two';
if (property === 'length') return 2;
return Reflect.get(target, property);
},
has(target, property) {
if (['0', '1', 'length'].includes(property)) return true;
return Reflect.has(target, property);
},
});
p.forEach(element => console.log(element));
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.16.0/polyfill.min.js"></script>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to vertically center an element when using WearableDrawerLayout?
I am using a WearableDrawerLayout, and testing on a emulator with a chin. I am trying to have an element vertically centered. Instead what I see is that the element is centered in the area of "the screen minus the chin" - i.e. it is a bit shifted towards the top of the screen.
What I see:
What I should see:
From what I can tell in the (non public?) source of WearableDrawerLayout I think this is due to this bit:
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
this.mSystemWindowInsetBottom = insets.getSystemWindowInsetBottom();
if(this.mSystemWindowInsetBottom != 0) {
MarginLayoutParams layoutParams = (MarginLayoutParams)this.getLayoutParams();
layoutParams.bottomMargin = this.mSystemWindowInsetBottom;
this.setLayoutParams(layoutParams);
}
return super.onApplyWindowInsets(insets);
}
What can I do to not have this problem?
Edit: here is another example of layout that demonstrates the issue:
As you can see, the chin is not included in the available area, which means the BoxInsetLayout has a height smaller than it should. As a consequence, its button children are too "high" - they're not bottom aligned.
Here's my edit (sorry about my Gimp skills), that shows the round display, and also where the BoxInsetLayout and buttons should go.
A:
There are a few ways to accomplish this. Here's a quick and easy one...
First, the layout that I used for testing:
<android.support.wearable.view.BoxInsetLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/box">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/close_button"
android:layout_centerInParent="true"
android:background="#0000"/>
</RelativeLayout>
</android.support.wearable.view.BoxInsetLayout>
It's a minimal example based on BoxInsetLayout, but the principle should scale to more complex layouts. I'm simply using a RelativeLayout for easy centering within the screen, and drawable/close_button was just a nice round graphic I had sitting around.
As is, the above layout should center in any square or fully round screen:
To also center it in a "flat tire" screen, we just need to tweak the root layout a bit. Here's my Java code to do so:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics metrics = getResources().getDisplayMetrics();
findViewById(R.id.box).getLayoutParams().height = metrics.widthPixels;
}
It's crude but effective: set the height of the BoxInsetLayout equal to the screen's width. The layout will then center within that height. Here it is on a "flat tire" screen:
Of course, you'll need to leave sufficient room at the bottom of your layout that your content isn't cropped, but that's unavoidable with a screen that's "missing" an area at the the bottom. If you have any elements using android:layout_alignBottom, you may need to compensate their position manually, or find another way to position them.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make a separate thread on each row of listview. GC_FOR_ALLOC
I can't understand how it should be, in my model-class i
am using runnable that counts time and sending it to handler which was initialized in MainActivity. I suppose, what i must using the Thread class with Handler, but where i must initialize Handler, in adapter? I trying and catch ANR message;
In logcat often write something like this:(even if listview is empty)
The application may be doing too much work on its main thread.
GC_FOR_ALLOC freed 795K, 56% free 9998K/22280K, paused 11ms, total 12ms
Here is the fragment of code of my model:
private String name;
private Boolean isStart=false, isFinished=false;
private Long elapsedTime=0L,seconds=0L,hours=0L,minutes=0L,lastPause=0L,updateTime=0L,startTime=0L,days=0L,limitTime=0L;
private Runnable updateTimeThread=new Runnable() {
@Override
public void run() {
if(isStart && startTime!=0) {
if(elapsedTime!=0 && updateTime==0)
lastPause=elapsedTime;
updateTime = ((System.currentTimeMillis() - startTime) + lastPause);
seconds = updateTime / 1000;
minutes = seconds / 60;
hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 24;
elapsedTime=updateTime;
holder.days.setText(String.format("%04d", days));
holder.hours.setText(String.format("%02d", hours));
holder.minutes.setText(String.format("%02d", minutes));
holder.seconds.setText(String.format("%02d", seconds));
if(limitTime!=0 && elapsedTime>limitTime) {
isFinished = true;
holder.stop.setVisibility(View.GONE);
holder.textFinish.setVisibility(View.VISIBLE);
holder.limDay.setVisibility(View.GONE);
holder.limMin.setVisibility(View.GONE);
holder.limHours.setVisibility(View.GONE);
holder.textLimit.setVisibility(View.GONE);
RemindMe.db.execSQL(Util.concat("UPDATE trackers SET isFinish=1, elapsedTime=",limitTime," WHERE _id=",getId()));
}
if(!isFinished)
MainActivity.handler.post(this);
}
}
};
MyAdapter.ViewHolder holder;
public MyAdapter.ViewHolder getHolder() {
return holder;
}
Fragment of Adapter
@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final Tracker tracker = trackerList.get(position);
final Runnable updateTimeThread=tracker.getRunnable();
ViewHolder holder;
if(row == null){
holder = new ViewHolder();
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item,parent,false);
holder.name = (TextView)row.findViewById(R.id.tvName);
holder.days = (TextView)row.findViewById(R.id.tvDays);
holder.hours = (TextView)row.findViewById(R.id.tvHours);
holder.minutes = (TextView)row.findViewById(R.id.tvMinutes);
holder.seconds = (TextView)row.findViewById(R.id.tvSeconds);
holder.start = (Button)row.findViewById(R.id.btStart);
holder.stop = (Button)row.findViewById(R.id.btStop);
holder.textFinish = (TextView)row.findViewById(R.id.txtFinish);
holder.textLimit = (TextView)row.findViewById(R.id.txtLimit);
holder.limDay = (TextView)row.findViewById(R.id.limDay);
holder.limHours = (TextView)row.findViewById(R.id.limHours);
holder.limMin = (TextView)row.findViewById(R.id.limMin);
row.setTag(holder);
}else {
holder = (ViewHolder) row.getTag();
}
//изнальначальный вид
final ViewHolder finalHolder = holder;
finalHolder.start.setVisibility(View.VISIBLE);
finalHolder.stop.setVisibility(View.GONE);
finalHolder.name.setText(tracker.getName());
if(tracker.getElapsedTime()!=0 && tracker.getLimitTime()==0){//если прошедшее время !=0 и таймер без лимита
long days = tracker.getElapsedTime()/86400000;
long hours = (tracker.getElapsedTime()/360000)%24;
long minutes = (tracker.getElapsedTime()/60000)%60;
long seconds = (tracker.getElapsedTime()/1000)%60;
if(days!=0)
finalHolder.days.setText(Util.concat(days<=9?0:"",days,":"));
if(hours!=0)
finalHolder.hours.setText(Util.concat(hours <=9 ?0:"",hours,":"));
if(minutes!=0)
finalHolder.minutes.setText(Util.concat(minutes<=9?0:"",minutes,":"));
if(seconds!=0)
finalHolder.seconds.setText(Util.concat(seconds<=9?0:"",seconds));
}
if(tracker.getIsFinished()){//если таск закончен, дошел до лимита
long hours = (tracker.getLimitTime()/360000)%24;
long minutes = (tracker.getLimitTime()/60000)%60;
long seconds = (tracker.getLimitTime()/1000)%60;
finalHolder.start.setVisibility(View.GONE);
finalHolder.textFinish.setVisibility(View.VISIBLE);
finalHolder.stop.setVisibility(View.GONE);
if(seconds!=60)
finalHolder.seconds.setText(Util.concat(seconds<=9?0:"",seconds));
if(minutes!=60)
finalHolder.minutes.setText(Util.concat(minutes<=9?0:"",minutes,":"));
if(hours!=24)
finalHolder.hours.setText(Util.concat(hours <= 9 ? 0 : "", hours, ":"));
}
if(tracker.getLimitTime()!=0 && !tracker.getIsFinished()){//если установлен лимит, но еще не дошел до конца
long days = tracker.getLimitTime()/86400000;
long hours = (tracker.getLimitTime()/3600000)%24;
long minutes = (tracker.getLimitTime()/60000)%60;
finalHolder.textLimit.setVisibility(View.VISIBLE);
if(days!=0) {
finalHolder.limDay.setVisibility(View.VISIBLE);
finalHolder.limDay.setText("" + (days <= 9 ? "0" + days : days) + ":");
}
if(hours!=0) {
finalHolder.limHours.setVisibility(View.VISIBLE);
finalHolder.limHours.setText(Util.concat(hours <= 9 ? 0 : "", hours, ":"));
}
if(minutes!=0) {
finalHolder.limMin.setVisibility(View.VISIBLE);
finalHolder.limMin.setText(Util.concat(minutes<=9?0:"",minutes,":"));
}
if(days==0 && hours==0 & minutes!=0){
finalHolder.limMin.setText(Util.concat(minutes,"minutes"));
}
}
if(tracker.getIsStart()) {//если был стартован
finalHolder.start.setVisibility(View.GONE);
finalHolder.stop.setVisibility(View.VISIBLE);
}
onSavedList.set(position,tracker);
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btStart:
tracker.setStartTime(System.currentTimeMillis());
tracker.setIsStart(true);
tracker.setHolder(finalHolder);
finalHolder.start.setVisibility(View.GONE);
finalHolder.stop.setVisibility(View.VISIBLE);
MainActivity.handler.post(updateTimeThread);
break;
case R.id.btStop:
tracker.setLastPause(tracker.getUpdateTime());
MainActivity.handler.removeCallbacks(updateTimeThread);
finalHolder.stop.setVisibility(View.GONE);
finalHolder.start.setVisibility(View.VISIBLE);
tracker.setIsStart(false);
break;
}
}
};
finalHolder.start.setOnClickListener(onClickListener);
finalHolder.stop.setOnClickListener(onClickListener);
return row;
}
And MainActivity
public class MainActivity extends ActionBarActivity implements LoaderManager.LoaderCallbacks<Cursor>,View.OnClickListener {
ListView listView;
MyAdapter adapter;
static Handler handler;
SQLiteDatabase db;
List<Tracker> trackerList;
static final String LOG_TAG = "myTag";
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
db = RemindMe.db;
trackerList = Tracker.getListAll(db);
listView = (ListView) findViewById(R.id.listView);
String[] from = {Tracker.COL_NAME, Tracker.COL_ELAPSED_TIME, Tracker.COL_ELAPSED_TIME, Tracker.COL_ELAPSED_TIME, Tracker.COL_ELAPSED_TIME};
int[] to = {R.id.tvName, R.id.tvDays, R.id.tvHours, R.id.tvMinutes, R.id.tvSeconds};
adapter = new MyAdapter(this, R.layout.list_item, Tracker.getAll(db), from, to, 0,trackerList);
listView.setAdapter(adapter);
getSupportLoaderManager().initLoader(1, null, this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(this, AddTrack.class);
startActivity(intent);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new TrackerLoader(this, db);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
static class TrackerLoader extends android.support.v4.content.CursorLoader {
SQLiteDatabase db;
TrackerLoader(Context context, SQLiteDatabase db) {
super(context);
this.db = db;
}
@Override
public Cursor loadInBackground() {
return Tracker.getAll(db);
}
}
@Override
protected void onStop() {
super.onStop();
Log.d(LOG_TAG, "onStop " + hashCode());
}
@Override
protected void onPause() {
super.onPause();
Log.d(LOG_TAG, "onPause "+hashCode());
for (int i = 0; i <adapter.getCount() ; i++) {
trackerList.get(i).update(db);
}
}
@Override
protected void onResume() {
super.onResume();
Log.d(LOG_TAG, "onResume "+hashCode());
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(LOG_TAG, "onDestroy "+hashCode());
}
}
Add task activity:
Tracker tracker;
SQLiteDatabase db;
EditText name,limitHours,limitMinute;
RadioButton limitTime,unlimitTime;
RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_track);
name = (EditText)findViewById(R.id.edit_name);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
limitHours = (EditText)findViewById(R.id.edit_Hours);
limitMinute = (EditText)findViewById(R.id.edit_Min);
limitTime = (RadioButton)findViewById(R.id.rdbLimit);
unlimitTime = (RadioButton)findViewById(R.id.rdbUnlimit);
tracker = new Tracker();
db = RemindMe.db;//it's db.getWritableDatabase();
}
A:
Solution was very simple, in model class put Thread class which will counts time, sending to Handler some int value, just to turn it on. The handler will change the UI uses the ViewHolder object which will be setted to each item in the listview in getView() adapter's method.
To adapter constructor I send a static List (in getView() method I pull the needed object and work with it), this is very important because, if the list is not static, after the leave Activity with listview and re-entry will be the creation of new instances activity / adapter / models.
Here is the fragment of my model class:
private String name;
private Boolean isStart=false, isFinished=false;
private Long elapsedTime=0L,seconds=0L,hours=0L,minutes=0L,lastPause=0L,updateTime=0L,startTime=0L,days=0L,limitTime=0L;
class TrackerThread extends Thread{
public TrackerThread() {
super();
}
@Override
public void run() {
super.run();
try {
while (isStart && !isInterrupted()){
if (isStart && startTime != 0) {
if (elapsedTime != 0 && updateTime == 0)
lastPause = elapsedTime;
updateTime = ((System.currentTimeMillis() - startTime) + lastPause);
seconds = updateTime / 1000;
minutes = seconds / 60;
hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 24;
elapsedTime = updateTime;
handler.sendEmptyMessage(1);//its just for run Handler
if(limitTime!=0 && elapsedTime > limitTime) {
interrupt();
}else
sleep(1000);
}
}
}catch (Exception ex){
ex.printStackTrace();
}
}
}
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
holder.days.setText(String.format("%04d",days));
holder.hours.setText(String.format("%02d", hours));
holder.minutes.setText(String.format("%02d", minutes));
holder.seconds.setText(String.format("%02d", seconds));
if(limitTime!=0 && elapsedTime>limitTime) {
isFinished = true;
holder.stop.setVisibility(View.GONE);
holder.textFinish.setVisibility(View.VISIBLE);
holder.limDay.setVisibility(View.GONE);
holder.limMin.setVisibility(View.GONE);
holder.limHours.setVisibility(View.GONE);
holder.textLimit.setVisibility(View.GONE);
RemindMe.db.execSQL(Util.concat("UPDATE trackers SET isFinish=1, elapsedTime=",limitTime," WHERE _id=",getId()));
}
return true;
}
});
Here is the getView() adapter:
@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final Tracker tracker = trackerList.get(position);
final Thread thread = tracker.getThread();
ViewHolder holder;
long days,hours,minutes,seconds;
long eDays,eHours,eMins,eSecs;
if(row == null){
holder = new ViewHolder();
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item,parent,false);
holder.name = (TextView)row.findViewById(R.id.tvName);
holder.days = (TextView)row.findViewById(R.id.tvDays);
holder.hours = (TextView)row.findViewById(R.id.tvHours);
holder.minutes = (TextView)row.findViewById(R.id.tvMinutes);
holder.seconds = (TextView)row.findViewById(R.id.tvSeconds);
holder.start = (ButtonFloatSmall)row.findViewById(R.id.btStart);
holder.stop = (ButtonFloatSmall)row.findViewById(R.id.btStop);
holder.textFinish = (TextView)row.findViewById(R.id.txtFinish);
holder.textLimit = (TextView)row.findViewById(R.id.txtLimit);
holder.limDay = (TextView)row.findViewById(R.id.limDay);
holder.limHours = (TextView)row.findViewById(R.id.limHours);
holder.limMin = (TextView)row.findViewById(R.id.limMin);
row.setTag(holder);
}else {
holder = (ViewHolder) row.getTag();
}
//изнальначальный вид
final ViewHolder finalHolder = holder;
finalHolder.start.setVisibility(View.VISIBLE);
finalHolder.stop.setVisibility(View.GONE);
finalHolder.name.setText(tracker.getName());
if(tracker.getElapsedTime()!=0 && tracker.getLimitTime()==0){//если прошедшее время !=0 и таймер без лимита
days = tracker.getElapsedTime()/86400000;
hours = (tracker.getElapsedTime()/3600000)%24;
minutes = (tracker.getElapsedTime()/60000)%60;
seconds = (tracker.getElapsedTime()/1000)%60;
if(days!=0)
finalHolder.days.setText(Util.concat(days <= 9 ? 0 : "", days));
if(hours!=0)
finalHolder.hours.setText(Util.concat(hours <=9 ?0:"",hours));
if(minutes!=0)
finalHolder.minutes.setText(Util.concat(minutes<=9?0:"",minutes));
if(seconds!=0)
finalHolder.seconds.setText(Util.concat(seconds<=9?0:"",seconds));
}
if(tracker.getIsFinished()){//если таск закончен, дошел до лимита
hours = (tracker.getLimitTime()/3600000)%24;
minutes = (tracker.getLimitTime()/60000)%60;
seconds = (tracker.getLimitTime()/1000)%60;
finalHolder.start.setVisibility(View.GONE);
finalHolder.textFinish.setVisibility(View.VISIBLE);
finalHolder.stop.setVisibility(View.GONE);
if(seconds!=60)
finalHolder.seconds.setText(Util.concat(seconds<=9?0:"",seconds));
if(minutes!=60)
finalHolder.minutes.setText(Util.concat(minutes<=9?0:"",minutes));
if(hours!=24)
finalHolder.hours.setText(Util.concat(hours <= 9 ? 0 : "", hours));
}
if(tracker.getLimitTime()!=0 && !tracker.getIsFinished()){//если установлен лимит, но еще не дошел до конца
days = tracker.getLimitTime()/86400000;
hours = (tracker.getLimitTime()/3600000)%24;
minutes = (tracker.getLimitTime()/60000)%60;
finalHolder.textLimit.setVisibility(View.VISIBLE);
finalHolder.limHours.setVisibility(View.VISIBLE);
finalHolder.limDay.setVisibility(View.VISIBLE);
finalHolder.limMin.setVisibility(View.VISIBLE);
finalHolder.limDay.setText(Util.concat(days <= 9 ? 0 : "", days, ":"));
finalHolder.limHours.setText(Util.concat(hours <= 9 ? 0 : "", hours, ":"));
finalHolder.limMin.setText(Util.concat(minutes<=9?0:"",minutes));
eDays = (tracker.getElapsedTime() / 86400000);
eHours = (tracker.getElapsedTime()/3600000)%24;
eMins = (tracker.getElapsedTime()/60000)%60;
eSecs = (tracker.getElapsedTime()/1000)%60;
if(eSecs!=0)
finalHolder.seconds.setText(Util.concat(eSecs<=9?0:"",eSecs));
if(eMins!=0)
finalHolder.minutes.setText(Util.concat(minutes<=9?0:"",eMins));
if(eHours!=0)
finalHolder.hours.setText(Util.concat(hours<= 9 ? 0 : "", eHours));
if(eSecs!=0)
finalHolder.days.setText(Util.concat(days<= 9 ? 0 : "", eDays));
}else {
finalHolder.textLimit.setVisibility(View.GONE);
finalHolder.limHours.setVisibility(View.GONE);
finalHolder.limDay.setVisibility(View.GONE);
finalHolder.limMin.setVisibility(View.GONE);
}
if(tracker.getIsStart() && !tracker.getIsFinished()) {//если был стартован
finalHolder.start.setVisibility(View.GONE);
finalHolder.stop.setVisibility(View.VISIBLE);
}
tracker.setHolder(finalHolder);
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btStart:
tracker.setStartTime(System.currentTimeMillis());
tracker.setIsStart(true);
tracker.setHolder(finalHolder);
finalHolder.start.setVisibility(View.GONE);
finalHolder.stop.setVisibility(View.VISIBLE);
if(tracker.getUpdateTime()==0)
thread.start();
else
tracker.getThread().start();
break;
case R.id.btStop:
tracker.setLastPause(tracker.getUpdateTime());
finalHolder.stop.setVisibility(View.GONE);
finalHolder.start.setVisibility(View.VISIBLE);
tracker.setIsStart(false);
break;
}
}
};
finalHolder.start.setOnClickListener(onClickListener);
finalHolder.stop.setOnClickListener(onClickListener);
return row;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How does a Braille siddur work?
A member of our minyan has a degenerative vision problem and has, for a time, been using a home-made very-large-print siddur. After an absence, she returned this Shabbat with a guide dog and said she can no longer use the siddur. She said the stuff she has memorized and listened to the rest. I've started to work with her to help her learn/memorize more (and we'll get recordings), which helps some, but that's not an ideal solution. I mean, being able to do the Shabbat t'filah from memory is helpful, but it doesn't help with seasonal changes, and memorizing the whole service is a big task. What she really needs, I suspect, is a Braille siddur.
But does her knowledge of standard Braille help with Hebrew? I know that it's possible to have a Braille siddur, because I once saw somebody using one, but I didn't ask him about it at the time. Do they transliterate the Hebrew, so you use the Braille alphabet you already know? Or is there a scheme of writing Hebrew in Braille that requires the reader to learn a new Braille alphabet? I got the sense in talking with her that she's probably not ready to learn a second Braille system yet (she's still learning the first).
I'd like to help her get the best tools to be able to participate in the minyan. But before I approach the siddur publisher to ask about a Braille edition, I want to know if that would actually be helpful to somebody who only knows "regular" Braille for the English language. And that leads me to the question: how do Hebrew texts get set in Braille, linguistically speaking?
(This question arises out of a Jewish situation, but I recognize that it might be borderline here as it's about language (in a way) and publishing. If people think it's off-topic, please speak up.)
A:
Being blind myself, I can more specifically address Hebrew Braille and how siddurim work. As the first answer says, a person who knows English Grade 2 braille does not need to start from scratch, because there are many similarities. However, it is not transliteration; the Hebrew letters are represented character for character, with the vowels, when used, following the consonants, nut under them. Hebrew, as any other script, and even music notation, is written from left to right in braille. Most of the consonants correspond to their English equivalents, with some exceptions. For example, the Vav is represented by the symbol that is the W in english (the symbol for English V is used for Vet), the Chet is X, the Tav is an inverted T (which in English Grade 2 is the contraction for OU. Most of the vowels are similar to english vowels, but some are different.
As far as the siddurim themselves are concerned, they are usually in many volumes, and the ones produced by the Jewish Braille Institute typically have the Hebrew text on the right side of the binding, and the English on the left The specially made Sidurim from CSB Care, and the ones that come from Mesillah in Israel do not have English, and the instructions are usually in unvoweled Hebrew. In my opinion, the representation of the entire Sidur page for page is not always ideal. The Birnbaum Siddur and Machzor provided with JBI often, especially on holidays, require you to have several volumes in front of you, In one point, on Yom Kippur, it is necessary to switch from one volume to another in the middle of the silent Amidah. The Artscroll Siddur, also provided by JBI, tries to set up each volume to have all that is needed. It does not always succeed, as Shacharis has many parts to it, and with English translation included, it cannot fit into one volume. My first preference is those provided by CSB Care or by Mesillah, which have no English, and can fit even an entire Morning Service in one volume. But I only state this as my opinion, as English is sometimes a necessity for others. In addition, braille Siddurim are in general bulky, and sometimes slow the user down, especially in a fast-paced Minyan. I have resorted to memorizing as much as possible.
A:
I have a friend who is blind. Hebrew braille does not have its own alphabet, but rather uses the same symbols that English braille does. Also, text runs in the same direction as English letters (see the first paragraph of the aforementioned Wikipedia article) -- which I can imagine might be confusing to someone who used to read Hebrew in the original right-to-left direction.
This also means that a new braille system needs to be learned (though not necessarily a new alphabet, which could be good and bad....), in the case of your friend. Sorry :(
(I suppose the reasoning may be that since Hebrew or English text is not immediately recognizable to the blind as it is to sighted people, all text is read in the same direction and understood to be Hebrew or English based on context and / or page titles.)
My friend gets his siddurim and chumashim from CSB CARE, although he also has a computer with a wider library of sefarim on it, equipped with a refreshable braille display.
Also, while I haven't heard about them from my friend, the Jewish Braille Institute looks like a good resource. (Kudos to sabbahillel for pointing them out)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to implode the foreach loop values?
I am trying to implode the for each loop to get results like this
["86","87","88"]
Code I am using to achieve results as follows
$tags = [];
$tagsData = $this->Constant_model->getDataOneColumn('snippets_tags', 'snippet_id', $id);
foreach ($tagsData as $data) {
$tag_data = $data->tag_id;
array_push($tags, $tag_data );
}
A:
Use json_encode() to output that format:
echo json_encode($tags);
| {
"pile_set_name": "StackExchange"
} |
Q:
Request bypasses spring security filter
Request of : /myProjectName/person/myProfile/
is ignored(ie I can access it when I should not) by:
<security:intercept-url pattern="/person/myProfile" access="isAuthenticated()"/>
However if I write:
<security:intercept-url pattern="/person/**" access="isAuthenticated()"/>
it works.
I have controller with handler mapping:
@RequestMapping("/person")
and inside of this controller I have method with handler mapping:
@RequestMapping(value= "/myProfile")
I don't understand it at all. I don't want to put "/person/**" as I will restrict other handler methods which should be available to anonymous. :-(
A:
The issue was with understanding requests.
First: case does not matter as it is lowercased automatically unless explicitly stated not to.
Second: if you are control freak like me and like to protect every possible request manually make sure to have distinction between /request and /request/ as Spring security treat them separately(allowing second) - if we write...
<security:intercept-url pattern="/request" access="isAuthenticated()"/>
HOWEVER if we write:
<security:intercept-url pattern="/request/**" access="isAuthenticated()"/>
We protect both types, so in my case I should've put
<security:intercept-url pattern="/person/myProfile/**" access="isAuthenticated()"/>
Good day and be careful ;-) mine was especially ugly as it started to access fields that would throw exception if access was unauthorised.
| {
"pile_set_name": "StackExchange"
} |
Q:
Powershell copying subfolders only
I'm needing to copy the subfolders to another location.
Folder1
-subfolder1
-subfolder2
Folder2
and need it like...
Folder1
-subfolder1
-subfolder2
I've used this script ...
Copy-Item -LiteralPath '\ipaddress\Exports' -Destination '\ipaddress\Exports2' -Recurse -Filter {PSIsContainer -eq $true}
I was hoping to get the subfolders but instead I get the main folder with subfolders underneath...
Folder1
-subfolder1
-subfolder2
Folder2
Folder1
-subfolder1
-subfolder2
A:
If you also want to include files directly under Folder1:
Copy-Item .\Folder1\* -Recurse -Destination .\Folder2\
If not:
Get-ChildItem -Directory .\Folder1\ | Copy-Item -Destination .\Folder2\ -Recurse
| {
"pile_set_name": "StackExchange"
} |
Q:
If Statement when x is near a value
I am trying to solve the numerical equation:
sin^2(x)tan(x) = 0.499999
Using a while loop in C.
However I was only able to get program to print an answer if I rounded to 0.5. This led me to thinking, is there a way of writing:
For(x=0;x<=360;x=x+0.001)
{ y=f(x)
If(y **is near x**(e.g. Within 1 percent) )
Do something etc.
}
Is there a way of telling the computer to execute a task if the value is sufficiently near. Such as in this if statement?
Thank you.
A:
Use a relative difference, such as:
#include <math.h>
static inline double reldiff(double x, double y)
{
return fabs(x - y) / fmax(fabs(x), fabs(y));
}
Now your test becomes:
if (reldiff(x, y) < 0.01) // 1% as requested
| {
"pile_set_name": "StackExchange"
} |
Q:
Selecting a subclass at instantiation in Python
I would like to choose a subclass at instantiation to select specific attributes from certain classes. I've worked out the following:
Code
class Foo:
a = "foo"
def __init__(self, dtype=Bar):
self.__class__ = dtype
class Bar:
b = "bar"
class Baz(Bar):
c = "baz"
Demo
Foo(dtype=Bar).b
# 'bar'
Foo(dtype=Baz).b
# 'bar'
Foo(dtype=Baz).c
# 'baz'
This gives the desired result, selecting specific attributes from Bar while optionally extending features with Baz. Unlike subclassing however, we have no access to Foo's attributes.
Foo(dtype=Baz).a
# AttributeError: 'Baz' object has no attribute 'a'
There are occasions when not all attributes are desired, so subclassing Foo(Baz) is not preferred.
What's the idiomatic analog to accomplish this in Python?
A:
Why create an instance of Foo in the first place if you really want an instance of Bar or Baz? Instead, make Foo a factory for instance of Bar and Baz.
class Bar:
b = "bar"
class Baz(Bar):
c = "baz"
class Foo:
a = "foo"
def __new__(cls, dtype=Bar):
return dtype()
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I pass data between states with angular ui-router?
I originally did not intend on doing the project with ui-router (just got to know about it 2 days ago), so I'm quite new at this.
What I have for this issue is :
Template for list of images, shown using ng-repeat, and getting img-src from a service called in the controller. The service gets the source from a json file.
Template for image editor. The controller for this should get the image source of the image that was clicked in the image list.
How do I pass the image source from one state (the image list) to the another state (the image editor)?
I was using a service to do that when I was assuming that I won't use ui-router and its states. How do I do this with states?
A:
So, I found a simple and efficient way to pass data, and this has worked for all of my cases till now. (including scenarios different from the one mentioned in the original question)
In the controller of the first state, state1, I can just call the function
$state.go('state2', {id: self.value} );
And in state2, I can obtain the value by the following code:
this.state2value = $state.params.id;
So can pass value from one state to another, and retrieve it through state params.
Note: you should inject $state, and $stateParams into both controllers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Recommended way to work offline with TFS having specific constraints?
We sometimes face the issue that individual colleagues of our team need to work offline with TFS.
This may happen if they have to debug their code on the customer site where possibly no internet connection is available.
Is there any suggested way to work offline and to check-in the changes later when the internet connection is available (f. e. if they are back in the office)?
In our case the following conditions are given and can unfortunately not be changed:
we have to use a "Server Workspace" and cannot switch to a "Local Workspace" in the TFS Collection Workspace Settings (usually we work in the office having an internet connection and we want to use the feature "GetLatest on CheckOut")
we have to use the TFVC repository and cannot switch to Git in the team project
as far as I know, it is not possible to use and synchronize two different repositories (TFVC and Git) in one Team Project
if this would be possible, the group of people sometimes leaving the office could use Git and the remaining ones could use TFVC
since we do not work with "Solutions" but only with version controlled files, the "Go Offline" option of the Solution Explorer is also not an option.
A:
Use git-tfs and all your developers will be happy to go fix bugs on the customer site ;-)
They will even gain a better local workflow!
A:
You can't have it both ways. Centralized version control is designed from the ground up to require a connection to the server.
Either you use a distributed version control system (like Git) or you start using local workspaces, which provide some quality-of-life offline work features.
The people that need to work offline can have local workspaces, while everyone else continues to use server workspaces. They could even convert their server workspaces to local workspaces right before leaving the office, then turn them back into server workspaces when they return.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to explore styling in android
I'm trying to theme my app in Android. However, each widget is an excrutiating pain in itself: I have to search for theming that particular widget and then create a style that hopefully derives from same style that widget uses.
Of course, answers about theming a particular widget don't always contain info about base style, just the particular colors.
So, instead of accepting fish to eat, can you teach me to fish instead?
How do I interpret those ObtainStyledAttributes() calls in widget constructors and extract styles from that? How do I recurse that?
In particular, can you walk me through AlertDialog button color? What style defines lollipop flat button + teal text color? How do I get to that style if I start from AlertDialog source and ObtainStyledAttributes call?
A:
I find that styling is about sherlocking your way through the framework. The what (almost always) comes from the widget's implementation. The where, I find is all over the place. I will try my best to explain the process through your particular use-case - AlertDialog's button(s).
Starting off:
You already have this figured out: we start with the widget's source code. We are specifically trying to find - where AlertDialog buttons get their text-color. So, we start with looking at where these buttons come from. Are they being explicitly created at runtime? Or are they defined in an xml layout, which is being inflated?
In source code, we find that mAlert handles the button options among other things:
public void setButton(int whichButton, CharSequence text, Message msg) {
mAlert.setButton(whichButton, text, null, msg);
}
mAlert is an instance of AlertController. In its constructor, we find that the attribute alertDialogStyle defines the xml layout:
TypedArray a = context.obtainStyledAttributes(null,
com.android.internal.R.styleable.AlertDialog,
com.android.internal.R.attr.alertDialogStyle, 0);
mAlertDialogLayout =
a.getResourceId(
com.android.internal.R.styleable.AlertDialog_layout,
com.android.internal.R.layout.alert_dialog);
So, the layout we should look at is alert_dialog.xml - [sdk_folder]/platforms/android-21/data/res/layout/alert_dialog.xml:
The layout xml is quite long. This is the relevant part:
<LinearLayout>
....
....
<LinearLayout android:id="@+id/buttonPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="54dip"
android:orientation="vertical" >
<LinearLayout
style="?android:attr/buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="4dip"
android:paddingStart="2dip"
android:paddingEnd="2dip"
android:measureWithLargestChild="true">
<LinearLayout android:id="@+id/leftSpacer"
android:layout_weight="0.25"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="gone" />
<Button android:id="@+id/button1"
android:layout_width="0dip"
android:layout_gravity="start"
android:layout_weight="1"
style="?android:attr/buttonBarButtonStyle"
android:maxLines="2"
android:layout_height="wrap_content" />
<Button android:id="@+id/button3"
android:layout_width="0dip"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
style="?android:attr/buttonBarButtonStyle"
android:maxLines="2"
android:layout_height="wrap_content" />
<Button android:id="@+id/button2"
android:layout_width="0dip"
android:layout_gravity="end"
android:layout_weight="1"
style="?android:attr/buttonBarButtonStyle"
android:maxLines="2"
android:layout_height="wrap_content" />
<LinearLayout android:id="@+id/rightSpacer"
android:layout_width="0dip"
android:layout_weight="0.25"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="gone" />
</LinearLayout>
We now know that the buttons get the style held by attribute buttonBarButtonStyle.
Head over to [sdk_folder]/platforms/android-21/data/res/values/themes.material.xml and search for buttonBarButtonStyle:
<!-- Defined under `<style name="Theme.Material">` -->
<item name="buttonBarButtonStyle">@style/Widget.Material.Button.ButtonBar.AlertDialog</item>
<!-- Defined under `<style name="Theme.Material.Light">` -->
<item name="buttonBarButtonStyle">@style/Widget.Material.Light.Button.ButtonBar.AlertDialog</item>
Depending on what your activity's parent theme is, buttonBarButtonStyle will refer to one of these two styles. For now, let's assume your activity's theme extends Theme.Material. We'll look at @style/Widget.Material.Button.ButtonBar.AlertDialog:
Open [sdk_folder]/platforms/android-21/data/res/values/styles_material.xml and search for Widget.Material.Button.ButtonBar.AlertDialog:
<!-- Alert dialog button bar button -->
<style name="Widget.Material.Button.ButtonBar.AlertDialog" parent="Widget.Material.Button.Borderless.Colored">
<item name="minWidth">64dp</item>
<item name="maxLines">2</item>
<item name="minHeight">@dimen/alert_dialog_button_bar_height</item>
</style>
Okay. But these values don't help us in determining the button's text color. We should look at the parent style next - Widget.Material.Button.Borderless.Colored:
<!-- Colored borderless ink button -->
<style name="Widget.Material.Button.Borderless.Colored">
<item name="textColor">?attr/colorAccent</item>
<item name="stateListAnimator">@anim/disabled_anim_material</item>
</style>
At last, we find the textColor - and its supplied by attr/colorAccent initialized in Theme.Material:
<item name="colorAccent">@color/accent_material_dark</item>
For Theme.Material.Light, colorAccent is defined as:
<item name="colorAccent">@color/accent_material_light</item>
Browse to [sdk_folder]/platforms/android-21/data/res/values/colors_material.xml and locate these colors:
<color name="accent_material_dark">@color/material_deep_teal_200</color>
<color name="accent_material_light">@color/material_deep_teal_500</color>
<color name="material_deep_teal_200">#ff80cbc4</color>
<color name="material_deep_teal_500">#ff009688</color>
Screenshot of an AlertDialog and the corresponding text-color:
Shortcut:
Sometimes, its easier to read the color value (as in the picture above) and search for it using AndroidXRef. This approach would not have been useful in your case since #80cbc4 would have only pointed out that its the accent color. You would still have to locate Widget.Material.Button.Borderless.Colored and tie it with attribute buttonBarButtonStyle.
Changing button's text-color:
Ideally, we should create a style that extends Widget.Material.Button.ButtonBar.AlertDialog, override android:textColor inside it, and assign it to attribute buttonBarButtonStyle. But, this won't work - your project won't compile. This is because Widget.Material.Button.ButtonBar.AlertDialog is a non-public style and hence cannot be extended. You can confirm this by checking Link.
We'll do the next best thing - extend the parent style of Widget.Material.Button.ButtonBar.AlertDialog - Widget.Material.Button.Borderless.Colored which is public.
<style name="CusButtonBarButtonStyle"
parent="@android:style/Widget.Material.Button.Borderless.Colored">
<!-- Yellow -->
<item name="android:textColor">#ffffff00</item>
<!-- From Widget.Material.Button.ButtonBar.AlertDialog -->
<item name="android:minWidth">64dp</item>
<item name="android:maxLines">2</item>
<item name="android:minHeight">@dimen/alert_dialog_button_bar_height</item>
</style>
Note that we add 3 more items after overriding android:textColor. These are from non-public style Widget.Material.Button.ButtonBar.AlertDialog. Since we cannot extend it directly, we must include the items it defines. Note: the dimen value(s) will have to be looked up and transferred to appropriate res/values(-xxxxx)/dimens.xml files(s) in your project.
The style CusButtonBarButtonStyle will be assigned to attribute buttonBarButtonStyle. But the question is, how will an AlertDialog know of this? From the source code:
protected AlertDialog(Context context) {
this(context, resolveDialogTheme(context, 0), true);
}
Passing 0 as the second argument for resolveDialogTheme(Context, int) will end up in the else clause:
static int resolveDialogTheme(Context context, int resid) {
if (resid == THEME_TRADITIONAL) {
....
} else {
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(
com.android.internal.R.attr.alertDialogTheme,
outValue, true);
return outValue.resourceId;
}
}
We now know that the theme is held by alertDialogTheme attribute. Next, we look at what alertDialogTheme points to. The value of this attribute will depend on your activity's parent theme. Browse to your sdk folder and find the values/themes_material.xml inside android-21. Search for alertDialogTheme. Results:
<!-- Defined under `<style name="Theme.Material">` -->
<item name="alertDialogTheme">@style/Theme.Material.Dialog.Alert</item>
<!-- Defined under `<style name="Theme.Material.Light">` -->
<item name="alertDialogTheme">@style/Theme.Material.Light.Dialog.Alert</item>
<!-- Defined under `<style name="Theme.Material.Settings">` -->
<item name="alertDialogTheme">@style/Theme.Material.Settings.Dialog.Alert</item>
So, based on what your activity's base theme is, alertDialogTheme will hold one of these 3 values. To let AlertDialog know of CusButtonBarButtonStyle, we need to override attribute alertDialogTheme in our app's theme. Say, we're using Theme.Material as the base theme.
<style name="AppTheme" parent="android:Theme.Material">
<item name="android:alertDialogTheme">@style/CusAlertDialogTheme</item>
</style>
From above, we know that alertDialogTheme points to Theme.Material.Dialog.Alert when your app's base theme is Theme.Material. So, CusAlertDialogTheme should have Theme.Material.Dialog.Alert as its parent:
<style name="CusAlertDialogTheme"
parent="android:Theme.Material.Dialog.Alert">
<item name="android:buttonBarButtonStyle">@style/CusButtonBarButtonStyle</item>
</style>
Result:
So, instead of accepting fish to eat, can you teach me to fish
instead?
In the very least, I hope to have explained where the fish are.
P.S. I realize I have posted a mammoth.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the advantages of having component logic in a "system" versus the component itself?
For the past few days I've been trying to make my first game. I did some research on usual development practices and patterns and I settled on a composition system where the different components communicate using messages that the container-GameObject distributes.
For instance say that I press the attack key. The playerInput component sends an AttackMessage to all the other components using the notify function of the GameObject. The Weapon component picks the message, sets some local variables and sends a RigidBodyStateMessage to the RigidBody component which in turn sends another message containing the rotation and position of the GameObject. The Weapon component catches the message and instantiates a bullet using the information passed in the message.
Communication between different objects is achieved using messages sent in message buses on which the GameObjects have registered. For example, the PhysicsComponent continuously sends messages to the collisionBus which are then delivered to the registered GameObjects.
This approach allows for complete decoupling between the components but I am not sure if it may create any long-term problems. Some people also told me that components shouldn't have any logic in them and that they should only keep data which will be processed in systems. I was wondering what advantages the latter method would bring compared to the one that I am currently using. Sorry for the wall of text, I am writing from my phone.
Any help is much appreciated!
A:
First, it is perfectly acceptable for a component-based system to support components with logic, or to support components without logic. There is no codified standard for component-based implementations used in game development.
There are advantages and disadvantages to either approach, but in the end none of the advantages really outweigh the others. The right choice for your game will be to choose the pattern that best expresses how you want to, or need to, reason about your components and their place in your larger architectural space.
Components as "pure data" allow you to make certain assumptions about them: for example, you know there is no execution state (such as "where they are in their update method") that you would need to persist if you wanted to serialize the component out to persistent storage. This can result in a simpler, cleaner system of serialization for components (both for save data and for sending across a network). If you really implement them as pure, plain-old-data objects they can be faster to copy around in bulk (depending on your language and its idioms regarding "objects" versus plain data).
However, components as "pure data" also mean you need a third-party (a "system" in your parlance) interface to drive any behavior or processing you want associated with the components. This can be disadvantageous if the overhead of creating a new "system" in your API is large. If the overhead is small, then this problem is essentially reduced to the issue of syntactic sugar for OO operations (this->Method() as a member function is not much different then Method(object); both can be used to implement OO design).
Now, there are fairly compelling advantages to processing components in external "systems" objects versus within the entity itself ("foreach entity, foreach component in entity, update the component"). Externalizing the processing provides for potentially better cache locality, makes concurrent processing easier, and other sorts of things. That is orthogonal to the concept of requiring that components only be data though; you can have components with behavior that are also bulk-processed by a "system" interface.
| {
"pile_set_name": "StackExchange"
} |
Q:
Quasicompact over affine scheme
Let $X$ be a scheme and $f : X \rightarrow \mathrm{Spec}\, A$ a quasicompact morphism. Are there any easy conditions on $A$ under which we can say that $X$ is quasicompact?
Quasicompact morphism means only that there is an affine cover $\cup_{i \in I} \mathrm{Spec}\, A_i$ where $f^{-1}(\mathrm{Spec}\, A_i)$ is quasicompact. It doesn't seem to be enough.
A:
$X$ is always quasi-compact. This is a standard result which can be found in any good and complete introduction to algebraic geometry. But you can also prove it yourself. In the end, it is just an exercise in general topology. Hint: Affines schemes are quasi-compact. So choose a finite subcover of $\{\mathrm{Spec} A_i \to \mathrm{Spec} A\}$ and observe that $X$ is a finite union of quasi-compact open subspaces.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I make web page look as pop up?
I have created webpage and I am calling it from Jquery function. Technically I used {info} as image button and I am replacing with it with .aspx so that it is redirecting to that page.
.replace("${info}","/_layouts/webpage.aspx");
The web page is opening in new browser window. Is there any way that I could make it as pop up so I can place it anywhere in the page. That is to get rid off the toolbar address bar etc. It should look like a pop up.
Can anyone help me regarding this. Thanks in advance. I guess I provided the enough info. If not, please ask me.. May be next time I make it clearer.
2#(extend)
I am already using pop up..and I want to display another pop up on that which is having some server controls. Frankly I am new to jquery. I was thinking like I can create a.aspx page and after that I can modify it to as look like as pop up. or making it as fancy box.
Please help me
A:
What you are looking for is called a modal popup. I like to use ColorBox for this type of functionality. That said there are a large variety of alternative modal jQuery plugins that will also work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to capture cURL output in a text file?
I am using this command to capture time taken by cURL command:
time curl -v -k http://10.164.128.232:8011/oam/server/HeartBeat >> abc.txt
This leaves abc.txt blank. I further tried this:
time curl -v -k http://10.164.128.232:8011/oam/server/HeartBeat 2>> bcde.txt
I was expecting this command to write complete console output on my text file, but it din't capture time in bcde.txt.
I am unable to find a way using which I can capture cURL's output alongside time taken by it.
Please assist me on this.
A:
(time curl -v -k http://10.164.128.232:8011/oam/server/HeartBeat) 2>> abc.txt
This worked for me!
| {
"pile_set_name": "StackExchange"
} |
Q:
Range-Bounded Commitment fails when implemented?
For part of my thesis I must implement (in Java) a Chan, Frankel, Tsiounis range-bounded commitment protocol as quoted in Boudot's paper Efficient Proofs that a Committed Number Lies in an Interval §1.2.3 which I've quoted below for convenience:
The main idea of this proof is roughly the same as the one of [2]. Let $t$, $l$, and $s$ be three security parameters. This protocol (due to Chan, Frankel, and Tsiounis [7], and corrected in [8], and also due to [14] in another form) proves that a committed number in $x \in I$ belongs to $J$, where the expansion rate $\#J/\#I$ is equal to $2^{t+l+1}$. Let $n$ be a large composite number whose factorization is unknown by Alice and Bob, $g$ be an element of large order in $\mathbb{Z}^{*}_{n}$ and $h$ be an element of the group generated by $g$ sucht hat both the discrete logarithm of $g$ in bade $h$ and the discrete logarithm of $h$ in base $g$ are unknown by Alice. Let $H$ be a hash-function which outputs $2t$-bit strings. We denote by $E=E(x,r)=g^{x}h^{r}\mod n$ a commitment to $x \in [0,b]$, where $r$ is randomly selected over $[-2^{s}n+1,2^{s}n-1]$. This commitment, from [13], statistically reveals no information about $x$ to Bob.
Protocol: $PK_{[CFT]}(x,r: E=E(x,r) \wedge x \in [-2^{t+l}b,2^{t+l}b])$.
Alice picks random $\omega \in _{R}[0,2^{t+l}b-1]$ and $\eta \in _{R}[-2^{t+l+s}n+1,2^{t+l+s}n-1]$, and then computes $W=g^{\omega}h^{\eta} \mod n$.
Then, she computes $C=H(W)$ and $c=C \mod 2^{t}$.
Finally, she computes $D_{1}= \omega + xc$ and $D_{2}= \eta +rc$ (in $\mathbb{Z}$). If $D_{1} \in [cb,2^{t+l}b-1]$, she sends $(C,D+{1},D_{2})$ to Bob, otherwise she starts again the protocol.
Bob checks that $D_{1} \in [cb,2^{t+l}b-1]$ and that $C=H(g^{D_{1}}h^{D_{2}}E^{-c})$. This convinces Bob that $x \in [-2^{t+l}b, 2^{t+l}b]$.
I have implemented other protocols in this paper successfully, however in this case I haven't had any success, specifically because Alice's check of $D_{1} \in [cb,2^{t+l}b-1]$ always fails no matter how many times it is retried. I am curious if the logic in the protocol as written is invalid, or if it is something in my code. I've looked over the code for days and had a couple peers review it, and neither have found anything that should be causing this to fail. I've quoted code below.
/**
* Produces a CFT proof as defined in Boudot paper.
* @param x The original message committed to in e.
* @param r The random value in the commitment e of x.
* @param e The value of the commitment.
* @param b The bounding value such that x is in [0, b]
* @param commit Object containing all the FO commitment parameters (e.g. g, h, n) and access to commit()
* @return An array {C, D1, D2} that satisfies the CFT range-bounded commitment proof.
*/
public static BigInteger[] proofCFT(BigInteger x, BigInteger r, BigInteger e, BigInteger b, FujisakiOkamotoCommitment commit)
{
SecureRandom rand = new SecureRandom();
// Security parameters
int t = 128; // Because SHA-256 is 256-bit
int l = rand.nextInt(100);
int s = rand.nextInt(100);
// 2^(t+l+s)
BigInteger tls2 = BigInteger.valueOf(2L).pow(t+l+s);
// 2^(t+l)*b-1
BigInteger b2tl_minus1 = BigInteger.valueOf(2L).pow(t+l).multiply(b).subtract(BigInteger.ONE);
while(true)
{
BigInteger omega = getRandomInRange(BigInteger.ZERO, b2tl_minus1); // omega in [0, 2^(t+l)*b-1]
BigInteger eta = getRandomInRange( // eta in [-2^(t+l+s)*n+1, 2^(t+l+s)*n-1]
commit.n().multiply(tls2).negate().add(BigInteger.ONE),
commit.n().multiply(tls2).subtract(BigInteger.ONE));
BigInteger w = commit.commit(omega, eta); // g^(omega)*h^(eta) mod n
byte[] hash = new byte[0];
try
{
hash = MessageDigest.getInstance("SHA-256").digest(w.toByteArray());
}
catch(NoSuchAlgorithmException nsae){} // Never occurs
BigInteger bigC = new BigInteger(1, hash);
BigInteger littleC = bigC.mod(BigInteger.valueOf(2L).pow(t)); // bigC mod 2^t
BigInteger d1 = x.multiply(littleC).add(omega); // d1 = omega + xc
BigInteger d2 = r.multiply(littleC).add(eta); // d2 = eta + rc
// Keep going until D1 in [c*b, b*2^(t+l)-1]
BigInteger lowerBound = b.multiply(littleC);
if(d1.compareTo(lowerBound) >= 0 && d1.compareTo(b2tl_minus1) <= 0) // Never succeeds??
return new BigInteger[]{bigC, d1, d2};
}
}
Note that getRandomInRange(BigInteger max, BigInteger min) has been thoroughly tested and always uniformly returns a value in that range (inclusive).
Also, FujisakiOkamotoCommitment always generates $n$ such that its large prime factors $p$ and $q$ are safe primes.
A:
After further testing and research into where this came from, I have determined that it was indeed the algorithm as written that was incorrect. Namely, the original protocol computes $\omega = _{R}[0,2^{b(t+l)}-1]$ and thus the check is $D_{1}\in[cb,2^{b(t+l)}-1]$, and not $2^{t+l}b-1$ as the linked paper specifies.
Also incorrect is the line in step 4: $H(g^{D_{1}}h^{D_{2}}E^{-c})$, which should be $H(g^{D_{1}}h^{D_{2}}E^{-c}\mod n)$, which the author may have intended to imply but (in my opinion) should probably have specified.
With these errors in mind, and the corresponding adjustments to the code, the protocol now consistently passes. I am confident in judging this as a misprint in the Boudot paper.
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete leading comma
I am reading info from a sqlite database to a .csv file. I am able to get the file to build, but each new line starts with a ",". I have done some android programming, but not much ios. I am thinking that the issue is componentsJoinedByString:@"," since it joins everything together, but I am not sure how to get rid of the "," at the beginning of each new line using this. Is there another way to join them to write to a csv file or a way to get rid of the first comma?
NSMutableArray *exportBike = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"MemberDB.sql"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
FMResultSet *resultsBike = [database executeQuery:@"SELECT * FROM bike"];
while([resultsBike next]) {
NSString *name = [resultsBike stringForColumn:@"name"];
NSInteger stage1HR = [resultsBike intForColumn:@"stage1HR"];
NSInteger stage1BP = [resultsBike intForColumn:@"stage1BP"];
NSInteger stage2HR = [resultsBike intForColumn:@"stage2HR"];
NSInteger stage2BP = [resultsBike intForColumn:@"stage2BP"];
NSInteger stage3HR = [resultsBike intForColumn:@"stage3HR"];
NSInteger stage3BP = [resultsBike intForColumn:@"stage3BP"];
NSInteger stage4HR = [resultsBike intForColumn:@"stage4HR"];
NSInteger stage4BP = [resultsBike intForColumn:@"stage4BP"];
NSInteger stage5HR = [resultsBike intForColumn:@"stage5HR"];
NSInteger stage5BP = [resultsBike intForColumn:@"stage5BP"];
NSInteger stage6HR = [resultsBike intForColumn:@"stage6HR"];
NSInteger stage6BP = [resultsBike intForColumn:@"stage6BP"];
NSInteger stage7HR = [resultsBike intForColumn:@"stage7HR"];
NSInteger stage7BP = [resultsBike intForColumn:@"stage7BP"];
NSInteger recoveryHR = [resultsBike intForColumn:@"recoveryHR"];
NSLog(@"%@,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",name, stage1HR, stage1BP, stage2HR, stage2BP, stage3HR, stage3BP, stage4HR, stage4BP, stage5HR, stage5BP, stage6HR, stage6BP, stage7HR, stage7BP, recoveryHR);
[exportBike addObject:[NSString stringWithFormat:@"%@,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d""\n",name, stage1HR, stage1BP, stage2HR, stage2BP, stage3HR, stage3BP, stage4HR, stage4BP, stage5HR, stage5BP, stage6HR, stage6BP, stage7HR, stage7BP, recoveryHR]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *savePath = [paths objectAtIndex:0];
savePath = [savePath stringByAppendingPathComponent:@"bike.csv"];
[[exportBike componentsJoinedByString:@","] writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
A:
Change
[exportBike addObject:[NSString stringWithFormat:@"%@,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d""\n",name, stage1HR, stage1BP, stage2HR, stage2BP, stage3HR, stage3BP, stage4HR, stage4BP, stage5HR, stage5BP, stage6HR, stage6BP, stage7HR, stage7BP, recoveryHR]];
[[exportBike componentsJoinedByString:@","] writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
to
[exportBike addObject:[NSString stringWithFormat:@"%@,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",name, stage1HR, stage1BP, stage2HR, stage2BP, stage3HR, stage3BP, stage4HR, stage4BP, stage5HR, stage5BP, stage6HR, stage6BP, stage7HR, stage7BP, recoveryHR]];
[[exportBike componentsJoinedByString:@"\n"] writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
Instead of "," use "\n" in componentsJoinedByString method and in addObject line remove the "\n" at the end.
As Martin mentioned below, another option is to keep the new line character in addObject line and use [exportBike componentsJoinedByString:@""]. This will add a new line character at the end of the file.
| {
"pile_set_name": "StackExchange"
} |
Q:
No Business Data Connectivity Service associated with current web context error
I am running on a new dev setup for SharePoint 2010 and trying to setup some External Content types. I think that I have setup BCS correctly (since I see it running in the central administration). When I go into SharePoint designer 2010 and try to setup a new External Content Type, I get the following error:
There is no Business Connectivity Service associated with the current web context.
Am I missing something with the configuration? Why am I not able to setup a new External Content Type to point to my existing SQL database?
A:
The service might be running but make sure that you have associated the service with your Web Application. Go to Central Admin > Manage Web Applications > Select the Web Application > Click Service Connections in the Ribbon. In the dialog make sure that the BDC Service is checked.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access azure service bus message properties in Azure function 2
Using azure functions version 1 it was possible to accept a message as BrokeredMessage.
public static void Run([ServiceBusTrigger("MySServiceBus", "MySubscriptionName", AccessRights.Listen, Connection = "MyConnectionString")]BrokeredMessage message, TraceWriter log)
And then retrieve the properties using code similar to this:
var MyProperty = message.Properties["MyMessageProperty"] as string
Using version 2.0 of the function SDK I can't cast the incoming object to a BrokeredMessage without getting a deserialization error message
There was an error deserializing the object of type
Microsoft.ServiceBus.Messaging.BrokeredMessage. The input source is
not correctly formatted. System.Private.DataContractSerialization: The
input source is not correctly formatted.
Is it possible to get the message properties using functions 2.0
A:
Version 2.0 of runtime switched to the new Service Bus client library based on .NET Standard.
BrokeredMessage class is not part of that library, instead it has Message class with comparable functionality but different API.
You should be able to bind your input parameter to this class and then access custom properties via Message.UserProperties dictionary.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I make a query which selects as nested?
I have two tables:
// users
+----+--------+
| id | name |
+----+--------+
| 1 | Jack |
| 2 | Peter |
| 3 | John |
| 4 | Barman |
| 5 | Ali |
+----+--------+
// friends
+---------+-----------+
| user_id | friend_id |
+---------+-----------+
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 3 | 1 |
| 3 | 2 |
| 3 | 4 |
| 5 | 2 |
+---------+-----------+
-- both user_id and friend_id columns refer to the id column of users table
I want to select all friends of Jack (id = 1). So here is the query:
select * from friend where user_id = 1
/* output
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
*/
Now I also want to select friends of Jack's friends. How can I do that?
Note, I don't want to select duplicate rows. So I want this output:
/* expected output:
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 3 | 2 |
| 3 | 4 |
| 5 | 2 |
*/
A:
Add a IN clause with all friends of Jack use distinct user_id, friend_id
select distinct f1.user_id, f1.friend_id
from friend f1
where user_id = 1
or
user_id in (select f2.friend_id
from friend f2
where user_id = 1);
| {
"pile_set_name": "StackExchange"
} |
Q:
Can had inversion occur in past tense, not past perfect?
If the man had his life partner, he would be very happy.
Had the man his life partner, he would be very happy.
Is this inversion valid? I have learned that Had inversion only occurs in past perfect tense and also I can't find any example that represents Had inversion occuring in past tense.
A:
In short, yes, but such a usage will be considered stuffy.
In the prologue of Canterbury Tales, in the introduction of the Dr. of Phisick, we see
Full ready had he his 'Pothecaries, To send him druggis and 'lectuaries,...
Samuel Richardson's 1748 epistolary novel Clarissa, Or: the History of a young Lady, has this:
And thus, as Mr. Lovelace thought fit to take it, had he his answer from my sister.
Modern inversions of this sort are typically a way of expressing conditional mood.
We have this in a 1965 Harlan Ellison review of the movie The Train in Cinema magazine:
Unlike most of the flea-marketeers of Hollywood, director John Frankenheimer is a man who would deal with whales, had he his choice.
Piers Anthony's book Aliena Too has
Had he his choice of a perfect world, he would never have left her. But that kind of choice he never had.
You're unlikely to see this outside of poetry and literature, however. It's a little stuffy, verging on idiomatic, because in ordinary conversational English one would typically say "If I had my choice" rather than "Had I my choice".
Also see this old EL&U question.
| {
"pile_set_name": "StackExchange"
} |
Q:
R function returns nothing instead of data.table object when data.table := is last operation
A function taking a data.table df as input uses the data.table := operation should return the modified data.table but returns nothing even with explicit return(df) statement.
The function returns the data.table if we force a transformation to data.table with data.table(df).
What is the reason behind this behavior? And what are the good practices in coding functions with the data.table := operator?
Here is a minimal example:
library(data.table)
data <- data.table(x = 1:3)
test_function_1 <- function(df){
df[, new_column := 1]
}
test_function_2 <- function(df){
df[, new_column := 1]
return(df)
}
test_function_3 <- function(df){
df[, new_column := 1]
data.table(df)
}
test_function_1(data) # returns nothing
test_function_2(data) # returns nothing
test_function_3(data) # returns the modified data.table
Here is my sessionInfo() if needed:
> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
Matrix products: default
[...]
attached base packages:
[1] stats graphics grDevices utils datasets
[6] methods base
other attached packages:
[1] data.table_1.11.4
A:
library(data.table)
data <- data.table(x = 1:3)
test_function_1 <- function(df){
df[, new_column := 1][]
}
test_function_2 <- function(df){
df[, new_column := 1][]
return(df)
}
test_function_3 <- function(df){
df[, new_column := 1]
data.table(df)
}
test_function_1(data) # returns the modified data.table
test_function_2(data) # returns the modified data.table
test_function_3(data) # returns the modified data.table
more info: H E R E
| {
"pile_set_name": "StackExchange"
} |
Q:
Get android context inside Acra reportSender implementation
Is there a way to get android context inside custom ACRA ReportSender implementation class?
public class MyReportSender implements ReportSender {
public ErrorReportSender(){}
}
A:
You can save reference to object of your Application implementation into the static variable and get it using static method:
private static Application sInstance;
@Override
public void onCreate ()
{
sInstance = this;
ACRA.init( this );
super.onCreate();
}
public static Application getInstance()
{
return sInstance;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento - Move a category programmatically
How do I move a category to another category with all child categories?
I have tried the following solution:
$nodeId = 2269;
$parentId = 2268;
$tree = Mage::getResourceModel('catalog/category_tree')->load();
$node = $tree->getNodeById($nodeId);
$parentNode = $tree->getNodeById($parentId);
$parentChildren = explode(',', $parentNode->getChildren());
$afterId = array_pop($parentChildren);
$prevNode = $tree->getNodeById($afterId);
if (!$prevNode || !$prevNode->getId()) {
$prevNode = null;
}
$tree->move($node, $parentNode, $prevNode);
However my result is somewhat twisted. If I move to the root-category the move works, but if I move to a child-category I get faulty results and disappearing categories.
These are the values of the field path in the database:
Old: 1/2/3/2175/2269
New: 1/2/3/2175/2226/2268/2269
Correct: 1/2/3/2226/2268/2269
A:
The solution was quite simple, this one doesn't mess up the paths. However it feels like this method is slower.
$categoryId = 2269;
$parentId = 2268;
$category = Mage::getModel('catalog/category')->load($categoryId);
$category->move($parentId, null);
| {
"pile_set_name": "StackExchange"
} |
Q:
UICollectionView vertical scroll last item
Hi I have a vertical UICollectionView that works just fine, but the las item is barely visible and you have to pan up the scrollview to fully be able to see it, when you stop panning the item bounces back and you can almost interact with it.
I've tried with the bounces properties in the collection view's properties for scrollview in interface builder, but it's still the same.
Should I have to increase "manually" the scrollview's contentsize in order to let me interact with this item?.
You can barely see in the following screenshot, at the bottom just below 25th July
A:
Just a guess here, but maybe your navigation bar is "pushing" your UICollectionView down.
Are you sure the frame of the UICollectionView is right? Maybe it is extended off screen.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this request encrypted with SSL?
I am viewing a page secured by SSL on my server, (the padlock is showing in firefox) using jQuery I execute the following:
$.post("/cgi-bin/foobar.pl", {
foo: "bar"
}, function(data) {
alert(data);
});
I would just like to double check that this request is encrypted via. SSL?
A:
if ('https:' == document.location.protocol) {
$.post("/cgi-bin/foobar.pl", {
foo: "bar"
}, function(data) {
alert(data);
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find out the TabSelection
I have using the following code for developing tabs.
$(document).ready(function() {
$('#container-1').tabs();
}
....
<div id="container-1">
<ul>
<li><a href="#fragment-1"><span>Home</span></a></li>
<li><a href="#fragment-2"><span>Contact</span></a></li>
</ul>
</div>
...
It works fine! I need the tab click event. If it is the Home tab click, I have to do alert();. How do I achieve this?
A:
Personally, I'd handle it all in the tab configuration itself rather than adding click events to the elements which ultimately will be the clickable part of the tab. If you do it via the tab config, then all of your tab logic is centralized thus making things cleaner and you don't need to be familiar with the implementation details of the tabs:
$(document).ready(function() {
$('#container-1').tabs({
selected : function(e, ui) {
if (ui.index == 0) {
alert('Home clicked!');
}
}
});
});
....
<div id="container-1">
<ul>
<li><a href="#fragment-1"><span>Home</span></a></li>
<li><a href="#fragment-2"><span>Contact</span></a></li>
</ul>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
ReWrite rule to add .html extension
I need a rule that will add an .html extension whenever there is 'not' a trailing slash.
A new client recently changed ecommerce scripts and the new version handles SEO differently and changed all of their 16,000+ product links. This was not caught prior to the site being re-indexed so we need to redirect the old to the new..
All products used to have links like this
domain.com/category/productname
but are now
domain.com/category/productname.html
Category links did not change and all are like this
domain.com/category/ (with trailing slash)
A:
The answer from @david-wolever redirects everything that does not end in .html (or the root) to the same URL with an added .html extension, meaning it appends a .html extension to things like CSS and JavaScripts files, e.g. it will redirect /style.css to /style.css.html which is not likely what you want. It also has the spaces after ! character which will likely caused @greggles 500s
This redirects URLs which do not end in a dot followed by 3 or 4 alphanumeric characters:
RewriteEngine On
RewriteCond %{REQUEST_URI} !\.[a-zA-Z0-9]{3,4}
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.*)$ $1.html
Or for finer grain control, whitelist the extensions you do not want .html appended to e.g.
RewriteCond %{REQUEST_URI} !\.(html|css|js|less|jpg|png|gif)$
A:
This option is similar to @remco's, but doesn't require the use of [R] (an "external" redirect sent back to the brower). I also added a missing \ in the first condition:
Options FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^.*\.html$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ %{REQUEST_FILENAME}.html
A:
RewriteEngine On
RewriteCond %{REQUEST_URI} ! \.html$
RewriteCond %{REQUEST_URI} ! /$
RewriteRule ^(.*)$ $1.html
You might want to throw an [R] in there, or something too. See docs: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule (search for "redirect|R").
| {
"pile_set_name": "StackExchange"
} |
Q:
Which style of Django Rest Framework should I be using
(I'm using the latest django/python/DRF)
My API endpoints are application internal. They do not match 1-to-1 to models I have in the system. I've seen two techniques of using views for APIs.
The first uses methods, like I'm using:
@api_view(['GET', 'POST'])
@authentication_classes([JSONWebTokenAuthentication])
def myApiEndPoint(request):
"""
This text is the description for this API.
"""
if request.method == 'GET':
return Response("ok get", status=status.HTTP_200_OK)
elif request.method == 'POST':
return Response("ok post", status=status.HTTP_200_OK)
The second uses class definitions, like the DRF documentation
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
The second way seems more neat and orderly. But:
Can I use it for validations that aren't model specific?
How do I define the per-class permission and authentication classes in this instance?
Thanks
A:
yes
create serializers based on Serializer (not ModelSerializer) and the put your custom validations for fields there
instead of using ModelViewSet as your base class use viewsets.GenericViewSet for GET create a method named list and for POST create a method named create for more info check viewset docs
it's very simple:
simply define these vars in your viewset: (also check docs for authentication and permissions
class UserViewSet(GenericViewSet):
permission_classes = [AllowAny, ] # or any other permission class
authentication_classes = [JSONWebTokenAuthentication, ] # or any other authentication class
| {
"pile_set_name": "StackExchange"
} |
Q:
Undefined PHP Constant in require_once() in IntelliJ IDEA 11
I'm new to IntelliJ IDEA 11. Most of the PHP-Files of my Zend-Project start with something like:
require_once(APPLICATION_PATH . '/businessobjects/Car.php');
The IDE mentions two Warnings on this line:
Undefined Constant APPLICATION_PATH
Path "businessobjects" not found
As a Consequence, when I hover "new Car()" the IDE tells me "Undefined class Car".
How can I solve this Issue?
A:
Solution
I had another Issue with IntelliJ IDEA which has been discussed here on StackOverflow (IntelliJ did not display any Folders in the Project Tree). After I added all of my Files as one single "WebModule" and IntelliJ finished Indexing all these Folders and Files, it perfectly found the Path to my businessobjects and the Class "Car".
| {
"pile_set_name": "StackExchange"
} |
Q:
GitLab: admin but can't update my role in a project
I'm an admin of a private GitLab project, we have several projects, I can update anyone role inside these projects except me, I only can "Leave"! can you provide any tips in this,
A:
That is a bit tricky in Gitlab. You can't change the own group. So you could try to login with another user and change it with that user. I haven't tested this yet. Here you can find some good ways to change it.
How to change the project owner in gitlab
You can basically create a group then add the project to a group, then from the group member setting add a new owner and you can leave the group yourself.
Some things in Gitlab are a bit strange but perhaps you can solve the problem with one of that solutions.
| {
"pile_set_name": "StackExchange"
} |
Q:
2 sets of Custom Membership in ASP .Net MVC
I can setup custom membership easily enough, but what if I need two sets i.e. admin for control panel and registered for logged on customers. This would mean two seperate tables to get users from. My question is how can I integrate the two to control through 1 custom membership and how can I authenticate on the controller for the 2?
A:
You wouldn't separate users this way, you'd implement a custom role provider and allocate these roles to the user. So say you have created two roles admin and user you'd set an attribute to your controller like so:
Admin page controller
[Authorize(Roles = "Admin")]
public ActionResult AdminAction() { }
User page controller
[Authorize(Roles = "User")]
public ActionResult UserAction() { }
If you wanted your administrators to view all logged in user pages, you'd simply just assign the user role to your administrators.
| {
"pile_set_name": "StackExchange"
} |
Q:
(Homework) Dice Program, cannot find symbol
I'm new to java and I've encountered yet another error with my dice program.
In this program I have three methods, roll() to roll the die and return a value between 1 and a number specified by the user, getFaceValue(), to return the value of the die roll as an int, and toString(), to return the die roll as a string.
The answer to my previous question about my program enabled me to get the program working, but it was not structured as the professor wanted, so I've had to rework it. I now know that none of my methods/variables can be static, and I can only take user input in the main part of the program.
When I try to compile, I get the following error:
Die.java:12: error: cannot find symbol
double y = (x * sides) + 1;
symbol: variable sides
location: class Die
My code is as follows:
import java.io.*;
import java.util.*;
public class Die {
//private int sides;
private int z;
private String faceName;
//sets (and returns) the face value to a uniform random number between 1 and the number of faces.
public int roll() {
double x = Math.random();
double y = (x * sides) + 1;
z = (int)y;
return z;
}
//returns the current face value of the die.
public int getFaceValue() {
int face = z;
return face;
}
//returns the string representation of the face value.
public String toString() {
faceName = Integer.toString(z);
return faceName;
}
public static void main(String [] args) {
int sides;
System.out.println("How many sides will the die have?");
Scanner keyboard = new Scanner(System.in);
sides = keyboard.nextInt();
System.out.println(" ");
Die die = new Die();
System.out.println("Roll: " + die.roll());
System.out.println("Face: " + die.getFaceValue());
System.out.println("String: " + die.toString());
}
}
Originally, I had the variable sides as a private int (you can see it commented out in my program), but this produced a static reference error.
I appreciate any help you can offer.
The previous question was: Methods in Dice Program return 0
A:
You can create an instance variable for sides and pass it to the die via a constructor. This would require you to uncomment your private int sides variable.
Example Die constructor:
public Die(int sides) {
this.sides = sides;
}
With a constructor like this, you can instantiate your Die with the number of sides you read as input.
sides = keyboard.nextInt();
Die die = new Die(sides);
Now, your die's sides field is set to whatever the user entered, and the die's methods use that value accordingly.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way to level transmutation in Everquest 2 if you got a late start
I've been playing EverQuest 2 Extended with my after quitting WoW several months ago. Not used to the tradeskill system in EQ we didn't realize you started with the transmutation skill instead of having to learn it, so I didn't start transmuting anything until I hit level 15. Unfortunately, by then I'd gotten rid of most of my low level gear. Low level mobs won't drop me items since they're grey, and finding rare mats to craft Mastercrafted quality items takes forever and since the highest level item I can make of the first tier is level 2, they rarely give skillups. Is there a better way to do this? We're on bronze accounts so we can't use the broker or anything, and my limited bank slots are filling up with gear that I could disenchant if I could just get to X or Y or Z level transmutation.
A:
Ok, I found a way that is at least, not as painful, though it's still not super fast. The scholar type crafting professions (sage, artificing, and alchemy) can create skill learning items for various classes. Skill items of at least expert level can be transmuted like Treasured or Mastercrafted items. Unlike Mastercrafted items, these items can have levels other than X1 and X2. This seems to be the only way to craft transmutable items high enough level to give a decent chance at skillups.
There's also a mount you can get from a crafting quest chain in Butcherblock Mountains that increases your transmutation skill by 9.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract time features using the periodic normal distribution (von mises) in Python
I am trying to find the mean, variance and confidence interval of the periodic/wrapped normal distribution (von Mises) but within a time interval (as opposed to the traditional interval of pi). I looked at a solution on stack overflow here, its close but I am not sure its exactly what I am looking for.
I found exactly what I was looking for here, which uses R (see below an extract of the code). I'm looking to replicate this in Python.
> data(timestamps)
> head(timestamps)
[1] "20:27:28" "21:08:41" "01:30:16" "00:57:04" "23:12:14" "22:54:16"
> library(lubridate)
> ts <- as.numeric(hms(timestamps)) / 3600
> head(ts)
[1] 20.4577778 21.1447222 1.5044444 0.9511111 23.2038889 22.9044444
> library(circular)
> ts <- circular(ts, units = "hours", template = "clock24")
> head(ts)
Circular Data:
[1] 20.457889 21.144607 1.504422 0.950982 23.203917 4.904397
> estimates <- mle.vonmises(ts)
> p_mean <- estimates$mu %% 24
> concentration <- estimates$kappa
> densities <- dvonmises(ts, mu = p_mean, kappa = concentration)
> alpha <- 0.90
> quantile <- qvonmises((1 - alpha)/2, mu = p_mean, kappa = concentration) %% 24
> cutoff <- dvonmises(quantile, mu = p_mean, kappa = concentration)
> time_feature <- densities >= cutoff
Like the library circular, python has a package scipy.stats.vonmises but lies within the interval pi instead of time. Are there any alternative packages that can help?
A:
I built a python function which does what I need, taking the formulae from this pdf
Hope this helps the community. Please provide corrections if I am wrong.
Note: this works for values within the interval [0,2pi] or 360 degrees.
import pandas as pd
import numpy as np
from scipy.stats import chi2
def random_dates(start, end, n, unit='D', seed=None):
if not seed:
np.random.seed(0)
ndays = (end - start).days + 1
return pd.to_timedelta(np.random.rand(n) * ndays, unit=unit) + start
def vonmises(df, field):
N = len(df[field])
s = np.sum(np.sin(df[field]))
c = np.sum(np.cos(df[field]))
sbar = (1/N)*s
cbar = (1/N)*c
if cbar > 0:
if sbar >= 0:
df['mu_vm'] = np.arctan(sbar/cbar)
else:
df['mu_vm'] = np.arctan(sbar/cbar) + 2*np.pi
elif cbar < 0:
df['mu_vm'] = np.arctan(sbar/cbar) + np.pi
else:
df['mu_vm'] = np.nan
R = np.sqrt(c**2 + s**2)
Rbar = (1/N)*R
if Rbar < 0.53:
kstar = 2*Rbar + Rbar**3 + 5*(Rbar**5)/6
elif Rbar >= 0.85:
kstar = 1/(3*Rbar -4*(Rbar**2) + Rbar**3)
else:
kstar = -0.4 + 1.39*Rbar + 0.43/(1-Rbar)
if N<=15:
if kstar < 2:
df['kappa_vm'] = np.max([kstar - 2/(N*kstar),0])
else:
df['kappa_vm'] = ((N-1)**3)*kstar/(N*(N**2+1))
else:
df['kappa_vm'] = kstar
if Rbar <= 2/3:
df['vm_plus'] = df['mu_vm'] + np.arccos(np.sqrt(2*N*(2*(R**2) -
N*chi2.isf(0.9,1))/((R**2)*(4*N - chi2.isf(0.9,1)))))
df['vm_minus'] = df['mu_vm'] - np.arccos(np.sqrt(2*N*(2*(R**2) -
N*chi2.isf(0.9,1))/((R**2)*(4*N - chi2.isf(0.9,1)))))
else:
df['vm_plus'] = df['mu_vm'] + np.arccos(np.sqrt((N**2) -
((N**2) - (R**2))*np.exp(chi2.isf(0.9,1)/N))/R)
df['vm_minus'] = df['mu_vm'] - np.arccos(np.sqrt((N**2) -
((N**2) - (R**2))*np.exp(chi2.isf(0.9,1)/N))/R)
df['vm_conft'] = np.where((df['vm_plus'] < df[field]) |
(df['vm_minus'] > df[field]), True, False)
return df
df = pd.concat([pd.DataFrame({'A':[1,1,1,1,1,2,2,2,2,2]}), pd.DataFrame({'B':random_dates(pd.to_datetime('2015-01-01'), pd.to_datetime('2018-01-01'), 10)})],axis=1)
df['C'] = (df['B'].dt.hour*60+df['B'].dt.minute)*60 + df['B'].dt.second
df['D'] = df['C']*2*np.pi/(24*60*60)
df = df.groupby('A').apply(lambda x : vonmises(x, 'D'))
To get back to hours, for example, simply multiply by 24 and divide by 2pi
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.